Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Water Surface Rendering Fix #71

Merged
merged 4 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions MGSHDFix.vcxproj
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
</ItemGroup>
<ItemGroup>
<ClInclude Include="src\external\loguru\loguru.hpp" />
<ClInclude Include="src\external\minhook\MinHook.h" />
<ClInclude Include="src\helper.hpp" />
<ClInclude Include="src\stdafx.h" />
</ItemGroup>
Expand Down Expand Up @@ -142,6 +143,7 @@
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
<AdditionalDependencies>lib\libMinHook-x64-v141-mt.lib;$(CoreLibraryDependencies);%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
Expand All @@ -163,6 +165,9 @@
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
<AdditionalLibraryDirectories>
</AdditionalLibraryDirectories>
<AdditionalDependencies>lib\libMinHook-x64-v141-mt.lib;$(CoreLibraryDependencies);%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
Expand Down
Binary file added lib/libMinHook-x64-v141-mt.lib
Binary file not shown.
74 changes: 74 additions & 0 deletions src/dllmain.cpp
Copy link
Owner

@Lyall Lyall Nov 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me. My only suggestions would be to use less unique patterns so there's some resilience against game patches, also to add some logging upon successful hooking. Maybe something like this?

  if (eGameType == MgsGame::MGS3)
  {
      MH_STATUS status;

      uint8_t* MGS3_RenderWaterSurfaceScanResult = Memory::PatternScan(baseModule, "0F 57 ?? ?? ?? ?? ?? F3 0F ?? ?? ?? ?? ?? ?? E8 ?? ?? ?? ?? 48 8B ?? ?? ?? 48 89 ?? ?? ?? ?? ??");
      uintptr_t MGS3_RenderWaterSurfaceScanAddress = Memory::GetAbsolute((uintptr_t)MGS3_RenderWaterSurfaceScanResult + 0x10);
      if (MGS3_RenderWaterSurfaceScanResult && MGS3_RenderWaterSurfaceScanAddress)
      {
          status = Memory::HookFunction((uint8_t*)MGS3_RenderWaterSurfaceScanAddress, MGS3_RenderWaterSurface_Hook, (LPVOID*)&MGS3_RenderWaterSurface);

          if (status != MH_OK)
          {
              LOG_F(INFO, "MGS 3: Render Water Surface: Hook failed.");
          }
          else if (status == MH_OK)
          {
              LOG_F(INFO, "MGS 3: Render Water Surface: Hook successful. Hook address is 0x%" PRIxPTR, MGS3_RenderWaterSurfaceScanAddress);
          }
      }
      else
      {
          LOG_F(INFO, "MGS 3:  Render Water Surface: Pattern scan failed.");
      }

      uint8_t* MGS3_GetViewportCameraOffsetYScanResult = Memory::PatternScan(baseModule, "E8 ?? ?? ?? ?? F3 44 ?? ?? ?? E8 ?? ?? ?? ?? F3 44 ?? ?? ?? ?? ?? ?? 00 00");
      uintptr_t MGS3_GetViewportCameraOffsetYScanAddress = Memory::GetAbsolute((uintptr_t)MGS3_GetViewportCameraOffsetYScanResult + 0xB);
      if (MGS3_GetViewportCameraOffsetYScanResult && MGS3_GetViewportCameraOffsetYScanAddress)
      {
          status = Memory::HookFunction((uint8_t*)MGS3_GetViewportCameraOffsetYScanAddress, MGS3_GetViewportCameraOffsetY_Hook, (LPVOID*)&MGS3_GetViewportCameraOffsetY);

          if (status != MH_OK)
          {
              LOG_F(INFO, "MGS 3: Get Viewport Camera Offset: Hook failed.");
          }
          else if (status == MH_OK)
          {
              LOG_F(INFO, "MGS 3: Get Viewport Camera Offset: Hook successful. Hook address is 0x%" PRIxPTR, MGS3_GetViewportCameraOffsetYScanAddress);
          }
      }
      else
      {
          LOG_F(INFO, "MGS 3: Get Viewport Camera Offset: Pattern scan failed.");
      }
  }

Copy link
Contributor Author

@cipherxof cipherxof Nov 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't it be more useful to report the address relative to baseModule? At the very least the base module address should be logged, because currently logging the absolute addresses doesn't allow us to actually check what is being patched in a disassembler.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've updated with the requested changes as well as logging the module address.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't it be more useful to report the address relative to baseModule? At the very least the base module address should be logged, because currently logging the absolute addresses doesn't allow us to actually check what is being patched in a disassembler.

That's true, so should we add a log of the baseModule address during DetectGame? Then for the relative addresses on hooks have something like this?

  uintptr_t MGS3_RenderWaterSurfaceScanRelAddress = MGS3_RenderWaterSurfaceScanAddress - baseModuleAddr;
  LOG_F(INFO, "MGS 3: Render Water Surface: Address is %s+%x", sExeName.c_str(), MGS3_RenderWaterSurfaceScanRelAddress);

This would look like MGS 3: Render Water Surface: Address is METAL GEAR SOLID3.exe+5ac7c0 in the log.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that works. Although it may be worth doing a separate pass on all of the logs in another PR as to not muddy this one. For now, logging the base module address at least allows us to manually find the relative addresses.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that works. Although it may be worth doing a separate pass on all of the logs in another PR as to not muddy this one. For now, logging the base module address at least allows us to manually find the relative addresses.

Sounds good to me. I'll merge this and put up a new release.

Copy link
Contributor

@emoose emoose Dec 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI in case it helps at all, you can disable the relocating with an EXE flag, steamstub would need to be removed first though: nipkownix/re4_tweaks#201 (comment)

Of course that doesn't help with user logs though, but can make debugging stuff a bit easier.

Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,25 @@ void __declspec(naked) MGS2_MGS3_SetSamplerStateAniso_CC()
}
}

bool MGS3_UseAdjustedOffsetY = true;

typedef int64_t MGS3_RenderWaterSurface_Fn(int64_t work);
MGS3_RenderWaterSurface_Fn* MGS3_RenderWaterSurface = nullptr;
int64_t __fastcall MGS3_RenderWaterSurface_Hook(int64_t work)
{
MGS3_UseAdjustedOffsetY = false;
auto result = MGS3_RenderWaterSurface(work);
MGS3_UseAdjustedOffsetY = true;
return result;
}

typedef float MGS3_GetViewportCameraOffsetY_Fn(void);
MGS3_GetViewportCameraOffsetY_Fn* MGS3_GetViewportCameraOffsetY = nullptr;
float MGS3_GetViewportCameraOffsetY_Hook()
{
return MGS3_UseAdjustedOffsetY ? MGS3_GetViewportCameraOffsetY() : 0.00f;
}

void Logging()
{
loguru::add_file("MGSHDFix.log", loguru::Truncate, loguru::Verbosity_MAX);
Expand Down Expand Up @@ -584,6 +603,7 @@ bool DetectGame()

LOG_F(INFO, "Module Name: %s", sExeName.c_str());
LOG_F(INFO, "Module Path: %s", sExePath.string().c_str());
LOG_F(INFO, "Module Address: %p", baseModule);
LOG_F(INFO, "Module Timestamp: %u", Memory::ModuleTimestamp(baseModule)); // TODO: convert from unix timestamp to string, store in sGameVersion?

eGameType = MgsGame::Unknown;
Expand Down Expand Up @@ -1214,6 +1234,54 @@ void Miscellaneous()
}
}

void ViewportFix()
{
if (eGameType == MgsGame::MGS3)
{
MH_STATUS status;

uint8_t* MGS3_RenderWaterSurfaceScanResult = Memory::PatternScan(baseModule, "0F 57 ?? ?? ?? ?? ?? F3 0F ?? ?? ?? ?? ?? ?? E8 ?? ?? ?? ?? 48 8B ?? ?? ?? 48 89 ?? ?? ?? ?? ??");
uintptr_t MGS3_RenderWaterSurfaceScanAddress = Memory::GetAbsolute((uintptr_t)MGS3_RenderWaterSurfaceScanResult + 0x10);
if (MGS3_RenderWaterSurfaceScanResult && MGS3_RenderWaterSurfaceScanAddress)
{
status = Memory::HookFunction((uint8_t*)MGS3_RenderWaterSurfaceScanAddress, MGS3_RenderWaterSurface_Hook, (LPVOID*)&MGS3_RenderWaterSurface);

if (status != MH_OK)
{
LOG_F(INFO, "MGS 3: Render Water Surface: Hook failed.");
}
else if (status == MH_OK)
{
LOG_F(INFO, "MGS 3: Render Water Surface: Hook successful. Hook address is 0x%" PRIxPTR, MGS3_RenderWaterSurfaceScanAddress);
}
}
else
{
LOG_F(INFO, "MGS 3: Render Water Surface: Pattern scan failed.");
}

uint8_t* MGS3_GetViewportCameraOffsetYScanResult = Memory::PatternScan(baseModule, "E8 ?? ?? ?? ?? F3 44 ?? ?? ?? E8 ?? ?? ?? ?? F3 44 ?? ?? ?? ?? ?? ?? 00 00");
uintptr_t MGS3_GetViewportCameraOffsetYScanAddress = Memory::GetAbsolute((uintptr_t)MGS3_GetViewportCameraOffsetYScanResult + 0xB);
if (MGS3_GetViewportCameraOffsetYScanResult && MGS3_GetViewportCameraOffsetYScanAddress)
{
status = Memory::HookFunction((uint8_t*)MGS3_GetViewportCameraOffsetYScanAddress, MGS3_GetViewportCameraOffsetY_Hook, (LPVOID*)&MGS3_GetViewportCameraOffsetY);

if (status != MH_OK)
{
LOG_F(INFO, "MGS 3: Get Viewport Camera Offset: Hook failed.");
}
else if (status == MH_OK)
{
LOG_F(INFO, "MGS 3: Get Viewport Camera Offset: Hook successful. Hook address is 0x%" PRIxPTR, MGS3_GetViewportCameraOffsetYScanAddress);
}
}
else
{
LOG_F(INFO, "MGS 3: Get Viewport Camera Offset: Pattern scan failed.");
}
}
}

using NHT_COsContext_SetControllerID_Fn = void (*)(int controllerType);
NHT_COsContext_SetControllerID_Fn NHT_COsContext_SetControllerID = nullptr;
void NHT_COsContext_SetControllerID_Hook(int controllerType)
Expand Down Expand Up @@ -1418,13 +1486,19 @@ DWORD __stdcall Main(void*)
ReadConfig();
if (DetectGame())
{
auto mhStatus = MH_Initialize();

if (mhStatus != MH_OK)
LOG_F(INFO, "MG/MG2 | MGS 2 | MGS 3: MinHook: Failed to initialize with error %d", mhStatus);

LauncherConfigOverride();
CustomResolution();
IntroSkip();
ScaleEffects();
AspectFOVFix();
HUDFix();
Miscellaneous();
ViewportFix();
}

// Signal any threads which might be waiting for us before continuing
Expand Down
186 changes: 186 additions & 0 deletions src/external/minhook/MinHook.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
/*
* MinHook - The Minimalistic API Hooking Library for x64/x86
* Copyright (C) 2009-2017 Tsuda Kageyu.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#pragma once

#if !(defined _M_IX86) && !(defined _M_X64) && !(defined __i386__) && !(defined __x86_64__)
#error MinHook supports only x86 and x64 systems.
#endif

#include <windows.h>

// MinHook Error Codes.
typedef enum MH_STATUS
{
// Unknown error. Should not be returned.
MH_UNKNOWN = -1,

// Successful.
MH_OK = 0,

// MinHook is already initialized.
MH_ERROR_ALREADY_INITIALIZED,

// MinHook is not initialized yet, or already uninitialized.
MH_ERROR_NOT_INITIALIZED,

// The hook for the specified target function is already created.
MH_ERROR_ALREADY_CREATED,

// The hook for the specified target function is not created yet.
MH_ERROR_NOT_CREATED,

// The hook for the specified target function is already enabled.
MH_ERROR_ENABLED,

// The hook for the specified target function is not enabled yet, or already
// disabled.
MH_ERROR_DISABLED,

// The specified pointer is invalid. It points the address of non-allocated
// and/or non-executable region.
MH_ERROR_NOT_EXECUTABLE,

// The specified target function cannot be hooked.
MH_ERROR_UNSUPPORTED_FUNCTION,

// Failed to allocate memory.
MH_ERROR_MEMORY_ALLOC,

// Failed to change the memory protection.
MH_ERROR_MEMORY_PROTECT,

// The specified module is not loaded.
MH_ERROR_MODULE_NOT_FOUND,

// The specified function is not found.
MH_ERROR_FUNCTION_NOT_FOUND
}
MH_STATUS;

// Can be passed as a parameter to MH_EnableHook, MH_DisableHook,
// MH_QueueEnableHook or MH_QueueDisableHook.
#define MH_ALL_HOOKS NULL

#ifdef __cplusplus
extern "C" {
#endif

// Initialize the MinHook library. You must call this function EXACTLY ONCE
// at the beginning of your program.
MH_STATUS WINAPI MH_Initialize(VOID);

// Uninitialize the MinHook library. You must call this function EXACTLY
// ONCE at the end of your program.
MH_STATUS WINAPI MH_Uninitialize(VOID);

// Creates a Hook for the specified target function, in disabled state.
// Parameters:
// pTarget [in] A pointer to the target function, which will be
// overridden by the detour function.
// pDetour [in] A pointer to the detour function, which will override
// the target function.
// ppOriginal [out] A pointer to the trampoline function, which will be
// used to call the original target function.
// This parameter can be NULL.
MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal);

// Creates a Hook for the specified API function, in disabled state.
// Parameters:
// pszModule [in] A pointer to the loaded module name which contains the
// target function.
// pszTarget [in] A pointer to the target function name, which will be
// overridden by the detour function.
// pDetour [in] A pointer to the detour function, which will override
// the target function.
// ppOriginal [out] A pointer to the trampoline function, which will be
// used to call the original target function.
// This parameter can be NULL.
MH_STATUS WINAPI MH_CreateHookApi(
LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal);

// Creates a Hook for the specified API function, in disabled state.
// Parameters:
// pszModule [in] A pointer to the loaded module name which contains the
// target function.
// pszTarget [in] A pointer to the target function name, which will be
// overridden by the detour function.
// pDetour [in] A pointer to the detour function, which will override
// the target function.
// ppOriginal [out] A pointer to the trampoline function, which will be
// used to call the original target function.
// This parameter can be NULL.
// ppTarget [out] A pointer to the target function, which will be used
// with other functions.
// This parameter can be NULL.
MH_STATUS WINAPI MH_CreateHookApiEx(
LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal, LPVOID *ppTarget);

// Removes an already created hook.
// Parameters:
// pTarget [in] A pointer to the target function.
MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget);

// Enables an already created hook.
// Parameters:
// pTarget [in] A pointer to the target function.
// If this parameter is MH_ALL_HOOKS, all created hooks are
// enabled in one go.
MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget);

// Disables an already created hook.
// Parameters:
// pTarget [in] A pointer to the target function.
// If this parameter is MH_ALL_HOOKS, all created hooks are
// disabled in one go.
MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget);

// Queues to enable an already created hook.
// Parameters:
// pTarget [in] A pointer to the target function.
// If this parameter is MH_ALL_HOOKS, all created hooks are
// queued to be enabled.
MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget);

// Queues to disable an already created hook.
// Parameters:
// pTarget [in] A pointer to the target function.
// If this parameter is MH_ALL_HOOKS, all created hooks are
// queued to be disabled.
MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget);

// Applies all queued changes in one go.
MH_STATUS WINAPI MH_ApplyQueued(VOID);

// Translates the MH_STATUS to its name as a string.
const char * WINAPI MH_StatusToString(MH_STATUS status);

#ifdef __cplusplus
}
#endif

9 changes: 9 additions & 0 deletions src/helper.hpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include "stdafx.h"
#include <stdio.h>
#include "external/minhook/MinHook.h"

using namespace std;

Expand Down Expand Up @@ -216,4 +217,12 @@ namespace Memory

return FALSE;
}

MH_STATUS HookFunction(LPVOID target, LPVOID detour, LPVOID* ppOriginal)
{
MH_STATUS status = MH_CreateHook(target, detour, ppOriginal);
if (status == MH_OK)
MH_EnableHook(target);
return status;
}
}