feat: port aelrynth 2026.9.27.2 snapshot onto GitHub history

Overlay upstream/main (9b5e276) onto BlankenshipG main without rewriting
history. Keep origin-only Decal/plugin/docs trees. Re-apply aelrynth.com
and sibling-fork URL fixes that aelrynth git still has as tombohar links.

Co-authored-by: BlankenshipG <BlankenshipG@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-10-04 15:43:50 +00:00
commit 4ddbb52eb2
No known key found for this signature in database
244 changed files with 59710 additions and 3067 deletions

View file

@ -7,6 +7,7 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using ImGuiNET;
using RynthCore.Engine.D3D9;
using RynthCore.Engine.UI;
@ -17,6 +18,7 @@ internal static unsafe class Win32Backend
{
// ─── Win32 messages ───────────────────────────────────────────────
private const uint WM_MOUSEMOVE = 0x0200;
private const uint WM_NCMOUSEMOVE = 0x00A0;
private const uint WM_SETFOCUS = 0x0007;
private const uint WM_KILLFOCUS = 0x0008;
private const uint WM_ACTIVATE = 0x0006;
@ -39,23 +41,77 @@ internal static unsafe class Win32Backend
private const uint WM_SETCURSOR = 0x0020;
private const uint WM_XBUTTONDOWN = 0x020B;
private const uint WM_XBUTTONUP = 0x020C;
private const uint WM_CLOSE = 0x0010;
// Set on the first WM_CLOSE so we kick off the engine teardown exactly
// once even if AC reposts WM_CLOSE during its shutdown sequence.
private static int _wmCloseSeen;
/// <summary>Arms the post-close mouse/cursor input swallow without running the
/// WM_CLOSE pump-stop/shutdown block (the caller has already quiesced). Used by
/// GameTickHooks when AC exits via a path that never delivers WM_CLOSE (in-game
/// exit / logout-quit) — late WM_MOUSEMOVE/WM_SETCURSOR otherwise reach
/// ClientUISystem::UpdateCursorState after AC frees the combat-system singleton
/// (the 0x0056547B close AV).</summary>
internal static void MarkCloseInFlight() => Interlocked.Exchange(ref _wmCloseSeen, 1);
private const int GWL_WNDPROC = -4;
private const uint GA_ROOT = 2;
private const int HTCLIENT = 1;
/// <summary>Posted by AvaloniaSubclassWndProc when Avalonia acquires focus.
/// Handled here (game thread) so SetFocus is always same-thread — no cross-thread wait.</summary>
public const uint WM_RYNTH_RESTORE_FOCUS = 0x8001;
/// <summary>Sent by RunOnGameThread to execute a queued Action on the game's
/// main thread (where AC's WndProc dispatches). Used to create top-level HWNDs
/// like floating panels' LayeredWindow on AC's thread instead of Avalonia's UI
/// thread, so WS_EX_NOACTIVATE + mouse delivery work as documented (cross-thread
/// HWNDs drop WM_LBUTTONDOWN on Win11 in some focus states).</summary>
public const uint WM_RYNTH_RUN_ACTION = 0x8002;
/// <summary>UI deep-dive finding P0-1 belt-and-braces (2026-07-02):
/// posted (not sent) by LayeredWindow.Dispose to destroy an HWND on the
/// game thread without blocking the calling thread — DestroyWindow must
/// run on the owning thread, but the caller (often the Avalonia UI
/// thread, e.g. redocking a panel) doesn't need to wait for it to
/// finish. wParam carries the HWND to destroy.</summary>
public const uint WM_RYNTH_DESTROY_HWND = 0x8003;
/// <summary>Destroys floating-panel HWNDs on the game thread (their owner).
/// wParam != 0 includes this engine load's own panels (sent synchronously by
/// Shutdown before unhooking); wParam == 0 removes only panels an earlier
/// load left behind (posted by Init). See LayeredWindow.DestroyThreadPanelWindows.</summary>
public const uint WM_RYNTH_SWEEP_PANELS = 0x8004;
private const int VK_CONTROL = 0x11;
private const int VK_SHIFT = 0x10;
private const int VK_MENU = 0x12; // Alt
private const int VK_LWIN = 0x5B;
private const int VK_RWIN = 0x5C;
private const int VK_INSERT = 0x2D;
private const int VK_RETURN = 0x0D;
private const int VK_BACK = 0x08;
private const int VK_ESCAPE = 0x1B;
private const int VK_LEFT = 0x25;
private const int VK_UP = 0x26;
private const int VK_RIGHT = 0x27;
private const int VK_DOWN = 0x28;
private const int VK_HOME = 0x24;
private const int VK_END = 0x23;
private const int VK_DELETE = 0x2E;
// lParam bit 24: extended key flag. Set for numpad Enter, right-side Ctrl/Alt.
// Used to distinguish numpad Enter (extended) from the main keyboard Enter (not extended).
private static bool IsExtendedKey(IntPtr lParam) => ((int)(long)lParam & 0x01000000) != 0;
// ─── Win32 P/Invoke ───────────────────────────────────────────────
// On x86, SetWindowLongPtr doesn't exist — use SetWindowLong
[DllImport("user32.dll", EntryPoint = "SetWindowLongA", SetLastError = true)]
private static extern IntPtr SetWindowLong32(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll", EntryPoint = "GetWindowLongA", SetLastError = true)]
private static extern IntPtr GetWindowLong32(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", EntryPoint = "CallWindowProcA")]
private static extern IntPtr CallWindowProcA(IntPtr lpPrevWndFunc, IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
@ -93,12 +149,47 @@ internal static unsafe class Win32Backend
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
private const uint SMTO_NORMAL = 0x0000;
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam,
uint fuFlags, uint uTimeout, out IntPtr lpdwResult);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DestroyWindow(IntPtr hWnd);
[DllImport("kernel32.dll")]
private static extern uint GetCurrentThreadId();
[DllImport("user32.dll")]
private static extern IntPtr SetFocus(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr SetCapture(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ReleaseCapture();
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetClassNameW(IntPtr hWnd, System.Text.StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetWindowTextW(IntPtr hWnd, System.Text.StringBuilder lpString, int nMaxCount);
private static string DescribeHwnd(IntPtr hwnd)
{
if (hwnd == IntPtr.Zero) return "null";
var cls = new System.Text.StringBuilder(128);
var txt = new System.Text.StringBuilder(128);
GetClassNameW(hwnd, cls, cls.Capacity);
GetWindowTextW(hwnd, txt, txt.Capacity);
return $"class='{cls}' title='{txt}'";
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT { public int Left, Top, Right, Bottom; }
@ -152,10 +243,36 @@ internal static unsafe class Win32Backend
/// <summary>Custom WM_USER message for deferred chat command dispatch.</summary>
internal const uint WM_RYNTHCORE_CHAT = 0x0400 + 0x5243; // WM_USER + "RC"
// Chat's Tell button (Avalonia UI thread) asks for "/tell <selected>, " to be started;
// posted so the selection and its name are read on AC's main thread.
internal const uint WM_RYNTHCORE_TELL = 0x0400 + 0x5244;
/// <summary>Fired on the game thread when the Tell button asks to address the selected object.</summary>
public static Action? OnChatTellSelected;
/// <summary>Callable from any thread: runs <see cref="OnChatTellSelected"/> on AC's main thread.</summary>
public static void RequestTellSelected()
{
if (_gameHwnd != IntPtr.Zero)
PostMessage(_gameHwnd, WM_RYNTHCORE_TELL, IntPtr.Zero, IntPtr.Zero);
}
/// <summary>The game's main window handle.</summary>
public static IntPtr GameHwnd => _gameHwnd;
/// <summary>
/// Populate <see cref="GameHwnd"/> from outside the ImGui Init path.
/// Used by Avalonia-only overlay mode where ImGui is disabled but Avalonia
/// panels still need the game HWND for owner-window binding. Idempotent —
/// the WndProc subclass that <see cref="Init"/> installs is *not* set up by
/// this call, so don't use this if ImGui is going to init too.
/// </summary>
public static void SetGameHwndExternal(IntPtr hwnd)
{
if (hwnd != IntPtr.Zero && _gameHwnd == IntPtr.Zero)
_gameHwnd = hwnd;
}
/// <summary>
/// Sends a message directly to the game's original WndProc, bypassing our subclass.
/// </summary>
@ -163,8 +280,127 @@ internal static unsafe class Win32Backend
{
if (_originalWndProc == IntPtr.Zero || _gameHwnd == IntPtr.Zero)
return IntPtr.Zero;
// Diag (diag/logoff-origin): engine-synthesised input bypasses the subclass.
Compatibility.LogoffOriginProbe.RecordWndMsg(msg, wParam, lParam, synthetic: true);
return CallWindowProcA(_originalWndProc, _gameHwnd, msg, wParam, lParam);
}
private static readonly object _gameThreadLock = new();
private static volatile Action? _pendingGameThreadAction;
/// <summary>
/// Runs <paramref name="action"/> synchronously on AC's main thread (the one
/// that dispatches the hooked game WndProc), and returns its result. Used so
/// HWNDs that must dispatch input on the game thread — most notably the
/// floating-panel LayeredWindows — can be created from any thread (e.g.
/// Avalonia's UI thread) without ending up cross-thread to AC. Without
/// same-thread ownership, Win11's WS_EX_NOACTIVATE silently drops
/// WM_LBUTTONDOWN in some focus states (the docked panels work because they
/// already live on the game thread via the EndScene-driven path).
///
/// Implementation: a single shared action slot serialized by a lock; the
/// action is delivered via SendMessage(WM_RYNTH_RUN_ACTION) which blocks
/// until the game thread's WndProc has handled it. Game-thread callers
/// bypass the marshal and invoke inline.
/// </summary>
public static T RunOnGameThread<T>(Func<T> action)
{
ArgumentNullException.ThrowIfNull(action);
if (_gameHwnd == IntPtr.Zero)
throw new InvalidOperationException("RunOnGameThread called before Win32Backend.Init.");
GetWindowThreadProcessId(_gameHwnd, out uint gameThreadId);
if (gameThreadId == GetCurrentThreadId())
return action();
lock (_gameThreadLock)
{
T result = default!;
Exception? caught = null;
_pendingGameThreadAction = () =>
{
try { result = action(); }
catch (Exception ex) { caught = ex; }
};
// UI deep-dive finding P0-1 belt-and-braces (2026-07-02): a plain
// SendMessage here blocks with no visibility if the game thread's
// WndProc is ever stuck (the AB-BA class the OnInput fix above
// closes, or any future one). SendMessageTimeout with a 2s
// budget logs loudly the instant a stall crosses that threshold
// — a concrete timestamped log line to correlate against a user
// report, instead of silence.
//
// Deliberately does NOT retry the send on timeout: this shared
// single-slot design (_pendingGameThreadAction) has no way to
// tell a stale delivery from a fresh one, and Win32 doesn't
// guarantee a second SendMessage call coalesces with a still-
// pending first one rather than queuing a second delivery — a
// retry risks the action firing twice (e.g. creating a
// LayeredWindow, twice) once the game thread unblocks. Logging
// and returning the default result is a strictly better failure
// mode than today's silent, undiagnosed, permanent hang: if
// we're 2s+ into this wait, something is already badly wrong,
// and a caller getting a default/null result it can react to
// beats every thread being frozen with nothing in the log.
IntPtr sendResult = SendMessageTimeout(_gameHwnd, WM_RYNTH_RUN_ACTION, IntPtr.Zero, IntPtr.Zero,
SMTO_NORMAL, 2000, out _);
if (sendResult == IntPtr.Zero)
{
try { RynthLog.Info($"Win32Backend: RunOnGameThread stalled >2s waiting on game thread (hwnd=0x{_gameHwnd.ToInt64():X}) — giving up this wait; result will be default."); }
catch { }
}
_pendingGameThreadAction = null;
if (caught != null)
throw caught;
return result;
}
}
/// <summary>Void overload of <see cref="RunOnGameThread{T}"/>.</summary>
public static void RunOnGameThread(Action action)
{
RunOnGameThread<bool>(() => { action(); return true; });
}
/// <summary>
/// UI deep-dive finding P0-1 (2026-07-02): posts (does not block on) a
/// DestroyWindow for <paramref name="hwnd"/> onto the game thread.
/// DestroyWindow must run on the HWND's owning thread, but unlike
/// RunOnGameThread this never needs the caller to observe a result — so
/// it uses a dedicated PostMessage instead of the shared
/// RunOnGameThread action slot, avoiding any risk of blocking the
/// caller (e.g. LayeredWindow.Dispose called from the Avalonia UI
/// thread while redocking a panel) on the game thread's WndProc.
/// </summary>
public static void PostDestroyWindow(IntPtr hwnd)
{
if (hwnd == IntPtr.Zero) return;
if (_gameHwnd == IntPtr.Zero)
{
// No game thread to marshal to (e.g. very early/late in
// lifecycle) — best-effort inline as LayeredWindow.Dispose's own
// fallback already does for the RunOnGameThread-unavailable case.
DestroyWindow(hwnd);
return;
}
GetWindowThreadProcessId(_gameHwnd, out uint gameThreadId);
if (gameThreadId == GetCurrentThreadId())
{
DestroyWindow(hwnd);
return;
}
PostMessage(_gameHwnd, WM_RYNTH_DESTROY_HWND, hwnd, IntPtr.Zero);
}
/// <summary>Deactivates chat capture. The game HWND retains focus throughout so no
/// Win32 focus transfer is needed.</summary>
public static void ReturnFocusToGame() => ChatCaptureActive = false;
/// <summary>Called by AvaloniaSubclassWndProc when WM_LBUTTONUP arrives via the
/// SetCapture route so _avPanelMouseDown doesn't get stuck true.</summary>
internal static void ClearPanelMouseDown() => _avPanelMouseDown = false;
private static readonly bool[] _mouseButtons = new bool[5];
private static readonly object _inputLock = new();
private static readonly Queue<QueuedInputMessage> _pendingInput = new();
@ -176,6 +412,50 @@ internal static unsafe class Win32Backend
private static bool _focusInitialized;
private static bool _insertWasDown;
private static bool _avaloniaHasMouse; // cursor is currently over the Avalonia panel
/// <summary>While true, WM_CHAR / special keys are consumed for the chat input TextBox
/// instead of passing to the game. Focus stays on the game HWND.</summary>
public static volatile bool ChatCaptureActive;
/// <summary>While true, an Avalonia panel TextBox currently has keyboard focus and
/// the WM_SETFOCUS hijack in <see cref="UI.AvaloniaOverlay"/>'s subclass WndProc
/// must NOT immediately PostMessage focus back to the game window — doing so
/// yanks focus off the TextBox ~50 ms after the user clicks it, making it
/// impossible to type. Set true on Avalonia TextBox.GotFocus, false on
/// LostFocus. (ChatCaptureActive uses a completely different pipeline:
/// the game HWND keeps focus and WM_CHAR is routed to the chat callbacks,
/// so it doesn't help for normal panels that genuinely need Avalonia focus.)</summary>
public static volatile bool AvaloniaTextInputActive;
/// <summary>Set when we consume the VK_RETURN/VK_ESCAPE that ends chat capture, so the
/// trailing WM_CHAR ('\r') + WM_KEYUP of that same keystroke are eaten too and never
/// leak to the game (a lone '\r' can spuriously re-open AC's native chat bar).</summary>
private static bool _swallowEnterTail;
// ── Chat input callbacks (set by RynthChatPanel) ─────────────────────
/// <summary>Fired when Enter in-game activates chat (UI thread dispatch optional).</summary>
public static Action? OnChatCaptureActivated;
/// <summary>Fired for each printable character (≥ 0x20) while capture is active.</summary>
public static Action<char>? OnChatChar;
/// <summary>Fired on VK_BACK while capture is active.</summary>
public static Action? OnChatBackspace;
/// <summary>Fired on VK_DELETE while capture is active.</summary>
public static Action? OnChatDelete;
/// <summary>Fired on VK_RETURN while capture is active (ChatCaptureActive already false).</summary>
public static Action? OnChatSend;
/// <summary>Fired on VK_ESCAPE while capture is active (ChatCaptureActive already false).</summary>
public static Action? OnChatCancel;
/// <summary>Fired on VK_LEFT while capture is active.</summary>
public static Action? OnChatLeft;
/// <summary>Fired on VK_RIGHT while capture is active.</summary>
public static Action? OnChatRight;
/// <summary>Fired on VK_HOME while capture is active.</summary>
public static Action? OnChatHome;
/// <summary>Fired on VK_END while capture is active.</summary>
public static Action? OnChatEnd;
/// <summary>Fired on VK_UP while capture is active (history previous).</summary>
public static Action? OnChatUp;
/// <summary>Fired on VK_DOWN while capture is active (history next).</summary>
public static Action? OnChatDown;
private static int _lastPanelClientX; // last game-client pos over the panel (for wheel)
private static int _lastPanelClientY;
@ -185,6 +465,12 @@ internal static unsafe class Win32Backend
private static bool _avIsResizing;
private static bool _avIsButtonCapture;
private static bool _avHasNativeCapture;
// Set when a left-button press lands on an opened Avalonia panel (not the
// bar). While set, every mouse event is forwarded to Avalonia regardless
// of whether the cursor is still over the panel rect — without this,
// a fast drag where the cursor outpaces the panel-position update lands
// outside IsOverPanel and the drag drops.
private static bool _avPanelMouseDown;
private static int _avPrevPhysX;
private static int _avPrevPhysY;
private static double _avDragResidualX;
@ -201,6 +487,7 @@ internal static unsafe class Win32Backend
public static bool Init(IntPtr hWnd)
{
if (_initialized) return true;
_forwardOnly = false; // re-arming in this generation — stop any pass-through latch
_gameHwnd = hWnd;
_uiCaptureEnabled = true;
_hasFocus = false;
@ -208,11 +495,16 @@ internal static unsafe class Win32Backend
_wantCaptureMouse = false;
_wantCaptureKeyboard = false;
_insertWasDown = false;
_swallowEnterTail = false;
// Subclass the window
_wndProcDelegate = WndProcHook;
IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_wndProcDelegate);
_installedWndProcPtr = hookPtr;
_originalWndProc = SetWindowLong32(hWnd, GWL_WNDPROC, hookPtr);
// RynthLog.UI (not .Render — RenderEnabled is false) so chain
// composition across generations is reconstructible from the log.
RynthLog.UI($"Win32Backend: subclass installed — hook=0x{hookPtr:X8}, previous WndProc=0x{_originalWndProc:X8}.");
if (_originalWndProc == IntPtr.Zero)
{
@ -223,15 +515,60 @@ internal static unsafe class Win32Backend
_initialized = true;
RynthLog.Render("Win32Backend: Initialized (WndProc subclassed).");
RynthLog.Render("Win32Backend: UI capture ENABLED by default (Insert to release).");
// A previous engine load may have left floating panels behind (its
// teardown predates the synchronous sweep in Shutdown, or the game
// thread was stalled past the timeout) — clear them now, while
// sparing this load's own.
PostMessage(_gameHwnd, WM_RYNTH_SWEEP_PANELS, IntPtr.Zero, IntPtr.Zero);
return true;
}
private static IntPtr _installedWndProcPtr;
private static volatile bool _forwardOnly;
public static void Shutdown()
{
if (!_initialized) return;
// Restore original WndProc
SetWindowLong32(_gameHwnd, GWL_WNDPROC, _originalWndProc);
// Destroy floating panels while our hook can still run on the game
// thread. LayeredWindow.Dispose only POSTS its destroy, and the game
// thread usually hasn't reached that post by the time we unhook below —
// AC's own WndProc then drops it and the panel outlives this engine
// load, frozen and unclickable (duplicate RynthAi dashboard after RL).
IntPtr swept = SendMessageTimeout(_gameHwnd, WM_RYNTH_SWEEP_PANELS, new IntPtr(1), IntPtr.Zero,
SMTO_NORMAL, 2000, out _);
if (swept == IntPtr.Zero)
RynthLog.Info($"Win32Backend: Shutdown — panel sweep didn't run on the game thread (err={Marshal.GetLastWin32Error()}); the next engine load clears what's left.");
// Restore the original WndProc ONLY if we are still the head of the
// chain. If something subclassed on top of us after Init (Decal /
// DINPUT8 re-hooks, a newer engine generation), a blind restore RIPS
// their hook out of the chain — DirectInput's hook proc then
// dereferences a freed per-window record on AC's main thread and the
// render pump never recovers (the 2026-06-11 DINPUT8+0x20CCC reload
// wedge). Leaving the chain intact is always safe: our thunk stays
// valid because engine module pages are intentionally leaked across
// reloads, and a no-longer-initialized backend just forwards.
IntPtr currentProc = GetWindowLong32(_gameHwnd, GWL_WNDPROC);
if (currentProc == _installedWndProcPtr || currentProc == IntPtr.Zero)
{
SetWindowLong32(_gameHwnd, GWL_WNDPROC, _originalWndProc);
RynthLog.UI("Win32Backend: Shutdown — WndProc restored (we were chain head).");
}
else
{
// Become a pure pass-through instead: a frozen generation that
// keeps PROCESSING input swallows WM_CHAR and kills AC's chat
// after a reload (the historic stacking bug the unconditional
// restore was originally added for). Forward-only keeps the
// foreign chain intact AND keeps this generation inert.
_forwardOnly = true;
// A hit on this line positively confirms a foreign subclasser
// stacks above us in live sessions — the blind-restore wedge's
// missing precondition. Must be visible in the log.
RynthLog.UI($"Win32Backend: Shutdown — chain head is 0x{currentProc:X8}, not ours (0x{_installedWndProcPtr:X8}); leaving the chain intact, hook now forward-only.");
}
lock (_inputLock)
_pendingInput.Clear();
Array.Clear(_mouseButtons, 0, _mouseButtons.Length);
@ -250,6 +587,7 @@ internal static unsafe class Win32Backend
_avIsDragging = false;
_avIsResizing = false;
_avIsButtonCapture = false;
_avPanelMouseDown = false;
ReleaseAvaloniaNativeCapture();
_avDragResidualX = 0;
_avDragResidualY = 0;
@ -268,6 +606,9 @@ internal static unsafe class Win32Backend
public static void NewFrame()
{
// Deferred focus restore: AvaloniaSubclassWndProc sets this flag when
// WM_SETFOCUS lands on the off-screen Avalonia HWND. We reclaim focus
// here (game thread owns _gameHwnd) so there's no cross-thread wait.
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
// Update display size
@ -288,7 +629,7 @@ internal static unsafe class Win32Backend
}
// If GetClientRect returns 0x0 or 1x1, the HWND might be wrong.
// DisplaySize will be set from D3D viewport in ImGuiController instead.
// DisplaySize will be set from D3D viewport in EngineFrameController instead.
if (w > 1 && h > 1)
io.DisplaySize = new System.Numerics.Vector2(w, h);
@ -340,20 +681,274 @@ internal static unsafe class Win32Backend
private static IntPtr WndProcHook(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
// Post-shutdown pass-through: Shutdown could not restore the chain
// (someone subclassed after us) — this generation must be inert.
if (_forwardOnly)
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam);
try
{
_wndProcLogCount++;
// ── Game-thread executor: run a queued Action on this thread ──
// Sent by RunOnGameThread via SendMessage (synchronous, blocks the
// caller until this returns). Keep this near the top — must dispatch
// before any chat / focus / mouse paths so callers waiting on a
// CreateWindowExW etc. aren't stuck behind unrelated input handling.
if (msg == WM_RYNTH_RUN_ACTION)
{
Action? a = _pendingGameThreadAction;
if (a != null)
{
try { a(); }
catch (Exception ex) { RynthLog.Info($"Win32Backend: WM_RYNTH_RUN_ACTION threw {ex.GetType().Name}: {ex.Message}"); }
}
return IntPtr.Zero;
}
if (msg == WM_RYNTH_DESTROY_HWND)
{
IntPtr target = wParam;
try
{
bool destroyed = DestroyWindow(target);
int err = destroyed ? 0 : Marshal.GetLastWin32Error();
RynthLog.Info($"Win32Backend: WM_RYNTH_DESTROY_HWND DestroyWindow(0x{target.ToInt64():X}) = {destroyed} err={err}.");
}
catch (Exception ex) { RynthLog.Info($"Win32Backend: WM_RYNTH_DESTROY_HWND threw {ex.GetType().Name}: {ex.Message}"); }
return IntPtr.Zero;
}
if (msg == WM_RYNTH_SWEEP_PANELS)
{
try { UI.LayeredWindow.DestroyThreadPanelWindows(includeThisGeneration: wParam != IntPtr.Zero); }
catch (Exception ex) { RynthLog.Info($"Win32Backend: WM_RYNTH_SWEEP_PANELS threw {ex.GetType().Name}: {ex.Message}"); }
return IntPtr.Zero;
}
// Diag (diag/logoff-origin): ring of recent key/click/focus/close messages,
// dumped when the client requests a logoff. Filters first; never throws.
Compatibility.LogoffOriginProbe.RecordWndMsg(msg, wParam, lParam, synthetic: false);
// ── User clicked X / Alt+F4 on AC window — tear our overlay down NOW ──
// AC's own shutdown takes 20-30 s (network logout, save, etc.) before
// it finally calls ExitProcess and triggers ProcessExitHooks. During
// that gap EndScene keeps firing and the floating LayeredWindows
// (RynthAi panel etc.) stay visible on the OS desktop, which looks
// like the overlay is "stuck up" long after the close click. Running
// EngineLifecycle.Shutdown here uninstalls the EndScene hook and
// closes every floating panel immediately; the later ExitProcess
// detour is a no-op (interlocked guard inside Shutdown). Run on a
// background thread so the join on the Avalonia STA doesn't block
// AC's own message pump during its shutdown.
if (msg == WM_CLOSE && Interlocked.Exchange(ref _wmCloseSeen, 1) == 0)
{
RynthLog.UI("Win32Backend: WM_CLOSE on AC window — quiescing plugin pump, then kicking engine shutdown.");
// AC is about to free the ClientUISystem singleton — drop the
// busy watchdog's cached pointer so no force-clear can run
// against freed memory during the teardown window.
try { Compatibility.BusyCountHooks.ResetSession(); }
catch { }
// Stop the off-thread plugin pump FIRST, synchronously, on AC's main
// thread — we run here BEFORE falling through to AC's own WndProc (which
// starts AC's object teardown). The pump's in-flight frame finishes on
// still-valid AC objects and then it exits; otherwise it keeps ticking
// into DestroyObjectCaches and races AC's frees -> the recurring on-close
// AVs (BusyCountHooks.ForceResetBusyCount / PlayerPhysicsHooks.TryGetPlayerPose
// -> AC, e.g. acclient+0x16547B null+0x1C; EIP->heap). Bounded ~2s inside
// StopTickPumpAndJoin; the background EngineLifecycle.Shutdown below then
// finds the pump already stopped (its TickPump.StopAndJoin is a no-op).
try { EntryPoint.StopTickPumpAndJoin(); }
catch (Exception ex) { RynthLog.UI($"Win32Backend: WM_CLOSE pump-stop threw {ex.GetType().Name}: {ex.Message}"); }
new Thread(() =>
{
try { EngineLifecycle.Shutdown(); }
catch (Exception ex) { RynthLog.UI($"Win32Backend: WM_CLOSE shutdown threw {ex.GetType().Name}: {ex.Message}"); }
})
{ Name = "RynthCore.WmCloseShutdown", IsBackground = true }.Start();
// Fall through to AC's original WndProc so AC starts its own
// shutdown sequence in parallel with ours.
}
// ── Once close is in flight, stop feeding mouse/cursor input to AC ──
// After WM_CLOSE, AC tears down its world — including the combat-system
// singleton. AC's ClientUISystem::UpdateCursorState (acclient 0x005653D0)
// runs on every mouse-move / cursor refresh and dereferences
// GetCombatSystem()->[+0x1C]; once the singleton is freed that's an AV at
// acclient 0x0056547B reading [null+0x1C]. The user is actively moving the
// mouse toward the close control, so a trailing WM_MOUSEMOVE / WM_SETCURSOR
// lands right after the free. THIS subclass is the one installed on the
// game window (AvaloniaSubclassWndProc carries a matching block, but it is
// installed on the off-screen Avalonia HWND and never sees AC's mouse
// traffic). WM_CLOSE / WM_DESTROY / paint still fall through so the window
// closes normally.
if (Volatile.Read(ref _wmCloseSeen) != 0)
{
switch (msg)
{
case WM_MOUSEMOVE:
case WM_NCMOUSEMOVE:
case WM_MOUSEWHEEL:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
return IntPtr.Zero;
case WM_SETCURSOR:
return (IntPtr)1; // handled — halt AC's cursor-update chain
}
}
// ── Chat capture: consume all key input for the chat TextBox ────
// Game HWND keeps Win32 focus throughout; callbacks dispatch Text
// updates to the panel on Avalonia's UI thread — no Avalonia focus needed.
if (ChatCaptureActive && IsKeyMessage(msg))
{
if (msg == WM_CHAR)
{
int ch = (int)wParam;
if (ch >= 0x20) // printable characters only
OnChatChar?.Invoke((char)ch);
}
else if (msg == WM_KEYDOWN)
{
int vk = (int)wParam;
if (vk == VK_RETURN && !IsExtendedKey(lParam)) { ChatCaptureActive = false; _swallowEnterTail = true; PostMessage(_gameHwnd, WM_RYNTHCORE_CHAT, IntPtr.Zero, IntPtr.Zero); }
else if (vk == VK_ESCAPE) { ChatCaptureActive = false; _swallowEnterTail = true; OnChatCancel?.Invoke(); }
else if (vk == VK_BACK) { OnChatBackspace?.Invoke(); }
else if (vk == VK_DELETE) { OnChatDelete?.Invoke(); }
else if (vk == VK_LEFT) { OnChatLeft?.Invoke(); }
else if (vk == VK_RIGHT) { OnChatRight?.Invoke(); }
else if (vk == VK_HOME) { OnChatHome?.Invoke(); }
else if (vk == VK_END) { OnChatEnd?.Invoke(); }
else if (vk == VK_UP) { OnChatUp?.Invoke(); }
else if (vk == VK_DOWN) { OnChatDown?.Invoke(); }
}
return IntPtr.Zero; // eat all key messages while chat is active
}
// ── Swallow the tail of the send/cancel keystroke ─────────────
// The block above ends chat capture on VK_RETURN/VK_ESCAPE but eats
// only the WM_KEYDOWN. The OS still delivers the matching WM_CHAR
// ('\r') and WM_KEYUP; with ChatCaptureActive now false they'd fall
// through to the game, and a lone '\r' can spuriously re-open AC's
// native chat bar (which then sits open, hidden by suppress, eating
// input until it resets — a multi-second dead window for chat).
if (_swallowEnterTail)
{
if (msg == WM_CHAR)
return IntPtr.Zero;
if ((msg == WM_KEYUP || msg == WM_SYSKEYUP) &&
((int)wParam == VK_RETURN || (int)wParam == VK_ESCAPE) &&
!IsExtendedKey(lParam))
{
_swallowEnterTail = false;
return IntPtr.Zero;
}
if (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN)
_swallowEnterTail = false; // a new keystroke began; stop guarding
}
// ── Deferred chat send ────────────────────────────────────────
// The send Enter (handled above) posts WM_RYNTHCORE_CHAT instead of
// dispatching inline. We fire OnChatSend here, on a *fresh* game-thread
// message dispatch — after the Enter's WM_CHAR/WM_KEYUP tail has been
// consumed and outside the original keystroke's WndProc frame. This
// matters because OnChatSend → RynthChatSendLine → ChatCommandDispatcher
// .SimulateChatInput drives CallWindowProcA back into AC's window proc;
// doing that reentrantly inside the Enter keystroke left AC's chat bar
// misaligned after the first send ("worked once, then stopped"). The
// dispatch must stay on the game thread (it owns the window), so a posted
// message — not a worker-thread tick — is the right deferral.
if (msg == WM_RYNTHCORE_CHAT)
{
OnChatSend?.Invoke();
return IntPtr.Zero;
}
if (msg == WM_RYNTHCORE_TELL)
{
OnChatTellSelected?.Invoke();
return IntPtr.Zero;
}
// ── Chat: Enter in-game activates the chat TextBox ───────────
// Numpad Enter (extended key, lParam bit 24) is reserved for AC functions — never capture it.
// !AvaloniaTextInputActive: while the user is typing in a docked
// panel TextBox this branch otherwise runs BEFORE the text-input
// forwarding block and hijacks Enter into chat capture — stealing
// the TextBox's own commit handler and every subsequent keystroke.
// RynthChatOwnsChat: only while RynthChat is open AND hiding the retail chatbox —
// whichever chat is visible gets Enter. Otherwise Enter belongs to AC's own chat,
// which used to be unusable whenever RynthChat was installed, even closed.
if (msg == WM_KEYDOWN && (int)wParam == VK_RETURN && !IsExtendedKey(lParam) && !ChatCaptureActive && !AvaloniaTextInputActive
&& RynthCore.Engine.Compatibility.ChatHooks.RynthChatOwnsChat)
{
if (OnChatCaptureActivated != null)
{
ChatCaptureActive = true;
OnChatCaptureActivated.Invoke();
return IntPtr.Zero;
}
}
// ── Restore focus to game when Avalonia acquires it ───────────
if (msg == WM_RYNTH_RESTORE_FOCUS)
{
IntPtr prev = SetFocus(_gameHwnd);
IntPtr fg = GetForegroundWindow();
RynthLog.Info($"Win32Backend: WM_RYNTH_RESTORE_FOCUS → SetFocus(gameHwnd) prev=0x{prev.ToInt64():X} fg=0x{fg.ToInt64():X} game=0x{_gameHwnd.ToInt64():X}.");
return IntPtr.Zero;
}
// ── Diag: game-window focus transitions (driven by clicks on Avalonia panels) ──
if (msg == WM_SETFOCUS)
RynthLog.Info($"Win32Backend: game WM_SETFOCUS (from hwnd=0x{wParam.ToInt64():X} {DescribeHwnd(wParam)}).");
else if (msg == WM_KILLFOCUS)
RynthLog.Info($"Win32Backend: game WM_KILLFOCUS (to hwnd=0x{wParam.ToInt64():X} {DescribeHwnd(wParam)}).");
// ── Vital HUD drag/resize ─────────────────────────────────────
// Give the custom vital-bar HUD first crack at mouse input: a click
// landing on it moves/resizes the HUD and is swallowed so it never
// reaches AC (no camera spin) or the Avalonia panels. Placed before
// the ImGui EnqueueInput/capture-eat below so ImGui never tracks the
// HUD drag (keeps our SetCapture from fighting NewFrame's). No-op
// unless the HUD is drawn.
if (IsMouseMessage(msg) && VitalHud.TryHandleMouse(hWnd, msg, wParam, lParam))
return IntPtr.Zero;
// ── Avalonia panel hit-test & input forwarding ────────────────
if (IsMouseMessage(msg))
// Only in the world: between characters the overlay isn't drawn, so its
// panels mustn't take clicks meant for character select.
bool overlayLive = RynthCore.Engine.Compatibility.LoginLifecycleHooks.HasObservedLoginComplete;
if (!overlayLive)
{
// fall through: AC gets the message
}
else if (IsMouseMessage(msg))
{
bool handled = TryForwardToAvalonia(msg, wParam, lParam);
if (handled)
return IntPtr.Zero;
}
else if (IsKeyMessage(msg) && _avaloniaHasMouse)
else if (IsKeyMessage(msg) && AvaloniaTextInputActive)
{
// Keyboard goes to Avalonia only while the cursor is over the panel.
// Keys go to Avalonia only when a TextBox actually holds keyboard focus.
// Gating on mouse-hover instead was wrong: a held game key whose KEYUP
// landed while the cursor was over a panel got swallowed, leaving AC's
// edge-driven input state latched (character kept moving until the user
// tapped again with the mouse elsewhere).
//
// CRITICAL: forward only WM_KEYDOWN/WM_KEYUP (and SYS variants). Do NOT
// forward WM_CHAR — Avalonia's own message pump calls TranslateMessage on
// the WM_KEYDOWN we just posted and synthesises its own WM_CHAR. If we
// also post WM_CHAR directly, Avalonia receives the character twice and
// every keypress shows up doubled in TextBoxes.
if (msg == WM_CHAR)
return IntPtr.Zero;
IntPtr avHwnd = AvaloniaOverlay.AvaloniaHwnd;
if (avHwnd != IntPtr.Zero)
{
@ -364,6 +959,8 @@ internal static unsafe class Win32Backend
}
// ─────────────────────────────────────────────────────────────
// Only enqueue if we did NOT already forward to Avalonia above.
// (When AvaloniaTextInputActive is true and a key fires, we returned early.)
if (IsMouseMessage(msg) || IsKeyMessage(msg) || IsFocusMessage(msg))
EnqueueInput(msg, wParam, lParam);
@ -380,10 +977,12 @@ internal static unsafe class Win32Backend
return CallWindowProcA(_originalWndProc, hWnd, msg, (IntPtr)1, lParam);
// WM_ACTIVATE WA_INACTIVE fires when focus moves to another window in the SAME
// process (e.g. an ImGui viewport popup). WM_ACTIVATEAPP doesn't fire in that case,
// so AC would see its window go inactive and may idle-throttle its render loop.
// Intercept and lie: tell AC its window is still active.
if (msg == WM_ACTIVATE && EndSceneHook.FpsLimitEnabled)
// process (e.g. an ImGui viewport popup, the DComp overlay bar). WM_ACTIVATEAPP
// doesn't fire in that case, so AC would see its window go inactive and idle-
// throttle its render loop. Always intercept same-process activations — this is
// unconditionally correct for an injected overlay and must not be gated on
// FpsLimitEnabled (DComp overlay clicks cause 8fps without this fix).
if (msg == WM_ACTIVATE)
{
int activationCode = (int)((long)wParam & 0xFFFF);
if (activationCode == WA_INACTIVE && lParam != IntPtr.Zero)
@ -473,6 +1072,12 @@ internal static unsafe class Win32Backend
AvaloniaOverlay.ActivateBarButton(releasedButtonTitle!);
}
// Persist bar position on drag-end. All the live moves were
// applied via MoveBarByPhys; CommitDrag(0,0) saves the final
// canvas position without applying any additional delta.
if (_avIsDragging)
AvaloniaOverlay.CommitDrag(0, 0);
AvaloniaOverlay.IsDragInProgress = false;
_avIsDragging = false;
_avIsResizing = false;
@ -519,16 +1124,62 @@ internal static unsafe class Win32Backend
_avaloniaHasMouse = over;
}
// While the left button is held down on a panel, keep forwarding
// even if the cursor wanders off the panel rect — Avalonia's drag
// handler needs uninterrupted PointerMoved + PointerReleased to
// commit/release the drag. The latch clears on WM_LBUTTONUP.
if (_avPanelMouseDown)
{
_lastPanelClientX = overlayPoint.X;
_lastPanelClientY = overlayPoint.Y;
AvaloniaMessagePoint heldPoint = ClientToAvaloniaMessagePoint(overlayPoint.X, overlayPoint.Y);
_lastAvaloniaMessageX = heldPoint.X;
_lastAvaloniaMessageY = heldPoint.Y;
PostOverlayMouseMessage(avHwnd, msg, wParam, heldPoint.X, heldPoint.Y);
if (msg == WM_LBUTTONUP)
{
_avPanelMouseDown = false;
AvaloniaOverlay.SetDockedPanelPointerCaptureActive(false);
}
if (msg != WM_MOUSEMOVE || AvaloniaOverlay.ShouldUseCustomSkiaProducer)
AvaloniaOverlay.RequestCapture();
return true;
}
if (!over)
{
if (msg == WM_LBUTTONUP)
_pendingBarButtonTitle = null;
// An open Flyout / ContextMenu / dropdown is embedded in the
// overlay window, but a click on the game world is never
// forwarded, so Avalonia's light-dismiss never sees it. Close
// it here; the click still goes to AC.
if ((msg == WM_LBUTTONDOWN || msg == WM_RBUTTONDOWN || msg == WM_MBUTTONDOWN)
&& AvaloniaOverlay.HasOpenLightDismissPopup)
{
AvaloniaOverlay.DismissLightDismissPopups();
}
return false;
}
_lastPanelClientX = overlayPoint.X;
_lastPanelClientY = overlayPoint.Y;
// A docked press is starting (over a docked panel/bar). Assert no
// floating panel is still marked as the shared-HWND SetCapture
// coordinate owner: a stale FloatingPanelHost.PointerCapturingHost
// (left set when a floating WM_LBUTTONUP never reached
// AvaloniaSubclassWndProc — swallowed by the DockedPanelPointer-
// CaptureActive early-return, or a redock/close mid-press) would
// make this docked interaction's capture-routed move/release get
// remapped into the floating panel's off-bounds space — the docked
// click is eaten / needs a double-click. A WM_LBUTTONDOWN means the
// button was up before, so any prior floating press already ended;
// clearing here cannot truncate a live floating interaction.
if (msg == WM_LBUTTONDOWN)
FloatingPanelHost.PointerCapturingHost = null;
if (AvaloniaOverlay.TryGetBarButtonTitleAt(overlayPoint.X, overlayPoint.Y, out string? barButtonTitle))
{
if (msg == WM_LBUTTONDOWN)
@ -627,8 +1278,17 @@ internal static unsafe class Win32Backend
_lastAvaloniaMessageX = messagePoint.X;
_lastAvaloniaMessageY = messagePoint.Y;
if (msg == WM_LBUTTONDOWN)
{
LogAvaloniaPointerDebug("forward-down", cx, cy, overlayPoint.X, overlayPoint.Y, messagePoint.X, messagePoint.Y);
_avPanelMouseDown = true;
AvaloniaOverlay.SetDockedPanelPointerCaptureActive(true);
}
PostOverlayMouseMessage(avHwnd, msg, wParam, messagePoint.X, messagePoint.Y);
if (msg == WM_LBUTTONUP)
{
_avPanelMouseDown = false;
AvaloniaOverlay.SetDockedPanelPointerCaptureActive(false);
}
if (msg != WM_MOUSEMOVE || AvaloniaOverlay.ShouldUseCustomSkiaProducer)
AvaloniaOverlay.RequestCapture();
return true;
@ -799,7 +1459,10 @@ internal static unsafe class Win32Backend
private static void LogAvaloniaPointerDebug(string phase, int clientX, int clientY, int overlayX, int overlayY, int? messageX = null, int? messageY = null)
{
// Suppressed — these diagnostics are no longer needed for stable operation.
if (messageX.HasValue)
RynthLog.Info($"AvaloniaPtr [{phase}] client=({clientX},{clientY}) overlay=({overlayX},{overlayY}) msg=({messageX},{messageY}).");
else
RynthLog.Info($"AvaloniaPtr [{phase}] client=({clientX},{clientY}) overlay=({overlayX},{overlayY}).");
}
private static void AcquireAvaloniaNativeCapture()
@ -820,10 +1483,28 @@ internal static unsafe class Win32Backend
_avHasNativeCapture = false;
}
// UI deep-dive finding P0-2 / TL;DR #2 (2026-07-02): every mouse/key/
// focus message was enqueued here unconditionally, all session, but
// FlushQueuedInput only ever drains it from inside the ImGui NewFrame
// path (line ~599 above) — which never runs when EngineSettings.
// EnableImGuiBackend is false (the daily-driver config: "Avalonia-only"
// mode, bar + plugin ImGui hidden). Tens to hundreds of MB accumulate
// over a session on this stack's 32-bit VA budget. Guard on the backend
// actually running; cap regardless as defense-in-depth (e.g. a brief
// startup window before the flag is known, or a future caller).
private const int MaxPendingInput = 4096;
private static void EnqueueInput(uint msg, IntPtr wParam, IntPtr lParam)
{
if (!RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend)
return;
lock (_inputLock)
{
if (_pendingInput.Count >= MaxPendingInput)
_pendingInput.Dequeue(); // drop oldest — a stale mouse-move/key is harmless to lose
_pendingInput.Enqueue(new QueuedInputMessage(msg, wParam, lParam));
}
}
private static void FlushQueuedInput(ImGuiIOPtr io)