Fix logout crash, add OnLogout plugin export, and read true buffed skill

The long-standing "DX9 error / client crash on logout" was ChatHooks.TickHide
calling SetVisible() on a stale gmMainChatUI pointer that AC frees during the
world-to-charselect transition. TickHide now gates on HasObservedLoginComplete
and the cached instance is reset in DispatchPendingLogout. CrashLogger gained a
register dump + EBP-frame walk + ESP sweep with module resolution that made
this trace possible.

Plugin contract bumped to v57 with optional RynthPluginOnLogout export.
LogoutLifecycleHooks hooks CPlayerSystem::ExecuteLogOff (fires after the user
confirms the logoff prompt — not RecvNotice_EndCharacterSession which fires on
the menu click before the prompt) plus RecvNotice_Logoff as fallback.
RynthCoreShell + PluginManager.RenderAll gate on HasObservedLoginComplete so
the bar/plugins hide between sessions.

ClientObjectHooks.TryGetObjectSkill now calls CACQualities::InqSkill(raw=0)
for the truly buffed skill — the old code returned InitialLevel +
LevelFromPracticePoints which is just the base trained level, missing
attribute / augmentation / spell-buff contributions.

CharacterCaptureHooks latches _autoLoginEverFired so manual logout doesn't
re-fire auto-login from the next 0xF658 packet. AccountProfileDialog drops
the now-redundant Character/Slot field. UpdateObjectInventoryHooks pack scan
also matches by wielderID so wielded items are picked up.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
tombohar 2026-04-25 23:36:56 -04:00
commit 8260c60494
17 changed files with 539 additions and 125 deletions

View file

@ -61,6 +61,14 @@ internal static class CharacterCaptureHooks
private static int _autoLoginScheduled;
// Latches once auto-login has fired in this process. The character-list packet
// (0xF658) arrives every time the client sees char-select — including the
// logout-to-char-select transition — and without this latch we'd re-trigger
// auto-login the moment the user manually logs out. One-shot per process: if
// the user wants to swap characters, they can pick from char-select manually,
// or relaunch.
private static int _autoLoginEverFired;
public static void ProcessPotentialCharacterMessage(IntPtr blob, bool isGameEvent = false)
{
if (blob == IntPtr.Zero)
@ -269,6 +277,15 @@ internal static class CharacterCaptureHooks
if (string.IsNullOrWhiteSpace(targetCharacter))
return;
// One-shot per process: if auto-login already fired (and the user has
// since logged back out), don't re-trigger. This keeps a manual logout
// from instantly re-logging the same character.
if (Interlocked.CompareExchange(ref _autoLoginEverFired, 1, 0) != 0)
{
RynthLog.Verbose($"CharacterCapture: Auto-login already fired this session — skipping for '{targetCharacter}'.");
return;
}
if (Interlocked.Exchange(ref _autoLoginScheduled, 1) != 0)
return;

View file

@ -117,6 +117,17 @@ internal static class ChatHooks
/// </summary>
public static unsafe void TickHide()
{
// CRITICAL: do not call SetVisible while AC is between in-world sessions.
// _gmMainChatInstance points at AC's gmMainChatUI singleton, which AC
// frees during the logout-to-charselect transition. Calling SetVisible
// on the freed pointer dereferences a stale vtable (filled with reused
// float/zero data) and AVs inside UIElement::IsVisible. We resume the
// assertion only after the next SendLoginCompleteNotification, by which
// time AC has rebuilt gmMainChatUI and ListenDetour has re-captured the
// fresh pointer.
if (!LoginLifecycleHooks.HasObservedLoginComplete)
return;
IntPtr inst = _gmMainChatInstance;
if (inst == IntPtr.Zero) return;
@ -142,4 +153,16 @@ internal static class ChatHooks
_isHiddenAsserted = false;
}
}
/// <summary>
/// Drops the cached <c>gmMainChatUI</c> singleton pointer. Called from the
/// logout pipeline so we don't reuse a freed pointer after the next login —
/// <see cref="ListenDetour"/> re-captures the fresh instance on the next
/// chat-UI message dispatch.
/// </summary>
public static void ResetCachedInstance()
{
_gmMainChatInstance = IntPtr.Zero;
_isHiddenAsserted = false;
}
}

View file

@ -561,14 +561,29 @@ internal static class ClientObjectHooks
return false;
training = unchecked((int)skill.AdvancementClass);
buffed = unchecked((int)(skill.InitialLevel + skill.LevelFromPracticePoints));
// Use CACQualities::InqSkill(stype, retval, raw=0) for the FULL buffed
// skill — that includes attribute contribution, augmentations, and
// spell-buff enchantments. The raw struct fields (InitialLevel +
// LevelFromPracticePoints) only give the base trained level and miss
// everything else, which is why this used to return ~208 for a
// character whose true buffed Creature Enchantment was 360+.
int rawBase = unchecked((int)(skill.InitialLevel + skill.LevelFromPracticePoints));
int trulyBuffed = rawBase;
if (_inqSkillLevel != null)
{
int retval = 0;
if (_inqSkillLevel(qualitiesPtr, skillStype, &retval, 0) != 0)
trulyBuffed = retval;
}
buffed = trulyBuffed;
if (_skillProbeLogCount < 6)
{
_skillProbeLogCount++;
RynthLog.Verbose(
$"Compat: skillTableProbe obj=0x{objectId:X8} skill={skillStype} qualities=0x{qualitiesPtr.ToInt32():X8} " +
$"table=0x{skillTablePtr.ToInt32():X8} buckets={tableSize} training={training} base={buffed}");
$"table=0x{skillTablePtr.ToInt32():X8} buckets={tableSize} training={training} base={rawBase} buffed={buffed}");
}
return true;

View file

@ -92,6 +92,18 @@ internal static class LoginLifecycleHooks
}
}
/// <summary>
/// Clears the one-shot observation flag so the next <c>SendLoginCompleteNotification</c>
/// raises <see cref="LoginComplete"/> again. Called by the logout pipeline so the
/// following login (e.g. swapping characters) re-runs login-gated startup.
/// </summary>
public static void ResetObservation()
{
HasObservedLoginComplete = false;
_statusMessage = "Awaiting next SendLoginCompleteNotification.";
_waitingLogged = false;
}
public static void Poll()
{
if (HasObservedLoginComplete || !IsInstalled)

View file

@ -0,0 +1,168 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Hooks the moments when the AC client commits to ending the in-world session, so the
/// engine can close its UI gate before AC starts rebuilding its UIElement tree —
/// touching world data while AC is mid-teardown crashes the client.
///
/// We hook both:
/// - <c>CPlayerSystem::ExecuteLogOff(void)</c> — fires when the player has confirmed
/// the logoff prompt and the actual logoff begins. This is the earliest reliable
/// "we're committed to leaving the world" signal. (NOT
/// <c>gmGamePlayUI::RecvNotice_EndCharacterSession</c> — that fires when the user
/// clicks the Exit-to-Character-Selection menu item, BEFORE the confirmation
/// prompt; if we close the UI there and the user clicks "No" on the prompt, the
/// overlay is hidden while gameplay continues.)
/// - <c>gmGamePlayUI::RecvNotice_Logoff(void)</c> — server-driven full logoff
/// notice. Belt-and-braces in case ExecuteLogOff is bypassed in some flow.
///
/// Either one raises <see cref="LogoutComplete"/> once per logout cycle.
///
/// Public symbol addresses taken from Chorizite's acclient.map:
/// - CPlayerSystem::ExecuteLogOff: file offset 0x0015D4A0, VA 0x0055E4A0
/// - RecvNotice_Logoff: file offset 0x000EBBA0, VA 0x004ECBA0
/// (Standard 0x56D000 acclient.exe build.)
/// </summary>
internal static class LogoutLifecycleHooks
{
private const int ExpectedImageSize = 0x56D000;
private const int ExecuteLogOffFileOffset = 0x0015D4A0;
private const int RecvNoticeLogoffFileOffset = 0x000EBBA0;
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void ThisCallVoidDelegate(IntPtr thisPtr);
private static ThisCallVoidDelegate? _originalExecuteLogOff;
private static ThisCallVoidDelegate? _executeLogOffDetour;
private static IntPtr _executeLogOffAddress;
private static ThisCallVoidDelegate? _originalRecvNoticeLogoff;
private static ThisCallVoidDelegate? _recvNoticeLogoffDetour;
private static IntPtr _logoffAddress;
private static string _statusMessage = "Not probed yet.";
public static bool IsInstalled { get; private set; }
public static bool HasObservedLogout { get; private set; }
public static string StatusMessage => _statusMessage;
/// <summary>Fires once per logout cycle, after the first observed logout signal returns from its original.</summary>
public static event Action? LogoutComplete;
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
int imageSize = textSection.ImageSize;
if (imageSize != ExpectedImageSize)
RynthLog.Compat($"Compat: logout lifecycle hook using unverified acclient image size 0x{imageSize:X} (expected 0x{ExpectedImageSize:X}).");
bool anyHooked = false;
anyHooked |= TryInstallHook(textSection, ExecuteLogOffFileOffset, ExecuteLogOffDetour,
out _executeLogOffAddress, out _executeLogOffDetour, out _originalExecuteLogOff,
"CPlayerSystem::ExecuteLogOff");
anyHooked |= TryInstallHook(textSection, RecvNoticeLogoffFileOffset, RecvNoticeLogoffDetour,
out _logoffAddress, out _recvNoticeLogoffDetour, out _originalRecvNoticeLogoff,
"gmGamePlayUI::RecvNotice_Logoff");
if (anyHooked)
{
IsInstalled = true;
RynthLog.Compat($"Compat: logout lifecycle hook ready - ExecuteLogOff=0x{_executeLogOffAddress.ToInt32():X8} Logoff=0x{_logoffAddress.ToInt32():X8}");
}
}
private static bool TryInstallHook(
AcClientTextSection textSection, int fileOffset, ThisCallVoidDelegate detour,
out IntPtr address, out ThisCallVoidDelegate detourField, out ThisCallVoidDelegate? original,
string name)
{
try
{
address = new IntPtr(textSection.TextBaseVa + fileOffset);
detourField = detour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(detourField);
original = Marshal.GetDelegateForFunctionPointer<ThisCallVoidDelegate>(MinHook.HookCreate(address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(address);
_statusMessage = $"Hooked {name} @ 0x{address.ToInt32():X8}.";
return true;
}
catch (Exception ex)
{
address = IntPtr.Zero;
detourField = detour;
original = null;
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: {name} hook failed - {ex.Message}");
return false;
}
}
/// <summary>Resets the observation flag so the next logout-class notice fires <see cref="LogoutComplete"/> again.</summary>
public static void ResetObservation()
{
HasObservedLogout = false;
}
private static void ExecuteLogOffDetour(IntPtr thisPtr)
{
if (!HasObservedLogout)
RynthLog.Compat("Compat: CPlayerSystem::ExecuteLogOff detour entered.");
try { _originalExecuteLogOff!(thisPtr); }
catch { /* original must run */ }
RaiseLogoutCompleteOnce("CPlayerSystem::ExecuteLogOff");
}
private static void RecvNoticeLogoffDetour(IntPtr thisPtr)
{
if (!HasObservedLogout)
RynthLog.Compat("Compat: RecvNotice_Logoff detour entered.");
try { _originalRecvNoticeLogoff!(thisPtr); }
catch { /* original must run */ }
RaiseLogoutCompleteOnce("gmGamePlayUI::RecvNotice_Logoff");
}
/// <summary>
/// Either notice may fire first (a session may receive both — ExecuteLogOff at
/// commit, RecvNotice_Logoff later from the server). Only the first one in a
/// logout cycle should drive the dispatch — subsequent ones are no-ops until
/// <see cref="ResetObservation"/> runs after the next login.
/// </summary>
private static void RaiseLogoutCompleteOnce(string source)
{
if (HasObservedLogout)
return;
HasObservedLogout = true;
_statusMessage = $"Logout observed via {source}.";
RynthLog.Compat($"Compat: logout observed via {source} — raising LogoutComplete.");
// Subscribers MUST keep their handler short — this fires on AC's UI thread.
// Long work (plugin teardown, disposing world data, etc.) must be deferred to
// the EndScene queue.
try { LogoutComplete?.Invoke(); }
catch (Exception ex)
{
RynthLog.Compat($"Compat: LogoutComplete handler threw {ex.GetType().Name}: {ex.Message}");
}
}
}

View file

@ -178,9 +178,12 @@ internal static class UpdateObjectInventoryHooks
}
/// <summary>
/// Scan a range of object IDs, calling GetWeenieObject for each, and return
/// those whose containerID matches the target. This discovers items that were
/// created before the plugin loaded (e.g. pack contents at login).
/// Scan a range of object IDs and return those owned by the target container —
/// either as a contained child (containerID match) OR as a wielded child
/// (wielderID match). PublicWeenieDesc stores those as separate fields, so
/// matching only on containerID misses wielded items (weapons, armor, ammo).
/// Returning both keeps the plugin's container walk a single authoritative
/// list of "everything the player owns right now."
/// </summary>
private static int ScanByContainerId(uint containerId, Span<uint> itemIds)
{
@ -190,9 +193,9 @@ internal static class UpdateObjectInventoryHooks
for (uint id = 0x80000001; id <= 0x8000FFFF && written < itemIds.Length; id++)
{
if (id == containerId) continue;
if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint cid, out _, out _))
if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint cid, out uint wid, out _))
continue;
if (cid == containerId)
if (cid == containerId || wid == containerId)
itemIds[written++] = id;
}