RynthCore as of 2026-09-05 (internal f9abab9)
A snapshot of the working tree for aelrynth.com/git/: the code, build files and public docs. Internal review notes and agent instructions are left out. MIT licensed; see LICENSE. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
68c301dac8
277 changed files with 86286 additions and 0 deletions
168
src/RynthCore.Engine/D3D9/BitmapFont.cs
Normal file
168
src/RynthCore.Engine/D3D9/BitmapFont.cs
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/BitmapFont.cs
|
||||
// Dependency-free 5x7 bitmap font, ported from RynthCore2's bitmap_font.cpp.
|
||||
//
|
||||
// Standard 5x7 glyph cells. Each glyph is 7 rows; the low 5 bits of each row
|
||||
// are the columns, bit 4 = leftmost. A set bit is a lit pixel cell. Lit cells
|
||||
// are emitted as rectangles through a caller-supplied sink so the renderer
|
||||
// (VitalHud) can turn each into a colored quad. No allocation, no texture.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class BitmapFont
|
||||
{
|
||||
/// <summary>Receives one lit pixel cell as an inclusive-exclusive rect.</summary>
|
||||
internal delegate void CellSink(int x0, int y0, int x1, int y1);
|
||||
|
||||
public const int GlyphW = 5;
|
||||
public const int GlyphH = 7;
|
||||
private const int Advance = GlyphW + 1; // one-cell gap between glyphs
|
||||
|
||||
// Glyph table row, in a fixed order; IndexOf maps a character to a row.
|
||||
// 0 = space
|
||||
// 1..10 = '0'..'9'
|
||||
// 11..36 = 'A'..'Z'
|
||||
// 37..45 = '/' ':' '.' ',' '-' '+' '%' '(' ')'
|
||||
private const int GSpace = 0;
|
||||
private const int GDigit0 = 1;
|
||||
private const int GLetterA = 11;
|
||||
private const int GSlash = 37;
|
||||
private const int GColon = 38;
|
||||
private const int GDot = 39;
|
||||
private const int GComma = 40;
|
||||
private const int GDash = 41;
|
||||
private const int GPlus = 42;
|
||||
private const int GPercent = 43;
|
||||
private const int GLParen = 44;
|
||||
private const int GRParen = 45;
|
||||
|
||||
// 5x7 cells, bit 4 leftmost — transcribed verbatim from bitmap_font.cpp.
|
||||
private static readonly byte[][] Glyphs =
|
||||
[
|
||||
/* space */ [0, 0, 0, 0, 0, 0, 0],
|
||||
/* 0 */ [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110],
|
||||
/* 1 */ [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
|
||||
/* 2 */ [0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111],
|
||||
/* 3 */ [0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110],
|
||||
/* 4 */ [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010],
|
||||
/* 5 */ [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110],
|
||||
/* 6 */ [0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110],
|
||||
/* 7 */ [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000],
|
||||
/* 8 */ [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110],
|
||||
/* 9 */ [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100],
|
||||
/* A */ [0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
|
||||
/* B */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110],
|
||||
/* C */ [0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110],
|
||||
/* D */ [0b11100, 0b10010, 0b10001, 0b10001, 0b10001, 0b10010, 0b11100],
|
||||
/* E */ [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111],
|
||||
/* F */ [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000],
|
||||
/* G */ [0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01111],
|
||||
/* H */ [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
|
||||
/* I */ [0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
|
||||
/* J */ [0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100],
|
||||
/* K */ [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001],
|
||||
/* L */ [0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111],
|
||||
/* M */ [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001],
|
||||
/* N */ [0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001],
|
||||
/* O */ [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
|
||||
/* P */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000],
|
||||
/* Q */ [0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101],
|
||||
/* R */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001],
|
||||
/* S */ [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110],
|
||||
/* T */ [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100],
|
||||
/* U */ [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
|
||||
/* V */ [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100],
|
||||
/* W */ [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b10101, 0b01010],
|
||||
/* X */ [0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001],
|
||||
/* Y */ [0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100],
|
||||
/* Z */ [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111],
|
||||
/* / */ [0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000],
|
||||
/* : */ [0b00000, 0b00100, 0b00100, 0b00000, 0b00100, 0b00100, 0b00000],
|
||||
/* . */ [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b01100],
|
||||
/* , */ [0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b00100, 0b01000],
|
||||
/* - */ [0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000],
|
||||
/* + */ [0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000],
|
||||
/* % */ [0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011],
|
||||
/* ( */ [0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010],
|
||||
/* ) */ [0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000],
|
||||
];
|
||||
|
||||
// Maps an ASCII character to a glyph row, or -1 if unsupported (advance blank).
|
||||
private static int IndexOf(char c)
|
||||
{
|
||||
if (c >= '0' && c <= '9') return GDigit0 + (c - '0');
|
||||
if (c >= 'A' && c <= 'Z') return GLetterA + (c - 'A');
|
||||
if (c >= 'a' && c <= 'z') return GLetterA + (c - 'a'); // fold to uppercase
|
||||
return c switch
|
||||
{
|
||||
' ' => GSpace,
|
||||
'/' => GSlash,
|
||||
':' => GColon,
|
||||
'.' => GDot,
|
||||
',' => GComma,
|
||||
'-' => GDash,
|
||||
'+' => GPlus,
|
||||
'%' => GPercent,
|
||||
'(' => GLParen,
|
||||
')' => GRParen,
|
||||
_ => -1,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Pixel height of a glyph at the given cell size.</summary>
|
||||
public static int Height(int cellPx)
|
||||
{
|
||||
if (cellPx < 1) cellPx = 1;
|
||||
return GlyphH * cellPx;
|
||||
}
|
||||
|
||||
/// <summary>Pixel width of a rendered string at the given cell size. Takes a
|
||||
/// span so callers can measure stack-formatted text without allocating.</summary>
|
||||
public static int MeasureWidth(ReadOnlySpan<char> s, int cellPx)
|
||||
{
|
||||
if (s.IsEmpty) return 0;
|
||||
if (cellPx < 1) cellPx = 1;
|
||||
int n = s.Length;
|
||||
// n glyphs, each GlyphW wide, with (n-1) single-cell gaps between them.
|
||||
return (n * GlyphW + (n - 1)) * cellPx;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emits the lit cells of <paramref name="s"/> at (x, y) at the given cell
|
||||
/// size by invoking <paramref name="sink"/> once per lit cell. Takes a span
|
||||
/// (string literals convert implicitly) so it stays allocation-free; the sink
|
||||
/// is a cached delegate on the caller side.
|
||||
/// </summary>
|
||||
public static void Emit(ReadOnlySpan<char> s, int x, int y, int cellPx, CellSink sink)
|
||||
{
|
||||
if (s.IsEmpty || sink == null) return;
|
||||
if (cellPx < 1) cellPx = 1;
|
||||
|
||||
int penX = x;
|
||||
foreach (char ch in s)
|
||||
{
|
||||
int gi = IndexOf(ch);
|
||||
if (gi >= 0 && gi != GSpace)
|
||||
{
|
||||
byte[] rows = Glyphs[gi];
|
||||
for (int r = 0; r < GlyphH; r++)
|
||||
{
|
||||
int bits = rows[r];
|
||||
for (int c = 0; c < GlyphW; c++)
|
||||
{
|
||||
if (((bits >> (GlyphW - 1 - c)) & 1) != 0)
|
||||
{
|
||||
int x0 = penX + c * cellPx;
|
||||
int y0 = y + r * cellPx;
|
||||
sink(x0, y0, x0 + cellPx, y0 + cellPx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
penX += Advance * cellPx;
|
||||
}
|
||||
}
|
||||
}
|
||||
270
src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs
Normal file
270
src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs
Normal file
|
|
@ -0,0 +1,270 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class D3D9Bootstrapper
|
||||
{
|
||||
private const uint D3DSdkVersion = 32;
|
||||
private const int PollIntervalMs = 50;
|
||||
private const int BootstrapFallbackMs = 15000;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate IntPtr Direct3DCreate9Delegate(uint sdkVersion);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int CreateDeviceDelegate(
|
||||
IntPtr pD3D9,
|
||||
uint adapter,
|
||||
uint deviceType,
|
||||
IntPtr hFocusWindow,
|
||||
uint behaviorFlags,
|
||||
IntPtr pPresentationParameters,
|
||||
out IntPtr ppDevice);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
|
||||
private static extern IntPtr GetModuleHandleA(string? lpModuleName);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
private static int _started;
|
||||
private static bool _d3dCreateHookInstalled;
|
||||
private static bool _createDeviceHookInstalled;
|
||||
private static bool _realDeviceObserved;
|
||||
private static Direct3DCreate9Delegate? _originalDirect3DCreate9;
|
||||
private static Direct3DCreate9Delegate? _direct3DCreate9Detour;
|
||||
private static CreateDeviceDelegate? _originalCreateDevice;
|
||||
private static CreateDeviceDelegate? _createDeviceDetour;
|
||||
private static IntPtr _createDeviceTarget;
|
||||
private static IntPtr _direct3DCreate9Target;
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _started, 1, 0) != 0)
|
||||
return;
|
||||
|
||||
var thread = new Thread(BootstrapWorker)
|
||||
{
|
||||
Name = "RynthCore.D3D9Bootstrap",
|
||||
IsBackground = true
|
||||
};
|
||||
thread.Start();
|
||||
}
|
||||
|
||||
private static void BootstrapWorker()
|
||||
{
|
||||
try
|
||||
{
|
||||
// This runs after character login, so d3d9.dll and the game's
|
||||
// device are fully initialized. Use the NULLREF throwaway device
|
||||
// for vtable discovery — it's safe post-login because the
|
||||
// d3d9-on-d3d12 wrapper has finished all its one-time init work.
|
||||
IntPtr earlyModule = GetModuleHandleA("d3d9.dll");
|
||||
if (earlyModule != IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: d3d9.dll loaded — discovering EndScene via NULLREF device.");
|
||||
EndSceneHook.Install("post-login-vtable");
|
||||
return;
|
||||
}
|
||||
|
||||
RynthLog.D3D9("D3D9Bootstrapper: Waiting for d3d9.dll so RynthCore can hook the real device creation path.");
|
||||
DateTime fallbackDeadline = DateTime.UtcNow.AddMilliseconds(BootstrapFallbackMs);
|
||||
|
||||
while (!EndSceneHook.IsInstalled())
|
||||
{
|
||||
IntPtr d3d9Module = GetModuleHandleA("d3d9.dll");
|
||||
if (d3d9Module != IntPtr.Zero)
|
||||
{
|
||||
TryHookDirect3DCreate9(d3d9Module);
|
||||
if (_realDeviceObserved || EndSceneHook.IsInstalled())
|
||||
return;
|
||||
}
|
||||
|
||||
if (DateTime.UtcNow >= fallbackDeadline)
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: Real CreateDevice path was not observed in time. Falling back to shared vtable discovery.");
|
||||
RemoveBootstrapHooks();
|
||||
EndSceneHook.Install();
|
||||
return;
|
||||
}
|
||||
|
||||
Thread.Sleep(PollIntervalMs);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: FATAL bootstrap error: {ex}");
|
||||
if (!EndSceneHook.IsInstalled())
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: Attempting fallback EndScene install after bootstrap failure.");
|
||||
RemoveBootstrapHooks();
|
||||
EndSceneHook.Install();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryHookDirect3DCreate9(IntPtr d3d9Module)
|
||||
{
|
||||
if (_d3dCreateHookInstalled)
|
||||
return;
|
||||
|
||||
IntPtr direct3DCreate9Addr = GetProcAddress(d3d9Module, "Direct3DCreate9");
|
||||
if (direct3DCreate9Addr == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Direct3DCreate9 export unavailable (error {Marshal.GetLastWin32Error()}).");
|
||||
return;
|
||||
}
|
||||
|
||||
_direct3DCreate9Target = direct3DCreate9Addr;
|
||||
_direct3DCreate9Detour = Direct3DCreate9Detour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_direct3DCreate9Detour);
|
||||
|
||||
_originalDirect3DCreate9 = Marshal.GetDelegateForFunctionPointer<Direct3DCreate9Delegate>(MinHook.HookCreate(direct3DCreate9Addr, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(direct3DCreate9Addr);
|
||||
_d3dCreateHookInstalled = true;
|
||||
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Hooked Direct3DCreate9 @ 0x{direct3DCreate9Addr:X8}");
|
||||
}
|
||||
|
||||
private static IntPtr Direct3DCreate9Detour(uint sdkVersion)
|
||||
{
|
||||
// The call-through happens unconditionally, outside any try/catch —
|
||||
// it must always run so the game gets its real IDirect3D9 regardless
|
||||
// of what our own bootstrapping below does.
|
||||
IntPtr direct3D9 = _originalDirect3DCreate9!(sdkVersion);
|
||||
|
||||
// Deep-audit finding #11 (2026-06-18): everything past the
|
||||
// call-through is a delegate-marshalled reverse-P/Invoke callback
|
||||
// with no try/catch. TryHookCreateDevice can throw
|
||||
// InvalidOperationException out of MinHook.HookCreate/Enable — an
|
||||
// escaping exception here fail-fasts the whole client. Wrapped for
|
||||
// parity even though the logging above it can't realistically throw.
|
||||
try
|
||||
{
|
||||
if (sdkVersion != D3DSdkVersion)
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Direct3DCreate9 called with SDK {sdkVersion} (expected {D3DSdkVersion}).");
|
||||
|
||||
if (direct3D9 == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: Direct3DCreate9 returned null.");
|
||||
return direct3D9;
|
||||
}
|
||||
|
||||
TryHookCreateDevice(direct3D9);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.D3D9($"D3D9Bootstrapper: Direct3DCreate9Detour post-processing threw {ex.GetType().Name}: {ex.Message} — degrading to no CreateDevice hook."); }
|
||||
catch { }
|
||||
}
|
||||
return direct3D9;
|
||||
}
|
||||
|
||||
private static void TryHookCreateDevice(IntPtr direct3D9)
|
||||
{
|
||||
if (_createDeviceHookInstalled)
|
||||
return;
|
||||
|
||||
// Genuinely unguarded path per the audit: MinHook.HookCreate/Enable can
|
||||
// throw InvalidOperationException. Log and swallow — the caller already
|
||||
// has the real direct3D9 pointer from the call-through, so degrading to
|
||||
// "no CreateDevice hook installed" is a safe no-op, not a crash.
|
||||
try
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(direct3D9);
|
||||
_createDeviceTarget = Marshal.ReadIntPtr(vtable, D3D9VTableIndex.CreateDevice * IntPtr.Size);
|
||||
if (_createDeviceTarget == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: IDirect3D9::CreateDevice pointer was null.");
|
||||
return;
|
||||
}
|
||||
|
||||
_createDeviceDetour = CreateDeviceDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_createDeviceDetour);
|
||||
|
||||
_originalCreateDevice = Marshal.GetDelegateForFunctionPointer<CreateDeviceDelegate>(MinHook.HookCreate(_createDeviceTarget, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_createDeviceTarget);
|
||||
_createDeviceHookInstalled = true;
|
||||
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Hooked IDirect3D9::CreateDevice @ 0x{_createDeviceTarget:X8}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.D3D9($"D3D9Bootstrapper: TryHookCreateDevice threw {ex.GetType().Name}: {ex.Message} — CreateDevice hook not installed."); }
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private static void RemoveBootstrapHooks()
|
||||
{
|
||||
if (_d3dCreateHookInstalled && _direct3DCreate9Target != IntPtr.Zero)
|
||||
{
|
||||
int status = MinHook.MH_DisableHook(_direct3DCreate9Target);
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Disable Direct3DCreate9 hook = {MinHook.StatusString(status)}");
|
||||
status = MinHook.MH_RemoveHook(_direct3DCreate9Target);
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Remove Direct3DCreate9 hook = {MinHook.StatusString(status)}");
|
||||
_d3dCreateHookInstalled = false;
|
||||
}
|
||||
|
||||
if (_createDeviceHookInstalled && _createDeviceTarget != IntPtr.Zero)
|
||||
{
|
||||
int status = MinHook.MH_DisableHook(_createDeviceTarget);
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Disable CreateDevice hook = {MinHook.StatusString(status)}");
|
||||
status = MinHook.MH_RemoveHook(_createDeviceTarget);
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Remove CreateDevice hook = {MinHook.StatusString(status)}");
|
||||
_createDeviceHookInstalled = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static int CreateDeviceDetour(
|
||||
IntPtr pD3D9,
|
||||
uint adapter,
|
||||
uint deviceType,
|
||||
IntPtr hFocusWindow,
|
||||
uint behaviorFlags,
|
||||
IntPtr pPresentationParameters,
|
||||
out IntPtr ppDevice)
|
||||
{
|
||||
// Call-through happens unconditionally, outside any try/catch, same
|
||||
// rationale as Direct3DCreate9Detour above.
|
||||
int hr = _originalCreateDevice!(
|
||||
pD3D9,
|
||||
adapter,
|
||||
deviceType,
|
||||
hFocusWindow,
|
||||
behaviorFlags,
|
||||
pPresentationParameters,
|
||||
out ppDevice);
|
||||
|
||||
// Deep-audit finding #11: wrapped for parity with Direct3DCreate9Detour.
|
||||
// This path is already pre-contained by InstallFromDevice ->
|
||||
// InstallFromEndSceneAddress's own try/catch, but a throw from
|
||||
// RemoveBootstrapHooks (MinHook calls) before that point was not.
|
||||
try
|
||||
{
|
||||
if (hr >= 0 && ppDevice != IntPtr.Zero)
|
||||
{
|
||||
_realDeviceObserved = true;
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Observed real device creation (device=0x{ppDevice:X8}, hwnd=0x{hFocusWindow:X8}, hr=0x{hr:X8}).");
|
||||
RemoveBootstrapHooks();
|
||||
EndSceneHook.InstallFromDevice(ppDevice);
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: CreateDevice returned hr=0x{hr:X8}, device=0x{ppDevice:X8}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.D3D9($"D3D9Bootstrapper: CreateDeviceDetour post-processing threw {ex.GetType().Name}: {ex.Message}."); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
return hr;
|
||||
}
|
||||
}
|
||||
613
src/RynthCore.Engine/D3D9/D3D9VTable.cs
Normal file
613
src/RynthCore.Engine/D3D9/D3D9VTable.cs
Normal file
|
|
@ -0,0 +1,613 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/D3D9VTable.cs
|
||||
// Creates a throwaway D3D9 device to harvest vtable function pointers.
|
||||
// The vtable is shared across all IDirect3DDevice9 instances in the process,
|
||||
// so the addresses we read here apply to the game's real device.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
/// <summary>
|
||||
/// IDirect3DDevice9 vtable indices (x86, standard d3d9.h order).
|
||||
/// </summary>
|
||||
internal static class DeviceVTableIndex
|
||||
{
|
||||
public const int Release = 2;
|
||||
public const int GetCreationParameters = 9;
|
||||
public const int CreateAdditionalSwapChain = 13;
|
||||
public const int Reset = 16;
|
||||
public const int GetBackBuffer = 18;
|
||||
public const int CreateTexture = 23;
|
||||
public const int BeginScene = 41;
|
||||
public const int EndScene = 42;
|
||||
public const int Clear = 43;
|
||||
public const int SetTransform = 44;
|
||||
public const int GetTransform = 45;
|
||||
public const int GetRenderTarget = 38;
|
||||
public const int SetRenderTarget = 37;
|
||||
public const int SetViewport = 47;
|
||||
public const int GetViewport = 48;
|
||||
public const int GetTexture = 64;
|
||||
public const int SetRenderState = 57;
|
||||
public const int GetRenderState = 58;
|
||||
public const int SetTexture = 65;
|
||||
public const int GetTextureStageState = 66;
|
||||
public const int SetTextureStageState = 67;
|
||||
public const int GetSamplerState = 68;
|
||||
public const int SetSamplerState = 69;
|
||||
public const int SetScissorRect = 75;
|
||||
public const int GetScissorRect = 76;
|
||||
public const int DrawPrimitive = 81;
|
||||
public const int DrawIndexedPrimitive = 82;
|
||||
public const int DrawPrimitiveUP = 83;
|
||||
public const int DrawIndexedPrimitiveUP = 84;
|
||||
public const int SetFVF = 89;
|
||||
public const int GetFVF = 90;
|
||||
public const int SetVertexShader = 92;
|
||||
public const int GetVertexShader = 93;
|
||||
public const int SetStreamSource = 100;
|
||||
public const int GetStreamSource = 101;
|
||||
public const int SetIndices = 104;
|
||||
public const int GetIndices = 105;
|
||||
public const int SetPixelShader = 107;
|
||||
public const int GetPixelShader = 108;
|
||||
public const int CreateStateBlock = 60;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IDirect3DStateBlock9 vtable indices.
|
||||
/// </summary>
|
||||
internal static class StateBlockVTableIndex
|
||||
{
|
||||
public const int Release = 2;
|
||||
public const int Capture = 4;
|
||||
public const int Apply = 5;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IDirect3DTexture9 vtable indices.
|
||||
/// </summary>
|
||||
internal static class TextureVTableIndex
|
||||
{
|
||||
public const int Release = 2;
|
||||
public const int LockRect = 19;
|
||||
public const int UnlockRect = 20;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IDirect3DSwapChain9 vtable indices.
|
||||
/// </summary>
|
||||
internal static class SwapChain9VTableIndex
|
||||
{
|
||||
public const int Release = 2;
|
||||
public const int Present = 3;
|
||||
// IDirect3DSwapChain9 vtable: 3=Present, 4=GetFrontBufferData, 5=GetBackBuffer.
|
||||
public const int GetBackBuffer = 5;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IDirect3DSurface9 vtable indices.
|
||||
/// </summary>
|
||||
internal static class Surface9VTableIndex
|
||||
{
|
||||
public const int Release = 2;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IDirect3D9 vtable indices.
|
||||
/// </summary>
|
||||
internal static class D3D9VTableIndex
|
||||
{
|
||||
public const int Release = 2;
|
||||
public const int CreateDevice = 16;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the IDirect3DDevice9 vtable by creating (and immediately releasing)
|
||||
/// a temporary device + hidden window.
|
||||
/// Also provides <see cref="ScanModuleForDeviceVTable"/> which finds the vtable
|
||||
/// by scanning d3d9.dll's module image — no device creation required.
|
||||
/// </summary>
|
||||
internal static unsafe class D3D9VTable
|
||||
{
|
||||
// ─── D3D9 constants ───────────────────────────────────────────────
|
||||
private const uint D3D_SDK_VERSION = 32;
|
||||
private const uint D3DDEVTYPE_HAL = 1;
|
||||
private const uint D3DDEVTYPE_NULLREF = 4;
|
||||
private const uint D3DCREATE_SOFTWARE_VERTEXPROCESSING = 0x00000020;
|
||||
private const uint D3DCREATE_MULTITHREADED = 0x00000004;
|
||||
private const uint D3DFMT_UNKNOWN = 0;
|
||||
private const uint D3DSWAPEFFECT_DISCARD = 1;
|
||||
|
||||
// ─── Win32 ────────────────────────────────────────────────────────
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
private static extern IntPtr CreateWindowExA(
|
||||
uint dwExStyle, string lpClassName, string lpWindowName,
|
||||
uint dwStyle, int x, int y, int nWidth, int nHeight,
|
||||
IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool DestroyWindow(IntPtr hWnd);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern IntPtr GetModuleHandleA(string? lpModuleName);
|
||||
|
||||
// ─── D3D9 ─────────────────────────────────────────────────────────
|
||||
[DllImport("d3d9.dll")]
|
||||
private static extern IntPtr Direct3DCreate9(uint SDKVersion);
|
||||
|
||||
// ─── COM Release delegate ─────────────────────────────────────────
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate uint ReleaseDelegate(IntPtr pThis);
|
||||
|
||||
// ─── IDirect3D9::CreateDevice delegate ────────────────────────────
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int CreateDeviceDelegate(
|
||||
IntPtr pD3D9,
|
||||
uint Adapter,
|
||||
uint DeviceType,
|
||||
IntPtr hFocusWindow,
|
||||
uint BehaviorFlags,
|
||||
IntPtr pPresentationParameters,
|
||||
out IntPtr ppDevice);
|
||||
|
||||
// ─── D3DPRESENT_PARAMETERS (x86 layout) ───────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct D3DPRESENT_PARAMETERS
|
||||
{
|
||||
public uint BackBufferWidth;
|
||||
public uint BackBufferHeight;
|
||||
public uint BackBufferFormat; // D3DFORMAT
|
||||
public uint BackBufferCount;
|
||||
public uint MultiSampleType; // D3DMULTISAMPLE_TYPE
|
||||
public uint MultiSampleQuality;
|
||||
public uint SwapEffect; // D3DSWAPEFFECT
|
||||
public IntPtr hDeviceWindow;
|
||||
public int Windowed; // BOOL
|
||||
public int EnableAutoDepthStencil; // BOOL
|
||||
public uint AutoDepthStencilFormat; // D3DFORMAT
|
||||
public uint Flags;
|
||||
public uint FullScreen_RefreshRateInHz;
|
||||
public uint PresentationInterval;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a temp D3D9 device and returns a copy of the device vtable
|
||||
/// (array of function pointers). Returns null on failure.
|
||||
/// </summary>
|
||||
public static IntPtr[]? GetDeviceVTable(int numEntries = 119)
|
||||
{
|
||||
IntPtr hWnd = IntPtr.Zero;
|
||||
IntPtr pD3D9 = IntPtr.Zero;
|
||||
IntPtr pDevice = IntPtr.Zero;
|
||||
|
||||
try
|
||||
{
|
||||
// Create a hidden window
|
||||
hWnd = CreateWindowExA(
|
||||
0, "STATIC", "RynthCore_D3D9_Temp", 0,
|
||||
0, 0, 1, 1,
|
||||
IntPtr.Zero, IntPtr.Zero,
|
||||
GetModuleHandleA(null), IntPtr.Zero);
|
||||
|
||||
if (hWnd == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: Failed to create temp window.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Create IDirect3D9
|
||||
pD3D9 = Direct3DCreate9(D3D_SDK_VERSION);
|
||||
if (pD3D9 == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: Direct3DCreate9 failed.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Set up present parameters
|
||||
var pp = new D3DPRESENT_PARAMETERS
|
||||
{
|
||||
BackBufferWidth = 1,
|
||||
BackBufferHeight = 1,
|
||||
BackBufferFormat = D3DFMT_UNKNOWN,
|
||||
BackBufferCount = 1,
|
||||
SwapEffect = D3DSWAPEFFECT_DISCARD,
|
||||
hDeviceWindow = hWnd,
|
||||
Windowed = 1, // TRUE
|
||||
};
|
||||
|
||||
// Call IDirect3D9::CreateDevice via vtable
|
||||
IntPtr d3d9VTable = Marshal.ReadIntPtr(pD3D9); // pD3D9->lpVtbl
|
||||
IntPtr createDeviceAddr = Marshal.ReadIntPtr(d3d9VTable, D3D9VTableIndex.CreateDevice * IntPtr.Size);
|
||||
var createDevice = Marshal.GetDelegateForFunctionPointer<CreateDeviceDelegate>(createDeviceAddr);
|
||||
|
||||
IntPtr ppAlloc = Marshal.AllocHGlobal(Marshal.SizeOf<D3DPRESENT_PARAMETERS>());
|
||||
Marshal.StructureToPtr(pp, ppAlloc, false);
|
||||
|
||||
// Try NULLREF device first — it doesn't touch the GPU, avoiding
|
||||
// race conditions with the game's render thread on the real HAL device.
|
||||
int hr = createDevice(
|
||||
pD3D9,
|
||||
0, // D3DADAPTER_DEFAULT
|
||||
D3DDEVTYPE_NULLREF,
|
||||
hWnd,
|
||||
D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED,
|
||||
ppAlloc,
|
||||
out pDevice);
|
||||
|
||||
if (hr < 0 || pDevice == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: NULLREF device failed (hr=0x{hr:X8}), trying HAL fallback.");
|
||||
Marshal.StructureToPtr(pp, ppAlloc, false);
|
||||
hr = createDevice(
|
||||
pD3D9,
|
||||
0,
|
||||
D3DDEVTYPE_HAL,
|
||||
hWnd,
|
||||
D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED,
|
||||
ppAlloc,
|
||||
out pDevice);
|
||||
}
|
||||
|
||||
Marshal.FreeHGlobal(ppAlloc);
|
||||
|
||||
if (hr < 0 || pDevice == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: CreateDevice failed, HRESULT=0x{hr:X8}");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Read the device vtable
|
||||
IntPtr deviceVTable = Marshal.ReadIntPtr(pDevice); // pDevice->lpVtbl
|
||||
var vtable = new IntPtr[numEntries];
|
||||
for (int i = 0; i < numEntries; i++)
|
||||
vtable[i] = Marshal.ReadIntPtr(deviceVTable, i * IntPtr.Size);
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Captured {numEntries} entries. " +
|
||||
$"EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8}");
|
||||
|
||||
return vtable;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: Exception: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Release the temp device and D3D9 object
|
||||
if (pDevice != IntPtr.Zero)
|
||||
{
|
||||
IntPtr vtbl = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr releaseAddr = Marshal.ReadIntPtr(vtbl, DeviceVTableIndex.Release * IntPtr.Size);
|
||||
var release = Marshal.GetDelegateForFunctionPointer<ReleaseDelegate>(releaseAddr);
|
||||
release(pDevice);
|
||||
}
|
||||
|
||||
if (pD3D9 != IntPtr.Zero)
|
||||
{
|
||||
IntPtr vtbl = Marshal.ReadIntPtr(pD3D9);
|
||||
IntPtr releaseAddr = Marshal.ReadIntPtr(vtbl, D3D9VTableIndex.Release * IntPtr.Size);
|
||||
var release = Marshal.GetDelegateForFunctionPointer<ReleaseDelegate>(releaseAddr);
|
||||
release(pD3D9);
|
||||
}
|
||||
|
||||
if (hWnd != IntPtr.Zero)
|
||||
DestroyWindow(hWnd);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scans the loaded d3d9.dll module image for the IDirect3DDevice9 vtable
|
||||
/// without creating any D3D9 objects. This avoids the thread-safety hazard
|
||||
/// of creating a throwaway device while the game's real device is rendering.
|
||||
/// Returns null if the scan cannot find a valid candidate.
|
||||
/// </summary>
|
||||
public static IntPtr[]? ScanModuleForDeviceVTable(int numEntries = 119)
|
||||
{
|
||||
IntPtr hModule = GetModuleHandleA("d3d9.dll");
|
||||
if (hModule == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: d3d9.dll not loaded — module scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
const int MaxReasonableModuleSize = 50 * 1024 * 1024;
|
||||
if (!TryReadModuleImageSize(hModule, out int imageSize) || imageSize < 0x2000 || imageSize > MaxReasonableModuleSize)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: d3d9.dll PE headers unusable (imageSize=0x{imageSize:X}) — module scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
int baseAddr = hModule.ToInt32();
|
||||
int vtableByteLen = numEntries * 4; // x86 pointer size
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Reading d3d9.dll (0x{baseAddr:X8}, 0x{imageSize:X} bytes)...");
|
||||
|
||||
// Copy module into managed memory page-by-page, skipping any
|
||||
// uncommitted pages. SizeOfImage can exceed committed memory
|
||||
// and NativeAOT cannot catch the resulting AccessViolationException.
|
||||
byte[] image = new byte[imageSize];
|
||||
int readableBytes = 0;
|
||||
const int PageSize = 0x1000;
|
||||
for (int off = 0; off < imageSize; off += PageSize)
|
||||
{
|
||||
int chunk = Math.Min(PageSize, imageSize - off);
|
||||
IntPtr addr = IntPtr.Add(hModule, off);
|
||||
if (SmartBoxLocator.IsMemoryReadable(addr, chunk))
|
||||
{
|
||||
Marshal.Copy(addr, image, off, chunk);
|
||||
readableBytes += chunk;
|
||||
}
|
||||
}
|
||||
|
||||
if (readableBytes < vtableByteLen + 0x1000)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: Only {readableBytes} readable bytes in d3d9.dll — too small for vtable scan.");
|
||||
return null;
|
||||
}
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Scanning d3d9.dll ({readableBytes} readable bytes) for {numEntries}-entry device vtable...");
|
||||
|
||||
// Collect ALL candidate vtables. d3d9.dll on Windows 11 can contain
|
||||
// multiple vtables (inner implementation + outer proxy). The game's
|
||||
// device typically uses the LAST one (the outer proxy layer).
|
||||
IntPtr[]? bestCandidate = null;
|
||||
int bestOffset = 0;
|
||||
int candidateCount = 0;
|
||||
|
||||
for (int off = 0x1000; off <= imageSize - vtableByteLen; off += 4)
|
||||
{
|
||||
// Fast reject: first 3 entries (QueryInterface, AddRef, Release) must be in-module
|
||||
int p0 = BitConverter.ToInt32(image, off);
|
||||
if ((uint)(p0 - baseAddr) >= (uint)imageSize) continue;
|
||||
int p1 = BitConverter.ToInt32(image, off + 4);
|
||||
if ((uint)(p1 - baseAddr) >= (uint)imageSize) continue;
|
||||
int p2 = BitConverter.ToInt32(image, off + 8);
|
||||
if ((uint)(p2 - baseAddr) >= (uint)imageSize) continue;
|
||||
|
||||
// QI, AddRef, Release must be distinct functions
|
||||
if (p0 == p1 || p1 == p2) continue;
|
||||
|
||||
// Count in-module pointers across all entries
|
||||
int inModule = 3;
|
||||
for (int i = 3; i < numEntries; i++)
|
||||
{
|
||||
int ptr = BitConverter.ToInt32(image, off + i * 4);
|
||||
if ((uint)(ptr - baseAddr) < (uint)imageSize)
|
||||
inModule++;
|
||||
}
|
||||
|
||||
// Require ≥95% in-module (113 of 119)
|
||||
if (inModule < numEntries * 95 / 100) continue;
|
||||
|
||||
// EndScene (42) and BeginScene (41) must differ
|
||||
int esPtr = BitConverter.ToInt32(image, off + DeviceVTableIndex.EndScene * 4);
|
||||
int bsPtr = BitConverter.ToInt32(image, off + DeviceVTableIndex.BeginScene * 4);
|
||||
if (esPtr == bsPtr) continue;
|
||||
|
||||
// Verify EndScene starts with a hookable function prologue
|
||||
int esOff = esPtr - baseAddr;
|
||||
if ((uint)esOff >= (uint)(imageSize - 3)) continue;
|
||||
if (!IsRecognizedPrologue(image, esOff)) continue;
|
||||
|
||||
candidateCount++;
|
||||
|
||||
// Build candidate array
|
||||
var vtable = new IntPtr[numEntries];
|
||||
for (int i = 0; i < numEntries; i++)
|
||||
vtable[i] = new IntPtr(BitConverter.ToInt32(image, off + i * 4));
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Candidate #{candidateCount} at d3d9+0x{off:X}: " +
|
||||
$"EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8} ({inModule}/{numEntries} in-module)");
|
||||
|
||||
bestCandidate = vtable;
|
||||
bestOffset = off;
|
||||
}
|
||||
|
||||
if (bestCandidate != null)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: Using candidate #{candidateCount} (last of {candidateCount}) at d3d9+0x{bestOffset:X}: " +
|
||||
$"EndScene=0x{bestCandidate[DeviceVTableIndex.EndScene]:X8}");
|
||||
return bestCandidate;
|
||||
}
|
||||
|
||||
RynthLog.D3D9("D3D9VTable: Module scan found no device vtable candidates.");
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool IsRecognizedPrologue(byte[] image, int offset)
|
||||
{
|
||||
byte b = image[offset];
|
||||
if (b == 0x55) return true; // push ebp
|
||||
if (b == 0x8B && image[offset + 1] == 0xFF) return true; // mov edi,edi (hot-patch)
|
||||
if (b == 0x83 && image[offset + 1] == 0xEC) return true; // sub esp, imm8
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the game's existing IDirect3DDevice9 by scanning process heap memory
|
||||
/// for a live COM object whose vtable is in d3d9.dll with 119 entries.
|
||||
/// Completely read-only — no D3D9 API calls, no thread-safety hazards.
|
||||
/// Returns null if no device is found.
|
||||
/// </summary>
|
||||
public static IntPtr[]? FindExistingDeviceVTable(int numEntries = 119)
|
||||
{
|
||||
IntPtr d3d9Module = GetModuleHandleA("d3d9.dll");
|
||||
if (d3d9Module == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: d3d9.dll not loaded — device scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!TryReadModuleImageSize(d3d9Module, out int d3d9Size) || d3d9Size < 0x2000)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: d3d9.dll PE headers unusable — device scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
int d3d9Base = d3d9Module.ToInt32();
|
||||
int d3d9End = d3d9Base + d3d9Size;
|
||||
int vtableByteLen = numEntries * 4;
|
||||
|
||||
// Pre-read d3d9.dll image so vtable validation reads from safe managed memory
|
||||
byte[] d3d9Image = new byte[d3d9Size];
|
||||
int d3d9Readable = 0;
|
||||
const int PageSize = 0x1000;
|
||||
for (int off = 0; off < d3d9Size; off += PageSize)
|
||||
{
|
||||
int chunk = Math.Min(PageSize, d3d9Size - off);
|
||||
IntPtr addr = IntPtr.Add(d3d9Module, off);
|
||||
if (SmartBoxLocator.IsMemoryReadable(addr, chunk))
|
||||
{
|
||||
Marshal.Copy(addr, d3d9Image, off, chunk);
|
||||
d3d9Readable += chunk;
|
||||
}
|
||||
}
|
||||
|
||||
if (d3d9Readable < vtableByteLen + PageSize)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: Only {d3d9Readable} readable bytes in d3d9.dll — device scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Scanning process heap for live D3D9 device (d3d9=0x{d3d9Base:X8}, size=0x{d3d9Size:X})...");
|
||||
|
||||
int regionsScanned = 0;
|
||||
long bytesScanned = 0;
|
||||
int d3d9Pointers = 0;
|
||||
|
||||
IntPtr scanAddr = new IntPtr(0x10000);
|
||||
|
||||
while (scanAddr.ToInt32() > 0 && scanAddr.ToInt32() < 0x7FFE0000)
|
||||
{
|
||||
if (!VirtualQueryWrapped(scanAddr, out int regionBase, out int regionSize,
|
||||
out uint state, out uint protect, out uint type))
|
||||
break;
|
||||
|
||||
if (regionSize <= 0) break;
|
||||
IntPtr nextAddr = new IntPtr(regionBase + regionSize);
|
||||
|
||||
// Only scan committed, readable, private (heap) memory
|
||||
bool committed = (state & 0x1000) != 0; // MEM_COMMIT
|
||||
bool readable = protect != 0 && (protect & 0x01) == 0 && (protect & 0x100) == 0; // !NOACCESS, !GUARD
|
||||
bool isPrivate = (type & 0x20000) != 0; // MEM_PRIVATE
|
||||
|
||||
if (!committed || !readable || !isPrivate || regionSize < 128)
|
||||
{
|
||||
scanAddr = nextAddr;
|
||||
continue;
|
||||
}
|
||||
|
||||
regionsScanned++;
|
||||
|
||||
// Safe page-by-page copy of this region
|
||||
byte[] regionData = new byte[regionSize];
|
||||
int regionReadable = 0;
|
||||
for (int off = 0; off < regionSize; off += PageSize)
|
||||
{
|
||||
int chunk = Math.Min(PageSize, regionSize - off);
|
||||
IntPtr pageAddr = new IntPtr(regionBase + off);
|
||||
if (SmartBoxLocator.IsMemoryReadable(pageAddr, chunk))
|
||||
{
|
||||
Marshal.Copy(pageAddr, regionData, off, chunk);
|
||||
regionReadable += chunk;
|
||||
}
|
||||
}
|
||||
|
||||
bytesScanned += regionReadable;
|
||||
|
||||
// Scan each dword for a vtable pointer into d3d9.dll
|
||||
for (int off = 0; off <= regionReadable - 4; off += 4)
|
||||
{
|
||||
int value = BitConverter.ToInt32(regionData, off);
|
||||
if (value < d3d9Base || value >= d3d9End) continue;
|
||||
|
||||
d3d9Pointers++;
|
||||
|
||||
// Check if this is a 119-entry device vtable
|
||||
int vtableOffset = value - d3d9Base;
|
||||
if (vtableOffset + vtableByteLen > d3d9Readable) continue;
|
||||
|
||||
int inModule = 0;
|
||||
for (int i = 0; i < numEntries; i++)
|
||||
{
|
||||
int entry = BitConverter.ToInt32(d3d9Image, vtableOffset + i * 4);
|
||||
if (entry >= d3d9Base && entry < d3d9End)
|
||||
inModule++;
|
||||
}
|
||||
|
||||
if (inModule < numEntries * 95 / 100) continue;
|
||||
|
||||
// BeginScene and EndScene must differ
|
||||
int bs = BitConverter.ToInt32(d3d9Image, vtableOffset + DeviceVTableIndex.BeginScene * 4);
|
||||
int es = BitConverter.ToInt32(d3d9Image, vtableOffset + DeviceVTableIndex.EndScene * 4);
|
||||
if (bs == es) continue;
|
||||
|
||||
// EndScene must have a hookable prologue
|
||||
int esOff = es - d3d9Base;
|
||||
if ((uint)esOff >= (uint)(d3d9Readable - 3)) continue;
|
||||
if (!IsRecognizedPrologue(d3d9Image, esOff)) continue;
|
||||
|
||||
var vtable = new IntPtr[numEntries];
|
||||
for (int i = 0; i < numEntries; i++)
|
||||
vtable[i] = new IntPtr(BitConverter.ToInt32(d3d9Image, vtableOffset + i * 4));
|
||||
|
||||
int objectAddr = regionBase + off;
|
||||
RynthLog.D3D9($"D3D9VTable: Found live device at 0x{objectAddr:X8}, vtable=0x{value:X8} (d3d9+0x{vtableOffset:X}), " +
|
||||
$"EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8} ({inModule}/{numEntries} in-module)");
|
||||
RynthLog.D3D9($"D3D9VTable: Heap scan stats: {regionsScanned} regions, {bytesScanned / 1024}KB, {d3d9Pointers} d3d9 pointers checked.");
|
||||
return vtable;
|
||||
}
|
||||
|
||||
scanAddr = nextAddr;
|
||||
}
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: No live device found — {regionsScanned} regions, {bytesScanned / 1024}KB, {d3d9Pointers} d3d9 pointers.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─── VirtualQuery wrapper ─────────────────────────────────────────
|
||||
[DllImport("kernel32.dll", SetLastError = false)]
|
||||
private static extern int VirtualQuery(IntPtr lpAddress, byte[] lpBuffer, int dwLength);
|
||||
|
||||
private static bool VirtualQueryWrapped(IntPtr address, out int regionBase, out int regionSize,
|
||||
out uint state, out uint protect, out uint type)
|
||||
{
|
||||
regionBase = 0; regionSize = 0; state = 0; protect = 0; type = 0;
|
||||
byte[] buf = new byte[28]; // MEMORY_BASIC_INFORMATION on x86
|
||||
int result = VirtualQuery(address, buf, 28);
|
||||
if (result == 0) return false;
|
||||
|
||||
regionBase = BitConverter.ToInt32(buf, 0); // BaseAddress
|
||||
regionSize = BitConverter.ToInt32(buf, 12); // RegionSize
|
||||
state = BitConverter.ToUInt32(buf, 16); // State
|
||||
protect = BitConverter.ToUInt32(buf, 20); // Protect
|
||||
type = BitConverter.ToUInt32(buf, 24); // Type
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryReadModuleImageSize(IntPtr moduleBase, out int imageSize)
|
||||
{
|
||||
imageSize = 0;
|
||||
try
|
||||
{
|
||||
if ((ushort)Marshal.ReadInt16(moduleBase) != 0x5A4D) return false; // MZ
|
||||
int peOffset = Marshal.ReadInt32(moduleBase, 0x3C);
|
||||
if (peOffset <= 0) return false;
|
||||
IntPtr ntHeaders = IntPtr.Add(moduleBase, peOffset);
|
||||
if ((uint)Marshal.ReadInt32(ntHeaders) != 0x00004550) return false; // PE\0\0
|
||||
imageSize = Marshal.ReadInt32(ntHeaders, 0x18 + 0x38); // SizeOfImage
|
||||
return imageSize > 0x1000;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
408
src/RynthCore.Engine/D3D9/EndSceneHook.cs
Normal file
408
src/RynthCore.Engine/D3D9/EndSceneHook.cs
Normal file
|
|
@ -0,0 +1,408 @@
|
|||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class EndSceneHook
|
||||
{
|
||||
private const int MaxOffscreenSkipLogs = 3;
|
||||
private const int MaxOffscreenSkipsBeforeFallback = 120;
|
||||
private const int OffscreenFallbackDelayMs = 3000;
|
||||
private const int UiInitWarmupFrames = 180;
|
||||
|
||||
// ── FPS Governor — set by plugins via API ───────────────────────
|
||||
internal static bool FpsLimitEnabled;
|
||||
internal static int FpsTargetFocused = 60;
|
||||
internal static int FpsTargetBackground = 30;
|
||||
private static readonly Stopwatch _fpsTimer = Stopwatch.StartNew();
|
||||
private static bool _fpsLimiterLoggedOnce;
|
||||
private static int _fpsDebugCounter;
|
||||
private static long _fpsCounterStart;
|
||||
private static int _fpsCounterFrames;
|
||||
|
||||
/// <summary>
|
||||
/// Last measured EndScene frames-per-second, refreshed once per second.
|
||||
/// Updated whether or not the FPS governor is enabled — UI panels (the
|
||||
/// RynthAi footer) read this for a live frame-rate display. Volatile
|
||||
/// because writes happen on the AC pump thread and reads happen on the
|
||||
/// Avalonia dispatcher thread (10 Hz panel tick); double-word atomic on
|
||||
/// x86 and we don't need a tear-free guarantee on this value.
|
||||
/// </summary>
|
||||
internal static volatile float MeasuredFps;
|
||||
private static long _liveFpsCounterStart;
|
||||
private static int _liveFpsCounterFrames;
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetForegroundWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint lpdwProcessId);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern uint GetCurrentProcessId();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int EndSceneDelegate(IntPtr pDevice);
|
||||
|
||||
private static EndSceneDelegate? _originalEndScene;
|
||||
private static EndSceneDelegate? _hookDelegate;
|
||||
private static IntPtr _endSceneAddr;
|
||||
private static bool _installed;
|
||||
private static int _frameCount;
|
||||
private static int _renderCount;
|
||||
private static int _skipCount;
|
||||
private static int _uiFrameCount;
|
||||
private static bool _offscreenFilterDisabled;
|
||||
private static bool _uiActivated;
|
||||
private static bool _warmupLogged;
|
||||
private static long _installTick;
|
||||
private static long _firstOffscreenTick;
|
||||
private static string _installSource = "uninitialized";
|
||||
|
||||
public static void Install()
|
||||
{
|
||||
Install("fallback-vtable");
|
||||
}
|
||||
|
||||
public static void Install(string installSource)
|
||||
{
|
||||
if (_installed)
|
||||
return;
|
||||
|
||||
ResetInstallState(installSource);
|
||||
|
||||
// Vtable discovery uses a NULLREF device to avoid GPU contention
|
||||
// with the game's render thread. Retry once on failure.
|
||||
const int maxAttempts = 2;
|
||||
for (int attempt = 1; attempt <= maxAttempts; attempt++)
|
||||
{
|
||||
RynthLog.D3D9($"EndSceneHook: Discovering D3D9 vtable (attempt {attempt}/{maxAttempts})...");
|
||||
|
||||
if (attempt > 1)
|
||||
System.Threading.Thread.Sleep(500);
|
||||
|
||||
IntPtr[]? vtable = D3D9VTable.GetDeviceVTable();
|
||||
if (vtable != null)
|
||||
{
|
||||
IntPtr endSceneAddress = vtable[DeviceVTableIndex.EndScene];
|
||||
RynthLog.D3D9($"EndSceneHook: EndScene @ 0x{endSceneAddress:X8}");
|
||||
InstallFromEndSceneAddress(endSceneAddress);
|
||||
return;
|
||||
}
|
||||
|
||||
RynthLog.D3D9($"EndSceneHook: Vtable discovery returned null on attempt {attempt}.");
|
||||
}
|
||||
|
||||
RynthLog.D3D9("EndSceneHook: FAILED - could not discover vtable after all attempts.");
|
||||
}
|
||||
|
||||
public static void InstallFromDevice(IntPtr pDevice)
|
||||
{
|
||||
if (_installed)
|
||||
return;
|
||||
|
||||
if (pDevice == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("EndSceneHook: Real-device install skipped because the device pointer was null.");
|
||||
return;
|
||||
}
|
||||
|
||||
ResetInstallState("real-device");
|
||||
|
||||
IntPtr deviceVTable = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr endSceneAddress = Marshal.ReadIntPtr(deviceVTable, DeviceVTableIndex.EndScene * IntPtr.Size);
|
||||
RynthLog.D3D9($"EndSceneHook: Using real D3D9 device 0x{pDevice:X8}; EndScene @ 0x{endSceneAddress:X8}");
|
||||
InstallFromEndSceneAddress(endSceneAddress);
|
||||
}
|
||||
|
||||
public static void InstallFromAddress(IntPtr endSceneAddress, string installSource)
|
||||
{
|
||||
if (_installed)
|
||||
return;
|
||||
|
||||
if (endSceneAddress == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("EndSceneHook: Address install skipped because EndScene was null.");
|
||||
return;
|
||||
}
|
||||
|
||||
ResetInstallState(installSource);
|
||||
RynthLog.D3D9($"EndSceneHook: Using explicit EndScene address 0x{endSceneAddress:X8} from {installSource}.");
|
||||
InstallFromEndSceneAddress(endSceneAddress);
|
||||
}
|
||||
|
||||
public static bool IsInstalled()
|
||||
{
|
||||
return _installed;
|
||||
}
|
||||
|
||||
public static int GetRenderCount()
|
||||
{
|
||||
return _renderCount;
|
||||
}
|
||||
|
||||
public static void Uninstall()
|
||||
{
|
||||
if (!_installed)
|
||||
return;
|
||||
|
||||
// Order is critical: disable the detour FIRST so AC's render thread
|
||||
// stops entering our code, then drain in-flight calls, THEN tear down
|
||||
// ImGui. If we destroyed the context first, an in-flight EndScene call
|
||||
// would assert on `GImGui != NULL`.
|
||||
int status = MinHook.MH_DisableHook(_endSceneAddr);
|
||||
RynthLog.D3D9($"EndSceneHook: Disable = {MinHook.StatusString(status)}");
|
||||
|
||||
// Let the render thread return through the trampoline.
|
||||
Thread.Sleep(80);
|
||||
|
||||
EngineFrameController.Shutdown();
|
||||
|
||||
status = MinHook.MH_RemoveHook(_endSceneAddr);
|
||||
RynthLog.D3D9($"EndSceneHook: Remove = {MinHook.StatusString(status)}");
|
||||
|
||||
_installed = false;
|
||||
_originalEndScene = null;
|
||||
_offscreenFilterDisabled = false;
|
||||
}
|
||||
|
||||
private static void ResetInstallState(string installSource)
|
||||
{
|
||||
_installSource = installSource;
|
||||
_frameCount = 0;
|
||||
_renderCount = 0;
|
||||
_skipCount = 0;
|
||||
_uiFrameCount = 0;
|
||||
_offscreenFilterDisabled = false;
|
||||
_uiActivated = false;
|
||||
_warmupLogged = false;
|
||||
_installTick = Environment.TickCount64;
|
||||
_firstOffscreenTick = 0;
|
||||
}
|
||||
|
||||
private static void InstallFromEndSceneAddress(IntPtr endSceneAddress)
|
||||
{
|
||||
_endSceneAddr = endSceneAddress;
|
||||
|
||||
_hookDelegate = new EndSceneDelegate(EndSceneDetour);
|
||||
IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);
|
||||
|
||||
try
|
||||
{
|
||||
_originalEndScene = Marshal.GetDelegateForFunctionPointer<EndSceneDelegate>(MinHook.HookCreate(_endSceneAddr, hookPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_endSceneAddr);
|
||||
_installed = true;
|
||||
|
||||
RynthLog.D3D9($"EndSceneHook: INSTALLED successfully via {_installSource}.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"EndSceneHook: MinHook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int EndSceneDetour(IntPtr pDevice)
|
||||
{
|
||||
// Liveness beacon for MainThreadHangWatchdog — this detour runs on AC's
|
||||
// main/render thread every frame (even with the ImGui backend disabled),
|
||||
// so a stalled beat means the main thread is wedged. Must never throw.
|
||||
try { MainThreadHangWatchdog.MainThreadBeat(); } catch { }
|
||||
try
|
||||
{
|
||||
if (!_offscreenFilterDisabled && !DX9Backend.IsRenderingToBackBuffer(pDevice))
|
||||
{
|
||||
if (_firstOffscreenTick == 0)
|
||||
_firstOffscreenTick = Environment.TickCount64;
|
||||
|
||||
if (_skipCount < MaxOffscreenSkipLogs)
|
||||
RynthLog.D3D9("EndSceneHook: Skipping offscreen EndScene pass.");
|
||||
_skipCount++;
|
||||
|
||||
long offscreenElapsedMs = Environment.TickCount64 - _firstOffscreenTick;
|
||||
if (_skipCount < MaxOffscreenSkipsBeforeFallback && offscreenElapsedMs < OffscreenFallbackDelayMs)
|
||||
return _originalEndScene!(pDevice);
|
||||
|
||||
_offscreenFilterDisabled = true;
|
||||
RynthLog.D3D9($"EndSceneHook: Falling back to unfiltered EndScene after {_skipCount} skipped offscreen pass(es) over {offscreenElapsedMs}ms.");
|
||||
}
|
||||
|
||||
_renderCount++;
|
||||
_frameCount++;
|
||||
|
||||
// Per-frame chatbox visibility assertion (no-op unless plugin enables suppression).
|
||||
try { ChatHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
|
||||
// Per-frame retail-radar visibility assertion (no-op unless plugin enables suppression).
|
||||
try { RadarHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
|
||||
// Per-frame retail-powerbar visibility assertion (no-op unless plugin enables suppression).
|
||||
try { PowerbarHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
|
||||
|
||||
if (_renderCount == 1 && _offscreenFilterDisabled && _skipCount > 0)
|
||||
{
|
||||
long installElapsedMs = Environment.TickCount64 - _installTick;
|
||||
RynthLog.D3D9($"EndSceneHook: First render after offscreen fallback ({_skipCount} skip(s), {installElapsedMs}ms since install).");
|
||||
}
|
||||
|
||||
if (_renderCount == 1 && _skipCount > 0)
|
||||
RynthLog.D3D9($"EndSceneHook: First backbuffer frame after skipping {_skipCount} offscreen pass(es).");
|
||||
|
||||
// On first backbuffer frame, verify we hooked the right function by
|
||||
// reading the device's own vtable. A mismatch means the module scan
|
||||
// found an internal/proxy vtable, not the one the game's device uses.
|
||||
if (_renderCount == 1)
|
||||
{
|
||||
IntPtr deviceVtable = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr actualEndScene = Marshal.ReadIntPtr(deviceVtable, DeviceVTableIndex.EndScene * IntPtr.Size);
|
||||
bool match = actualEndScene == _endSceneAddr;
|
||||
RynthLog.D3D9($"EndSceneHook: Device vtable EndScene=0x{actualEndScene:X8}, hooked=0x{_endSceneAddr:X8} — {(match ? "MATCH" : "MISMATCH")}");
|
||||
|
||||
if (!match && actualEndScene != IntPtr.Zero)
|
||||
{
|
||||
// Deep-audit finding #8 (2026-06-18): the old sequence
|
||||
// disabled+REMOVED the old hook (freeing the trampoline
|
||||
// _originalEndScene points at) BEFORE attempting the new
|
||||
// install. If the new MH_CreateHook then threw,
|
||||
// _originalEndScene was never reassigned — it still bound
|
||||
// the now-freed trampoline — yet the code force-set
|
||||
// _installed=true and this function's bottom called
|
||||
// through it: a use-after-free. Fixed order: only remove
|
||||
// the OLD hook after the NEW one is confirmed installed;
|
||||
// on failure, re-enable the OLD hook and keep using its
|
||||
// still-valid trampoline instead of a dangling one.
|
||||
RynthLog.D3D9("EndSceneHook: Rehooking at the device's actual EndScene address.");
|
||||
IntPtr oldAddr = _endSceneAddr;
|
||||
EndSceneDelegate? oldOriginal = _originalEndScene;
|
||||
MinHook.MH_DisableHook(oldAddr);
|
||||
|
||||
InstallFromEndSceneAddress(actualEndScene);
|
||||
if (_installed)
|
||||
{
|
||||
// New hook confirmed live — safe to free the old
|
||||
// trampoline now.
|
||||
MinHook.MH_RemoveHook(oldAddr);
|
||||
return _originalEndScene!(pDevice);
|
||||
}
|
||||
|
||||
RynthLog.D3D9("EndSceneHook: Rehook failed — restoring original hook.");
|
||||
// New install failed (InstallFromEndSceneAddress leaves
|
||||
// _installed=false on failure). Restore the OLD hook
|
||||
// rather than trust a dangling delegate.
|
||||
_endSceneAddr = oldAddr;
|
||||
_originalEndScene = oldOriginal;
|
||||
MinHook.Enable(oldAddr);
|
||||
_installed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!_uiActivated)
|
||||
{
|
||||
if (!_warmupLogged)
|
||||
{
|
||||
RynthLog.D3D9($"EndSceneHook: Backbuffer detected. Warming up {UiInitWarmupFrames} frame(s) before UI init.");
|
||||
_warmupLogged = true;
|
||||
}
|
||||
|
||||
if (_renderCount < UiInitWarmupFrames)
|
||||
return _originalEndScene!(pDevice);
|
||||
|
||||
_uiActivated = true;
|
||||
RynthLog.D3D9("EndSceneHook: Warmup complete - initializing ImGui.");
|
||||
}
|
||||
|
||||
// EngineFrameController.OnEndScene runs the always-on engine work
|
||||
// (matrix capture, plugin tick, nav rendering, pending action drains)
|
||||
// every frame. The EnableImGuiBackend gate moved INSIDE the
|
||||
// controller so it scopes only the ImGui-specific block; this call
|
||||
// site no longer needs to gate it.
|
||||
EngineFrameController.OnEndScene(pDevice);
|
||||
_uiFrameCount++;
|
||||
|
||||
if (_uiFrameCount == 60 && RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend)
|
||||
RynthLog.D3D9("EndSceneHook: 60 UI frames - ImGui is stable.");
|
||||
if (_renderCount == UiInitWarmupFrames && !RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend)
|
||||
RynthLog.D3D9("EndSceneHook: ImGui backend disabled via engine.json (EnableImGuiBackend=false). Always-on engine work still runs; only ImGui draw calls are skipped.");
|
||||
|
||||
// Avalonia compositor: independent of ImGui. Reads the latest
|
||||
// Avalonia surface from OverlaySurfaceBridge and blits it as a
|
||||
// fullscreen alpha-blended quad onto AC's back buffer. Runs every
|
||||
// frame regardless of EnableImGuiBackend so the Avalonia overlay
|
||||
// is visible even when ImGui per-frame work is disabled. Driven
|
||||
// here exclusively — EngineFrameController.OnEndScene intentionally
|
||||
// does NOT call it (avoids double-blit / TryConsume races).
|
||||
try
|
||||
{
|
||||
OverlayTextureRenderer.Render(pDevice);
|
||||
}
|
||||
catch (Exception ovEx)
|
||||
{
|
||||
if (_uiFrameCount < 30)
|
||||
RynthLog.D3D9($"EndSceneHook: OverlayTextureRenderer.Render error: {ovEx.GetType().Name}: {ovEx.Message}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_uiFrameCount < 30)
|
||||
RynthLog.D3D9($"EndSceneHook: Frame {_frameCount} error: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
|
||||
}
|
||||
|
||||
// ── Always-on FPS measurement for UI footer ──────────────────
|
||||
// Runs whether or not the governor is enabled so the RynthAi
|
||||
// footer can show a live FPS even when the user hasn't capped.
|
||||
// Cheap: one increment + a once-per-second division.
|
||||
_liveFpsCounterFrames++;
|
||||
long liveNow = Environment.TickCount64;
|
||||
if (_liveFpsCounterStart == 0) _liveFpsCounterStart = liveNow;
|
||||
long liveElapsed = liveNow - _liveFpsCounterStart;
|
||||
if (liveElapsed >= 1000)
|
||||
{
|
||||
MeasuredFps = (float)(_liveFpsCounterFrames * 1000.0 / liveElapsed);
|
||||
_liveFpsCounterFrames = 0;
|
||||
_liveFpsCounterStart = liveNow;
|
||||
}
|
||||
|
||||
// ── FPS Governor (matches proven NexSuite2 pattern) ─────────
|
||||
if (FpsLimitEnabled)
|
||||
{
|
||||
IntPtr fgWnd = GetForegroundWindow();
|
||||
// Focused when AC itself is foreground, OR when any window belonging
|
||||
// to our process is foreground (covers DComp overlay, any Avalonia
|
||||
// child window, etc.). PID comparison is reliable regardless of how
|
||||
// the owner chain was established (GWL_HWNDPARENT vs CreateWindow).
|
||||
GetWindowThreadProcessId(fgWnd, out uint fgPid);
|
||||
bool isFocused = fgWnd != IntPtr.Zero &&
|
||||
(fgWnd == Win32Backend.GameHwnd || fgPid == GetCurrentProcessId());
|
||||
int targetFps = isFocused ? FpsTargetFocused : FpsTargetBackground;
|
||||
double minFrameMs = 1000.0 / Math.Max(targetFps, 1);
|
||||
|
||||
while (_fpsTimer.Elapsed.TotalMilliseconds < minFrameMs)
|
||||
Thread.Sleep(isFocused ? 0 : 1);
|
||||
_fpsTimer.Restart();
|
||||
|
||||
if (!_fpsLimiterLoggedOnce)
|
||||
{
|
||||
_fpsLimiterLoggedOnce = true;
|
||||
RynthLog.D3D9($"EndSceneHook: FPS governor active — max={FpsTargetFocused} focused, max={FpsTargetBackground} background, gameHwnd=0x{Win32Backend.GameHwnd.ToInt64():X}");
|
||||
}
|
||||
|
||||
// Periodic FPS measurement — log every 60 seconds
|
||||
_fpsCounterFrames++;
|
||||
long now = Environment.TickCount64;
|
||||
if (_fpsCounterStart == 0) _fpsCounterStart = now;
|
||||
long elapsedMs = now - _fpsCounterStart;
|
||||
if (elapsedMs >= 60_000)
|
||||
{
|
||||
double measuredFps = _fpsCounterFrames * 1000.0 / elapsedMs;
|
||||
RynthLog.D3D9($"EndSceneHook: FPS={measuredFps:F1} (target={targetFps}, {(isFocused ? "focused" : "background")})");
|
||||
_fpsCounterFrames = 0;
|
||||
_fpsCounterStart = now;
|
||||
}
|
||||
}
|
||||
|
||||
return _originalEndScene!(pDevice);
|
||||
}
|
||||
}
|
||||
374
src/RynthCore.Engine/D3D9/GameMatrixCapture.cs
Normal file
374
src/RynthCore.Engine/D3D9/GameMatrixCapture.cs
Normal file
|
|
@ -0,0 +1,374 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/GameMatrixCapture.cs
|
||||
// Captures the game's camera transform and perspective Projection matrix
|
||||
// for WorldToScreen projection.
|
||||
//
|
||||
// AC sets View=identity and World=identity — it transforms all vertices
|
||||
// on the CPU before sending to D3D9. Only the Projection matrix is real.
|
||||
//
|
||||
// Strategy:
|
||||
// - Hook SetTransform to capture the perspective Projection matrix.
|
||||
// - Read the camera position + rotation from SmartBox memory.
|
||||
// - Build the View matrix manually, then ViewProj = View * Proj.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static unsafe class GameMatrixCapture
|
||||
{
|
||||
private const uint D3DTS_PROJECTION = 3;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTransformD(IntPtr dev, uint state, float* pMatrix);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetViewportD(IntPtr dev, int* pViewport);
|
||||
|
||||
// SetTransform hook
|
||||
private static SetTransformD? _originalSetTransform;
|
||||
private static SetTransformD? _hookDelegate;
|
||||
private static bool _hookInstalled;
|
||||
|
||||
// Viewport
|
||||
private static GetViewportD? _getViewport;
|
||||
private static bool _viewportCached;
|
||||
private static uint _vpWidth;
|
||||
private static uint _vpHeight;
|
||||
private static bool _hasViewport;
|
||||
|
||||
// Captured Projection matrix
|
||||
private static readonly float[] _perspProj = new float[16];
|
||||
private static bool _hasProj;
|
||||
|
||||
// Computed matrices
|
||||
private static readonly float[] _viewMatrix = new float[16];
|
||||
private static readonly float[] _viewProj = new float[16];
|
||||
private static bool _hasValidViewProj;
|
||||
|
||||
// Camera frame from SmartBox memory.
|
||||
// AC's Position struct: PackObj.vfptr (4) + objcell_id (4) + Frame (...).
|
||||
// Frame is qw,qx,qy,qz (16) + m_fl2gv[9] (36) + m_fOrigin (12) = 64 bytes.
|
||||
// So at Position start (+0x08 from SmartBox):
|
||||
// +0x00 PackObj.vfptr (4)
|
||||
// +0x04 objcell_id (4) ← real viewer cellId
|
||||
// +0x08 Frame.qw,qx,qy,qz (16)
|
||||
// +0x18 Frame.m_fl2gv[9] (36) ← cached 3x3 rotation matrix
|
||||
// +0x3C Frame.m_fOrigin (12) ← camera position (x, y, z)
|
||||
private const int CameraFrameOffset = 0x08;
|
||||
private const int CamCellIdOffset = 0x04; // viewer cellId (skips PackObj.vfptr)
|
||||
private const int CamRotOffset = 0x18;
|
||||
private const int CamPosOffset = 0x3C;
|
||||
|
||||
// Diagnostics
|
||||
private static int _framesSinceLog;
|
||||
private static bool _loggedFirstCapture;
|
||||
|
||||
public static bool HasCapturedFrame => _hasValidViewProj;
|
||||
public static uint ViewportWidth => _vpWidth;
|
||||
public static uint ViewportHeight => _vpHeight;
|
||||
|
||||
/// <summary>Copy the 4x4 View matrix (row-major) into the destination.</summary>
|
||||
public static void GetViewMatrix(ref float dest)
|
||||
{
|
||||
fixed (float* s = _viewMatrix)
|
||||
fixed (float* d = &dest)
|
||||
{
|
||||
for (int i = 0; i < 16; i++)
|
||||
d[i] = s[i];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Copy the 4x4 Projection matrix (row-major) into the destination.</summary>
|
||||
public static void GetProjectionMatrix(ref float dest)
|
||||
{
|
||||
fixed (float* s = _perspProj)
|
||||
fixed (float* d = &dest)
|
||||
{
|
||||
for (int i = 0; i < 16; i++)
|
||||
d[i] = s[i];
|
||||
}
|
||||
}
|
||||
|
||||
private static int SetTransformDetour(IntPtr dev, uint state, float* pMatrix)
|
||||
{
|
||||
if (pMatrix != null && state == D3DTS_PROJECTION)
|
||||
{
|
||||
bool isPerspective = Math.Abs(pMatrix[11]) > 0.01f;
|
||||
if (isPerspective)
|
||||
{
|
||||
for (int i = 0; i < 16; i++)
|
||||
_perspProj[i] = pMatrix[i];
|
||||
_hasProj = true;
|
||||
}
|
||||
}
|
||||
return _originalSetTransform!(dev, state, pMatrix);
|
||||
}
|
||||
|
||||
public static void CaptureFrame(IntPtr pDevice)
|
||||
{
|
||||
if (pDevice == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
if (!_hookInstalled)
|
||||
InstallHook(pDevice);
|
||||
|
||||
// Read viewport
|
||||
if (!_viewportCached)
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
_getViewport = Marshal.GetDelegateForFunctionPointer<GetViewportD>(
|
||||
Marshal.ReadIntPtr(vtable, DeviceVTableIndex.GetViewport * IntPtr.Size));
|
||||
_viewportCached = true;
|
||||
}
|
||||
|
||||
int* vp = stackalloc int[6];
|
||||
if (_getViewport!(pDevice, vp) >= 0 && vp[2] > 0 && vp[3] > 0)
|
||||
{
|
||||
_vpWidth = (uint)vp[2];
|
||||
_vpHeight = (uint)vp[3];
|
||||
_hasViewport = true;
|
||||
}
|
||||
|
||||
if (_hasProj)
|
||||
BuildViewProjFromCamera();
|
||||
|
||||
_framesSinceLog++;
|
||||
if (_framesSinceLog >= 3000)
|
||||
{
|
||||
_framesSinceLog = 0;
|
||||
RynthLog.D3D9($"GameMatrixCapture: valid={_hasValidViewProj} vp={_vpWidth}x{_vpHeight}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void BuildViewProjFromCamera()
|
||||
{
|
||||
if (!SmartBoxLocator.TryGetSmartBox(out IntPtr smartBox, out _, out _))
|
||||
return;
|
||||
|
||||
IntPtr camFrame = smartBox + CameraFrameOffset;
|
||||
if (!SmartBoxLocator.IsMemoryReadable(camFrame + CamPosOffset, 12))
|
||||
return;
|
||||
|
||||
// Read 3x3 rotation matrix
|
||||
float m11 = ReadFloat(camFrame + CamRotOffset + 0);
|
||||
float m12 = ReadFloat(camFrame + CamRotOffset + 4);
|
||||
float m13 = ReadFloat(camFrame + CamRotOffset + 8);
|
||||
float m21 = ReadFloat(camFrame + CamRotOffset + 12);
|
||||
float m22 = ReadFloat(camFrame + CamRotOffset + 16);
|
||||
float m23 = ReadFloat(camFrame + CamRotOffset + 20);
|
||||
float m31 = ReadFloat(camFrame + CamRotOffset + 24);
|
||||
float m32 = ReadFloat(camFrame + CamRotOffset + 28);
|
||||
float m33 = ReadFloat(camFrame + CamRotOffset + 32);
|
||||
|
||||
// Read position (AC physics: x=EW, y=NS, z=height)
|
||||
float cx = ReadFloat(camFrame + CamPosOffset + 0);
|
||||
float cy = ReadFloat(camFrame + CamPosOffset + 4);
|
||||
float cz = ReadFloat(camFrame + CamPosOffset + 8);
|
||||
|
||||
if (cx == 0f && cy == 0f && cz == 0f)
|
||||
return;
|
||||
|
||||
// The camera's pose is stored landblock-local: as the camera orbits
|
||||
// across a landblock boundary, AC re-anchors the viewer to the new
|
||||
// landblock and (cx, cy) jumps to that landblock's frame. Plugins
|
||||
// submitting Nav3D markers around the player are in the PLAYER's
|
||||
// landblock frame, so we shift the camera back into that frame here.
|
||||
// Without this, every marker visually leaps 192 m when the camera
|
||||
// crosses a landblock boundary even though the player hasn't moved.
|
||||
//
|
||||
// Guards: the viewer cellId can briefly hold uninitialized / mid-
|
||||
// teleport junk (e.g. landblock 0x0001 while the world isn't loaded)
|
||||
// that gives a multi-thousand-meter "delta" and produces a wildly
|
||||
// wrong view matrix. Only apply the shift when both landblocks look
|
||||
// like real outdoor world landblocks AND the delta is within ±4
|
||||
// landblocks (no legitimate camera frustum reaches further).
|
||||
float rawCx = cx, rawCy = cy;
|
||||
bool shiftApplied = false;
|
||||
int dXBlocks = 0, dYBlocks = 0;
|
||||
uint viewerLbForLog = 0, playerLbForLog = 0;
|
||||
bool guardBlocked = false;
|
||||
string guardReason = "";
|
||||
|
||||
uint viewerCellId = unchecked((uint)Marshal.ReadInt32(camFrame + CamCellIdOffset));
|
||||
uint viewerLandblock = viewerCellId >> 16;
|
||||
viewerLbForLog = viewerLandblock;
|
||||
|
||||
// Prefer the landblock the plugin tick LOCKED IN when it submitted
|
||||
// its Nav3D geometry (see Nav3DRenderer.ClearFrame). If we use the
|
||||
// CURRENT player landblock instead, render and triangles disagree
|
||||
// for the frames between the player crossing a boundary and the next
|
||||
// plugin tick re-submitting — geometry jumps to the adjacent
|
||||
// landblock for ~1 s and snaps back. Fall back to current player
|
||||
// landblock when no submission frame is published (zero).
|
||||
uint submissionLandblock = Nav3DRenderer.ReadyPlayerLandblock;
|
||||
bool havePose;
|
||||
uint playerCellId;
|
||||
if (submissionLandblock != 0)
|
||||
{
|
||||
havePose = true;
|
||||
playerCellId = submissionLandblock << 16;
|
||||
}
|
||||
else
|
||||
{
|
||||
havePose = PlayerPhysicsHooks.TryGetPlayerPose(out playerCellId, out _, out _, out _,
|
||||
out _, out _, out _, out _);
|
||||
}
|
||||
if (viewerLandblock != 0 && havePose && (playerCellId >> 16) != 0)
|
||||
{
|
||||
uint playerLandblock = playerCellId >> 16;
|
||||
playerLbForLog = playerLandblock;
|
||||
int viewerLbX = (int)((viewerLandblock >> 8) & 0xFF);
|
||||
int viewerLbY = (int)(viewerLandblock & 0xFF);
|
||||
int playerLbX = (int)((playerLandblock >> 8) & 0xFF);
|
||||
int playerLbY = (int)(playerLandblock & 0xFF);
|
||||
dXBlocks = viewerLbX - playerLbX;
|
||||
dYBlocks = viewerLbY - playerLbY;
|
||||
if (Math.Abs(dXBlocks) <= 4 && Math.Abs(dYBlocks) <= 4 &&
|
||||
viewerLbX != 0 && viewerLbY != 0)
|
||||
{
|
||||
cx += dXBlocks * 192f; // EW shift back into player-landblock frame
|
||||
cy += dYBlocks * 192f; // NS
|
||||
shiftApplied = (dXBlocks != 0 || dYBlocks != 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
guardBlocked = (dXBlocks != 0 || dYBlocks != 0);
|
||||
guardReason = $"dx={dXBlocks},dy={dYBlocks},vLbX={viewerLbX},vLbY={viewerLbY}";
|
||||
}
|
||||
}
|
||||
|
||||
// Log when a non-zero shift fires (camera crossed a landblock) or when
|
||||
// the guard blocked one. Helps catch "paintings move with camera"
|
||||
// without spamming when player and viewer landblocks agree.
|
||||
if (shiftApplied || guardBlocked)
|
||||
{
|
||||
RynthLog.D3D9($"GameMatrixCapture: viewer lb=0x{viewerLbForLog:X4} player lb=0x{playerLbForLog:X4} " +
|
||||
$"d=({dXBlocks},{dYBlocks}) raw=({rawCx:F1},{rawCy:F1}) adj=({cx:F1},{cy:F1}) " +
|
||||
$"{(shiftApplied ? "SHIFTED" : "GUARD-BLOCKED " + guardReason)}");
|
||||
}
|
||||
|
||||
// View matrix rotation block (D3D Y-up, with AC Y/Z swap).
|
||||
// AC camera rows: row1=Right, row2=Forward, row3=Up
|
||||
// After Y/Z component swap → D3D basis vectors as columns:
|
||||
// col0 = Right_d3d = (m11, m13, m12)
|
||||
// col1 = Up_d3d = (m31, m33, m32)
|
||||
// col2 = Forward_d3d = (m21, m23, m22)
|
||||
_viewMatrix[0] = m11; _viewMatrix[1] = m31; _viewMatrix[2] = m21; _viewMatrix[3] = 0;
|
||||
_viewMatrix[4] = m13; _viewMatrix[5] = m33; _viewMatrix[6] = m23; _viewMatrix[7] = 0;
|
||||
_viewMatrix[8] = m12; _viewMatrix[9] = m32; _viewMatrix[10] = m22; _viewMatrix[11] = 0;
|
||||
|
||||
// Translation = -CamPos_D3D * R_view
|
||||
// CamPos_D3D = (cx, cz, cy) after Y/Z swap
|
||||
float px = cx; // EW
|
||||
float py = cz; // height (D3D Y)
|
||||
float pz = cy; // NS (D3D Z)
|
||||
|
||||
_viewMatrix[12] = -(px * _viewMatrix[0] + py * _viewMatrix[4] + pz * _viewMatrix[8]);
|
||||
_viewMatrix[13] = -(px * _viewMatrix[1] + py * _viewMatrix[5] + pz * _viewMatrix[9]);
|
||||
_viewMatrix[14] = -(px * _viewMatrix[2] + py * _viewMatrix[6] + pz * _viewMatrix[10]);
|
||||
_viewMatrix[15] = 1;
|
||||
|
||||
// ViewProj = View * Projection
|
||||
fixed (float* v = _viewMatrix)
|
||||
fixed (float* p = _perspProj)
|
||||
fixed (float* r = _viewProj)
|
||||
{
|
||||
for (int row = 0; row < 4; row++)
|
||||
for (int col = 0; col < 4; col++)
|
||||
r[row * 4 + col] =
|
||||
v[row * 4 + 0] * p[0 * 4 + col] +
|
||||
v[row * 4 + 1] * p[1 * 4 + col] +
|
||||
v[row * 4 + 2] * p[2 * 4 + col] +
|
||||
v[row * 4 + 3] * p[3 * 4 + col];
|
||||
}
|
||||
|
||||
if (!_loggedFirstCapture)
|
||||
{
|
||||
_loggedFirstCapture = true;
|
||||
RynthLog.D3D9($"GameMatrixCapture: camera pos=({cx:F2},{cy:F2},{cz:F2}) [EW,NS,Z]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: View row0=[{_viewMatrix[0]:F4}, {_viewMatrix[1]:F4}, {_viewMatrix[2]:F4}, {_viewMatrix[3]:F4}]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: View row1=[{_viewMatrix[4]:F4}, {_viewMatrix[5]:F4}, {_viewMatrix[6]:F4}, {_viewMatrix[7]:F4}]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: View row2=[{_viewMatrix[8]:F4}, {_viewMatrix[9]:F4}, {_viewMatrix[10]:F4}, {_viewMatrix[11]:F4}]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: View row3=[{_viewMatrix[12]:F4}, {_viewMatrix[13]:F4}, {_viewMatrix[14]:F4}, {_viewMatrix[15]:F4}]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: viewport={_vpWidth}x{_vpHeight}");
|
||||
}
|
||||
|
||||
_hasValidViewProj = true;
|
||||
}
|
||||
|
||||
private static float ReadFloat(IntPtr address)
|
||||
{
|
||||
int bits = Marshal.ReadInt32(address);
|
||||
return BitConverter.Int32BitsToSingle(bits);
|
||||
}
|
||||
|
||||
public static bool WorldToScreen(float wx, float wy, float wz, out float sx, out float sy)
|
||||
{
|
||||
sx = 0f;
|
||||
sy = 0f;
|
||||
|
||||
if (!_hasValidViewProj || _vpWidth == 0 || _vpHeight == 0)
|
||||
return false;
|
||||
|
||||
float clipX = wx * _viewProj[0] + wy * _viewProj[4] + wz * _viewProj[8] + _viewProj[12];
|
||||
float clipY = wx * _viewProj[1] + wy * _viewProj[5] + wz * _viewProj[9] + _viewProj[13];
|
||||
float clipW = wx * _viewProj[3] + wy * _viewProj[7] + wz * _viewProj[11] + _viewProj[15];
|
||||
|
||||
if (clipW <= 0.001f)
|
||||
return false;
|
||||
|
||||
float ndcX = clipX / clipW;
|
||||
float ndcY = clipY / clipW;
|
||||
|
||||
sx = (ndcX + 1.0f) * 0.5f * _vpWidth;
|
||||
sy = (1.0f - ndcY) * 0.5f * _vpHeight;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static int WorldToScreenCallback(float wx, float wy, float wz, float* sx, float* sy)
|
||||
{
|
||||
bool result = WorldToScreen(wx, wy, wz, out float screenX, out float screenY);
|
||||
*sx = screenX;
|
||||
*sy = screenY;
|
||||
return result ? 1 : 0;
|
||||
}
|
||||
|
||||
public static int GetViewportSizeCallback(uint* width, uint* height)
|
||||
{
|
||||
if (!_hasViewport || _vpWidth == 0 || _vpHeight == 0)
|
||||
return 0;
|
||||
|
||||
*width = _vpWidth;
|
||||
*height = _vpHeight;
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static void InstallHook(IntPtr pDevice)
|
||||
{
|
||||
try
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr setTransformAddr = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.SetTransform * IntPtr.Size);
|
||||
|
||||
_hookDelegate = new SetTransformD(SetTransformDetour);
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);
|
||||
_originalSetTransform = Marshal.GetDelegateForFunctionPointer<SetTransformD>(MinHook.HookCreate(setTransformAddr, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(setTransformAddr);
|
||||
_hookInstalled = true;
|
||||
|
||||
RynthLog.D3D9("GameMatrixCapture: SetTransform hook installed.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"GameMatrixCapture: SetTransform hook FAILED — {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
101
src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs
Normal file
101
src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/Nav3DRenderInjector.cs
|
||||
// Hooks DrawIndexedPrimitive to inject nav marker rendering at the
|
||||
// 3D→UI boundary. When ZENABLE transitions from 1→0, renders markers
|
||||
// so they appear after the 3D world but before the game's UI pass.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class Nav3DRenderInjector
|
||||
{
|
||||
private const uint D3DRS_ZENABLE = 7;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int DrawIndexedPrimitiveD(IntPtr dev, uint primitiveType,
|
||||
int baseVertexIndex, uint minVertexIndex, uint numVertices,
|
||||
uint startIndex, uint primCount);
|
||||
|
||||
private static DrawIndexedPrimitiveD? _originalDIP;
|
||||
private static DrawIndexedPrimitiveD? _hookDelegate;
|
||||
private static bool _hookInstalled;
|
||||
private static bool _inRender;
|
||||
|
||||
// Per-frame transition detection
|
||||
private static uint _lastZEnable;
|
||||
private static bool _markersRenderedThisFrame;
|
||||
private static bool _seen3D;
|
||||
|
||||
public static bool RenderedThisFrame => _markersRenderedThisFrame;
|
||||
|
||||
public static void ResetFrame()
|
||||
{
|
||||
_markersRenderedThisFrame = false;
|
||||
_seen3D = false;
|
||||
_lastZEnable = 0;
|
||||
}
|
||||
|
||||
public static void Install(IntPtr pDevice)
|
||||
{
|
||||
if (_hookInstalled) return;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.DrawIndexedPrimitive * IntPtr.Size);
|
||||
|
||||
_hookDelegate = new DrawIndexedPrimitiveD(Detour);
|
||||
IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);
|
||||
_originalDIP = Marshal.GetDelegateForFunctionPointer<DrawIndexedPrimitiveD>(
|
||||
MinHook.HookCreate(addr, hookPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(addr);
|
||||
_hookInstalled = true;
|
||||
|
||||
RynthLog.D3D9("Nav3DRenderInjector: DrawIndexedPrimitive hook installed.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"Nav3DRenderInjector: Hook install FAILED — {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int Detour(IntPtr dev, uint primitiveType,
|
||||
int baseVertexIndex, uint minVertexIndex, uint numVertices,
|
||||
uint startIndex, uint primCount)
|
||||
{
|
||||
if (_inRender)
|
||||
return _originalDIP!(dev, primitiveType, baseVertexIndex,
|
||||
minVertexIndex, numVertices, startIndex, primCount);
|
||||
|
||||
ImGuiBackend.DX9Backend.DeviceGetRenderState(dev, D3DRS_ZENABLE, out uint zEnable);
|
||||
|
||||
if (zEnable != 0)
|
||||
_seen3D = true;
|
||||
|
||||
// Detect 3D→UI transition: ZENABLE goes from 1→0 after 3D draws
|
||||
if (!_markersRenderedThisFrame && _seen3D && _lastZEnable != 0 && zEnable == 0)
|
||||
{
|
||||
_markersRenderedThisFrame = true;
|
||||
_inRender = true;
|
||||
try
|
||||
{
|
||||
ImGuiBackend.DX9Backend.RenderNav3D(dev);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
_inRender = false;
|
||||
}
|
||||
|
||||
_lastZEnable = zEnable;
|
||||
|
||||
return _originalDIP!(dev, primitiveType, baseVertexIndex,
|
||||
minVertexIndex, numVertices, startIndex, primCount);
|
||||
}
|
||||
}
|
||||
221
src/RynthCore.Engine/D3D9/Nav3DRenderer.cs
Normal file
221
src/RynthCore.Engine/D3D9/Nav3DRenderer.cs
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/Nav3DRenderer.cs
|
||||
// Data store for 3D navigation markers. Plugins submit geometry every plugin
|
||||
// tick via AddRing/AddLine/AddTriangle; DX9Backend.RenderNav3D reads it
|
||||
// during EndScene.
|
||||
//
|
||||
// Double-buffered to keep the render thread (60 Hz, AC's EndScene) from
|
||||
// reading a half-rewritten buffer while the plugin pump thread (~30 Hz) is
|
||||
// mid Clear → Submit. Without this, every plugin tick produced a 1-frame
|
||||
// empty/partial render that the user sees as flicker — pronounced when the
|
||||
// player or camera is in motion (because the submitted contents change each
|
||||
// tick; when stationary the race window contains identical data so it's
|
||||
// invisible).
|
||||
//
|
||||
// Pattern:
|
||||
// pump: BeginFrame() → AddX(...) × N → CommitFrame()
|
||||
// render: reads from the "ready" buffer only; never touches "pending"
|
||||
// CommitFrame atomically swaps the index reads see.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class Nav3DRenderer
|
||||
{
|
||||
private const int MaxRings = 256;
|
||||
private const int MaxLines = 512;
|
||||
// Triangle: three vertices + color. Sized for a ~3×3-landblock slope
|
||||
// overlay around the player: 24-cell radius ≈ 49×49 cells × 2 triangles
|
||||
// = 4802 triangles worst case, with headroom for water and other uses.
|
||||
private const int MaxTriangles = 8192;
|
||||
|
||||
private const float DefaultRingHeight = 0.5f; // back-compat default for AddRing
|
||||
|
||||
private sealed class NavBuffer
|
||||
{
|
||||
public readonly float[] RingX = new float[MaxRings];
|
||||
public readonly float[] RingY = new float[MaxRings];
|
||||
public readonly float[] RingZ = new float[MaxRings];
|
||||
public readonly float[] RingRadius = new float[MaxRings];
|
||||
public readonly float[] RingThick = new float[MaxRings];
|
||||
public readonly float[] RingHeight = new float[MaxRings];
|
||||
public readonly uint[] RingColor = new uint[MaxRings];
|
||||
public int RingCount;
|
||||
|
||||
public readonly float[] LineX1 = new float[MaxLines];
|
||||
public readonly float[] LineY1 = new float[MaxLines];
|
||||
public readonly float[] LineZ1 = new float[MaxLines];
|
||||
public readonly float[] LineX2 = new float[MaxLines];
|
||||
public readonly float[] LineY2 = new float[MaxLines];
|
||||
public readonly float[] LineZ2 = new float[MaxLines];
|
||||
public readonly float[] LineThick = new float[MaxLines];
|
||||
public readonly uint[] LineColor = new uint[MaxLines];
|
||||
public int LineCount;
|
||||
|
||||
public readonly float[] TriX1 = new float[MaxTriangles];
|
||||
public readonly float[] TriY1 = new float[MaxTriangles];
|
||||
public readonly float[] TriZ1 = new float[MaxTriangles];
|
||||
public readonly float[] TriX2 = new float[MaxTriangles];
|
||||
public readonly float[] TriY2 = new float[MaxTriangles];
|
||||
public readonly float[] TriZ2 = new float[MaxTriangles];
|
||||
public readonly float[] TriX3 = new float[MaxTriangles];
|
||||
public readonly float[] TriY3 = new float[MaxTriangles];
|
||||
public readonly float[] TriZ3 = new float[MaxTriangles];
|
||||
public readonly uint[] TriColor = new uint[MaxTriangles];
|
||||
public int TriCount;
|
||||
|
||||
// The player's landblock at the moment ClearFrame was called for
|
||||
// this buffer. All AddX submissions in this tick are in PLAYER-
|
||||
// landblock-local coordinates (per RynthAi + RynthVision contract),
|
||||
// so the render side needs THIS landblock — not the current
|
||||
// player landblock — when it computes the view-matrix shift, or the
|
||||
// tick's geometry will jump 192m when the player crosses a boundary
|
||||
// between this tick and the next render frame.
|
||||
// Zero = "no player pose available; fall back to current".
|
||||
public uint SubmissionPlayerLandblock;
|
||||
|
||||
public void Reset() { RingCount = 0; LineCount = 0; TriCount = 0; SubmissionPlayerLandblock = 0; }
|
||||
}
|
||||
|
||||
// Triple buffer:
|
||||
// _ready — what the render thread reads (volatile, swap published here)
|
||||
// _pending — what the pump writes into for the current tick
|
||||
// _spare — last tick's ready, "cooling off" one tick before the pump
|
||||
// recycles it. This guarantees the buffer the render thread
|
||||
// has captured isn't overwritten mid-iteration: when pump
|
||||
// commits, the buffer the reader was holding becomes _spare
|
||||
// (untouched for this tick) before becoming _pending the
|
||||
// tick after that. Cheap insurance against any timing where
|
||||
// render takes longer than one pump interval.
|
||||
private static readonly NavBuffer _a = new();
|
||||
private static readonly NavBuffer _b = new();
|
||||
private static readonly NavBuffer _c = new();
|
||||
private static volatile NavBuffer _ready = _a;
|
||||
private static NavBuffer _pending = _b;
|
||||
private static NavBuffer _spare = _c;
|
||||
|
||||
// ── Render-side reads ────────────────────────────────────────────────────
|
||||
|
||||
public static int RingCount => _ready.RingCount;
|
||||
public static int LineCount => _ready.LineCount;
|
||||
public static int TriangleCount => _ready.TriCount;
|
||||
|
||||
public static void GetRing(int i, out float x, out float y, out float z,
|
||||
out float radius, out float thickness, out float height, out uint color)
|
||||
{
|
||||
var r = _ready;
|
||||
x = r.RingX[i]; y = r.RingY[i]; z = r.RingZ[i];
|
||||
radius = r.RingRadius[i]; thickness = r.RingThick[i];
|
||||
height = r.RingHeight[i]; color = r.RingColor[i];
|
||||
}
|
||||
|
||||
public static void GetLine(int i, out float x1, out float y1, out float z1,
|
||||
out float x2, out float y2, out float z2, out float thickness, out uint color)
|
||||
{
|
||||
var r = _ready;
|
||||
x1 = r.LineX1[i]; y1 = r.LineY1[i]; z1 = r.LineZ1[i];
|
||||
x2 = r.LineX2[i]; y2 = r.LineY2[i]; z2 = r.LineZ2[i];
|
||||
thickness = r.LineThick[i]; color = r.LineColor[i];
|
||||
}
|
||||
|
||||
public static void GetTriangle(int i, out float x1, out float y1, out float z1,
|
||||
out float x2, out float y2, out float z2,
|
||||
out float x3, out float y3, out float z3, out uint color)
|
||||
{
|
||||
var r = _ready;
|
||||
x1 = r.TriX1[i]; y1 = r.TriY1[i]; z1 = r.TriZ1[i];
|
||||
x2 = r.TriX2[i]; y2 = r.TriY2[i]; z2 = r.TriZ2[i];
|
||||
x3 = r.TriX3[i]; y3 = r.TriY3[i]; z3 = r.TriZ3[i];
|
||||
color = r.TriColor[i];
|
||||
}
|
||||
|
||||
// The landblock the plugin tick that produced the ready buffer was using.
|
||||
// Render thread uses this for view-matrix shifting so geometry stays
|
||||
// anchored to that tick's reference frame even if the player crosses a
|
||||
// landblock boundary between this tick and the next render frame.
|
||||
// Returns 0 when no pose was sampled; caller should fall back to
|
||||
// current player landblock in that case.
|
||||
public static uint ReadyPlayerLandblock => _ready.SubmissionPlayerLandblock;
|
||||
|
||||
// ── Pump-side writes ─────────────────────────────────────────────────────
|
||||
|
||||
public static void ClearFrame()
|
||||
{
|
||||
_pending.Reset();
|
||||
// Capture the player's current landblock so the render side knows
|
||||
// which frame the tick's submissions are anchored in.
|
||||
if (PlayerPhysicsHooks.TryGetPlayerPose(out uint cellId, out _, out _, out _,
|
||||
out _, out _, out _, out _))
|
||||
_pending.SubmissionPlayerLandblock = cellId >> 16;
|
||||
}
|
||||
|
||||
public static void AddRing(float wx, float wy, float wz, float radius, float thickness, uint colorArgb)
|
||||
=> AddRingEx(wx, wy, wz, radius, thickness, DefaultRingHeight, colorArgb);
|
||||
|
||||
public static void AddRingEx(float wx, float wy, float wz, float radius, float thickness, float height, uint colorArgb)
|
||||
{
|
||||
var p = _pending;
|
||||
if (p.RingCount >= MaxRings) return;
|
||||
int i = p.RingCount++;
|
||||
p.RingX[i] = wx; p.RingY[i] = wy; p.RingZ[i] = wz;
|
||||
p.RingRadius[i] = radius;
|
||||
p.RingThick[i] = thickness;
|
||||
p.RingHeight[i] = height;
|
||||
p.RingColor[i] = colorArgb;
|
||||
}
|
||||
|
||||
public static void AddLine(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb)
|
||||
{
|
||||
var p = _pending;
|
||||
if (p.LineCount >= MaxLines) return;
|
||||
int i = p.LineCount++;
|
||||
p.LineX1[i] = x1; p.LineY1[i] = y1; p.LineZ1[i] = z1;
|
||||
p.LineX2[i] = x2; p.LineY2[i] = y2; p.LineZ2[i] = z2;
|
||||
p.LineThick[i] = thickness;
|
||||
p.LineColor[i] = colorArgb;
|
||||
}
|
||||
|
||||
public static void AddTriangle(float x1, float y1, float z1,
|
||||
float x2, float y2, float z2,
|
||||
float x3, float y3, float z3, uint colorArgb)
|
||||
{
|
||||
var p = _pending;
|
||||
if (p.TriCount >= MaxTriangles) return;
|
||||
int i = p.TriCount++;
|
||||
p.TriX1[i] = x1; p.TriY1[i] = y1; p.TriZ1[i] = z1;
|
||||
p.TriX2[i] = x2; p.TriY2[i] = y2; p.TriZ2[i] = z2;
|
||||
p.TriX3[i] = x3; p.TriY3[i] = y3; p.TriZ3[i] = z3;
|
||||
p.TriColor[i] = colorArgb;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cycle: _pending → _ready → _spare → _pending. The newly-filled buffer
|
||||
/// becomes ready; the old ready becomes spare (idle this tick); the old
|
||||
/// spare becomes the next pending. Render reads of the new ready buffer
|
||||
/// become visible across cores via the volatile field. Called by
|
||||
/// PluginManager.TickAll AFTER all plugins have submitted.
|
||||
/// </summary>
|
||||
public static void CommitFrame()
|
||||
{
|
||||
NavBuffer newReady = _pending;
|
||||
NavBuffer newSpare = _ready;
|
||||
NavBuffer newPending = _spare;
|
||||
_spare = newSpare;
|
||||
_pending = newPending;
|
||||
Volatile.Write(ref _ready, newReady);
|
||||
}
|
||||
|
||||
// ── C ABI callbacks for plugin contract ──────────────────────────────────
|
||||
public static void Nav3DClearCallback() => ClearFrame();
|
||||
public static void Nav3DAddRingCallback(float wx, float wy, float wz, float radius, float thickness, uint color)
|
||||
=> AddRing(wx, wy, wz, radius, thickness, color);
|
||||
public static void Nav3DAddRingExCallback(float wx, float wy, float wz, float radius, float thickness, float height, uint color)
|
||||
=> AddRingEx(wx, wy, wz, radius, thickness, height, color);
|
||||
public static void Nav3DAddLineCallback(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint color)
|
||||
=> AddLine(x1, y1, z1, x2, y2, z2, thickness, color);
|
||||
public static void Nav3DAddTriangleCallback(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint color)
|
||||
=> AddTriangle(x1, y1, z1, x2, y2, z2, x3, y3, z3, color);
|
||||
}
|
||||
600
src/RynthCore.Engine/D3D9/OverlayTextureRenderer.cs
Normal file
600
src/RynthCore.Engine/D3D9/OverlayTextureRenderer.cs
Normal file
|
|
@ -0,0 +1,600 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - D3D9/OverlayTextureRenderer.cs
|
||||
// Consumes BGRA frames from OverlayFrameBuffer and composites them onto
|
||||
// the D3D9 back buffer as a fullscreen alpha-blended quad.
|
||||
//
|
||||
// Called at the end of OnEndScene, after ImGui has already rendered.
|
||||
// Uses D3DFVF_XYZRHW | D3DFVF_TEX1 (pre-transformed vertices) so no
|
||||
// projection matrix setup is needed.
|
||||
//
|
||||
// Pixel format: Avalonia Bgra8888 == D3DFMT_A8R8G8B8 in memory — no swizzle.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.UI;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static unsafe class OverlayTextureRenderer
|
||||
{
|
||||
private static readonly Guid IID_IDirect3DDevice9Ex = new("B18B10CE-2649-405A-870F-95F777D4313A");
|
||||
// ─── D3D9 constants ───────────────────────────────────────────────────
|
||||
private const uint D3DPT_TRIANGLESTRIP = 5;
|
||||
private const uint D3DUSAGE_RENDERTARGET = 0x00000001;
|
||||
private const uint D3DFMT_A8R8G8B8 = 21;
|
||||
private const uint D3DPOOL_DEFAULT = 0;
|
||||
private const uint D3DPOOL_MANAGED = 1;
|
||||
|
||||
private const uint D3DRS_ALPHABLENDENABLE = 27;
|
||||
private const uint D3DRS_SRCBLEND = 19;
|
||||
private const uint D3DRS_DESTBLEND = 20;
|
||||
private const uint D3DRS_ZENABLE = 7;
|
||||
private const uint D3DRS_ALPHATESTENABLE = 15;
|
||||
private const uint D3DRS_CULLMODE = 22;
|
||||
private const uint D3DRS_LIGHTING = 137;
|
||||
private const uint D3DRS_FOGENABLE = 28;
|
||||
private const uint D3DRS_STENCILENABLE = 52;
|
||||
private const uint D3DRS_COLORWRITEENABLE = 168;
|
||||
private const uint D3DRS_BLENDOP = 171;
|
||||
private const uint D3DRS_SCISSORTESTENABLE = 174;
|
||||
private const uint D3DRS_SRGBWRITEENABLE = 194;
|
||||
private const uint D3DRS_SEPARATEALPHABLENDENABLE = 206;
|
||||
private const uint D3DBLENDOP_ADD = 1;
|
||||
|
||||
private const uint D3DBLEND_ONE = 2;
|
||||
private const uint D3DBLEND_SRCALPHA = 5;
|
||||
private const uint D3DBLEND_INVSRCALPHA = 6;
|
||||
private const uint D3DCULL_NONE = 1;
|
||||
|
||||
private const uint D3DTSS_COLOROP = 1;
|
||||
private const uint D3DTSS_COLORARG1 = 2;
|
||||
private const uint D3DTSS_COLORARG2 = 3;
|
||||
private const uint D3DTSS_ALPHAOP = 4;
|
||||
private const uint D3DTSS_ALPHAARG1 = 5;
|
||||
private const uint D3DTSS_ALPHAARG2 = 6;
|
||||
|
||||
private const uint D3DTOP_SELECTARG1 = 2;
|
||||
private const uint D3DTOP_MODULATE = 4;
|
||||
private const uint D3DTA_TEXTURE = 2;
|
||||
private const uint D3DTA_DIFFUSE = 0;
|
||||
|
||||
private const uint D3DSAMP_MINFILTER = 5;
|
||||
private const uint D3DSAMP_MAGFILTER = 6;
|
||||
private const uint D3DTEXF_LINEAR = 2;
|
||||
private const uint D3DTEXF_POINT = 1;
|
||||
|
||||
// D3DFVF_XYZRHW | D3DFVF_TEX1
|
||||
private const uint FVF = 0x004 | 0x100;
|
||||
|
||||
// ─── Vertex (pre-transformed screen-space + UV) ────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct QuadVertex
|
||||
{
|
||||
public float X, Y, Z, RHW;
|
||||
public float U, V;
|
||||
}
|
||||
|
||||
// ─── D3D9 struct ──────────────────────────────────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct D3DVIEWPORT9
|
||||
{
|
||||
public uint X, Y, Width, Height;
|
||||
public float MinZ, MaxZ;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct D3DLOCKED_RECT
|
||||
{
|
||||
public int Pitch;
|
||||
public IntPtr pBits;
|
||||
}
|
||||
|
||||
// ─── Vtable delegates ─────────────────────────────────────────────────
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int CreateTextureD(IntPtr dev, uint w, uint h, uint levels, uint usage, uint fmt, uint pool, out IntPtr ppTex, IntPtr pShared);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureD(IntPtr dev, uint stage, IntPtr pTex);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureStageStateD(IntPtr dev, uint stage, uint type, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetTextureStageStateD(IntPtr dev, uint stage, uint type, out uint pValue);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetSamplerStateD(IntPtr dev, uint sampler, uint type, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetSamplerStateD(IntPtr dev, uint sampler, uint type, out uint pValue);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetTextureD(IntPtr dev, uint stage, out IntPtr ppTex);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetFVFD(IntPtr dev, uint fvf);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetFVFD(IntPtr dev, out uint pFvf);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetRenderStateD(IntPtr dev, uint state, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetRenderStateD(IntPtr dev, uint state, out uint pValue);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetVertexShaderD(IntPtr dev, IntPtr pShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetVertexShaderD(IntPtr dev, out IntPtr ppShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetPixelShaderD(IntPtr dev, IntPtr pShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetPixelShaderD(IntPtr dev, out IntPtr ppShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetViewportD(IntPtr dev, D3DVIEWPORT9* vp);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int DrawPrimitiveUPD(IntPtr dev, uint primType, uint primCount, IntPtr pVtxData, uint vtxStride);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate uint ReleaseD(IntPtr pObj);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int QueryInterfaceD(IntPtr pObj, Guid* riid, out IntPtr ppvObject);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int TexLockRectD(IntPtr pTex, uint level, D3DLOCKED_RECT* pLocked, IntPtr pRect, uint flags);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int TexUnlockRectD(IntPtr pTex, uint level);
|
||||
|
||||
// ─── Cached delegates ─────────────────────────────────────────────────
|
||||
private static CreateTextureD? _createTexture;
|
||||
private static SetTextureD? _setTexture;
|
||||
private static SetTextureStageStateD? _setTexStageState;
|
||||
private static GetTextureStageStateD? _getTexStageState;
|
||||
private static SetSamplerStateD? _setSamplerState;
|
||||
private static GetSamplerStateD? _getSamplerState;
|
||||
private static GetTextureD? _getTexture;
|
||||
private static SetFVFD? _setFVF;
|
||||
private static GetFVFD? _getFVF;
|
||||
private static SetRenderStateD? _setRenderState;
|
||||
private static GetRenderStateD? _getRenderState;
|
||||
private static SetVertexShaderD? _setVertexShader;
|
||||
private static GetVertexShaderD? _getVertexShader;
|
||||
private static SetPixelShaderD? _setPixelShader;
|
||||
private static GetPixelShaderD? _getPixelShader;
|
||||
private static GetViewportD? _getViewport;
|
||||
private static DrawPrimitiveUPD? _drawPrimitiveUP;
|
||||
private static QueryInterfaceD? _queryInterface;
|
||||
|
||||
// ─── State ────────────────────────────────────────────────────────────
|
||||
private static IntPtr _texture;
|
||||
private static IntPtr _sharedTextureHandle;
|
||||
private static int _texW;
|
||||
private static int _texH;
|
||||
private static bool _delegatesCached;
|
||||
private static bool _sharedInteropProbed;
|
||||
private static bool _sharedInteropSupported;
|
||||
|
||||
// ─── Public entry point ───────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Called from EndScene (D3D9 render thread) after ImGui has rendered.
|
||||
/// Uploads any pending Avalonia frame to the texture and draws it.
|
||||
/// </summary>
|
||||
public static void Render(IntPtr pDevice)
|
||||
{
|
||||
if (pDevice == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
if (!_delegatesCached)
|
||||
{
|
||||
CacheDelegates(pDevice);
|
||||
_delegatesCached = true;
|
||||
}
|
||||
|
||||
// Publish viewport size BEFORE consuming a frame so Avalonia has a non-zero
|
||||
// game-surface size on the very first tick. Without this, the producer waits
|
||||
// for size > 1 (set previously only inside DrawQuad), but DrawQuad doesn't
|
||||
// run until a frame is uploaded — chicken-and-egg when ImGui's Win32Backend
|
||||
// (which also publishes ClientPixelWidth/Height) is disabled.
|
||||
D3DVIEWPORT9 earlyVp;
|
||||
if (_getViewport!(pDevice, &earlyVp) >= 0)
|
||||
{
|
||||
int vw = (int)earlyVp.Width;
|
||||
int vh = (int)earlyVp.Height;
|
||||
if (vw > 1 && vh > 1)
|
||||
{
|
||||
bool changed = AvaloniaOverlay.ViewportWidth != vw || AvaloniaOverlay.ViewportHeight != vh;
|
||||
AvaloniaOverlay.ViewportWidth = vw;
|
||||
AvaloniaOverlay.ViewportHeight = vh;
|
||||
if (changed)
|
||||
AvaloniaOverlay.NotifyGameSurfaceMetricsChanged();
|
||||
}
|
||||
}
|
||||
|
||||
// Learn as early as possible whether this game device can consume shared
|
||||
// textures. That lets the producer stay on software submissions only on
|
||||
// unsupported clients instead of discovering it mid-session.
|
||||
if (OverlaySurfaceBridge.ActiveSupportsGpuInterop && !_sharedInteropProbed)
|
||||
EnsureSharedInteropSupport(pDevice);
|
||||
|
||||
// Upload new frame if one is available
|
||||
if (OverlaySurfaceBridge.TryConsume(out OverlaySurfaceFrame? frame) && frame != null)
|
||||
{
|
||||
switch (frame.Kind)
|
||||
{
|
||||
case OverlaySurfaceKind.SoftwareBgra32 when frame.SoftwarePixels != null:
|
||||
UploadFrame(pDevice, frame.SoftwarePixels, frame.Width, frame.Height);
|
||||
break;
|
||||
case OverlaySurfaceKind.AngleSharedTexture when frame.SharedTexture != null:
|
||||
if (!TryUseSharedTexture(pDevice, "ANGLE", frame.SharedTexture.Value))
|
||||
LogSharedTextureStub("ANGLE", frame.SharedTexture);
|
||||
break;
|
||||
case OverlaySurfaceKind.DxgiSharedTexture when frame.SharedTexture != null:
|
||||
if (!TryUseSharedTexture(pDevice, "DXGI", frame.SharedTexture.Value))
|
||||
LogSharedTextureStub("DXGI", frame.SharedTexture);
|
||||
break;
|
||||
case OverlaySurfaceKind.D3D9SharedTexture when frame.SharedTexture != null:
|
||||
if (!TryUseSharedTexture(pDevice, "D3D9Ex", frame.SharedTexture.Value))
|
||||
LogSharedTextureStub("D3D9Ex", frame.SharedTexture);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (_texture == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
DrawQuad(pDevice);
|
||||
}
|
||||
|
||||
private static void LogSharedTextureStub(string label, OverlaySharedTextureDescriptor? descriptor)
|
||||
{
|
||||
if (descriptor == null)
|
||||
{
|
||||
RynthLog.D3D9($"OverlayTextureRenderer: {label} shared texture frame arrived without a descriptor.");
|
||||
return;
|
||||
}
|
||||
|
||||
RynthLog.D3D9(
|
||||
$"OverlayTextureRenderer: {label} shared texture interop is not implemented yet " +
|
||||
$"(handle=0x{descriptor.Value.SharedHandle:X8}, size={descriptor.Value.Width}x{descriptor.Value.Height}, adapterLuid=0x{descriptor.Value.AdapterLuid:X}).");
|
||||
}
|
||||
|
||||
public static void Shutdown()
|
||||
{
|
||||
ReleaseTexture();
|
||||
_delegatesCached = false;
|
||||
_sharedInteropProbed = false;
|
||||
_sharedInteropSupported = false;
|
||||
}
|
||||
|
||||
// ─── Upload ───────────────────────────────────────────────────────────
|
||||
|
||||
private static void UploadFrame(IntPtr pDevice, byte[] pixels, int w, int h)
|
||||
{
|
||||
// Recreate texture if dimensions changed
|
||||
if (_texture == IntPtr.Zero || w != _texW || h != _texH || _sharedTextureHandle != IntPtr.Zero)
|
||||
{
|
||||
ReleaseTexture();
|
||||
|
||||
int hr = _createTexture!(pDevice, (uint)w, (uint)h, 1, 0,
|
||||
D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, out _texture, IntPtr.Zero);
|
||||
|
||||
if (hr < 0 || _texture == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9($"OverlayTextureRenderer: CreateTexture({w}x{h}) failed HRESULT=0x{hr:X8}");
|
||||
return;
|
||||
}
|
||||
|
||||
_texW = w;
|
||||
_texH = h;
|
||||
RynthLog.D3D9($"OverlayTextureRenderer: Created {w}x{h} overlay texture.");
|
||||
}
|
||||
|
||||
// Lock → copy → unlock
|
||||
// Use raw function pointers (no GC delegate alloc) — Marshal.GetDelegateForFunctionPointer
|
||||
// creates a small heap object per call, which at 60+ FPS hammers the LFH and was bisected
|
||||
// as the cause of a heap-corruption AV in ntdll (write fault at addr ending in FFC).
|
||||
IntPtr texVtbl = Marshal.ReadIntPtr(_texture);
|
||||
var lockRectFn = (delegate* unmanaged[Stdcall]<IntPtr, uint, D3DLOCKED_RECT*, IntPtr, uint, int>)
|
||||
Marshal.ReadIntPtr(texVtbl, TextureVTableIndex.LockRect * IntPtr.Size);
|
||||
var unlockRectFn = (delegate* unmanaged[Stdcall]<IntPtr, uint, int>)
|
||||
Marshal.ReadIntPtr(texVtbl, TextureVTableIndex.UnlockRect * IntPtr.Size);
|
||||
|
||||
D3DLOCKED_RECT locked;
|
||||
if (lockRectFn(_texture, 0, &locked, IntPtr.Zero, 0) < 0)
|
||||
return;
|
||||
|
||||
// Avalonia Bgra8888 == D3DFMT_A8R8G8B8 in memory — direct copy, no swizzle
|
||||
int srcStride = w * 4;
|
||||
fixed (byte* srcBase = pixels)
|
||||
{
|
||||
for (int row = 0; row < h; row++)
|
||||
{
|
||||
IntPtr dst = locked.pBits + row * locked.Pitch;
|
||||
Buffer.MemoryCopy(srcBase + row * srcStride, (void*)dst, srcStride, srcStride);
|
||||
}
|
||||
}
|
||||
|
||||
unlockRectFn(_texture, 0);
|
||||
}
|
||||
|
||||
private static bool TryUseSharedTexture(IntPtr pDevice, string label, OverlaySharedTextureDescriptor descriptor)
|
||||
{
|
||||
if (descriptor.SharedHandle == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
if (!EnsureSharedInteropSupport(pDevice))
|
||||
return false;
|
||||
|
||||
if (_texture != IntPtr.Zero &&
|
||||
_sharedTextureHandle == descriptor.SharedHandle &&
|
||||
_texW == descriptor.Width &&
|
||||
_texH == descriptor.Height)
|
||||
{
|
||||
OverlaySurfaceBridge.NotifySharedTextureOpened(descriptor.SharedHandle);
|
||||
return true;
|
||||
}
|
||||
|
||||
IntPtr openedTexture = IntPtr.Zero;
|
||||
IntPtr sharedHandle = descriptor.SharedHandle;
|
||||
uint usage = descriptor.Usage != 0 ? (uint)descriptor.Usage : D3DUSAGE_RENDERTARGET;
|
||||
uint format = descriptor.PixelFormat != 0 ? (uint)descriptor.PixelFormat : D3DFMT_A8R8G8B8;
|
||||
int hr = _createTexture!(
|
||||
pDevice,
|
||||
(uint)descriptor.Width,
|
||||
(uint)descriptor.Height,
|
||||
1,
|
||||
usage,
|
||||
format,
|
||||
D3DPOOL_DEFAULT,
|
||||
out openedTexture,
|
||||
new IntPtr(&sharedHandle));
|
||||
|
||||
if (hr < 0 || openedTexture == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9(
|
||||
$"OverlayTextureRenderer: Failed to open {label} shared texture handle 0x{descriptor.SharedHandle:X8}, HRESULT=0x{hr:X8}.");
|
||||
return false;
|
||||
}
|
||||
|
||||
ReleaseTexture();
|
||||
_texture = openedTexture;
|
||||
_sharedTextureHandle = descriptor.SharedHandle;
|
||||
_texW = descriptor.Width;
|
||||
_texH = descriptor.Height;
|
||||
OverlaySurfaceBridge.NotifySharedTextureOpened(descriptor.SharedHandle);
|
||||
RynthLog.D3D9(
|
||||
$"OverlayTextureRenderer: Opened {label} shared texture handle 0x{descriptor.SharedHandle:X8} ({descriptor.Width}x{descriptor.Height}).");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool EnsureSharedInteropSupport(IntPtr pDevice)
|
||||
{
|
||||
if (_sharedInteropProbed)
|
||||
return _sharedInteropSupported;
|
||||
|
||||
_sharedInteropProbed = true;
|
||||
|
||||
if (_queryInterface == null)
|
||||
{
|
||||
RynthLog.D3D9("OverlayTextureRenderer: Shared-texture probe unavailable because QueryInterface is not cached.");
|
||||
OverlaySurfaceBridge.NotifySharedTextureUnavailable();
|
||||
return false;
|
||||
}
|
||||
|
||||
IntPtr exDevice = IntPtr.Zero;
|
||||
Guid iid = IID_IDirect3DDevice9Ex;
|
||||
int hr = _queryInterface(pDevice, &iid, out exDevice);
|
||||
if (hr >= 0 && exDevice != IntPtr.Zero)
|
||||
{
|
||||
_sharedInteropSupported = true;
|
||||
RynthLog.D3D9("OverlayTextureRenderer: D3D9Ex shared-texture consumption is available on the active game device.");
|
||||
ReleaseComObject(exDevice);
|
||||
return true;
|
||||
}
|
||||
|
||||
RynthLog.D3D9("OverlayTextureRenderer: D3D9Ex shared-texture consumption is unavailable on the active game device; software fallback will remain active.");
|
||||
OverlaySurfaceBridge.NotifySharedTextureUnavailable();
|
||||
return false;
|
||||
}
|
||||
|
||||
// ─── Draw ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void DrawQuad(IntPtr pDevice)
|
||||
{
|
||||
// Get current viewport to size the quad
|
||||
D3DVIEWPORT9 vp;
|
||||
if (_getViewport!(pDevice, &vp) < 0)
|
||||
return;
|
||||
|
||||
float W = vp.Width;
|
||||
float H = vp.Height;
|
||||
|
||||
// Tell the Avalonia thread what the current viewport size is so it can
|
||||
// keep the canvas sized correctly (prevents stretch/scale artifacts).
|
||||
int viewportWidth = (int)W;
|
||||
int viewportHeight = (int)H;
|
||||
bool viewportChanged =
|
||||
AvaloniaOverlay.ViewportWidth != viewportWidth ||
|
||||
AvaloniaOverlay.ViewportHeight != viewportHeight;
|
||||
AvaloniaOverlay.ViewportWidth = viewportWidth;
|
||||
AvaloniaOverlay.ViewportHeight = viewportHeight;
|
||||
if (viewportChanged)
|
||||
AvaloniaOverlay.NotifyGameSurfaceMetricsChanged();
|
||||
|
||||
// Save render states we will change
|
||||
_getRenderState!(pDevice, D3DRS_ALPHABLENDENABLE, out uint savedAlpha);
|
||||
_getRenderState!(pDevice, D3DRS_SRCBLEND, out uint savedSrcBlend);
|
||||
_getRenderState!(pDevice, D3DRS_DESTBLEND, out uint savedDstBlend);
|
||||
_getRenderState!(pDevice, D3DRS_ZENABLE, out uint savedZ);
|
||||
_getRenderState!(pDevice, D3DRS_ALPHATESTENABLE, out uint savedAlphaTest);
|
||||
_getRenderState!(pDevice, D3DRS_CULLMODE, out uint savedCull);
|
||||
_getRenderState!(pDevice, D3DRS_LIGHTING, out uint savedLighting);
|
||||
_getRenderState!(pDevice, D3DRS_FOGENABLE, out uint savedFog);
|
||||
_getRenderState!(pDevice, D3DRS_STENCILENABLE, out uint savedStencil);
|
||||
_getRenderState!(pDevice, D3DRS_COLORWRITEENABLE, out uint savedColorWrite);
|
||||
_getRenderState!(pDevice, D3DRS_BLENDOP, out uint savedBlendOp);
|
||||
_getRenderState!(pDevice, D3DRS_SCISSORTESTENABLE, out uint savedScissor);
|
||||
_getRenderState!(pDevice, D3DRS_SRGBWRITEENABLE, out uint savedSrgb);
|
||||
_getRenderState!(pDevice, D3DRS_SEPARATEALPHABLENDENABLE, out uint savedSeparateAlpha);
|
||||
_getVertexShader!(pDevice, out IntPtr savedVS);
|
||||
_getPixelShader!(pDevice, out IntPtr savedPS);
|
||||
_getFVF!(pDevice, out uint savedFVF);
|
||||
_getTexture!(pDevice, 0, out IntPtr savedTex0);
|
||||
_getTexStageState!(pDevice, 0, D3DTSS_COLOROP, out uint savedTSS_ColorOp);
|
||||
_getTexStageState!(pDevice, 0, D3DTSS_COLORARG1, out uint savedTSS_ColorArg1);
|
||||
_getTexStageState!(pDevice, 0, D3DTSS_COLORARG2, out uint savedTSS_ColorArg2);
|
||||
_getTexStageState!(pDevice, 0, D3DTSS_ALPHAOP, out uint savedTSS_AlphaOp);
|
||||
_getTexStageState!(pDevice, 0, D3DTSS_ALPHAARG1, out uint savedTSS_AlphaArg1);
|
||||
_getTexStageState!(pDevice, 0, D3DTSS_ALPHAARG2, out uint savedTSS_AlphaArg2);
|
||||
_getSamplerState!(pDevice, 0, D3DSAMP_MINFILTER, out uint savedSamp_Min);
|
||||
_getSamplerState!(pDevice, 0, D3DSAMP_MAGFILTER, out uint savedSamp_Mag);
|
||||
|
||||
try
|
||||
{
|
||||
// Avalonia produces premultiplied BGRA, so the right blend is
|
||||
// ONE / INVSRCALPHA. SRCALPHA would square the alpha and dim the
|
||||
// overlay; ONE matches the premul invariant exactly.
|
||||
_setRenderState!(pDevice, D3DRS_ALPHABLENDENABLE, 1);
|
||||
_setRenderState!(pDevice, D3DRS_SRCBLEND, D3DBLEND_ONE);
|
||||
_setRenderState!(pDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
|
||||
_setRenderState!(pDevice, D3DRS_BLENDOP, D3DBLENDOP_ADD);
|
||||
_setRenderState!(pDevice, D3DRS_ZENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_ALPHATESTENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_CULLMODE, D3DCULL_NONE);
|
||||
_setRenderState!(pDevice, D3DRS_LIGHTING, 0);
|
||||
// AC enables fog (often white) for portal-space and dungeon
|
||||
// particle effects; without disabling it our quad gets
|
||||
// fog-blended toward white. Same for scissor (AC clips), stencil
|
||||
// (UI passes), and separate-alpha-blend (would override our blend).
|
||||
_setRenderState!(pDevice, D3DRS_FOGENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_STENCILENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_SCISSORTESTENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_SRGBWRITEENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_SEPARATEALPHABLENDENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_COLORWRITEENABLE, 0xF);
|
||||
|
||||
_setVertexShader!(pDevice, IntPtr.Zero);
|
||||
_setPixelShader!(pDevice, IntPtr.Zero);
|
||||
|
||||
_setFVF!(pDevice, FVF);
|
||||
_setTexture!(pDevice, 0, _texture);
|
||||
|
||||
// Use SELECTARG1 (texture only) instead of MODULATE so a stale
|
||||
// per-vertex DIFFUSE left over from ImGui's previous DrawPrimitiveUP
|
||||
// call can't tint the overlay — our FVF doesn't include DIFFUSE,
|
||||
// making its value undefined under MODULATE.
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
|
||||
// POINT filter is crisper than LINEAR when the texture and the
|
||||
// target backbuffer have the same dimensions — each output pixel
|
||||
// maps to exactly one texel, so we don't want any blending.
|
||||
_setSamplerState!(pDevice, 0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
|
||||
_setSamplerState!(pDevice, 0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
|
||||
|
||||
// D3D9 half-texel offset: pixel centers are at integer + 0.5, but
|
||||
// texel coords are at integer indexes. Without -0.5 vertex offset,
|
||||
// each output pixel samples *between* two texels, blending them
|
||||
// (visible blur even with POINT filter due to rasterization rules).
|
||||
QuadVertex* verts = stackalloc QuadVertex[4];
|
||||
verts[0] = new QuadVertex { X = -0.5f, Y = -0.5f, Z = 0, RHW = 1, U = 0, V = 0 };
|
||||
verts[1] = new QuadVertex { X = W - 0.5f, Y = -0.5f, Z = 0, RHW = 1, U = 1, V = 0 };
|
||||
verts[2] = new QuadVertex { X = -0.5f, Y = H - 0.5f, Z = 0, RHW = 1, U = 0, V = 1 };
|
||||
verts[3] = new QuadVertex { X = W - 0.5f, Y = H - 0.5f, Z = 0, RHW = 1, U = 1, V = 1 };
|
||||
|
||||
_drawPrimitiveUP!(pDevice, D3DPT_TRIANGLESTRIP, 2,
|
||||
new IntPtr(verts), (uint)sizeof(QuadVertex));
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Restore changed state. Anything we touched must be put back —
|
||||
// AC re-enters EndScene mid-frame for additional passes (post-fx,
|
||||
// particles, fog) and inherits whatever device state we left.
|
||||
_setRenderState!(pDevice, D3DRS_ALPHABLENDENABLE, savedAlpha);
|
||||
_setRenderState!(pDevice, D3DRS_SRCBLEND, savedSrcBlend);
|
||||
_setRenderState!(pDevice, D3DRS_DESTBLEND, savedDstBlend);
|
||||
_setRenderState!(pDevice, D3DRS_BLENDOP, savedBlendOp);
|
||||
_setRenderState!(pDevice, D3DRS_ZENABLE, savedZ);
|
||||
_setRenderState!(pDevice, D3DRS_ALPHATESTENABLE, savedAlphaTest);
|
||||
_setRenderState!(pDevice, D3DRS_CULLMODE, savedCull);
|
||||
_setRenderState!(pDevice, D3DRS_LIGHTING, savedLighting);
|
||||
_setRenderState!(pDevice, D3DRS_FOGENABLE, savedFog);
|
||||
_setRenderState!(pDevice, D3DRS_STENCILENABLE, savedStencil);
|
||||
_setRenderState!(pDevice, D3DRS_SCISSORTESTENABLE, savedScissor);
|
||||
_setRenderState!(pDevice, D3DRS_SRGBWRITEENABLE, savedSrgb);
|
||||
_setRenderState!(pDevice, D3DRS_SEPARATEALPHABLENDENABLE, savedSeparateAlpha);
|
||||
_setRenderState!(pDevice, D3DRS_COLORWRITEENABLE, savedColorWrite);
|
||||
_setVertexShader!(pDevice, savedVS);
|
||||
_setPixelShader!(pDevice, savedPS);
|
||||
_setFVF!(pDevice, savedFVF);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLOROP, savedTSS_ColorOp);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLORARG1, savedTSS_ColorArg1);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLORARG2, savedTSS_ColorArg2);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAOP, savedTSS_AlphaOp);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAARG1, savedTSS_AlphaArg1);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAARG2, savedTSS_AlphaArg2);
|
||||
_setSamplerState!(pDevice, 0, D3DSAMP_MINFILTER, savedSamp_Min);
|
||||
_setSamplerState!(pDevice, 0, D3DSAMP_MAGFILTER, savedSamp_Mag);
|
||||
_setTexture!(pDevice, 0, savedTex0);
|
||||
|
||||
if (savedVS != IntPtr.Zero) ReleaseComObject(savedVS);
|
||||
if (savedPS != IntPtr.Zero) ReleaseComObject(savedPS);
|
||||
if (savedTex0 != IntPtr.Zero) ReleaseComObject(savedTex0);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void ReleaseTexture()
|
||||
{
|
||||
if (_texture == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
IntPtr texVtbl = Marshal.ReadIntPtr(_texture);
|
||||
var release = (delegate* unmanaged[Stdcall]<IntPtr, uint>)
|
||||
Marshal.ReadIntPtr(texVtbl, TextureVTableIndex.Release * IntPtr.Size);
|
||||
release(_texture);
|
||||
_texture = IntPtr.Zero;
|
||||
_sharedTextureHandle = IntPtr.Zero;
|
||||
_texW = 0;
|
||||
_texH = 0;
|
||||
}
|
||||
|
||||
private static void ReleaseComObject(IntPtr pObj)
|
||||
{
|
||||
if (pObj == IntPtr.Zero) return;
|
||||
IntPtr vtbl = Marshal.ReadIntPtr(pObj);
|
||||
// Raw function pointer — avoids GC delegate alloc on every per-frame Release.
|
||||
var rel = (delegate* unmanaged[Stdcall]<IntPtr, uint>)
|
||||
Marshal.ReadIntPtr(vtbl, 2 * IntPtr.Size);
|
||||
rel(pObj);
|
||||
}
|
||||
|
||||
private static void CacheDelegates(IntPtr pDevice)
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
_createTexture = Get<CreateTextureD>(vtable, DeviceVTableIndex.CreateTexture);
|
||||
_setTexture = Get<SetTextureD>(vtable, DeviceVTableIndex.SetTexture);
|
||||
_getTexture = Get<GetTextureD>(vtable, DeviceVTableIndex.GetTexture);
|
||||
_setTexStageState = Get<SetTextureStageStateD>(vtable, DeviceVTableIndex.SetTextureStageState);
|
||||
_getTexStageState = Get<GetTextureStageStateD>(vtable, DeviceVTableIndex.GetTextureStageState);
|
||||
_setSamplerState = Get<SetSamplerStateD>(vtable, DeviceVTableIndex.SetSamplerState);
|
||||
_getSamplerState = Get<GetSamplerStateD>(vtable, DeviceVTableIndex.GetSamplerState);
|
||||
_setFVF = Get<SetFVFD>(vtable, DeviceVTableIndex.SetFVF);
|
||||
_getFVF = Get<GetFVFD>(vtable, DeviceVTableIndex.GetFVF);
|
||||
_setRenderState = Get<SetRenderStateD>(vtable, DeviceVTableIndex.SetRenderState);
|
||||
_getRenderState = Get<GetRenderStateD>(vtable, DeviceVTableIndex.GetRenderState);
|
||||
_setVertexShader = Get<SetVertexShaderD>(vtable, DeviceVTableIndex.SetVertexShader);
|
||||
_getVertexShader = Get<GetVertexShaderD>(vtable, DeviceVTableIndex.GetVertexShader);
|
||||
_setPixelShader = Get<SetPixelShaderD>(vtable, DeviceVTableIndex.SetPixelShader);
|
||||
_getPixelShader = Get<GetPixelShaderD>(vtable, DeviceVTableIndex.GetPixelShader);
|
||||
_getViewport = Get<GetViewportD>(vtable, DeviceVTableIndex.GetViewport);
|
||||
_drawPrimitiveUP = Get<DrawPrimitiveUPD>(vtable, DeviceVTableIndex.DrawPrimitiveUP);
|
||||
_queryInterface = Get<QueryInterfaceD>(vtable, 0);
|
||||
}
|
||||
|
||||
private static T Get<T>(IntPtr vtable, int index) where T : Delegate
|
||||
{
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
|
||||
private static T GetTexMethod<T>(IntPtr pTex, int index) where T : Delegate
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pTex);
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
}
|
||||
175
src/RynthCore.Engine/D3D9/TestRenderer.cs
Normal file
175
src/RynthCore.Engine/D3D9/TestRenderer.cs
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/TestRenderer.cs
|
||||
// Draws a small colored rectangle in the top-left corner of the game.
|
||||
// Pure D3D9 via vtable calls — no dependencies on any overlay framework.
|
||||
//
|
||||
// Uses pre-transformed vertices (D3DFVF_XYZRHW | D3DFVF_DIFFUSE) so no
|
||||
// world/view/projection matrices needed. The rectangle is screen-space.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static unsafe class TestRenderer
|
||||
{
|
||||
// ─── D3D9 constants ───────────────────────────────────────────────
|
||||
private const uint D3DFVF_XYZRHW = 0x0004;
|
||||
private const uint D3DFVF_DIFFUSE = 0x0040;
|
||||
private const uint D3DFVF_CUSTOM = D3DFVF_XYZRHW | D3DFVF_DIFFUSE;
|
||||
|
||||
private const uint D3DPT_TRIANGLESTRIP = 5;
|
||||
|
||||
// D3DRENDERSTATETYPE
|
||||
private const uint D3DRS_LIGHTING = 137;
|
||||
private const uint D3DRS_ALPHABLENDENABLE = 27;
|
||||
private const uint D3DRS_SRCBLEND = 19;
|
||||
private const uint D3DRS_DESTBLEND = 20;
|
||||
private const uint D3DRS_ZENABLE = 7;
|
||||
private const uint D3DRS_FOGENABLE = 28;
|
||||
|
||||
// D3DBLEND
|
||||
private const uint D3DBLEND_SRCALPHA = 5;
|
||||
private const uint D3DBLEND_INVSRCALPHA = 6;
|
||||
|
||||
// D3DTRANSFORMSTATETYPE
|
||||
private const uint D3DTS_WORLD = 256;
|
||||
private const uint D3DTS_VIEW = 2;
|
||||
private const uint D3DTS_PROJECTION = 3;
|
||||
|
||||
// ─── Vertex structure ─────────────────────────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct Vertex
|
||||
{
|
||||
public float X, Y, Z, RHW;
|
||||
public uint Color; // ARGB
|
||||
|
||||
public Vertex(float x, float y, uint color)
|
||||
{
|
||||
X = x; Y = y; Z = 0f; RHW = 1f;
|
||||
Color = color;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Device method delegates (COM/stdcall) ────────────────────────
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetRenderStateDelegate(IntPtr pDevice, uint state, uint value);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetRenderStateDelegate(IntPtr pDevice, uint state, out uint pValue);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureDelegate(IntPtr pDevice, uint stage, IntPtr pTexture);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetFVFDelegate(IntPtr pDevice, uint fvf);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int DrawPrimitiveUPDelegate(
|
||||
IntPtr pDevice, uint primitiveType, uint primitiveCount,
|
||||
IntPtr pVertexStreamZeroData, uint vertexStreamZeroStride);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetVertexShaderDelegate(IntPtr pDevice, IntPtr pShader);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetPixelShaderDelegate(IntPtr pDevice, IntPtr pShader);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureStageStateDelegate(IntPtr pDevice, uint stage, uint type, uint value);
|
||||
|
||||
// ─── Cached delegates (created once from vtable on first frame) ──
|
||||
private static SetRenderStateDelegate? _setRenderState;
|
||||
private static GetRenderStateDelegate? _getRenderState;
|
||||
private static SetTextureDelegate? _setTexture;
|
||||
private static SetFVFDelegate? _setFVF;
|
||||
private static DrawPrimitiveUPDelegate? _drawPrimitiveUP;
|
||||
private static SetVertexShaderDelegate? _setVertexShader;
|
||||
private static SetPixelShaderDelegate? _setPixelShader;
|
||||
private static SetTextureStageStateDelegate? _setTextureStageState;
|
||||
private static bool _delegatesCached;
|
||||
|
||||
// ─── Rectangle config ─────────────────────────────────────────────
|
||||
// Bright green semi-transparent rectangle, top-left corner
|
||||
private const float RectX = 10f;
|
||||
private const float RectY = 10f;
|
||||
private const float RectW = 120f;
|
||||
private const float RectH = 40f;
|
||||
private const uint RectColor = 0xCC00FF00; // ARGB: green, ~80% opaque
|
||||
|
||||
// ─── Public API ───────────────────────────────────────────────────
|
||||
|
||||
public static void Draw(IntPtr pDevice)
|
||||
{
|
||||
if (pDevice == IntPtr.Zero) return;
|
||||
|
||||
// Cache vtable delegates on first call
|
||||
if (!_delegatesCached)
|
||||
CacheDelegates(pDevice);
|
||||
|
||||
// Save render states we'll modify
|
||||
_getRenderState!(pDevice, D3DRS_LIGHTING, out uint oldLighting);
|
||||
_getRenderState(pDevice, D3DRS_ALPHABLENDENABLE, out uint oldAlphaBlend);
|
||||
_getRenderState(pDevice, D3DRS_SRCBLEND, out uint oldSrcBlend);
|
||||
_getRenderState(pDevice, D3DRS_DESTBLEND, out uint oldDestBlend);
|
||||
_getRenderState(pDevice, D3DRS_ZENABLE, out uint oldZEnable);
|
||||
_getRenderState(pDevice, D3DRS_FOGENABLE, out uint oldFogEnable);
|
||||
|
||||
// Set up for 2D overlay drawing
|
||||
_setRenderState!(pDevice, D3DRS_LIGHTING, 0); // no lighting
|
||||
_setRenderState(pDevice, D3DRS_ZENABLE, 0); // no depth test
|
||||
_setRenderState(pDevice, D3DRS_FOGENABLE, 0); // no fog
|
||||
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, 1); // alpha blend on
|
||||
_setRenderState(pDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
|
||||
_setRenderState(pDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
|
||||
|
||||
_setTexture!(pDevice, 0, IntPtr.Zero); // no texture
|
||||
_setVertexShader!(pDevice, IntPtr.Zero); // fixed function
|
||||
_setPixelShader!(pDevice, IntPtr.Zero); // fixed function
|
||||
_setFVF!(pDevice, D3DFVF_CUSTOM);
|
||||
|
||||
// Build quad (triangle strip: TL, TR, BL, BR)
|
||||
var verts = stackalloc Vertex[4];
|
||||
verts[0] = new Vertex(RectX, RectY, RectColor);
|
||||
verts[1] = new Vertex(RectX + RectW, RectY, RectColor);
|
||||
verts[2] = new Vertex(RectX, RectY + RectH, RectColor);
|
||||
verts[3] = new Vertex(RectX + RectW, RectY + RectH, RectColor);
|
||||
|
||||
_drawPrimitiveUP!(pDevice, D3DPT_TRIANGLESTRIP, 2, (IntPtr)verts, (uint)sizeof(Vertex));
|
||||
|
||||
// Restore saved render states
|
||||
_setRenderState(pDevice, D3DRS_LIGHTING, oldLighting);
|
||||
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, oldAlphaBlend);
|
||||
_setRenderState(pDevice, D3DRS_SRCBLEND, oldSrcBlend);
|
||||
_setRenderState(pDevice, D3DRS_DESTBLEND, oldDestBlend);
|
||||
_setRenderState(pDevice, D3DRS_ZENABLE, oldZEnable);
|
||||
_setRenderState(pDevice, D3DRS_FOGENABLE, oldFogEnable);
|
||||
}
|
||||
|
||||
// ─── Internals ────────────────────────────────────────────────────
|
||||
|
||||
private static void CacheDelegates(IntPtr pDevice)
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
|
||||
_setRenderState = GetMethod<SetRenderStateDelegate>(vtable, DeviceVTableIndex.SetRenderState);
|
||||
_getRenderState = GetMethod<GetRenderStateDelegate>(vtable, DeviceVTableIndex.GetRenderState);
|
||||
_setTexture = GetMethod<SetTextureDelegate>(vtable, DeviceVTableIndex.SetTexture);
|
||||
_setFVF = GetMethod<SetFVFDelegate>(vtable, DeviceVTableIndex.SetFVF);
|
||||
_drawPrimitiveUP = GetMethod<DrawPrimitiveUPDelegate>(vtable, DeviceVTableIndex.DrawPrimitiveUP);
|
||||
_setVertexShader = GetMethod<SetVertexShaderDelegate>(vtable, DeviceVTableIndex.SetVertexShader);
|
||||
_setPixelShader = GetMethod<SetPixelShaderDelegate>(vtable, DeviceVTableIndex.SetPixelShader);
|
||||
_setTextureStageState = GetMethod<SetTextureStageStateDelegate>(vtable, DeviceVTableIndex.SetTextureStageState);
|
||||
|
||||
_delegatesCached = true;
|
||||
RynthLog.D3D9("TestRenderer: D3D9 delegates cached.");
|
||||
}
|
||||
|
||||
private static T GetMethod<T>(IntPtr vtable, int index) where T : Delegate
|
||||
{
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
}
|
||||
706
src/RynthCore.Engine/D3D9/VitalHud.cs
Normal file
706
src/RynthCore.Engine/D3D9/VitalHud.cs
Normal file
|
|
@ -0,0 +1,706 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/VitalHud.cs
|
||||
//
|
||||
// "Hot HUD" — draws player Health / Stamina / Mana bars directly in the D3D9
|
||||
// EndScene path, on AC's render thread, every frame. Ported from RynthCore2's
|
||||
// overlay/hud_overlay.cpp; the D3D9 plumbing mirrors TestRenderer.cs (cached
|
||||
// vtable delegates + full render-state save/restore).
|
||||
//
|
||||
// Visuals: a translucent panel with a drop shadow, three gradient-filled bars
|
||||
// (track + fill + gloss + border) with an HP/STAM/MANA label and a right-
|
||||
// aligned "cur/max" number drawn from the dependency-free BitmapFont.
|
||||
// Everything is colored 2D quads (D3DFVF_XYZRHW | D3DFVF_DIFFUSE, no texture)
|
||||
// accumulated into one static vertex batch flushed with a single
|
||||
// DrawPrimitiveUP — no per-frame heap allocation (avoids the LFH per-frame-
|
||||
// alloc AV class).
|
||||
//
|
||||
// Interactive: drag the panel to move it, drag the bottom-right grip to resize.
|
||||
// Win32Backend routes mouse messages to TryHandleMouse, which consumes the ones
|
||||
// that land on the HUD so they never reach AC (no stray camera spin). Position +
|
||||
// scale persist to %APPDATA%\RynthCore\vitalhud.cfg.
|
||||
//
|
||||
// Data source: Compatibility.PlayerVitalsHooks.TryGetSnapshot — the same
|
||||
// buffed-effective values AC's own bars render, maintained on AC's main thread.
|
||||
// Draw and TryHandleMouse both run on that thread (EndScene / WndProc), so the
|
||||
// shared geometry state needs no cross-thread synchronization.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static unsafe class VitalHud
|
||||
{
|
||||
// ─── D3D9 constants ───────────────────────────────────────────────
|
||||
private const uint D3DFVF_XYZRHW = 0x0004;
|
||||
private const uint D3DFVF_DIFFUSE = 0x0040;
|
||||
private const uint HudFvf = D3DFVF_XYZRHW | D3DFVF_DIFFUSE;
|
||||
|
||||
private const uint D3DPT_TRIANGLELIST = 4;
|
||||
|
||||
// D3DRENDERSTATETYPE
|
||||
private const uint D3DRS_ZENABLE = 7;
|
||||
private const uint D3DRS_ZWRITEENABLE = 14;
|
||||
private const uint D3DRS_ALPHATESTENABLE = 15;
|
||||
private const uint D3DRS_SRCBLEND = 19;
|
||||
private const uint D3DRS_DESTBLEND = 20;
|
||||
private const uint D3DRS_CULLMODE = 22;
|
||||
private const uint D3DRS_ALPHABLENDENABLE = 27;
|
||||
private const uint D3DRS_FOGENABLE = 28;
|
||||
private const uint D3DRS_STENCILENABLE = 52;
|
||||
private const uint D3DRS_LIGHTING = 137;
|
||||
private const uint D3DRS_COLORWRITEENABLE = 168;
|
||||
private const uint D3DRS_BLENDOP = 171;
|
||||
private const uint D3DRS_SCISSORTESTENABLE = 174;
|
||||
|
||||
// D3DTEXTURESTAGESTATETYPE
|
||||
private const uint D3DTSS_COLOROP = 1;
|
||||
private const uint D3DTSS_COLORARG1 = 2;
|
||||
private const uint D3DTSS_ALPHAOP = 4;
|
||||
private const uint D3DTSS_ALPHAARG1 = 6;
|
||||
|
||||
// values
|
||||
private const uint D3DBLEND_SRCALPHA = 5;
|
||||
private const uint D3DBLEND_INVSRCALPHA = 6;
|
||||
private const uint D3DBLENDOP_ADD = 1;
|
||||
private const uint D3DCULL_NONE = 1;
|
||||
private const uint D3DTOP_DISABLE = 1;
|
||||
private const uint D3DTOP_SELECTARG1 = 2;
|
||||
private const uint D3DTA_DIFFUSE = 0;
|
||||
|
||||
// ─── Win32 messages + capture P/Invoke ────────────────────────────
|
||||
private const uint WM_LBUTTONDOWN = 0x0201;
|
||||
private const uint WM_LBUTTONUP = 0x0202;
|
||||
private const uint WM_MOUSEMOVE = 0x0200;
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr SetCapture(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool ReleaseCapture();
|
||||
|
||||
// ─── Vertex ───────────────────────────────────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct Vertex
|
||||
{
|
||||
public float X, Y, Z, Rhw;
|
||||
public uint Color; // ARGB
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct D3DVIEWPORT9
|
||||
{
|
||||
public uint X, Y, Width, Height;
|
||||
public float MinZ, MaxZ;
|
||||
}
|
||||
|
||||
// ─── Device method delegates (COM/stdcall) ────────────────────────
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetRenderStateDelegate(IntPtr dev, uint state, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetRenderStateDelegate(IntPtr dev, uint state, out uint pValue);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureStageStateDelegate(IntPtr dev, uint stage, uint type, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetTextureStageStateDelegate(IntPtr dev, uint stage, uint type, out uint pValue);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureDelegate(IntPtr dev, uint stage, IntPtr pTexture);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetTextureDelegate(IntPtr dev, uint stage, out IntPtr ppTexture);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetFVFDelegate(IntPtr dev, uint fvf);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetFVFDelegate(IntPtr dev, out uint fvf);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetVertexShaderDelegate(IntPtr dev, IntPtr pShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetVertexShaderDelegate(IntPtr dev, out IntPtr ppShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetPixelShaderDelegate(IntPtr dev, IntPtr pShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetPixelShaderDelegate(IntPtr dev, out IntPtr ppShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int DrawPrimitiveUPDelegate(IntPtr dev, uint primitiveType, uint primitiveCount, IntPtr pData, uint stride);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetViewportDelegate(IntPtr dev, out D3DVIEWPORT9 vp);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate uint ReleaseComDelegate(IntPtr pUnk);
|
||||
|
||||
private static SetRenderStateDelegate? _setRenderState;
|
||||
private static GetRenderStateDelegate? _getRenderState;
|
||||
private static SetTextureStageStateDelegate? _setTextureStageState;
|
||||
private static GetTextureStageStateDelegate? _getTextureStageState;
|
||||
private static SetTextureDelegate? _setTexture;
|
||||
private static GetTextureDelegate? _getTexture;
|
||||
private static SetFVFDelegate? _setFVF;
|
||||
private static GetFVFDelegate? _getFVF;
|
||||
private static SetVertexShaderDelegate? _setVertexShader;
|
||||
private static GetVertexShaderDelegate? _getVertexShader;
|
||||
private static SetPixelShaderDelegate? _setPixelShader;
|
||||
private static GetPixelShaderDelegate? _getPixelShader;
|
||||
private static DrawPrimitiveUPDelegate? _drawPrimitiveUP;
|
||||
private static GetViewportDelegate? _getViewport;
|
||||
private static bool _delegatesCached;
|
||||
|
||||
// ─── Geometry / interaction state (AC main thread only) ───────────
|
||||
private const float MinScale = 0.6f;
|
||||
private const float MaxScale = 2.5f;
|
||||
|
||||
private static float _hudX = 16f, _hudY = 16f, _scale = 1f;
|
||||
private static float _vpW, _vpH; // last viewport, for input clamp
|
||||
private static bool _geomInit;
|
||||
private static bool _firstDrawLogged;
|
||||
|
||||
private static int _dragMode; // 0 none, 1 move, 2 resize
|
||||
private static float _grabDX, _grabDY;
|
||||
private static float _resizeStartScale = 1f, _resizeStartDist = 1f;
|
||||
|
||||
/// <summary>True while the user is dragging or resizing the HUD. Win32Backend
|
||||
/// keeps routing mouse messages to <see cref="TryHandleMouse"/> while set.</summary>
|
||||
public static bool IsDragging => _dragMode != 0;
|
||||
|
||||
// ─── Vertex batch (single static buffer; no per-frame heap alloc) ──
|
||||
// Text is the big consumer — the outline pass below draws each number 9×.
|
||||
private const int MaxVerts = 48000;
|
||||
private static readonly Vertex[] _batch = new Vertex[MaxVerts];
|
||||
private static int _batchCount;
|
||||
|
||||
// Cached text sink + color so BitmapFont.Emit allocates nothing per call.
|
||||
private static readonly BitmapFont.CellSink _cellSink = TextCell;
|
||||
private static uint _textColor;
|
||||
|
||||
// ─── Layout derived from the uniform scale ────────────────────────
|
||||
private struct Metrics
|
||||
{
|
||||
public float Scale, Pad, BarW, BarH, Gap, PanelW, PanelH, Grip;
|
||||
}
|
||||
|
||||
private static Metrics Metric(float s)
|
||||
{
|
||||
if (s < MinScale) s = MinScale;
|
||||
if (s > MaxScale) s = MaxScale;
|
||||
Metrics m;
|
||||
m.Scale = s;
|
||||
m.Pad = 8f * s;
|
||||
m.BarW = 228f * s; // wide enough for a big "cur/max" number
|
||||
m.BarH = 26f * s; // taller bars → bigger, retail-legible numbers
|
||||
m.Gap = 6f * s;
|
||||
m.PanelW = m.Pad * 2f + m.BarW;
|
||||
m.PanelH = m.Pad * 2f + m.BarH * 3f + m.Gap * 2f;
|
||||
m.Grip = 16f * s;
|
||||
return m;
|
||||
}
|
||||
|
||||
// ─── Color helpers ────────────────────────────────────────────────
|
||||
private static uint Argb(int a, int r, int g, int b)
|
||||
=> ((uint)a << 24) | ((uint)r << 16) | ((uint)g << 8) | (uint)b;
|
||||
|
||||
private static uint Lighten(uint c, int add)
|
||||
{
|
||||
static int Cl(int v) => v < 0 ? 0 : (v > 255 ? 255 : v);
|
||||
int a = (int)((c >> 24) & 0xFF);
|
||||
int r = (int)((c >> 16) & 0xFF);
|
||||
int g = (int)((c >> 8) & 0xFF);
|
||||
int b = (int)(c & 0xFF);
|
||||
return Argb(a, Cl(r + add), Cl(g + add), Cl(b + add));
|
||||
}
|
||||
|
||||
// ─── Batch builders ───────────────────────────────────────────────
|
||||
private static void BatchReset() => _batchCount = 0;
|
||||
|
||||
private static void PushQuad(float x0, float y0, float x1, float y1,
|
||||
uint cTL, uint cTR, uint cBR, uint cBL)
|
||||
{
|
||||
if (_batchCount + 6 > MaxVerts) return;
|
||||
Set(ref _batch[_batchCount + 0], x0, y0, cTL);
|
||||
Set(ref _batch[_batchCount + 1], x1, y0, cTR);
|
||||
Set(ref _batch[_batchCount + 2], x1, y1, cBR);
|
||||
Set(ref _batch[_batchCount + 3], x0, y0, cTL);
|
||||
Set(ref _batch[_batchCount + 4], x1, y1, cBR);
|
||||
Set(ref _batch[_batchCount + 5], x0, y1, cBL);
|
||||
_batchCount += 6;
|
||||
|
||||
static void Set(ref Vertex v, float x, float y, uint c)
|
||||
{
|
||||
v.X = x; v.Y = y; v.Z = 0f; v.Rhw = 1f; v.Color = c;
|
||||
}
|
||||
}
|
||||
|
||||
private static void PushRect(float x0, float y0, float x1, float y1, uint c)
|
||||
=> PushQuad(x0, y0, x1, y1, c, c, c, c);
|
||||
|
||||
private static void PushVGrad(float x0, float y0, float x1, float y1, uint top, uint bot)
|
||||
=> PushQuad(x0, y0, x1, y1, top, top, bot, bot);
|
||||
|
||||
// ─── Text → batched quads via the bitmap font ─────────────────────
|
||||
private static void TextCell(int x0, int y0, int x1, int y1)
|
||||
=> PushRect(x0, y0, x1, y1, _textColor);
|
||||
|
||||
// Draws text with a full dark outline (all 8 neighbour offsets) then the
|
||||
// foreground on top, so it stays legible over any bar fill color — the
|
||||
// single drop-shadow was washed out on the light (yellow) bar.
|
||||
private static void DrawText(ReadOnlySpan<char> s, int x, int y, int cellPx, uint color)
|
||||
{
|
||||
int o = cellPx >= 4 ? 2 : 1; // outline thickness in px
|
||||
_textColor = Argb(235, 0, 0, 0);
|
||||
BitmapFont.Emit(s, x - o, y - o, cellPx, _cellSink);
|
||||
BitmapFont.Emit(s, x, y - o, cellPx, _cellSink);
|
||||
BitmapFont.Emit(s, x + o, y - o, cellPx, _cellSink);
|
||||
BitmapFont.Emit(s, x - o, y, cellPx, _cellSink);
|
||||
BitmapFont.Emit(s, x + o, y, cellPx, _cellSink);
|
||||
BitmapFont.Emit(s, x - o, y + o, cellPx, _cellSink);
|
||||
BitmapFont.Emit(s, x, y + o, cellPx, _cellSink);
|
||||
BitmapFont.Emit(s, x + o, y + o, cellPx, _cellSink);
|
||||
_textColor = color;
|
||||
BitmapFont.Emit(s, x, y, cellPx, _cellSink);
|
||||
}
|
||||
|
||||
// "cur/max" formatted into the caller's buffer without allocating; returns
|
||||
// the number of chars written (≤ buf.Length).
|
||||
private static int FormatVital(uint cur, uint mx, Span<char> buf)
|
||||
{
|
||||
int len = 0;
|
||||
if (cur.TryFormat(buf, out int w1)) len += w1;
|
||||
if (len < buf.Length) buf[len++] = '/';
|
||||
if (mx.TryFormat(buf.Slice(len), out int w2)) len += w2;
|
||||
return len;
|
||||
}
|
||||
|
||||
private static void EmitBar(float x, float y, in Metrics m,
|
||||
uint cur, uint mx, uint baseColor)
|
||||
{
|
||||
float w = m.BarW, h = m.BarH;
|
||||
|
||||
PushRect(x, y, x + w, y + h, Argb(205, 18, 20, 26)); // track
|
||||
|
||||
if (mx > 0)
|
||||
{
|
||||
float ratio = (float)cur / mx;
|
||||
if (ratio < 0f) ratio = 0f;
|
||||
if (ratio > 1f) ratio = 1f;
|
||||
float fw = w * ratio;
|
||||
PushVGrad(x, y, x + fw, y + h, Lighten(baseColor, 55), baseColor); // fill
|
||||
PushRect(x, y, x + fw, y + h * 0.32f, Argb(60, 255, 255, 255)); // gloss
|
||||
}
|
||||
|
||||
float bw = m.Scale >= 1.5f ? 2f : 1f; // border
|
||||
uint bc = Argb(180, 90, 100, 120);
|
||||
PushRect(x, y, x + w, y + bw, bc);
|
||||
PushRect(x, y + h - bw, x + w, y + h, bc);
|
||||
PushRect(x, y, x + bw, y + h, bc);
|
||||
PushRect(x + w - bw, y, x + w, y + h, bc);
|
||||
|
||||
// Number only (no label — the red/yellow/blue color identifies the bar).
|
||||
// Sized as large as fits the bar, centered, with a dark outline so it
|
||||
// reads clearly over any fill color (especially white-on-yellow).
|
||||
Span<char> numBuf = stackalloc char[24];
|
||||
ReadOnlySpan<char> num = numBuf[..FormatVital(cur, mx, numBuf)];
|
||||
|
||||
int innerPad = (int)(m.Pad * 0.4f);
|
||||
if (innerPad < 2) innerPad = 2;
|
||||
int availW = (int)w - 2 * innerPad;
|
||||
|
||||
int cellPx = (int)(h * 0.82f / BitmapFont.GlyphH); // tallest that fits the bar
|
||||
if (cellPx < 1) cellPx = 1;
|
||||
while (cellPx > 1 && BitmapFont.MeasureWidth(num, cellPx) > availW) cellPx--;
|
||||
|
||||
int tw = BitmapFont.MeasureWidth(num, cellPx);
|
||||
int th = BitmapFont.Height(cellPx);
|
||||
int tx = (int)(x + (w - tw) * 0.5f); // center horizontally
|
||||
int ty = (int)(y + (h - th) * 0.5f); // center vertically
|
||||
DrawText(num, tx, ty, cellPx, Argb(255, 245, 250, 255));
|
||||
}
|
||||
|
||||
// ─── Public API ───────────────────────────────────────────────────
|
||||
public static void Draw(IntPtr pDevice)
|
||||
{
|
||||
if (pDevice == IntPtr.Zero) return;
|
||||
if (!PlayerVitalsHooks.TryGetSnapshot(out PlayerVitalsSnapshot snap)) return;
|
||||
|
||||
if (!_delegatesCached)
|
||||
CacheDelegates(pDevice);
|
||||
if (_drawPrimitiveUP == null) return; // delegate cache failed
|
||||
|
||||
if (_getViewport!(pDevice, out D3DVIEWPORT9 vp) < 0) return;
|
||||
float wF = vp.Width;
|
||||
float hF = vp.Height;
|
||||
if (wF < 1f || hF < 1f) return;
|
||||
|
||||
if (!_firstDrawLogged)
|
||||
{
|
||||
_firstDrawLogged = true;
|
||||
RynthLog.D3D9("VitalHud: first draw.");
|
||||
}
|
||||
|
||||
// First-draw placement: prefer the saved config, else default top-right.
|
||||
if (!_geomInit)
|
||||
{
|
||||
_geomInit = true;
|
||||
if (LoadCfg(out float lx, out float ly, out float ls))
|
||||
{
|
||||
_scale = ls; _hudX = lx; _hudY = ly;
|
||||
}
|
||||
else
|
||||
{
|
||||
_scale = 1f;
|
||||
Metrics dm = Metric(1f);
|
||||
_hudX = wF - dm.PanelW - 16f;
|
||||
_hudY = 16f;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Save the device state we are about to clobber ──────────────
|
||||
_getRenderState!(pDevice, D3DRS_ZENABLE, out uint svZE);
|
||||
_getRenderState(pDevice, D3DRS_ZWRITEENABLE, out uint svZWE);
|
||||
_getRenderState(pDevice, D3DRS_ALPHATESTENABLE, out uint svATE);
|
||||
_getRenderState(pDevice, D3DRS_ALPHABLENDENABLE, out uint svABE);
|
||||
_getRenderState(pDevice, D3DRS_SRCBLEND, out uint svSB);
|
||||
_getRenderState(pDevice, D3DRS_DESTBLEND, out uint svDB);
|
||||
_getRenderState(pDevice, D3DRS_BLENDOP, out uint svBO);
|
||||
_getRenderState(pDevice, D3DRS_CULLMODE, out uint svCull);
|
||||
_getRenderState(pDevice, D3DRS_LIGHTING, out uint svLit);
|
||||
_getRenderState(pDevice, D3DRS_FOGENABLE, out uint svFog);
|
||||
_getRenderState(pDevice, D3DRS_STENCILENABLE, out uint svSte);
|
||||
_getRenderState(pDevice, D3DRS_SCISSORTESTENABLE, out uint svSci);
|
||||
_getRenderState(pDevice, D3DRS_COLORWRITEENABLE, out uint svCW);
|
||||
_getFVF!(pDevice, out uint svFvf);
|
||||
|
||||
_getTextureStageState!(pDevice, 0, D3DTSS_COLOROP, out uint svT0CO);
|
||||
_getTextureStageState(pDevice, 0, D3DTSS_COLORARG1, out uint svT0CA1);
|
||||
_getTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, out uint svT0AO);
|
||||
_getTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, out uint svT0AA1);
|
||||
_getTextureStageState(pDevice, 1, D3DTSS_COLOROP, out uint svT1CO);
|
||||
|
||||
_getVertexShader!(pDevice, out IntPtr svVS);
|
||||
_getPixelShader!(pDevice, out IntPtr svPS);
|
||||
_getTexture!(pDevice, 0, out IntPtr svTex0);
|
||||
|
||||
try
|
||||
{
|
||||
// ── Set HUD state: 2D, alpha-blended, colored verts, no tex/shaders ──
|
||||
_setRenderState!(pDevice, D3DRS_ZENABLE, 0);
|
||||
_setRenderState(pDevice, D3DRS_ZWRITEENABLE, 0);
|
||||
_setRenderState(pDevice, D3DRS_ALPHATESTENABLE, 0);
|
||||
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, 1);
|
||||
_setRenderState(pDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
|
||||
_setRenderState(pDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
|
||||
_setRenderState(pDevice, D3DRS_BLENDOP, D3DBLENDOP_ADD);
|
||||
_setRenderState(pDevice, D3DRS_CULLMODE, D3DCULL_NONE);
|
||||
_setRenderState(pDevice, D3DRS_LIGHTING, 0);
|
||||
_setRenderState(pDevice, D3DRS_FOGENABLE, 0);
|
||||
_setRenderState(pDevice, D3DRS_STENCILENABLE, 0);
|
||||
_setRenderState(pDevice, D3DRS_SCISSORTESTENABLE, 0);
|
||||
_setRenderState(pDevice, D3DRS_COLORWRITEENABLE, 0xF);
|
||||
|
||||
_setTextureStageState!(pDevice, 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
|
||||
_setTextureStageState(pDevice, 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE);
|
||||
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
|
||||
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);
|
||||
_setTextureStageState(pDevice, 1, D3DTSS_COLOROP, D3DTOP_DISABLE);
|
||||
|
||||
_setTexture!(pDevice, 0, IntPtr.Zero);
|
||||
_setVertexShader!(pDevice, IntPtr.Zero);
|
||||
_setPixelShader!(pDevice, IntPtr.Zero);
|
||||
_setFVF!(pDevice, HudFvf);
|
||||
|
||||
BuildBatch(in snap, wF, hF);
|
||||
|
||||
if (_batchCount >= 3)
|
||||
{
|
||||
fixed (Vertex* p = _batch)
|
||||
{
|
||||
_drawPrimitiveUP(pDevice, D3DPT_TRIANGLELIST,
|
||||
(uint)(_batchCount / 3), (IntPtr)p, (uint)sizeof(Vertex));
|
||||
}
|
||||
}
|
||||
|
||||
_vpW = wF; // for input hit-test clamping
|
||||
_vpH = hF;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// ── Restore the saved state ────────────────────────────────
|
||||
_setRenderState!(pDevice, D3DRS_ZENABLE, svZE);
|
||||
_setRenderState(pDevice, D3DRS_ZWRITEENABLE, svZWE);
|
||||
_setRenderState(pDevice, D3DRS_ALPHATESTENABLE, svATE);
|
||||
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, svABE);
|
||||
_setRenderState(pDevice, D3DRS_SRCBLEND, svSB);
|
||||
_setRenderState(pDevice, D3DRS_DESTBLEND, svDB);
|
||||
_setRenderState(pDevice, D3DRS_BLENDOP, svBO);
|
||||
_setRenderState(pDevice, D3DRS_CULLMODE, svCull);
|
||||
_setRenderState(pDevice, D3DRS_LIGHTING, svLit);
|
||||
_setRenderState(pDevice, D3DRS_FOGENABLE, svFog);
|
||||
_setRenderState(pDevice, D3DRS_STENCILENABLE, svSte);
|
||||
_setRenderState(pDevice, D3DRS_SCISSORTESTENABLE, svSci);
|
||||
_setRenderState(pDevice, D3DRS_COLORWRITEENABLE, svCW);
|
||||
|
||||
_setTextureStageState!(pDevice, 0, D3DTSS_COLOROP, svT0CO);
|
||||
_setTextureStageState(pDevice, 0, D3DTSS_COLORARG1, svT0CA1);
|
||||
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, svT0AO);
|
||||
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, svT0AA1);
|
||||
_setTextureStageState(pDevice, 1, D3DTSS_COLOROP, svT1CO);
|
||||
|
||||
_setFVF!(pDevice, svFvf);
|
||||
_setVertexShader!(pDevice, svVS);
|
||||
_setPixelShader!(pDevice, svPS);
|
||||
_setTexture!(pDevice, 0, svTex0);
|
||||
|
||||
// GetVertexShader / GetPixelShader / GetTexture each AddRef — release.
|
||||
ReleaseCom(svVS);
|
||||
ReleaseCom(svPS);
|
||||
ReleaseCom(svTex0);
|
||||
}
|
||||
}
|
||||
|
||||
private static void BuildBatch(in PlayerVitalsSnapshot snap, float wF, float hF)
|
||||
{
|
||||
Metrics m = Metric(_scale);
|
||||
float px = _hudX;
|
||||
float py = _hudY;
|
||||
if (px > wF - m.PanelW) px = wF - m.PanelW; // keep on-screen (draw-only)
|
||||
if (py > hF - m.PanelH) py = hF - m.PanelH;
|
||||
if (px < 0f) px = 0f;
|
||||
if (py < 0f) py = 0f;
|
||||
|
||||
BatchReset();
|
||||
|
||||
float so = 5f * m.Scale; // shadow
|
||||
PushRect(px + so, py + so, px + m.PanelW + so, py + m.PanelH + so, Argb(110, 0, 0, 0));
|
||||
PushVGrad(px, py, px + m.PanelW, py + m.PanelH, // backing
|
||||
Argb(205, 28, 30, 38), Argb(205, 16, 17, 22));
|
||||
PushRect(px, py, px + m.PanelW, py + m.Pad * 0.6f, Argb(45, 255, 255, 255)); // header hint
|
||||
|
||||
float pbw = m.Scale >= 1.5f ? 2f : 1f; // panel border
|
||||
uint pbc = Argb(200, 120, 130, 150);
|
||||
PushRect(px, py, px + m.PanelW, py + pbw, pbc);
|
||||
PushRect(px, py + m.PanelH - pbw, px + m.PanelW, py + m.PanelH, pbc);
|
||||
PushRect(px, py, px + pbw, py + m.PanelH, pbc);
|
||||
PushRect(px + m.PanelW - pbw, py, px + m.PanelW, py + m.PanelH, pbc);
|
||||
|
||||
float bx = px + m.Pad;
|
||||
float by = py + m.Pad;
|
||||
EmitBar(bx, by, in m, snap.Health, snap.MaxHealth, Argb(235, 200, 45, 45));
|
||||
by += m.BarH + m.Gap;
|
||||
EmitBar(bx, by, in m, snap.Stamina, snap.MaxStamina, Argb(235, 205, 170, 45));
|
||||
by += m.BarH + m.Gap;
|
||||
EmitBar(bx, by, in m, snap.Mana, snap.MaxMana, Argb(235, 55, 115, 235));
|
||||
|
||||
// resize grip (three dots) bottom-right
|
||||
float d = 3f * m.Scale;
|
||||
if (d < 2f) d = 2f;
|
||||
float gx = px + m.PanelW - m.Pad * 0.5f;
|
||||
float gy = py + m.PanelH - m.Pad * 0.5f;
|
||||
uint gc = Argb(200, 200, 205, 215);
|
||||
for (int i = 1; i <= 3; i++)
|
||||
{
|
||||
float ox = gx - i * (d + 1f);
|
||||
float oy = gy - i * (d + 1f);
|
||||
PushRect(ox, oy, ox + d, oy + d, gc);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Input ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Handles left-button drag (anywhere on the panel) + grip resize. Returns
|
||||
/// true when the message landed on the HUD and should be swallowed so it
|
||||
/// never reaches AC. Called from Win32Backend.WndProcHook on AC's main
|
||||
/// thread, before the Avalonia forward. No-op (returns false) when the HUD
|
||||
/// is not being drawn.
|
||||
/// </summary>
|
||||
public static bool TryHandleMouse(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
if (!_geomInit || !EngineSettings.DrawCustomVitalBars)
|
||||
return false;
|
||||
|
||||
switch (msg)
|
||||
{
|
||||
case WM_LBUTTONDOWN:
|
||||
{
|
||||
float mxf = (short)((long)lParam & 0xFFFF);
|
||||
float myf = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
Metrics m = Metric(_scale);
|
||||
|
||||
// Clamp the same way Draw does so the hit-test matches the pixels.
|
||||
float px = _hudX, py = _hudY;
|
||||
if (_vpW > 0f && px > _vpW - m.PanelW) px = _vpW - m.PanelW;
|
||||
if (_vpH > 0f && py > _vpH - m.PanelH) py = _vpH - m.PanelH;
|
||||
if (px < 0f) px = 0f;
|
||||
if (py < 0f) py = 0f;
|
||||
|
||||
bool inPanel = mxf >= px && mxf <= px + m.PanelW &&
|
||||
myf >= py && myf <= py + m.PanelH;
|
||||
if (!inPanel) return false;
|
||||
|
||||
// Pin the (clamped) top-left so move/resize anchor to the pixels.
|
||||
_hudX = px; _hudY = py;
|
||||
|
||||
bool inGrip = mxf >= px + m.PanelW - m.Grip && myf >= py + m.PanelH - m.Grip;
|
||||
if (inGrip)
|
||||
{
|
||||
float dx = mxf - px, dy = myf - py;
|
||||
float dist = MathF.Sqrt(dx * dx + dy * dy);
|
||||
if (dist < 8f) dist = 8f;
|
||||
_resizeStartDist = dist;
|
||||
_resizeStartScale = m.Scale;
|
||||
_dragMode = 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
_grabDX = mxf - px;
|
||||
_grabDY = myf - py;
|
||||
_dragMode = 1;
|
||||
}
|
||||
SetCapture(hWnd);
|
||||
return true;
|
||||
}
|
||||
|
||||
case WM_MOUSEMOVE:
|
||||
{
|
||||
if (_dragMode == 0) return false;
|
||||
// Left button no longer held (we missed the UP — e.g. capture
|
||||
// stolen by alt-tab): end the drag and let the move through so the
|
||||
// HUD can't get stuck following the cursor.
|
||||
if (((long)wParam & 0x0001 /* MK_LBUTTON */) == 0)
|
||||
{
|
||||
_dragMode = 0;
|
||||
ReleaseCapture();
|
||||
SaveCfg();
|
||||
return false;
|
||||
}
|
||||
float mxf = (short)((long)lParam & 0xFFFF);
|
||||
float myf = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
|
||||
if (_dragMode == 1) // move
|
||||
{
|
||||
float nx = mxf - _grabDX;
|
||||
float ny = myf - _grabDY;
|
||||
Metrics m = Metric(_scale);
|
||||
if (_vpW > 0f && nx > _vpW - m.PanelW) nx = _vpW - m.PanelW;
|
||||
if (_vpH > 0f && ny > _vpH - m.PanelH) ny = _vpH - m.PanelH;
|
||||
if (nx < 0f) nx = 0f;
|
||||
if (ny < 0f) ny = 0f;
|
||||
_hudX = nx; _hudY = ny;
|
||||
}
|
||||
else // resize
|
||||
{
|
||||
float dx = mxf - _hudX, dy = myf - _hudY;
|
||||
float dist = MathF.Sqrt(dx * dx + dy * dy);
|
||||
float s = _resizeStartScale * dist / _resizeStartDist;
|
||||
if (s < MinScale) s = MinScale;
|
||||
if (s > MaxScale) s = MaxScale;
|
||||
_scale = s;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
case WM_LBUTTONUP:
|
||||
{
|
||||
if (_dragMode == 0) return false;
|
||||
_dragMode = 0;
|
||||
ReleaseCapture();
|
||||
SaveCfg();
|
||||
return true;
|
||||
}
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Persistence: %APPDATA%\RynthCore\vitalhud.cfg ("x y scale") ──
|
||||
private static string? CfgPath()
|
||||
{
|
||||
string? appData = Environment.GetEnvironmentVariable("APPDATA");
|
||||
if (string.IsNullOrEmpty(appData)) return null;
|
||||
return Path.Combine(appData, "RynthCore", "vitalhud.cfg");
|
||||
}
|
||||
|
||||
private static bool LoadCfg(out float x, out float y, out float s)
|
||||
{
|
||||
x = 0f; y = 0f; s = 1f;
|
||||
try
|
||||
{
|
||||
string? path = CfgPath();
|
||||
if (path == null || !File.Exists(path)) return false;
|
||||
string[] parts = File.ReadAllText(path)
|
||||
.Split([' ', '\t', '\r', '\n'], StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 3) return false;
|
||||
if (!float.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out float fx) ||
|
||||
!float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out float fy) ||
|
||||
!float.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out float fs))
|
||||
return false;
|
||||
if (fs < MinScale) fs = MinScale;
|
||||
if (fs > MaxScale) fs = MaxScale;
|
||||
if (fx < 0f) fx = 0f;
|
||||
if (fy < 0f) fy = 0f;
|
||||
x = fx; y = fy; s = fs;
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"VitalHud: LoadCfg failed - {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void SaveCfg()
|
||||
{
|
||||
try
|
||||
{
|
||||
string? path = CfgPath();
|
||||
if (path == null) return;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
string body = string.Format(CultureInfo.InvariantCulture, "{0:F1} {1:F1} {2:F4}", _hudX, _hudY, _scale);
|
||||
File.WriteAllText(path, body);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"VitalHud: SaveCfg failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Internals ────────────────────────────────────────────────────
|
||||
private static void CacheDelegates(IntPtr pDevice)
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
|
||||
_setRenderState = Get<SetRenderStateDelegate>(vtable, DeviceVTableIndex.SetRenderState);
|
||||
_getRenderState = Get<GetRenderStateDelegate>(vtable, DeviceVTableIndex.GetRenderState);
|
||||
_setTextureStageState = Get<SetTextureStageStateDelegate>(vtable, DeviceVTableIndex.SetTextureStageState);
|
||||
_getTextureStageState = Get<GetTextureStageStateDelegate>(vtable, DeviceVTableIndex.GetTextureStageState);
|
||||
_setTexture = Get<SetTextureDelegate>(vtable, DeviceVTableIndex.SetTexture);
|
||||
_getTexture = Get<GetTextureDelegate>(vtable, DeviceVTableIndex.GetTexture);
|
||||
_setFVF = Get<SetFVFDelegate>(vtable, DeviceVTableIndex.SetFVF);
|
||||
_getFVF = Get<GetFVFDelegate>(vtable, DeviceVTableIndex.GetFVF);
|
||||
_setVertexShader = Get<SetVertexShaderDelegate>(vtable, DeviceVTableIndex.SetVertexShader);
|
||||
_getVertexShader = Get<GetVertexShaderDelegate>(vtable, DeviceVTableIndex.GetVertexShader);
|
||||
_setPixelShader = Get<SetPixelShaderDelegate>(vtable, DeviceVTableIndex.SetPixelShader);
|
||||
_getPixelShader = Get<GetPixelShaderDelegate>(vtable, DeviceVTableIndex.GetPixelShader);
|
||||
_drawPrimitiveUP = Get<DrawPrimitiveUPDelegate>(vtable, DeviceVTableIndex.DrawPrimitiveUP);
|
||||
_getViewport = Get<GetViewportDelegate>(vtable, DeviceVTableIndex.GetViewport);
|
||||
|
||||
_delegatesCached = true;
|
||||
RynthLog.D3D9("VitalHud: D3D9 delegates cached.");
|
||||
}
|
||||
|
||||
private static T Get<T>(IntPtr vtable, int index) where T : Delegate
|
||||
{
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
|
||||
private static void ReleaseCom(IntPtr pUnk)
|
||||
{
|
||||
if (pUnk == IntPtr.Zero) return;
|
||||
IntPtr vtbl = Marshal.ReadIntPtr(pUnk);
|
||||
IntPtr releaseAddr = Marshal.ReadIntPtr(vtbl, 2 * IntPtr.Size); // IUnknown::Release
|
||||
var release = Marshal.GetDelegateForFunctionPointer<ReleaseComDelegate>(releaseAddr);
|
||||
release(pUnk);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue