// RynthILTPlugin.cs - Infinite Leaftide (ACECustom) features, kept out of RynthAi and the engine core. // // Two features, both shown only on ILT: // * Bounties (Bounty/BountyTracker.cs): the engine's Bounties window (the bar's ILT button, // /rc bounties). Its reads run only while that window polls RynthILTGetBountiesJson, and the // engine polls only on ILT. // * The ILT Hub (Hub/, SilentKelpie's, moved here from RynthAi 2026-10-13): the Mini Remote's // ILT tabs (Character, Banking, Gear, Charms, Games; RynthAi's Mini Remote hosts them through // RynthILT.Hub, HubInterface.cs), their sections in its Quests / Pets / Remote tabs, the // Guardian panel (RynthPluginRenderEmbed "guardian"), the Skills panel's Progression data // (RynthILTGetProgressionJson, "prog ..." through RynthILTCommand), server feature detection. // Every feature stays dormant off an ILT-like world (IltServerOptions: no probes, no chat). // // Threads: OnTick, OnChatWindowText, OnKillNotification, login/logout and the engine's export calls // run on the plugin pump. OnChatBarEnter runs on AC's main thread (the engine's dispatcher queues it // there, our own InvokeChatParser too), and RynthAi forwards its "/ra hub ..." verbs from there too, // so commands only queue and run on the next tick. OnRender / RenderEmbed and the RynthILT.Hub // render functions run on the render thread and only read what the pump built. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using ImGuiNET; using RynthCore.Plugin.RynthILT.Bounty; using RynthCore.Plugin.RynthILT.Hub; using RynthCore.Plugin.Shared; using RynthCore.PluginCore; namespace RynthCore.Plugin.RynthILT; public sealed class RynthILTPlugin : RynthPluginBase { internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthILT"); internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.2.0"); /// Wait this long after login for the character's name before tracking without a save file. private const long NameWaitMs = 30_000; private const long NameRetryMs = 1_000; private bool _loginComplete; private long _loginAtMs; private long _nextNameTryMs; private long _nextHubTryMs; private BountyTracker? _bounties; private IltHubController? _hub; // An unfinished copy from RynthAi (IltMigration pending): the Hub writes nothing for this // character and the copy is retried every MigrationRetryMs; once it works the Hub restarts on // the copied files. private const long MigrationRetryMs = 120_000; private volatile bool _hubWritesBlocked; private long _nextMigrationRetryMs; private string _hubFolder = string.Empty, _hubWorld = string.Empty, _hubChar = string.Empty; private bool _forceOnRestart; private RynthAiClient? _ai; private IltSettings _settings = new(); // "/ilt ..." lines from OnChatBarEnter and RynthAi's forwarded "/ra" verbs, run on the next tick. private readonly ConcurrentQueue _commands = new(); // "/bounty ..." lines from OnChatBarEnter (typed by the player, or our own coming back through // the engine's dispatcher), passed to the tracker before the next chat line or tick. private readonly ConcurrentQueue _typedBounty = new(); // Engine / plugin commands (RynthPluginApplyRemoteCommand: "prog ..." from RynthAi or an older engine). private readonly ConcurrentQueue _engineCommands = new(); /// The Bounties window's tracker (PluginExports); null until login. internal BountyTracker? Bounties => _bounties; /// The ILT Hub for the logged-in character (HubInterface, PluginExports); null until its name is known. internal IltHubController? Hub => _hub; public override int Initialize() { RynthLog.Init(Host); // The Hub's windows and RynthAi-hosted tabs draw through the engine's cimgui module. ImGuiNativeBinding.Ensure(msg => RynthLog.Write(LogCat.IltHub, msg)); // Every use goes through Host.UseFor (Plugins/Shared/UseAudit.cs): one log line each. UseAudit.Reset("RynthILT", null); // Saves (Hub state, bank log, profiles, settings, bounty list, the copies from RynthAi) say // when they fail and why (Plugins/Shared/DataWriteGuard.cs): always in the log, in chat // once per folder, and only on an ILT world (PostDataWriteProblems). DataWriteGuard.Reset(); DataWriteGuard.PluginName = "RynthILT"; DataWriteGuard.LogSink = msg => RynthLog.Write(LogCat.IltStore, msg.StartsWith("[RynthILT] ", StringComparison.Ordinal) ? msg.Substring(11) : msg); _ai = new RynthAiClient(Host); _settings = IltSettingsStore.Load(); Host.Log("[RynthILT] Plugin initialized."); return 0; } // Also called on a freshly (re)loaded plugin while already in game. public override void OnLoginComplete() { SaveBounties(); StopHub(); _bounties = null; _loginComplete = true; _loginAtMs = Environment.TickCount64; _nextNameTryMs = 0; _nextHubTryMs = 0; _ai?.Reset(); TryStartBounties(); TryStartHub(); } public override void OnLogout() { SaveBounties(); _bounties = null; StopHub(); _ai?.Reset(); _loginComplete = false; while (_commands.TryDequeue(out _)) { } while (_typedBounty.TryDequeue(out _)) { } } // Plugin unload (hot reload, update, client closing): keep the list and the Hub state for the next copy. public override void Shutdown() { SaveBounties(); StopHub(); HubInterface.Release(); RynthLog.Shutdown(); } public override void OnTick() { try { RynthLog.Pump(); } catch { } if (!_loginComplete) return; _ai?.Tick(); if (_bounties == null) TryStartBounties(); if (_hub == null) TryStartHub(); DrainTypedBounty(); while (_commands.TryDequeue(out string[]? parts)) RunCommand(parts); while (_engineCommands.TryDequeue(out string? engineCommand)) RunEngineCommand(engineCommand); _bounties?.Tick(); try { _hub?.Tick(); } catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "Tick"); } RetryPendingMigration(); PostDataWriteProblems(); } /// /// The save failures queued by DataWriteGuard, in chat once the Hub knows this is an ILT world /// (or "Treat this world as ILT"). Off ILT they stay in the log only: nothing ILT shows there. /// private void PostDataWriteProblems() { if (DataWriteGuard.PendingCount == 0 || _hub?.OffersTabs != true || !Host.HasWriteToChat) return; DataWriteGuard.DrainChat(line => Host.WriteToChat(line, 2)); } public override void OnChatWindowText(string? text, int chatType, ref int eat) { if (string.IsNullOrEmpty(text)) return; try { // The Hub eats its own probe / capture replies (IltChatCapture). if (_hub?.OnChat(text) == true) eat = 1; } catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnChat"); } if (_bounties == null) return; DrainTypedBounty(); try { // Eats only the reply to the tracker's own /bounty list (BountyTracker.OnChat). if (_bounties.OnChat(text)) eat = 1; } catch (Exception ex) { Host.Log($"[RynthILT] Bounty chat parse failed: {ex.Message}"); } } public override void OnChatBarEnter(string? text, ref int eat) { if (!_loginComplete || string.IsNullOrEmpty(text)) return; string trimmed = text.Trim(); // A /bounty going out: its reply must not be eaten (BountyTracker.NoteTypedCommand). Never eaten here. if (BountyTracker.IsBountyCommand(trimmed)) { _typedBounty.Enqueue(trimmed); return; } if (!trimmed.Equals("/ilt", StringComparison.OrdinalIgnoreCase) && !trimmed.StartsWith("/ilt ", StringComparison.OrdinalIgnoreCase)) return; eat = 1; _commands.Enqueue(trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries)); } // The server's killer notification: this character landed the killing blow. public override void OnKillNotification(string? deathMessage) => _bounties?.OnKill(); private void DrainTypedBounty() { while (_typedBounty.TryDequeue(out string? typed)) _bounties?.NoteTypedCommand(typed); } // ── Rendering (render thread) ──────────────────────────────────────────── /// The Hub's floating extras (Games HUD, confirmations) in the engine's ImGui frame. public override void OnRender() { var hub = _hub; if (!_loginComplete || hub == null || Host.ImGuiContext == IntPtr.Zero) return; IntPtr previous = ImGui.GetCurrentContext(); ImGui.SetCurrentContext(Host.ImGuiContext); try { hub.Render(); } catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnRender"); } finally { ImGui.SetCurrentContext(previous); } } /// The same while the engine's ImGui shell is off (RynthPluginRenderOverlay), in the dashboard colours. internal void OnRenderOverlay() { var hub = _hub; if (!_loginComplete || hub == null || Host.ImGuiContext == IntPtr.Zero) return; IntPtr previous = ImGui.GetCurrentContext(); ImGui.SetCurrentContext(Host.ImGuiContext); int pushed = IltStyle.PushDashboardStyle(); try { hub.Render(); } catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnRenderOverlay"); } finally { ImGui.PopStyleColor(pushed); ImGui.SetCurrentContext(previous); } } /// /// RynthPluginRenderEmbed "guardian": the Temple guardian tools inside RynthCore's Guardian /// panel (the bar's ILT button), drawn into the engine's current ImGui window and context /// (a popped-out panel has its own context, not Host.ImGuiContext; switching to the main one /// there crashed the client, 2026-10-11). False (nothing drawn) until login and the Hub exist. /// internal bool RenderEmbeddedGuardian() { var hub = _hub; if (!_loginComplete || hub == null || Host.ImGuiContext == IntPtr.Zero) return false; IntPtr previous = ImGui.GetCurrentContext(); if (previous == IntPtr.Zero) ImGui.SetCurrentContext(Host.ImGuiContext); int pushed = IltStyle.PushDashboardStyle(); try { hub.RenderGuardianPanel(); return true; } catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "RenderEmbeddedGuardian"); return false; } finally { ImGui.PopStyleColor(pushed); if (previous == IntPtr.Zero) ImGui.SetCurrentContext(previous); } } // ── Commands ───────────────────────────────────────────────────────────── /// /// RynthILT.Hub Command: an ILT "/ra" verb RynthAi forwards ("hub bank", "guardian handin", /// "bounty show", "rates reset"). Decides at once whether it is ours (RynthAi answers the rest) /// and queues it for the next tick. Any thread. /// internal bool RunForwardedCommand(string line) { string[] words = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (words.Length == 0 || !IsIltVerb(words)) return false; var parts = new string[words.Length + 1]; parts[0] = "/ra"; Array.Copy(words, 0, parts, 1, words.Length); _commands.Enqueue(parts); return true; } /// /// The verbs RynthILT answers: the ILT "/ra hub" verbs (not RynthAi's Quests / Pets tabs or its /// Remote tab), "/ra guardian", "/ra bounty|bounties|bountys" and "rates". /// internal static bool IsIltVerb(string[] words) { string verb = words[0].ToLowerInvariant(); switch (verb) { case "guardian": case "bounty": case "bounties": case "bountys": case "rates": return true; case "hub": if (words.Length < 2) return false; // "/ra hub" alone toggles RynthAi's Mini Remote string sub = words[1].ToLowerInvariant(); if (sub is "open") return words.Length < 3 || !IltSections.IsUniversalTabName(words[2]); if (sub is "tab") return words.Length >= 3 && IltSections.TryParse(words[2], out IltSection t) && IltSections.IsTab(t); return true; default: return false; } } private void RunCommand(string[] parts) { // RynthAi's forwarded "/ra ..." and "/ilt hub|guardian|bounty ..." reach the Hub alike. bool fromRa = parts.Length > 0 && parts[0].Equals("/ra", StringComparison.OrdinalIgnoreCase); string verb = parts.Length >= 2 ? parts[1].ToLowerInvariant() : "help"; string[] args = parts.Length > 2 ? parts[2..] : Array.Empty(); if (!fromRa && (verb == "bounty" || verb == "bounties" || verb == "bountys")) { // "/ilt bounty [list|refresh]": the tracker's own chat commands ("/ra bounty" opens the window). if (_bounties == null) ChatLine("[RynthILT] Bounties not ready (not logged in yet)."); else _bounties.HandleChatCommand(parts); return; } switch (verb) { case "trace": HandleTrace(args); return; case "debug": RynthLog.DebugToChat = args.Length > 0 ? args[0].Equals("on", StringComparison.OrdinalIgnoreCase) : !RynthLog.DebugToChat; ChatLine($"[RynthILT] Debug-to-chat is {(RynthLog.DebugToChat ? "ON" : "off")} (traced: {RynthLog.TracedList()})."); return; case "servers": verb = "hub"; args = Prepend("servers", args); break; case "bounty": case "bounties": case "bountys": case "guardian": case "hub": case "rates": break; case "help": ChatLine("[RynthILT] /ilt hub ... (the Mini Remote's ILT tabs; same as /ra hub ...), /ilt guardian ..., /ilt servers [list||default],"); ChatLine("[RynthILT] /ilt bounty [list|refresh] - the tracked ACECustom bounties (the Bounties window: the ILT button on the RynthCore bar, or /rc bounties),"); ChatLine("[RynthILT] /ilt trace [on|off], /ilt debug [on|off]."); return; default: // "/ilt bank", "/ilt attr run", ...: the Hub's verbs without "hub". args = Prepend(verb, args); verb = "hub"; break; } if (_hub == null) { ChatLine("[RynthILT] ILT features not ready (log in first)."); return; } try { if (!_hub.HandleCommand(verb, args)) ChatLine($"[RynthILT] Unknown command: {string.Join(" ", parts)}. /ilt help"); } catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "command"); } } private static string[] Prepend(string first, string[] rest) { var a = new string[rest.Length + 1]; a[0] = first; Array.Copy(rest, 0, a, 1, rest.Length); return a; } /// "/ilt trace <category|all|list> [on|off]". private void HandleTrace(string[] args) { string target = args.Length > 0 ? args[0] : "list"; bool on = args.Length < 2 || !args[1].Equals("off", StringComparison.OrdinalIgnoreCase); if (target.Equals("list", StringComparison.OrdinalIgnoreCase) || target.Equals("status", StringComparison.OrdinalIgnoreCase)) { ChatLine($"[RynthILT] Traced: {RynthLog.TracedList()}. Categories: {string.Join(", ", Enum.GetNames())}. Log folder: {RynthLog.Directory}"); return; } if (target.Equals("all", StringComparison.OrdinalIgnoreCase) || target.Equals("ilt", StringComparison.OrdinalIgnoreCase)) { int n = RynthLog.SetTracingAll(on); ChatLine($"[RynthILT] Tracing {(on ? "enabled" : "disabled")} for {n} categories."); return; } if (!RynthLog.TryParseCategory(target, out LogCat cat)) { ChatLine($"[RynthILT] Unknown trace category '{target}'. /ilt trace list"); return; } RynthLog.SetTracing(cat, on); ChatLine($"[RynthILT] Trace {cat}: {(on ? "ON" : "off")}"); } /// RynthILTCommand: "prog ..." (the Skills panel's Progression tab) and the Hub verbs, from the engine. Pump thread. internal void RunEngineCommand(string text) { string[] words = text.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (words.Length == 0) return; if (words[0].Equals("prog", StringComparison.OrdinalIgnoreCase)) { if (_hub == null) { ChatLine("[RynthILT] ILT features not ready (log in first)."); return; } try { _hub.Progression.HandleRemote(words[1..]); } catch (Exception ex) { RynthLog.Exception(LogCat.IltProgression, ex, "prog command"); } return; } if (IsIltVerb(words)) RunForwardedCommand(text); } /// RynthPluginApplyRemoteCommand (any thread): "prog" + its arguments, or an ILT verb; run on the next tick. internal void EnqueueRemoteCommand(string action, string value) { if (_engineCommands.Count < 64) _engineCommands.Enqueue((action + " " + value).Trim()); } private void ChatLine(string text) { if (Host.HasWriteToChat) Host.WriteToChat(text, 1); } // ── The ILT Hub ────────────────────────────────────────────────────────── /// /// Starts the Hub once the character's name is known (its files are per character). The first /// time a character logs in with RynthILT its RynthAi ILT Hub files are copied over (IltMigration). /// private void TryStartHub() { long now = Environment.TickCount64; if (now < _nextHubTryMs || _hub != null || _ai == null) return; _nextHubTryMs = now + NameRetryMs; uint me = Host.GetPlayerId(); if (me == 0 || !Host.HasGetObjectName || !Host.TryGetObjectName(me, out string charName) || string.IsNullOrWhiteSpace(charName)) return; string world = Host.HasGetWorldName && Host.TryGetWorldName(out string w) && !string.IsNullOrWhiteSpace(w) ? w.Trim() : string.Empty; string folder = CharacterFolder(world, charName); bool force = false; try { var lines = new List(IltMigration.MigrateShared(_settings, SettingsRoot)); lines.AddRange(IltMigration.MigrateCharacter(folder, world, charName, _settings, out force)); if (lines.Count > 0) { IltSettingsStore.Save(_settings); RynthLog.Write(LogCat.IltStore, $"Carried the ILT Hub's saved data over from RynthAi for {charName}: {string.Join(", ", lines)}."); } } catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, "migration"); } force |= _forceOnRestart; _forceOnRestart = false; bool pending = IltMigration.IsPending(_settings, folder); _hubWritesBlocked = pending; _hubFolder = folder; _hubWorld = world; _hubChar = charName; _nextMigrationRetryMs = now + MigrationRetryMs; if (pending) RynthLog.Write(LogCat.IltStore, $"{charName}'s Hub data isn't all copied from RynthAi yet: the Hub saves nothing for this character " + "until it is (read from RynthAi's files where it can; retried every 2 minutes and at each login)."); try { _hub = new IltHubController(Host, folder, _settings, _ai, () => _hubWritesBlocked, pending ? IltMigration.FindLegacyCharFolder(world, charName) : null); _hub.OnLoginComplete(charName, force); } catch (Exception ex) { _hub = null; RynthLog.Exception(LogCat.IltHub, ex, "start"); } } /// /// Pump: while this character's copy from RynthAi is unfinished, tries it again every /// MigrationRetryMs. When it completes the Hub is stopped (still writing nothing, so the copied /// files stay as they are) and started again on them. /// private void RetryPendingMigration() { if (_hub == null || !_hubWritesBlocked) return; long now = Environment.TickCount64; if (now < _nextMigrationRetryMs) return; _nextMigrationRetryMs = now + MigrationRetryMs; try { var lines = IltMigration.MigrateCharacter(_hubFolder, _hubWorld, _hubChar, _settings, out bool force); if (lines.Count > 0) { IltSettingsStore.Save(_settings); RynthLog.Write(LogCat.IltStore, $"Retried copying {_hubChar}'s ILT Hub data from RynthAi: {string.Join(", ", lines)}."); } if (IltMigration.IsPending(_settings, _hubFolder)) return; _forceOnRestart = force; StopHub(); // _hubWritesBlocked is still true: the logout save writes nothing _nextHubTryMs = 0; TryStartHub(); // loads the copied files; saves from now on RynthLog.Write(LogCat.IltStore, $"{_hubChar}'s ILT Hub data is copied; the Hub restarted on it."); } catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, "migration retry"); } } private void StopHub() { var hub = _hub; _hub = null; if (hub == null) return; try { hub.OnLogout(); } catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "logout"); } } /// %APPDATA%\RynthCore\RynthILT\{world}\{character} (the bounty list's folder too). internal static string CharacterFolder(string world, string charName) => Path.Combine(SettingsRoot, SafeName(world.Length > 0 ? world : "UnknownWorld"), SafeName(charName)); // ── Bounties ───────────────────────────────────────────────────────────── /// Starts the tracker once the character's name is known (its save file is per character). private void TryStartBounties() { long now = Environment.TickCount64; if (now < _nextNameTryMs) return; _nextNameTryMs = now + NameRetryMs; string file = BountyFilePath(out bool named); if (!named && now - _loginAtMs < NameWaitMs) return; if (!named) Host.Log("[RynthILT] Bounties: no character name; the list won't be saved this session."); _bounties = new BountyTracker(SendCommand, ChatLine, Host.Log, file); } private void SaveBounties() { try { _bounties?.Save(); } catch (Exception ex) { Host.Log($"[RynthILT] Bounties: save failed: {ex.Message}"); } } /// The tracker's only way to the server: one chat command (Host.InvokeChatParser). private void SendCommand(string command) { if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command)) throw new InvalidOperationException("the engine's chat parser is not available"); } /// /// %APPDATA%\RynthCore\RynthILT\{world}\{character}\bounties.json, or "" (no save file) while /// the character's name is unknown. Both names are reduced to safe folder names. /// private string BountyFilePath(out bool named) { named = false; uint me = Host.GetPlayerId(); if (me == 0 || !Host.HasGetObjectName || !Host.TryGetObjectName(me, out string charName) || string.IsNullOrWhiteSpace(charName)) return string.Empty; string world = Host.HasGetWorldName && Host.TryGetWorldName(out string w) && !string.IsNullOrWhiteSpace(w) ? w : "UnknownWorld"; named = true; return Path.Combine(SettingsRoot, SafeName(world), SafeName(charName), BountyTracker.FileName); } /// RynthILT's settings folder: %APPDATA%\RynthCore\RynthILT. internal static string SettingsRoot => Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "RynthILT"); /// A name safe as one folder: invalid characters become '_', no leading/trailing dots or spaces, at most 64 chars. internal static string SafeName(string name) { char[] invalid = Path.GetInvalidFileNameChars(); var chars = name.Trim().ToCharArray(); for (int i = 0; i < chars.Length; i++) if (Array.IndexOf(invalid, chars[i]) >= 0 || chars[i] == '/' || chars[i] == '\\') chars[i] = '_'; string s = new string(chars).Trim(' ', '.'); if (s.Length > 64) s = s.Substring(0, 64).TrimEnd(' ', '.'); return s.Length == 0 ? "_" : s; } }