RynthCore as of 2026-10-04 (internal 843c801): RynthNav auto-travel and the navigation map, plugin API v75 (server and titles), launcher with Available plugins, download progress and the update on the front page, opt-in usage statistics, NPC names, radar colours, title-bar text size, FPS limiter, client action unlocks, release 2026.10.4.6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-10-04 18:34:27 -04:00
commit a24ed6df7c
322 changed files with 83009 additions and 7504 deletions

View file

@ -1,168 +0,0 @@
// ═══════════════════════════════════════════════════════════════════════════
// 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;
}
}
}

View file

@ -30,6 +30,15 @@ internal static class D3D9Bootstrapper
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
/// <summary>
/// Decal is in this client and the in-game renderer was asked for (EntryPoint,
/// DecalInGameImGui). Decal detours Direct3DCreate9 and IDirect3D9::CreateDevice, so the
/// throwaway-device discovery would hand a second device to Decal: the EndScene address
/// comes from AC's live device (heap scan) or d3d9.dll's image instead. Never set
/// without Decal.
/// </summary>
internal static volatile bool DecalInProcess;
private static int _started;
private static bool _d3dCreateHookInstalled;
private static bool _createDeviceHookInstalled;
@ -46,18 +55,23 @@ internal static class D3D9Bootstrapper
if (Interlocked.CompareExchange(ref _started, 1, 0) != 0)
return;
var thread = new Thread(BootstrapWorker)
{
Name = "RynthCore.D3D9Bootstrap",
IsBackground = true
};
thread.Start();
EngineThreads.Start("RynthCore.D3D9Bootstrap", BootstrapWorker);
}
private static void BootstrapWorker()
{
try
{
if (DecalInProcess)
{
while (GetModuleHandleA("d3d9.dll") == IntPtr.Zero)
if (!EngineThreads.Sleep(PollIntervalMs))
return;
RynthLog.D3D9("D3D9Bootstrapper: Decal in the process - discovering EndScene without creating a device.");
EndSceneHook.InstallWithoutDevice("decal-live-device");
return;
}
// 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
@ -91,7 +105,8 @@ internal static class D3D9Bootstrapper
return;
}
Thread.Sleep(PollIntervalMs);
if (!EngineThreads.Sleep(PollIntervalMs))
return; // engine shutting down: don't install hooks for a dying generation
}
}
catch (Exception ex)

View file

@ -421,6 +421,68 @@ internal static unsafe class D3D9VTable
return null;
}
/// <summary>
/// Decal clients: Decal gives AC's device its own copy of the vtable (EndScene and Reset
/// point into Inject.dll, the rest still into d3d9.dll). This finds the d3d9.dll vtable the
/// copy was made from - the vtable in d3d9's image that agrees with the copy in the most
/// slots - so the engine can hook d3d9's own functions and never Decal's. Read-only.
/// Returns null when no candidate agrees in at least 100 slots.
/// </summary>
public static IntPtr[]? MatchOriginalDeviceVTable(IntPtr copiedVTable, int numEntries = 119)
{
IntPtr hModule = GetModuleHandleA("d3d9.dll");
if (hModule == IntPtr.Zero || copiedVTable == IntPtr.Zero)
return null;
if (!TryReadModuleImageSize(hModule, out int imageSize) || imageSize < 0x2000 || imageSize > 50 * 1024 * 1024)
return null;
var copy = new int[numEntries];
for (int i = 0; i < numEntries; i++)
copy[i] = Marshal.ReadInt32(copiedVTable, i * 4);
byte[] image = new byte[imageSize];
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);
}
int bestOff = -1, bestMatches = 0;
for (int off = 0x1000; off <= imageSize - numEntries * 4; off += 4)
{
// Cheap reject: QueryInterface and AddRef of the copy must match.
if (BitConverter.ToInt32(image, off) != copy[0] || BitConverter.ToInt32(image, off + 4) != copy[1])
continue;
int matches = 0;
for (int i = 0; i < numEntries; i++)
if (BitConverter.ToInt32(image, off + i * 4) == copy[i])
matches++;
if (matches > bestMatches)
{
bestMatches = matches;
bestOff = off;
}
}
if (bestOff < 0 || bestMatches < 100)
{
RynthLog.D3D9($"D3D9VTable: no d3d9.dll vtable matches the copied one (best {bestMatches}/{numEntries}).");
return null;
}
var vtable = new IntPtr[numEntries];
var differs = new System.Text.StringBuilder();
for (int i = 0; i < numEntries; i++)
{
vtable[i] = new IntPtr(BitConverter.ToInt32(image, bestOff + i * 4));
if (vtable[i].ToInt32() != copy[i])
differs.Append(' ').Append(i);
}
RynthLog.D3D9($"D3D9VTable: the copied device vtable came from d3d9+0x{bestOff:X} ({bestMatches}/{numEntries} slots equal; replaced slots:{differs}). " +
$"d3d9's EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8}.");
return vtable;
}
private static bool IsRecognizedPrologue(byte[] image, int offset)
{
byte b = image[offset];

View file

@ -0,0 +1,129 @@
// ============================================================================
// RynthCore.Engine - D3D9/DecalD3D9.cs
//
// Decal clients with the in-game renderer only (DecalInGameImGui, docs/DECAL_BRIDGE_PLAN.md).
// Decal gives AC's device its own copy of the vtable, with Reset, BeginScene, EndScene and a
// few more slots pointing into Inject.dll (measured 2026-09-30). The engine hooks d3d9.dll's
// own functions (which Decal's wrappers call) and never Decal's code: HookTarget resolves a
// device slot through d3d9's original vtable. Without Decal, Enabled stays false and
// HookTarget is the plain vtable read it always was.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.D3D9;
internal static unsafe class DecalD3D9
{
/// <summary>Set by EndSceneHook.InstallWithoutDevice (Decal clients only).</summary>
internal static bool Enabled;
/// <summary>d3d9.dll's own EndScene for AC's device, from <see cref="TryResolve"/>.</summary>
internal static IntPtr ResolvedEndScene;
/// <summary>
/// Decides, before any hook goes in, whether the in-game renderer can run in this Decal
/// client: AC's device from the bridge (Decal's public IDecalCore.GetD3DDevice; read
/// without waiting), and d3d9.dll's EndScene for it - directly when its vtable is d3d9's,
/// or through the d3d9 vtable Decal's per-device copy was made from. Read-only. False =
/// stay on the Decal-coexistence path (no D3D9). Called once per generation.
/// </summary>
internal static bool TryResolve()
{
if (ResolvedEndScene != IntPtr.Zero)
return true;
IntPtr device = Compatibility.DecalBridgeHost.DecalDevice;
if (device == IntPtr.Zero)
{
RynthLog.D3D9("DecalD3D9: the bridge hasn't reported Decal's device - staying on the coexistence path.");
return false;
}
IntPtr es = DescribeDevice(device, "Decal's device (GetD3DDevice)", out bool inD3d9);
if (inD3d9 && es != IntPtr.Zero)
{
ResolvedEndScene = es;
return true;
}
// Decal swapped the device's vtable for its own copy: find d3d9's original.
IntPtr[]? original = D3D9VTable.MatchOriginalDeviceVTable(Marshal.ReadIntPtr(device));
if (original == null)
{
RynthLog.D3D9("DecalD3D9: d3d9.dll's original device vtable wasn't found - staying on the coexistence path.");
return false;
}
OriginalVTable = original;
ResolvedEndScene = original[DeviceVTableIndex.EndScene];
RynthLog.D3D9($"DecalD3D9: Decal wraps EndScene; d3d9's own EndScene is {Describe(ResolvedEndScene)} (Decal's wrapper calls it).");
return true;
}
/// <summary>Decal clients: d3d9.dll's own device vtable (the one Decal's per-device copy
/// was made from), when found. Hooks on device methods resolve through it.</summary>
internal static IntPtr[]? OriginalVTable;
private static int _refusedLogged;
/// <summary>
/// The address to hook for a device method. Without Decal: the device's vtable slot, as
/// always. With Decal: d3d9.dll's own function for that slot, and zero (do not hook) if
/// it isn't in d3d9.dll - the engine never hooks Decal's code.
/// </summary>
internal static IntPtr HookTarget(IntPtr device, int index)
{
IntPtr fn = Marshal.ReadIntPtr(Marshal.ReadIntPtr(device), index * IntPtr.Size);
if (!Enabled)
return fn;
if (OriginalVTable != null && index < OriginalVTable.Length)
fn = OriginalVTable[index];
string where = Describe(fn);
if (where.StartsWith("d3d9.dll+", StringComparison.OrdinalIgnoreCase))
return fn;
if (Interlocked.Increment(ref _refusedLogged) <= 8)
RynthLog.D3D9($"DecalD3D9: device slot {index} resolves to {where}, not d3d9.dll - not hooked (Decal's code is never patched).");
return IntPtr.Zero;
}
[DllImport("kernel32.dll")]
private static extern bool GetModuleHandleExW(uint flags, IntPtr address, out IntPtr module);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern uint GetModuleFileNameW(IntPtr module, char* buffer, uint size);
/// <summary>"module+0xRVA" for a code or data address.</summary>
internal static string Describe(IntPtr address)
{
const uint FROM_ADDRESS = 0x4, UNCHANGED_REFCOUNT = 0x2;
if (address == IntPtr.Zero)
return "null";
if (!GetModuleHandleExW(FROM_ADDRESS | UNCHANGED_REFCOUNT, address, out IntPtr module) || module == IntPtr.Zero)
return $"0x{address.ToInt32():X8} (no module)";
char* buf = stackalloc char[260];
uint n = GetModuleFileNameW(module, buf, 260);
return $"{System.IO.Path.GetFileName(new string(buf, 0, (int)n))}+0x{address.ToInt32() - module.ToInt32():X}";
}
/// <summary>Logs a device's vtable owner and EndScene/Reset/Present slots; returns its EndScene.</summary>
internal static IntPtr DescribeDevice(IntPtr device, string what, out bool endSceneInD3d9)
{
endSceneInD3d9 = false;
try
{
IntPtr vtable = Marshal.ReadIntPtr(device);
IntPtr endScene = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.EndScene * IntPtr.Size);
IntPtr reset = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.Reset * IntPtr.Size);
IntPtr present = Marshal.ReadIntPtr(vtable, 17 * IntPtr.Size);
string es = Describe(endScene);
endSceneInD3d9 = es.StartsWith("d3d9.dll+", StringComparison.OrdinalIgnoreCase);
RynthLog.D3D9($"DecalD3D9: {what} 0x{device.ToInt32():X8}: vtable {Describe(vtable)}, EndScene {es}, Reset {Describe(reset)}, Present {Describe(present)}.");
return endScene;
}
catch (Exception ex)
{
RynthLog.D3D9($"DecalD3D9: reading {what} threw {ex.GetType().Name}: {ex.Message}");
return IntPtr.Zero;
}
}
/// <summary>First backbuffer frame in our EndScene detour (AC's thread): which device our
/// d3d9 hook is called with, and whose code its vtable points at.</summary>
internal static void FirstFrame(IntPtr device) => DescribeDevice(device, "EndScene called with device", out _);
}

View file

@ -0,0 +1,88 @@
// ============================================================================
// RynthCore.Engine - D3D9/DeviceResetHook.cs
// IDirect3DDevice9::Reset: release the engine's D3DPOOL_DEFAULT resources
// (the pop-outs' render targets) just before AC resets a lost device.
//
// A plain D3D9 device can't be Reset while any default-pool resource is
// alive: Reset fails, and AC shows "Could not initialize Direct3D" and stops
// (2026-09-30 15:06, Lucy, PID 9384: the ImGui bar was popped out when the
// device was lost — screen lock / display change). The resources are
// recreated on the next frame, so nothing else changes.
//
// AC's main thread (Reset is called where EndScene is). Installed from the
// device when the frame controller first sees it; removed at shutdown.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.ImGuiBackend;
namespace RynthCore.Engine.D3D9;
internal static class DeviceResetHook
{
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int ResetDelegate(IntPtr device, IntPtr presentationParameters);
private static ResetDelegate? _original;
private static ResetDelegate? _detour;
private static IntPtr _address;
private static bool _installed;
private static int _resets;
public static void InstallFromDevice(IntPtr device)
{
if (_installed || device == IntPtr.Zero) return;
try
{
// Without Decal: the device's vtable slot, as before. With Decal: d3d9's own Reset
// (Decal wraps Reset; its code is never hooked) - zero means not hooked.
_address = DecalD3D9.HookTarget(device, DeviceVTableIndex.Reset);
if (_address == IntPtr.Zero) return;
_detour = ResetDetour;
_original = Marshal.GetDelegateForFunctionPointer<ResetDelegate>(
MinHook.HookCreate(_address, Marshal.GetFunctionPointerForDelegate(_detour)));
Thread.MemoryBarrier();
MinHook.Enable(_address);
_installed = true;
RynthLog.D3D9($"DeviceResetHook: installed at 0x{_address.ToInt32():X8}.");
}
catch (Exception ex)
{
RynthLog.D3D9($"DeviceResetHook: install failed - {ex.Message}");
}
}
public static void Uninstall()
{
if (!_installed) return;
RynthLog.D3D9($"DeviceResetHook: disable = {MinHook.StatusString(MinHook.MH_DisableHook(_address))}, remove = {MinHook.StatusString(MinHook.MH_RemoveHook(_address))}.");
_installed = false;
_original = null;
_detour = null;
}
private static int ResetDetour(IntPtr device, IntPtr presentationParameters)
{
int n = Interlocked.Increment(ref _resets);
try
{
int released = ImGuiPopOuts.ReleaseDeviceResources();
if (n <= 20)
RynthLog.D3D9($"DeviceResetHook: device Reset #{n}: released {released} pop-out surface set(s) first.");
}
catch (Exception ex)
{
try { RynthLog.D3D9($"DeviceResetHook: releasing before Reset threw {ex.GetType().Name}: {ex.Message}"); } catch { }
}
int hr = _original!(device, presentationParameters);
if (n <= 20 || hr < 0)
{
try { RynthLog.D3D9($"DeviceResetHook: Reset #{n} returned 0x{hr:X8}."); } catch { }
}
return hr;
}
}

View file

@ -14,6 +14,10 @@ internal static class EndSceneHook
private const int MaxOffscreenSkipsBeforeFallback = 120;
private const int OffscreenFallbackDelayMs = 3000;
private const int UiInitWarmupFrames = 180;
// After a hot reload the device and the game have been running all along: a few
// frames is enough (180 was ~1 s more of no overlay on every reload).
private const int UiInitWarmupFramesReload = 5;
private static int WarmupFrames => EntryPoint.InitCount >= 2 ? UiInitWarmupFramesReload : UiInitWarmupFrames;
// ── FPS Governor — set by plugins via API ───────────────────────
internal static bool FpsLimitEnabled;
@ -46,6 +50,62 @@ internal static class EndSceneHook
[DllImport("kernel32.dll")]
private static extern uint GetCurrentProcessId();
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr CreateWaitableTimerExW(IntPtr attributes, string? name, uint flags, uint access);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetWaitableTimer(IntPtr timer, ref long dueTime, int period, IntPtr completion, IntPtr arg, [MarshalAs(UnmanagedType.Bool)] bool resume);
[DllImport("kernel32.dll")]
private static extern uint WaitForSingleObject(IntPtr handle, uint ms);
[DllImport("winmm.dll")]
private static extern uint timeBeginPeriod(uint ms);
private const uint CREATE_WAITABLE_TIMER_HIGH_RESOLUTION = 0x2;
private const uint TIMER_ALL_ACCESS = 0x1F0003;
private static IntPtr _frameTimer;
private static bool _frameTimerTried;
/// <summary>
/// Waits <paramref name="ms"/> without burning the CPU. The governor used to wait with
/// Sleep(0) in a loop when focused (Sleep(0) returns at once when nothing else is ready,
/// so a "capped" focused client spun a whole core) and Sleep(1) in the background (15.6 ms
/// timer steps, so a 30 fps cap gave 19 fps, 2026-10-03). A high-resolution waitable timer
/// (Windows 10 1803+) wakes within about half a millisecond; without one, timeBeginPeriod(1)
/// makes Sleep(1) a 1 ms sleep. The last 0.3 ms is a yield loop for accuracy.
/// </summary>
private static void WaitFrame(double ms)
{
if (!_frameTimerTried)
{
_frameTimerTried = true;
try { _frameTimer = CreateWaitableTimerExW(IntPtr.Zero, null, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS); } catch { }
if (_frameTimer == IntPtr.Zero) { try { timeBeginPeriod(1); } catch { } }
RynthLog.D3D9($"EndSceneHook: FPS governor waits with {(_frameTimer != IntPtr.Zero ? "a high-resolution timer" : "1 ms sleeps")}.");
}
long start = Stopwatch.GetTimestamp();
double waitMs = ms - 0.3;
if (waitMs > 0.5)
{
if (_frameTimer != IntPtr.Zero)
{
long due = -(long)(waitMs * 10_000); // negative = relative, in 100 ns units
if (SetWaitableTimer(_frameTimer, ref due, 0, IntPtr.Zero, IntPtr.Zero, false))
WaitForSingleObject(_frameTimer, (uint)Math.Ceiling(waitMs) + 50);
}
else
{
while ((Stopwatch.GetTimestamp() - start) * 1000.0 / Stopwatch.Frequency < waitMs - 1.0)
Thread.Sleep(1);
}
}
while ((Stopwatch.GetTimestamp() - start) * 1000.0 / Stopwatch.Frequency < ms)
Thread.Yield();
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int EndSceneDelegate(IntPtr pDevice);
@ -54,6 +114,8 @@ internal static class EndSceneHook
private static IntPtr _endSceneAddr;
private static bool _installed;
private static int _frameCount;
/// <summary>Back-buffer frames drawn (offscreen passes - Decal views, VVS, UB - not counted). Resets on reinstall.</summary>
internal static int BackBufferFrames => Volatile.Read(ref _frameCount);
private static int _renderCount;
private static int _skipCount;
private static int _uiFrameCount;
@ -101,6 +163,30 @@ internal static class EndSceneHook
RynthLog.D3D9("EndSceneHook: FAILED - could not discover vtable after all attempts.");
}
/// <summary>
/// Decal clients (D3D9Bootstrapper.DecalInProcess): no D3D9 object is created (Decal
/// detours Direct3DCreate9 and CreateDevice). AC's device comes from the Decal bridge
/// (Decal's public IDecalCore.GetD3DDevice); Decal has swapped its vtable for a copy, so
/// d3d9.dll's original vtable is found by matching and d3d9's own EndScene is hooked
/// (DecalD3D9.TryResolve). A heap or image scan is not used: it can't tell AC's device
/// from the ones Decal plugins create (measured: it picked another device).
/// </summary>
public static void InstallWithoutDevice(string installSource)
{
if (_installed)
return;
ResetInstallState(installSource);
DecalD3D9.Enabled = true;
// Resolved (read-only) by EntryPoint before it chose this path; never Decal's code.
if (!DecalD3D9.TryResolve())
{
RynthLog.D3D9("EndSceneHook: FAILED - AC's device couldn't be identified through the Decal bridge; no in-game UI in this client.");
return;
}
RynthLog.D3D9($"EndSceneHook: hooking d3d9's own EndScene @ 0x{DecalD3D9.ResolvedEndScene.ToInt32():X8} ({DecalD3D9.Describe(DecalD3D9.ResolvedEndScene)}).");
InstallFromEndSceneAddress(DecalD3D9.ResolvedEndScene);
}
public static void InstallFromDevice(IntPtr pDevice)
{
if (_installed)
@ -161,6 +247,7 @@ internal static class EndSceneHook
// Let the render thread return through the trampoline.
Thread.Sleep(80);
DeviceResetHook.Uninstall();
EngineFrameController.Shutdown();
status = MinHook.MH_RemoveHook(_endSceneAddr);
@ -225,7 +312,12 @@ internal static class EndSceneHook
_skipCount++;
long offscreenElapsedMs = Environment.TickCount64 - _firstOffscreenTick;
if (_skipCount < MaxOffscreenSkipsBeforeFallback && offscreenElapsedMs < OffscreenFallbackDelayMs)
// Decal clients: Decal's views, VVS and UB render into their own targets every
// frame, so an offscreen EndScene is normal there and the fallback below would
// draw our UI (and nav rings) into their textures (measured 2026-09-30). Never
// fall back with Decal; without Decal nothing changes.
if (DecalD3D9.Enabled ||
(_skipCount < MaxOffscreenSkipsBeforeFallback && offscreenElapsedMs < OffscreenFallbackDelayMs))
return _originalEndScene!(pDevice);
_offscreenFilterDisabled = true;
@ -241,6 +333,8 @@ internal static class EndSceneHook
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 */ }
// Per-frame retail health/stamina/mana bars visibility ("Hide retail vitals").
try { RetailVitalsHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
if (_renderCount == 1 && _offscreenFilterDisabled && _skipCount > 0)
{
@ -260,8 +354,16 @@ internal static class EndSceneHook
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 (DecalD3D9.Enabled)
DecalD3D9.FirstFrame(pDevice);
if (!match && actualEndScene != IntPtr.Zero)
if (!match && DecalD3D9.Enabled)
{
// Decal client: the device's slot is Decal's wrapper (we hooked d3d9's own
// EndScene, which that wrapper calls). Never rehook onto Decal's code.
RynthLog.D3D9($"EndSceneHook: mismatch expected with Decal (slot is {DecalD3D9.Describe(actualEndScene)}) - keeping the d3d9 hook.");
}
else if (!match && actualEndScene != IntPtr.Zero)
{
// Deep-audit finding #8 (2026-06-18): the old sequence
// disabled+REMOVED the old hook (freeing the trampoline
@ -303,11 +405,11 @@ internal static class EndSceneHook
{
if (!_warmupLogged)
{
RynthLog.D3D9($"EndSceneHook: Backbuffer detected. Warming up {UiInitWarmupFrames} frame(s) before UI init.");
RynthLog.D3D9($"EndSceneHook: Backbuffer detected. Warming up {WarmupFrames} frame(s) before UI init.");
_warmupLogged = true;
}
if (_renderCount < UiInitWarmupFrames)
if (_renderCount < WarmupFrames)
return _originalEndScene!(pDevice);
_uiActivated = true;
@ -324,7 +426,7 @@ internal static class EndSceneHook
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)
if (_renderCount == WarmupFrames && !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
@ -383,8 +485,8 @@ internal static class EndSceneHook
int targetFps = isFocused ? FpsTargetFocused : FpsTargetBackground;
double minFrameMs = 1000.0 / Math.Max(targetFps, 1);
while (_fpsTimer.Elapsed.TotalMilliseconds < minFrameMs)
Thread.Sleep(isFocused ? 0 : 1);
double leftMs = minFrameMs - _fpsTimer.Elapsed.TotalMilliseconds;
if (leftMs > 0) WaitFrame(leftMs);
_fpsTimer.Restart();
if (!_fpsLimiterLoggedOnce)

View file

@ -70,6 +70,33 @@ internal static unsafe class GameMatrixCapture
private static bool _loggedFirstCapture;
public static bool HasCapturedFrame => _hasValidViewProj;
// Landblock whose local frame the current view matrix is built in: the
// anchor (submission / player) landblock when the camera was shifted into
// it, else the viewer's own. Anything projecting a world point must first
// move that point into this landblock's frame (192 m per landblock step).
private static uint _frameLandblock;
/// <summary>
/// Landblock (cellId &gt;&gt; 16) whose local coordinates WorldToScreen expects,
/// as of the last CaptureFrame; 0 when unknown. AC's render thread.
/// </summary>
public static uint FrameLandblock => _frameLandblock;
// Camera position in the same frame as the view matrix (D3D axes: x = east,
// y = up, z = north, FrameLandblock-local), as of the last CaptureFrame.
private static float _camX, _camY, _camZ;
/// <summary>
/// The camera's position in WorldToScreen's frame (D3D axes, FrameLandblock-local).
/// False before the first capture. AC's render thread.
/// </summary>
public static bool TryGetCameraPosition(out float x, out float y, out float z)
{
x = _camX; y = _camY; z = _camZ;
return _hasValidViewProj;
}
public static uint ViewportWidth => _vpWidth;
public static uint ViewportHeight => _vpHeight;
@ -100,6 +127,10 @@ internal static unsafe class GameMatrixCapture
if (pMatrix != null && state == D3DTS_PROJECTION)
{
bool isPerspective = Math.Abs(pMatrix[11]) > 0.01f;
// Decal clients: a Virindi/Decal/UB 3D pass into its own render target must not
// replace AC's projection. Projection sets are rare; only checked with Decal.
if (isPerspective && DecalD3D9.Enabled && !ImGuiBackend.DX9Backend.IsRenderingToBackBuffer(dev))
isPerspective = false;
if (isPerspective)
{
for (int i = 0; i < 16; i++)
@ -198,6 +229,7 @@ internal static unsafe class GameMatrixCapture
uint viewerCellId = unchecked((uint)Marshal.ReadInt32(camFrame + CamCellIdOffset));
uint viewerLandblock = viewerCellId >> 16;
viewerLbForLog = viewerLandblock;
uint frameLandblock = viewerLandblock; // replaced by the anchor when the shift applies
// Prefer the landblock the plugin tick LOCKED IN when it submitted
// its Nav3D geometry (see Nav3DRenderer.ClearFrame). If we use the
@ -235,6 +267,7 @@ internal static unsafe class GameMatrixCapture
cx += dXBlocks * 192f; // EW shift back into player-landblock frame
cy += dYBlocks * 192f; // NS
shiftApplied = (dXBlocks != 0 || dYBlocks != 0);
frameLandblock = playerLandblock;
}
else
{
@ -299,6 +332,8 @@ internal static unsafe class GameMatrixCapture
RynthLog.D3D9($"GameMatrixCapture: viewport={_vpWidth}x{_vpHeight}");
}
_camX = px; _camY = py; _camZ = pz;
_frameLandblock = frameLandblock;
_hasValidViewProj = true;
}
@ -354,8 +389,8 @@ internal static unsafe class GameMatrixCapture
{
try
{
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
IntPtr setTransformAddr = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.SetTransform * IntPtr.Size);
IntPtr setTransformAddr = DecalD3D9.HookTarget(pDevice, DeviceVTableIndex.SetTransform);
if (setTransformAddr == IntPtr.Zero) return; // Decal client and the slot isn't d3d9's: not hooked
_hookDelegate = new SetTransformD(SetTransformDetour);
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);

View file

@ -46,8 +46,8 @@ internal static class Nav3DRenderInjector
try
{
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
IntPtr addr = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.DrawIndexedPrimitive * IntPtr.Size);
IntPtr addr = DecalD3D9.HookTarget(pDevice, DeviceVTableIndex.DrawIndexedPrimitive);
if (addr == IntPtr.Zero) return; // Decal client and the slot isn't d3d9's: not hooked
_hookDelegate = new DrawIndexedPrimitiveD(Detour);
IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);
@ -79,7 +79,11 @@ internal static class Nav3DRenderInjector
_seen3D = true;
// Detect 3D→UI transition: ZENABLE goes from 1→0 after 3D draws
if (!_markersRenderedThisFrame && _seen3D && _lastZEnable != 0 && zEnable == 0)
// Decal clients: VVS/Decal/UB draw 3D into their own render targets too; only AC's
// back buffer gets the markers and nameplates (measured 2026-09-30: without this they
// showed up inside a Virindi window). Evaluated only at a transition, and only with Decal.
if (!_markersRenderedThisFrame && _seen3D && _lastZEnable != 0 && zEnable == 0 &&
(!DecalD3D9.Enabled || ImGuiBackend.DX9Backend.IsRenderingToBackBuffer(dev)))
{
_markersRenderedThisFrame = true;
_inRender = true;
@ -90,6 +94,15 @@ internal static class Nav3DRenderInjector
catch
{
}
// The world overlays (nameplates, combat text) go here too, over the
// markers and under AC's UI. Its own frame flag: drawn at most once.
try
{
ImGuiBackend.UnderUiLayer.PresentAtTransition(dev);
}
catch
{
}
_inRender = false;
}

View file

@ -13,9 +13,11 @@
// invisible).
//
// Pattern:
// pump: BeginFrame() → AddX(...) × N → CommitFrame()
// render: reads from the "ready" buffer only; never touches "pending"
// CommitFrame atomically swaps the index reads see.
// pump: ClearFrame() → AddX(...) × N → CommitFrame()
// render: Ready once per draw, then reads only that buffer; never
// touches "pending"
// CommitFrame atomically swaps the buffer reads see. A tick during which the
// player crossed a landblock boundary is dropped (see CommitFrame).
// ═══════════════════════════════════════════════════════════════════════════
using System.Threading;
@ -34,7 +36,8 @@ internal static class Nav3DRenderer
private const float DefaultRingHeight = 0.5f; // back-compat default for AddRing
private sealed class NavBuffer
/// <summary>One tick's submissions. Render side: read-only.</summary>
internal sealed class NavBuffer
{
public readonly float[] RingX = new float[MaxRings];
public readonly float[] RingY = new float[MaxRings];
@ -99,38 +102,14 @@ internal static class Nav3DRenderer
// ── 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];
}
/// <summary>
/// The latest committed frame. Take it once per draw and read everything
/// from it: re-reading this (volatile) property per item would mix two
/// ticks if a commit landed mid-draw (a count from one, contents from the
/// other). The triple buffer keeps a taken frame untouched for a full
/// tick after it stops being ready.
/// </summary>
public static NavBuffer Ready => _ready;
// The landblock the plugin tick that produced the ready buffer was using.
// Render thread uses this for view-matrix shifting so geometry stays
@ -197,9 +176,26 @@ internal static class Nav3DRenderer
/// 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.
///
/// The pump runs off AC's thread, so the player can cross a landblock
/// boundary between ClearFrame and here. Plugins sample the pose during
/// their tick, so some of this tick's geometry may then be in the old
/// landblock's frame and some in the new one, while the frame is anchored
/// to the old — whatever was sampled after the crossing would draw 192 m
/// off for a tick. Such a tick is dropped: the previous frame stays ready
/// (one tick stale, consistent) and the next tick is anchored correctly.
/// </summary>
public static void CommitFrame()
{
uint anchored = _pending.SubmissionPlayerLandblock;
if (anchored != 0 &&
PlayerPhysicsHooks.TryGetPlayerPose(out uint cellId, out _, out _, out _, out _, out _, out _, out _) &&
(cellId >> 16) != 0 && (cellId >> 16) != anchored)
{
_pending.Reset();
return;
}
NavBuffer newReady = _pending;
NavBuffer newSpare = _ready;
NavBuffer newPending = _spare;

View file

@ -1,706 +0,0 @@
// ═══════════════════════════════════════════════════════════════════════════
// 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);
}
}