merge: bring feat/full-installer into SK-local

Integrates the aelrynth snapshot port (main), the full installer, the
tmds.dbus advisory fix and all launcher/engine work into SK-local.

Conflict resolutions:
- Logging: keep SK-local's level-based logging (EngineLogLevel, ShouldLog,
  engine.json LoggingLevel) and adopt full-installer's tagged WRN/ERR,
  LastIssue and per-PID logs; the Desktop rolling log is superseded.
- Launcher: keep the inject-all-sessions toggle and Logging level combo
  alongside the new stagger/crash-relaunch/stuck-client options; the
  LoggingLevel is now written through EngineJsonStore.SetString.
- PluginManager: keep SK-local's basename/canonical-path de-duplication,
  drop the default-directory scan (opt-in via PluginPaths).
- Injector, installer, CI workflow, BUILD.md: take full-installer.
- Solution: add DesktopLog + Loader, drop the stale Plugins/RynthAi stub.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
BlankenshipG 2026-10-04 16:16:24 -04:00
commit 36ffa94252
256 changed files with 62130 additions and 3382 deletions

View file

@ -13,6 +13,17 @@ internal static class EngineSettings
"engine.json");
private static List<string> _pluginPaths = new();
private static bool _enableImGuiShell = true;
private static bool _enablePlugins = true;
private static bool _enableDatShareHook = true;
private static bool _enableAvaloniaOverlay = true;
private static bool _enableD3D9Hook = true;
private static bool _enableEngine = true;
private static int _engineHookCount = int.MaxValue;
private static bool _enableImGuiBackend = true;
private static bool _enableHangMinidump = true;
private static bool _drawCustomVitalBars = true;
private static bool _preventIdleLogoff = true;
private static string _loggingLevel = "Info";
private static bool _loaded;
@ -25,6 +36,167 @@ internal static class EngineSettings
}
}
/// <summary>Force-disabled in code: RynthCore's in-AC UI is the Avalonia overlay, so the
/// ImGui shell (RynthCoreShell bar + plugin ImGui windows) never renders. engine.json and
/// the launcher Plugins tab can no longer toggle this; the persisted field is now a no-op.
/// A developer can opt back in for debugging by setting env var RYNTHCORE_FORCE_IMGUI=1
/// before launching AC — normal users never set this.</summary>
public static bool EnableImGuiShell
=> string.Equals(
System.Environment.GetEnvironmentVariable("RYNTHCORE_FORCE_IMGUI"),
"1", System.StringComparison.Ordinal);
/// <summary>When false, PluginManager.LoadPlugins is skipped so no plugin DLLs load,
/// init, tick, or render. Decal-coexistence plugin pump is also skipped. Default true.</summary>
public static bool EnablePlugins
{
get
{
EnsureLoaded();
return _enablePlugins;
}
}
/// <summary>When false, DatFileShareHooks.Initialize is skipped so kernel32!CreateFileA/W
/// are NOT detoured and no DAT-extension access/share rewriting happens. Multi-client DAT
/// coexistence with Decal-injected clients sharing the same install will fall back to the
/// stricter share semantics those clients negotiated. Default true. Use to isolate the
/// hook for crash diagnostics.</summary>
public static bool EnableDatShareHook
{
get
{
EnsureLoaded();
return _enableDatShareHook;
}
}
/// <summary>When false, AvaloniaOverlay.Start() is skipped so the Avalonia STA thread,
/// the offscreen overlay window, and all OverlayHost-registered panels never instantiate.
/// Eliminates the entire Avalonia/Skia surface from the process. Compatibility hooks and
/// (when enabled) plugins still load. Default true. Use to confirm whether the engine
/// runs cleanly without Avalonia.</summary>
public static bool EnableAvaloniaOverlay
{
get
{
EnsureLoaded();
return _enableAvaloniaOverlay;
}
}
/// <summary>When false, D3D9Bootstrapper.Start() is skipped at LoginComplete so neither
/// Direct3DCreate9/CreateDevice nor IDirect3DDevice9::EndScene get hooked. Eliminates the
/// entire D3D9 detour path, ImGui per-frame work, and the in-AC overlay bar. Compatibility
/// hooks and Avalonia (when enabled) still run. Default true. Use to confirm whether the
/// engine runs cleanly without the EndScene detour.</summary>
public static bool EnableD3D9Hook
{
get
{
EnsureLoaded();
return _enableD3D9Hook;
}
}
/// <summary>When false, InitWorker installs no Compatibility/* hooks, no
/// LoginLifecycleHooks subscriber chain, no OverlayHost panels, no Avalonia,
/// no D3D9. Only the early items (CrashLogger, ProcessExitHooks,
/// MultiClientHooks, DatFileShareHooks, HeartbeatLogger) that fire before
/// InitWorker stay active. Use to confirm whether the recursive AV is in
/// the engine's main hook path or in something earlier (loader, NativeAOT
/// runtime, MultiClientHooks/DatFileShareHooks).</summary>
public static bool EnableEngine
{
get
{
EnsureLoaded();
return _enableEngine;
}
}
/// <summary>Cap on how many of InitWorker's RunInitStep calls actually fire.
/// Default = int.MaxValue (= install all 36). Set to 18 to install only the
/// first half, 9 for the first quarter, etc — use for binary-search
/// bisection of which Compatibility hook is causing the recursive AV.
/// Has no effect if EnableEngine is false.</summary>
public static int EngineHookCount
{
get
{
EnsureLoaded();
return _engineHookCount;
}
}
/// <summary>When false, EngineFrameController.OnEndScene skips its
/// ImGui-specific block (Win32Backend.NewFrame, DX9Backend.NewFrame,
/// ImGui.NewFrame/EndFrame/Render, RynthCoreShell + plugin RenderAll,
/// DX9Backend.RenderDrawData, viewport pump). The always-on engine work
/// (GameMatrixCapture, Nav3DRenderInjector, PluginManager init/tick/
/// pending-action drains, DX9Backend.RenderNav3D fallback) still runs
/// every frame. Diagnostic for whether the per-frame ImGui path is the
/// recurser.</summary>
public static bool EnableImGuiBackend
{
get
{
EnsureLoaded();
return _enableImGuiBackend;
}
}
/// <summary>When true, MainThreadHangWatchdog writes a minidump to
/// Logs\dumps\ the first time AC's main thread is confirmed permanently
/// wedged — a targeted post-mortem to replace always-on procdump (which
/// dumped on every clean exit too). Default true.</summary>
public static bool EnableHangMinidump
{
get
{
EnsureLoaded();
return _enableHangMinidump;
}
}
/// <summary>When true, the engine draws the custom D3D9 Health/Stamina/Mana HUD
/// (<see cref="D3D9.VitalHud"/>) in EndScene. Toggleable live via "/rc vitals";
/// the setter persists to engine.json so it survives relaunch. Default true.
/// Only takes visible effect on a clean (no-Decal) client where the
/// D3D9/EndScene path runs.</summary>
public static bool DrawCustomVitalBars
{
get
{
EnsureLoaded();
return _drawCustomVitalBars;
}
set
{
EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file
if (_drawCustomVitalBars == value) return;
_drawCustomVitalBars = value;
Save();
}
}
/// <summary>When true (default), the engine keeps the retail client's idle clock fresh
/// while in the world, so ClientUISystem::UseTime's 20-minute idle auto-logoff
/// (InactiveTimeBeforeLogout) can't log off a character a bot is playing: the bot's
/// actions aren't keyboard/mouse input, so the client counted it as idle. Set false in
/// engine.json to get the retail behaviour back.</summary>
public static bool PreventIdleLogoff
{
get
{
EnsureLoaded();
return _preventIdleLogoff;
}
}
/// <summary>Engine log threshold from engine.json "LoggingLevel", written by the launcher's
/// Logging level box: Error, Warning, Info (default), Debug/Verbose or Trace. Parsed by
/// EntryPoint.ParseLoggingLevel at init; unknown values fall back to Info.</summary>
public static string LoggingLevel
{
get
@ -65,7 +237,13 @@ internal static class EngineSettings
try
{
if (!File.Exists(SettingsPath)) return;
using var doc = JsonDocument.Parse(File.ReadAllBytes(SettingsPath));
// ReadAllText detects + strips the UTF-8/UTF-16 BOM that some editors
// (PowerShell 5.1 Set-Content -Encoding utf8, Notepad) silently prepend.
// ReadAllBytes + JsonDocument.Parse trips on a leading BOM with
// "'0xEF' is an invalid start of a value", which then sends every
// EngineSettings flag back to its default — silently re-enables
// EnableImGuiBackend etc. with no surfaced error.
using var doc = JsonDocument.Parse(File.ReadAllText(SettingsPath));
if (doc.RootElement.TryGetProperty("PluginPaths", out var arr) &&
arr.ValueKind == JsonValueKind.Array)
{
@ -77,10 +255,77 @@ internal static class EngineSettings
}
}
if (doc.RootElement.TryGetProperty("LoggingLevel", out var loggingLevelElement) &&
loggingLevelElement.ValueKind == JsonValueKind.String)
if (doc.RootElement.TryGetProperty("EnableImGuiShell", out var shellEl) &&
(shellEl.ValueKind == JsonValueKind.True || shellEl.ValueKind == JsonValueKind.False))
{
string? configuredLevel = loggingLevelElement.GetString();
_enableImGuiShell = shellEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnablePlugins", out var pluginsEl) &&
(pluginsEl.ValueKind == JsonValueKind.True || pluginsEl.ValueKind == JsonValueKind.False))
{
_enablePlugins = pluginsEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableDatShareHook", out var datEl) &&
(datEl.ValueKind == JsonValueKind.True || datEl.ValueKind == JsonValueKind.False))
{
_enableDatShareHook = datEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableAvaloniaOverlay", out var avEl) &&
(avEl.ValueKind == JsonValueKind.True || avEl.ValueKind == JsonValueKind.False))
{
_enableAvaloniaOverlay = avEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableD3D9Hook", out var d3dEl) &&
(d3dEl.ValueKind == JsonValueKind.True || d3dEl.ValueKind == JsonValueKind.False))
{
_enableD3D9Hook = d3dEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableEngine", out var engEl) &&
(engEl.ValueKind == JsonValueKind.True || engEl.ValueKind == JsonValueKind.False))
{
_enableEngine = engEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EngineHookCount", out var ehcEl) &&
ehcEl.ValueKind == JsonValueKind.Number &&
ehcEl.TryGetInt32(out int ehc))
{
_engineHookCount = ehc;
}
if (doc.RootElement.TryGetProperty("EnableImGuiBackend", out var ibEl) &&
(ibEl.ValueKind == JsonValueKind.True || ibEl.ValueKind == JsonValueKind.False))
{
_enableImGuiBackend = ibEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableHangMinidump", out var hmEl) &&
(hmEl.ValueKind == JsonValueKind.True || hmEl.ValueKind == JsonValueKind.False))
{
_enableHangMinidump = hmEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("DrawCustomVitalBars", out var cvbEl) &&
(cvbEl.ValueKind == JsonValueKind.True || cvbEl.ValueKind == JsonValueKind.False))
{
_drawCustomVitalBars = cvbEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) &&
(pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False))
{
_preventIdleLogoff = pilEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("LoggingLevel", out var logLevelEl) &&
logLevelEl.ValueKind == JsonValueKind.String)
{
string? configuredLevel = logLevelEl.GetString();
if (!string.IsNullOrWhiteSpace(configuredLevel))
_loggingLevel = configuredLevel;
}
@ -106,6 +351,18 @@ internal static class EngineSettings
foreach (string p in _pluginPaths)
w.WriteStringValue(p);
w.WriteEndArray();
w.WriteBoolean("EnableImGuiShell", _enableImGuiShell);
w.WriteBoolean("EnablePlugins", _enablePlugins);
w.WriteBoolean("EnableDatShareHook", _enableDatShareHook);
w.WriteBoolean("EnableAvaloniaOverlay", _enableAvaloniaOverlay);
w.WriteBoolean("EnableD3D9Hook", _enableD3D9Hook);
w.WriteBoolean("EnableEngine", _enableEngine);
w.WriteNumber("EngineHookCount", _engineHookCount);
w.WriteBoolean("EnableImGuiBackend", _enableImGuiBackend);
w.WriteBoolean("EnableHangMinidump", _enableHangMinidump);
w.WriteBoolean("DrawCustomVitalBars", _drawCustomVitalBars);
w.WriteBoolean("PreventIdleLogoff", _preventIdleLogoff);
// Preserve the launcher-chosen level; dropping it here would reset logging to Info.
w.WriteString("LoggingLevel", _loggingLevel);
w.WriteEndObject();
}

View file

@ -23,6 +23,7 @@ internal sealed class LoadedPlugin
public PluginNameDelegate? GetName { get; set; }
public PluginVersionDelegate? GetVersion { get; set; }
public PluginOnLoginCompleteDelegate? OnLoginComplete { get; set; }
public PluginOnLogoutDelegate? OnLogout { get; set; }
public PluginOnUIInitializedDelegate? OnUIInitialized { get; set; }
public PluginOnBusyCountIncrementedDelegate? OnBusyCountIncremented { get; set; }
public PluginOnBusyCountDecrementedDelegate? OnBusyCountDecremented { get; set; }
@ -41,6 +42,10 @@ internal sealed class LoadedPlugin
public PluginOnVendorCloseDelegate? OnVendorClose { get; set; }
public IntPtr OnUpdateHealthPtr { get; set; }
public PluginOnUpdateHealthDelegate? OnUpdateHealth { get; set; }
public IntPtr OnCombatDamagePtr { get; set; }
public PluginOnCombatDamageDelegate? OnCombatDamage { get; set; }
public IntPtr OnKillNotificationPtr { get; set; }
public PluginOnKillNotificationDelegate? OnKillNotification { get; set; }
public IntPtr OnChatWindowTextPtr { get; set; }
public PluginOnChatWindowTextDelegate? OnChatWindowText { get; set; }
public PluginOnChatBarEnterDelegate? OnChatBarEnter { get; set; }

View file

@ -461,6 +461,273 @@ internal struct RynthCoreAPI
/// Returns total subpalette count, or -1 if no data was captured for this object.
/// subIds[i] is the palette DID; offsets[i] is the range-start offset (used as slot index).</summary>
public IntPtr GetObjectPalettesFn;
/// <summary>Function pointer: int CommenceJump()
/// Calls ClientCombatSystem::CommenceJump (spacebar key-down). Starts the
/// power-bar charge cycle. Pair with DoJump(autonomous) to release.</summary>
public IntPtr CommenceJumpFn;
/// <summary>Function pointer: int DoJump(int autonomous)
/// Calls ClientCombatSystem::DoJump (spacebar key-up). Releases a jump
/// at the current power-bar level. Pass autonomous=1 for the normal
/// player-driven jump (matches keyboard behavior).</summary>
public IntPtr DoJumpFn;
/// <summary>Function pointer: int LaunchJumpWithMotion(int shift, int w, int x, int z, int c)
/// Writes motion vector directly into CMotionInterp, calls DoJump(1), then
/// clears the motion. This is the only way to jump with forward/back/strafe
/// momentum — SetMotion does not bake velocity into the physics sim in time
/// for DoJump. Mirrors UB's UBHelper.Jumper algorithm.</summary>
public IntPtr LaunchJumpWithMotionFn;
/// <summary>Function pointer: int GetRadarRect(int* x0, int* y0, int* x1, int* y1)
/// Returns the retail gmRadarUI element's current screen rect in pixels
/// (x0,y0 top-left, x1,y1 bottom-right exclusive). Returns 1 on success, 0
/// if the radar has not rendered yet this session. Requires API v53+.</summary>
public IntPtr GetRadarRectFn;
/// <summary>Function pointer: void SetRadarSuppressed(int enabled)
/// When enabled=1, the engine skips the original gmRadarUI::DrawObjects call
/// so the vanilla radar stops rendering and a plugin can own that rect.
/// Requires API v54+.</summary>
public IntPtr SetRadarSuppressedFn;
/// <summary>Function pointer: void SetChatSuppressed(int enabled)
/// When enabled=1, the engine calls UIElement::SetVisible(false) on the
/// gmMainChatUI each frame, hiding the retail chatbox entirely.
/// Requires API v55+.</summary>
public IntPtr SetChatSuppressedFn;
/// <summary>Function pointer: void SetPowerbarSuppressed(int enabled)
/// When enabled=1, the engine no-ops gmPowerbarUI's RecvNotice_(Begin/
/// Level/Finish), so the retail attack/magic power bar never renders.
/// Requires API v56+.</summary>
public IntPtr SetPowerbarSuppressedFn;
/// <summary>Function pointer: int GetCastBusyState()
/// 0 = clear to cast, 1 = a cast/action gesture is animating. This is the
/// REAL cast gate (CMotionInterp sequenced-motion queue), distinct from
/// GetBusyState (the ClientUISystem hourglass, which reads 0 while AC still
/// rejects a cast with "You're too busy!"). Sampled on the plugin pump; no
/// acclient.exe hook. Returns 0 when not reachable. Requires API v58+.</summary>
public IntPtr GetCastBusyStateFn;
/// <summary>Function pointer: int ReadKnownSpells(uint* spellIds, int maxCount)
/// Fills the array with the character's known spell ids from a main-thread
/// spellbook snapshot. Returns count written, or -1 if unavailable (cold
/// snapshot / not logged in). Requires API v59+.</summary>
public IntPtr ReadKnownSpellsFn;
/// <summary>Function pointer:
/// void Nav3DAddTriangle(float x1, float y1, float z1,
/// float x2, float y2, float z2,
/// float x3, float y3, float z3,
/// uint colorArgb)
/// Submits a filled 3D triangle in world coordinates. Coordinates are D3D:
/// X=EW, Y=height, Z=NS. Use this instead of three Nav3DAddLine calls when
/// you want a face that conforms exactly to a terrain triangle (slope
/// passability overlay). Requires API v60+.</summary>
public IntPtr Nav3DAddTriangleFn;
/// <summary>Function pointer:
/// void Nav3DAddRingEx(float wx, float wy, float wz, float radius,
/// float thickness, float height, uint colorArgb)
/// Same as Nav3DAddRing but with an explicit cylinder-wall height in
/// world units. Use when you want a tall but thin ring (radar range
/// marker) without coupling visual thickness to wall height. Requires
/// API v61+.</summary>
public IntPtr Nav3DAddRingExFn;
/// <summary>Function pointer: int GiveObjectTo(uint objectId, uint targetId, int amount)
/// Gives an item to an NPC/player via CM_Inventory::Event_GiveObjectRequest
/// (the F7B1 give GameAction). amount=0 gives the whole object. This is the
/// correct give-to-NPC primitive; MoveItemExternal is move-to-container and
/// does NOT give. Requires API v62+. APPENDED-AT-END for ABI safety.</summary>
public IntPtr GiveObjectToFn;
/// <summary>Function pointer: int GetUseDoneSeq()
/// Monotonic count of inbound server UseDone (GameEvent 0x01C7) events. The
/// server sends UseDone when it FINISHES an action (cast/use) — completed
/// (WeenieError.None) or refused (e.g. YoureTooBusy). A plugin records this
/// at cast time and watches for it to change to know the server resolved the
/// cast, so combat casts can be paced on real completion instead of a blind
/// interval (which re-fires into the deferred-windup window and orphans the
/// cast). Read-only observation; never touches client m_cBusy. Returns 0 when
/// unavailable. Requires API v63+. APPENDED-AT-END for ABI safety.</summary>
public IntPtr GetUseDoneSeqFn;
/// <summary>Function pointer: const char* GetEngineStatusJson()
/// Returns the engine-side per-client status fields (host/pid/account/character/server/
/// uptime/fps/pluginTicksPerSec/workingSet/inWorld/queueDropped/reconciles/forceClears/
/// deaths/vitae/xp+lum rates/burden/area/lastIssue) as an ANSI JSON object, EXCLUDING the
/// bot sub-object. A generic "here are my own metrics" accessor — benign, not a remote
/// feature. The returned pointer is valid until the next call on the same thread. Returns
/// IntPtr.Zero on failure. Requires API v64+. APPENDED-AT-END for ABI safety.</summary>
public IntPtr GetEngineStatusJsonFn;
/// <summary>Function pointer: const char* GetPluginSnapshotJson(const char* pluginName)
/// Brokers the named plugin's RynthPluginGetSnapshotJson export and returns its ANSI JSON
/// pointer (IntPtr.Zero if that plugin isn't loaded / produced no snapshot). Lets one plugin
/// read another's snapshot without GetProcAddress-ing it directly — PluginManager owns the
/// module handles. The returned buffer is owned by the target plugin (valid until its next
/// snapshot call); copy it immediately. Requires API v64+. APPENDED-AT-END for ABI safety.</summary>
public IntPtr GetPluginSnapshotJsonFn;
/// <summary>Function pointer: int SendPluginCommand(const char* pluginName, const char* action, const char* value)
/// Forwards a (action,value) command to the named plugin's RynthPluginApplyRemoteCommand
/// export. Returns 1 if delivered, 0 otherwise. The receiving plugin copies the args and
/// applies them on its OWN pump/main thread (never on the caller's thread). Requires API
/// v64+. APPENDED-AT-END for ABI safety.</summary>
public IntPtr SendPluginCommandFn;
/// <summary>Function pointer: int GetObjectDataIdProperty(uint objectId, uint stype, uint* value)
/// Reads a STypeDID property that lives in the object's PublicWeenieDesc (currently Icon=8 →
/// _iconID). Read directly from the embedded PWD struct — network-populated, so it works on
/// UNequipped/never-appraised pack items with no qualities pointer and no main-thread native
/// call. Returns 1 on success (value = the DataID, e.g. 0x06xxxxxx), 0 otherwise. Requires API
/// v65+. APPENDED-AT-END for ABI safety.</summary>
public IntPtr GetObjectDataIdPropertyFn;
/// <summary>Function pointer: const char* GetPluginExportJson(const char* pluginName, const char* exportName)
/// Generic sibling of GetPluginSnapshotJson: brokers ANY parameterless JSON-getter export on the named
/// plugin (by convention RynthPluginGet*Json — takes no args, returns const char*). Lets one plugin read
/// another's secondary JSON surfaces (e.g. RynthRemote pulling RynthAi's RynthPluginGetInventoryJson)
/// without GetProcAddress-ing it directly — PluginManager owns the module handles. The returned buffer is
/// owned by the target plugin (valid until its next call on that export); copy it immediately. Requires
/// API v66+. APPENDED-AT-END for ABI safety.</summary>
public IntPtr GetPluginExportJsonFn;
// ── Vendor trading (v67) ─────────────────────────────────────────────
// Decal's WorldFilter.OpenVendor + Actions.VendorBuyAll/VendorSellAll, as
// stateless batch calls. Reads come from a snapshot the engine takes on AC's
// main thread when the server's vendor list (ApproachVendor 0x0062) is
// opened; buy/sell are queued and sent on AC's main thread through the
// client's own gmVendorUI::SendShopEvent (CM_Vendor::Event_Buy/Event_Sell).
// See Compatibility/VendorTrade.cs. APPENDED-AT-END for ABI safety.
/// <summary>Function pointer: int GetVendorInfo(VendorInfoNative* info)
/// Fills <paramref>info</paramref> for the vendor that is open right now. Returns 1
/// if a vendor is open, 0 if not (info is zeroed). Any thread. Requires API v67+.</summary>
public IntPtr GetVendorInfoFn;
/// <summary>Function pointer: int GetVendorItems(VendorItemNative* items, int maxCount)
/// Copies up to maxCount of the open vendor's items. Returns the TOTAL item count
/// (call with maxCount=0 to size a buffer), or -1 if no vendor is open. Any thread.
/// Requires API v67+.</summary>
public IntPtr GetVendorItemsFn;
/// <summary>Function pointer: uint VendorBuy(uint vendorId, VendorTradeEntryNative* entries, int count)
/// Buys (objectId, amount) pairs from the open vendor (vendorId 0 = whichever is open).
/// Returns a request id (&gt;0) once the request passes the snapshot checks and is
/// queued, or 0 if it was refused (reason in GetVendorTradeStatus and the log).
/// Funds, pack slots and burden are checked again on AC's main thread before the
/// packet goes out; poll GetVendorTradeStatus for the outcome. One transaction is in
/// flight at a time. Requires API v67+.</summary>
public IntPtr VendorBuyFn;
/// <summary>Function pointer: uint VendorSell(uint vendorId, uint* itemIds, int count)
/// Sells the player's own items (whole stacks) to the open vendor. Same return and
/// status contract as VendorBuy. Requires API v67+.</summary>
public IntPtr VendorSellFn;
/// <summary>Function pointer: int GetVendorTradeStatus(VendorTradeStatusNative* status)
/// Fills the state of the most recent VendorBuy/VendorSell request. Returns 1 if a
/// request has been made this session, 0 if not. Any thread. Requires API v67+.</summary>
public IntPtr GetVendorTradeStatusFn;
}
// ─── Vendor trading ABI structs (v67) ───────────────────────────────────
// Blittable, Pack=4, 4-byte fields + fixed ANSI buffers only. Mirrored exactly
// by RynthCore.PluginSdk/VendorTypes.cs. Never reorder or resize; add new calls
// instead of growing these.
/// <summary>The open vendor (VendorProfile from ApproachVendor 0x0062). 192 bytes.</summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal unsafe struct VendorInfoNative
{
public uint VendorId;
/// <summary>Bumps every time the server (re)sends the vendor list: on open and after
/// each accepted buy/sell. Compare before/after a trade to see the refresh.</summary>
public uint Generation;
/// <summary>ShopMode passed to gmVendorUI::OpenVendor (raw client value).</summary>
public int ShopMode;
/// <summary>ITEM_TYPE mask of what the vendor buys.</summary>
public uint ItemTypes;
public int MinValue;
public int MaxValue;
public int DealsMagic;
/// <summary>Vendor pays value * BuyRate when you sell.</summary>
public float BuyRate;
/// <summary>Vendor charges value * SellRate when you buy.</summary>
public float SellRate;
/// <summary>WCID of the vendor's currency; 0 = pyreals.</summary>
public uint AltCurrencyWcid;
/// <summary>Alt currency count as the server reported it in the vendor list (-1 if none).</summary>
public int AltCurrencyServerCount;
/// <summary>Alt currency the engine counted in the player's packs (-1 = not counted yet).</summary>
public int AltCurrencyHave;
/// <summary>Player's pyreals (CoinValue), refreshed on AC's main thread; -1 unknown.</summary>
public int PlayerCoins;
public int ItemCount;
/// <summary>bit0 = trading available (client functions resolved and layout verified),
/// bit1 = a transaction is in flight.</summary>
public uint Flags;
public uint Reserved0;
public fixed byte Name[64];
public fixed byte AltCurrencyName[64];
}
/// <summary>One item on the vendor's list (ItemProfile + its PublicWeenieDesc). 120 bytes.</summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal unsafe struct VendorItemNative
{
public uint ObjectId;
public uint Wcid;
public uint ItemType;
public uint IconId;
/// <summary>How many the vendor has; -1 = unlimited.</summary>
public int Amount;
public int StackSize;
public int MaxStackSize;
/// <summary>PWD value of the listed stack.</summary>
public int Value;
/// <summary>Value of one unit (Value / StackSize for stacks).</summary>
public int UnitValue;
/// <summary>What one unit costs the player here (server rounding; notes at 1.15x).</summary>
public int UnitPrice;
public int Burden;
/// <summary>bit0 unlimited, bit1 stackable, bit2 needs a container slot (pack/foci).</summary>
public uint Flags;
public uint Reserved0;
public uint Reserved1;
public fixed byte Name[64];
}
/// <summary>One buy line: vendor object id + how many.</summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct VendorTradeEntryNative
{
public uint ObjectId;
public int Amount;
}
/// <summary>State of the most recent trade request. 160 bytes.</summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal unsafe struct VendorTradeStatusNative
{
public uint RequestId;
/// <summary>1 queued, 2 sent (waiting for the server), 3 done, 4 refused (never sent).</summary>
public int State;
/// <summary>With State 3: 1 = server accepted (vendor list re-sent), 2 = server answered
/// without re-sending the list (refused: funds/busy/space), 3 = no answer (timed out).</summary>
public int Result;
public int IsBuy;
public uint VendorId;
public int EntryCount;
/// <summary>Buy: estimated cost (pyreals or alt currency). Sell: estimated payout.</summary>
public int Estimate;
public uint Reserved0;
public fixed byte Message[128];
}
@ -468,7 +735,7 @@ internal struct RynthCoreAPI
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary>
internal static class PluginContractVersion
{
public const uint Current = 50;
public const uint Current = 67;
}
internal static class ClientActionHookFlags
@ -509,6 +776,9 @@ internal delegate IntPtr PluginVersionDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnLoginCompleteDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnLogoutDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnUIInitializedDelegate();
@ -554,6 +824,12 @@ internal delegate void PluginOnVendorCloseDelegate(uint vendorId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnUpdateHealthDelegate(uint targetId, float healthRatio, uint currentHealth, uint maxHealth);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnCombatDamageDelegate(uint damage, uint damageType, uint crit, uint isAttacker);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnKillNotificationDelegate(IntPtr textUtf16);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnChatWindowTextDelegate(IntPtr textUtf16, int chatType, IntPtr eatFlag);
@ -625,6 +901,15 @@ internal delegate int SetAutoRunCallbackDelegate(int enabled);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int TapJumpCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int CommenceJumpCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int DoJumpCallbackDelegate(int autonomous);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int LaunchJumpWithMotionCallbackDelegate(int shift, int w, int x, int z, int c);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int SetMotionCallbackDelegate(uint motion, int enabled);
@ -673,6 +958,9 @@ internal delegate int SplitStackInternalCallbackDelegate(uint objectId, uint tar
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int MergeStackInternalCallbackDelegate(uint sourceObjectId, uint targetObjectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int GiveObjectToCallbackDelegate(uint objectId, uint targetId, int amount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int WriteToChatCallbackDelegate(IntPtr textUtf16, int chatType);
@ -750,6 +1038,9 @@ internal delegate void PluginOnEnchantmentRemovedDelegate(uint enchantmentId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int ReadPlayerEnchantmentsCallbackDelegate(uint* spellIds, double* expiryTimes, int maxCount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int ReadKnownSpellsCallbackDelegate(uint* spellIds, int maxCount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate double GetServerTimeCallbackDelegate();
@ -771,6 +1062,12 @@ internal delegate void Nav3DAddRingCallbackDelegate(float wx, float wy, float wz
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void Nav3DAddLineCallbackDelegate(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void Nav3DAddTriangleCallbackDelegate(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint colorArgb);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void Nav3DAddRingExCallbackDelegate(float wx, float wy, float wz, float radius, float thickness, float height, uint colorArgb);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int InvokeChatParserCallbackDelegate(IntPtr textUtf16);
@ -791,6 +1088,8 @@ internal delegate IntPtr GetObjectStringPropertyCallbackDelegate(uint objectId,
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectWielderInfoCallbackDelegate(uint objectId, uint* wielderID, uint* location);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetContainerContentsCallbackDelegate(uint containerId, uint* itemIds, int maxCount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
@ -832,6 +1131,12 @@ internal unsafe delegate int GetObjectHeadingCallbackDelegate(uint objectId, flo
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int GetBusyStateCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int GetCastBusyStateCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int GetUseDoneSeqCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectSpellIdsCallbackDelegate(uint guid, uint* spellIds, int maxCount);
@ -855,3 +1160,45 @@ internal delegate void ForceResetBusyCountCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectPalettesCallbackDelegate(uint objectId, uint* subIds, uint* offsets, int maxCount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetRadarRectCallbackDelegate(int* x0, int* y0, int* x1, int* y1);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void SetRadarSuppressedCallbackDelegate(int enabled);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void SetPowerbarSuppressedCallbackDelegate(int enabled);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void SetChatSuppressedCallbackDelegate(int enabled);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate IntPtr GetEngineStatusJsonCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate IntPtr GetPluginSnapshotJsonCallbackDelegate(IntPtr pluginNameAnsi);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int SendPluginCommandCallbackDelegate(IntPtr pluginNameAnsi, IntPtr actionAnsi, IntPtr valueAnsi);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectDataIdPropertyCallbackDelegate(uint objectId, uint stype, uint* value);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate IntPtr GetPluginExportJsonCallbackDelegate(IntPtr pluginNameAnsi, IntPtr exportNameAnsi);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetVendorInfoCallbackDelegate(VendorInfoNative* info);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetVendorItemsCallbackDelegate(VendorItemNative* items, int maxCount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate uint VendorBuyCallbackDelegate(uint vendorId, VendorTradeEntryNative* entries, int count);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate uint VendorSellCallbackDelegate(uint vendorId, uint* itemIds, int count);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetVendorTradeStatusCallbackDelegate(VendorTradeStatusNative* status);

View file

@ -75,7 +75,14 @@ internal static class PluginLoader
}
/// <summary>
/// Unloads a plugin by freeing its DLL.
/// Unloads a plugin. <b>Does NOT call FreeLibrary</b> — NativeAOT plugin DLLs
/// share the .NET runtime with the host engine, and their <c>DLL_PROCESS_DETACH</c>
/// path tears down NativeAOT runtime state in ways that race with our other
/// threads (TickPump, Avalonia STA, hooks) and produce a deterministic
/// <c>ntdll!RtlpHeap</c> AV at addr ending in <c>0xFFC</c> on hot-reload + manual
/// exit. The module handle is intentionally leaked; on next reload, a new
/// shadow copy at a different path is loaded so the new plugin code runs
/// cleanly. The OS reclaims the leaked module pages when the process exits.
/// </summary>
public static void Unload(LoadedPlugin plugin)
{
@ -84,12 +91,11 @@ internal static class PluginLoader
if (plugin.ModuleHandle != IntPtr.Zero)
{
FreeLibrary(plugin.ModuleHandle);
RynthLog.Verbose($"PluginLoader: Unloaded {plugin.FileName}");
RynthLog.Verbose($"PluginLoader: Skipping FreeLibrary on {plugin.FileName} (NativeAOT — module pages leaked intentionally).");
}
TryDeleteFile(plugin.FilePath);
TryDeleteFile(Path.ChangeExtension(plugin.FilePath, ".pdb"));
// Don't try to delete the .dll/.pdb either — they're still mapped.
// Old shadow copies get cleaned up on next launch via CleanupShadowCopies.
TryDeleteEmptyDirectory(Path.GetDirectoryName(plugin.FilePath));
}
@ -109,6 +115,190 @@ internal static class PluginLoader
}
}
/// <summary>
/// One-shot startup sweep over sibling per-PID shadow roots
/// (<c>&lt;baseShadowRootDir&gt;/p&lt;PID&gt;/</c>). Deletes dirs whose
/// owning PID is dead — i.e. orphans from previous client runs that
/// crashed or were killed before tearing down their shadow tree.
///
/// Mutex-serialized across processes: two clients launching concurrently
/// must not race on the same dead-PID dirs, because Directory.Delete
/// failures (already-deleted-by-other-client → DirectoryNotFoundException)
/// generate exception heap pressure, which is exactly the failure mode
/// the per-PID shadow-root design is meant to eliminate.
/// </summary>
public static void CleanupOrphanShadowRoots(string baseShadowRootDir, int currentPid)
{
RynthLog.Plugin($"PluginLoader: orphan sweep starting (root={baseShadowRootDir}, currentPid={currentPid}).");
if (!Directory.Exists(baseShadowRootDir))
{
RynthLog.Plugin("PluginLoader: orphan sweep — base dir does not exist, nothing to do.");
return;
}
RynthLog.Plugin("PluginLoader: orphan sweep DIAG-1 — base dir exists, creating mutex.");
System.Threading.Mutex? mutex = null;
bool acquired = false;
int deleted = 0;
int skippedAlive = 0;
try
{
try
{
mutex = new System.Threading.Mutex(false, "Local\\RynthCore.PluginShadow.OrphanSweep");
}
catch (Exception ex)
{
RynthLog.Plugin($"PluginLoader: orphan sweep — mutex create threw {ex.GetType().Name}: {ex.Message}. Proceeding without serialization.");
}
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-2 — mutex created (null={mutex == null}).");
if (mutex != null)
{
RynthLog.Plugin("PluginLoader: orphan sweep DIAG-3 — calling mutex.WaitOne(5s).");
try { acquired = mutex.WaitOne(TimeSpan.FromSeconds(5)); }
catch (System.Threading.AbandonedMutexException) { acquired = true; }
catch (Exception ex)
{
RynthLog.Plugin($"PluginLoader: orphan sweep — mutex wait threw {ex.GetType().Name}: {ex.Message}. Proceeding without serialization.");
}
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-4 — mutex.WaitOne returned, acquired={acquired}.");
if (!acquired)
RynthLog.Plugin("PluginLoader: orphan sweep — mutex not acquired within 5s; proceeding without serialization.");
}
RynthLog.Plugin("PluginLoader: orphan sweep DIAG-5 — calling Directory.GetDirectories.");
string[] dirs = Directory.GetDirectories(baseShadowRootDir);
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-6 — got {dirs.Length} dirs.");
for (int i = 0; i < dirs.Length; i++)
{
string dir = dirs[i];
string name = Path.GetFileName(dir);
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-7.{i} — examining '{name}'.");
if (name.Length < 2 || name[0] != 'p') continue;
if (!int.TryParse(name.AsSpan(1), out int ownerPid)) continue;
if (ownerPid == currentPid)
{
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-7.{i} — skipping {name} (own PID).");
continue;
}
// Liveness check via Win32 OpenProcess — bypasses
// System.Diagnostics.Process which was crashing this thread
// (and by extension the process) under NativeAOT in a
// heavily-hooked acclient.exe. We need this gate because
// Directory.Delete over a still-mapped DLL — which is what
// a LIVE owner's shadow dir contains — also crashes silently
// here, bypassing the managed try/catch in
// TryDeleteDirectoryReporting. So delete is unsafe without
// knowing the owner is dead.
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-7.{i} — checking IsPidAliveWin32({ownerPid}).");
bool alive = IsPidAliveWin32(ownerPid);
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-7.{i} — IsPidAliveWin32({ownerPid})={alive}.");
if (alive)
{
skippedAlive++;
RynthLog.Plugin($"PluginLoader: orphan sweep skipping {name} — PID {ownerPid} still running.");
continue;
}
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-7.{i} — calling TryDeleteDirectoryReporting('{name}').");
bool ok = TryDeleteDirectoryReporting(dir);
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-7.{i} — delete returned ok={ok}.");
if (ok) deleted++;
}
RynthLog.Plugin($"PluginLoader: orphan sweep complete (deleted={deleted}, skippedAlive={skippedAlive}).");
}
catch (Exception ex)
{
RynthLog.Plugin($"PluginLoader: orphan sweep threw {ex.GetType().Name}: {ex.Message}");
}
finally
{
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-FIN — releasing mutex (acquired={acquired}).");
if (acquired && mutex != null)
{
try { mutex.ReleaseMutex(); } catch { }
}
mutex?.Dispose();
RynthLog.Plugin("PluginLoader: orphan sweep DIAG-FIN — done.");
}
}
private static bool TryDeleteDirectoryReporting(string path)
{
try
{
Directory.Delete(path, true);
return true;
}
catch (Exception ex)
{
RynthLog.Plugin($"PluginLoader: orphan sweep delete failed for {Path.GetFileName(path)} — {ex.GetType().Name}: {ex.Message}");
return false;
}
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenProcess(uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
private const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
private const uint STILL_ACTIVE = 259;
/// <summary>
/// Win32-native liveness check. Replaces the original
/// System.Diagnostics.Process.GetProcessById path which AVs the host
/// process under NativeAOT in injected acclient.exe — see the comment in
/// CleanupOrphanShadowRoots. Trade-off vs. the original: no ProcessName
/// verification, so a recycled PID held by an unrelated process keeps the
/// orphan dir alive. The cost is a stale shadow tree, not a crash.
/// </summary>
private static bool IsPidAliveWin32(int pid)
{
if (pid <= 0) return false;
IntPtr h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
if (h == IntPtr.Zero) return false;
try
{
if (!GetExitCodeProcess(h, out uint exitCode)) return false;
return exitCode == STILL_ACTIVE;
}
finally
{
CloseHandle(h);
}
}
[Obsolete("Use IsPidAliveWin32 — Process.GetProcessById crashes under NativeAOT in injected x86 acclient.exe.")]
private static bool IsProcessAlive(int pid)
{
try
{
using var p = System.Diagnostics.Process.GetProcessById(pid);
if (p.HasExited) return false;
return string.Equals(p.ProcessName, "acclient", StringComparison.OrdinalIgnoreCase);
}
catch
{
return false;
}
}
public static LoadedPlugin? LoadSingle(string sourcePath, string shadowRootDir, int generation)
{
string sessionShadowDir = PrepareShadowDirectory(shadowRootDir, generation);
@ -174,6 +364,10 @@ internal static class PluginLoader
if (onLoginCompletePtr != IntPtr.Zero)
plugin.OnLoginComplete = Marshal.GetDelegateForFunctionPointer<PluginOnLoginCompleteDelegate>(onLoginCompletePtr);
IntPtr onLogoutPtr = GetProcAddress(handle, "RynthPluginOnLogout");
if (onLogoutPtr != IntPtr.Zero)
plugin.OnLogout = Marshal.GetDelegateForFunctionPointer<PluginOnLogoutDelegate>(onLogoutPtr);
IntPtr onUiInitializedPtr = GetProcAddress(handle, "RynthPluginOnUIInitialized");
if (onUiInitializedPtr != IntPtr.Zero)
plugin.OnUIInitialized = Marshal.GetDelegateForFunctionPointer<PluginOnUIInitializedDelegate>(onUiInitializedPtr);
@ -243,6 +437,20 @@ internal static class PluginLoader
plugin.OnUpdateHealth = Marshal.GetDelegateForFunctionPointer<PluginOnUpdateHealthDelegate>(onUpdateHealthPtr);
}
IntPtr onCombatDamagePtr = GetProcAddress(handle, "RynthPluginOnCombatDamage");
if (onCombatDamagePtr != IntPtr.Zero)
{
plugin.OnCombatDamagePtr = onCombatDamagePtr;
plugin.OnCombatDamage = Marshal.GetDelegateForFunctionPointer<PluginOnCombatDamageDelegate>(onCombatDamagePtr);
}
IntPtr onKillNotificationPtr = GetProcAddress(handle, "RynthPluginOnKillNotification");
if (onKillNotificationPtr != IntPtr.Zero)
{
plugin.OnKillNotificationPtr = onKillNotificationPtr;
plugin.OnKillNotification = Marshal.GetDelegateForFunctionPointer<PluginOnKillNotificationDelegate>(onKillNotificationPtr);
}
IntPtr onChatWindowTextPtr = GetProcAddress(handle, "RynthPluginOnChatWindowText");
if (onChatWindowTextPtr != IntPtr.Zero)
{
@ -288,6 +496,12 @@ internal static class PluginLoader
if (strPtr != IntPtr.Zero)
plugin.VersionString = Marshal.PtrToStringAnsi(strPtr) ?? "";
}
// The DLL's version resource is stamped at release time with the release and commit;
// the plugins' own RynthPluginVersion strings are hand-written and never change.
string fileVersion = RynthCore.App.BuildVersion.OfFile(
plugin.SourceFilePath.Length > 0 ? plugin.SourceFilePath : plugin.FilePath);
if (fileVersion.Length > 0)
plugin.VersionString = fileVersion;
string ver = string.IsNullOrEmpty(plugin.VersionString) ? "" : $" v{plugin.VersionString}";
string caps = BuildCapsList(plugin);
@ -298,7 +512,14 @@ internal static class PluginLoader
private static string PrepareShadowDirectory(string shadowRootDir, int generation)
{
string sessionDir = Path.Combine(shadowRootDir, $"session-{generation:D4}-pid{Environment.ProcessId}");
// Include EntryPoint.InitCount so each engine instance gets its own
// shadow root. After an engine hot-reload the previous engine's
// plugin DLL stays pinned (FreeLibrary doesn't actually unmap), so
// overwriting its shadow path would fail with a sharing violation.
int engineInit = EntryPoint.InitCount;
string sessionDir = Path.Combine(
shadowRootDir,
$"session-{generation:D4}-pid{Environment.ProcessId}-eng{engineInit:D2}");
Directory.CreateDirectory(sessionDir);
return sessionDir;
}
@ -361,6 +582,7 @@ internal static class PluginLoader
{
var parts = new List<string>(4) { "init", "shutdown" };
if (p.OnLoginComplete != null) parts.Add("login");
if (p.OnLogout != null) parts.Add("logout");
if (p.OnUIInitialized != null) parts.Add("ui");
if (p.OnBusyCountIncremented != null) parts.Add("busy+");
if (p.OnBusyCountDecremented != null) parts.Add("busy-");
@ -376,6 +598,8 @@ internal static class PluginLoader
if (p.OnVendorOpen != null) parts.Add("vendor-open");
if (p.OnVendorClose != null) parts.Add("vendor-close");
if (p.OnUpdateHealth != null || p.OnUpdateHealthPtr != IntPtr.Zero) parts.Add("health");
if (p.OnCombatDamage != null || p.OnCombatDamagePtr != IntPtr.Zero) parts.Add("combatdmg");
if (p.OnKillNotification != null || p.OnKillNotificationPtr != IntPtr.Zero) parts.Add("kill");
if (p.OnChatWindowText != null) parts.Add("chat-in");
if (p.OnChatBarEnter != null) parts.Add("chat-out");
if (p.OnBarAction != null) parts.Add("bar");

File diff suppressed because it is too large Load diff