Snapshot for release 2026.10.21.1 (internal 32a418d)

This commit is contained in:
Tom Bohar 2026-10-21 09:35:08 -04:00
commit 6fe5630e8c
202 changed files with 43765 additions and 0 deletions

View file

@ -0,0 +1,229 @@
// BountyParse.cs - Parses ACECustom's bounty output (BountyManager / BountyCommands).
//
// The progress itself (PropertyString BountyProgress) is server-only, so the tracker reads
// what the server prints. All lines are ChatMessageType.Broadcast:
// /bounty list "Bounties:" header, then one line per reward of every active area:
// " {where}: {amount} {item} every {N kill(s)}[ (at most every {wait})] - you: {status}."
// footer "Bounty: type /bounty to see the bounties where you stand."
// or "Bounty: there are no bounties anywhere right now."
// /bounty "Bounty[ (all zones)| ({region})]: {amount} {item} - {status}."
// or "Bounty: there is no bounty here."
// status "{k} of {n} kills" | "unlocks in {wait}, then {N kill(s)} required" | "needs {qb} QB (you have {n})"
// events "Bounty unlocked: {item} - {N kill(s)} required." "Bounty complete! +{n} {item} gained."
// "Next bounty unlocks in {wait} - {N kill(s)} required." "Next bounty requires {N kill(s)}."
// held rewards: "Bounty: +{n} ..." / "Bounty: Your inventory is full. ..."
// wait "45 sec", "5 min", "2 min 30 sec", "1 hr 15 sec" (FormatWait); numbers use N0 grouping.
// A server without the bounty system answers "Unknown command: bounty".
using System;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthILT.Bounty;
/// <summary>Where the player stands on one bounty reward.</summary>
internal enum BountyStatus
{
/// <summary>Kills are counting: Kills of KillsRequired.</summary>
Counting = 0,
/// <summary>The cooldown after the last award runs; kills do not count until UnlockAtUtc.</summary>
Cooldown = 1,
/// <summary>The player's QB is below the reward's minimum; kills do not count.</summary>
NeedsQb = 2,
}
/// <summary>One parsed status phrase.</summary>
internal readonly record struct BountyStatusInfo(BountyStatus Status, int Kills, int KillsRequired,
int WaitSeconds, long QbRequired, long QbHave);
/// <summary>One "/bounty list" line.</summary>
internal readonly record struct BountyListLine(string Where, long Amount, string Item, int KillsRequired,
int CooldownSeconds, BountyStatusInfo Status);
/// <summary>One "/bounty" (where you stand) line. Scope is "" (this dungeon/zone), "all zones" or a region name.</summary>
internal readonly record struct BountyHereLine(string Scope, long Amount, string Item, BountyStatusInfo Status);
/// <summary>Kind of a bounty chat event.</summary>
internal enum BountyEventKind { Unlocked, Complete, NextCooldown, NextReady, Held }
internal static class BountyParse
{
private const RegexOptions Opt = RegexOptions.Compiled | RegexOptions.CultureInvariant;
private const string Num = @"\d[\d,]*";
// Status alternatives are spelled out inside the line patterns so backtracking can place the
// " - " separator correctly when an item name itself contains " - ".
private const string StatusPattern =
@"(?<status>" + Num + @" of " + Num + @" kills?|unlocks in .+?, then " + Num + @" kills? required|needs "
+ Num + @" QB \(you have " + Num + @"\))";
/// <summary>"/bounty list" reward line (leading indentation already trimmed).</summary>
private static readonly Regex ListLine = new(
@"^(?<where>.+?): (?<amount>" + Num + @") (?<item>.+?) every (?<kills>" + Num + @") kills?"
+ @"(?: \(at most every (?<cd>[^)]+)\))? - you: " + StatusPattern + @"\.$", Opt);
/// <summary>"/bounty" reward line.</summary>
private static readonly Regex HereLine = new(
@"^Bounty(?: \((?<scope>[^)]+)\))?: (?<amount>" + Num + @") (?<item>.+?) - " + StatusPattern + @"\.$", Opt);
private static readonly Regex Counting = new(@"^(?<k>" + Num + @") of (?<n>" + Num + @") kills?$", Opt);
private static readonly Regex Cooldown = new(@"^unlocks in (?<wait>.+?), then (?<n>" + Num + @") kills? required$", Opt);
private static readonly Regex Qb = new(@"^needs (?<qb>" + Num + @") QB \(you have (?<have>" + Num + @")\)$", Opt);
private static readonly Regex WaitPart = new(@"(?<v>\d+)\s*(?<u>hr|min|sec)\b", Opt);
private static readonly Regex EvUnlocked = new(@"^Bounty unlocked: (?<item>.+) - (?<n>" + Num + @") kills? required\.$", Opt);
private static readonly Regex EvComplete = new(@"^Bounty complete! \+(?<n>" + Num + @") (?<item>.+) gained\.$", Opt);
private static readonly Regex EvNextWait = new(@"^Next bounty unlocks in (?<wait>.+?) - (?<n>" + Num + @") kills? required\.$", Opt);
private static readonly Regex EvNextReady = new(@"^Next bounty requires (?<n>" + Num + @") kills?\.$", Opt);
/// <summary>"/bounty list" header line.</summary>
public const string ListHeader = "Bounties:";
/// <summary>True for the line that ends a "/bounty list" reply (footer or "no bounties anywhere").</summary>
public static bool IsListTerminator(string text)
=> text.StartsWith("Bounty: type /bounty", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("Bounty: there are no bounties anywhere", StringComparison.OrdinalIgnoreCase);
/// <summary>True when the terminator says no bounty is active anywhere.</summary>
public static bool IsNoBountiesAnywhere(string text)
=> text.StartsWith("Bounty: there are no bounties anywhere", StringComparison.OrdinalIgnoreCase);
/// <summary>ACE's reply to a command the server doesn't register.</summary>
public static bool IsUnknownCommand(string text)
=> text.StartsWith("Unknown command: bounty", StringComparison.OrdinalIgnoreCase);
/// <summary>Parses a "/bounty list" reward line.</summary>
public static bool TryParseListLine(string text, out BountyListLine line)
{
line = default;
var m = ListLine.Match((text ?? string.Empty).Trim());
if (!m.Success || !TryParseStatus(m.Groups["status"].Value, out var status)) return false;
int required = ToInt(m.Groups["kills"].Value);
int cooldown = m.Groups["cd"].Success ? ParseWaitSeconds(m.Groups["cd"].Value) : 0;
line = new BountyListLine(m.Groups["where"].Value.Trim(), ParseLong(m.Groups["amount"].Value),
m.Groups["item"].Value.Trim(), required, cooldown, status);
return true;
}
/// <summary>Parses a "/bounty" (where you stand) reward line.</summary>
public static bool TryParseHereLine(string text, out BountyHereLine line)
{
line = default;
var m = HereLine.Match((text ?? string.Empty).Trim());
if (!m.Success || !TryParseStatus(m.Groups["status"].Value, out var status)) return false;
line = new BountyHereLine(m.Groups["scope"].Success ? m.Groups["scope"].Value.Trim() : string.Empty,
ParseLong(m.Groups["amount"].Value), m.Groups["item"].Value.Trim(), status);
return true;
}
/// <summary>Parses one status phrase (without the trailing period).</summary>
public static bool TryParseStatus(string text, out BountyStatusInfo status)
{
status = default;
string t = (text ?? string.Empty).Trim().TrimEnd('.');
var m = Counting.Match(t);
if (m.Success)
{
status = new BountyStatusInfo(BountyStatus.Counting, ToInt(m.Groups["k"].Value), ToInt(m.Groups["n"].Value), 0, 0, 0);
return true;
}
m = Cooldown.Match(t);
if (m.Success)
{
status = new BountyStatusInfo(BountyStatus.Cooldown, 0, ToInt(m.Groups["n"].Value),
ParseWaitSeconds(m.Groups["wait"].Value), 0, 0);
return true;
}
m = Qb.Match(t);
if (m.Success)
{
status = new BountyStatusInfo(BountyStatus.NeedsQb, 0, 0, 0,
ParseLong(m.Groups["qb"].Value), ParseLong(m.Groups["have"].Value));
return true;
}
return false;
}
/// <summary>"2 min 30 sec" → 150, "1 hr 15 sec" → 3615. 0 when nothing parses.</summary>
public static int ParseWaitSeconds(string text)
{
long total = 0;
foreach (Match m in WaitPart.Matches(text ?? string.Empty))
{
long v = ParseLong(m.Groups["v"].Value);
total += m.Groups["u"].Value switch { "hr" => v * 3600, "min" => v * 60, _ => v };
}
return (int)Math.Min(total, int.MaxValue);
}
/// <summary>
/// Recognises a bounty chat event (award, unlock, next cooldown, held reward). Item and
/// KillsRequired are filled when the line names them; WaitSeconds for "Next bounty unlocks in".
/// </summary>
public static bool TryParseEvent(string text, out BountyEventKind kind, out string item, out int killsRequired, out int waitSeconds)
{
kind = BountyEventKind.Held;
item = string.Empty;
killsRequired = 0;
waitSeconds = 0;
string t = (text ?? string.Empty).Trim();
if (t.Length == 0) return false;
Match m;
if ((m = EvUnlocked.Match(t)).Success)
{
kind = BountyEventKind.Unlocked;
item = m.Groups["item"].Value.Trim();
killsRequired = ToInt(m.Groups["n"].Value);
return true;
}
if ((m = EvComplete.Match(t)).Success)
{
kind = BountyEventKind.Complete;
item = m.Groups["item"].Value.Trim();
return true;
}
if ((m = EvNextWait.Match(t)).Success)
{
kind = BountyEventKind.NextCooldown;
waitSeconds = ParseWaitSeconds(m.Groups["wait"].Value);
killsRequired = ToInt(m.Groups["n"].Value);
return true;
}
if ((m = EvNextReady.Match(t)).Success)
{
kind = BountyEventKind.NextReady;
killsRequired = ToInt(m.Groups["n"].Value);
return true;
}
// Held-reward notices; the "/bounty" and "/bounty list" status lines also start with "Bounty: ".
if (t.StartsWith("Bounty: +", StringComparison.Ordinal)
|| t.StartsWith("Bounty: Your inventory is full", StringComparison.OrdinalIgnoreCase))
{
kind = BountyEventKind.Held;
return true;
}
return false;
}
/// <summary>Key that identifies one reward of one area across refreshes.</summary>
public static string Key(string where, long amount, string item, int killsRequired)
=> $"{where}|{amount}|{item}|{killsRequired}".ToLowerInvariant();
/// <summary>"1 hr 5 min", "45 sec", "2 days 3 hr". Negative spans read as 0 sec.</summary>
public static string Duration(TimeSpan span)
{
long s = Math.Max(0, (long)span.TotalSeconds);
if (s >= 86400) return $"{s / 86400} day{(s / 86400 == 1 ? "" : "s")}" + (s % 86400 >= 3600 ? $" {s % 86400 / 3600} hr" : "");
if (s >= 3600) return $"{s / 3600} hr" + (s % 3600 >= 60 ? $" {s % 3600 / 60} min" : "");
if (s >= 60) return $"{s / 60} min" + (s % 60 > 0 ? $" {s % 60} sec" : "");
return $"{s} sec";
}
/// <summary>Digits with "," grouping removed; 0 when nothing parses.</summary>
internal static long ParseLong(string text)
{
string digits = (text ?? string.Empty).Replace(",", string.Empty).Trim();
return long.TryParse(digits, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out long v) ? v : 0;
}
private static int ToInt(string text) => (int)Math.Min(ParseLong(text), int.MaxValue);
}

View file

@ -0,0 +1,714 @@
// BountyTracker.cs - Every ACECustom bounty and this character's progress, for the engine's Bounties window.
//
// The server keeps the counts (PropertyString BountyProgress is server-only), so the tracker reads
// "/bounty list", which reports every active bounty on the server - wherever the player stands -
// with the player's kills, cooldown or QB requirement for each. The read is a quiet capture (the
// reply is eaten from chat) and runs only while the engine's Bounties window polls the export:
// * when the window opens (and the list is old or kills happened while it was closed),
// * a moment after each of this character's kills,
// * after a bounty chat event ("Bounty complete!", "Bounty unlocked:", "Next bounty ..."),
// * every PeriodicRefreshMinutes as a backstop, and on Refresh / "/ilt bounty refresh".
// Every read, whatever asked for it, waits for MinRefreshSeconds (at least 5 s) since the last
// one, and none is sent while the window is closed (RynthILT review, 2026-10-09).
// Lines the player prints themselves ("/bounty list", "/bounty") update the list too, and are
// never eaten: a /bounty the player types (NoteTypedCommand) turns the capture it overlaps into
// a shown one, and a typed "/bounty list" stands in for the tracker's next read.
// Cooldowns count down locally from the read time; when one ends the bounty shows 0 of N kills,
// which is what the server says too (an award resets the count before the cooldown starts).
//
// Everything runs on the plugin's game thread: OnTick, chat, kills and the engine's export polls.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RynthCore.Plugin.RynthILT.Bounty;
/// <summary>Persisted per character (bounties.json): the window's options and the last list read.</summary>
internal sealed class BountyState
{
public bool RefreshOnKills = true;
public int MinRefreshSeconds = 10;
public int PeriodicRefreshMinutes = 5;
public bool HideQbLocked;
public bool SortByProgress;
public List<BountyEntry> Entries = new();
public DateTime ListedUtc;
public bool NoneAnywhere;
public string LastEvent = string.Empty;
public DateTime LastEventUtc;
}
/// <summary>One reward of one bounty area and where this character stands on it.</summary>
internal sealed class BountyEntry
{
public string Where = string.Empty;
public long Amount;
public string Item = string.Empty;
public int KillsRequired;
public int CooldownSeconds;
/// <summary>A <see cref="BountyStatus"/> value.</summary>
public int Status;
public int Kills;
public DateTime UnlockAtUtc;
public long QbRequired;
public long QbHave;
/// <summary>Last time the kills went up or an award reset them (row highlight).</summary>
public DateTime ChangedUtc;
}
/// <summary>
/// RynthPluginGetBountiesJson payload. Mirrored by RynthCore.Engine UI/Data/BountiesSnapshotJson.cs;
/// either side may add fields (unknown ones are skipped, missing ones keep their defaults).
/// </summary>
internal sealed class BountyBridgePayload
{
[JsonPropertyName("unsupported")] public bool Unsupported;
[JsonPropertyName("reading")] public bool Reading;
[JsonPropertyName("status")] public string Status = string.Empty;
/// <summary>Seconds since the last list read; -1 = never.</summary>
[JsonPropertyName("listedAgoSec")] public int ListedAgoSec = -1;
[JsonPropertyName("noneAnywhere")] public bool NoneAnywhere;
[JsonPropertyName("lastEvent")] public string LastEvent = string.Empty;
[JsonPropertyName("lastEventAgoSec")] public int LastEventAgoSec = -1;
[JsonPropertyName("refreshOnKills")] public bool RefreshOnKills;
[JsonPropertyName("minRefreshSeconds")] public int MinRefreshSeconds;
[JsonPropertyName("periodicRefreshMinutes")] public int PeriodicRefreshMinutes;
[JsonPropertyName("hideQbLocked")] public bool HideQbLocked;
[JsonPropertyName("sortByProgress")] public bool SortByProgress;
/// <summary>Rows not shown because of HideQbLocked.</summary>
[JsonPropertyName("hiddenCount")] public int HiddenCount;
[JsonPropertyName("rows")] public List<BountyRow> Rows = new();
}
/// <summary>One row of <see cref="BountyBridgePayload"/>, with the status as of the poll.</summary>
internal sealed class BountyRow
{
[JsonPropertyName("where")] public string Where = string.Empty;
[JsonPropertyName("amount")] public long Amount;
[JsonPropertyName("item")] public string Item = string.Empty;
[JsonPropertyName("killsRequired")] public int KillsRequired;
[JsonPropertyName("cooldownSeconds")] public int CooldownSeconds;
/// <summary>A <see cref="BountyStatus"/> value; an ended cooldown is already Counting.</summary>
[JsonPropertyName("status")] public int Status;
[JsonPropertyName("kills")] public int Kills;
[JsonPropertyName("unlockInSec")] public int UnlockInSec;
[JsonPropertyName("qbRequired")] public long QbRequired;
[JsonPropertyName("qbHave")] public long QbHave;
/// <summary>Kills went up (or an award reset them) in the last 15 seconds.</summary>
[JsonPropertyName("changed")] public bool Changed;
}
internal sealed class BountyTracker
{
/// <summary>The capture command; "/bounty all" is the same list.</summary>
public const string ListCommand = "/bounty list";
/// <summary>Lowest allowed MinRefreshSeconds (the server is asked at most this often after kills).</summary>
public const int MinRefreshFloorSeconds = 5;
public const int MinRefreshCeilingSeconds = 300;
public const int PeriodicCeilingMinutes = 60;
public const string FileName = "bounties.json";
/// <summary>Wait after a kill so a burst of kills (and the server's own award lines) lands in one read.</summary>
private const long KillDebounceMs = 2000;
/// <summary>Wait after a bounty chat event before re-reading.</summary>
private const long EventDebounceMs = 1500;
/// <summary>The window counts as open while the engine polled the export this recently (it polls every second).</summary>
private const long WindowPollWindowMs = 3000;
/// <summary>A capture with no reply line by then is abandoned.</summary>
private const long FirstLineTimeoutMs = 10000;
/// <summary>A capture whose footer never came ends this long after its last line.</summary>
private const long IdleEndMs = 1500;
/// <summary>The engine may pass our own /bounty list back through the chat bar hook this soon after sending it.</summary>
private const long OwnEchoMs = 2000;
/// <summary>Longer chat lines are never parsed (no bounty line is near this; bounds the regex work).</summary>
private const int MaxLineLength = 512;
private const long SaveDebounceMs = 5000;
/// <summary>A list older than this is re-read when the window opens.</summary>
private static readonly TimeSpan OpenRefreshAge = TimeSpan.FromSeconds(30);
/// <summary>How long a row stays highlighted after its kills went up.</summary>
private static readonly TimeSpan ChangedHighlight = TimeSpan.FromSeconds(15);
private readonly Action<string> _send;
private readonly Action<string> _chat;
private readonly Action<string> _log;
private readonly string _filePath;
private readonly Func<long> _clock;
private BountyState _s;
// Scheduling.
private long _dueAtMs; // 0 = no read scheduled
private long _lastSentMs; // 0 = never this session
private long _lastPollMs; // last engine poll of the export; 0 = never
private bool _wasOpen;
private bool _stale; // kills or bounty events happened while the window was closed
// The quiet "/bounty list" capture.
private bool _capActive;
private bool _capShown; // the player asked too (NoteTypedCommand): parse, never eat
private bool _expectEcho; // our /bounty list may come back through the chat bar hook
private long _capSentMs;
private long _capLastLineMs; // 0 = no reply line yet
private readonly List<BountyListLine> _capLines = new();
private bool _unsupported;
private string _status = string.Empty;
private bool _dirty;
private long _lastSaveMs;
/// <param name="send">Sends a chat command to the server (Host.InvokeChatParser).</param>
/// <param name="chat">Prints a line to the player's chat window.</param>
/// <param name="log">Writes to the RynthCore log.</param>
/// <param name="filePath">bounties.json in the character folder; empty = not persisted.</param>
/// <param name="clock">Milliseconds clock; Environment.TickCount64 unless a test supplies one.</param>
public BountyTracker(Action<string> send, Action<string> chat, Action<string> log, string filePath, Func<long>? clock = null)
{
_send = send;
_chat = chat;
_log = log;
_filePath = filePath ?? string.Empty;
_clock = clock ?? (() => Environment.TickCount64);
_s = Load();
}
private long NowMs => _clock();
/// <summary>The persisted state (host tests).</summary>
internal BountyState State => _s;
/// <summary>True once the server answered "Unknown command: bounty" (no bounty system on this server).</summary>
public bool Unsupported => _unsupported;
/// <summary>True while a "/bounty list" reply is being captured.</summary>
public bool Reading => _capActive;
/// <summary>True while the engine's Bounties window is polling the export.</summary>
public bool WindowOpen => _lastPollMs != 0 && NowMs - _lastPollMs < WindowPollWindowMs;
// ── Scheduling ──────────────────────────────────────────────────────────
/// <summary>
/// Schedules a "/bounty list" read; the earliest pending request wins. Every read waits for
/// MinRefreshSeconds since the last one; <paramref name="respectMinInterval"/> false (a manual
/// refresh) waits only for the MinRefreshFloorSeconds floor.
/// </summary>
private void Schedule(long nowMs, long delayMs, bool respectMinInterval)
{
long due = nowMs + delayMs;
if (_lastSentMs != 0)
due = Math.Max(due, _lastSentMs + (respectMinInterval ? _s.MinRefreshSeconds : MinRefreshFloorSeconds) * 1000L);
if (_dueAtMs == 0 || due < _dueAtMs) _dueAtMs = due;
}
/// <summary>
/// Manual refresh (window button, "/ilt bounty refresh"): retries an unsupported server and
/// reads as soon as the 5 s floor since the last read allows. Never sends with the window
/// closed: the next open reads instead.
/// </summary>
public string RequestRefresh()
{
_unsupported = false;
if (!WindowOpen)
{
_stale = true;
return "The list is read while the Bounties window is open (the ILT button, or /rc bounties).";
}
long now = NowMs;
Schedule(now, 0, respectMinInterval: false);
return "Reading /bounty list...";
}
/// <summary>One of this character's kills (RynthILTPlugin.OnKillNotification).</summary>
public void OnKill()
{
if (!_s.RefreshOnKills || _unsupported) return;
if (WindowOpen) Schedule(NowMs, KillDebounceMs, respectMinInterval: true);
else _stale = true;
}
private void Send(long nowMs)
{
if (_capActive) { _dueAtMs = 0; return; }
// The invariants, whatever scheduled this: the window is open, and the last read was at
// least MinRefreshFloorSeconds ago (else the read waits until then).
if (!WindowOpen) { _dueAtMs = 0; return; }
if (_lastSentMs != 0 && nowMs - _lastSentMs < MinRefreshFloorSeconds * 1000L)
{
_dueAtMs = _lastSentMs + MinRefreshFloorSeconds * 1000L;
return;
}
_dueAtMs = 0;
_lastSentMs = nowMs;
StartCapture(nowMs, shown: false);
_expectEcho = true;
try { _send(ListCommand); }
catch (Exception ex)
{
_capActive = false;
_expectEcho = false;
_status = "could not send /bounty list";
_log($"[RynthILT] Bounties: sending {ListCommand} failed: {ex.Message}");
}
}
private void StartCapture(long nowMs, bool shown)
{
_capActive = true;
_capShown = shown;
_capSentMs = nowMs;
_capLastLineMs = 0;
_capLines.Clear();
}
/// <summary>
/// A "/bounty ..." the player typed (the plugin's OnChatBarEnter, passed on on the pump).
/// Its reply is never eaten: an overlapping capture of ours becomes a shown one, and a typed
/// "/bounty list" (or "/bounty all") starts a shown capture that counts as the next read, so
/// the tracker doesn't send its own on top. Our own command coming back through the chat
/// bar hook right after we sent it is recognised and ignored.
/// </summary>
public void NoteTypedCommand(string text)
{
string t = (text ?? string.Empty).Trim();
long now = NowMs;
if (_expectEcho && now - _capSentMs <= OwnEchoMs && string.Equals(t, ListCommand, StringComparison.OrdinalIgnoreCase))
{
_expectEcho = false;
return;
}
_expectEcho = false;
if (_capActive) { _capShown = true; return; }
if (!IsListCommand(t)) return;
_lastSentMs = now;
_dueAtMs = 0;
StartCapture(now, shown: true);
}
/// <summary>"/bounty list" or "/bounty all" (or with ACE's '@' command prefix).</summary>
internal static bool IsListCommand(string text)
{
string[] parts = (text ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
return parts.Length == 2
&& (parts[0].Equals("/bounty", StringComparison.OrdinalIgnoreCase) || parts[0].Equals("@bounty", StringComparison.OrdinalIgnoreCase))
&& (parts[1].Equals("list", StringComparison.OrdinalIgnoreCase) || parts[1].Equals("all", StringComparison.OrdinalIgnoreCase));
}
/// <summary>True for a chat-bar line that is a /bounty command (what the plugin passes to NoteTypedCommand).</summary>
public static bool IsBountyCommand(string? text)
{
string t = (text ?? string.Empty).TrimStart();
if (!t.StartsWith("/bounty", StringComparison.OrdinalIgnoreCase) && !t.StartsWith("@bounty", StringComparison.OrdinalIgnoreCase))
return false;
return t.Length == 7 || t[7] == ' '; // "/bounty" or "/bounty ...", not "/bountyhunter"
}
public void Tick()
{
long now = NowMs;
if (_capActive)
{
if (_capLastLineMs == 0 && now - _capSentMs >= FirstLineTimeoutMs)
{
_capActive = false;
_expectEcho = false;
if (!_capShown) _status = "no reply to /bounty list";
}
else if (_capLastLineMs != 0 && now - _capLastLineMs >= IdleEndMs)
{
FinishCapture(terminator: null);
}
}
if (_dirty && now - _lastSaveMs >= SaveDebounceMs) Save();
bool open = WindowOpen;
if (!open) { _wasOpen = false; _dueAtMs = 0; return; }
if (!_wasOpen)
{
_wasOpen = true;
if (_stale || _lastSentMs == 0 || DateTime.UtcNow - _s.ListedUtc > OpenRefreshAge)
Schedule(now, 0, respectMinInterval: true);
_stale = false;
}
if (_s.PeriodicRefreshMinutes > 0 && _lastSentMs != 0 && now - _lastSentMs >= _s.PeriodicRefreshMinutes * 60_000L)
Schedule(now, 0, respectMinInterval: true);
if (_dueAtMs != 0 && now >= _dueAtMs && !_unsupported) Send(now);
}
private void FinishCapture(string? terminator)
{
_capActive = false;
_expectEcho = false;
bool complete = terminator != null;
bool none = complete && BountyParse.IsNoBountiesAnywhere(terminator!);
ApplyList(_capLines, complete, none, DateTime.UtcNow);
_status = complete ? string.Empty : "partial reply";
_capLines.Clear();
}
// ── Chat ────────────────────────────────────────────────────────────────
/// <summary>
/// One chat line. Returns true when it belongs to our own "/bounty list" read and should be
/// eaten; everything else (the player's own bounty output, award lines) stays in chat.
/// </summary>
public bool OnChat(string text)
{
string t = (text ?? string.Empty).Trim();
if (t.Length == 0 || t.Length > MaxLineLength) return false;
long now = NowMs;
if (_capActive)
{
// A shown capture (the player asked too) parses the same lines but eats none.
bool eat = !_capShown;
if (BountyParse.IsUnknownCommand(t))
{
_capActive = false;
_expectEcho = false;
_capLines.Clear();
_unsupported = true;
_status = "this server has no /bounty command";
_log("[RynthILT] Bounties: server has no /bounty command; automatic reads stopped.");
return eat;
}
if (t == BountyParse.ListHeader) { _capLastLineMs = now; return eat; }
if (BountyParse.TryParseListLine(t, out var captured)) { _capLines.Add(captured); _capLastLineMs = now; return eat; }
if (BountyParse.IsListTerminator(t)) { FinishCapture(t); return eat; }
}
if (BountyParse.TryParseListLine(t, out var listLine))
{
ApplyList(new[] { listLine }, complete: false, noneAnywhere: false, DateTime.UtcNow);
return false;
}
if (BountyParse.TryParseHereLine(t, out var here))
{
ApplyHere(here, DateTime.UtcNow);
return false;
}
if (BountyParse.TryParseEvent(t, out var kind, out _, out _, out _))
{
_s.LastEvent = t;
_s.LastEventUtc = DateTime.UtcNow;
_dirty = true;
if (kind != BountyEventKind.Held)
{
// Awards can come every kill (a 1-kill bounty with no cooldown): the interval holds.
if (WindowOpen) Schedule(now, EventDebounceMs, respectMinInterval: true);
else _stale = true;
}
}
return false;
}
// ── Applying server output (internal for the host tests) ────────────────
/// <summary>
/// Applies parsed "/bounty list" lines. A complete reply (footer seen) replaces the list in
/// server order; a partial one only updates or appends the rewards it names.
/// </summary>
internal void ApplyList(IReadOnlyList<BountyListLine> lines, bool complete, bool noneAnywhere, DateTime nowUtc)
{
var old = new Dictionary<string, BountyEntry>(StringComparer.OrdinalIgnoreCase);
foreach (var e in _s.Entries)
old[BountyParse.Key(e.Where, e.Amount, e.Item, e.KillsRequired)] = e;
var fresh = new List<BountyEntry>(lines.Count);
foreach (var l in lines)
{
old.TryGetValue(BountyParse.Key(l.Where, l.Amount, l.Item, l.KillsRequired), out var prev);
var e = new BountyEntry
{
Where = l.Where,
Amount = l.Amount,
Item = l.Item,
KillsRequired = l.KillsRequired,
CooldownSeconds = l.CooldownSeconds,
ChangedUtc = prev?.ChangedUtc ?? default,
};
ApplyStatus(e, l.Status, prev, nowUtc);
fresh.Add(e);
}
if (complete)
{
_s.Entries = fresh;
}
else
{
foreach (var e in fresh)
{
string key = BountyParse.Key(e.Where, e.Amount, e.Item, e.KillsRequired);
int i = _s.Entries.FindIndex(x => string.Equals(BountyParse.Key(x.Where, x.Amount, x.Item, x.KillsRequired),
key, StringComparison.OrdinalIgnoreCase));
if (i >= 0) _s.Entries[i] = e; else _s.Entries.Add(e);
}
}
if (complete || lines.Count > 0) _s.ListedUtc = nowUtc;
if (complete) _s.NoneAnywhere = noneAnywhere;
_dirty = true;
}
/// <summary>
/// Applies a "/bounty" (where you stand) line to the one listed reward it can only mean.
/// Returns false when no reward or more than one matches.
/// </summary>
internal bool ApplyHere(BountyHereLine h, DateTime nowUtc)
{
BountyEntry? match = null;
foreach (var e in _s.Entries)
{
if (e.Amount != h.Amount || !string.Equals(e.Item, h.Item, StringComparison.OrdinalIgnoreCase)) continue;
if (h.Status.KillsRequired > 0 && e.KillsRequired != h.Status.KillsRequired) continue;
bool allZones = string.Equals(e.Where, "All zones", StringComparison.OrdinalIgnoreCase);
bool scopeOk = h.Scope.Length == 0 ? !allZones
: h.Scope.Equals("all zones", StringComparison.OrdinalIgnoreCase) ? allZones
: string.Equals(e.Where, h.Scope, StringComparison.OrdinalIgnoreCase);
if (!scopeOk) continue;
if (match != null) return false; // ambiguous: two areas pay the same reward
match = e;
}
if (match == null) return false;
var prev = new BountyEntry { Status = match.Status, Kills = match.Kills };
ApplyStatus(match, h.Status, prev, nowUtc);
_dirty = true;
return true;
}
/// <summary>Copies a parsed status onto <paramref name="e"/> and stamps ChangedUtc when kills went up or an award reset them.</summary>
private static void ApplyStatus(BountyEntry e, BountyStatusInfo st, BountyEntry? prev, DateTime nowUtc)
{
e.Status = (int)st.Status;
e.Kills = st.Status == BountyStatus.Counting ? st.Kills : 0;
e.UnlockAtUtc = st.Status == BountyStatus.Cooldown ? nowUtc.AddSeconds(st.WaitSeconds) : default;
e.QbRequired = st.QbRequired;
e.QbHave = st.QbHave;
if (prev == null) return;
bool wasCounting = prev.Status == (int)BountyStatus.Counting;
bool gained = wasCounting && st.Status == BountyStatus.Counting && st.Kills > prev.Kills;
bool awarded = wasCounting && prev.Kills > 0
&& (st.Status == BountyStatus.Cooldown || (st.Status == BountyStatus.Counting && st.Kills < prev.Kills));
if (gained || awarded) e.ChangedUtc = nowUtc;
}
/// <summary>The status to show now: a cooldown that has ended is "0 of N kills".</summary>
internal static (BountyStatus Status, int Kills) Effective(BountyEntry e, DateTime nowUtc)
{
var st = (BountyStatus)e.Status;
if (st == BountyStatus.Cooldown && nowUtc >= e.UnlockAtUtc) return (BountyStatus.Counting, 0);
return (st, st == BountyStatus.Counting ? e.Kills : 0);
}
/// <summary>"Closest first" order: counting by fraction left, then cooldowns by time left, then QB-locked.</summary>
private static double SortKey(BountyEntry e, DateTime now)
{
var (st, kills) = Effective(e, now);
return st switch
{
BountyStatus.Counting => e.KillsRequired > 0 ? 1.0 - kills / (double)e.KillsRequired : 1.0,
BountyStatus.Cooldown => 2.0 + Math.Min((e.UnlockAtUtc - now).TotalSeconds, 1e9) / 1e9,
_ => 4.0,
};
}
// ── Engine bridge ───────────────────────────────────────────────────────
/// <summary>RynthPluginGetBountiesJson. Each call also marks the window open for the read schedule.</summary>
public string BuildJson()
{
_lastPollMs = NowMs;
var now = DateTime.UtcNow;
var p = new BountyBridgePayload
{
Unsupported = _unsupported,
Reading = _capActive,
Status = _status,
ListedAgoSec = _s.ListedUtc == default ? -1 : AgoSeconds(now - _s.ListedUtc),
NoneAnywhere = _s.NoneAnywhere,
LastEvent = _s.LastEvent,
LastEventAgoSec = _s.LastEventUtc == default ? -1 : AgoSeconds(now - _s.LastEventUtc),
RefreshOnKills = _s.RefreshOnKills,
MinRefreshSeconds = _s.MinRefreshSeconds,
PeriodicRefreshMinutes = _s.PeriodicRefreshMinutes,
HideQbLocked = _s.HideQbLocked,
SortByProgress = _s.SortByProgress,
};
IEnumerable<BountyEntry> shown = _s.Entries;
if (_s.HideQbLocked)
{
p.HiddenCount = _s.Entries.Count(e => e.Status == (int)BountyStatus.NeedsQb);
shown = shown.Where(e => e.Status != (int)BountyStatus.NeedsQb);
}
if (_s.SortByProgress) shown = shown.OrderBy(e => SortKey(e, now));
foreach (var e in shown)
{
var (st, kills) = Effective(e, now);
p.Rows.Add(new BountyRow
{
Where = e.Where,
Amount = e.Amount,
Item = e.Item,
KillsRequired = e.KillsRequired,
CooldownSeconds = e.CooldownSeconds,
Status = (int)st,
Kills = kills,
UnlockInSec = st == BountyStatus.Cooldown ? AgoSeconds(e.UnlockAtUtc - now) : 0,
QbRequired = e.QbRequired,
QbHave = e.QbHave,
Changed = e.ChangedUtc != default && now - e.ChangedUtc < ChangedHighlight,
});
}
return JsonSerializer.Serialize(p, RynthILTJsonContext.Default.BountyBridgePayload);
}
private static int AgoSeconds(TimeSpan span) => (int)Math.Clamp(span.TotalSeconds, 0, int.MaxValue);
/// <summary>
/// RynthPluginBountyCommand: "refresh", or "set {option} {value}" with option one of
/// refreshonkills, minrefreshseconds, periodicminutes, hideqblocked, sortbyprogress.
/// </summary>
public string Command(string text)
{
string[] parts = (text ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0) return string.Empty;
switch (parts[0].ToLowerInvariant())
{
case "refresh":
case "read":
return RequestRefresh();
case "set" when parts.Length >= 3:
return SetOption(parts[1], parts[2]);
default:
return $"unknown bounty command '{text}'";
}
}
private string SetOption(string name, string value)
{
bool on = value is "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase)
|| value.Equals("on", StringComparison.OrdinalIgnoreCase);
int.TryParse(value, out int n);
switch (name.ToLowerInvariant())
{
case "refreshonkills": _s.RefreshOnKills = on; break;
case "minrefreshseconds": _s.MinRefreshSeconds = Math.Clamp(n, MinRefreshFloorSeconds, MinRefreshCeilingSeconds); break;
case "periodicminutes": _s.PeriodicRefreshMinutes = Math.Clamp(n, 0, PeriodicCeilingMinutes); break;
case "hideqblocked": _s.HideQbLocked = on; break;
case "sortbyprogress": _s.SortByProgress = on; break;
default: return $"unknown bounty option '{name}'";
}
_dirty = true;
return string.Empty;
}
// ── Chat command ────────────────────────────────────────────────────────
/// <summary>"/ilt bounty [refresh|list]".</summary>
public void HandleChatCommand(string[] parts)
{
string verb = parts.Length >= 3 ? parts[2].ToLowerInvariant() : "list";
switch (verb)
{
case "refresh":
case "read":
_chat("[Bounties] " + RequestRefresh());
break;
case "list":
case "print":
case "show":
PrintList();
_chat("[Bounties] The Bounties window: the ILT button on the RynthCore bar, or /rc bounties.");
break;
default:
_chat("[Bounties] /ilt bounty [list|refresh] - list the tracked bounties, or re-read /bounty list (while the window is open).");
break;
}
}
/// <summary>One-line chat text for an entry.</summary>
internal static string Describe(BountyEntry e, DateTime nowUtc)
{
var (st, kills) = Effective(e, nowUtc);
string reward = $"{e.Amount:N0} {e.Item}";
return st switch
{
BountyStatus.Counting => $"{e.Where}: {kills:N0}/{e.KillsRequired:N0} kills -> {reward}",
BountyStatus.Cooldown => $"{e.Where}: unlocks in {BountyParse.Duration(e.UnlockAtUtc - nowUtc)}, then {e.KillsRequired:N0} kills -> {reward}",
_ => $"{e.Where}: needs {e.QbRequired:N0} QB (you have {e.QbHave:N0}) -> {reward}",
};
}
/// <summary>"/ilt bounty list": the tracked bounties in chat.</summary>
public void PrintList()
{
if (_unsupported) { _chat("[Bounties] This server has no /bounty command."); return; }
if (_s.Entries.Count == 0)
{
_chat(_s.NoneAnywhere ? "[Bounties] No bounties are active anywhere right now."
: "[Bounties] Nothing read yet. Open the Bounties window (the ILT button, or /rc bounties).");
return;
}
var now = DateTime.UtcNow;
string age = _s.ListedUtc == default ? "never" : BountyParse.Duration(now - _s.ListedUtc) + " ago";
_chat($"[Bounties] {_s.Entries.Count} bounty reward(s), read {age}:");
foreach (var e in _s.Entries) _chat("[Bounties] " + Describe(e, now));
}
// ── Persistence ─────────────────────────────────────────────────────────
private BountyState Load()
{
var s = new BountyState();
try
{
if (_filePath.Length > 0 && File.Exists(_filePath))
s = JsonSerializer.Deserialize(File.ReadAllText(_filePath), RynthILTJsonContext.Default.BountyState) ?? new BountyState();
}
catch (Exception ex)
{
_log($"[RynthILT] Bounties: {_filePath} unreadable, starting empty: {ex.Message}");
s = new BountyState();
}
s.Entries ??= new List<BountyEntry>();
s.Entries.RemoveAll(e => e == null);
s.LastEvent ??= string.Empty;
s.MinRefreshSeconds = Math.Clamp(s.MinRefreshSeconds, MinRefreshFloorSeconds, MinRefreshCeilingSeconds);
s.PeriodicRefreshMinutes = Math.Clamp(s.PeriodicRefreshMinutes, 0, PeriodicCeilingMinutes);
return s;
}
/// <summary>Writes bounties.json when something changed (also called at logout).</summary>
public void Save()
{
_lastSaveMs = NowMs;
if (!_dirty || _filePath.Length == 0) { _dirty = false; return; }
_dirty = false;
string json;
try { json = JsonSerializer.Serialize(_s, RynthILTJsonContext.Default.BountyState); }
catch (Exception ex)
{
_log($"[RynthILT] Bounties: saving {_filePath} failed: {ex.Message}");
return;
}
// A failed write is said in chat once per folder (on ILT) and logged; it stays dirty so the
// next debounced save tries again.
if (!RynthCore.Plugin.Shared.DataWriteGuard.TrySave("the bounty list", _filePath, () =>
{
string? dir = Path.GetDirectoryName(_filePath);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
string tmp = _filePath + ".tmp";
File.WriteAllText(tmp, json);
File.Move(tmp, _filePath, overwrite: true);
}))
_dirty = true;
}
}

View file

@ -0,0 +1,173 @@
// DataInterface.cs - RynthILT's side of the "RynthILT.Data" interface (Plugins/Shared/RynthIltDataApi.cs):
// the charms list and the bank balances (every character RynthILT has seen on this server) the
// Mini Remote's Charms and Banking tabs show, for other plugins to draw, with the charm Toggle and
// the bank verbs they send back; since version 2 also the pet breeding tracker's JSON and verbs;
// since version 3 the Temple guardians' JSON and verbs. (RynthOracle and RynthInventory drew them
// until 2026-10-21; those screens are RynthILT's own now, so no RynthSuite plugin reads this table.)
//
// The table is allocated once per loaded copy of RynthILT and never freed (a plugin DLL is never
// unloaded); after Release() it reports Version 0 and every function answers 0. Before login there
// is no controller: the JSON getters answer 0 (nothing to report) and the actions are refused.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT;
internal static unsafe class DataInterface
{
/// <summary>Longest bank / breeding verb line taken (a transfer with a long character name fits easily).</summary>
private const int MaxVerbBytes = 256;
private static RynthIltDataApiV1* _table;
private static volatile bool _released;
/// <summary>The table for (<paramref name="iface"/>, <paramref name="version"/>), or 0 when it isn't ours.</summary>
public static IntPtr Query(string iface, uint version)
{
if (iface != RynthIltDataApiV1.InterfaceName || version < 1 || version > RynthIltDataApiV1.InterfaceVersion || _released)
return IntPtr.Zero;
if (_table == null)
{
var t = (RynthIltDataApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthIltDataApiV1));
t->StructSize = (uint)sizeof(RynthIltDataApiV1);
t->GetCharmsJson = &GetCharmsJson;
t->GetBankJson = &GetBankJson;
t->ToggleCharm = &ToggleCharm;
t->BankCommand = &BankCommand;
t->GetPetBreedingJson = &GetPetBreedingJson;
t->PetBreedingCommand = &PetBreedingCommand;
t->GetGuardianJson = &GetGuardianJson;
t->GuardianCommand = &GuardianCommand;
t->Version = RynthIltDataApiV1.InterfaceVersion;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>Plugin shutdown: readers see Version 0 and re-query; every function answers 0.</summary>
public static void Release()
{
_released = true;
if (_table != null) _table->Version = 0;
}
private static IltHubController? Hub => _released ? null : PluginExports.Runtime.Plugin?.Hub;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetCharmsJson(byte* buffer, int capacity)
{
try
{
string? json = Hub?.CharmsJson;
return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity);
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetBankJson(byte* buffer, int capacity)
{
try
{
string? json = Hub?.BankJson;
return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity);
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ToggleCharm(uint objectId)
{
try
{
IltHubController? hub = Hub;
if (hub == null || objectId == 0) return 0;
hub.RequestCharmToggle(objectId);
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int BankCommand(byte* utf8)
{
try
{
IltHubController? hub = Hub;
if (hub == null) return 0;
string? line = ReadVerb(utf8);
if (line == null) return 0;
hub.RequestBankVerb(line);
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetPetBreedingJson(byte* buffer, int capacity)
{
try
{
string? json = Hub?.PetBreedingJson;
return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity);
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int PetBreedingCommand(byte* utf8)
{
try
{
IltHubController? hub = Hub;
if (hub == null) return 0;
string? line = ReadVerb(utf8);
if (line == null) return 0;
hub.RequestBreedingVerb(line);
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetGuardianJson(byte* buffer, int capacity)
{
try
{
string? json = Hub?.GuardianJson;
return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity);
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GuardianCommand(byte* utf8)
{
try
{
IltHubController? hub = Hub;
if (hub == null) return 0;
string? line = ReadVerb(utf8);
if (line == null) return 0;
hub.RequestGuardianVerb(line);
return 1;
}
catch { return 0; }
}
/// <summary>A reader's verb line, or null when it is empty, too long or not plain ASCII (no control characters reach a chat command).</summary>
private static string? ReadVerb(byte* utf8)
{
if (utf8 == null) return null;
int len = 0;
while (len < MaxVerbBytes && utf8[len] != 0) len++;
if (len == 0 || len >= MaxVerbBytes) return null;
string line = System.Text.Encoding.UTF8.GetString(utf8, len);
foreach (char c in line)
if (c < 0x20 || c > 0x7E) return null;
return line;
}
}

View file

@ -0,0 +1,638 @@
// IltAttributeRaiser.cs — Infinite attributes: spend unassigned XP with the server's /attr.
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// ACECustom (Infinite Leaftide) lets attributes and vitals go past the retail cap, so the
// client's XP tables stop applying. The server is the only source of truth:
// "/xp all" → "[XP] Your XP cost for next 1 Strength level is: 1,234" per stat
// "/attr <abbr> <n>" → "[ATTR] Strength attribute raised by 1, costing 1,234!"
// (Same commands UB's Leaftide XP Calculator drives; it raises one level at a time and
// re-reads the costs after each confirmation, which is what this does too.)
//
// Raise now / auto-raise run one loop: read costs → pick a stat → /attr <abbr> 1 → wait for
// the [ATTR] reply → read costs again → ... until nothing ticked is affordable, a reply is
// not a success, or MaxRaisesPerRun. Only the ticked stats are ever spent on, never below
// the reserve (AttrKeepXp). Which stat comes next depends on the raise mode:
// Priority the first ticked stat in the order that is affordable (fills the top stat)
// RoundRobin one level per ticked stat in order, then around again
// Cheapest the ticked stat with the lowest next-level cost
// Manual +1 / +10 buttons send "/attr <abbr> N" straight to the server (its reply shows in chat)
// once the known (+1) or projected (+10, 7.7% per level as in UB) cost fits the unassigned XP.
//
// Gated on ServerFeatureGate (via IltServerOptions.IsIltLikeWorld) and on the server not
// reporting /xp off. Everything here runs on the plugin pump thread.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltAttributeRaiser
{
/// <summary>Raise modes (IltCharacterState.AttrRaiseMode).</summary>
public enum Mode { Priority = 0, RoundRobin = 1, Cheapest = 2 }
/// <summary>/attr abbreviation, display name, vital?</summary>
public sealed record Stat(string Abbr, string Name, bool Vital);
public static readonly Stat[] Stats =
{
new("str", "Strength", false), new("end", "Endurance", false), new("coo", "Coordination", false),
new("qui", "Quickness", false), new("foc", "Focus", false), new("sel", "Self", false),
new("hea", "Health", true), new("sta", "Stamina", true), new("man", "Mana", true),
};
/// <summary>UB's default priority (Coordination, Quickness, Strength, Endurance, Focus, Self, vitals).</summary>
public static readonly string[] DefaultOrder = { "coo", "qui", "str", "end", "foc", "sel", "hea", "sta", "man" };
public const int MaxRaisesPerRun = 200;
/// <summary>
/// Per-level growth for projecting several levels from the one cost "/xp all" reports (UB's
/// Leaftide XP tab uses the same 7.7%). The server prices each level itself; this only labels
/// the +10 button and gates it on the XP you have.
/// </summary>
public const double ProjectedLevelGrowth = 0.077;
private const long FirstAutoDelayMs = 30_000; // after login / arming, before the first auto run
private const int ReplyTimeoutMs = 8000;
/// <summary>A run with no reply/step for this long is ended (a lost callback must not wedge it).</summary>
private const long StallMs = 45_000;
/// <summary>"Your base Strength is now 250!" / "Your base Maximum Health is now 900!" (older servers / UB wording).</summary>
private static readonly Regex BaseNow = new(@"Your base (?:Maximum )?(\w+) is now (\d+)!", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private readonly IltHubContext _ctx;
// Last known costs (display, and the passive chat reader). A run decides only from _runCosts:
// the costs in the "/xp all" reply read right before that step, never an older value.
private readonly Dictionary<string, long> _cost = new(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, long> _runCosts = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, int> _base = new(StringComparer.OrdinalIgnoreCase);
private long _costsAtMs;
private DateTime _costsAtLocal;
// Opening the Progression tab reads the costs once per login, like UB's XP tab does on load.
private bool _autoCostsTried;
// Run state. _runId guards against a capture that completes after Stop / a newer run.
private enum Phase { Idle, ReadingCosts, Raising }
private Phase _phase;
private int _runId;
private bool _runAuto;
private int _runRaised;
private long _runSpent;
private readonly Dictionary<string, int> _runGains = new(StringComparer.OrdinalIgnoreCase);
private int _rrNext;
private string _raisingAbbr = string.Empty;
private long _raisingCost;
private long _lastProgressMs;
private long _nextAutoAtMs;
private volatile string _status = "Idle.";
private volatile string _lastRun = string.Empty;
public IltAttributeRaiser(IltHubContext ctx) => _ctx = ctx;
/// <summary>
/// True while another XP spender runs (IltProgression's spend-before-/enl loop sends /attr
/// outside the capture queue). Nothing here starts, by hand or on the timer, while it is.
/// </summary>
public Func<bool>? HoldOff { get; set; }
private bool HeldOff
{
get { try { return HoldOff?.Invoke() == true; } catch { return false; } }
}
private IltCharacterState C => _ctx.State.Character;
public bool Running => _phase != Phase.Idle;
// ── Order / selection helpers (also used by IltHubStore.Normalize) ─────────
public static Stat? Find(string keyOrName)
{
if (string.IsNullOrWhiteSpace(keyOrName)) return null;
string k = keyOrName.Trim();
foreach (var s in Stats)
if (s.Abbr.Equals(k, StringComparison.OrdinalIgnoreCase) || s.Name.Equals(k, StringComparison.OrdinalIgnoreCase))
return s;
// Cost lines may say "MaxHealth" / "Maximum Health"; the reply may abbreviate.
string lower = k.ToLowerInvariant().Replace(" ", "");
if (lower.StartsWith("maximum")) lower = lower.Substring(7);
else if (lower.StartsWith("max")) lower = lower.Substring(3);
foreach (var s in Stats)
if (s.Name.Equals(lower, StringComparison.OrdinalIgnoreCase) || lower.StartsWith(s.Abbr, StringComparison.Ordinal))
return s;
return null;
}
/// <summary>All nine abbreviations exactly once: saved order first, missing ones appended, junk dropped.</summary>
public static List<string> RepairOrder(List<string>? order)
{
var result = new List<string>();
foreach (string k in order ?? new List<string>())
{
Stat? s = Find(k);
if (s != null && !result.Contains(s.Abbr)) result.Add(s.Abbr);
}
foreach (string k in DefaultOrder)
if (!result.Contains(k)) result.Add(k);
return result;
}
public static List<string> RepairSelection(List<string>? selection)
{
var result = new List<string>();
foreach (string k in selection ?? new List<string>())
{
Stat? s = Find(k);
if (s != null && !result.Contains(s.Abbr)) result.Add(s.Abbr);
}
return result;
}
/// <summary>
/// Picks the next stat to raise. Pure (unit-testable): <paramref name="order"/> is the
/// priority order, <paramref name="ticked"/> the stats allowed, <paramref name="cost"/> the
/// known next-level costs, <paramref name="budget"/> what may be spent. Round robin starts at
/// <paramref name="rrNext"/> and returns the index after the pick there.
/// </summary>
public static string? Pick(Mode mode, IReadOnlyList<string> order, ICollection<string> ticked,
IReadOnlyDictionary<string, long> cost, long budget, ref int rrNext)
{
if (budget <= 0 || order.Count == 0) return null;
bool Affordable(string k) => ticked.Contains(k) && cost.TryGetValue(k, out long c) && c > 0 && c <= budget;
switch (mode)
{
case Mode.RoundRobin:
for (int step = 0; step < order.Count; step++)
{
int i = ((rrNext % order.Count) + step) % order.Count;
if (!Affordable(order[i])) continue;
rrNext = i + 1;
return order[i];
}
return null;
case Mode.Cheapest:
string? best = null;
long bestCost = long.MaxValue;
foreach (string k in order) // ties go to the higher-priority stat
{
if (!Affordable(k)) continue;
long c = cost[k];
if (c < bestCost) { best = k; bestCost = c; }
}
return best;
default:
foreach (string k in order)
if (Affordable(k)) return k;
return null;
}
}
// ── Gate ──────────────────────────────────────────────────────────────────
/// <summary>Why the raiser can't run here, or null when it can.</summary>
public string? Blocker()
{
if (!_ctx.Options.IsIltLikeWorld)
return "Server features are off for this world (Settings > Misc > Server Features).";
if (_ctx.Options.IsOff(IltFeature.Xp)) return "This server reports /xp as unavailable.";
if (!_ctx.Host.HasInvokeChatParser) return "This engine build can't send chat commands.";
return null;
}
// ── Pump-thread lifecycle ─────────────────────────────────────────────────
/// <summary>Tick. <paramref name="holdOff"/>: another XP spender (auto-enlighten's loop) is running.</summary>
public void Tick(long nowMs, bool holdOff)
{
if (Running && nowMs - _lastProgressMs > StallMs) { Finish($"Stopped: no reply for {StallMs / 1000} s."); return; }
if (!C.AttrAutoRaise || Running || holdOff || HeldOff) return;
if (_nextAutoAtMs == 0) { _nextAutoAtMs = nowMs + FirstAutoDelayMs; return; }
if (nowMs < _nextAutoAtMs) return;
_nextAutoAtMs = nowMs + Math.Clamp(C.AttrAutoRaiseMinutes, 1, 1440) * 60_000L;
if (Blocker() != null || C.AttrRaiseStats.Count == 0) return;
if (_ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp) <= Math.Max(0, C.AttrKeepXp)) return;
Start(auto: true);
}
/// <summary>Passive: keeps costs / base values current when the player runs the commands by hand.</summary>
public void OnChat(string text)
{
var cost = IltParse.XpCost.Match(text);
if (cost.Success)
{
Stat? s = Find(cost.Groups[1].Value);
if (s != null) { _cost[s.Abbr] = IltParse.ParseLeadingLong(cost.Groups[2].Value); MarkCostsRead(); }
return;
}
var now = BaseNow.Match(text);
if (now.Success)
{
Stat? s = Find(now.Groups[1].Value);
if (s != null && int.TryParse(now.Groups[2].Value, out int v)) _base[s.Abbr] = v;
}
}
public void OnLogout()
{
_runId++;
_phase = Phase.Idle;
_cost.Clear();
_runCosts.Clear();
_base.Clear();
_costsAtMs = 0;
_autoCostsTried = false;
_nextAutoAtMs = 0;
_status = "Idle.";
}
// ── Runs ──────────────────────────────────────────────────────────────────
/// <summary>Starts a spend run (manual "Raise now" or the auto timer).</summary>
public void Start(bool auto)
{
if (Running) return;
string? blocked = Blocker();
if (blocked != null) { _status = blocked; return; }
if (HeldOff) { _status = "Auto-enlighten is spending XP right now; try again when it finishes."; return; }
if (C.AttrRaiseStats.Count == 0) { _status = "Tick at least one attribute or vital to raise."; return; }
_runId++;
_runAuto = auto;
_runRaised = 0;
_runSpent = 0;
_runGains.Clear();
_rrNext = 0;
_runCosts = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
_lastProgressMs = IltHubContext.NowMs;
RynthLog.Trace(LogCat.IltProgression, $"attr raise run {_runId} start (auto={auto}, mode={(Mode)C.AttrRaiseMode}, keep={C.AttrKeepXp}, stats={string.Join(",", C.AttrRaiseStats)})");
ReadCosts(_runId, thenStep: true);
}
public void Stop(string why = "Stopped.")
{
if (!Running) return;
Finish(why);
}
/// <summary>Re-reads the costs only (the panel's Refresh button).</summary>
public void RefreshCosts()
{
if (Running || Blocker() != null) return;
ReadCosts(_runId, thenStep: false);
}
/// <summary>Reads the costs once per login when the Progression tab is first shown. Pump thread.</summary>
public void EnsureCosts()
{
if (_autoCostsTried || _costsAtMs != 0 || Running || Blocker() != null) return;
_autoCostsTried = true;
ReadCosts(_runId, thenStep: false);
}
/// <summary>
/// XP for <paramref name="levels"/> raises when the next one costs <paramref name="nextCost"/>,
/// each level <see cref="ProjectedLevelGrowth"/> dearer than the last. Saturates at long.MaxValue.
/// </summary>
public static long ProjectCost(long nextCost, int levels)
{
if (nextCost <= 0 || levels <= 0) return 0;
double total = 0, step = nextCost;
for (int i = 0; i < levels; i++)
{
total += step;
step *= 1 + ProjectedLevelGrowth;
}
return total >= long.MaxValue ? long.MaxValue : (long)total;
}
private void MarkCostsRead()
{
_costsAtMs = IltHubContext.NowMs;
_costsAtLocal = DateTime.Now;
}
/// <summary>
/// "+N" button: sends "/attr abbr N"; the server's reply shows in chat. Refused up front when
/// the known (or, for N &gt; 1, projected) cost is more than the unassigned XP, like UB's XP tab.
/// </summary>
public void RaiseManual(string key, int levels)
{
Stat? s = Find(key);
if (s == null || levels <= 0) return;
if (Running) { _status = "Wait for the current raise run to finish (or Stop it)."; return; }
string? blocked = Blocker();
if (blocked != null) { _status = blocked; return; }
if (HeldOff) { _status = "Auto-enlighten is spending XP right now; try again when it finishes."; return; }
levels = Math.Min(levels, 1000);
if (_cost.TryGetValue(s.Abbr, out long next) && next > 0)
{
long need = ProjectCost(next, levels);
long have = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp);
if (need > have)
{
_status = $"Not enough unassigned XP for {s.Name} +{levels}: need {(levels > 1 ? "~" : "")}{IltParse.Compact(need)}, have {IltParse.Compact(have)}.";
return;
}
}
RynthLog.Trace(LogCat.IltProgression, $"attr manual raise {s.Abbr} +{levels}");
int run = _runId;
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = $"/attr {s.Abbr} {levels}",
IsResponseLine = IsAttrReply,
IsTerminator = IsAttrReply,
IdleEndMs = 600,
FirstLineTimeoutMs = ReplyTimeoutMs,
Eat = false,
OnComplete = r =>
{
string reply = r.TerminatorLine ?? r.Lines.FirstOrDefault() ?? (r.TimedOut ? "no reply" : "");
_status = $"{s.Name} +{levels}: {reply}";
if (run == _runId && !Running) ReadCosts(_runId, thenStep: false);
},
});
_status = $"Sent /attr {s.Abbr} {levels}...";
}
private static bool IsAttrReply(string t)
=> t.StartsWith("[ATTR]", StringComparison.OrdinalIgnoreCase) || t.StartsWith("Your base", StringComparison.OrdinalIgnoreCase);
private void ReadCosts(int run, bool thenStep)
{
// A plain refresh doesn't stack on one already queued; a run always gets its own reply.
if (!thenStep && _ctx.Capture.IsPending("/xp all")) return;
if (thenStep)
{
_phase = Phase.ReadingCosts;
if (_runRaised == 0) _status = "Reading XP costs (/xp all)...";
}
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/xp all",
IsResponseLine = t => t.StartsWith("[XP]", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 900,
FirstLineTimeoutMs = ReplyTimeoutMs,
Eat = true,
OnComplete = r => Guard(run, () =>
{
if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Xp, IltTri.Off); if (run == _runId && thenStep) Finish("This server has no /xp command."); return; }
var fresh = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
foreach (string line in r.Lines)
{
var m = IltParse.XpCost.Match(line);
if (!m.Success) continue;
Stat? s = Find(m.Groups[1].Value);
if (s == null) continue;
fresh[s.Abbr] = IltParse.ParseLeadingLong(m.Groups[2].Value);
}
foreach (var kv in fresh) _cost[kv.Key] = kv.Value;
if (fresh.Count > 0) MarkCostsRead();
RynthLog.Trace(LogCat.IltProgression, $"attr costs: {fresh.Count} line(s) (timedOut={r.TimedOut})");
if (!thenStep || run != _runId || !Running) return;
if (fresh.Count == 0) { Finish(r.TimedOut ? "No reply to /xp all." : "No cost lines in the /xp all reply."); return; }
_runCosts = fresh; // a stat missing from this reply is not raised this step
_lastProgressMs = IltHubContext.NowMs;
Step(run);
}),
});
}
private void Step(int run)
{
if (run != _runId || !Running) return;
// The world can leave Server Features (or /xp go off) mid-run, and auto-enlighten can start.
if (Blocker() is string blocked) { Finish("Stopped: " + blocked); return; }
if (HeldOff) { Finish("Stopped: auto-enlighten started spending XP."); return; }
if (_runRaised >= MaxRaisesPerRun) { Finish($"Stopped after {MaxRaisesPerRun} raises (runs again later)."); return; }
long have = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp);
long budget = have - Math.Max(0, C.AttrKeepXp);
var ticked = new HashSet<string>(C.AttrRaiseStats, StringComparer.OrdinalIgnoreCase);
string? pick = Pick((Mode)Math.Clamp(C.AttrRaiseMode, 0, 2), C.AttrOrder, ticked, _runCosts, budget, ref _rrNext);
if (pick == null)
{
Finish(_runRaised == 0
? (budget <= 0 ? "Nothing to spend (unassigned XP is at or below the reserve)."
: "Nothing affordable among the ticked stats.")
: string.Empty);
return;
}
Stat s = Find(pick)!;
_phase = Phase.Raising;
_raisingAbbr = s.Abbr;
_raisingCost = _runCosts.TryGetValue(s.Abbr, out long c) ? c : 0;
_status = $"Raising {s.Name} +1 (cost {IltParse.Compact(_raisingCost)})...";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = $"/attr {s.Abbr} 1",
IsResponseLine = IsAttrReply,
IsTerminator = IsAttrReply,
IdleEndMs = 600,
FirstLineTimeoutMs = ReplyTimeoutMs,
Eat = true,
OnComplete = r => Guard(run, () => OnRaiseReply(run, s, r)),
});
}
private void OnRaiseReply(int run, Stat s, IltChatResult r)
{
if (run != _runId || !Running) return;
string reply = r.TerminatorLine ?? r.Lines.FirstOrDefault() ?? string.Empty;
var ok = IltParse.AttrRaised.Match(reply);
var baseNow = BaseNow.Match(reply);
// The reply must be about the stat we raised (another /attr sender could answer first).
if (ok.Success && Find(ok.Groups[1].Value) != s) ok = Match.Empty;
if (baseNow.Success && Find(baseNow.Groups[1].Value) != s) baseNow = Match.Empty;
if (!ok.Success && !baseNow.Success)
{
RynthLog.Trace(LogCat.IltProgression, $"attr raise {s.Abbr}: not a success ('{reply}', timedOut={r.TimedOut}, unknown={r.UnknownCommand})");
Finish(r.UnknownCommand ? "This server has no /attr command."
: reply.Length > 0 ? $"Server: {reply}" : "No reply to /attr.");
return;
}
long spent = ok.Success ? IltParse.ParseLeadingLong(ok.Groups[3].Value) : _raisingCost;
int levels = ok.Success && int.TryParse(ok.Groups[2].Value, out int n) ? n : 1;
if (baseNow.Success && int.TryParse(baseNow.Groups[2].Value, out int v)) _base[s.Abbr] = v;
else if (_base.TryGetValue(s.Abbr, out int b)) _base[s.Abbr] = b + levels;
_runGains[s.Abbr] = (_runGains.TryGetValue(s.Abbr, out int g) ? g : 0) + levels;
_runRaised += levels;
_runSpent += spent;
_cost.Remove(s.Abbr); // its next level costs more; re-read before deciding again
_runCosts.Clear();
_lastProgressMs = IltHubContext.NowMs;
_status = $"Raised {s.Name} (+{_runRaised} this run, {IltParse.Compact(_runSpent)} XP)...";
ReadCosts(run, thenStep: true);
}
/// <summary>Runs a capture callback; an exception ends the run instead of leaving it Running.</summary>
private void Guard(int run, Action body)
{
try { body(); }
catch (Exception ex)
{
RynthLog.Exception(LogCat.IltProgression, ex, "attr raise callback");
if (run == _runId && Running) Finish("Stopped: internal error (see the RynthAi log).");
}
}
private void Finish(string reason)
{
_phase = Phase.Idle;
_runId++; // late callbacks from this run are ignored
string summary = _runRaised > 0
? "Raised " + string.Join(", ", C.AttrOrder.Where(_runGains.ContainsKey).Select(k => $"{Find(k)!.Name} +{_runGains[k]}"))
+ $" ({IltParse.Compact(_runSpent)} XP)."
: string.Empty;
string text = (summary + (reason.Length > 0 ? (summary.Length > 0 ? " " : "") + reason : "")).Trim();
if (text.Length == 0) text = "Done.";
_status = text;
_lastRun = $"{DateTime.Now:t} {(_runAuto ? "auto" : "manual")}: {text}";
RynthLog.Trace(LogCat.IltProgression, $"attr raise run finished: {text}");
if (_runRaised > 0) _ctx.Chat($"[Mini Remote] Attribute raise ({(_runAuto ? "auto" : "manual")}): {text}");
}
// ── Engine Skills panel bridge ────────────────────────────────────────────
/// <summary>Appends <c>"attr":{...}</c> for the Progression tab.</summary>
public void AppendJson(StringBuilder sb)
{
string? blocked = Blocker();
long have = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp);
long budget = have - Math.Max(0, C.AttrKeepXp);
long now = IltHubContext.NowMs;
sb.Append("\"attr\":{\"off\":").Append(blocked != null ? "true" : "false");
Str(sb, "reason", blocked ?? string.Empty);
sb.Append(",\"auto\":").Append(C.AttrAutoRaise ? "true" : "false")
.Append(",\"every\":").Append(Math.Clamp(C.AttrAutoRaiseMinutes, 1, 1440))
.Append(",\"mode\":").Append(Math.Clamp(C.AttrRaiseMode, 0, 2))
.Append(",\"running\":").Append(Running ? "true" : "false");
Str(sb, "keep", C.AttrKeepXp > 0 ? IltParse.Compact(C.AttrKeepXp) : "0");
// The reserve box edits the exact number (the compact form above is lossy).
Str(sb, "keepFull", IltParse.N0(Math.Max(0, C.AttrKeepXp)));
Str(sb, "status", _status);
Str(sb, "lastRun", _lastRun);
Str(sb, "unassigned", $"Unassigned XP {IltParse.Compact(have)}"
+ (C.AttrKeepXp > 0 ? $" (spendable {IltParse.Compact(Math.Max(0, budget))})" : ""));
string next = !C.AttrAutoRaise ? string.Empty
: Running ? "running"
: _nextAutoAtMs <= 0 ? "soon"
: IltParse.Duration(TimeSpan.FromMilliseconds(Math.Max(0, _nextAutoAtMs - now)));
Str(sb, "next", next);
Str(sb, "costsAge", _costsAtMs == 0 ? "costs not read yet" : $"costs read {Ago(now - _costsAtMs)} ago");
Str(sb, "updated", _costsAtMs == 0 ? "-" : _costsAtLocal.ToString("HH:mm:ss"));
int level = _ctx.Inventory.PlayerInt(IltInventory.IntLevel);
long totalXp = _ctx.Inventory.PlayerQuad(IltInventory.QuadTotalXp);
Str(sb, "xpHeader", $"Level {(level > 0 ? level.ToString() : "?")} Total XP {(totalXp > 0 ? IltParse.Compact(totalXp) : "?")} Unassigned {IltParse.Compact(have)}");
var ticked = new HashSet<string>(C.AttrRaiseStats, StringComparer.OrdinalIgnoreCase);
sb.Append(",\"rows\":[");
bool first = true;
foreach (string k in C.AttrOrder)
{
Stat? s = Find(k);
if (s == null) continue;
if (!first) sb.Append(',');
first = false;
bool known = _cost.TryGetValue(s.Abbr, out long c) && c > 0;
sb.Append('{');
Str(sb, "key", s.Abbr, first: true);
Str(sb, "label", s.Name);
sb.Append(",\"vital\":").Append(s.Vital ? "true" : "false")
.Append(",\"on\":").Append(ticked.Contains(s.Abbr) ? "true" : "false")
.Append(",\"base\":").Append(_base.TryGetValue(s.Abbr, out int b) ? b : -1)
.Append(",\"afford\":").Append(known && c <= budget ? "true" : "false");
Str(sb, "cost", known ? IltParse.Compact(c) : "?");
// By hand (+1 / +10) only the unassigned XP limits, not the raiser's reserve.
long ten = known ? ProjectCost(c, 10) : 0;
sb.Append(",\"known\":").Append(known ? "true" : "false")
.Append(",\"afford1\":").Append(known && c <= have ? "true" : "false")
.Append(",\"afford10\":").Append(known && ten <= have ? "true" : "false");
Str(sb, "cost10", known ? "~" + IltParse.Compact(ten) : "?");
Str(sb, "costFull", known ? IltParse.N0(c) : "");
Str(sb, "cost10Full", known ? IltParse.N0(ten) : "");
sb.Append('}');
}
sb.Append("]}");
}
private static string Ago(long ms)
{
long sec = Math.Max(0, ms / 1000);
return sec < 60 ? $"{sec}s" : sec < 3600 ? $"{sec / 60}m" : $"{sec / 3600}h {sec % 3600 / 60}m";
}
private static void Str(StringBuilder sb, string name, string value, bool first = false)
{
if (!first) sb.Append(',');
sb.Append('"').Append(name).Append("\":\"").Append(IltStyle.JsonEscape(value ?? string.Empty)).Append('"');
}
/// <summary>"prog attr…" commands from the Skills panel. Returns false when the verb isn't ours.</summary>
public bool HandleRemote(string verb, string[] a)
{
string arg1 = a.Length > 1 ? a[1] : string.Empty;
string arg2 = a.Length > 2 ? a[2] : string.Empty;
switch (verb)
{
case "attrauto":
C.AttrAutoRaise = arg1.Equals("on", StringComparison.OrdinalIgnoreCase);
_nextAutoAtMs = C.AttrAutoRaise ? IltHubContext.NowMs + FirstAutoDelayMs : 0;
if (!C.AttrAutoRaise && Running && _runAuto) Stop("Auto-raise turned off.");
return true;
case "attrevery":
if (int.TryParse(arg1, out int min))
{
C.AttrAutoRaiseMinutes = Math.Clamp(min, 1, 1440);
if (C.AttrAutoRaise) _nextAutoAtMs = IltHubContext.NowMs + C.AttrAutoRaiseMinutes * 60_000L;
}
return true;
case "attrmode":
if (int.TryParse(arg1, out int mode)) C.AttrRaiseMode = Math.Clamp(mode, 0, 2);
return true;
case "attrkeep":
if (arg1.Length == 0 || arg1 == "0") C.AttrKeepXp = 0;
else if (IltParse.TryParseAmount(arg1, out long keep)) C.AttrKeepXp = Math.Max(0, keep);
return true;
case "attron":
{
Stat? s = Find(arg1);
if (s == null) return true;
bool on = arg2.Equals("on", StringComparison.OrdinalIgnoreCase);
C.AttrRaiseStats.RemoveAll(x => x.Equals(s.Abbr, StringComparison.OrdinalIgnoreCase));
if (on) C.AttrRaiseStats.Add(s.Abbr);
return true;
}
case "attrmove":
{
Stat? s = Find(arg1);
if (s == null) return true;
int i = C.AttrOrder.FindIndex(x => x.Equals(s.Abbr, StringComparison.OrdinalIgnoreCase));
int j = arg2.Equals("up", StringComparison.OrdinalIgnoreCase) ? i - 1
: arg2.Equals("top", StringComparison.OrdinalIgnoreCase) ? 0 : i + 1;
if (i < 0 || j < 0 || j >= C.AttrOrder.Count || i == j) return true;
string item = C.AttrOrder[i];
C.AttrOrder.RemoveAt(i);
C.AttrOrder.Insert(j, item);
return true;
}
case "attrorderreset":
C.AttrOrder = new List<string>(DefaultOrder);
return true;
case "attrraise":
if (int.TryParse(arg2, out int levels)) RaiseManual(arg1, levels);
return true;
case "attrrun": Start(auto: false); return true;
case "attrstop": Stop(); return true;
case "attrcosts": RefreshCosts(); return true;
}
return false;
}
}

View file

@ -0,0 +1,228 @@
// IltAugCosts.cs — luminance augmentation cost rules, per server (world name).
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Defaults are UB's Leaftide Augs tab (correct for InfiniteLeaftide):
// level i (1-based) costs (Base + (i-1) * Base * LinearPercent/100) * multiplier(i)
// multiplier(i) = M0 below S1, M1 from S1, M2 from S2, M3 from S3, M4 from S4
// (UB: 1 / 4 / 8 / 16 / 24; a tier starts AT its S level).
// Another server can change the multipliers and every aug's base, growth, S1..S4, target cap
// and coins per level from the Progression tab; those edits are saved for that world only in
// one shared file, so every character on the world prices augs the same way.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>The saved file: one cost profile per world that was changed from the defaults.</summary>
public sealed class IltAugCostFile
{
public Dictionary<string, IltAugCostProfile> Servers = new(StringComparer.OrdinalIgnoreCase);
}
/// <summary>A world's cost rules: the five tier multipliers and one row per aug.</summary>
public sealed class IltAugCostProfile
{
public double[] Multipliers = (double[])IltAugCosts.DefaultMultipliers.Clone();
public List<IltAugCostRow> Augs = new();
}
/// <summary>One aug's cost rule. Thresholds are 1-based levels; Cap 0 = no target limit.</summary>
public sealed class IltAugCostRow
{
public string Key = string.Empty;
public long Base;
public double LinearPercent;
public int CoinsPerLevel;
public int S1, S2, S3, S4;
public int Cap;
public IltAugCostRow Clone() => (IltAugCostRow)MemberwiseClone();
}
internal sealed class IltAugCosts
{
/// <summary>UB's tier multipliers: below S1, from S1, from S2, from S3, from S4.</summary>
public static readonly double[] DefaultMultipliers = { 1, 4, 8, 16, 24 };
/// <summary>Highest target the planner accepts when an aug has no cap (keeps the plan sane).</summary>
public const int NoCapLimit = 100_000;
/// <summary>Display order and labels; also the only keys a profile may hold.</summary>
public static readonly (string Key, string Label)[] Labels =
{
("creature", "Creature"), ("item", "Item"), ("life", "Life"), ("war", "War"), ("void", "Void"),
("duration", "Duration"), ("melee", "Melee"), ("missile", "Missile"),
("specialization", "Specialization"), ("summon", "Summon"),
};
/// <summary>UB Augs.cs (ILT): cost models, coins per level and soft caps S1..S4; no target cap.</summary>
public static IltAugCostRow[] DefaultRows() => new[]
{
Row("creature", 750_000, 130, 3, 2750, 4000, 4750, 5250),
Row("item", 1_000_000, 165, 18, 1250, 2000, 3000, 3500),
Row("life", 975_000, 195, 12, 1000, 2000, 3000, 3750),
Row("war", 750_000, 140, 5, 1750, 2500, 3000, 3750),
Row("void", 800_000, 160, 5, 1750, 2500, 3000, 3750),
Row("duration", 400_000, 120, 5, 1000, 2000, 2500, 3000),
Row("melee", 750_000, 140, 5, 1750, 2500, 3000, 3750),
Row("missile", 750_000, 140, 5, 1750, 2500, 3000, 3750),
Row("specialization", 3_000_000, 200, 50, 1750, 2500, 3000, 3750),
Row("summon", 500_000, 125, 36, 1750, 2500, 3000, 3750),
};
private static IltAugCostRow Row(string key, long b, double lp, int coins, int s1, int s2, int s3, int s4)
=> new() { Key = key, Base = b, LinearPercent = lp, CoinsPerLevel = coins, S1 = s1, S2 = s2, S3 = s3, S4 = s4, Cap = 0 };
/// <summary>The shared settings file. Tests point it at a scratch folder before first use.</summary>
public static string FilePath { get; set; } = Path.Combine(IltHubStore.SharedRoot, "ilt-aug-costs.json");
private IltAugCostFile? _file;
private string _lastJson = string.Empty;
private static readonly IltAugCostProfile Defaults = NewDefaultProfile();
public static string Label(string key)
{
foreach (var l in Labels) if (l.Key.Equals(key, StringComparison.OrdinalIgnoreCase)) return l.Label;
return key;
}
private static IltAugCostProfile NewDefaultProfile()
=> new() { Multipliers = (double[])DefaultMultipliers.Clone(), Augs = DefaultRows().ToList() };
private IltAugCostFile File_
{
get
{
if (_file != null) return _file;
_file = new IltAugCostFile();
try
{
if (File.Exists(FilePath))
{
string json = File.ReadAllText(FilePath);
_file = JsonSerializer.Deserialize(json, IltHubJsonContext.Default.IltAugCostFile) ?? new IltAugCostFile();
_lastJson = json;
}
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {FilePath}"); _file = new IltAugCostFile(); }
var fixedUp = new Dictionary<string, IltAugCostProfile>(StringComparer.OrdinalIgnoreCase);
foreach (var kv in _file.Servers ?? new())
if (kv.Value != null) fixedUp[kv.Key ?? string.Empty] = Normalize(kv.Value);
_file.Servers = fixedUp;
return _file;
}
}
/// <summary>
/// Repairs a loaded or edited profile: five multipliers, exactly one row per known aug (missing
/// ones from the defaults, unknown ones dropped), non-negative values and S1 &lt;= S2 &lt;= S3 &lt;= S4.
/// </summary>
public static IltAugCostProfile Normalize(IltAugCostProfile p)
{
var m = new double[5];
for (int i = 0; i < 5; i++)
{
double v = p.Multipliers != null && i < p.Multipliers.Length ? p.Multipliers[i] : DefaultMultipliers[i];
m[i] = double.IsFinite(v) ? Math.Clamp(v, 0, 1000) : DefaultMultipliers[i];
}
p.Multipliers = m;
var byKey = new Dictionary<string, IltAugCostRow>(StringComparer.OrdinalIgnoreCase);
foreach (var r in p.Augs ?? new()) if (r != null && !string.IsNullOrEmpty(r.Key)) byKey[r.Key] = r;
var rows = new List<IltAugCostRow>(Labels.Length);
foreach (var def in DefaultRows())
{
var r = byKey.TryGetValue(def.Key, out var have) ? have : def;
r.Key = def.Key;
r.Base = Math.Max(0, r.Base);
r.LinearPercent = double.IsFinite(r.LinearPercent) ? Math.Clamp(r.LinearPercent, 0, 100_000) : def.LinearPercent;
r.CoinsPerLevel = Math.Max(0, r.CoinsPerLevel);
r.S1 = Math.Max(0, r.S1);
r.S2 = Math.Max(r.S1, r.S2);
r.S3 = Math.Max(r.S2, r.S3);
r.S4 = Math.Max(r.S3, r.S4);
r.Cap = Math.Max(0, r.Cap);
rows.Add(r);
}
p.Augs = rows;
return p;
}
/// <summary>The rules for <paramref name="world"/>: its saved profile, or the UB defaults.</summary>
public IltAugCostProfile For(string world)
=> File_.Servers.TryGetValue(world ?? string.Empty, out var p) ? p : Defaults;
/// <summary>True when <paramref name="world"/> has its own saved rules.</summary>
public bool IsCustom(string world) => File_.Servers.ContainsKey(world ?? string.Empty);
/// <summary>Applies an edit to <paramref name="world"/>'s rules (copying the defaults first) and saves.</summary>
public void Edit(string world, Action<IltAugCostProfile> change)
{
string key = world ?? string.Empty;
if (!File_.Servers.TryGetValue(key, out var p))
{
p = NewDefaultProfile();
File_.Servers[key] = p;
}
change(p);
Normalize(p);
Save();
}
/// <summary>Drops <paramref name="world"/>'s saved rules: it goes back to the UB defaults.</summary>
public void Reset(string world)
{
if (File_.Servers.Remove(world ?? string.Empty)) Save();
}
private void Save()
{
try
{
string json = JsonSerializer.Serialize(File_, IltHubJsonContext.Default.IltAugCostFile);
if (json == _lastJson) return;
if (RynthCore.Plugin.Shared.DataWriteGuard.TrySave("the aug cost table", FilePath, () =>
{
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
string tmp = FilePath + ".tmp";
File.WriteAllText(tmp, json);
File.Move(tmp, FilePath, overwrite: true);
}))
_lastJson = json;
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {FilePath}"); }
}
/// <summary>Highest target the planner allows for <paramref name="r"/> at current level <paramref name="cur"/>.</summary>
public static int Ceiling(IltAugCostRow r, int cur) => Math.Max(cur, r.Cap > 0 ? r.Cap : NoCapLimit);
/// <summary>
/// Luminance for levels cur+1 .. tgt. Same result as UB's per-level loop, summed per tier in
/// closed form: within a tier the per-level base grows linearly, so each tier is an arithmetic series.
/// </summary>
public static decimal LumCost(IltAugCostRow r, double[] mult, int cur, int tgt)
{
int first = Math.Max(1, cur + 1);
if (tgt < first) return 0;
decimal b = r.Base;
decimal step = b * (decimal)r.LinearPercent / 100m;
// Tier t covers levels [lo[t], hi[t]) (1-based); the last tier has no end.
long[] lo = { 1, r.S1, r.S2, r.S3, r.S4 };
long[] hi = { r.S1, r.S2, r.S3, r.S4, long.MaxValue };
decimal total = 0;
for (int t = 0; t < 5; t++)
{
long a = Math.Max(first, lo[t]);
long z = Math.Min(tgt, hi[t] - 1);
if (z < a) continue;
decimal n = z - a + 1;
// sum over i=a..z of (b + (i-1)*step) = n*b + step * sum(i-1) = n*b + step * n*(a-1 + z-1)/2
decimal levels = n * b + step * (n * ((a - 1) + (z - 1)) / 2m);
total += levels * (decimal)mult[t];
}
return total;
}
}

View file

@ -0,0 +1,188 @@
// IltBankCommands.cs — The /bank commands the Banking tab sends, and the reply lines it collects.
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Server contract (ACECustom PlayerCommands.HandleBank / Player_Bank, upstream 976606695):
// /b d [code] deposit everything (no code) or one kind; "Deposited N <kind>",
// "No <kind> found to deposit", "Deposited all <kind>!".
// /b lum bank luminance tokens: "Starting Banked Lum", one "Deposited N x <token>"
// a kind, "Ending Banked Lum"; "No luminance tokens found to deposit".
// /b w <code> <amount> withdraw: "Withdrew ...", "You don't have enough ...", "Failed to create ...".
// /b w n <denom> [n] trade notes by denomination (i v x l c d m md mm mmd).
// /b t <code> <n> <who> transfer; "Transferred {N0} {Currency} to {Name}[ (offline)]".
// /b t n <denom> <n> <who> trade notes' pyreal value, then "(Equivalent to Nx DENOM notes)".
// The recipient is one argument: a name with a space has to be in "quotes".
// Prestige Coins are bound to the character: "[BANK] Prestige Coins are bound to you and
// cannot be transferred." Pyreal peas and luminance tokens are deposit only.
// Items is the one table of what the server allows; the deposit, withdraw and transfer lists
// are built from it. Deposit, withdraw and transfer share one server throttle
// (bank_command_limit); a plain /bank balance doesn't touch it. Pure: no host calls, so the
// host tests cover it.
using System;
using System.Linq;
namespace RynthCore.Plugin.RynthILT.Hub;
internal static class IltBankCommands
{
/// <summary>
/// One bank item: label, server code, and what the server allows for it. For trade notes
/// ("n") a withdrawal or transfer is by denomination and note count.
/// </summary>
internal sealed record BankItem(string Label, string Code, bool Deposit, bool Withdraw, bool Transfer);
/// <summary>The trade-notes code: withdrawn and transferred by denomination.</summary>
public const string NotesCode = "n";
/// <summary>The luminance-tokens deposit: its own command, "/b lum".</summary>
public const string LuminanceTokensCode = "lum";
/// <summary>Everything the bank holds, in the server's order, with what it allows.</summary>
public static readonly BankItem[] Items =
{
new("Pyreals", "p", Deposit: true, Withdraw: true, Transfer: true),
new("Pyreal peas", "ps", Deposit: true, Withdraw: false, Transfer: false),
new("Luminance", "l", Deposit: true, Withdraw: true, Transfer: true),
new("Luminance tokens", LuminanceTokensCode, Deposit: true, Withdraw: false, Transfer: false),
new("Legendary keys", "k", Deposit: true, Withdraw: true, Transfer: true),
new("Mythical keys", "mk", Deposit: true, Withdraw: true, Transfer: true),
new("Enlightened coins", "e", Deposit: true, Withdraw: true, Transfer: true),
new("Weakly enlightened coins", "we", Deposit: true, Withdraw: true, Transfer: true),
new("Prestige coins", "pc", Deposit: true, Withdraw: true, Transfer: false),
new("Trade notes", NotesCode, Deposit: true, Withdraw: true, Transfer: true),
};
/// <summary>A deposit choice: label, and the command's argument after "/b d" ("" = all).</summary>
public static readonly (string Label, string Args)[] Deposits =
new[] { ("Everything", string.Empty) }
.Concat(Items.Where(i => i.Deposit).Select(i => (i.Label, i.Code)))
.ToArray();
/// <summary>A withdraw choice: label and the server code; "n" is trade notes (by denomination).</summary>
public static readonly (string Label, string Code)[] Withdrawals =
Items.Where(i => i.Withdraw).Select(i => (i.Label, i.Code)).ToArray();
/// <summary>A transfer choice: label and the server code; "n" moves trade notes' pyreal value.</summary>
public static readonly (string Label, string Code)[] Transfers =
Items.Where(i => i.Transfer).Select(i => (i.Label, i.Code)).ToArray();
/// <summary>Trade note denominations: label and code, in the server's order.</summary>
public static readonly (string Label, string Code, long Value)[] NoteDenominations =
{
("I (100)", "i", 100), ("V (500)", "v", 500), ("X (1K)", "x", 1_000), ("L (5K)", "l", 5_000),
("C (10K)", "c", 10_000), ("D (50K)", "d", 50_000), ("M (100K)", "m", 100_000),
("MD (150K)", "md", 150_000), ("MM (200K)", "mm", 200_000), ("MMD (250K)", "mmd", 250_000),
};
/// <summary>The server refuses a trade-note withdrawal of more than this many notes; transfers use the same cap.</summary>
public const int MaxNoteCount = 50_000;
/// <summary>"/b d", "/b d p", or "/b lum" for the luminance tokens; empty for an unknown index.</summary>
public static string Deposit(int index)
{
if (index < 0 || index >= Deposits.Length) return string.Empty;
string args = Deposits[index].Args;
if (args.Length == 0) return "/b d";
return args == LuminanceTokensCode ? "/b lum" : "/b d " + args;
}
/// <summary>
/// "/b w p 1000000", or "/b w n mmd 5" for trade notes (<paramref name="amount"/> is then the
/// note count). Empty (with <paramref name="error"/>) when the input can't be sent.
/// </summary>
public static string Withdraw(int index, long amount, int denomination, out string error)
{
error = string.Empty;
if (index < 0 || index >= Withdrawals.Length) { error = "Pick what to withdraw."; return string.Empty; }
if (amount <= 0) { error = "Amount must be positive."; return string.Empty; }
string code = Withdrawals[index].Code;
if (code != NotesCode) return $"/b w {code} {amount}";
if (!TryNote(denomination, amount, out string denom, out error)) return string.Empty;
return $"/b w n {denom} {amount}";
}
/// <summary>
/// "/bank t p 250000 Bob", "/bank t n mmd 4 \"Some Name\"" for trade notes (<paramref name="amount"/>
/// is then the note count). <paramref name="target"/> must already be a checked character name
/// (IltParse.CharacterName); a name with a space is quoted, as the server reads one argument.
/// Empty (with <paramref name="error"/>) when the input can't be sent.
/// </summary>
public static string Transfer(int index, long amount, int denomination, string target, out string error)
{
error = string.Empty;
if (index < 0 || index >= Transfers.Length) { error = "Pick a currency."; return string.Empty; }
if (amount <= 0) { error = "Amount must be positive."; return string.Empty; }
target = (target ?? string.Empty).Trim();
if (target.Length == 0) { error = "Enter a recipient."; return string.Empty; }
if (target.IndexOf('"') >= 0) { error = "Recipient must be a character name."; return string.Empty; }
string who = target.IndexOf(' ') >= 0 ? "\"" + target + "\"" : target;
string code = Transfers[index].Code;
if (code != NotesCode) return $"/bank t {code} {amount} {who}";
if (!TryNote(denomination, amount, out string denom, out error)) return string.Empty;
return $"/bank t n {denom} {amount} {who}";
}
/// <summary>True when <paramref name="index"/> is the trade-notes transfer (denomination and count).</summary>
public static bool IsNoteTransfer(int index) => index >= 0 && index < Transfers.Length && Transfers[index].Code == NotesCode;
/// <summary>The pyreal value of <paramref name="count"/> notes of <paramref name="denomination"/> (0 if unknown).</summary>
public static long NoteValue(int denomination, long count) =>
denomination >= 0 && denomination < NoteDenominations.Length && count > 0 ? NoteDenominations[denomination].Value * count : 0;
private static bool TryNote(int denomination, long count, out string code, out string error)
{
code = string.Empty;
error = string.Empty;
if (denomination < 0 || denomination >= NoteDenominations.Length) { error = "Pick a note denomination."; return false; }
if (count > MaxNoteCount) { error = $"At most {MaxNoteCount:N0} notes at a time."; return false; }
code = NoteDenominations[denomination].Code;
return true;
}
/// <summary>
/// True for a line the server sends in reply to a deposit or withdrawal (so the tab can show
/// it as the result). Only lines the bank code writes; never "[BANK]" balance lines.
/// </summary>
public static bool IsActionReply(string line)
{
if (string.IsNullOrEmpty(line)) return false;
return line.StartsWith("Deposited ", StringComparison.Ordinal)
|| line.StartsWith("Withdrew ", StringComparison.Ordinal)
|| (line.StartsWith("No ", StringComparison.Ordinal) && line.EndsWith("to deposit", StringComparison.Ordinal))
|| line.StartsWith("Starting Banked Lum", StringComparison.Ordinal)
|| line.StartsWith("Ending Banked Lum", StringComparison.Ordinal)
|| line.StartsWith("Not deposited", StringComparison.Ordinal)
|| line.StartsWith("You don't have enough", StringComparison.Ordinal)
|| line.StartsWith("You cannot hold any more", StringComparison.Ordinal)
|| line.StartsWith("You have not been luminance flagged", StringComparison.Ordinal)
|| line.StartsWith("Failed to ", StringComparison.Ordinal)
|| line.StartsWith("Warning: Requested", StringComparison.Ordinal)
|| line.StartsWith("Amount must be", StringComparison.Ordinal)
|| line.StartsWith("Cannot deposit while", StringComparison.Ordinal)
|| line.StartsWith("[Deposit]", StringComparison.Ordinal)
|| line.StartsWith("[Withdraw]", StringComparison.Ordinal)
|| line.StartsWith("Invalid amount", StringComparison.Ordinal)
|| line.StartsWith("Invalid denomination", StringComparison.Ordinal)
|| line.StartsWith("Count must be", StringComparison.Ordinal)
|| line.StartsWith("Count cannot exceed", StringComparison.Ordinal)
|| line.StartsWith("You are not permitted to use bank commands", StringComparison.Ordinal);
}
/// <summary>
/// True for a line the server sends in reply to a transfer: the result, the trade-note
/// equivalent, the throttle, or a refusal (unknown player, bound prestige coins, bad input).
/// </summary>
public static bool IsTransferReply(string line)
{
if (string.IsNullOrEmpty(line)) return false;
return line.StartsWith("Transferred ", StringComparison.Ordinal)
|| line.StartsWith("(Equivalent to ", StringComparison.Ordinal)
|| line.StartsWith("Character '", StringComparison.Ordinal)
|| line.StartsWith("You cannot transfer", StringComparison.Ordinal)
|| line.StartsWith("You don't have enough", StringComparison.Ordinal)
|| line.StartsWith("[Transfer]", StringComparison.Ordinal)
|| line.StartsWith("[BANK] Too many parameters", StringComparison.Ordinal)
|| line.StartsWith("[BANK] Prestige Coins are bound", StringComparison.Ordinal)
|| line.StartsWith("Invalid count", StringComparison.Ordinal)
|| line.StartsWith("Invalid denomination", StringComparison.Ordinal);
}
}

View file

@ -0,0 +1,151 @@
// IltBankExport.cs - The bank JSON of "RynthILT.Data" (Plugins/Shared/RynthIltDataApi.cs): the
// Banking tab's balances, form choices and log for another plugin's view (every character here).
//
// Every character RynthILT has run on this server keeps its balances in its own hub.json
// (<RynthILT folder>\<world>\<character>\hub.json, IltHubStore); the export lists them all, the
// logged-in character from its live state and the rest from their saved files (read on the pump
// at most every SiblingReadMs, so a reader polling every couple of seconds costs one directory
// listing now and then). Plus the form choices (IltBankCommands), the last action's reply and
// the recent transfers. Build is pure: the tests feed it rows.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal static class IltBankExport
{
/// <summary>How many recent transfers the JSON carries (newest first).</summary>
public const int MaxTransactions = 50;
/// <summary>One character's balances as exported.</summary>
internal sealed record Row(string Name, bool Current, IltBankState Bank);
/// <summary>
/// The bank JSON. <paramref name="enabled"/>: 1 the server has /bank, 0 not, -1 not known yet.
/// Rows are listed current character first, then by name. Plain ASCII.
/// </summary>
public static string Build(bool available, int enabled, string world, string character, IReadOnlyList<Row> rows,
string result, IReadOnlyList<IltBankTransaction> transactions)
{
var sb = new StringBuilder(4096);
sb.Append("{\"available\":").Append(available ? "true" : "false");
sb.Append(",\"enabled\":").Append(Math.Clamp(enabled, -1, 1).ToString(CultureInfo.InvariantCulture));
sb.Append(",\"world\":\"").Append(IltStyle.JsonEscape(world ?? string.Empty)).Append('"');
sb.Append(",\"character\":\"").Append(IltStyle.JsonEscape(character ?? string.Empty)).Append('"');
var ordered = new List<Row>(rows);
ordered.Sort((a, b) => a.Current != b.Current ? (a.Current ? -1 : 1) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
sb.Append(",\"characters\":[");
for (int i = 0; i < ordered.Count; i++)
{
Row r = ordered[i];
IltBankState b = r.Bank;
if (i > 0) sb.Append(',');
sb.Append("{\"name\":\"").Append(IltStyle.JsonEscape(r.Name)).Append('"');
sb.Append(",\"current\":").Append(r.Current ? "true" : "false");
Num(sb, "pyreals", b.Pyreals);
Num(sb, "luminance", b.Luminance);
Num(sb, "legendaryKeys", b.LegendaryKeys);
Num(sb, "mythicalKeys", b.MythicalKeys);
Num(sb, "enlightenedCoins", b.EnlightenedCoins);
Num(sb, "weaklyEnlightenedCoins", b.WeaklyEnlightenedCoins);
Num(sb, "prestigeCoins", b.PrestigeCoins);
sb.Append(",\"updated\":\"").Append(Utc(b.LastUpdated)).Append("\"}");
}
sb.Append(']');
sb.Append(",\"deposits\":[");
for (int i = 0; i < IltBankCommands.Deposits.Length; i++)
{
if (i > 0) sb.Append(',');
sb.Append('"').Append(IltStyle.JsonEscape(IltBankCommands.Deposits[i].Label)).Append('"');
}
sb.Append(']');
Choices(sb, "withdrawals", IltBankCommands.Withdrawals, w => w.Code == IltBankCommands.NotesCode);
Choices(sb, "transfers", IltBankCommands.Transfers, t => t.Code == IltBankCommands.NotesCode);
sb.Append(",\"notes\":[");
for (int i = 0; i < IltBankCommands.NoteDenominations.Length; i++)
{
var n = IltBankCommands.NoteDenominations[i];
if (i > 0) sb.Append(',');
sb.Append("{\"label\":\"").Append(IltStyle.JsonEscape(n.Label)).Append('"');
Num(sb, "value", n.Value);
sb.Append('}');
}
sb.Append(']');
sb.Append(",\"result\":\"").Append(IltStyle.JsonEscape(result ?? string.Empty)).Append('"');
sb.Append(",\"transactions\":[");
int written = 0;
for (int i = transactions.Count - 1; i >= 0 && written < MaxTransactions; i--, written++)
{
IltBankTransaction t = transactions[i];
if (written > 0) sb.Append(',');
sb.Append("{\"when\":\"").Append(t.Timestamp == default ? "" : t.Timestamp.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture)).Append('"');
sb.Append(",\"type\":\"").Append(IltStyle.JsonEscape(t.Type)).Append('"');
Num(sb, "amount", t.Amount);
sb.Append(",\"currency\":\"").Append(IltStyle.JsonEscape(t.Currency)).Append('"');
sb.Append(",\"player\":\"").Append(IltStyle.JsonEscape(t.OtherPlayer)).Append("\"}");
}
sb.Append("]}");
return sb.ToString();
}
private static void Num(StringBuilder sb, string name, long value)
=> sb.Append(",\"").Append(name).Append("\":").Append(value.ToString(CultureInfo.InvariantCulture));
private static void Choices(StringBuilder sb, string name, (string Label, string Code)[] items, Func<(string Label, string Code), bool> notes)
{
sb.Append(",\"").Append(name).Append("\":[");
for (int i = 0; i < items.Length; i++)
{
if (i > 0) sb.Append(',');
sb.Append("{\"label\":\"").Append(IltStyle.JsonEscape(items[i].Label)).Append("\",\"notes\":")
.Append(notes(items[i]) ? "true" : "false").Append('}');
}
sb.Append(']');
}
/// <summary>A local DateTime as ISO UTC ("" = never).</summary>
private static string Utc(DateTime local) => local == DateTime.MinValue || local == default
? ""
: local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
/// <summary>
/// The other characters' saved balances: every <c>&lt;world folder&gt;\*\hub.json</c> except
/// <paramref name="currentFolder"/>. A file that can't be read is skipped (its character just
/// isn't listed). Characters never banked (no LastUpdated) are left out.
/// </summary>
public static List<Row> ReadSiblings(string currentFolder)
{
var rows = new List<Row>();
if (string.IsNullOrEmpty(currentFolder)) return rows;
string? worldDir = Path.GetDirectoryName(currentFolder.TrimEnd('\\', '/'));
if (string.IsNullOrEmpty(worldDir) || !Directory.Exists(worldDir)) return rows;
string self = Path.GetFullPath(currentFolder).TrimEnd('\\', '/');
foreach (string dir in Directory.EnumerateDirectories(worldDir))
{
if (string.Equals(Path.GetFullPath(dir).TrimEnd('\\', '/'), self, StringComparison.OrdinalIgnoreCase)) continue;
string file = Path.Combine(dir, IltHubStore.StateFile);
if (!File.Exists(file)) continue;
try
{
using var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
var state = JsonSerializer.Deserialize(fs, IltHubJsonContext.Default.IltHubState);
IltBankState? bank = state?.Bank;
if (bank == null || bank.LastUpdated == DateTime.MinValue) continue;
rows.Add(new Row(Path.GetFileName(dir), false, bank));
}
catch (Exception ex)
{
RynthLog.Trace(LogCat.IltBanking, $"bank export: skipped {file} ({ex.Message})");
}
}
return rows;
}
}

View file

@ -0,0 +1,76 @@
// IltBankRoster.cs - Every character's bank on this server, for the Banking tab's "Characters" table
// and the transfer form's recipient picker. SilentKelpie's (RynthInventory 0.1.1's Banking tab, RynthSuite
// PR 12, ported by hand 2026-10-19); it read RynthILT's bank export from RynthInventory's window and
// moved into RynthILT's own Banking tab on 2026-10-21 (one server's features live in its server plugin).
// The characters are the ones RynthILT keeps balances for on this server: the logged-in one from its
// live state, every other one from its saved hub.json (IltBankExport.ReadSiblings), so every account
// played on this PC with RynthILT loaded. (RynthInventory's version also listed characters Global
// Inventory knew without a balance yet, as "not read yet" rows; those carry no balance and are left out.)
// Pure: RynthILT.Tests covers it.
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One character's balances as the Banking tab shows them (a copy: the render thread reads it).</summary>
internal sealed record IltBankRosterRow(string Name, bool Current, long Pyreals, long Luminance, long LegendaryKeys, long MythicalKeys,
long EnlightenedCoins, long WeaklyEnlightenedCoins, long PrestigeCoins, DateTime Updated)
{
public static IltBankRosterRow From(string name, bool current, IltBankState b) =>
new(name, current, b.Pyreals, b.Luminance, b.LegendaryKeys, b.MythicalKeys, b.EnlightenedCoins, b.WeaklyEnlightenedCoins,
b.PrestigeCoins, b.LastUpdated);
}
internal static class IltBankRoster
{
/// <summary>
/// The roster: the logged-in character first, then by name; a name listed twice keeps the current
/// character's row (its live state beats its saved file).
/// </summary>
public static IltBankRosterRow[] Build(IReadOnlyList<IltBankExport.Row> rows)
{
var byName = new Dictionary<string, IltBankRosterRow>(StringComparer.OrdinalIgnoreCase);
foreach (IltBankExport.Row r in rows)
{
if (string.IsNullOrWhiteSpace(r.Name)) continue;
if (byName.TryGetValue(r.Name, out IltBankRosterRow? have) && have.Current && !r.Current) continue;
byName[r.Name] = IltBankRosterRow.From(r.Name, r.Current, r.Bank);
}
var list = new List<IltBankRosterRow>(byName.Values);
list.Sort((a, b) => a.Current != b.Current ? (a.Current ? -1 : 1) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
return list.ToArray();
}
/// <summary>The sums over every character with a balance read (one row of the same shape).</summary>
public static IltBankRosterRow Totals(IReadOnlyList<IltBankRosterRow> roster)
{
long py = 0, lum = 0, lk = 0, mk = 0, ec = 0, wec = 0, pc = 0;
foreach (IltBankRosterRow r in roster)
{
if (r.Updated == DateTime.MinValue) continue;
py += r.Pyreals; lum += r.Luminance; lk += r.LegendaryKeys; mk += r.MythicalKeys;
ec += r.EnlightenedCoins; wec += r.WeaklyEnlightenedCoins; pc += r.PrestigeCoins;
}
return new IltBankRosterRow("Total", false, py, lum, lk, mk, ec, wec, pc, DateTime.MinValue);
}
/// <summary>The other characters, by name: the transfer form's recipient picker.</summary>
public static List<string> Others(IReadOnlyList<IltBankRosterRow> roster)
{
var names = new List<string>();
foreach (IltBankRosterRow r in roster) if (!r.Current) names.Add(r.Name);
return names;
}
/// <summary>"3m ago", "2h ago", "4d ago": how old a saved balance is; "-" when never read.</summary>
public static string Age(DateTime updatedLocal, DateTime nowLocal)
{
if (updatedLocal == DateTime.MinValue) return "-";
TimeSpan d = nowLocal - updatedLocal;
if (d < TimeSpan.Zero) d = TimeSpan.Zero;
if (d.TotalMinutes < 1) return "just now";
if (d.TotalHours < 1) return $"{(int)d.TotalMinutes}m ago";
if (d.TotalDays < 1) return $"{(int)d.TotalHours}h ago";
return $"{(int)d.TotalDays}d ago";
}
}

View file

@ -0,0 +1,750 @@
// IltBanking.cs — ILT banking: /bank balances, deposits, withdrawals, confirmed transfers,
// transaction log. Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
// Render is the Mini Remote's "Banking" tab, with every character's bank on this server since 2026-10-21
// (IltBankRoster: SilentKelpie's Banking tab from RynthInventory, which showed RynthILT's data there). The
// balances and log are also exported to other plugins through "RynthILT.Data" (IltBankExport; their verbs
// come back through RunVerb).
//
// Server contract (ACECustom PlayerCommands bank handler, upstream 2026-10-11):
// /bank → "[BANK] Your balances are:" then "[BANK] Pyreals: N", "Luminance:",
// "Legendary Keys:", "Mythical Keys:", "Enlightened Coins:",
// "Weakly Enlightened Coins:", "Prestige Coins: N (bound to you ...)".
// /b d, /b lum, /b w → deposits and withdrawals (IltBankCommands has the commands and replies).
// /bank t <c> <n> <who> → "Transferred {N0} {Currency} to {Name}[ (offline)]" or an error;
// the recipient sees "Received {N0} {currency} from {Name}".
// /bank t n <d> <n> <who> → trade notes' pyreal value, then "(Equivalent to ...)".
// What each item allows is IltBankCommands.Items (the server's table): Prestige Coins (pc)
// are bound (deposit and withdraw only); pyreal peas and luminance tokens deposit only.
// Deposit, withdraw and transfer share the server's bank_command_limit throttle; a balance
// refresh doesn't, so it has its own (client-side) spacing.
// Balance lines are parsed whenever they appear (player-typed /bank too) but only EATEN
// when the Hub asked. Transfers always need a confirmation (UB had none).
// Backstop (SilentKelpie's PR 12, narrowed): the capture queue eats a quiet refresh's reply, but if
// it misses, balance-dump lines arriving within QuietBalanceWindowMs of a quiet refresh are eaten
// here. Only the dump itself (header and "Label: N" lines): other [BANK] lines (errors, bound-coin
// notes), Transferred / Received lines, and balance reads nobody here asked for (a macro's or another
// plugin's /bank, outside the window) are left alone.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltBanking : IIltFeature
{
/// <summary>Transfer currencies: display name, /bank t code (IltBankCommands.Transfers).</summary>
public static readonly (string Name, string Code)[] Currencies = IltBankCommands.Transfers;
private static readonly string[] CurrencyNames = Currencies.Select(c => c.Name).ToArray();
private static readonly string[] DepositNames = IltBankCommands.Deposits.Select(d => d.Label).ToArray();
private static readonly string[] WithdrawNames = IltBankCommands.Withdrawals.Select(w => w.Label).ToArray();
private static readonly string[] NoteNames = IltBankCommands.NoteDenominations.Select(n => n.Label).ToArray();
/// <summary>Server throttle for deposit / withdraw / transfer (bank_command_limit).</summary>
private const long BankCommandSpacingMs = 5000;
/// <summary>Client spacing for balance refreshes (the server doesn't throttle a plain /bank).</summary>
private const long BalanceSpacingMs = 5000;
/// <summary>After a deposit or withdrawal, the balances are re-read this long after the reply.</summary>
private const long RefreshAfterActionMs = 1500;
private readonly IltHubContext _ctx;
private readonly object _txLock = new();
private readonly List<IltBankTransaction> _transactions;
private IltBankTransaction[] _txSnapshot = Array.Empty<IltBankTransaction>();
private bool _txDirty;
private long _lastBankCommandAt;
private long _lastBalanceAt;
private long _lastAutoRefreshAt;
/// <summary>When a quiet balance refresh is due after an action (0 = none). Pump thread.</summary>
private long _refreshDueAt;
/// <summary>Until then, money is moving between pack and bank (MovingMoney). Pump thread.</summary>
private long _moveUntil;
/// <summary>How long after a deposit / withdrawal reply the moved amounts are not income (covers the balance re-read).</summary>
private const long MoveWindowMs = 12_000;
/// <summary>Until this tick, a balance dump that reaches chat is the reply to a quiet Hub refresh (0 = no quiet refresh out).</summary>
private long _quietBalanceUntil;
/// <summary>How long after a quiet refresh is queued its leaked dump lines are still eaten here.</summary>
internal const long QuietBalanceWindowMs = 15_000;
// Render-thread form state.
private string _amountText = string.Empty;
private string _withdrawText = string.Empty;
private string _txFilter = string.Empty;
private string _lastResult = string.Empty;
private volatile string _actionResult = string.Empty;
/// <summary>The newest action reply or error (deposit, withdrawal or transfer), for the bank export.</summary>
private volatile string _latestResult = string.Empty;
/// <summary>
/// Another plugin is showing the balances (a "RynthILT.Data" reader):
/// the periodic quiet refresh runs as it does while the Mini Remote is open. Pump thread.
/// </summary>
public bool ReaderWatching;
/// <summary>The newest action reply or error (any thread).</summary>
public string LatestResult => _latestResult;
// Every character's balances on this server (IltBankRoster), built by the controller on the pump
// while the tab is on screen (the render thread marks it watched).
private volatile IltBankRosterRow[] _roster = Array.Empty<IltBankRosterRow>();
private long _rosterWatchedAt = long.MinValue / 2;
/// <summary>Every character's balances on this server, logged-in one first (any thread).</summary>
public IltBankRosterRow[] Roster => _roster;
/// <summary>Pump thread: the controller's latest roster.</summary>
public void PublishRoster(IltBankRosterRow[] rows) => _roster = rows ?? Array.Empty<IltBankRosterRow>();
/// <summary>When the tab last drew the roster (any thread).</summary>
public long RosterWatchedAt => System.Threading.Interlocked.Read(ref _rosterWatchedAt);
/// <summary>The roster is on screen: the controller keeps it fresh (render thread, or a test).</summary>
internal void MarkRosterWatched() => System.Threading.Interlocked.Exchange(ref _rosterWatchedAt, IltHubContext.NowMs);
/// <summary>The transaction log as last published (any thread; oldest first).</summary>
public IReadOnlyList<IltBankTransaction> Transactions => _txSnapshot;
/// <summary>The bank state (pump thread).</summary>
public IltBankState State => Bank;
/// <summary>Raised (pump thread) after a balance line updates the state; Character rates use the deltas.</summary>
public event Action<string, long, long>? BalanceChanged;
public IltBanking(IltHubContext ctx)
{
_ctx = ctx;
_transactions = ctx.Store.LoadTransactions();
PublishSnapshot();
}
private IltBankState Bank => _ctx.State.Bank;
public bool Enabled => _ctx.Options.IsOn(IltFeature.Bank);
/// <summary>
/// True while a deposit or withdrawal is moving money between the pack and the bank (sent from
/// this tab or typed): session rates then re-baseline instead of counting it as income. Pump thread.
/// </summary>
public bool MovingMoney => IltHubContext.NowMs < _moveUntil;
/// <summary>Exposed for the one-time UB import (mutated under the lock).</summary>
public void ImportUb(Func<List<IltBankTransaction>, string> importer)
{
string summary;
lock (_txLock)
{
summary = importer(_transactions);
_txDirty = true;
}
PublishSnapshot();
RynthLog.Write(LogCat.IltBanking, $"[IltHub] UB sidecar import: {summary}");
}
// ── Commands ────────────────────────────────────────────────────────────
/// <summary>Queues a /bank balance refresh (eaten when <paramref name="quiet"/>).</summary>
public void RequestRefresh(bool quiet)
{
RynthLog.Trace(LogCat.IltBanking, $"RequestRefresh(quiet={quiet})");
if (_ctx.Capture.IsPending("/bank")) return;
long now = IltHubContext.NowMs;
if (now - _lastBalanceAt < BalanceSpacingMs) return;
_lastBalanceAt = now;
_quietBalanceUntil = quiet ? now + QuietBalanceWindowMs : 0;
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/bank",
IsResponseLine = t => t.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 2000,
FirstLineTimeoutMs = 15000,
Eat = quiet,
OnComplete = r =>
{
if (r.UnknownCommand) _ctx.Options.Set(IltFeature.Bank, IltTri.Off);
else if (r.Lines.Count > 0) _ctx.Options.Set(IltFeature.Bank, IltTri.On);
},
});
}
/// <summary>
/// Validates and (after the UI confirm) sends a transfer. For trade notes
/// <paramref name="amount"/> is the note count of <paramref name="denomination"/>. Pump thread.
/// Returns an error message, or empty when the command was queued.
/// </summary>
public string SendTransfer(int currencyIndex, long amount, string target, int denomination = -1)
{
RynthLog.Trace(LogCat.IltBanking, $"SendTransfer(currency={currencyIndex}, amount={amount}, denom={denomination}, target='{target}')");
if (!Enabled) return "Bank is not available on this server.";
target = (target ?? string.Empty).Trim();
// The recipient is spliced into a chat command, so only character-name characters are
// allowed: no '/', quotes, control characters or line breaks that could start a second command.
if (target.Length > 0 && !IltParse.CharacterName.IsMatch(target)) return "Recipient must be a character name (letters, spaces, ' and - only).";
if (target.Equals(_ctx.CharName, StringComparison.OrdinalIgnoreCase)) return "You cannot transfer to yourself.";
string cmd = IltBankCommands.Transfer(currencyIndex, amount, denomination, target, out string error);
if (cmd.Length == 0) return error;
long now = IltHubContext.NowMs;
if (now - _lastBankCommandAt < BankCommandSpacingMs) return "Bank commands are limited to one every 5 seconds.";
_lastBankCommandAt = now;
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = cmd,
IsResponseLine = IltBankCommands.IsTransferReply,
IdleEndMs = 500,
FirstLineTimeoutMs = 8000,
Eat = false,
OnComplete = r =>
{
_lastResult = r.Lines.Count > 0 ? r.Lines[^1] : (r.TimedOut ? "No reply from server." : string.Empty);
_latestResult = _lastResult;
// Balances changed: read them again shortly.
_refreshDueAt = IltHubContext.NowMs + RefreshAfterActionMs;
},
});
return string.Empty;
}
/// <summary>
/// Sends a deposit (<see cref="IltBankCommands.Deposits"/> index). Pump thread. Returns an
/// error message, or empty when the command was queued; the reply lands in the tab.
/// </summary>
public string SendDeposit(int index)
{
string cmd = IltBankCommands.Deposit(index);
if (cmd.Length == 0) return "Pick what to deposit.";
return SendAction(cmd, "Deposit");
}
/// <summary>
/// Sends a withdrawal (<see cref="IltBankCommands.Withdrawals"/> index; for trade notes
/// <paramref name="amount"/> is the note count). Pump thread; same result as SendDeposit.
/// </summary>
public string SendWithdraw(int index, long amount, int denomination)
{
string cmd = IltBankCommands.Withdraw(index, amount, denomination, out string error);
if (cmd.Length == 0) return error;
return SendAction(cmd, "Withdraw");
}
/// <summary>A deposit or withdrawal through the capture queue (shown, not eaten), then a quiet balance read.</summary>
private string SendAction(string cmd, string what)
{
RynthLog.Trace(LogCat.IltBanking, $"{what}: '{cmd}'");
if (!Enabled) return "Bank is not available on this server.";
long now = IltHubContext.NowMs;
if (now - _lastBankCommandAt < BankCommandSpacingMs) return "Bank commands are limited to one every 5 seconds.";
_lastBankCommandAt = now;
_moveUntil = now + MoveWindowMs;
_actionResult = what + " sent...";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = cmd,
IsResponseLine = IltBankCommands.IsActionReply,
IdleEndMs = 800,
FirstLineTimeoutMs = 8000,
Eat = false,
OnComplete = r =>
{
_actionResult = r.Lines.Count > 0 ? string.Join("\n", r.Lines.TakeLast(6))
: r.TimedOut ? "No reply from the server." : string.Empty;
_latestResult = _actionResult;
_refreshDueAt = IltHubContext.NowMs + RefreshAfterActionMs;
},
});
return string.Empty;
}
/// <summary>
/// A bank verb line from "RynthILT.Data" BankCommand (Plugins/Shared/RynthIltDataApi.cs):
/// "refresh", "deposit i", "withdraw i amount note", "transfer i amount note name". The reader
/// has already confirmed a transfer with the player. Pump thread. Returns an error, or empty
/// when it was queued; either way the outcome shows in <see cref="LatestResult"/>.
/// </summary>
public string RunVerb(string line)
{
string[] p = (line ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
string err;
if (p.Length == 0) err = "Empty bank command.";
else if (p[0] == "refresh" && p.Length == 1) { RequestRefresh(quiet: true); return string.Empty; }
else if (p[0] == "deposit" && p.Length == 2 && int.TryParse(p[1], out int d)) err = SendDeposit(d);
else if (p[0] == "withdraw" && p.Length == 4 && int.TryParse(p[1], out int w) && long.TryParse(p[2], out long wa)
&& int.TryParse(p[3], out int wn))
err = SendWithdraw(w, wa, wn);
else if (p[0] == "transfer" && p.Length >= 5 && int.TryParse(p[1], out int c) && long.TryParse(p[2], out long ta)
&& int.TryParse(p[3], out int tn))
{
// The name may hold spaces; SendTransfer checks it is a character name.
string who = string.Join(' ', p, 4, p.Length - 4);
err = SendTransfer(c, ta, who, IltBankCommands.IsNoteTransfer(c) ? tn : -1);
if (err.Length == 0) _latestResult = "Transfer sent...";
}
else err = "Unknown bank command.";
if (err.Length > 0) _latestResult = err;
RynthLog.Trace(LogCat.IltBanking, $"reader verb '{line}' -> {(err.Length > 0 ? err : "queued")}");
return err;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
// Periodic quiet refresh only while the balances are on screen (the Hub, or a reader's
// Banking tab) and the server has /bank.
int every = Bank.AutoRefreshSeconds;
if (Enabled && (_ctx.WindowOpen || ReaderWatching) && every > 0 && nowMs - _lastAutoRefreshAt >= every * 1000L
&& nowMs - _lastBalanceAt >= BalanceSpacingMs)
{
_lastAutoRefreshAt = nowMs;
RequestRefresh(quiet: true);
}
// The balance read a deposit, withdrawal or transfer asked for (retried until the spacing allows).
if (_refreshDueAt != 0 && nowMs >= _refreshDueAt && Enabled && nowMs - _lastBalanceAt >= BalanceSpacingMs)
{
_refreshDueAt = 0;
_lastAutoRefreshAt = nowMs;
RequestRefresh(quiet: true);
}
if (_txDirty)
{
lock (_txLock)
{
_ctx.Store.SaveTransactionsIfDirty(_transactions);
_txDirty = false;
}
PublishSnapshot();
}
}
public bool OnChat(string text)
{
if (text.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase))
{
bool dump = ParseBalanceLine(text);
// Eating is decided by the capture queue; this only backs it up for a quiet refresh's dump.
return EatLeakedDump(dump, IltHubContext.NowMs, _quietBalanceUntil);
}
// A deposit or withdrawal reply (ours or a typed /b): the next balance and pack changes are moves.
if (text.StartsWith("Deposited ", StringComparison.Ordinal) || text.StartsWith("Withdrew ", StringComparison.Ordinal))
_moveUntil = Math.Max(_moveUntil, IltHubContext.NowMs + MoveWindowMs);
TryLogTransaction(text);
return false;
}
public void OnLogout()
{
lock (_txLock) _ctx.Store.SaveTransactionsIfDirty(_transactions);
}
// ── Parsing ─────────────────────────────────────────────────────────────
/// <summary>
/// True when a quiet refresh's dump line that reached chat should be eaten here: it is a balance
/// line (see <see cref="ParseBalanceLine"/>) and a quiet refresh was queued within the window.
/// </summary>
internal static bool EatLeakedDump(bool isBalanceLine, long nowMs, long quietUntilMs)
=> isBalanceLine && quietUntilMs != 0 && nowMs < quietUntilMs;
/// <summary>The balance key a dump label belongs to ("Weakly Enlightened Coins" -> WeaklyEnlightenedCoins), or null.</summary>
internal static string? BalanceKeyFor(string label)
{
// Order matters: "Weakly Enlightened Coins" also contains "Enlightened Coins".
if (label.Contains("Prestige", StringComparison.OrdinalIgnoreCase)) return "PrestigeCoins";
if (label.Contains("Weakly", StringComparison.OrdinalIgnoreCase)) return "WeaklyEnlightenedCoins";
if (label.Contains("Enlightened", StringComparison.OrdinalIgnoreCase)) return "EnlightenedCoins";
if (label.Contains("Mythical", StringComparison.OrdinalIgnoreCase)) return "MythicalKeys";
if (label.Contains("Legendary", StringComparison.OrdinalIgnoreCase)) return "LegendaryKeys";
if (label.Contains("Luminance", StringComparison.OrdinalIgnoreCase)) return "Luminance";
if (label.Contains("Pyreal", StringComparison.OrdinalIgnoreCase)) return "Pyreals";
return null;
}
/// <summary>
/// True when a "[BANK] ..." line is part of the /bank balance dump: the "Your balances are:" header
/// or a "Label: N" line for a known currency. Errors, the bound-coin note and the like are not.
/// </summary>
internal static bool IsBalanceDumpLine(string text)
{
if (!text.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase)) return false;
string body = text.Substring("[BANK]".Length).Trim();
if (body.StartsWith("Your balances", StringComparison.OrdinalIgnoreCase)) return true;
int colon = body.IndexOf(':');
if (colon <= 0) return false;
if (body.Substring(colon + 1).Trim().Length == 0) return true; // a header ending in a colon
return BalanceKeyFor(body.Substring(0, colon).Trim()) != null;
}
/// <summary>Reads a "[BANK] ..." line into the balances. Returns <see cref="IsBalanceDumpLine"/>.</summary>
private bool ParseBalanceLine(string text)
{
if (!IsBalanceDumpLine(text)) return false;
string body = text.Substring("[BANK]".Length).Trim();
int colon = body.IndexOf(':');
if (colon <= 0 || body.Substring(colon + 1).Trim().Length == 0) return true; // a header: nothing to read
string label = body.Substring(0, colon).Trim();
long value = IltParse.ParseLeadingLong(body.Substring(colon + 1));
switch (BalanceKeyFor(label))
{
case "PrestigeCoins": Apply("PrestigeCoins", ref Bank.PrestigeCoins, value); break;
case "WeaklyEnlightenedCoins": Apply("WeaklyEnlightenedCoins", ref Bank.WeaklyEnlightenedCoins, value); break;
case "EnlightenedCoins": Apply("EnlightenedCoins", ref Bank.EnlightenedCoins, value); break;
case "MythicalKeys": Apply("MythicalKeys", ref Bank.MythicalKeys, value); break;
case "LegendaryKeys": Apply("LegendaryKeys", ref Bank.LegendaryKeys, value); break;
case "Luminance": Apply("Luminance", ref Bank.Luminance, value); break;
case "Pyreals": Apply("Pyreals", ref Bank.Pyreals, value); break;
default: return false;
}
Bank.LastUpdated = DateTime.Now;
_ctx.Options.Set(IltFeature.Bank, IltTri.On);
return true;
}
private void Apply(string key, ref long field, long value)
{
long old = field;
field = value;
if (old != value)
{
try { BalanceChanged?.Invoke(key, old, value); } catch { }
}
}
private void TryLogTransaction(string text)
{
if (!(text.StartsWith("Transferred ", StringComparison.Ordinal) || text.StartsWith("Received ", StringComparison.Ordinal)))
return;
// Only server system lines are logged. Anything another player can author (tells, says,
// emotes, any bracketed channel) is rejected so quoted "Transferred ..." text can't
// forge entries in the transaction log.
if (IsPlayerAuthoredLine(text))
{
RynthLog.Trace(LogCat.IltBanking, "transaction ignored (player-authored line): " + text);
return;
}
var sent = IltParse.BankSent.Match(text);
var recv = sent.Success ? System.Text.RegularExpressions.Match.Empty : IltParse.BankReceived.Match(text);
var m = sent.Success ? sent : recv;
if (!m.Success) return;
string other = IltParse.StripMarkup(m.Groups[3].Value).Replace(" (offline)", string.Empty).Trim();
var tx = new IltBankTransaction
{
Timestamp = DateTime.Now,
Type = sent.Success ? "Sent" : "Received",
Amount = IltParse.ParseLeadingLong(m.Groups[1].Value),
Currency = m.Groups[2].Value.Trim(),
OtherPlayer = other,
Description = text,
};
lock (_txLock)
{
_transactions.Add(tx);
if (_transactions.Count > IltHubStore.MaxTransactions)
_transactions.RemoveRange(0, _transactions.Count - IltHubStore.MaxTransactions);
_txDirty = true;
}
}
/// <summary>True for chat another player could have written (tells, says, channel or emote markup).</summary>
private static bool IsPlayerAuthoredLine(string text)
=> text.Contains("<Tell:", StringComparison.Ordinal)
|| text.Contains(" tells you", StringComparison.Ordinal)
|| text.Contains(" says, \"", StringComparison.Ordinal)
|| text.Contains("[Allegiance]", StringComparison.Ordinal)
|| text.Contains("[Fellowship]", StringComparison.Ordinal)
|| text.Contains("[General]", StringComparison.Ordinal)
|| text.Contains("[Trade]", StringComparison.Ordinal)
|| text.Contains("[LFG]", StringComparison.Ordinal)
|| text.Contains("[Roleplay]", StringComparison.Ordinal)
|| text.Contains("[Society]", StringComparison.Ordinal)
|| text.Contains("[Olthoi]", StringComparison.Ordinal)
|| text.Contains("[Patron]", StringComparison.Ordinal)
|| text.Contains("[Vassals]", StringComparison.Ordinal)
|| text.Contains("[Covassals]", StringComparison.Ordinal)
|| text.Contains("[Monarch]", StringComparison.Ordinal);
private void PublishSnapshot()
{
lock (_txLock) _txSnapshot = _transactions.ToArray();
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
if (!Enabled)
{
SafeImGui.TextColored(IltStyle.ColTextMute,
_ctx.Options.IsOff(IltFeature.Bank) ? "The server reports /bank is not available." : "Waiting for the server options check...");
return;
}
// Balances
ImGui.TextColored(IltStyle.ColTeal, "Balances");
ImGui.SameLine();
if (ImGui.SmallButton("Refresh##bank")) _ctx.Post(() => RequestRefresh(quiet: true));
ImGui.SameLine();
if (ImGui.SmallButton("Copy##bank")) ImGui.SetClipboardText(BuildCopyLine());
ImGui.SameLine();
SafeImGui.TextDisabled(Bank.LastUpdated == DateTime.MinValue ? "never updated" : "updated " + Bank.LastUpdated.ToString("g"));
if (ImGui.BeginTable("##iltbal", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV))
{
Row("Pyreals", Bank.Pyreals);
Row("Luminance", Bank.Luminance);
Row("Legendary Keys", Bank.LegendaryKeys);
Row("Mythical Keys", Bank.MythicalKeys);
Row("Enlightened Coins", Bank.EnlightenedCoins);
Row("Weakly Enlightened Coins", Bank.WeaklyEnlightenedCoins);
Row("Prestige Coins", Bank.PrestigeCoins);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Bound to you: deposit and withdraw only, never transferred.");
ImGui.EndTable();
}
int refresh = Bank.AutoRefreshSeconds;
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Auto-refresh seconds (0 = off)", ref refresh, 30))
Bank.AutoRefreshSeconds = refresh <= 0 ? 0 : Math.Max(30, refresh);
RenderRoster();
ImGui.Separator();
RenderDepositWithdraw();
ImGui.Separator();
RenderTransferForm();
ImGui.Separator();
RenderTransactionLog();
}
/// <summary>
/// "Every character on this server": the balances RynthILT keeps for each character it has run here
/// (SilentKelpie's Banking tab, from RynthInventory 2026-10-21), with the totals. Only you: nothing more to show.
/// </summary>
private void RenderRoster()
{
MarkRosterWatched();
IltBankRosterRow[] roster = _roster;
if (roster.Length <= 1) return;
if (!ImGui.CollapsingHeader($"Every character on this server ({roster.Length})##bankroster", ImGuiTreeNodeFlags.DefaultOpen)) return;
const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingStretchProp;
if (ImGui.BeginTable("##bankroster", 6, flags))
{
ImGui.TableSetupColumn("Character", ImGuiTableColumnFlags.None, 1.3f);
ImGui.TableSetupColumn("Pyreals", ImGuiTableColumnFlags.None, 1.1f);
ImGui.TableSetupColumn("Luminance", ImGuiTableColumnFlags.None, 1.1f);
ImGui.TableSetupColumn("Keys L/M", ImGuiTableColumnFlags.None, 0.7f);
ImGui.TableSetupColumn("Coins E/W/P", ImGuiTableColumnFlags.None, 1.0f);
ImGui.TableSetupColumn("Updated", ImGuiTableColumnFlags.None, 0.8f);
ImGui.TableHeadersRow();
DateTime now = DateTime.Now;
foreach (IltBankRosterRow r in roster) RosterRow(r.Current ? r.Name + " (you)" : r.Name, r, IltBankRoster.Age(r.Updated, now), false);
RosterRow("Total", IltBankRoster.Totals(roster), string.Empty, true);
ImGui.EndTable();
}
ImGui.TextDisabled("Each character's last read balance; it updates when that character logs in with RynthILT.");
}
private static void RosterRow(string name, IltBankRosterRow r, string updated, bool total)
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
if (total) SafeImGui.TextColored(IltStyle.ColAmber, name);
else ImGui.TextUnformatted(name);
ImGui.TableNextColumn(); ImGui.TextUnformatted(IltParse.N0(r.Pyreals));
ImGui.TableNextColumn(); ImGui.TextUnformatted(IltParse.N0(r.Luminance));
ImGui.TableNextColumn(); ImGui.TextUnformatted($"{IltParse.N0(r.LegendaryKeys)}/{IltParse.N0(r.MythicalKeys)}");
ImGui.TableNextColumn(); ImGui.TextUnformatted($"{IltParse.N0(r.EnlightenedCoins)}/{IltParse.N0(r.WeaklyEnlightenedCoins)}/{IltParse.N0(r.PrestigeCoins)}");
ImGui.TableNextColumn(); if (updated.Length > 0) SafeImGui.TextDisabled(updated);
}
private static void Row(string label, long value)
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.TextUnformatted(label);
ImGui.TableNextColumn();
ImGui.TextUnformatted($"{IltParse.N0(value)} ({IltParse.Compact(value)})");
}
/// <summary>Deposit (one kind or everything, luminance tokens included) and withdraw (an amount, or trade notes).</summary>
private void RenderDepositWithdraw()
{
ImGui.TextColored(IltStyle.ColTeal, "Deposit");
int dep = Math.Clamp(Bank.DepositIndex, 0, DepositNames.Length - 1);
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("##bankdep", ref dep, DepositNames, DepositNames.Length)) Bank.DepositIndex = dep;
ImGui.SameLine();
if (ImGui.Button("Deposit##bankdep"))
{
int index = dep;
_ctx.Post(() => { string err = SendDeposit(index); if (err.Length > 0) _actionResult = err; });
}
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip(IltBankCommands.Deposit(dep) + "\nEverything banks all currencies, notes and luminance tokens."
+ "\nThe server refuses while you are busy or moving.");
ImGui.TextColored(IltStyle.ColTeal, "Withdraw");
int wd = Math.Clamp(Bank.WithdrawIndex, 0, WithdrawNames.Length - 1);
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("##bankwd", ref wd, WithdrawNames, WithdrawNames.Length)) Bank.WithdrawIndex = wd;
bool notes = IltBankCommands.Withdrawals[wd].Code == "n";
int denom = Math.Clamp(Bank.WithdrawNoteIndex, 0, NoteNames.Length - 1);
if (notes)
{
ImGui.SameLine();
ImGui.SetNextItemWidth(110);
if (ImGui.Combo("##bankwdnote", ref denom, NoteNames, NoteNames.Length)) Bank.WithdrawNoteIndex = denom;
}
ImGui.SetNextItemWidth(200);
ImGui.InputTextWithHint("##bankwdamt", notes ? "how many notes" : "amount, e.g. 250000, 1.5m", ref _withdrawText, 32u);
bool ok = IltParse.TryParseAmount(_withdrawText, out long amount);
ImGui.SameLine();
ImGui.BeginDisabled(!ok);
if (ImGui.Button("Withdraw##bankwd"))
{
int index = wd, note = denom;
long amt = amount;
_ctx.Post(() => { string err = SendWithdraw(index, amt, note); if (err.Length > 0) _actionResult = err; });
}
ImGui.EndDisabled();
if (_withdrawText.Length > 0)
{
ImGui.SameLine();
if (!ok) ImGui.TextColored(IltStyle.ColHp, "invalid amount");
else if (notes) SafeImGui.TextDisabled("= " + IltParse.N0(amount * IltBankCommands.NoteDenominations[denom].Value) + " pyreals");
else SafeImGui.TextDisabled("= " + IltParse.N0(amount));
}
string result = _actionResult;
if (result.Length > 0) SafeImGui.TextWrapped(result);
}
private void RenderTransferForm()
{
ImGui.TextColored(IltStyle.ColTeal, "Transfer");
int idx = Math.Clamp(Bank.TransferCurrencyIndex, 0, Currencies.Length - 1);
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("Currency##xfer", ref idx, CurrencyNames, CurrencyNames.Length))
Bank.TransferCurrencyIndex = idx;
bool notes = IltBankCommands.IsNoteTransfer(idx);
int denom = Math.Clamp(Bank.TransferNoteIndex, 0, NoteNames.Length - 1);
if (notes)
{
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("Denomination##xfer", ref denom, NoteNames, NoteNames.Length)) Bank.TransferNoteIndex = denom;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("The server moves the notes' pyreal value from your bank (/b t n <denomination> <count> <name>).");
}
ImGui.SetNextItemWidth(200);
ImGui.InputTextWithHint("Amount##xfer", notes ? "how many notes" : "e.g. 250000, 1.5m, 2b", ref _amountText, 32u);
string target = Bank.TransferTarget;
ImGui.SetNextItemWidth(200);
if (ImGui.InputTextWithHint("Recipient##xfer", "character name", ref target, 64u))
Bank.TransferTarget = target;
// Your other characters on this server, to fill the recipient with one click.
List<string> others = IltBankRoster.Others(_roster);
if (others.Count > 0)
{
ImGui.SameLine();
ImGui.SetNextItemWidth(150);
if (ImGui.BeginCombo("##xferpick", "Pick a character..."))
{
for (int i = 0; i < others.Count; i++)
if (ImGui.Selectable(others[i] + "##xferpick" + i)) Bank.TransferTarget = others[i];
ImGui.EndCombo();
}
}
bool amountOk = IltParse.TryParseAmount(_amountText, out long amount);
if (_amountText.Length > 0)
{
ImGui.SameLine();
if (!amountOk) ImGui.TextColored(IltStyle.ColHp, "invalid amount");
else if (notes) SafeImGui.TextDisabled("= " + IltParse.N0(IltBankCommands.NoteValue(denom, amount)) + " pyreals");
else SafeImGui.TextDisabled("= " + IltParse.N0(amount));
}
ImGui.BeginDisabled(!amountOk || string.IsNullOrWhiteSpace(Bank.TransferTarget));
if (ImGui.Button("Send transfer..."))
{
int cur = idx, note = notes ? denom : -1;
long amt = amount;
string who = Bank.TransferTarget.Trim();
string what = notes
? $"{IltParse.N0(amt)} {IltBankCommands.NoteDenominations[denom].Label} trade notes ({IltParse.N0(IltBankCommands.NoteValue(denom, amt))} pyreals)"
: $"{IltParse.N0(amt)} {Currencies[cur].Name}";
_ctx.Confirm("Confirm bank transfer",
$"Send {what} to {who}?\n\nThis cannot be undone.",
() =>
{
string err = SendTransfer(cur, amt, who, note);
_lastResult = err.Length > 0 ? err : "Transfer sent...";
},
"Send");
}
ImGui.EndDisabled();
if (_lastResult.Length > 0) SafeImGui.TextWrapped(_lastResult);
}
private void RenderTransactionLog()
{
var snap = _txSnapshot;
SafeImGui.TextColored(IltStyle.ColTeal, $"Transactions ({snap.Length})");
ImGui.SameLine();
ImGui.SetNextItemWidth(180);
ImGui.InputTextWithHint("##txfilter", "filter player / currency", ref _txFilter, 64u);
ImGui.SameLine();
if (ImGui.SmallButton("Copy CSV")) ImGui.SetClipboardText(BuildCsv(snap));
if (ImGui.BeginTable("##ilttx", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.Resizable,
new Vector2(0, 220)))
{
ImGui.TableSetupScrollFreeze(0, 1);
ImGui.TableSetupColumn("When");
ImGui.TableSetupColumn("Type");
ImGui.TableSetupColumn("Amount");
ImGui.TableSetupColumn("Currency");
ImGui.TableSetupColumn("Player");
ImGui.TableHeadersRow();
for (int i = snap.Length - 1; i >= 0; i--)
{
var t = snap[i];
if (_txFilter.Length > 0
&& !t.OtherPlayer.Contains(_txFilter, StringComparison.OrdinalIgnoreCase)
&& !t.Currency.Contains(_txFilter, StringComparison.OrdinalIgnoreCase))
continue;
ImGui.TableNextRow();
ImGui.TableNextColumn(); ImGui.TextUnformatted(t.Timestamp.ToString("g"));
ImGui.TableNextColumn();
SafeImGui.TextColored(t.Type == "Sent" ? IltStyle.ColAmber : IltStyle.ColGreen, t.Type);
ImGui.TableNextColumn(); ImGui.TextUnformatted(IltParse.N0(t.Amount));
ImGui.TableNextColumn(); ImGui.TextUnformatted(t.Currency);
ImGui.TableNextColumn(); ImGui.TextUnformatted(t.OtherPlayer);
}
ImGui.EndTable();
}
}
/// <summary>One-line summary in UB's chat-paste format.</summary>
public string BuildCopyLine()
=> $"Bank Balances - {_ctx.CharName} | P: {IltParse.N0(Bank.Pyreals)} | L: {IltParse.N0(Bank.Luminance)} | "
+ $"LK: {IltParse.N0(Bank.LegendaryKeys)} | MK: {IltParse.N0(Bank.MythicalKeys)} | "
+ $"Coins: {IltParse.N0(Bank.EnlightenedCoins)} | W Coins: {IltParse.N0(Bank.WeaklyEnlightenedCoins)} | "
+ $"P Coins: {IltParse.N0(Bank.PrestigeCoins)} | "
+ $"Updated: {(Bank.LastUpdated == DateTime.MinValue ? "never" : Bank.LastUpdated.ToString("g"))}";
private static string BuildCsv(IltBankTransaction[] rows)
{
var sb = new System.Text.StringBuilder("Timestamp,Type,Amount,Currency,Player\n");
foreach (var t in rows)
sb.Append(t.Timestamp.ToString("s")).Append(',').Append(t.Type).Append(',').Append(t.Amount).Append(',')
.Append('"').Append(t.Currency.Replace("\"", "\"\"")).Append("\",\"")
.Append(t.OtherPlayer.Replace("\"", "\"\"")).Append("\"\n");
return sb.ToString();
}
}

View file

@ -0,0 +1,316 @@
// IltBreedingEssence.cs - One carried combat pet essence, as the breeding tracker sees it.
//
// The facts come from the essence's appraisal (ACECustom [AssessmentProperty] qualities: bond 9053,
// male charges 9057, next breeding time float 9056, incense float 9058, neutered bool 9051, the
// male override 50053, juvenile 50054, Chromatic Catalyst 50055, the guardian's Offering 50056,
// maturity kills 9077, the mutation lines 9070..9075) and its LongDesc breeding block ("Sex: ...",
// "Growth: ...", "(shiny - cannot breed)"). Evaluate turns them into what the player needs to know:
// stud or dam, every breeding gate that fails, when it clears, growth, and the boosters applied.
// The gates are ACE PetDevice_Breeding's, with the thresholds from IltBreedingRules.
//
// Pure: no host calls (IltPetBreeding reads the host), so RynthILT.Tests checks it offline.
using System;
using System.Collections.Generic;
using System.Globalization;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>A gate's outcome for one essence.</summary>
internal enum BreedGate { Ready, Resting, NoCharges, Growing, Neutered, Shiny, LowBond, LowTier, NeedsId }
/// <summary>What was read for one essence (host values; pump thread fills it).</summary>
internal sealed class BreedEssenceFacts
{
public int Id;
public string Name = string.Empty;
public uint Wcid;
public bool HasId;
/// <summary>The essence's level requirement (a tier fallback for WCIDs outside the table).</summary>
public int UseLevel;
public int Bond;
/// <summary>The server's explicit sex (Tailoring Kit), or null to derive it from the object id.</summary>
public bool? MaleOverride;
public bool Neutered;
public bool JuvenileFlag;
/// <summary>PetMaturityKills: -1 when absent (the essence was never bred).</summary>
public int MaturityKills = -1;
/// <summary>PetMaleBreedingCharges: -1 when absent (a full stud).</summary>
public int MaleCharges = -1;
public double MaleRefreshUnix;
public double NextBreedUnix;
public double Incense;
public bool Catalyst;
public bool Offering;
public double MaturityXpMult;
public int MutDamage, MutDamageResist, MutCrit, MutVitality, MutPotency, MutationCount;
public int PotencyStored;
public bool Attuned;
public string LongDesc = string.Empty;
}
/// <summary>One essence evaluated for breeding. Immutable; the UI and the reader JSON read it.</summary>
internal sealed record BreedEssence(
int Id, string Name, uint Wcid, bool HasId, int Tier, int Bond, bool Male, BreedGate Gate, string Status,
IReadOnlyList<string> Problems, double ReadyAtUnix, int Charges, int ChargesMax, double RefillAtUnix,
bool Bred, bool Juvenile, int Stage, int Stages, string StageName, int Kills, int KillsRequired, int KillsToNext,
double Incense, bool Catalyst, bool Offering, bool Draught, IReadOnlyList<string> Boosters,
int MutD, int MutDR, int MutC, int MutV, int MutP, bool Shiny, bool Unbound, int Potency)
{
/// <summary>Every gate passes now.</summary>
public bool Ready => Gate == BreedGate.Ready;
/// <summary>The stat mutation lines (damage, damage resist, crit, vitality) summed.</summary>
public int StatMutations => MutD + MutDR + MutC + MutV;
/// <summary>"Stud" or "Dam".</summary>
public string Role => Male ? "Stud" : "Dam";
}
internal static class IltBreedingEssence
{
/// <summary>Essence tiers, in the order of each family row below (ACE PetDeviceWcids petLevelIndexes).</summary>
public static readonly int[] Tiers = { 50, 80, 100, 125, 150, 180, 200, 250, 300 };
// ACECustom PetDeviceWcids: one row per combat pet family, tiers 50 .. 300 in order. "a-b" is a
// run of consecutive WCIDs. Rows copied from Source/ACE.Server/Factories/Tables/Wcids/PetDeviceWcids.cs.
private static readonly string[] FamilyRows =
{
"48942,48944,48945,48946,48947,48948,48956,787801001,787801037",
"49213-49219,787801002,787801038",
"49220-49226,787801003,787801039",
"49227-49232,49212,787801004,787801040",
"48972,49234-49239,787801005,787801041",
"49240-49246,787801006,787801042",
"49247-49253,787801007,787801043",
"49254-49259,49233,787801008,787801044",
"49421-49427,787801009,787801045",
"49428-49434,787801010,787801046",
"49435-49441,787801011,787801047",
"49442-49448,787801012,787801048",
"48959,48961,48963,48965,48967,48969,48957,787801013,787801049",
"49261-49267,787801014,787801050",
"49268-49274,787801015,787801051",
"49275-49280,49260,787801016,787801052",
"49282-49287,49281,787801017,787801053",
"49289-49294,49288,787801018,787801054",
"49296-49301,49295,787801019,787801055",
"49303-49308,49302,787801020,787801056",
"49310-49316,787801021,787801057",
"49317-49323,787801022,787801058",
"49324-49330,787801023,787801059",
"49331-49336,49309,787801024,787801060",
"49338-49344,787801025,787801061",
"49345-49351,787801026,787801062",
"49352-49358,787801027,787801063",
"49359-49364,49337,787801028,787801064",
"49366-49372,787801029,787801065",
"49373-49379,787801030,787801066",
"49380-49386,787801031,787801067",
"49387-49392,49365,787801032,787801068",
"49524-49530,787801033,787801069",
"49531-49537,787801034,787801070",
"49538-49544,787801035,787801071",
"49545-49551,787801036,787801072",
};
/// <summary>Each family row expanded (tests check every row has one WCID per tier).</summary>
internal static readonly uint[][] Families = Array.ConvertAll(FamilyRows, ExpandRow);
private static readonly Dictionary<uint, int> TierByWcid = BuildTiers();
private static uint[] ExpandRow(string row)
{
var list = new List<uint>(9);
foreach (string token in row.Split(','))
{
int dash = token.IndexOf('-');
if (dash < 0) { list.Add(uint.Parse(token, CultureInfo.InvariantCulture)); continue; }
uint a = uint.Parse(token.AsSpan(0, dash), NumberStyles.Integer, CultureInfo.InvariantCulture);
uint b = uint.Parse(token.AsSpan(dash + 1), NumberStyles.Integer, CultureInfo.InvariantCulture);
for (uint w = a; w <= b; w++) list.Add(w);
}
return list.ToArray();
}
private static Dictionary<uint, int> BuildTiers()
{
var d = new Dictionary<uint, int>();
foreach (uint[] row in Families)
for (int i = 0; i < row.Length && i < Tiers.Length; i++)
d[row[i]] = Tiers[i];
return d;
}
/// <summary>True for a combat pet essence WCID (the only kind that breeds).</summary>
public static bool IsCombatEssence(uint wcid) => TierByWcid.ContainsKey(wcid);
/// <summary>The essence tier for a WCID, else the level requirement when it is a tier, else 0.</summary>
public static int TierOf(uint wcid, int useLevel = 0)
{
if (TierByWcid.TryGetValue(wcid, out int t)) return t;
return Array.IndexOf(Tiers, useLevel) >= 0 ? useLevel : 0;
}
/// <summary>ACE PetDevice.IsMale without an override: murmur3 fmix32 on the object id, even = male.</summary>
public static bool DeriveIsMale(int objectId)
{
uint h = unchecked((uint)objectId);
h ^= h >> 16;
h = unchecked(h * 0x7feb352d);
h ^= h >> 15;
h = unchecked(h * 0x846ca68b);
h ^= h >> 16;
return (h & 1) == 0;
}
/// <summary>"3h 05m", "42m", "20s" (0 or less = "now").</summary>
public static string Duration(double seconds)
{
if (seconds <= 0) return "now";
long s = (long)Math.Ceiling(seconds);
if (s >= 3600) return $"{s / 3600}h {s % 3600 / 60:00}m";
if (s >= 60) return $"{s / 60}m";
return $"{s}s";
}
/// <summary>
/// Evaluates one essence: role, every failing gate (the first is the headline), the ready time,
/// growth and boosters. <paramref name="nowUnix"/> is unix seconds.
/// </summary>
public static BreedEssence Evaluate(BreedEssenceFacts f, IltBreedingRules r, double nowUnix)
{
string desc = f.LongDesc ?? string.Empty;
bool male = f.MaleOverride ?? DeriveIsMale(f.Id);
int tier = TierOf(f.Wcid, f.UseLevel);
int bond = Math.Max(1, f.Bond);
bool shiny = desc.Contains("(shiny - cannot breed)", StringComparison.OrdinalIgnoreCase);
bool bred = f.MaturityKills >= 0;
bool juvenile = f.JuvenileFlag || desc.Contains("cannot breed yet", StringComparison.OrdinalIgnoreCase);
// Stud charges refill lazily on the server: full again once the refill time has passed.
int max = Math.Max(0, r.GetInt(IltBreedingRules.MaleCharges));
int charges = f.MaleCharges < 0 ? max : Math.Min(f.MaleCharges, max);
double refillAt = 0;
double refillH = r.Get(IltBreedingRules.MaleRefillHours);
if (male && f.MaleRefreshUnix > 0 && refillH > 0)
{
refillAt = f.MaleRefreshUnix + refillH * 3600.0;
if (nowUnix >= refillAt) { charges = max; refillAt = 0; }
}
if (male && charges >= max) refillAt = 0;
// Growth (bred essences only): stage from credited kills, as ACE PetDevice_Maturity.
int required = Math.Max(1, r.GetInt(IltBreedingRules.MaturityKills));
int stages = Math.Max(1, r.GetInt(IltBreedingRules.MaturityStages));
int kills = Math.Max(0, f.MaturityKills);
int perStage = Math.Max(1, (int)Math.Ceiling(required / (double)stages));
int stage = juvenile ? Math.Min(stages, kills / perStage + 1) : stages + 1;
int toNext = juvenile ? Math.Max(0, Math.Min(required, stage * perStage) - kills) : 0;
string stageName = juvenile ? r.StageName(stage) : bred ? "Adult" : string.Empty;
if (juvenile && IltBreedingRules.TryParseGrowth(desc, out string seenName, out int seenStage, out _, out int seenNext, out _, out int seenAdult))
{
// The appraisal line is the server's own math: prefer it when it is there.
stage = seenStage;
stageName = seenName;
toNext = seenNext;
kills = Math.Max(kills, required - seenAdult);
}
// Every failing gate, in the order the server checks them.
var problems = new List<string>();
BreedGate gate = BreedGate.Ready;
void Fail(BreedGate g, string text)
{
if (gate == BreedGate.Ready) gate = g;
problems.Add(text);
}
double readyAt = 0;
if (!f.HasId) Fail(BreedGate.NeedsId, "not appraised yet");
if (f.Neutered) Fail(BreedGate.Neutered, "neutered (permanent)");
if (shiny) Fail(BreedGate.Shiny, "shiny essences can't breed");
if (juvenile) Fail(BreedGate.Growing, $"still growing: {stageName} ({Math.Max(0, required - kills)} kills to Adult)");
int minTier = r.GetInt(IltBreedingRules.MinTier);
if (tier > 0 && tier < minTier) Fail(BreedGate.LowTier, $"tier {tier} (needs {minTier}+)");
int minBond = r.GetInt(IltBreedingRules.MinBond);
if (f.HasId && bond < minBond) Fail(BreedGate.LowBond, $"bond {bond}/{minBond}");
if (male && charges <= 0)
{
Fail(BreedGate.NoCharges, refillAt > 0 ? $"no charges (refill in {Duration(refillAt - nowUnix)})" : "no charges left");
readyAt = Math.Max(readyAt, refillAt);
}
if (!male && f.NextBreedUnix > nowUnix)
{
Fail(BreedGate.Resting, $"resting ({Duration(f.NextBreedUnix - nowUnix)})");
readyAt = Math.Max(readyAt, f.NextBreedUnix);
}
string status = gate switch
{
BreedGate.Ready => male ? $"Ready ({charges}/{max})" : "Ready",
BreedGate.Resting => "Rest " + Duration(f.NextBreedUnix - nowUnix),
BreedGate.NoCharges => refillAt > 0 ? "0/" + max + " refill " + Duration(refillAt - nowUnix) : "0/" + max,
BreedGate.Growing => $"{stageName} {Math.Min(stage, stages)}/{stages}",
BreedGate.Neutered => "Neutered",
BreedGate.Shiny => "Shiny",
BreedGate.LowBond => $"Bond {bond}/{minBond}",
BreedGate.LowTier => $"Tier {tier}",
_ => "ID needed",
};
bool draught = f.MaturityXpMult > 1.0001;
var boosters = new List<string>(4);
if (f.Incense > 0) boosters.Add(IltBreedingSupplies.IncenseName(f.Incense));
if (f.Catalyst) boosters.Add("Chromatic Catalyst");
if (f.Offering) boosters.Add("Offering of Subjugation");
if (draught) boosters.Add("Nurturing Draught x" + f.MaturityXpMult.ToString("0.#", CultureInfo.InvariantCulture));
return new BreedEssence(
f.Id, f.Name, f.Wcid, f.HasId, tier, bond, male, gate, status, problems, readyAt,
male ? charges : 0, male ? max : 0, male ? refillAt : 0,
bred, juvenile, juvenile ? stage : 0, stages, stageName, kills, required, toNext,
Math.Max(0, f.Incense), f.Catalyst, f.Offering, draught, boosters,
Math.Max(0, f.MutDamage), Math.Max(0, f.MutDamageResist), Math.Max(0, f.MutCrit), Math.Max(0, f.MutVitality),
Math.Max(0, f.MutPotency), shiny, bred && !f.Attuned && desc.Contains("Bond: Unbound", StringComparison.OrdinalIgnoreCase),
Math.Max(0, f.PotencyStored));
}
}
/// <summary>What a stud + dam pairing would do: the gates both must pass, and the baby's odds.</summary>
internal sealed record BreedPairPlan(bool CanBreed, IReadOnlyList<string> Blockers, double Incense, double ChanceBest, double ChanceWorst,
double PotencyChance, int InheritMin, int InheritMax, IReadOnlyList<string> Notes);
internal static class IltBreedingPlanner
{
/// <summary>
/// Plans one pairing. Each stat line comes from one parent, so the baby inherits between the
/// sum of the lower lines and the sum of the higher lines; more inherited mutations lower the
/// stat mutation chance (the decay), so the best case is the fewest.
/// </summary>
public static BreedPairPlan Plan(BreedEssence stud, BreedEssence dam, IltBreedingRules r)
{
var blockers = new List<string>();
if (!stud.Male) blockers.Add($"{stud.Name} is female: the stud must be male.");
if (dam.Male) blockers.Add($"{dam.Name} is male: the dam must be female.");
if (stud.Id == dam.Id) blockers.Add("Pick two different essences.");
foreach (string p in stud.Problems) blockers.Add($"{stud.Name}: {p}");
foreach (string p in dam.Problems) blockers.Add($"{dam.Name}: {p}");
int lo = Math.Min(stud.MutD, dam.MutD) + Math.Min(stud.MutDR, dam.MutDR) + Math.Min(stud.MutC, dam.MutC) + Math.Min(stud.MutV, dam.MutV);
int hi = Math.Max(stud.MutD, dam.MutD) + Math.Max(stud.MutDR, dam.MutDR) + Math.Max(stud.MutC, dam.MutC) + Math.Max(stud.MutV, dam.MutV);
double incense = r.CombinedIncense(stud.Incense, dam.Incense);
var notes = new List<string>
{
"The baby goes to the dam's owner: they need a free main-pack slot and burden room.",
$"Both pets in the same room of the breeding area ({r.RoomText()}); both owners *dance* within {r.Get(IltBreedingRules.DanceWindow):0.#}s.",
};
if (stud.Catalyst || dam.Catalyst) notes.Add("Chromatic Catalyst: the baby rolls a fresh colour.");
if (r.Get(IltBreedingRules.GuardianEnabled) >= 0.5)
notes.Add(stud.Offering || dam.Offering
? "Offering of Subjugation applied: the mating guardian comes weakened."
: $"A mating guardian rises: kill it within {r.Get(IltBreedingRules.GuardianSeconds):0}s for an Awakened Blessing mutation.");
if (incense > 0) notes.Add($"Incense +{incense * 100:0.#}% is used up by this breed.");
return new BreedPairPlan(blockers.Count == 0, blockers, incense,
r.StatMutationChance(lo, incense), r.StatMutationChance(hi, incense),
Math.Clamp(r.Get(IltBreedingRules.PotencyMutation), 0, 1), lo, hi, notes);
}
}

View file

@ -0,0 +1,445 @@
// IltBreedingRules.cs - Infinite Leaftide's pet breeding rules as RynthILT knows them.
//
// ACECustom's breeding (Source/ACE.Server/WorldObjects/PetDevice_Breeding.cs, docs/PET_BREEDING_*.md)
// is driven by ServerConfig values the client is never sent. Each rule here therefore has three
// possible sources, best last:
// * ACE default - the ServerConfig default in ACECustom;
// * ILT profile - what Infinite Leaftide runs (deploy/PROD_DEPLOY_PLAN.md: decay 0.1, the
// mating guardian on, pet bond on, the Seedy Motel room);
// * seen on server - read back from this server's own text: the appraisal breeding block
// ("Sex: Male (9/10 breeding charges today) - refills in 3h 10m", "Growth: ..."),
// "@breed-debug" ("Allowed Target: whole landblock 0x106, Variant=2"), and
// breeding chat ("spent a breeding charge: 9/10 left today", "They have 90s ...").
// A value seen on the server is saved with the character (IltPetState.Breeding) and wins from then on.
//
// Pure: no host calls, so RynthILT.Tests checks every parser offline.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>Where a breeding rule's value came from (later = more trusted).</summary>
internal enum BreedRuleSource { AceDefault = 0, IltProfile = 1, Server = 2 }
/// <summary>One rule: stable key, label, unit, the ACE default and the ILT profile value (null = same as ACE).</summary>
internal sealed record BreedRuleDef(string Key, string Label, string Unit, double AceDefault, double? IltProfile, string Help);
/// <summary>A rule's effective value and where it came from.</summary>
internal readonly record struct BreedRuleValue(BreedRuleDef Def, double Value, BreedRuleSource Source, DateTime SeenUtc);
/// <summary>A value this server showed, saved with the character.</summary>
public sealed class IltLearnedRule
{
public string Key = string.Empty;
public double Value;
public DateTime SeenUtc;
}
/// <summary>One breeding event from chat (ritual, birth, growth, ...), newest last.</summary>
public sealed class IltBreedingEvent
{
public DateTime Utc;
/// <summary>ritual, charge, birth, mutation, guardian, growth, adult, imprint, dance, debug.</summary>
public string Kind = string.Empty;
public string Text = string.Empty;
}
/// <summary>The breeding tracker's saved part (IltPetState.Breeding).</summary>
public sealed class IltBreedingState
{
/// <summary>Rules read back from this server (see IltBreedingRules).</summary>
public List<IltLearnedRule> Rules = new();
/// <summary>Growth stage names this server uses, by stage (index 0 = stage 1); "" = not seen yet.</summary>
public List<string> StageNames = new();
/// <summary>Recent breeding events (capped at IltBreedingRules.MaxEvents).</summary>
public List<IltBreedingEvent> Log = new();
/// <summary>The last "@breed-debug" reply's lines and when it came.</summary>
public List<string> LastDebug = new();
public DateTime LastDebugUtc;
}
/// <summary>What one "@breed-debug" reply said.</summary>
internal sealed record BreedDebugInfo(bool? Enabled, string Location, uint AllowedLandblock, int AllowedVariant, string AllowedKind,
bool? LocationOk, string ActivePet, string PetSex, int Partners);
internal sealed class IltBreedingRules
{
// ── Rule keys ───────────────────────────────────────────────────────────
public const string Landblock = "landblock";
public const string Variant = "variant";
public const string DanceWindow = "dance_window_s";
public const string MinTier = "min_tier";
public const string MinBond = "min_bond";
public const string MaleCharges = "male_charges";
public const string MaleRefillHours = "male_refill_h";
public const string FemaleRestHours = "female_rest_h";
public const string BaseMutation = "base_mutation";
public const string MutationDecay = "mutation_decay";
public const string MutationFloor = "mutation_floor";
public const string PotencyMutation = "potency_mutation";
public const string IncenseCap = "incense_cap";
public const string Inheritance = "inheritance";
public const string GuardianEnabled = "guardian_enabled";
public const string GuardianSeconds = "guardian_s";
public const string MaturityKills = "maturity_kills";
public const string MaturityStages = "maturity_stages";
public const string MaturityShare = "maturity_share";
/// <summary>Breeding events kept with the character.</summary>
public const int MaxEvents = 60;
/// <summary>ACECustom's default growth stage names (pet_maturity_stage_names).</summary>
public static readonly string[] DefaultStageNames = { "Newborn", "Whelp", "Juvenile", "Adolescent", "Young Adult" };
/// <summary>Every rule shown, in display order. Values copied from ACECustom ServerConfig and the ILT deploy plan.</summary>
public static readonly BreedRuleDef[] Defs =
{
new(Landblock, "Breeding room landblock", "hex", 0x0106, null,
"pet_breeding_allowed_landblock: the Seedy Motel (Ruggan's Annex, portal by Prof. Ruggan in Lin 54.7S 73.5E)."),
new(Variant, "Breeding room variant", "", 2, null, "pet_breeding_allowed_variant: the landblock variant the room is in."),
new(DanceWindow, "Dance window", "s", 5, null, "Both owners must *dance* (or @dance) within this many seconds."),
new(MinTier, "Minimum essence tier", "", 100, null, "Both parents must be at least this tier (50, 80, 100, ... 300)."),
new(MinBond, "Minimum bond", "", 100, null, "Both parents need this bond level (bond grows from kills; pet_bond must be on)."),
new(MaleCharges, "Stud charges", "", 10, null, "pet_breeding_male_max_charges: breeds a male can sire per refill."),
new(MaleRefillHours, "Stud refill", "h", 24, null, "pet_breeding_male_charge_reset_hours: charges refill this long after the last refill."),
new(FemaleRestHours, "Dam rest", "h", 4, null, "A female rests this long after each breed before she can breed again."),
new(BaseMutation, "Stat mutation chance", "%", 0.05, null, "pet_breeding_mutation_chance: the base chance of a stat mutation."),
new(MutationDecay, "Mutation decay", "", 0.0, 0.1,
"pet_breeding_mutation_decay: each stat mutation the baby inherits divides the chance by (1 + decay x mutations)."),
new(MutationFloor, "Mutation floor", "%", 0.02, null, "The stat mutation chance never drops below this."),
new(PotencyMutation, "Potency mutation chance", "%", 0.03, null, "An independent roll for a potency mutation."),
new(IncenseCap, "Incense cap", "%", 0.50, null, "Both parents' incense together adds at most this much."),
new(Inheritance, "Dominant line weight", "%", 0.55, null, "Each stat line comes from one parent, 55 / 45."),
new(GuardianEnabled, "Mating guardian", "on/off", 0, 1,
"pet_breeding_guardian_enabled: a spirit rises after the ritual; killing it in time grants an Awakened Blessing mutation."),
new(GuardianSeconds, "Guardian timer", "s", 90, null, "How long the two parents have to kill the guardian."),
new(MaturityKills, "Kills to adulthood", "", 300, null, "pet_maturity_kills_required: a bred baby grows up with this many credited kills."),
new(MaturityStages, "Growth stages", "", 5, null, "pet_maturity_stages: the growth stages before Adult."),
new(MaturityShare, "Kill credit share", "%", 0.10, null,
"A kill counts when the pet dealt this share of the victim's health and the victim's level is at least the essence tier."),
};
private static readonly Dictionary<string, BreedRuleDef> DefByKey = BuildIndex();
private static Dictionary<string, BreedRuleDef> BuildIndex()
{
var d = new Dictionary<string, BreedRuleDef>(StringComparer.Ordinal);
foreach (BreedRuleDef def in Defs) d[def.Key] = def;
return d;
}
private readonly IltBreedingState _state;
/// <param name="state">The saved breeding state; learned values are read from and written to it.</param>
public IltBreedingRules(IltBreedingState state) => _state = state;
/// <summary>The saved state these rules read and update.</summary>
public IltBreedingState State => _state;
/// <summary>A copy that never changes (the render thread reads it while the pump learns).</summary>
public IltBreedingRules Frozen()
{
var copy = new IltBreedingState { StageNames = new List<string>(_state.StageNames) };
foreach (IltLearnedRule l in _state.Rules)
copy.Rules.Add(new IltLearnedRule { Key = l.Key, Value = l.Value, SeenUtc = l.SeenUtc });
return new IltBreedingRules(copy);
}
/// <summary>The effective value of rule <paramref name="key"/> (0 for an unknown key).</summary>
public double Get(string key) => Value(key).Value;
/// <summary>A whole-number rule (charges, kills, tiers).</summary>
public int GetInt(string key) => (int)Math.Round(Get(key));
/// <summary>The effective value and its source.</summary>
public BreedRuleValue Value(string key)
{
if (!DefByKey.TryGetValue(key, out BreedRuleDef? def))
return new BreedRuleValue(new BreedRuleDef(key, key, "", 0, null, ""), 0, BreedRuleSource.AceDefault, default);
foreach (IltLearnedRule l in _state.Rules)
if (l.Key == key) return new BreedRuleValue(def, l.Value, BreedRuleSource.Server, l.SeenUtc);
return def.IltProfile.HasValue
? new BreedRuleValue(def, def.IltProfile.Value, BreedRuleSource.IltProfile, default)
: new BreedRuleValue(def, def.AceDefault, BreedRuleSource.AceDefault, default);
}
/// <summary>Every rule's effective value, in display order.</summary>
public List<BreedRuleValue> All()
{
var list = new List<BreedRuleValue>(Defs.Length);
foreach (BreedRuleDef d in Defs) list.Add(Value(d.Key));
return list;
}
/// <summary>Records a value the server showed. True when it changed what RynthILT knew.</summary>
public bool Learn(string key, double value, DateTime utc)
{
if (!DefByKey.ContainsKey(key) || double.IsNaN(value) || double.IsInfinity(value)) return false;
foreach (IltLearnedRule l in _state.Rules)
{
if (l.Key != key) continue;
bool changed = Math.Abs(l.Value - value) > 1e-9;
l.Value = value;
l.SeenUtc = utc;
return changed;
}
_state.Rules.Add(new IltLearnedRule { Key = key, Value = value, SeenUtc = utc });
return true;
}
/// <summary>Applies every (key, value) an observer returned. True when anything changed.</summary>
public bool LearnAll(IEnumerable<(string Key, double Value)> seen, DateTime utc)
{
bool changed = false;
foreach ((string k, double v) in seen) changed |= Learn(k, v, utc);
return changed;
}
/// <summary>Records a growth stage's name (1-based) as the server spelled it.</summary>
public bool LearnStageName(int stage, string name)
{
name = (name ?? string.Empty).Trim();
if (stage < 1 || stage > 50 || name.Length == 0 || name.Length > 40) return false;
while (_state.StageNames.Count < stage) _state.StageNames.Add(string.Empty);
if (_state.StageNames[stage - 1] == name) return false;
_state.StageNames[stage - 1] = name;
return true;
}
/// <summary>The name of growth stage <paramref name="stage"/> (1-based): seen on the server, else ACE's default, else "Stage N".</summary>
public string StageName(int stage)
{
if (stage >= 1 && stage <= _state.StageNames.Count && _state.StageNames[stage - 1].Length > 0)
return _state.StageNames[stage - 1];
if (stage >= 1 && stage <= DefaultStageNames.Length && GetInt(MaturityStages) == DefaultStageNames.Length)
return DefaultStageNames[stage - 1];
return "Stage " + stage.ToString(CultureInfo.InvariantCulture);
}
/// <summary>Appends an event, dropping the oldest past <see cref="MaxEvents"/>.</summary>
public void AddEvent(string kind, string text, DateTime utc)
{
_state.Log.Add(new IltBreedingEvent { Utc = utc, Kind = kind, Text = text });
if (_state.Log.Count > MaxEvents) _state.Log.RemoveRange(0, _state.Log.Count - MaxEvents);
}
// ── Mutation odds (ACE PetDevice_Breeding) ──────────────────────────────
/// <summary>
/// The chance of a stat mutation for a baby that inherits <paramref name="babyStatMutations"/>
/// stat mutations, with <paramref name="incense"/> from both parents (already capped):
/// clamp(max(floor, (base + incense) / (1 + decay x mutations)), 0, 1).
/// </summary>
public double StatMutationChance(int babyStatMutations, double incense)
{
double decay = Math.Max(0, Get(MutationDecay));
double raw = (Get(BaseMutation) + Math.Max(0, incense)) / (1.0 + decay * Math.Max(0, babyStatMutations));
return Math.Clamp(Math.Max(Get(MutationFloor), raw), 0.0, 1.0);
}
/// <summary>Both parents' incense together, capped at the incense cap.</summary>
public double CombinedIncense(double a, double b) => Math.Clamp(Math.Max(0, a) + Math.Max(0, b), 0.0, Math.Max(0, Get(IncenseCap)));
// ── Observers: what the server's own text says about its rules ──────────
private const RegexOptions Rx = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase;
private static readonly Regex MaleLine = new(@"Sex:\s*Male\s*\((\d+)\s*/\s*(\d+) breeding charges today\)(?:\s*-\s*refills in (?:(\d+)h\s*)?(?:(\d+)m)?)?", Rx);
private static readonly Regex GrowthLine = new(@"Growth:\s*(.+?)\s+(\d+)\s*/\s*(\d+)\s*-\s*(\d+) kills to (.+?)(?:,\s*(\d+) to Adult)?\s*$", Rx | RegexOptions.Multiline);
private static readonly Regex ChargeSpent = new(@"spent a breeding charge:\s*(\d+)\s*/\s*(\d+) left today", Rx);
private static readonly Regex GuardianRise = new(@"They have (\d+)s to bring it down together", Rx);
private static readonly Regex GrownInto = new(@"has grown into an? (.+?)!.*\((\d+)\s*/\s*(\d+)\)", Rx);
private static readonly Regex DanceWindowLine = new(@"\*dance\* within (\d+(?:\.\d+)?) seconds", Rx);
private static readonly Regex DebugEnabled = new(@"Breeding System Enabled:\s*(True|False)", Rx);
private static readonly Regex DebugLocation = new(@"Your Location:\s*(.+)$", Rx);
private static readonly Regex DebugAllowed = new(@"Allowed Target:\s*(anywhere|whole landblock|exact cell)\s*0x([0-9A-F]+),\s*Variant=(-?\d+)\s*=>\s*Location Match:\s*(VALID|INVALID)", Rx);
private static readonly Regex DebugPet = new(@"Your Active Pet:\s*(.+)$", Rx);
private static readonly Regex DebugSex = new(@"^\s*Sex:\s*(.+)$", Rx);
private static readonly Regex DebugPartners = new(@"(?:Eligible breeding partners nearby|Valid Partner Candidates within 30m):\s*(\d+)", Rx);
/// <summary>
/// What an essence's appraisal text says: the stud's charge max and refill window (from the
/// "refills in" countdown against the essence's last refill time), and the growth stage count.
/// </summary>
/// <param name="longDesc">The appraisal LongDesc (string 16).</param>
/// <param name="maleRefreshUnix">The essence's PetMaleChargesRefreshTime (0 = not sent).</param>
/// <param name="nowUnix">Now, unix seconds.</param>
public static List<(string Key, double Value)> FromAppraisal(string longDesc, double maleRefreshUnix, double nowUnix)
{
var seen = new List<(string, double)>();
if (string.IsNullOrEmpty(longDesc)) return seen;
Match m = MaleLine.Match(longDesc);
if (m.Success)
{
if (int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int max) && max > 0 && max < 1000)
seen.Add((MaleCharges, max));
if ((m.Groups[3].Success || m.Groups[4].Success) && maleRefreshUnix > 0)
{
int h = m.Groups[3].Success ? int.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture) : 0;
int min = m.Groups[4].Success ? int.Parse(m.Groups[4].Value, CultureInfo.InvariantCulture) : 0;
double refillAt = nowUnix + h * 3600.0 + min * 60.0;
double hours = Math.Round((refillAt - maleRefreshUnix) / 3600.0);
// The countdown is minute-rounded; only a whole-hour window that makes sense is taken.
if (hours >= 1 && hours <= 24 * 14) seen.Add((MaleRefillHours, hours));
}
}
Match g = GrowthLine.Match(longDesc);
if (g.Success && int.TryParse(g.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int stages) && stages >= 1 && stages <= 50)
seen.Add((MaturityStages, stages));
return seen;
}
/// <summary>
/// The growth line of an appraisal: current stage name, stage, stages, kills to the next stage
/// and to adulthood (-1 when the line has no "to Adult" part, i.e. the last stage).
/// </summary>
public static bool TryParseGrowth(string longDesc, out string stageName, out int stage, out int stages, out int toNext, out string nextName, out int toAdult)
{
stageName = nextName = string.Empty;
stage = stages = toNext = toAdult = 0;
if (string.IsNullOrEmpty(longDesc)) return false;
Match g = GrowthLine.Match(longDesc);
if (!g.Success) return false;
stageName = g.Groups[1].Value.Trim();
int.TryParse(g.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stage);
int.TryParse(g.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stages);
int.TryParse(g.Groups[4].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out toNext);
nextName = g.Groups[5].Value.Trim();
if (g.Groups[6].Success) int.TryParse(g.Groups[6].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out toAdult);
else { toAdult = toNext; nextName = "Adult"; }
return true;
}
/// <summary>What one chat line says about the rules (a line can say nothing).</summary>
public static List<(string Key, double Value)> FromChat(string line)
{
var seen = new List<(string, double)>();
if (string.IsNullOrEmpty(line)) return seen;
Match m = ChargeSpent.Match(line);
if (m.Success && int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int max) && max > 0 && max < 1000)
seen.Add((MaleCharges, max));
m = GuardianRise.Match(line);
if (m.Success)
{
seen.Add((GuardianEnabled, 1));
if (int.TryParse(m.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int s) && s > 0 && s < 3600)
seen.Add((GuardianSeconds, s));
}
else if (line.Contains("The union stirs something", StringComparison.OrdinalIgnoreCase))
seen.Add((GuardianEnabled, 1));
m = GrownInto.Match(line);
if (m.Success && int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int stages) && stages >= 1 && stages <= 50)
seen.Add((MaturityStages, stages));
m = DanceWindowLine.Match(line);
if (m.Success && double.TryParse(m.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out double w) && w > 0 && w < 600)
seen.Add((DanceWindow, w));
foreach (string part in line.Split('\n'))
{
m = DebugAllowed.Match(part);
if (!m.Success) continue;
if (uint.TryParse(m.Groups[2].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint lb))
seen.Add((Landblock, lb));
if (int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v))
seen.Add((Variant, v));
}
return seen;
}
/// <summary>The stage name a "has grown into a Whelp! ... (2/5)" line gives, with its stage number; false for any other line.</summary>
public static bool TryParseGrownInto(string line, out int stage, out string name)
{
stage = 0;
name = string.Empty;
Match m = GrownInto.Match(line ?? string.Empty);
if (!m.Success || !int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stage)) return false;
name = m.Groups[1].Value.Trim();
return name.Length > 0;
}
/// <summary>True for any line of an "@breed-debug" reply (one multi-line message, or its lines one by one).</summary>
public static bool IsDebugLine(string text)
{
if (string.IsNullOrEmpty(text)) return false;
return text.Contains("PET BREEDING DIAGNOSTICS", StringComparison.OrdinalIgnoreCase)
|| DebugEnabled.IsMatch(text) || DebugLocation.IsMatch(text) || DebugAllowed.IsMatch(text)
|| DebugPet.IsMatch(text) || DebugPartners.IsMatch(text)
|| text.TrimStart().StartsWith("Sex:", StringComparison.OrdinalIgnoreCase)
|| text.Contains("Ensure your partner has their pet summoned", StringComparison.OrdinalIgnoreCase)
|| IsDebugEnd(text);
}
/// <summary>The reply's closing rule of '=' (alone, or ending the whole message).</summary>
public static bool IsDebugEnd(string text)
=> !string.IsNullOrEmpty(text) && text.TrimEnd().EndsWith("================================", StringComparison.Ordinal);
/// <summary>Parses an "@breed-debug" reply (any mix of whole messages and single lines).</summary>
public static BreedDebugInfo ParseDebug(IEnumerable<string> lines)
{
bool? enabled = null, ok = null;
string location = string.Empty, kind = string.Empty, pet = string.Empty, sex = string.Empty;
uint lb = 0;
int variant = -1, partners = -1;
foreach (string text in lines)
{
foreach (string raw in (text ?? string.Empty).Split('\n'))
{
string l = raw.TrimEnd('\r');
Match m;
if ((m = DebugEnabled.Match(l)).Success) enabled = m.Groups[1].Value.Equals("True", StringComparison.OrdinalIgnoreCase);
else if ((m = DebugAllowed.Match(l)).Success)
{
kind = m.Groups[1].Value.ToLowerInvariant();
uint.TryParse(m.Groups[2].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lb);
int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out variant);
ok = m.Groups[4].Value.Equals("VALID", StringComparison.OrdinalIgnoreCase);
}
else if ((m = DebugLocation.Match(l)).Success) location = m.Groups[1].Value.Trim();
else if ((m = DebugPet.Match(l)).Success) pet = m.Groups[1].Value.Trim();
else if ((m = DebugPartners.Match(l)).Success) int.TryParse(m.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out partners);
else if ((m = DebugSex.Match(l)).Success) sex = m.Groups[1].Value.Trim();
}
}
return new BreedDebugInfo(enabled, location, lb, variant, kind, ok, pet, sex, partners);
}
/// <summary>"0x0106 variant 2" (or "anywhere") for the rules list.</summary>
public string RoomText()
{
uint lb = (uint)Math.Max(0, Get(Landblock));
int variant = GetInt(Variant);
if (lb == 0) return "anywhere";
string place = lb > 0xFFFF ? "cell 0x" + lb.ToString("X8", CultureInfo.InvariantCulture) : "landblock 0x" + lb.ToString("X4", CultureInfo.InvariantCulture);
return variant >= 0 ? place + " variant " + variant.ToString(CultureInfo.InvariantCulture) : place;
}
/// <summary>A rule value for display: "5%", "24h", "0x0106", "on", "10".</summary>
public static string Format(BreedRuleValue v)
{
switch (v.Def.Unit)
{
case "%": return (v.Value * 100.0).ToString("0.##", CultureInfo.InvariantCulture) + "%";
case "h": return v.Value.ToString("0.#", CultureInfo.InvariantCulture) + "h";
case "s": return v.Value.ToString("0.#", CultureInfo.InvariantCulture) + "s";
case "hex": return "0x" + ((uint)Math.Max(0, v.Value)).ToString("X4", CultureInfo.InvariantCulture);
case "on/off": return v.Value >= 0.5 ? "on" : "off";
default: return v.Value.ToString("0.##", CultureInfo.InvariantCulture);
}
}
/// <summary>"ACE default", "ILT profile" or "seen on server".</summary>
public static string SourceText(BreedRuleSource s) => s switch
{
BreedRuleSource.Server => "seen on server",
BreedRuleSource.IltProfile => "ILT profile",
_ => "ACE default",
};
}

View file

@ -0,0 +1,112 @@
// IltBreedingSupplies.cs - Ivo's breeding supplies (ACECustom, Seedy Motel vendor) and when each can
// be used on an essence.
//
// WCIDs, prices and refusals copied from ACECustom (Player_Use.cs HandleActionUseOnTarget, the
// PetDevice.BreedingMath incense constants, docs/PET_BREEDING_PLAYER_GUIDE.md). RynthILT applies
// only the breeding boosters (incense, Nurturing Draught, Chromatic Catalyst, Offering of
// Subjugation), and only after the player confirms; the Neutering Kit is permanent and the kits,
// serum and tinctures are cosmetic, so those are counted, never used from here.
//
// Pure: RynthILT.Tests checks the refusals offline.
using System;
using System.Globalization;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One supply: key, WCID, name, what it does, Ivo's price, and whether the tracker can apply it.</summary>
internal sealed record BreedSupplyDef(string Key, uint Wcid, string Name, string Effect, long Price, bool Apply);
internal static class IltBreedingSupplies
{
public const string LesserIncense = "incense1";
public const string RefinedIncense = "incense2";
public const string ExquisiteIncense = "incense3";
public const string Draught = "draught";
public const string Catalyst = "catalyst";
public const string Offering = "offering";
public const string NeuteringKit = "neuter";
public const string TailoringKit = "tailor";
public const string FilledTailoringKit = "tailor_filled";
public const string Serum = "serum";
public const string Solidifying = "solidify";
public const string Fading = "fade";
/// <summary>Every supply, boosters first.</summary>
public static readonly BreedSupplyDef[] All =
{
new(LesserIncense, 78780250, "Lesser Courtship Incense", "+2.5% stat mutation chance on the next breed.", 1_250_000, true),
new(RefinedIncense, 78780251, "Refined Courtship Incense", "+5% stat mutation chance on the next breed.", 2_500_000, true),
new(ExquisiteIncense, 78780252, "Exquisite Courtship Incense", "+10% stat mutation chance on the next breed.", 5_000_000, true),
new(Draught, 78780253, "Nurturing Draught", "A juvenile earns 2x maturity kill credit until adulthood.", 2_500_000, true),
new(Catalyst, 78780254, "Chromatic Catalyst", "The next baby rolls a fresh colour.", 2_500_000, true),
new(Offering, 78780255, "Offering of Subjugation", "The next mating guardian comes weakened.", 2_500_000, true),
new(NeuteringKit, 78780258, "Neutering Kit", "Permanently stops an essence from breeding.", 2_500_000, false),
new(TailoringKit, 78780259, "Tailoring Kit", "Extracts an essence's appearance.", 125_000_000, false),
new(FilledTailoringKit, 78780260, "Filled Tailoring Kit", "Applies an extracted appearance.", 0, false),
new(Serum, 78780257, "Mutagenic Serum", "Re-rolls an essence's colour.", 25_000_000, false),
new(Solidifying, 78780262, "Solidifying Tincture", "Makes the summoned pet less translucent.", 12_500_000, false),
new(Fading, 78780263, "Fading Tincture", "Makes the summoned pet more translucent.", 12_500_000, false),
};
/// <summary>The supply with this key, or null.</summary>
public static BreedSupplyDef? Find(string key) => Array.Find(All, s => s.Key == key);
/// <summary>The incense bonus a supply gives (0 for anything else).</summary>
public static double IncenseBonus(string key) => key switch
{
LesserIncense => 0.025,
RefinedIncense => 0.05,
ExquisiteIncense => 0.10,
_ => 0,
};
/// <summary>"Refined incense +5%" for an applied bonus.</summary>
public static string IncenseName(double bonus)
{
string grade = bonus >= 0.0999 ? "Exquisite" : bonus >= 0.0499 ? "Refined" : "Lesser";
return $"{grade} incense +{(bonus * 100).ToString("0.#", CultureInfo.InvariantCulture)}%";
}
/// <summary>
/// Why the server would refuse <paramref name="s"/> on <paramref name="e"/> (the server's own
/// checks, so nothing is spent on a refusal), or null when it would take it.
/// </summary>
public static string? RefuseReason(BreedSupplyDef s, BreedEssence e, IltBreedingRules r)
{
if (!s.Apply) return "Not applied from here.";
double incense = IncenseBonus(s.Key);
if (incense > 0)
{
if (e.Gate == BreedGate.Neutered) return "A neutered essence can't take incense.";
if (e.Incense >= incense - 1e-6) return $"Already primed with equal or stronger incense (+{e.Incense * 100:0.#}%).";
return null;
}
return s.Key switch
{
Draught when !e.Juvenile => "Only a juvenile (still growing) can take a Nurturing Draught.",
Draught when e.Draught => "Already under a Nurturing Draught.",
Catalyst when e.Catalyst => "Already infused with a Chromatic Catalyst.",
Offering when r.Get(IltBreedingRules.GuardianEnabled) < 0.5 => "Mating guardians are off on this server.",
Offering when e.Offering => "Already under an Offering of Subjugation.",
_ => null,
};
}
/// <summary>A warning to show in the confirmation (a weaker incense being replaced), or "".</summary>
public static string Warning(BreedSupplyDef s, BreedEssence e)
{
double incense = IncenseBonus(s.Key);
if (incense > 0 && e.Incense > 0 && e.Incense < incense)
return $" It replaces the +{e.Incense * 100:0.#}% incense already on it (that one is lost).";
return string.Empty;
}
/// <summary>"1.25M", "125M", "-" for a price.</summary>
public static string PriceText(long price)
{
if (price <= 0) return "-";
if (price >= 1_000_000) return (price / 1_000_000.0).ToString("0.##", CultureInfo.InvariantCulture) + "M";
if (price >= 1_000) return (price / 1_000.0).ToString("0.#", CultureInfo.InvariantCulture) + "k";
return price.ToString(CultureInfo.InvariantCulture);
}
}

View file

@ -0,0 +1,256 @@
// IltBuffKeepers.cs — Rune-of-Dispel auto-dispel and Surging Strength keeper (Gear tab).
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Both read the player's enchantment list once a second (one shared read).
// Dispel: classifies active spells by NAME (RynthAi's SpellDatabase, through RynthAi.Hub; it has no debuff flag):
// 1. Mire Foot (3051 / "mire"+"foot") → never (dispelling it is pointless)
// 2. user include list → dispel
// 3. beneficial pattern → keep
// 4. user exclude list → keep
// 5. known-harmful exact name or pattern → dispel
// and uses a Rune of Dispel (WCID 30133). Cooldown, verify after 2 s, up to 3 retries.
// Surging Strength: uses the Empowered Volcanic Ember when the buff is missing.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltBuffKeepers : IIltFeature
{
private const int SpellMireFoot = 3051;
private const int MaxEnch = 256;
private static readonly HashSet<string> HarmfulExact = BuildHarmfulExact();
private static readonly Regex HarmfulPattern = new(
@"\b(vulnerability|imperil|weakness|slowness|bane|exhaustion|mana burn|fester|curse of|blight of|burden of)\b",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex BeneficialPattern = new(
@"\b(invulnerability|invulnerable|protection|ward|armor|blessing|strength|coordination|endurance|quickness|focus|willpower|"
+ @"regeneration|mana renewal|stamina renewal|health renewal|arcanum|cantrap|enhancement|augmentation|weave of|shroud of|"
+ @"mantle of|cloak of|veil of|master's blessing|society|fellowship|loyalty|devotion)\b",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static HashSet<string> BuildHarmfulExact()
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string s in new[] { "weakness other", "vulnerability other", "imperil other", "slowness other",
"bane other", "exhaustion other", "mana burn other", "fester other" })
{
set.Add(s);
set.Add("incantation of " + s);
}
foreach (string s in new[] { "belly of lead", "gelidite's gift", "inferno's gift", "senescence", "archer's gift",
"swordsman's gift", "leaden feet", "heart of ice", "burning soul", "withering" })
set.Add(s);
return set;
}
private readonly IltHubContext _ctx;
private readonly uint[] _ids = new uint[MaxEnch];
private readonly double[] _exp = new double[MaxEnch];
private long _lastRead;
// Dispel state
private long _dispelCooldownUntil;
private long _verifyAt;
private int _retries;
private volatile string[] _harmfulNow = Array.Empty<string>();
private volatile string _dispelStatus = "idle";
// Surging state
private long _surgeCooldownUntil;
private volatile bool _surgeActive;
private volatile string _surgeStatus = "idle";
// Render-thread edit buffers
private string _newInclude = string.Empty, _newExclude = string.Empty;
public IltBuffKeepers(IltHubContext ctx) => _ctx = ctx;
private IltGearState G => _ctx.State.Gear;
/// <summary>True when this spell should be dispelled (precedence documented above).</summary>
public bool IsHarmful(int spellId, string name)
{
if (spellId == SpellMireFoot || (name.Contains("mire", StringComparison.OrdinalIgnoreCase) && name.Contains("foot", StringComparison.OrdinalIgnoreCase)))
return false;
if (G.DispelInclusions.ToArray().Any(i => i.Length > 0 && name.Contains(i, StringComparison.OrdinalIgnoreCase))) return true;
if (BeneficialPattern.IsMatch(name)) return false;
if (G.DispelExclusions.ToArray().Any(e => e.Length > 0 && name.Contains(e, StringComparison.OrdinalIgnoreCase))) return false;
string bare = StripTier(name);
return HarmfulExact.Contains(name) || HarmfulExact.Contains(bare) || HarmfulPattern.IsMatch(name);
}
/// <summary>"Vulnerability Other VII" → "vulnerability other" (roman numeral suffix removed).</summary>
private static string StripTier(string name)
{
string n = name.Trim();
int sp = n.LastIndexOf(' ');
if (sp > 0)
{
string tail = n.Substring(sp + 1);
if (tail.Length > 0 && tail.All(ch => "IVXL".IndexOf(char.ToUpperInvariant(ch)) >= 0)) n = n.Substring(0, sp);
}
return n.ToLowerInvariant();
}
private WorldObject? FindRune()
=> _ctx.Inventory.FindByWcid(IltInventory.WcidRuneOfDispel)
?? _ctx.Inventory.FindByName(n => n.Equals("Rune of Dispel", StringComparison.OrdinalIgnoreCase)
|| (n.Contains("dispel", StringComparison.OrdinalIgnoreCase) && n.Contains("rune", StringComparison.OrdinalIgnoreCase)));
private WorldObject? FindEmber()
=> _ctx.Inventory.FindByName(n => n.Contains("empowered", StringComparison.OrdinalIgnoreCase)
&& n.Contains("volcanic", StringComparison.OrdinalIgnoreCase)
&& n.Contains("ember", StringComparison.OrdinalIgnoreCase));
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (!G.AutoDispel && !G.SurgingStrength) return;
if (nowMs - _lastRead < 1000) return;
_lastRead = nowMs;
if (!_ctx.Host.HasReadPlayerEnchantments) return;
int n = _ctx.Host.ReadPlayerEnchantments(_ids, _exp, MaxEnch);
if (n < 0) return;
n = Math.Min(n, MaxEnch);
var harmful = new List<string>();
bool surge = false;
for (int i = 0; i < n; i++)
{
int id = unchecked((int)_ids[i]);
// Spell names are RynthAi's spell table (RynthAi.Hub SpellName); without RynthAi nothing is classified.
string name = _ctx.Ai.SpellName(id);
if (string.IsNullOrEmpty(name)) continue;
if (name.Contains("Surging Strength", StringComparison.OrdinalIgnoreCase)) surge = true;
if (G.AutoDispel && IsHarmful(id, name)) harmful.Add(name);
}
_harmfulNow = harmful.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
_surgeActive = surge;
if (G.AutoDispel) TickDispel(nowMs, harmful.Count > 0);
if (G.SurgingStrength) TickSurge(nowMs, surge);
}
private void TickDispel(long now, bool anyHarmful)
{
// Verification / retry window after a rune use.
if (_verifyAt > 0)
{
if (now < _verifyAt) return;
if (!anyHarmful || _retries >= 3)
{
_dispelStatus = anyHarmful ? "debuffs remain after 3 retries" : "dispelled";
_verifyAt = 0;
_dispelCooldownUntil = now + Math.Max(2, G.DispelCooldownSeconds) * 1000L;
return;
}
_retries++;
if (UseRune(now)) _verifyAt = now + 2500;
return;
}
if (!anyHarmful) { _dispelStatus = "no harmful spells"; return; }
if (now < _dispelCooldownUntil) { _dispelStatus = "cooling down"; return; }
_retries = 0;
if (UseRune(now)) _verifyAt = now + 2000;
}
private bool UseRune(long now)
{
if (_ctx.Inventory.IsBusy) return false;
var rune = FindRune();
if (rune == null) { _dispelStatus = "no Rune of Dispel carried"; _dispelCooldownUntil = now + 30_000; _verifyAt = 0; return false; }
if (!_ctx.Inventory.Use(rune)) return false;
_dispelStatus = $"used {rune.Name} on {_harmfulNow.Length} debuff(s)";
return true;
}
private void TickSurge(long now, bool active)
{
if (active) { _surgeStatus = "Surging Strength active"; return; }
if (now < _surgeCooldownUntil || _ctx.Inventory.IsBusy) return;
var ember = FindEmber();
if (ember == null) { _surgeStatus = "no Empowered Volcanic Ember carried"; _surgeCooldownUntil = now + 30_000; return; }
if (_ctx.Inventory.Use(ember)) _surgeStatus = "used " + ember.Name;
_surgeCooldownUntil = now + Math.Max(5, G.SurgingCooldownSeconds) * 1000L;
}
public bool OnChat(string text)
{
if (!G.SurgingStrength) return false;
if (text.Contains("surging strength", StringComparison.OrdinalIgnoreCase))
{
if (text.Contains("you cast", StringComparison.OrdinalIgnoreCase) && text.Contains("on yourself", StringComparison.OrdinalIgnoreCase))
_surgeActive = true;
else if (text.Contains("has expired", StringComparison.OrdinalIgnoreCase))
{
_surgeActive = false;
_surgeCooldownUntil = 0; // re-apply on the next read
}
}
return false;
}
public void OnLogout()
{
_verifyAt = 0;
_harmfulNow = Array.Empty<string>();
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
ImGui.TextColored(IltStyle.ColTeal, "Auto-dispel (Rune of Dispel)");
bool ad = G.AutoDispel;
if (ImGui.Checkbox("Use a Rune of Dispel on harmful debuffs", ref ad)) G.AutoDispel = ad;
int cd = G.DispelCooldownSeconds;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Cooldown (s)##disp", ref cd)) G.DispelCooldownSeconds = Math.Max(2, cd);
SafeImGui.TextDisabled("Status: " + _dispelStatus);
var harm = _harmfulNow;
if (harm.Length > 0) SafeImGui.TextColored(IltStyle.ColAmber, "Harmful now: " + string.Join(", ", harm));
if (ImGui.TreeNode("Always / never dispel lists"))
{
EditList("Always dispel (name contains)", G.DispelInclusions, ref _newInclude, "inc");
EditList("Never dispel (name contains)", G.DispelExclusions, ref _newExclude, "exc");
ImGui.TreePop();
}
ImGui.Separator();
ImGui.TextColored(IltStyle.ColTeal, "Surging Strength");
bool ss = G.SurgingStrength;
if (ImGui.Checkbox("Keep Surging Strength up (Empowered Volcanic Ember)", ref ss)) G.SurgingStrength = ss;
SafeImGui.TextDisabled("Status: " + (_surgeActive ? "active" : _surgeStatus));
}
private void EditList(string label, List<string> list, ref string buffer, string id)
{
ImGui.TextUnformatted(label);
var snap = list.ToArray();
for (int i = 0; i < snap.Length; i++)
{
SafeImGui.BulletText(snap[i]);
ImGui.SameLine();
string victim = snap[i];
if (ImGui.SmallButton($"x##{id}{i}")) _ctx.Post(() => list.Remove(victim));
}
ImGui.SetNextItemWidth(200);
ImGui.InputTextWithHint($"##new{id}", "spell name text", ref buffer, 64u);
ImGui.SameLine();
if (ImGui.SmallButton($"Add##{id}") && buffer.Trim().Length > 0)
{
string add = buffer.Trim();
_ctx.Post(() => { if (!list.Contains(add, StringComparer.OrdinalIgnoreCase)) list.Add(add); });
buffer = string.Empty;
}
}
}

View file

@ -0,0 +1,144 @@
// IltCharmTracker.cs — Every ACECustom registry charm's state: the Mini Remote's Charms tab
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
// (IltCharms) and RynthPluginGetCharmsJson (an older engine's Settings "Charms Tracking" tab).
//
// Per charm it reports:
// acquired — "carried" (in pack / equipped now), "seen" (carried earlier this or a past
// session, remembered in IltCharacterState.CharmsSeen), or "no".
// active — "on" / "off" / "unknown". The charm's appraisal Use text ("Status: ON") wins;
// otherwise the player ability PropertyBool the server sets while it's active.
// The server deactivates abilities whose charm isn't possessed, so not carried = off.
// server — "off" when the server refused / reported the charm disabled, "on" when a feature
// dump reported it enabled, else "unknown" (clients can't query /charms).
// Pump thread only (inventory and property reads).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltCharmTracker
{
private readonly IltHubContext _ctx;
public IltCharmTracker(IltHubContext ctx) => _ctx = ctx;
/// <summary>
/// One charm's tracked state. <paramref name="ToggleId"/> is the carried copy a toggle uses
/// (the active one when one is on), 0 when none is carried.
/// </summary>
internal readonly record struct CharmState(
IltCharmDef Def, string Acquired, int Count, int Tier, int MaxTier,
IltTri Active, IltTri Server, DateTime LastSeenUtc, int ToggleId = 0);
/// <summary>Evaluates every registry charm and refreshes the "seen" memory for carried ones.</summary>
public List<CharmState> Evaluate()
{
var inv = _ctx.Inventory;
var seenMap = _ctx.State.Character.CharmsSeen;
var result = new List<CharmState>(IltInventory.Charms.Length);
// One inventory pass, grouped by charm definition, instead of a WCID scan per charm.
var carried = new Dictionary<IltCharmDef, List<WorldObject>>();
foreach (var wo in inv.Items())
{
var def = inv.CharmDefFor(wo);
if (def == null) continue;
if (!carried.TryGetValue(def, out var list)) carried[def] = list = new();
list.Add(wo);
}
foreach (var def in IltInventory.Charms)
{
carried.TryGetValue(def, out var items);
int count = items?.Count ?? 0;
int tier = 0, maxTier = 0, toggleId = 0;
IltTri active = IltTri.Off;
if (count > 0)
{
// Server allows only one active charm per ability, so any ON item means ON.
bool anyOn = false, allKnown = true;
toggleId = items![0].Id;
foreach (var wo in items!)
{
var (t, m) = inv.CharmTier(wo);
if (t > tier) { tier = t; maxTier = m; }
var st = inv.CharmStatus(wo);
if (st == IltTri.On) { anyOn = true; toggleId = wo.Id; }
else if (st == IltTri.Unknown) allKnown = false;
}
if (anyOn) active = IltTri.On;
else if (def.PlayerFlag != 0 && inv.PlayerBool(def.PlayerFlag)) active = IltTri.On;
else active = allKnown ? IltTri.Off : IltTri.Unknown;
if (!seenMap.TryGetValue(def.Name, out var seen)) seenMap[def.Name] = seen = new IltCharmSeen();
if (tier > seen.Tier) { seen.Tier = tier; seen.MaxTier = maxTier; }
// Day resolution keeps the persisted state from changing (and re-saving) every poll.
var today = DateTime.UtcNow.Date;
if (seen.LastSeenUtc != today) seen.LastSeenUtc = today;
}
seenMap.TryGetValue(def.Name, out var memory);
string acquired = count > 0 ? "carried" : memory != null ? "seen" : "no";
if (count == 0 && memory != null) { tier = memory.Tier; maxTier = memory.MaxTier; }
result.Add(new CharmState(def, acquired, count, tier, maxTier, active,
ServerState(def), memory?.LastSeenUtc ?? default, toggleId));
}
return result;
}
/// <summary>Server-side enabled state as far as the client has learned it.</summary>
private IltTri ServerState(IltCharmDef def)
{
var opts = _ctx.Options;
var tri = opts.Get(IltFeature.Charm(def.Name));
// Universal Summoning Mastery also has a ServerConfig switch, reported separately.
if (Array.IndexOf(def.Wcids, IltInventory.WcidUniversalMasteryCharm) >= 0)
{
var cfg = opts.Get(IltFeature.UniversalMastery);
if (cfg == IltTri.Off || tri == IltTri.Off) return IltTri.Off;
if (cfg == IltTri.On || tri == IltTri.On) return IltTri.On;
}
return tri;
}
/// <summary>JSON for RynthPluginGetCharmsJson. "available" is false off ILT-like worlds.</summary>
public string BuildJson()
{
var sb = new StringBuilder(4096);
bool available = _ctx.Options.IsIltLikeWorld;
sb.Append("{\"available\":").Append(available ? "true" : "false");
sb.Append(",\"world\":\"").Append(IltStyle.JsonEscape(_ctx.Options.WorldName ?? string.Empty)).Append('"');
if (!available) return sb.Append(",\"charms\":[]}").ToString();
var rows = Evaluate();
sb.Append(",\"total\":").Append(rows.Count);
sb.Append(",\"acquiredCount\":").Append(rows.Count(r => r.Acquired != "no"));
sb.Append(",\"activeCount\":").Append(rows.Count(r => r.Active == IltTri.On));
sb.Append(",\"charms\":[");
for (int i = 0; i < rows.Count; i++)
{
var r = rows[i];
if (i > 0) sb.Append(',');
sb.Append("{\"name\":\"").Append(IltStyle.JsonEscape(r.Def.Name)).Append('"');
sb.Append(",\"effect\":\"").Append(IltStyle.JsonEscape(r.Def.Effect)).Append('"');
sb.Append(",\"acquired\":\"").Append(r.Acquired).Append('"');
sb.Append(",\"count\":").Append(r.Count);
sb.Append(",\"tier\":").Append(r.Tier);
sb.Append(",\"maxTier\":").Append(r.MaxTier);
sb.Append(",\"active\":\"").Append(TriText(r.Active)).Append('"');
sb.Append(",\"server\":\"").Append(TriText(r.Server)).Append('"');
sb.Append(",\"lastSeen\":\"")
.Append(r.LastSeenUtc == default ? string.Empty : r.LastSeenUtc.ToString("yyyy-MM-dd"))
.Append('"');
// The carried copy a reader's Toggle uses ("RynthILT.Data" ToggleCharm); 0 = none carried.
sb.Append(",\"toggleId\":").Append(unchecked((uint)r.ToggleId)).Append('}');
}
sb.Append("]}");
return sb.ToString();
}
private static string TriText(IltTri t) => t switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" };
}

View file

@ -0,0 +1,266 @@
// IltCharms.cs — The Mini Remote's "Charms" ILT tab: every ACECustom registry charm and the
// Guardian Hand, with their toggles. Other plugins read the same list and toggle through
// "RynthILT.Data" (BuildReaderJson / ToggleFromReader).
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Per charm (IltCharmTracker): acquired ("carried" now, "stored" = carried before and remembered
// per character, or no), status ON / OFF from the charm's appraisal or the player's ability flag,
// best tier, and the server's switch when the client has learned it. A carried charm has a
// Toggle (using a charm flips it). The Guardian Hand isn't a registry charm (no published WCID),
// so it is matched by name or a configured WCID and listed under the table with its own Toggle.
// This was the engine Settings panel's "Charms Tracking" tab plus the Gear tab's charm strip.
// Scans run on the pump thread every 3 s while the Mini Remote is on screen; Render reads the
// published arrays only.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltCharms : IIltFeature
{
private const long ScanIntervalMs = 3000;
private readonly IltHubContext _ctx;
private readonly IltCharmTracker _tracker;
/// <summary>A Guardian Hand carried now (name or WCID match).</summary>
private sealed record HandRow(int Id, string Name, IltTri Status, bool ServerDisabled);
private volatile IltCharmTracker.CharmState[] _rows = Array.Empty<IltCharmTracker.CharmState>();
private volatile HandRow[] _hands = Array.Empty<HandRow>();
private long _lastScan;
public IltCharms(IltHubContext ctx, IltCharmTracker tracker)
{
_ctx = ctx;
_tracker = tracker;
}
private IltGearState G => _ctx.State.Gear;
private bool IsGuardianHand(WorldObject wo)
{
if (G.GuardianHandWcid != 0 && _ctx.Inventory.Wcid(wo) == G.GuardianHandWcid) return true;
string want = string.IsNullOrWhiteSpace(G.GuardianHandName) ? "Guardian Hand" : G.GuardianHandName.Trim();
return wo.Name.Contains(want, StringComparison.OrdinalIgnoreCase)
|| (wo.Name.Contains("guardian", StringComparison.OrdinalIgnoreCase) && wo.Name.Contains("hand", StringComparison.OrdinalIgnoreCase));
}
/// <summary>Pump thread: the registry table and the carried Guardian Hands.</summary>
private void Scan()
{
_rows = _tracker.Evaluate().ToArray();
var inv = _ctx.Inventory;
var hands = new List<HandRow>();
foreach (var wo in inv.Items().Where(IsGuardianHand))
hands.Add(new HandRow(wo.Id, wo.Name, inv.CharmStatus(wo), _ctx.Options.IsOff(IltFeature.Charm("Guardian Hand"))));
_hands = hands.ToArray();
}
/// <summary>Uses (toggles) a charm (pump thread).</summary>
private void Toggle(int id)
{
var wo = _ctx.Inventory.Cache?[id];
if (wo == null) return;
if (_ctx.Inventory.IsBusy) { _ctx.Chat("[Mini Remote] Busy - try the charm again in a moment."); return; }
_ctx.Inventory.Use(wo);
_lastScan = 0; // re-read the status soon (the appraisal refresh is throttled per item)
}
/// <summary>
/// A Toggle from another plugin ("RynthILT.Data" ToggleCharm). Only
/// a registry charm or Guardian Hand the player carries is used, so a reader can't make the
/// client use anything else. Pump thread. True when it was used.
/// </summary>
public bool ToggleFromReader(uint id)
{
if (id == 0 || id > int.MaxValue) return false;
var inv = _ctx.Inventory;
foreach (var wo in inv.Items())
{
if (wo.Id != (int)id) continue;
if (inv.CharmDefFor(wo) == null && !IsGuardianHand(wo)) return false;
Toggle(wo.Id);
return true;
}
return false;
}
/// <summary>
/// The "RynthILT.Data" charms JSON: the registry charms
/// (IltCharmTracker.BuildJson) plus a "hands" array, every Guardian Hand carried now with its
/// object id (the Toggle's id), status and the server's switch. Pump thread.
/// </summary>
public string BuildReaderJson()
{
string json = _tracker.BuildJson();
if (!_ctx.Options.IsIltLikeWorld || !json.EndsWith("]}", StringComparison.Ordinal)) return json;
var inv = _ctx.Inventory;
string server = _ctx.Options.Get(IltFeature.Charm("Guardian Hand")) switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" };
var sb = new System.Text.StringBuilder(json, 0, json.Length - 1, json.Length + 256);
sb.Append(",\"hands\":[");
bool first = true;
foreach (var wo in inv.Items().Where(IsGuardianHand))
{
if (!first) sb.Append(',');
first = false;
string active = inv.CharmStatus(wo) switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" };
sb.Append("{\"id\":").Append(unchecked((uint)wo.Id));
sb.Append(",\"name\":\"").Append(IltStyle.JsonEscape(wo.Name)).Append('"');
sb.Append(",\"active\":\"").Append(active).Append('"');
sb.Append(",\"server\":\"").Append(server).Append("\"}");
}
return sb.Append("]}").ToString();
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (!_ctx.WindowOpen || nowMs - _lastScan < ScanIntervalMs) return;
_lastScan = nowMs;
Scan();
}
public bool OnChat(string text) => false;
public void OnLogout()
{
_rows = Array.Empty<IltCharmTracker.CharmState>();
_hands = Array.Empty<HandRow>();
_lastScan = 0;
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
var rows = _rows;
if (rows.Length == 0)
{
SafeImGui.TextDisabled(_ctx.WindowOpen ? "Reading your charms..." : "Open the Mini Remote to read your charms.");
RenderGuardianHand();
return;
}
int acquired = rows.Count(r => r.Acquired != "no"), active = rows.Count(r => r.Active == IltTri.On);
SafeImGui.TextColored(IltStyle.ColTeal, $"{acquired} of {rows.Length} acquired, {active} active");
ImGui.SameLine();
if (ImGui.SmallButton("Refresh##charms")) _ctx.Post(() => { _lastScan = 0; });
const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit
| ImGuiTableFlags.ScrollY;
float h = Math.Max(140f, ImGui.GetContentRegionAvail().Y - 110f);
if (ImGui.BeginTable("##iltcharms", 6, flags, new Vector2(0, h)))
{
ImGui.TableSetupScrollFreeze(0, 1);
ImGui.TableSetupColumn("Charm", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Acquired", ImGuiTableColumnFlags.WidthFixed, 64);
ImGui.TableSetupColumn("Status", ImGuiTableColumnFlags.WidthFixed, 44);
ImGui.TableSetupColumn("Tier", ImGuiTableColumnFlags.WidthFixed, 40);
ImGui.TableSetupColumn("Server", ImGuiTableColumnFlags.WidthFixed, 58);
ImGui.TableSetupColumn("##toggle", ImGuiTableColumnFlags.WidthFixed, 52);
ImGui.TableHeadersRow();
for (int i = 0; i < rows.Length; i++) RenderRow(i, rows[i]);
ImGui.EndTable();
}
RenderGuardianHand();
ImGui.TextDisabled("Status comes from the charm's appraisal or your ability flag; a charm not carried is inactive.");
ImGui.TextDisabled("Stored = carried by this character before (remembered per character).");
}
private void RenderRow(int i, IltCharmTracker.CharmState r)
{
ImGui.PushID(i);
ImGui.TableNextRow();
ImGui.TableNextColumn();
bool carried = r.Acquired == "carried";
if (carried) ImGui.TextUnformatted(r.Def.Name);
else SafeImGui.TextColored(IltStyle.ColTextMute, r.Def.Name);
if (ImGui.IsItemHovered() && r.Def.Effect.Length > 0) SafeImGui.SetTooltip(r.Def.Effect);
ImGui.TableNextColumn();
if (carried) SafeImGui.TextColored(IltStyle.ColGreen, r.Count > 1 ? $"Carried x{r.Count}" : "Carried");
else if (r.Acquired == "seen")
{
ImGui.TextColored(IltStyle.ColAmber, "Stored");
if (ImGui.IsItemHovered() && r.LastSeenUtc != default)
SafeImGui.SetTooltip("Last carried " + r.LastSeenUtc.ToString("yyyy-MM-dd"));
}
else ImGui.TextDisabled("No");
ImGui.TableNextColumn();
if (!carried) ImGui.TextDisabled("-");
else if (r.Active == IltTri.On) ImGui.TextColored(IltStyle.ColGreen, "ON");
else if (r.Active == IltTri.Off) ImGui.TextColored(IltStyle.ColTextMute, "OFF");
else
{
ImGui.TextColored(IltStyle.ColAmber, "?");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Waiting for the charm's appraisal.");
}
ImGui.TableNextColumn();
ImGui.TextUnformatted(r.Tier <= 0 ? "-" : r.MaxTier > 0 ? $"{r.Tier}/{r.MaxTier}" : r.Tier.ToString());
ImGui.TableNextColumn();
if (r.Server == IltTri.Off)
{
ImGui.TextColored(IltStyle.ColHp, "Disabled");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("The server refused or reported this charm as disabled.");
}
else if (r.Server == IltTri.On) ImGui.TextColored(IltStyle.ColGreen, "Enabled");
else
{
ImGui.TextDisabled("-");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Not reported. The server only tells players when a charm is refused.");
}
ImGui.TableNextColumn();
if (carried && r.ToggleId != 0 && r.Server != IltTri.Off)
{
int id = r.ToggleId;
if (ImGui.SmallButton("Toggle")) _ctx.Post(() => Toggle(id));
}
ImGui.PopID();
}
/// <summary>The Guardian Hand (not a registry charm): each carried one with a Toggle, and how it is matched.</summary>
private void RenderGuardianHand()
{
var hands = _hands;
foreach (var h in hands)
{
ImGui.PushID(h.Id);
if (h.ServerDisabled) SafeImGui.TextDisabled($"{h.Name} - disabled on this server");
else
{
var col = h.Status == IltTri.On ? IltStyle.ColGreen
: h.Status == IltTri.Off ? IltStyle.ColTextMute : IltStyle.ColAmber;
SafeImGui.TextColored(col, h.Status == IltTri.On ? "ON " : h.Status == IltTri.Off ? "OFF" : " ? ");
ImGui.SameLine();
ImGui.TextUnformatted(h.Name);
ImGui.SameLine();
int id = h.Id;
if (ImGui.SmallButton("Toggle")) _ctx.Post(() => Toggle(id));
}
ImGui.PopID();
}
if (ImGui.TreeNode("Guardian Hand matching"))
{
string name = G.GuardianHandName;
ImGui.SetNextItemWidth(200);
if (ImGui.InputText("Name contains", ref name, 64u)) G.GuardianHandName = name;
int wcid = unchecked((int)G.GuardianHandWcid);
ImGui.SetNextItemWidth(140);
if (ImGui.InputInt("WCID (0 = name only)", ref wcid, 0)) G.GuardianHandWcid = unchecked((uint)Math.Max(0, wcid));
ImGui.TreePop();
}
}
}

View file

@ -0,0 +1,217 @@
// IltChatCapture.cs — Shared "send a server command and collect its reply" helper.
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Every ILT Hub feature that talks to ACECustom (/bank, /aug, /qb, /pets, /xp, /pb,
// the login probe, /myquests, ...) goes through this one queue so that:
// * only one capture is in flight at a time (replies can't be attributed to the wrong
// request),
// * reply lines can be eaten so a Hub refresh doesn't spam the chat window,
// * an "Unknown command: X" reply is recognised uniformly (feature not on this server).
// All methods must be called on the plugin pump thread (OnTick / OnChatWindowText).
using System;
using System.Collections.Generic;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>Describes one command whose reply should be captured.</summary>
internal sealed class IltChatRequest
{
/// <summary>Text handed to InvokeChatParser, e.g. "/bank".</summary>
public string Command = string.Empty;
/// <summary>True for lines that belong to this reply (captured, refresh the idle timer).</summary>
public Func<string, bool> IsResponseLine = _ => false;
/// <summary>
/// Optional: only these response lines arm / refresh the idle timer. Header / banner lines
/// still capture, but idle completion waits until a progress line arrives (UB's /aug fetch:
/// dashes and "Advanced Augmentation Levels:" must not start the 2s idle before Creature:).
/// </summary>
public Func<string, bool>? ArmsIdle;
/// <summary>Optional: a line that ends the reply immediately (it is captured too).</summary>
public Func<string, bool>? IsTerminator;
/// <summary>The reply is complete after this long with no new response line.</summary>
public int IdleEndMs = 2000;
/// <summary>Give up if no response line arrives within this long.</summary>
public int FirstLineTimeoutMs = 15000;
/// <summary>Hide captured lines from the chat window.</summary>
public bool Eat = true;
/// <summary>Invoked once on the pump thread when the capture finishes for any reason.</summary>
public Action<IltChatResult>? OnComplete;
}
/// <summary>What a capture produced.</summary>
internal sealed class IltChatResult
{
public readonly List<string> Lines = new();
/// <summary>No response line ever arrived.</summary>
public bool TimedOut;
/// <summary>The server answered "Unknown command: …" for this command.</summary>
public bool UnknownCommand;
/// <summary>The engine had no InvokeChatParser, so nothing was sent.</summary>
public bool NotSent;
public string? TerminatorLine;
}
internal sealed class IltChatCapture
{
private readonly RynthCoreHost _host;
private readonly Queue<IltChatRequest> _queue = new();
private IltChatRequest? _active;
private IltChatResult? _activeResult;
private long _sentAt;
private long _lastLineAt;
/// <summary>True once a response line that arms idle has arrived (always true when <see cref="IltChatRequest.ArmsIdle"/> is null).</summary>
private bool _idleArmed;
/// <summary>Minimum spacing between two sends so the server's own command throttles aren't tripped.</summary>
private const long SendSpacingMs = 400;
private long _lastSendAt;
private static long NowMs => Environment.TickCount64;
public IltChatCapture(RynthCoreHost host) => _host = host;
/// <summary>True while a capture is in flight or queued.</summary>
public bool IsBusy => _active != null || _queue.Count > 0;
/// <summary>True if a request with this exact command is queued or in flight (avoids duplicate refreshes).</summary>
public bool IsPending(string command)
{
if (_active != null && string.Equals(_active.Command, command, StringComparison.OrdinalIgnoreCase))
return true;
foreach (var r in _queue)
if (string.Equals(r.Command, command, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
/// <summary>Queues a capture. It is sent from <see cref="Tick"/> once earlier captures finish.</summary>
public void Enqueue(IltChatRequest request)
{
_queue.Enqueue(request);
RynthLog.Trace(LogCat.IltChat, $"enqueue '{request.Command}' (queue={_queue.Count}, busy={_active != null})");
}
/// <summary>Drops everything (logout / teardown). Pending callbacks are not invoked.</summary>
public void Clear()
{
if (_active != null || _queue.Count > 0)
RynthLog.Trace(LogCat.IltChat, $"clear: dropping active='{_active?.Command}' and {_queue.Count} queued");
_queue.Clear();
_active = null;
_activeResult = null;
}
/// <summary>Starts queued captures and finishes the active one on idle/timeout.</summary>
public void Tick()
{
long now = NowMs;
if (_active != null && _activeResult != null)
{
bool gotAny = _activeResult.Lines.Count > 0;
// Idle completion only after a progress line when ArmsIdle is set (header alone is not enough).
bool idleReady = _active.ArmsIdle == null || _idleArmed;
if (gotAny && idleReady && now - _lastLineAt >= _active.IdleEndMs)
Finish();
else if ((!gotAny || !idleReady) && now - _sentAt >= _active.FirstLineTimeoutMs)
{
_activeResult.TimedOut = true;
Finish();
}
}
if (_active == null && _queue.Count > 0 && now - _lastSendAt >= SendSpacingMs)
StartNext(now);
}
/// <summary>
/// Feed every incoming chat line. Returns true when the line belonged to the active
/// capture and that capture asked for its lines to be eaten.
/// </summary>
public bool OnChatLine(string rawText)
{
if (_active == null || _activeResult == null) return false;
string text = rawText.Trim();
if (text.Length == 0) return false;
// "Unknown command: blackjack" — ACE GameActionTalk reply for unregistered commands.
if (text.StartsWith("Unknown command:", StringComparison.OrdinalIgnoreCase)
&& CommandWordMatches(text.Substring("Unknown command:".Length).Trim()))
{
_activeResult.UnknownCommand = true;
_activeResult.Lines.Add(text);
bool eat = _active.Eat;
Finish();
return eat;
}
if (_active.IsTerminator != null && _active.IsTerminator(text))
{
_activeResult.TerminatorLine = text;
_activeResult.Lines.Add(text);
bool eat = _active.Eat;
Finish();
return eat;
}
if (!_active.IsResponseLine(text)) return false;
_activeResult.Lines.Add(text);
// Header-only replies (e.g. /aug dashes + banner) must not start the idle clock.
if (_active.ArmsIdle == null || _active.ArmsIdle(text))
{
_idleArmed = true;
_lastLineAt = NowMs;
}
RynthLog.Trace(LogCat.IltChat, $"line '{_active.Command}'{(_active.Eat ? " [eaten]" : "")}: {text}");
return _active.Eat;
}
private bool CommandWordMatches(string word)
{
if (_active == null) return false;
// Request "/bank t p 5 Bob" → command word "bank".
string cmd = _active.Command.TrimStart('/', '@');
int sp = cmd.IndexOf(' ');
if (sp >= 0) cmd = cmd.Substring(0, sp);
return string.Equals(cmd, word, StringComparison.OrdinalIgnoreCase);
}
private void StartNext(long now)
{
var req = _queue.Dequeue();
var result = new IltChatResult();
if (!_host.HasInvokeChatParser)
{
RynthLog.Trace(LogCat.IltChat, $"not sent '{req.Command}': engine has no InvokeChatParser");
result.NotSent = true;
try { req.OnComplete?.Invoke(result); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltChat, ex, $"capture callback '{req.Command}'"); }
return;
}
_active = req;
_activeResult = result;
_sentAt = now;
_lastLineAt = now;
_idleArmed = req.ArmsIdle == null; // no progress gate → idle can finish after any response line
_lastSendAt = now;
RynthLog.Trace(LogCat.IltChat, $"send '{req.Command}' (idle={req.IdleEndMs} ms, timeout={req.FirstLineTimeoutMs} ms, eat={req.Eat})");
_host.InvokeChatParser(req.Command);
}
private void Finish()
{
var req = _active;
var res = _activeResult;
_active = null;
_activeResult = null;
_idleArmed = false;
if (req == null || res == null) return;
RynthLog.Trace(LogCat.IltChat,
$"complete '{req.Command}' in {NowMs - _sentAt} ms: lines={res.Lines.Count} timedOut={res.TimedOut} " +
$"unknown={res.UnknownCommand} terminator={(res.TerminatorLine != null)}");
try { req.OnComplete?.Invoke(res); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltChat, ex, $"capture callback '{req.Command}'"); }
}
}

View file

@ -0,0 +1,672 @@
// IltChunkClap.cs — Lugian-hammer chunking and /clap automation (Gear tab).
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Chunk: uses the Lugian Aetheria Hammer on eligible items, one at a time. The rules follow ub-IT
// (Leaftide AetheriaChunkGuard / IsValidCorruptedWep / CorruptedChunkGuard):
// Aetheria — "Aetheria"/"Coalesced Aetheria" gems, not equipped, appraised, not flagged
// never-chunk (bool 9030), not tinkered (171) or imbued (179), never levelled
// (ItemTotalXp quad 4 == 0), no kept C / CD / CDR rating (gear ints 372 / 374 / 375;
// on by default; only a rating at or above the "rating level" keeps, a lower one
// chunks), and max level (int 319, up to 10 on ILT) under the configured cap.
// A levelled Coalesced piece gets the cap too; an unlevelled one (319 = 0 after
// appraisal, normal for Coalesced) is chunkable, as in ub-IT. RynthILT used to keep
// every unlevelled Coalesced piece forever.
// Corrupted — "Corrupted" melee/missile weapons, not equipped, not never-chunk, no tinks (171),
// no imbue (179), loot-gen workmanship (105) > 0, and cleave (292) <= 1, or <= 2 on a
// two-handed weapon that is not a thrust weapon (RynthILT used to cap every weapon
// at 1, so no two-handed corrupted weapon was ever chunked). Optional keep rules
// (Crushing Blow, Biting Strike, Armor Cleaving, slayer, multi-strike, elemental
// bonus, any spell, max damage, spell ids) are all off by default.
// Peace mode only unless ChunkInCombat. With ChunkInCombat on, a busy client in combat mode no
// longer blocks the hammer (a swinging bot is always busy); peace mode still waits for idle.
// Waits for the result line (10 s max); a target that leaves the pack first counts as chunked
// (ILT does not always send a known line). Each item's skip reason is logged when it changes
// and tallied in the status line.
// The tool is the "Lugian Aetheria Hammer" only. The Lugian Hammer weapons (Flaming, Acid, ...)
// are loot and chunk nothing: the server answers with no result line, so every item timed out
// into the skip list and the status sat on "nothing eligible" (SilentKelpie, 2026-10-15).
// Clap: "/clap all" converts aetheria + trinkets into coins server-side: red (Coalesced level 1-3,
// chunks, powder) with Empyrean Trinkets, blue with Falatacot Trinkets. Auto-clap sends it only
// when a pair is carried. Needs the AutoCraftingEnabled stamp; 30 min ± 2 min interval, first
// attempt ~1 min after enable.
using System;
using System.Collections.Generic;
using System.Linq;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltChunkClap : IIltFeature
{
private const long ChunkResultWaitMs = 10_000;
private const long ClapFirstDelayMs = 60_000;
private const long ClapJitterMs = 120_000;
private static readonly string[] ChunkDoneLines =
{
"You smash the aetheria with the hammer.", "The two artifacts link together effortlessly.",
"You successfully chunk the aetheria.", "You fail to chunk the aetheria.",
"The corrupted weapon is crushed into a fine powder.", "You smash the corrupted weapon with the hammer.",
"The corrupted weapon shatters into fragments.", "You fail to chunk the corrupted weapon.",
};
private static readonly string[] ChunkRefusedLines =
{
"The aetheria is too powerful to chunk.", "You cannot chunk this aetheria.",
"The corrupted weapon is too powerful to chunk.", "You cannot chunk this corrupted weapon.",
};
private readonly IltHubContext _ctx;
private readonly Random _rng = new();
// Chunk state
private long _lastChunkAt;
private int _waitingOn;
private long _waitStartedAt;
private readonly HashSet<int> _skip = new();
private bool _manualPass;
private volatile string _chunkStatus = "idle";
private int _chunked;
// Last skip reason per item, so each reason is logged once instead of every pass.
private readonly Dictionary<int, string> _lastSkip = new();
// Skip reasons of the current pass (reason -> items), shown in the status line.
private readonly Dictionary<string, int> _passSkips = new();
// Clap state
private long _nextClapAt;
private volatile string _clapStatus = "idle";
private bool _clapWasEnabled;
public IltChunkClap(IltHubContext ctx) => _ctx = ctx;
private IltGearState G => _ctx.State.Gear;
// ── Chunk ───────────────────────────────────────────────────────────────
/// <summary>Infinite Leaftide's chunking tool.</summary>
internal const string HammerName = "Lugian Aetheria Hammer";
/// <summary>True for the chunking tool only, never a Lugian Hammer weapon. Pure: the tests drive it.</summary>
internal static bool IsChunkHammer(string name) => name.Equals(HammerName, StringComparison.OrdinalIgnoreCase);
private WorldObject? FindHammer()
=> _ctx.Inventory.Items().FirstOrDefault(wo => IsChunkHammer(wo.Name) && !_ctx.Inventory.IsEquipped(wo));
/// <summary>Item kinds the hammer works on (the name and class gate, before any appraisal).</summary>
internal enum ChunkKind { None, Aetheria, Corrupted }
/// <summary>
/// Which chunk rules an item falls under, by class and name only. Aetheria chunks and powder
/// are clap material, not hammer targets. Pure: the tests drive it.
/// </summary>
internal static ChunkKind KindOf(AcObjectClass cls, string name)
{
if (cls == AcObjectClass.Gem)
{
if (name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase)) return ChunkKind.Aetheria;
if (name.Contains("Aetheria", StringComparison.OrdinalIgnoreCase)
&& !name.Contains("Chunk", StringComparison.OrdinalIgnoreCase)
&& !name.Contains("Powder", StringComparison.OrdinalIgnoreCase))
return ChunkKind.Aetheria;
return ChunkKind.None;
}
if (cls is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon
&& name.Contains("Corrupted", StringComparison.OrdinalIgnoreCase))
return ChunkKind.Corrupted;
return ChunkKind.None;
}
/// <summary>An aetheria piece's chunk facts, read after appraisal.</summary>
internal readonly record struct AetheriaFacts(
bool Coalesced, int MaxLevel, bool NeverChunk, long ItemXp, int Tinkers, int Imbue,
int Crit, int CritDamage, int CritDamageResist, string? Unreadable = null);
/// <summary>
/// Why an aetheria piece is kept, or null when it may be chunked (ub-IT AetheriaChunkGuard plus
/// RynthILT's C / CD / CDR keep switches). Pure: the tests drive it.
/// <para>
/// <see cref="AetheriaFacts.Unreadable"/> is set when the item's properties could not be read (the
/// host lacks a reader or the appraisal never arrived). A property that failed to read looks
/// exactly like one the item lacks (level 0, no XP, no tinks), so such a piece is kept: an
/// "unlevelled" Coalesced piece is only chunked when its level was truly read as none.
/// </para>
/// </summary>
internal static string? AetheriaSkip(IltGearState g, in AetheriaFacts f)
{
if (f.Unreadable != null) return $"item data unreadable ({f.Unreadable})";
if (f.NeverChunk) return "never-chunk flag";
if (f.Tinkers != 0 || f.Imbue != 0) return "tinkered or imbued";
if (f.ItemXp != 0) return "has item XP";
if (KeptForRatings(g, f.Crit, f.CritDamage, f.CritDamageResist)) return "kept for its C / CD / CDR rating";
if (!UnderChunkCap(f.MaxLevel, g.ChunkAetheriaUnderLevel, f.Coalesced))
return f.MaxLevel > 0 ? "level at or above the cap" : "no level read";
return null;
}
/// <summary>Why an aetheria item is kept (null = chunk it); "appraising" while its data is missing.</summary>
private string? AetheriaSkip(WorldObject wo)
{
var inv = _ctx.Inventory;
if (inv.IsEquipped(wo)) return "equipped";
if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return Appraising; }
string? gap = inv.ReadGap(wo, quads: true);
var f = new AetheriaFacts(
Coalesced: wo.Name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase),
MaxLevel: inv.Int(wo, IltInventory.IntItemMaxLevel),
NeverChunk: inv.Bool(wo, IltInventory.BoolNeverChunk),
ItemXp: inv.Quad(wo, IltInventory.QuadItemTotalXp),
Tinkers: inv.Int(wo, IltInventory.IntNumTimesTinkered),
Imbue: inv.Int(wo, IltInventory.IntImbuedEffect),
Crit: inv.Int(wo, IltInventory.IntGearCrit),
CritDamage: inv.Int(wo, IltInventory.IntGearCritDamage),
CritDamageResist: inv.Int(wo, IltInventory.IntGearCritDamageResist),
Unreadable: gap);
return AetheriaSkip(G, f);
}
/// <summary>The chunk cap in range: 1 (chunk nothing by level) to one past the ILT maximum (every level).</summary>
internal static int ClampUnderLevel(int under) => Math.Clamp(under, 1, IltInventory.AetheriaMaxLevel + 1);
/// <summary>
/// True when an aetheria's max level (int 319) is under the cap. A levelled Coalesced piece
/// (ACECustom rolls 1-10; level 6+ can carry a rating) gets the same cap. Level 0 after
/// appraisal: an unlevelled Coalesced piece is chunkable (ub-IT: "ItemMaxLevel 0 after assess
/// is normal"); any other aetheria with no level is never chunked. Pure: the tests drive it.
/// </summary>
internal static bool UnderChunkCap(int maxLevel, int under, bool coalesced = false)
=> maxLevel > 0 ? maxLevel < ClampUnderLevel(under) : coalesced && maxLevel == 0;
/// <summary>Highest rating level the keep threshold accepts.</summary>
internal const int MaxRatingLevel = 50;
/// <summary>The rating keep threshold in range: 1 (any rating keeps) to <see cref="MaxRatingLevel"/>.</summary>
internal static int ClampRatingLevel(int level) => Math.Clamp(level, 1, MaxRatingLevel);
/// <summary>
/// True when an aetheria's C / CD / CDR rating is one the settings keep: its keep switch is on and
/// the rating is at or above the rating level (<see cref="IltGearState.KeepAetheriaRatingAtLeast"/>).
/// A rating below that level does not protect the piece, so e.g. a C 1 Coalesced Aetheria chunks
/// with the level at 2 while a C 2 one is kept. Pure: the tests drive it.
/// </summary>
internal static bool KeptForRatings(IltGearState g, int crit, int critDamage, int critDamageResist)
{
int min = ClampRatingLevel(g.KeepAetheriaRatingAtLeast);
return (g.KeepAetheriaWithCrit && crit >= min)
|| (g.KeepAetheriaWithCritDamage && critDamage >= min)
|| (g.KeepAetheriaWithCritDamageResist && critDamageResist >= min);
}
private const string Appraising = "appraising";
private const int SkillTwoHandedCombat = 41;
private const int WeaponTypeTwoHanded = 11;
private const int AttackTypeThrust = 2;
/// <summary>A corrupted weapon's chunk facts, read after appraisal.</summary>
internal sealed record CorruptedFacts
{
public bool NeverChunk { get; init; }
public int Tinkers { get; init; }
public int Imbue { get; init; }
public int Workmanship { get; init; }
public int AttackType { get; init; }
public int Cleaving { get; init; }
public int WieldSkill { get; init; }
public int WeaponType { get; init; }
public double CritFrequency { get; init; }
public double CritMultiplier { get; init; }
public double IgnoreArmor { get; init; }
public int Slayer { get; init; }
public int ElementalBonus { get; init; }
public int MaxDamage { get; init; }
public IReadOnlyList<int> Spells { get; init; } = Array.Empty<int>();
/// <summary>What could not be read (null = everything the rules need was); see AetheriaFacts.Unreadable.</summary>
public string? Unreadable { get; init; }
}
/// <summary>
/// The most cleave a chunkable corrupted weapon may have (ub-IT IsValidCorruptedWep): 2 on a
/// two-handed weapon that is not a thrust weapon, 1 on everything else. Pure: the tests drive it.
/// </summary>
internal static int MaxChunkCleave(int wieldSkill, int weaponType, int attackType)
=> (wieldSkill == SkillTwoHandedCombat || weaponType == WeaponTypeTwoHanded) && attackType != AttackTypeThrust ? 2 : 1;
/// <summary>
/// Why a corrupted weapon is kept, or null when it may be chunked: ub-IT's hard rules, then its
/// IdleActs keep rules from the settings. Pure: the tests drive it.
/// </summary>
internal static string? CorruptedSkip(IltGearState g, CorruptedFacts f)
{
// A property that failed to read looks like one the weapon lacks (0), which would chunk it.
if (f.Unreadable != null) return $"item data unreadable ({f.Unreadable})";
// Hard rules (always on).
if (f.NeverChunk) return "never-chunk flag";
if (f.Tinkers != 0 || f.Imbue != 0) return "tinkered or imbued";
if (f.Workmanship <= 0) return "no workmanship";
if (f.Cleaving > MaxChunkCleave(f.WieldSkill, f.WeaponType, f.AttackType)) return "cleave over the limit";
// Keep rules (each off by default).
if (g.KeepCorruptedCrushingBlow && f.CritFrequency > 0) return "kept: Crushing Blow";
if (g.KeepCorruptedBitingStrike && f.CritMultiplier > 0) return "kept: Biting Strike";
if (g.KeepCorruptedArmorCleaving && f.IgnoreArmor > 0) return "kept: Armor Cleaving";
if (g.KeepCorruptedAnySlayer && f.Slayer > 0) return "kept: slayer";
if (g.KeepCorruptedMultiStrike && f.AttackType is 160 or 166 or 486) return "kept: multi-strike";
if (g.KeepCorruptedElementalBonus && f.ElementalBonus > 0) return "kept: elemental bonus";
if (g.KeepCorruptedMaxDamageAtLeast > 0 && f.MaxDamage >= g.KeepCorruptedMaxDamageAtLeast) return "kept: max damage";
if (f.Spells.Count > 0)
{
if (g.KeepCorruptedAnySpell) return "kept: has a spell";
var deny = ParseSpellIds(g.KeepCorruptedSpellIds);
if (deny.Count > 0 && f.Spells.Any(deny.Contains)) return "kept: listed spell";
}
return null;
}
/// <summary>Positive spell ids from a comma / semicolon / whitespace separated list. Pure: the tests drive it.</summary>
internal static HashSet<int> ParseSpellIds(string? csv)
{
var ids = new HashSet<int>();
if (string.IsNullOrWhiteSpace(csv)) return ids;
foreach (var part in csv.Split(new[] { ',', ';', ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
if (int.TryParse(part, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int id) && id > 0)
ids.Add(id);
return ids;
}
/// <summary>Why a corrupted weapon is kept (null = chunk it); "appraising" while its data is missing.</summary>
private string? CorruptedSkip(WorldObject wo)
{
var inv = _ctx.Inventory;
if (inv.IsEquipped(wo)) return "equipped";
if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return Appraising; }
bool needDoubles = G.KeepCorruptedCrushingBlow || G.KeepCorruptedBitingStrike || G.KeepCorruptedArmorCleaving;
bool needSpells = G.KeepCorruptedAnySpell || !string.IsNullOrWhiteSpace(G.KeepCorruptedSpellIds);
var f = new CorruptedFacts
{
Unreadable = inv.ReadGap(wo, doubles: needDoubles, spells: needSpells),
NeverChunk = inv.Bool(wo, IltInventory.BoolNeverChunk),
Tinkers = inv.Int(wo, IltInventory.IntNumTimesTinkered),
Imbue = inv.Int(wo, IltInventory.IntImbuedEffect),
Workmanship = inv.Int(wo, IltInventory.IntItemWorkmanship),
AttackType = inv.Int(wo, IltInventory.IntAttackType),
Cleaving = inv.Int(wo, IltInventory.IntCleaving),
WieldSkill = inv.Int(wo, IltInventory.IntWieldSkillType),
WeaponType = inv.Int(wo, IltInventory.IntWeaponType),
CritFrequency = inv.Double(wo, IltInventory.FloatCriticalFrequency),
CritMultiplier = inv.Double(wo, IltInventory.FloatCriticalMultiplier),
IgnoreArmor = inv.Double(wo, IltInventory.FloatIgnoreArmor),
Slayer = inv.Int(wo, IltInventory.IntSlayerCreatureType),
ElementalBonus = inv.Int(wo, IltInventory.IntElementalDamageBonus),
MaxDamage = inv.Int(wo, IltInventory.IntDamage),
// Spells are only read when a spell rule is on (the read copies the item's spell list).
Spells = needSpells ? inv.SpellIds(wo) : Array.Empty<int>(),
};
return CorruptedSkip(G, f);
}
/// <summary>
/// Chunk is allowed while the client is busy only in combat mode with ChunkInCombat on (ub-IT
/// AutoChunkCombatBusyPolicy v2.0.1059: a swinging bot is always busy). Peace mode still waits
/// for idle so the hammer never interrupts another use. Pure: the tests drive it.
/// </summary>
internal static bool AllowsChunkWhileBusy(bool isBusy, bool isPeace, bool chunkInCombat)
=> !isBusy || (!isPeace && chunkInCombat);
private WorldObject? NextChunkTarget()
{
_passSkips.Clear();
foreach (var wo in _ctx.Inventory.Items())
{
if (_skip.Contains(wo.Id)) continue;
string? reason;
switch (KindOf(wo.ObjectClass, wo.Name))
{
case ChunkKind.Aetheria when G.AutoChunkAetheria || _manualPass:
reason = AetheriaSkip(wo);
break;
case ChunkKind.Corrupted when G.AutoChunkCorrupted || _manualPass:
reason = CorruptedSkip(wo);
break;
default:
continue;
}
if (reason == null) { _lastSkip.Remove(wo.Id); return wo; }
NoteSkip(wo, reason);
}
return null;
}
/// <summary>Tallies a skip for the status line and logs it once per item and reason.</summary>
private void NoteSkip(WorldObject wo, string reason)
{
_passSkips[reason] = _passSkips.TryGetValue(reason, out int n) ? n + 1 : 1;
if (reason == Appraising) return;
if (_lastSkip.TryGetValue(wo.Id, out string? last) && last == reason) return;
_lastSkip[wo.Id] = reason;
RynthLog.Write(LogCat.IltGear, $"chunk: keep 0x{(uint)wo.Id:X8} '{wo.Name}': {reason}");
}
/// <summary>"3 kept for its C / CD / CDR rating, 1 appraising" — the current pass's skips.</summary>
private string PassSkipSummary()
=> string.Join(", ", _passSkips.OrderByDescending(kv => kv.Value).Select(kv => $"{kv.Value} {kv.Key}"));
/// <summary>Runs one chunk pass now (both item kinds) regardless of the auto toggles.</summary>
public void ChunkNow()
{
RynthLog.Trace(LogCat.IltGear, $"ChunkNow()");
_manualPass = true;
_lastChunkAt = 0;
_skip.Clear(); // a manual pass gives the items that got no answer another try
_chunkStatus = "manual pass started";
}
private void TickChunk(long now)
{
if (!G.AutoChunkAetheria && !G.AutoChunkCorrupted && !_manualPass) return;
if (_waitingOn != 0)
{
int id = _waitingOn;
switch (WaitOutcome(now - _waitStartedAt, _ctx.Inventory.Items().Any(wo => wo.Id == id)))
{
case ChunkWait.Waiting:
return;
case ChunkWait.Gone:
_chunked++;
RynthLog.Write(LogCat.IltGear, $"chunk: 0x{(uint)id:X8} left the pack with no result line; counted as chunked");
break;
case ChunkWait.TimedOut:
_skip.Add(id); // still carried and no result line: don't hammer the same item forever
RynthLog.Write(LogCat.IltGear, $"chunk: no result line for 0x{(uint)id:X8} in {ChunkResultWaitMs / 1000} s, skipped until a manual pass");
break;
}
_waitingOn = 0;
}
if (now - _lastChunkAt < Math.Max(500, G.ChunkIntervalMs)) return;
_lastChunkAt = now;
bool peace = _ctx.Inventory.InPeaceMode;
if (!G.ChunkInCombat && !peace) { _chunkStatus = "waiting for peace mode"; return; }
if (!AllowsChunkWhileBusy(_ctx.Inventory.IsBusy, peace, G.ChunkInCombat)) { _chunkStatus = "waiting for idle"; return; }
var hammer = FindHammer();
if (hammer == null) { _chunkStatus = $"no {HammerName} carried"; _manualPass = false; return; }
var target = NextChunkTarget();
if (target == null)
{
string kept = PassSkipSummary();
_chunkStatus = (_chunked > 0 ? $"nothing left to chunk ({_chunked} this session)" : "nothing eligible")
+ (kept.Length > 0 ? $"; not chunked: {kept}" : "")
+ (_skip.Count > 0 ? $"; {_skip.Count} skipped with no answer (Chunk now retries them)" : "");
_manualPass = false;
return;
}
if (_ctx.Inventory.UseOn(hammer, unchecked((uint)target.Id)))
{
_waitingOn = target.Id;
_waitStartedAt = now;
_chunkStatus = "chunking " + target.Name;
}
}
// ── Clap ────────────────────────────────────────────────────────────────
internal enum ClapPart { None, Red, Blue, Empyrean, Falatacot }
/// <summary>
/// Which side of /clap an item feeds (ACECustom PlayerCommands.HandleClap): red material (Red
/// Coalesced Aetheria, chunks, powder) pairs with Ancient Empyrean Trinkets, blue with Ancient
/// Falatacot Trinkets. Coalesced counts only unrevealed and at level 1-3; level 0 (not read yet)
/// counts, and the server has the last word. With no WCID yet, the chunk and trinket names
/// decide. Pure: the tests drive it.
/// </summary>
internal static ClapPart ClapPartOf(uint wcid, string name, int maxLevel)
{
bool lowCoalesced = name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase) && maxLevel <= 3;
switch (wcid)
{
case IltInventory.WcidRedCoalescedAetheria: return lowCoalesced ? ClapPart.Red : ClapPart.None;
case IltInventory.WcidBlueCoalescedAetheria: return lowCoalesced ? ClapPart.Blue : ClapPart.None;
case IltInventory.WcidRedAetheriaChunk:
case IltInventory.WcidRedAetheriaPowder: return ClapPart.Red;
case IltInventory.WcidBlueAetheriaChunk:
case IltInventory.WcidBlueAetheriaPowder: return ClapPart.Blue;
case IltInventory.WcidEmpyreanTrinket: return ClapPart.Empyrean;
case IltInventory.WcidFalatacotTrinket: return ClapPart.Falatacot;
case 0: break;
default: return ClapPart.None;
}
if (name.Equals("Red Aetheria Chunk", StringComparison.OrdinalIgnoreCase)) return ClapPart.Red;
if (name.Equals("Blue Aetheria Chunk", StringComparison.OrdinalIgnoreCase)) return ClapPart.Blue;
if (name.Equals("Ancient Empyrean Trinket", StringComparison.OrdinalIgnoreCase)) return ClapPart.Empyrean;
if (name.Equals("Ancient Falatacot Trinket", StringComparison.OrdinalIgnoreCase)) return ClapPart.Falatacot;
return ClapPart.None;
}
/// <summary>
/// True when /clap has a pair to work with: red material and an Empyrean Trinket, or blue
/// material and a Falatacot Trinket. One side alone gets "You don't have any aetheria materials".
/// Pure: the tests drive it.
/// </summary>
internal static bool CanClap(IEnumerable<ClapPart> parts)
{
bool red = false, blue = false, empyrean = false, falatacot = false;
foreach (var part in parts)
{
switch (part)
{
case ClapPart.Red: red = true; break;
case ClapPart.Blue: blue = true; break;
case ClapPart.Empyrean: empyrean = true; break;
case ClapPart.Falatacot: falatacot = true; break;
}
}
return (red && empyrean) || (blue && falatacot);
}
private bool HasClapMaterials()
{
var inv = _ctx.Inventory;
return CanClap(inv.Items().Where(wo => !inv.IsEquipped(wo))
.Select(wo => ClapPartOf(inv.Wcid(wo), wo.Name, inv.Int(wo, IltInventory.IntItemMaxLevel))));
}
/// <summary>Sends "/clap all" through the capture queue (reply stays visible).</summary>
public void ClapNow(bool manual)
{
RynthLog.Trace(LogCat.IltGear, $"ClapNow(manual={manual})");
if (_ctx.Options.IsOff(IltFeature.Clap)) { _clapStatus = "/clap is not available (server or AutoCraftingEnabled stamp)"; return; }
if (_ctx.Capture.IsPending("/clap all")) return;
if (!manual && !HasClapMaterials()) { _clapStatus = "no aetheria and trinket pair carried (red + Empyrean, blue + Falatacot)"; return; }
_clapStatus = "sending /clap all...";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/clap all",
IsResponseLine = t => t.StartsWith("Deposited ", StringComparison.Ordinal)
|| t.StartsWith("[Clap]", StringComparison.OrdinalIgnoreCase)
|| t.Contains("aetheria materials", StringComparison.OrdinalIgnoreCase)
|| t.Contains("AutoCraftingEnabled", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 800,
FirstLineTimeoutMs = 10_000,
Eat = false,
OnComplete = r =>
{
if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Clap, IltTri.Off); _clapStatus = "/clap not available"; return; }
_clapStatus = r.Lines.Count > 0 ? r.Lines[^1] : "no reply";
if (r.Lines.Any(l => l.StartsWith("Deposited ", StringComparison.Ordinal))) _ctx.Options.Set(IltFeature.Clap, IltTri.On);
},
});
}
private void TickClap(long now)
{
// Automation only runs once the server has positively confirmed /clap (unknown = wait).
if (!G.AutoClap || !_ctx.Options.IsOn(IltFeature.Clap)) { _clapWasEnabled = false; return; }
if (!_clapWasEnabled)
{
_clapWasEnabled = true;
_nextClapAt = now + ClapFirstDelayMs;
_clapStatus = "first auto-clap in ~1 min";
return;
}
if (now < _nextClapAt) return;
long interval = Math.Max(5, G.ClapIntervalMinutes) * 60_000L;
_nextClapAt = now + interval + (long)((_rng.NextDouble() * 2 - 1) * ClapJitterMs);
ClapNow(manual: false);
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
TickChunk(nowMs);
TickClap(nowMs);
}
internal enum ChunkResult { None, Busy, Done, Refused }
/// <summary>Where a chunk in flight stands when no chat line has ended the wait.</summary>
internal enum ChunkWait { Waiting, Gone, TimedOut }
/// <summary>
/// The wait for a chunk with no result line yet. The hammer destroys the target, so a target
/// that has left the pack was chunked: ILT does not always send a line the classifier knows
/// (Silentkelpie 2026-10-18: a Red Aetheria Chunk arrived and UseDone had no error, yet the
/// item was still filed as skipped after 10 s). Still carried after the wait = timed out.
/// Pure: the tests drive it.
/// </summary>
internal static ChunkWait WaitOutcome(long elapsedMs, bool targetStillCarried)
=> !targetStillCarried ? ChunkWait.Gone
: elapsedMs >= ChunkResultWaitMs ? ChunkWait.TimedOut
: ChunkWait.Waiting;
/// <summary>
/// What a chat line says about the chunk in flight. ILT names the item and the tool ("You
/// smash the Corrupted Sword with the Lugian Aetheria Hammer."), so a line naming a corrupted
/// item with the hammer, powder or shatter is a result too (combat's "You smash Foo for 147"
/// names neither). Pure: the tests drive it.
/// </summary>
internal static ChunkResult ClassifyChat(string text)
{
if (text.StartsWith("You're too busy", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You are too busy", StringComparison.OrdinalIgnoreCase))
return ChunkResult.Busy;
if (ChunkRefusedLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase))) return ChunkResult.Refused;
if (ChunkDoneLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase))) return ChunkResult.Done;
if (text.Contains("corrupted", StringComparison.OrdinalIgnoreCase)
&& (text.Contains("hammer", StringComparison.OrdinalIgnoreCase) || text.Contains("powder", StringComparison.OrdinalIgnoreCase)
|| text.Contains("shatter", StringComparison.OrdinalIgnoreCase)))
return ChunkResult.Done;
return ChunkResult.None;
}
public bool OnChat(string text)
{
if (_waitingOn == 0) return false;
switch (ClassifyChat(text))
{
case ChunkResult.Busy:
_waitingOn = 0; // retry the same item next interval
break;
case ChunkResult.Done:
_chunked++;
_waitingOn = 0;
break;
case ChunkResult.Refused:
_skip.Add(_waitingOn);
_waitingOn = 0;
break;
}
return false;
}
public void OnLogout()
{
_waitingOn = 0;
_skip.Clear();
_lastSkip.Clear();
_manualPass = false;
_clapWasEnabled = false;
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
SafeImGui.TextColored(IltStyle.ColTeal, $"Chunking ({HammerName})");
bool a = G.AutoChunkAetheria, c = G.AutoChunkCorrupted, comb = G.ChunkInCombat;
if (ImGui.Checkbox("Auto-chunk low aetheria", ref a)) G.AutoChunkAetheria = a;
ImGui.SameLine();
if (ImGui.Checkbox("Auto-chunk corrupted weapons", ref c)) G.AutoChunkCorrupted = c;
if (ImGui.Checkbox("Allow while in combat mode", ref comb)) G.ChunkInCombat = comb;
int under = G.ChunkAetheriaUnderLevel;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Chunk aetheria with max level below", ref under)) G.ChunkAetheriaUnderLevel = ClampUnderLevel(under);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip($"Infinite Leaftide aetheria goes up to level {IltInventory.AetheriaMaxLevel}; {IltInventory.AetheriaMaxLevel + 1} chunks every level.\nA levelled Coalesced Aetheria gets the cap too; an unlevelled one (level 0 after appraisal) is chunked, as in ub-IT.");
bool kc = G.KeepAetheriaWithCrit, kcd = G.KeepAetheriaWithCritDamage, kcdr = G.KeepAetheriaWithCritDamageResist;
ImGui.TextUnformatted("Never chunk aetheria with:");
ImGui.SameLine();
if (ImGui.Checkbox("C##keepc", ref kc)) G.KeepAetheriaWithCrit = kc;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit rating (GearCrit).");
ImGui.SameLine();
if (ImGui.Checkbox("CD##keepcd", ref kcd)) G.KeepAetheriaWithCritDamage = kcd;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit Damage rating (GearCritDamage).");
ImGui.SameLine();
if (ImGui.Checkbox("CDR##keepcdr", ref kcdr)) G.KeepAetheriaWithCritDamageResist = kcdr;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit Damage Resist rating (GearCritDamageResist).");
int ratingAt = G.KeepAetheriaRatingAtLeast;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Keep when the rating is at least##keeprating", ref ratingAt)) G.KeepAetheriaRatingAtLeast = ClampRatingLevel(ratingAt);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Rating level for the C / CD / CDR switches above (Coalesced Aetheria and revealed aetheria).\n"
+ "At or above this level: kept. Below it: the rating does not protect the piece, so it chunks\n"
+ "if the level cap and the other rules allow. 1 = any rating keeps.");
if (ImGui.TreeNode("Corrupted weapon keep rules##corrkeep"))
{
// ub-IT IdleActs > Corr Chunk: each matching rule keeps the weapon.
bool cb = G.KeepCorruptedCrushingBlow, bs = G.KeepCorruptedBitingStrike, acl = G.KeepCorruptedArmorCleaving;
bool sl = G.KeepCorruptedAnySlayer, ms = G.KeepCorruptedMultiStrike, el = G.KeepCorruptedElementalBonus, sp = G.KeepCorruptedAnySpell;
if (ImGui.Checkbox("Crushing Blow##ck", ref cb)) G.KeepCorruptedCrushingBlow = cb;
ImGui.SameLine();
if (ImGui.Checkbox("Biting Strike##ck", ref bs)) G.KeepCorruptedBitingStrike = bs;
ImGui.SameLine();
if (ImGui.Checkbox("Armor Cleaving##ck", ref acl)) G.KeepCorruptedArmorCleaving = acl;
if (ImGui.Checkbox("Any slayer##ck", ref sl)) G.KeepCorruptedAnySlayer = sl;
ImGui.SameLine();
if (ImGui.Checkbox("Multi-strike##ck", ref ms)) G.KeepCorruptedMultiStrike = ms;
ImGui.SameLine();
if (ImGui.Checkbox("Elemental bonus##ck", ref el)) G.KeepCorruptedElementalBonus = el;
if (ImGui.Checkbox("Any spell##ck", ref sp)) G.KeepCorruptedAnySpell = sp;
int maxDmg = G.KeepCorruptedMaxDamageAtLeast;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Keep max damage at least (0 = off)##ck", ref maxDmg)) G.KeepCorruptedMaxDamageAtLeast = Math.Max(0, maxDmg);
string ids = G.KeepCorruptedSpellIds ?? "";
ImGui.SetNextItemWidth(220);
if (ImGui.InputText("Keep spell ids##ck", ref ids, 512)) G.KeepCorruptedSpellIds = ids;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Comma or space separated spell ids: a corrupted weapon carrying any of them is kept.");
SafeImGui.TextDisabled("Always kept: tinkered, imbued, no workmanship, cleave over 1 (2 on two-handed, non-thrust).");
ImGui.TreePop();
}
if (ImGui.Button("Chunk eligible items now...")) _ctx.Confirm("Chunk items",
"Run one chunk pass now on every eligible aetheria and corrupted weapon?\nChunked items are destroyed.",
ChunkNow, "Chunk");
SafeImGui.TextDisabled("Status: " + _chunkStatus);
ImGui.Separator();
ImGui.TextColored(IltStyle.ColTeal, "Clap (/clap all)");
if (_ctx.Options.IsOff(IltFeature.Clap))
{
ImGui.TextColored(IltStyle.ColTextMute, "Not available (server off or AutoCraftingEnabled stamp missing).");
return;
}
bool ac = G.AutoClap;
if (ImGui.Checkbox("Auto-clap periodically", ref ac)) G.AutoClap = ac;
int mins = G.ClapIntervalMinutes;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Interval (min)", ref mins)) G.ClapIntervalMinutes = Math.Max(5, mins);
if (ImGui.SmallButton("Clap now")) _ctx.Post(() => ClapNow(manual: true));
ImGui.SameLine();
SafeImGui.TextDisabled(_clapStatus);
}
}

View file

@ -0,0 +1,274 @@
// IltDynamicStampList.cs - Infinite Leaftide's Dynamic Stamps: the list (Resources\dynstamps.csv) and
// the rules that tell a stamp had from one missing. SilentKelpie's (RynthSuite PR 12, RynthOracle 0.6.0,
// ported by hand onto our lineage 2026-10-19), where the stamps were rows of RynthOracle's Quests list;
// moved here on 2026-10-21 with RynthOracle's other Infinite Leaftide parts (one server's features live
// in its server plugin). The page that shows them is IltDynamicStamps.cs.
// The flags come from /myquests through RynthOracle's parser (QuestFlags.cs, linked source).
// Pure: RynthILT.Tests covers it.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using RynthCore.Plugin.RynthOracle.Data;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>
/// One Infinite Leaftide Dynamic Stamp (dynstamps.csv): an NPC hand-in that puts a
/// "Dynamic_N_..." quest flag on the character. List from the players' "ExtraDyn" sheet
/// (10.13.2026, one sheet per area, the wiki's Dynamic Stamps page); NPCs that give no stamp
/// are left out. A stamp is a one-time flag: having it in /myquests means it's done.
/// </summary>
internal sealed class DynamicStamp
{
public string Area = "";
/// <summary>Where in the area (a town, a dungeon, coordinates), or "".</summary>
public string Place = "";
public string Npc = "";
/// <summary>What the NPC gives back (the sheet's "X gives you Y"), or "".</summary>
public string Reward = "";
/// <summary>The quest flag, lower case (as QuestFlagStore keys it).</summary>
public string Stamp = "";
public string Note = "";
/// <summary>The NPC, else the place (a few sheet rows only name the spot).</summary>
public string Label => Npc.Length > 0 ? Npc : Place;
/// <summary>
/// The flag this character has for the stamp, or null. The sheet has a few stamps copied
/// without their closing "!" or cut short: those also match with "!" added and, when at
/// least <see cref="MinPrefixLength"/> long, the one Dynamic flag on the character starting
/// with them.
/// </summary>
public string? MatchedFlag(QuestFlagStore flags)
{
if (flags.TryGet(Stamp, out _)) return Stamp;
if (Stamp.EndsWith('!')) return null;
if (flags.TryGet(Stamp + "!", out _)) return Stamp + "!";
if (Stamp.Length < MinPrefixLength) return null;
string? only = null;
foreach (string key in flags.Flags.Keys)
{
if (!key.StartsWith(Stamp, StringComparison.OrdinalIgnoreCase)) continue;
if (only != null) return null; // more than one: can't tell which
only = key;
}
return only;
}
public bool Have(QuestFlagStore flags) => MatchedFlag(flags) != null;
// Sheet areas that are groupings, not places on the map.
private static readonly HashSet<string> NotPlaces = new(StringComparer.OrdinalIgnoreCase)
{
"Looking Around", "Odd Stamps", "Odd Stamps 2",
};
/// <summary>
/// Where RynthNav should go for this stamp, best first (RynthNav takes the first that is on its
/// map): the coordinates in the note or the place, the place and its parts ("Mhoire Castle -
/// Great Hall" also tries "Mhoire Castle"), the NPC, then the area. Empty when there is nothing.
/// </summary>
public List<string> NavCandidates()
{
var list = new List<string>();
void Add(string s)
{
s = s.Trim().Trim('.', ',', ';', ':').Trim();
if (s.Length >= 4 && !char.IsDigit(s[0]) && !list.Contains(s, StringComparer.OrdinalIgnoreCase)) list.Add(s);
}
foreach (string text in new[] { Note, Place })
if (NavTargets.FirstCoords(text) is string c && !list.Contains(c)) list.Add(c);
string place = NavTargets.WithoutCoords(Place);
place = Regex.Replace(place, @"\b(at|in the|nearby)\b", " ", RegexOptions.IgnoreCase);
place = Regex.Replace(place, @"\s+", " ").Trim();
Add(place);
foreach (string part in place.Split(new[] { " - ", " / ", "(", ")" }, StringSplitOptions.RemoveEmptyEntries))
Add(part);
Add(Npc);
if (!NotPlaces.Contains(Area)) Add(Area);
return list;
}
/// <summary>A truncated stamp shorter than this is matched exactly only (too many flags share a short stem).</summary>
public const int MinPrefixLength = 14;
}
internal static class DynamicStampList
{
/// <summary>Dynamic stamp quest flags start with this (lower case).</summary>
public const string FlagPrefix = "dynamic_";
/// <summary>The embedded list's resource name (the csproj).</summary>
public const string ResourceName = "RynthILT.dynstamps.csv";
public static List<DynamicStamp> All { get; } = Load();
/// <summary>The areas in list order (Facility Hub, Looking Around, ...).</summary>
public static List<string> Areas { get; } = BuildAreas();
/// <summary>
/// Dynamic stamps on this character that the list doesn't have (new or unlisted NPCs), so the
/// page can show them and the count isn't only what the sheet knows.
/// </summary>
public static List<string> Unlisted(QuestFlagStore flags)
{
var matched = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (DynamicStamp s in All)
if (s.MatchedFlag(flags) is string f) matched.Add(f);
var extra = new List<string>();
foreach (string key in flags.Flags.Keys)
if (key.StartsWith(FlagPrefix, StringComparison.OrdinalIgnoreCase) && !matched.Contains(key))
extra.Add(key);
extra.Sort(StringComparer.OrdinalIgnoreCase);
return extra;
}
private static List<DynamicStamp> Load()
{
try
{
using Stream? stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(ResourceName);
if (stream == null) return new List<DynamicStamp>();
using var r = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
return Parse(r);
}
catch (Exception)
{
// A missing or unreadable list must not take the page down with it.
return new List<DynamicStamp>();
}
}
/// <summary>
/// Reads a dynstamps.csv (a header row, then one NPC hand-in a row). A row whose stamp isn't a
/// "dynamic_" flag, or repeats one already read, is skipped; a missing column reads as empty.
/// Internal for the tests.
/// </summary>
internal static List<DynamicStamp> Parse(TextReader r)
{
var list = new List<DynamicStamp>();
Dictionary<string, int> col = Csv.MapColumns(r.ReadLine() ?? "");
int cArea = Csv.Column(col, "Area"), cPlace = Csv.Column(col, "Place"), cNpc = Csv.Column(col, "Npc"),
cReward = Csv.Column(col, "Reward"), cStamp = Csv.Column(col, "Stamp"), cNote = Csv.Column(col, "Note");
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
while (r.ReadLine() is string line)
{
if (string.IsNullOrWhiteSpace(line)) continue;
string[] f = Csv.ParseLine(line);
string stamp = Csv.Field(f, cStamp).Trim().ToLowerInvariant();
if (!stamp.StartsWith(FlagPrefix, StringComparison.Ordinal) || !seen.Add(stamp)) continue;
list.Add(new DynamicStamp
{
Area = Csv.Field(f, cArea),
Place = Csv.Field(f, cPlace),
Npc = Csv.Field(f, cNpc),
Reward = Csv.Field(f, cReward),
Stamp = stamp,
Note = Csv.Field(f, cNote),
});
}
return list;
}
private static List<string> BuildAreas()
{
var areas = new List<string>();
foreach (DynamicStamp s in All)
if (!areas.Contains(s.Area)) areas.Add(s.Area);
return areas;
}
}
/// <summary>
/// What the Dynamic Stamps page lists and sends, worked out without the game (the page's buttons and
/// RynthILT.Tests use it): the rows with their status, the filters, RynthNav's line and the hand-in.
/// </summary>
internal static class DynamicStampText
{
/// <summary>One listed stamp and whether this character has it.</summary>
internal sealed record Row(DynamicStamp Stamp, bool Have);
/// <summary>The Show filter: every stamp, the missing ones, or the ones had.</summary>
internal enum Show { All, Missing, Have }
/// <summary>Every listed stamp, in list order, with its status from <paramref name="flags"/>.</summary>
public static List<Row> Rows(IReadOnlyList<DynamicStamp> stamps, QuestFlagStore flags)
{
var rows = new List<Row>(stamps.Count);
foreach (DynamicStamp s in stamps) rows.Add(new Row(s, s.Have(flags)));
return rows;
}
/// <summary>
/// The rows the page shows: in <paramref name="area"/> ("" = every area), matching
/// <paramref name="show"/>, and with every word of <paramref name="search"/> in the NPC, place,
/// reward, area, stamp or note (any case).
/// </summary>
public static List<Row> Filter(IReadOnlyList<Row> rows, string? search, string? area, Show show)
{
string[] terms = (search ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var shown = new List<Row>();
foreach (Row r in rows)
{
DynamicStamp s = r.Stamp;
if (!string.IsNullOrEmpty(area) && !string.Equals(s.Area, area, StringComparison.Ordinal)) continue;
if (show == Show.Missing && r.Have || show == Show.Have && !r.Have) continue;
string hay = $"{s.Npc} {s.Place} {s.Reward} {s.Area} {s.Stamp} {s.Note}";
bool all = true;
foreach (string t in terms)
if (hay.IndexOf(t, StringComparison.OrdinalIgnoreCase) < 0) { all = false; break; }
if (all) shown.Add(r);
}
return shown;
}
/// <summary>
/// "&lt;verb&gt; a || b || c" for RynthNav's "/rnav" (go walks the route, route plans it in chat,
/// arrow points at it; RynthNav takes the first candidate on its map), or "" when there is nowhere to go.
/// </summary>
public static string NavLine(string verb, DynamicStamp s)
{
List<string> targets = s.NavCandidates();
return targets.Count == 0 ? string.Empty : verb + " " + string.Join(" || ", targets);
}
/// <summary>A name made safe to put inside a chat command: no control characters.</summary>
public static string ForCommand(string name)
{
var sb = new StringBuilder(name.Length);
foreach (char ch in name) if (ch >= ' ' && ch != '\u007f') sb.Append(ch);
return sb.ToString().Trim();
}
/// <summary>"/ub give 1 &lt;parchment&gt; to &lt;npc&gt;": RynthAi finds the NPC by name and hands it over.</summary>
public static string GiveCommand(string parchment, string npc) => $"/ub give 1 {ForCommand(parchment)} to {ForCommand(npc)}";
/// <summary>True for RynthAi's answer to a "/ub give" it doesn't have.</summary>
public static bool IsGiveRejection(string? line) => line != null && line.IndexOf("Unrecognized /ub", StringComparison.OrdinalIgnoreCase) >= 0;
/// <summary>Why Give Parchment can't be used now (its tooltip); null when it can.</summary>
public static string? GiveUnavailableReason(bool rynthAiLoaded, bool giveMissing)
{
if (giveMissing)
return "The loaded RynthAi has no \"/ub give\" (it answered \"Unrecognized /ub command\"). Update RynthAi, or hand the Parchment over yourself.";
if (!rynthAiLoaded)
return "Needs RynthAi: the hand-in is RynthAi's \"/ub give\". It isn't loaded (or you aren't logged in), so give the Parchment to the NPC yourself.";
return null;
}
/// <summary>The chat lines for a stamp: the NPC, its stamp and whether this character has it, where, the reward and any coordinates.</summary>
public static List<string> PrintLines(DynamicStamp s, bool have)
{
string where = s.Place.Length > 0 ? $"{s.Area}, {s.Place}" : s.Area;
string details = where + (s.Reward.Length > 0 ? $" - gives {s.Reward}" : "") + (s.Note.Length > 0 ? $" - {s.Note}" : "");
var lines = new List<string> { $"{s.Label} ({s.Stamp}) - {(have ? "have" : "missing")}" };
if (details.Length > 0) lines.Add(details);
return lines;
}
}

View file

@ -0,0 +1,411 @@
// IltDynamicStamps.cs - The Dynamic Stamps page: Infinite Leaftide's NPC hand-ins that put a one-time
// "Dynamic_N_..." flag on the character, which of them this character has, RynthNav's way there and
// the Parchment hand-in. SilentKelpie's (RynthSuite PR 12, RynthOracle 0.6.0, ported by hand onto our
// lineage 2026-10-19), first as rows of RynthOracle's Quests list ("/ro dynamic"); moved here on
// 2026-10-21 as RynthILT's own page: the Mini Remote's Quests section ("Dynamic Stamps", surface
// "section:ilt-dynstamps") and its own window ("/ilt stamps"). The list and its rules are
// IltDynamicStampList.cs.
//
// Quest flags: RynthILT reads every /myquests reply that passes through chat (RynthOracle's at login,
// the player's, RynthAi's polls) with RynthOracle's /myquests parser (QuestFlags.cs, linked source).
// "Read quest flags" sends one of its own and hides that reply. Go / Route / Arrow ask RynthNav
// ("/rnav <verb> a || b"); Give Parchment hands one Parchment from the packs to the stamp's NPC through
// RynthAi's "/ub give" (asked first, disabled without RynthAi or when it answers "Unrecognized /ub
// command"), then the flags are read again once the NPC has had time to answer.
//
// Threads: OnChat / Tick on the pump (dormant off ILT, as every Hub feature); Render on the render
// thread, reading the pump's snapshot and posting its buttons (IltHubContext.Post / Confirm).
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading;
using ImGuiNET;
using RynthCore.Plugin.RynthOracle.Data;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltDynamicStamps : IIltFeature
{
/// <summary>The page counts as on screen this long after it was last drawn.</summary>
private const long WatchMs = 4000;
/// <summary>The packs are scanned for a Parchment at most this often while the page is on screen.</summary>
private const long ParchmentScanMs = 1500;
/// <summary>A /myquests read this long after a Parchment hand-in (the walk there and the NPC's answer).</summary>
internal const long HandInRefreshMs = 8000;
/// <summary>"Unrecognized /ub command" this soon after a give is the answer to it.</summary>
private const long GiveRejectionMs = 5000;
/// <summary>The RynthNav plugin and its command broker action.</summary>
private const string NavPlugin = "RynthNav", NavAction = "rnav";
private readonly IltHubContext _ctx;
private readonly QuestFlagStore _flags = new();
// Pump state.
private int _builtRevision = -1;
private string? _builtParchment;
private bool _builtGiveOk;
private long _parchmentScanAt;
private string? _parchment;
private long _refreshAt;
private long _giveSentAt = long.MinValue / 2;
private bool _giveMissing;
// Shared: the render thread's last draw, the pump's snapshot and the last action's outcome.
private long _watchedAt = long.MinValue / 2;
private volatile Snapshot _snap = Snapshot.Empty;
private volatile string _status = string.Empty;
// Render thread only: the filters and the opened stamp.
private string _search = string.Empty;
private int _area; // 0 = every area, else DynamicStampList.Areas[n - 1]
private int _show; // DynamicStampText.Show
private string _selected = string.Empty;
/// <summary>What the page draws, built on the pump.</summary>
internal sealed class Snapshot
{
public static readonly Snapshot Empty = new();
public bool Built;
public IReadOnlyList<DynamicStampText.Row> Rows = Array.Empty<DynamicStampText.Row>();
public IReadOnlyList<string> Unlisted = Array.Empty<string>();
public int Have;
public bool Loading, Disabled;
public DateTime LastReadUtc = DateTime.MinValue;
public long ThrottledUntilMs = long.MinValue / 2;
/// <summary>A Parchment carried (null = none).</summary>
public string? Parchment;
/// <summary>Why Give Parchment can't be used (null = it can).</summary>
public string? GiveReason;
}
public IltDynamicStamps(IltHubContext ctx) => _ctx = ctx;
/// <summary>The flags read from /myquests (tests read them).</summary>
internal QuestFlagStore Flags => _flags;
/// <summary>The last snapshot (tests).</summary>
internal Snapshot Current => _snap;
/// <summary>The last action's outcome ("" = none yet).</summary>
internal string Status => _status;
/// <summary>Render thread (or a test): the page is on screen, so the pump keeps its snapshot fresh.</summary>
internal void MarkWatched() => Interlocked.Exchange(ref _watchedAt, IltHubContext.NowMs);
/// <summary>AC's thread (the chat bar): a "/myquests" went out, RynthILT's own or typed. Only interlocked state.</summary>
public void NoteTypedMyQuests() => _flags.NoteTypedCommand();
// ── Pump ───────────────────────────────────────────────────────────────
public bool OnChat(string text)
{
long now = IltHubContext.NowMs;
if (now - _giveSentAt < GiveRejectionMs && !_giveMissing && DynamicStampText.IsGiveRejection(text))
{
_giveMissing = true;
_status = "RynthAi has no \"/ub give\": hand the Parchment over yourself.";
}
MyQuestsLine kind = _flags.OnChatLine(text, now);
// Only the reply to RynthILT's own request is hidden; the player's and other plugins' show as they would.
return _flags.AwaitingOurs && kind is MyQuestsLine.Quest or MyQuestsLine.Empty;
}
public void Tick(long nowMs)
{
_flags.Tick(nowMs);
RefreshAfterHandIn(nowMs);
if (nowMs - Interlocked.Read(ref _watchedAt) >= WatchMs) return;
if (_parchmentScanAt == 0 || nowMs - _parchmentScanAt >= ParchmentScanMs)
{
_parchmentScanAt = nowMs;
_parchment = CarriedParchment();
}
bool giveOk = DynamicStampText.GiveUnavailableReason(_ctx.Ai.Available, _giveMissing) == null;
if (_flags.Revision == _builtRevision && _parchment == _builtParchment && giveOk == _builtGiveOk && _snap.Built) return;
_builtRevision = _flags.Revision;
_builtParchment = _parchment;
_builtGiveOk = giveOk;
Rebuild();
}
/// <summary>The snapshot from the flags, the carried Parchment and RynthAi's state. Pump thread.</summary>
internal void Rebuild()
{
List<DynamicStampText.Row> rows = DynamicStampText.Rows(DynamicStampList.All, _flags);
int have = 0;
foreach (DynamicStampText.Row r in rows) if (r.Have) have++;
_snap = new Snapshot
{
Built = true,
Rows = rows,
Unlisted = DynamicStampList.Unlisted(_flags),
Have = have,
Loading = _flags.Loading,
Disabled = _flags.ServerDisabled,
LastReadUtc = _flags.LastReadUtc,
ThrottledUntilMs = _flags.ThrottledUntilMs,
Parchment = _parchment,
GiveReason = DynamicStampText.GiveUnavailableReason(_ctx.Ai.Available, _giveMissing),
};
}
public void OnLogout()
{
_flags.Clear();
_snap = Snapshot.Empty;
_builtRevision = -1;
_parchment = _builtParchment = null;
_parchmentScanAt = 0;
_refreshAt = 0;
_giveSentAt = long.MinValue / 2;
_giveMissing = false;
_status = string.Empty;
}
/// <summary>Sends /myquests (its reply hidden). Pump thread.</summary>
internal void RequestFlags()
{
long now = IltHubContext.NowMs;
if (_flags.Request(cmd => _ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser(cmd), now))
{
_status = "Reading your quest flags (/myquests)...";
return;
}
int wait = _flags.ThrottleSecondsLeft(now);
_status = wait > 0 ? $"The server answers one /myquests a minute; try again in {wait}s (the stamps shown are kept)."
: _flags.Loading ? "Your quest flags are already being read."
: "Your quest flags were asked for a moment ago; wait a few seconds.";
}
/// <summary>The read after a hand-in, when it is due: now, or when the server's once-a-minute wait ends.</summary>
private void RefreshAfterHandIn(long now)
{
if (_refreshAt == 0 || now < _refreshAt || _flags.Loading) return;
int wait = _flags.ThrottleSecondsLeft(now);
if (wait > 0) { _refreshAt = now + wait * 1000L; return; }
_refreshAt = 0;
_flags.Request(cmd => _ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser(cmd), now);
}
/// <summary>"/rnav &lt;verb&gt; a || b || c" to RynthNav. Pump thread.</summary>
internal void Nav(string verb, DynamicStamp s)
{
string line = DynamicStampText.NavLine(verb, s);
if (line.Length == 0) return;
bool sent = _ctx.Host.HasSendPluginCommand && _ctx.Host.SendPluginCommand(NavPlugin, NavAction, line);
_status = !sent ? "RynthNav isn't loaded (it plans and walks the route)."
: verb == "go" ? "RynthNav is planning the route and walking it (its chat lines say how)."
: verb == "arrow" ? "RynthNav's arrow points at it."
: "RynthNav's route is in chat. Go walks it.";
}
/// <summary>The stamp in chat (RynthChat makes coordinates a RynthNav arrow link). Pump thread.</summary>
internal void Print(DynamicStamp s)
{
bool have = s.Have(_flags);
foreach (string line in DynamicStampText.PrintLines(s, have)) _ctx.Chat("[ILT Stamps] " + line);
}
/// <summary>Hands one <paramref name="parchment"/> to the stamp's NPC (RynthAi's "/ub give"). Pump thread.</summary>
internal void Give(DynamicStamp s, string parchment)
{
string? why = DynamicStampText.GiveUnavailableReason(_ctx.Ai.Available, _giveMissing);
if (why != null) { _status = why; return; }
long now = IltHubContext.NowMs;
_giveSentAt = now; // an "Unrecognized /ub command" in the next moments turns the button off
bool sent = _ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser(DynamicStampText.GiveCommand(parchment, s.Npc));
_parchmentScanAt = 0; // read the packs again after the give
// The stamp is a quest flag: read /myquests again once the NPC has had time to answer.
if (sent) _refreshAt = now + HandInRefreshMs;
_status = sent
? $"Giving {parchment} to {s.Npc} (RynthAi does the give; it says so in chat if {s.Npc} isn't in sight)."
: "Could not send the give.";
}
/// <summary>
/// The name of a Parchment carried (the main pack and its side packs, one level deep as AC packs
/// go), or null: any item whose name has "Parchment" in it. Pump thread.
/// </summary>
private string? CarriedParchment()
{
var host = _ctx.Host;
uint me = host.GetPlayerId();
if (me == 0 || !host.HasGetContainerContents) return null;
var buf = new uint[512];
var packs = new List<uint> { me };
for (int p = 0; p < packs.Count && p < 16; p++)
{
int n = Math.Min(host.GetContainerContents(packs[p], buf), buf.Length);
for (int i = 0; i < n; i++)
{
uint id = buf[i];
if (!host.TryGetObjectName(id, out string name)) continue;
if (name.IndexOf("Parchment", StringComparison.OrdinalIgnoreCase) >= 0) return name;
if (p == 0) packs.Add(id);
}
}
return null;
}
// ── UI (render thread) ────────────────────────────────────────────────
private static readonly string[] ShowNames = { "Every stamp", "Missing", "Had" };
/// <summary>The page's body, into the current window (the Mini Remote's view or "/ilt stamps").</summary>
public void Render()
{
MarkWatched();
Snapshot s = _snap;
SafeImGui.TextColored(IltStyle.ColTeal, "Dynamic Stamps");
ImGui.SameLine();
ImGui.TextDisabled("one-time quest flags (Dynamic_1_...) from handing items to NPCs");
if (!s.Built)
{
ImGui.TextDisabled("Reading the list...");
return;
}
int listed = s.Rows.Count;
string bar = $"{s.Have} / {listed} listed stamps" + (s.Unlisted.Count > 0 ? $" (+{s.Unlisted.Count} not in the list)" : "");
ImGui.ProgressBar(listed == 0 ? 0f : (float)s.Have / listed, new Vector2(-1, 0), bar);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("List: the players' ExtraDyn sheet (10.13.2026). Click a stamp for RynthNav's route to it and the Parchment hand-in.");
long now = IltHubContext.NowMs;
if (s.Disabled) SafeImGui.TextColored(IltStyle.ColHp, "This server has /myquests turned off, so the stamps can't be read.");
else if (s.Loading) SafeImGui.TextColored(IltStyle.ColAmber, "Reading your quest flags...");
else if (s.LastReadUtc == DateTime.MinValue) ImGui.TextDisabled("Quest flags not read yet: press Read quest flags (or type /myquests).");
else SafeImGui.TextDisabled($"Quest flags read at {s.LastReadUtc.ToLocalTime():HH:mm}.");
if (ImGui.SmallButton("Read quest flags##dystamps")) _ctx.Post(RequestFlags);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Sends /myquests (the reply is hidden). The server answers one a minute.");
if (now < s.ThrottledUntilMs)
{
ImGui.SameLine();
SafeImGui.TextDisabled($"again in {(s.ThrottledUntilMs - now + 999) / 1000}s");
}
ImGui.SetNextItemWidth(180);
ImGui.InputText("Search##dystamps", ref _search, 64u);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Words to find: an NPC, place, area, reward, stamp or note.");
ImGui.SameLine();
var areas = new List<string>(DynamicStampList.Areas.Count + 1) { "Every area" };
areas.AddRange(DynamicStampList.Areas);
_area = Math.Clamp(_area, 0, areas.Count - 1);
ImGui.SetNextItemWidth(150);
ImGui.Combo("##dystamps.area", ref _area, areas.ToArray(), areas.Count);
ImGui.SameLine();
_show = Math.Clamp(_show, 0, ShowNames.Length - 1);
ImGui.SetNextItemWidth(110);
ImGui.Combo("##dystamps.show", ref _show, ShowNames, ShowNames.Length);
string? area = _area > 0 ? areas[_area] : null;
List<DynamicStampText.Row> rows = DynamicStampText.Filter(s.Rows, _search, area, (DynamicStampText.Show)_show);
SafeImGui.TextDisabled($"{rows.Count} shown");
DynamicStamp? open = null;
bool openHave = false;
float height = Math.Max(120f, ImGui.GetContentRegionAvail().Y - (_selected.Length > 0 ? 170f : 40f));
const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.ScrollY | ImGuiTableFlags.SizingStretchProp;
if (ImGui.BeginTable("##dystamps", 4, flags, new Vector2(0, height)))
{
ImGui.TableSetupScrollFreeze(0, 1);
ImGui.TableSetupColumn("##have", ImGuiTableColumnFlags.WidthFixed, 40);
ImGui.TableSetupColumn("NPC", ImGuiTableColumnFlags.None, 1.2f);
ImGui.TableSetupColumn("Area", ImGuiTableColumnFlags.None, 0.9f);
ImGui.TableSetupColumn("Place", ImGuiTableColumnFlags.None, 1.3f);
ImGui.TableHeadersRow();
for (int i = 0; i < rows.Count; i++)
{
DynamicStampText.Row r = rows[i];
DynamicStamp st = r.Stamp;
ImGui.TableNextRow();
ImGui.TableNextColumn();
SafeImGui.TextColored(r.Have ? IltStyle.ColGreen : IltStyle.ColHp, r.Have ? "have" : "need");
ImGui.TableNextColumn();
bool selected = _selected == st.Stamp;
if (ImGui.Selectable(Cut(st.Label, 40) + "##dy" + i, selected, ImGuiSelectableFlags.SpanAllColumns))
{
_selected = selected ? string.Empty : st.Stamp;
// As its Quests row did: picking a stamp asks RynthNav for the route at once.
if (!selected && st.NavCandidates().Count > 0) _ctx.Post(() => Nav("route", st));
}
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(Tooltip(st));
ImGui.TableNextColumn();
SafeImGui.TextDisabled(Cut(st.Area, 28));
ImGui.TableNextColumn();
SafeImGui.TextDisabled(Cut(st.Place, 40));
if (selected) { open = st; openHave = r.Have; }
}
ImGui.EndTable();
}
if (rows.Count == 0) ImGui.TextDisabled("No stamps match.");
if (_selected.Length > 0 && open == null)
foreach (DynamicStampText.Row r in s.Rows)
if (r.Stamp.Stamp == _selected) { open = r.Stamp; openHave = r.Have; break; }
if (open != null) RenderSelected(s, open, openHave);
if (s.Unlisted.Count > 0 && ImGui.CollapsingHeader($"On this character, not in the list ({s.Unlisted.Count})##dyunlisted"))
foreach (string f in s.Unlisted) SafeImGui.TextDisabled(f);
string status = _status;
if (status.Length > 0) SafeImGui.TextDisabled(status);
}
/// <summary>The opened stamp: where RynthNav goes, Go / Route / Arrow, Chat, and the Parchment hand-in.</summary>
private void RenderSelected(Snapshot s, DynamicStamp st, bool have)
{
List<string> targets = st.NavCandidates();
ImGui.SeparatorText("Navigate to " + Cut(st.Label, 40));
SafeImGui.TextDisabled(targets.Count == 0
? "No place, coordinates or area to go to for this stamp."
: "Where: " + Cut(string.Join(" or ", targets), 90));
if (targets.Count > 0)
{
if (ImGui.Button("Go (auto nav)##dynav")) _ctx.Post(() => Nav("go", st));
if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthNav plans the route (walking, portals, recalls, the dungeon's entrance) and walks it.");
ImGui.SameLine();
if (ImGui.Button("Route##dynav")) _ctx.Post(() => Nav("route", st));
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Only plan it: RynthNav prints the steps in chat.");
ImGui.SameLine();
if (ImGui.Button("Arrow##dynav")) _ctx.Post(() => Nav("arrow", st));
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Only point RynthNav's arrow at it.");
ImGui.SameLine();
}
if (ImGui.Button("Chat##dynav")) _ctx.Post(() => Print(st));
ImGui.SameLine();
if (ImGui.Button("Close##dynav")) _selected = string.Empty;
SafeImGui.TextColored(have ? IltStyle.ColGreen : IltStyle.ColAmber, have ? "You have this stamp." : "You don't have this stamp yet.");
// The hand-in: a Parchment from your packs to the stamp's NPC (RynthAi's /ub give), asked first.
if (st.Npc.Length == 0) return;
string? parchment = s.Parchment;
if (parchment == null)
{
SafeImGui.TextDisabled("No Parchment in your packs to give " + Cut(st.Npc, 30) + ".");
return;
}
if (s.GiveReason != null)
{
// Greyed text in place of the button, so it can't be clicked into a command nobody answers.
SafeImGui.TextDisabled("[Give " + Cut(parchment, 24) + "]");
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(s.GiveReason);
return;
}
if (ImGui.Button("Give " + Cut(parchment, 24).Replace("#", "") + "##dygive"))
_ctx.Confirm("Give Parchment", $"Give one {parchment} to {st.Npc}? It leaves your pack for good.", () => Give(st, parchment), "Give it");
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip($"Hands one {parchment} to {st.Npc} (it asks first). Stand near them (or Go first): AC walks you the last bit.");
}
/// <summary>A stamp's hover text: area, place, reward and note.</summary>
private static string Tooltip(DynamicStamp s)
{
var parts = new List<string>(4);
foreach (string p in new[] { s.Area, s.Place, s.Reward.Length > 0 ? "gives " + s.Reward : "", s.Note })
if (!string.IsNullOrWhiteSpace(p)) parts.Add(p);
return Cut(string.Join(" - ", parts), 300);
}
private static string Cut(string s, int max) => s.Length <= max ? s : s.Substring(0, Math.Max(0, max - 3)) + "...";
}

View file

@ -0,0 +1,265 @@
// IltEquipSuits.cs — UtilityBelt-style equipment profiles (.utl VTank loot files) (Gear tab, P2).
//
// A suit is a VTank loot profile: every carried wearable whose first matching rule is
// Keep belongs to the suit. Loading a suit:
// 1. dequip phase — equipped wearables NOT in the suit go to a pack with a free slot
// (IltObjects.FindPackFor; never into a full pack — that crashes the client);
// 2. equip phase — suit items that aren't worn are used (AC equips on use).
// One action per 100 ms tick and only while not busy. An item is abandoned after 15
// attempts; the whole load bails after 10 s with no progress.
// The profile is matched by RynthAi's VTank loot evaluator (RynthAi.Hub LootKeeps), so suits need
// RynthAi. Search order: RynthILT EquipProfiles\<char>, EquipProfiles, the same two in the RynthAi
// folder (where they lived before the move), then UB's equip folders.
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Install;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltEquipSuits : IIltFeature
{
private const int MaxAttemptsPerItem = 15;
private const long NoProgressBailMs = 10_000;
private const long StepMs = 100;
private readonly IltHubContext _ctx;
// Load job (pump thread)
private readonly Queue<int> _dequip = new();
private readonly Queue<int> _equip = new();
private readonly Dictionary<int, int> _attempts = new();
private bool _running;
private long _lastStep, _lastProgress;
private int _doneCount;
private volatile string _status = "idle";
// Render snapshots
private volatile string[] _profiles = Array.Empty<string>();
private volatile string[] _preview = Array.Empty<string>();
private int _selected;
public IltEquipSuits(IltHubContext ctx) => _ctx = ctx;
private static readonly AcObjectClass[] WearableClasses =
{
AcObjectClass.Armor, AcObjectClass.Clothing, AcObjectClass.Gem, AcObjectClass.Jewelry,
AcObjectClass.MeleeWeapon, AcObjectClass.MissileWeapon, AcObjectClass.WandStaffOrb,
};
// ── Profile discovery ───────────────────────────────────────────────────
private IEnumerable<string> SearchDirs()
{
foreach (string baseDir in new[] { IltHubStore.SharedRoot, RynthInstallPaths.RynthAiDir })
{
string root = Path.Combine(baseDir, "EquipProfiles");
if (_ctx.CharName.Length > 0) yield return Path.Combine(root, _ctx.CharName);
yield return root;
}
string ub = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Decal Plugins", "UtilityBelt");
string world = _ctx.Options.WorldName;
if (world.Length > 0 && _ctx.CharName.Length > 0) yield return Path.Combine(ub, world, _ctx.CharName, "equip");
if (world.Length > 0) yield return Path.Combine(ub, world, "equip");
yield return Path.Combine(ub, "equip");
}
/// <summary>All .utl profiles, first directory wins for duplicate names.</summary>
public List<(string Name, string Path)> ListProfiles()
{
var seen = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (string dir in SearchDirs())
{
try
{
if (!Directory.Exists(dir)) continue;
foreach (string f in Directory.GetFiles(dir, "*.utl"))
{
string n = Path.GetFileNameWithoutExtension(f);
if (!seen.ContainsKey(n)) seen[n] = f;
}
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltGear, ex, $"equip dir {dir}"); }
}
return seen.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase).Select(k => (k.Key, k.Value)).ToList();
}
private string? ResolveProfile(string? name)
{
if (string.IsNullOrWhiteSpace(name)) name = _ctx.CharName;
name = name!.Trim();
if (name.EndsWith(".utl", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
return ListProfiles().FirstOrDefault(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).Path;
}
/// <summary>Items the suit wants worn (first matching rule is Keep; RynthAi evaluates the profile).</summary>
private List<WorldObject>? SuitItems(string path, out string error)
{
error = string.Empty;
var candidates = new List<WorldObject>();
foreach (var wo in _ctx.Inventory.Items())
{
if (Array.IndexOf(WearableClasses, wo.ObjectClass) < 0) continue;
if (_ctx.Inventory.Int(wo, IltInventory.IntValidLocations) == 0) continue;
candidates.Add(wo);
}
uint[] ids = candidates.Select(w => unchecked((uint)w.Id)).ToArray();
if (!_ctx.Ai.LootKeeps(path, ids, out bool[] keep, out error)) return null;
var list = new List<WorldObject>();
for (int i = 0; i < candidates.Count; i++)
if (keep[i]) list.Add(candidates[i]);
return list;
}
// ── Commands (pump thread) ──────────────────────────────────────────────
public void RefreshProfileList() => _profiles = ListProfiles().Select(p => p.Name).ToArray();
/// <summary>Lists what a load would do without doing it. Returns lines (also shown in the UI).</summary>
public List<string> Test(string? name)
{
var lines = new List<string>();
string? path = ResolveProfile(name);
if (path == null) { lines.Add($"Profile not found: {name ?? _ctx.CharName}"); _preview = lines.ToArray(); return lines; }
var suit = SuitItems(path, out string err);
if (suit == null) { lines.Add(err); _preview = lines.ToArray(); return lines; }
var suitIds = suit.Select(s => s.Id).ToHashSet();
foreach (var wo in _ctx.Inventory.Items().Where(w => _ctx.Inventory.IsEquipped(w) && !suitIds.Contains(w.Id)
&& Array.IndexOf(WearableClasses, w.ObjectClass) >= 0))
lines.Add("dequip " + wo.Name);
foreach (var wo in suit.Where(w => !_ctx.Inventory.IsEquipped(w))) lines.Add("equip " + wo.Name);
if (lines.Count == 0) lines.Add("Already wearing this suit.");
_preview = lines.ToArray();
return lines;
}
/// <summary>Starts loading a suit.</summary>
public string Load(string? name)
{
RynthLog.Trace(LogCat.IltGear, $"Suits.Load(name='{name}')");
if (_running) return "A suit load is already running.";
if (!_ctx.Host.HasMoveItemInternal || !_ctx.Host.HasUseObject) return "Engine lacks MoveItemInternal/UseObject.";
string? path = ResolveProfile(name);
if (path == null) return $"Profile not found: {name ?? _ctx.CharName}";
var suit = SuitItems(path, out string err);
if (suit == null) return err;
var suitIds = suit.Select(s => s.Id).ToHashSet();
_dequip.Clear(); _equip.Clear(); _attempts.Clear();
foreach (var wo in _ctx.Inventory.Items().Where(w => _ctx.Inventory.IsEquipped(w) && !suitIds.Contains(w.Id)
&& Array.IndexOf(WearableClasses, w.ObjectClass) >= 0))
_dequip.Enqueue(wo.Id);
foreach (var wo in suit.Where(w => !_ctx.Inventory.IsEquipped(w))) _equip.Enqueue(wo.Id);
if (_dequip.Count + _equip.Count == 0) return "Already wearing this suit.";
_running = true;
_doneCount = 0;
_lastProgress = IltHubContext.NowMs;
_ctx.State.Gear.LastEquipProfile = Path.GetFileNameWithoutExtension(path);
_status = $"loading {Path.GetFileNameWithoutExtension(path)}: {_dequip.Count} off, {_equip.Count} on";
return _status;
}
public void Cancel(string why)
{
RynthLog.Trace(LogCat.IltGear, $"Suits.Cancel(why='{why}')");
_running = false;
_dequip.Clear();
_equip.Clear();
_status = why;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (!_running || nowMs - _lastStep < StepMs) return;
_lastStep = nowMs;
if (nowMs - _lastProgress > NoProgressBailMs) { Cancel($"no progress for 10 s - stopped ({_doneCount} done)"); return; }
if (_ctx.Inventory.IsBusy) return;
var cache = _ctx.Inventory.Cache;
if (cache == null) { Cancel("cache not ready"); return; }
// Dequip phase first so slots are free for the suit.
if (_dequip.Count > 0)
{
int id = _dequip.Peek();
var wo = cache[id];
if (wo == null || !_ctx.Inventory.IsEquipped(wo)) { _dequip.Dequeue(); Progress(nowMs); return; }
if (!Attempt(id)) { _dequip.Dequeue(); return; }
int pack = IltObjects.FindPackFor(_ctx.Host, cache, includeMainPack: true, requireFree: 1);
if (pack == 0) { Cancel("no free pack slot for dequipped items - stopped"); return; }
_ctx.Host.MoveItemInternal(unchecked((uint)id), unchecked((uint)pack), 0, Math.Max(1, _ctx.Inventory.StackSize(wo)));
return;
}
if (_equip.Count > 0)
{
int id = _equip.Peek();
var wo = cache[id];
if (wo == null || _ctx.Inventory.IsEquipped(wo)) { _equip.Dequeue(); Progress(nowMs); return; }
if (!Attempt(id)) { _equip.Dequeue(); return; }
_ctx.Inventory.Use(wo);
return;
}
_running = false;
_status = $"suit loaded ({_doneCount} changes)";
}
/// <summary>Counts an attempt; false once the item has used up its attempts.</summary>
private bool Attempt(int id)
{
int n = _attempts.TryGetValue(id, out int a) ? a + 1 : 1;
_attempts[id] = n;
return n <= MaxAttemptsPerItem;
}
private void Progress(long now)
{
_doneCount++;
_lastProgress = now;
}
public bool OnChat(string text) => false;
public void OnLogout() => Cancel("idle");
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
ImGui.TextColored(IltStyle.ColTeal, "Equipment suits (.utl)");
if (ImGui.SmallButton("Rescan profiles")) _ctx.Post(RefreshProfileList);
var profiles = _profiles;
if (profiles.Length == 0)
{
SafeImGui.TextDisabled($"No .utl files found ({System.IO.Path.Combine(IltHubStore.SharedRoot, "EquipProfiles")}, the RynthAi folder's EquipProfiles or UtilityBelt equip folders).");
}
else
{
_selected = Math.Clamp(_selected, 0, profiles.Length - 1);
ImGui.SetNextItemWidth(220);
ImGui.Combo("Suit", ref _selected, profiles, profiles.Length);
string pick = profiles[_selected];
ImGui.SameLine();
if (ImGui.SmallButton("Test")) _ctx.Post(() => Test(pick));
ImGui.SameLine();
if (ImGui.SmallButton("Load..."))
_ctx.Confirm("Load equipment suit", $"Swap to suit '{pick}'?\nItems not in the suit are moved to your packs.",
() => _ctx.Chat("[Mini Remote] " + Load(pick)), "Load");
if (_running)
{
ImGui.SameLine();
if (ImGui.SmallButton("Cancel")) _ctx.Post(() => Cancel("cancelled by player"));
}
}
SafeImGui.TextDisabled("Status: " + _status);
foreach (string l in _preview) SafeImGui.BulletText(l);
}
}

View file

@ -0,0 +1,362 @@
// IltFeatureCatalog.cs — Every Infinite Leaftide feature RynthILT supports, in one list.
//
// Each entry says what the feature is, where it lives in the Rynth tools, and how its state is
// known. Detection is client-side only: the server type comes from the login (the world name,
// RynthCore's "ilt" verdict), and the ILT profile below is the known set of what Infinite
// Leaftide runs, taken from ACECustom (its ServerConfig defaults and deploy/PROD_DEPLOY_PLAN.md,
// e.g. pet bond and potency on in prod, pet strain off since launch). The server is never asked
// for a list; what it returns on its own (probe replies, chat) refines the profile:
// * Profile (IltKnown.Profile): on in ILT (T11, split arrows, pet breeding, ...). On with the
// ILT world; a server refusal seen in chat turns it off.
// * Profile off (IltKnown.ProfileOff): an ACECustom option ILT runs with off (pet strain,
// defense scaling, the pyreal refill). Off with the ILT world; a chat line only the feature
// sends (e.g. a pyreal refill) turns it on.
// * Checked (IltKnown.Checked): the login probe answers it (/bank, /aug, /xp, /pets, ...).
// "checking" until the reply arrives, then on or off.
// * No server bit at all (the Temple guardians, Paragon gear): content, on with the ILT world.
// Off an ILT world nothing is claimed: every state is unknown.
// The list feeds the ILT settings window ("/ilt settings", IltSettingsView/) and "/ra hub features".
// Server facts copied from ACECustom: Fellowship.MaxFellows = 29 (Source/ACE.Server/Entity/
// Fellowship.cs), Zone Share (ZoneShareManager) and the fellowship luminance share.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One Leaftide feature: id, display text, where it lives, and the server bit that says whether it's on.</summary>
/// <param name="Key">Stable id.</param>
/// <param name="Label">Display name.</param>
/// <param name="Group">Character, Items, Fellowship or Activities (the list's sections).</param>
/// <param name="Where">Where the Rynth tools handle it.</param>
/// <param name="Description">One line on what the server does.</param>
/// <param name="ServerBit">The IltServerOptions key probes and chat refusals set; null = content built into ACECustom (on with the world).</param>
/// <param name="Known">How the state is known while the bit hasn't been set (see <see cref="IltKnown"/>).</param>
internal sealed record IltFeatureInfo(string Key, string Label, string Group, string Where, string Description, string? ServerBit,
IltKnown Known = IltKnown.Profile);
/// <summary>How a feature's state is known on an ILT world before (or without) a server answer.</summary>
internal enum IltKnown
{
/// <summary>On in ILT: on with the ILT world unless chat shows it off.</summary>
Profile,
/// <summary>The login probe answers it: "checking" until the reply arrives.</summary>
Checked,
/// <summary>Off in ILT: off with the ILT world unless chat shows it on.</summary>
ProfileOff,
}
/// <summary>The quest bonus list as the profile JSON carries it ("questBonus"), for RynthOracle's Quests tab.</summary>
/// <param name="Disabled">The server has /qb turned off.</param>
/// <param name="Generation">Bumped per parsed "/qb list"; 0 = not loaded this session.</param>
/// <param name="Count">The server's quest bonus count; -1 = unknown.</param>
/// <param name="Status">One line on the last request ("loading...", "12 completed, 3 incomplete", ...).</param>
/// <param name="Completed">Completed bonus flags, sorted.</param>
/// <param name="Incomplete">Incomplete bonus flags, sorted.</param>
internal sealed record IltQuestBonusInfo(bool Disabled, int Generation, long Count, string Status,
IReadOnlyList<string> Completed, IReadOnlyList<string> Incomplete);
internal static class IltFeatureCatalog
{
public const string GroupCharacter = "Character";
public const string GroupItems = "Items";
public const string GroupPets = "Pets";
public const string GroupFellowship = "Fellowship";
public const string GroupCombat = "Combat";
public const string GroupActivities = "Activities";
/// <summary>The section order of the list (ACECustom's "/ilt features" uses the same).</summary>
public static readonly string[] Groups = { GroupCharacter, GroupItems, GroupPets, GroupFellowship, GroupCombat, GroupActivities };
/// <summary>ACECustom's fellowship member limit (Fellowship.MaxFellows); retail is 9.</summary>
public const int IltFellowshipMax = 29;
/// <summary>A retail fellowship's member limit.</summary>
public const int RetailFellowshipMax = 9;
/// <summary>Every Leaftide feature RynthILT supports, in display order.</summary>
public static readonly IltFeatureInfo[] All =
{
// Character progression and money.
new("bank", "Banking", GroupCharacter, "Mini Remote > Banking tab; Remote tab bank line",
"Bank pyreals, luminance, keys and coins; deposit, withdraw and transfer (/bank).", IltFeature.Bank, IltKnown.Checked),
new("bank_notes", "Trade note banking", GroupCharacter, "Mini Remote > Banking tab (trade notes)",
"Deposit trade notes as pyreals, withdraw any note from I to MMD, transfer note value (/bank d n).", "bank_notes"),
new("guardian", "Guardian (infinite base attributes)", GroupCharacter, "Guardian panel (/rc guardian)",
"Temple of Enlightenment guardians raise base attributes past the retail cap.", null),
new("attributes", "Infinite raised attributes", GroupCharacter, "Skills > Progression > Attributes",
"Spend unassigned XP on attributes past the retail max (/xp, /attr).", IltFeature.Xp, IltKnown.Checked),
new("augmentations", "Infinite augmentations", GroupCharacter, "Skills > Progression > Augmentations",
"Luminance augmentations far past retail: Creature 6000, Item / Life / War / Void 4000 (/aug).", IltFeature.Aug, IltKnown.Checked),
new("aug_charms", "Augmentation counter charms", GroupCharacter, "Skills > Progression > Augmentations",
"Triune Weave and the school charms add to your aug counts past the purchase cap (/aug).", "aug_charms"),
new("enlightenment", "Enlightenment", GroupCharacter, "Skills > Progression > Enlightenment",
"Enlightenment tiers past retail, with medallions, sigils and crests (/enl).", IltFeature.Enl, IltKnown.Checked),
new("ilt_skills", "Spend XP and train skills in one go", GroupCharacter, "Chat: /ilt xp, /ilt train",
"Spends all unspent XP into trained skills, or trains every affordable skill, in priority order.", "ilt_skills"),
new("leaderboards", "Leaderboards", GroupCharacter, "Chat: /top",
"Server leaderboards: quest bonus, level, enlightenment, augs, bank, pets and more (/top).", "leaderboards"),
// Items, loot and crafting.
new("paragon_armor", "Paragon armor", GroupItems, "Item info (RynthAi): Paragon sets and levels",
"Paragon armor progression; the 50th Armor Paragon gates enlightenment past 300.", null),
new("paragon_weapons", "Paragon weapons", GroupItems, "Item info (RynthAi): Paragon sets and levels",
"Paragon weapon progression (Paragon Missile, Caster and Melee sets).", null),
new("paragon_jewelry", "Paragon jewelry", GroupItems, "Item info (RynthAi): Paragon sets and levels",
"Paragon jewelry progression; the 50th Paragon gates enlightenment past 150.", null),
new("t11", "T11 items", GroupItems, "Item info and loot rules (RynthAi, RynthCore Loot Editor)",
"Tier 11 to 25 gear (Zone Control tiers): tiers, gear grades, property slots and modifiers.", "t11"),
new("t11_scaling", "T11+ weapon scaling", GroupItems, "Item info (RynthAi)",
"T11+ weapons scale with your augs and have aug wield floors; from T16, charm counts too.", "t11_scaling"),
new("t11_craft_gate", "T11+ crafting rules (crafting uniqueness)", GroupItems, "Mini Remote > Gear tab",
"On T11+ items the server refuses an imbue or tink that would replace a better value, and limits materials per item type.",
"t11_craft_gate"),
new("split_arrows", "Split arrows", GroupItems, "Mini Remote > Gear > Split arrows",
"Missile weapons carry split arrows, added with White Quartz salvage.", "split_arrows"),
new("charms", "Charms", GroupItems, "Mini Remote > Charms tab",
"Registry charms and the Guardian Hand, with their toggles; each charm is listed in the Charms section.", "charms"),
new("clap", "Chunk clap (auto craft)", GroupItems, "Mini Remote > Gear tab",
"Turns aetheria, chunks and trinkets into banked enlightened coins (/clap all).", IltFeature.Clap, IltKnown.Checked),
// Pets.
new("pets", "Pet log", GroupPets, "Mini Remote > Pets tab", "Captured pets, registered with Professor Ruggan (/pets).", IltFeature.Pets, IltKnown.Checked),
new("shinies", "Shiny log", GroupPets, "Mini Remote > Pets tab", "Rare shiny creature variants you captured (/shinies).", IltFeature.Shinies, IltKnown.Checked),
new("monster_capture", "Monster capture", GroupPets, "Mini Remote > Pets tab",
"Siphon lenses capture a creature\'s look into a pet essence (<=20% health or under 20 HP; Asheron\'s Lens skips the gate). Auto-capture is the checkbox on the Pets roster.", "monster_capture"),
new("pet_breeding", "Pet breeding", GroupPets, "Mini Remote > Pets > Breeding",
"Breed two combat pet devices at the Seedy Motel for inherited and mutated offspring (/dance).", "pet_breeding"),
new("pet_maturity", "Pet maturity", GroupPets, "Mini Remote > Pets > Breeding",
"Bred pets start small and weak and grow up with kills.", "pet_maturity"),
new("pet_bond", "Pet bond", GroupPets, "Mini Remote > Pets tab",
"Pets gain bond XP from kills, which scales their stats (/top bonds). On in ILT (breeding needs bond 100).", IltFeature.PetBond),
new("pet_potency", "Pet potency", GroupPets, "Mini Remote > Pets tab",
"Savage Echo residue raises a pet's potency (/echo-notify). On in ILT.", IltFeature.PetPotency),
new("pet_strain", "Pet strain", GroupPets, "Mini Remote > Pets tab",
"High pet potency lowers the owner's damage rating. Off in ILT since launch.", "pet_strain", IltKnown.ProfileOff),
new("pet_refill", "Summon essence refill", GroupPets, "Mini Remote > Pets tab",
"Pays pyreals to refill an empty essence when you summon (needs its charm). Off by default; a refill message in chat shows it on.", IltFeature.PetRefill, IltKnown.ProfileOff),
new("universal_mastery", "Universal summoning mastery", GroupPets, "Mini Remote > Pets tab",
"Use pet essences of any summoning mastery (needs its charm).", IltFeature.UniversalMastery),
new("pet_naming", "Pet names", GroupPets, "Chat: /pet-name",
"Ask for a name for your pet; staff approve it (/pet-name).", "pet_naming"),
// Fellowship.
new("fellowship_large", "Large fellowships (up to 29)", GroupFellowship, "The game's fellowship panel",
"Fellowships hold up to 29 members instead of retail's 9.", "fellowship_size"),
new("fship", "Fellowship commands", GroupFellowship, "ILT fellowship window (/ilt fellow)",
"Create, invite, invite your landblock, list nearby, leave and disband from chat (/fship).", "fship"),
new("zone_share", "Zone Share", GroupFellowship, "Mini Remote > Session Stats (luminance, pass-up)",
"XP and luminance shared with everyone in a Zone Share area, capped at a fellowship's size.", "zone_share"),
new("fellowship_luminance", "Fellowship luminance share", GroupFellowship, "Mini Remote > Session Stats (luminance, pass-up)",
"Luminance splits among fellows the way XP does.", "fellowship_luminance"),
new("fellowship_blackjack", "Fellowship Blackjack", GroupFellowship, "Mini Remote > Games tab",
"Blackjack played as a fellowship (/fblackjack).", IltFeature.FBlackjack, IltKnown.Checked),
// Combat.
new("smart_ring", "Smart ring spells", GroupCombat, "Chat: /ilt smartring",
"Ring spells hit everything in their radius, with double and triple procs (/ilt smartring on|off).", "smart_ring"),
new("dmgformat", "Damage number format", GroupCombat, "Chat: /ilt dmgformat",
"Damage shown plain, with commas, or short (K/M/B) (/ilt dmgformat).", "dmgformat"),
new("overkill", "Overkill on kill messages", GroupCombat, "Chat: /ilt showoverkill",
"Kill and death messages show the overkill amount (/ilt showoverkill).", "overkill"),
new("missile_power", "Missile power bar damage", GroupCombat, "Combat",
"The missile accuracy bar scales damage from 1x to 2.5x.", "missile_power"),
new("t11_hit_gate", "T11+ hit gate", GroupCombat, "Combat",
"Attacks on v11+ monsters miss unless your aug counts meet that tier's requirement.", "t11_hit_gate"),
new("v11_endgame", "v11+ endgame scaling", GroupCombat, "Combat",
"Percent-of-max-HP damage, compressed vulnerabilities and tougher v11+ monsters.", "v11_endgame"),
new("defense_scaling", "Defense scaling", GroupCombat, "Combat",
"Curbs extreme evasion at very high defense skill. Off by default in ACECustom.", "defense_scaling", IltKnown.ProfileOff),
// Activities.
new("quests", "Quest tracker", GroupActivities, "Mini Remote > Quests tab",
"Your quest timers from the server (/myquests).", IltFeature.Quests, IltKnown.Checked),
new("quest_bonus", "Quest bonus", GroupActivities, "Mini Remote > Quests tab (quest bonus)",
"Each quest completed adds to your XP bonus; the list (/qb).", IltFeature.Qb, IltKnown.Checked),
new("bounties", "Bounties", GroupActivities, "Bounties window (/rc bounties)", "ACECustom bounties and your progress.", "bounties"),
new("rifts", "Greater Rifts", GroupActivities, "Chat: /rift", "Private, timed dungeon runs that scale by tier (/rift).", "rifts"),
new("room_assign", "Room Assign dungeons", GroupActivities, "Portals and recalls",
"One-player rooms with their own spawns.", "room_assign"),
new("portal_requirements", "Aug / ENL / QB portals", GroupActivities, "Portals",
"Portals that need augmentations, an enlightenment level or a quest bonus.", "portal_requirements"),
new("powerball", "Powerball", GroupActivities, "Mini Remote > Games tab", "The Powerball lottery (/pb).", IltFeature.Powerball, IltKnown.Checked),
new("blackjack", "Blackjack", GroupActivities, "Mini Remote > Games tab", "Blackjack against the house (/blackjack).", IltFeature.Blackjack, IltKnown.Checked),
new("unstuck", "Unstuck", GroupActivities, "Chat: /unstuck", "Gets you out of a stuck portal or spot (/unstuck).", "unstuck"),
};
/// <summary>The entry with <paramref name="key"/>, or null.</summary>
public static IltFeatureInfo? Find(string key)
{
foreach (IltFeatureInfo f in All)
if (f.Key.Equals(key, StringComparison.OrdinalIgnoreCase)) return f;
return null;
}
/// <summary>
/// A feature's state on an ILT world: what the server returned (a probe reply or a refusal in
/// chat) when it did; else the ILT profile: On for content and <see cref="IltKnown.Profile"/>,
/// Off for <see cref="IltKnown.ProfileOff"/>, Unknown ("checking") for probed features.
/// Off ILT nothing is claimed: Unknown.
/// </summary>
public static IltTri StateOf(IltFeatureInfo f, bool iltWorld, Func<string, IltTri> bit)
{
if (!iltWorld) return IltTri.Unknown;
if (f.ServerBit == null) return IltTri.On;
IltTri reported = bit(f.ServerBit);
if (reported != IltTri.Unknown) return reported;
return f.Known switch
{
IltKnown.Profile => IltTri.On,
IltKnown.ProfileOff => IltTri.Off,
_ => IltTri.Unknown,
};
}
/// <summary>
/// A charm's state: charms are part of the ILT profile, so on with the ILT world unless the
/// server refused one in chat (e.g. "Auto-Rebuff Charm is currently disabled globally").
/// </summary>
public static IltTri CharmStateOf(bool iltWorld, IltTri reported)
=> !iltWorld ? IltTri.Unknown : reported != IltTri.Unknown ? reported : IltTri.On;
/// <summary>Prefix of a charm's server key (IltFeature.Charm): "charm:manabarrier".</summary>
public const string CharmKeyPrefix = "charm:";
/// <summary>
/// Display text for a key the settings view lists: a catalog feature (its label, group and
/// description with where it lives and how its state is known), a charm ("charm:..." under
/// Charms, named from the charm registry), or any other server bit as itself under "Other".
/// </summary>
public static (string Label, string Group, string Tooltip) Describe(string key)
{
IltFeatureInfo? f = Find(key);
if (f != null) return (f.Label, f.Group, f.Description + "\nWhere: " + f.Where + "\n" + HowKnown(f));
if (key.StartsWith(CharmKeyPrefix, StringComparison.OrdinalIgnoreCase))
{
const string charmNote = "Part of ILT: on unless the server refuses it in chat.";
foreach (IltCharmDef def in IltInventory.Charms)
if (IltFeature.Charm(def.Name).Equals(key, StringComparison.OrdinalIgnoreCase))
return (def.Name, GroupCharms, (def.Effect.Length > 0 ? def.Effect + "\n" : string.Empty)
+ "Where: Mini Remote > Charms tab\n" + charmNote);
return (key.Substring(CharmKeyPrefix.Length), GroupCharms, charmNote);
}
return (key, GroupOther, "A server switch RynthILT reads from chat.");
}
/// <summary>One line on where a feature's state comes from (tooltips).</summary>
private static string HowKnown(IltFeatureInfo f) => f.ServerBit == null
? "Built into ILT: on with the world."
: f.Known switch
{
IltKnown.Checked => "Checked at login: the server's reply decides.",
IltKnown.ProfileOff => "Off in ILT: on only if the server shows it in chat.",
_ => "Part of ILT: on unless the server refuses it in chat.",
};
/// <summary>The settings view's extra sections after <see cref="Groups"/>.</summary>
public const string GroupCharms = "Charms";
public const string GroupOther = "Other";
/// <summary>Short state text for the list and chat: "on", "off" or "checking".</summary>
public static string StateText(IltTri state) => state switch
{
IltTri.On => "on",
IltTri.Off => "off",
_ => "checking",
};
/// <summary>The fellowship member limit: ACECustom's 29 on an ILT world, retail's 9 elsewhere.</summary>
public static int FellowshipMax(bool iltWorld) => iltWorld ? IltFellowshipMax : RetailFellowshipMax;
/// <summary>
/// The "RynthILT.Server" profile JSON (schema in Plugins/Shared/RynthIltServerApi.cs). Pure:
/// everything comes in as arguments, so the tests build it without a client. Plain ASCII.
/// </summary>
public static string BuildProfileJson(bool iltWorld, string world, bool forced, string source, DateTime checkedUtc,
Func<string, IltTri> bit, IltQuestBonusInfo? questBonus = null)
{
var sb = new StringBuilder(4096);
sb.Append("{\"ilt\":").Append(iltWorld ? "true" : "false");
sb.Append(",\"world\":\"").Append(Escape(world)).Append('"');
sb.Append(",\"forced\":").Append(forced ? "true" : "false");
sb.Append(",\"source\":\"").Append(Escape(source)).Append('"');
sb.Append(",\"checked\":\"")
.Append(checkedUtc == DateTime.MinValue ? "" : checkedUtc.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture))
.Append('"');
sb.Append(",\"features\":[");
for (int i = 0; i < All.Length; i++)
{
IltFeatureInfo f = All[i];
if (i > 0) sb.Append(',');
sb.Append("{\"key\":\"").Append(Escape(f.Key))
.Append("\",\"label\":\"").Append(Escape(f.Label))
.Append("\",\"group\":\"").Append(Escape(f.Group))
.Append("\",\"state\":").Append(((int)StateOf(f, iltWorld, bit)).ToString(CultureInfo.InvariantCulture))
.Append(",\"where\":\"").Append(Escape(f.Where)).Append("\"}");
}
sb.Append(']');
int State(string key) => (int)StateOf(Find(key)!, iltWorld, bit);
sb.Append(",\"fellowship\":{\"maxMembers\":").Append(FellowshipMax(iltWorld).ToString(CultureInfo.InvariantCulture))
.Append(",\"zoneShare\":").Append(State("zone_share").ToString(CultureInfo.InvariantCulture))
.Append(",\"blackjack\":").Append(State("fellowship_blackjack").ToString(CultureInfo.InvariantCulture))
.Append(",\"luminanceShare\":").Append(State("fellowship_luminance").ToString(CultureInfo.InvariantCulture))
.Append('}');
// The /qb list (ILT worlds only): RynthOracle's Quests tab draws it.
if (questBonus != null && iltWorld)
{
sb.Append(",\"questBonus\":{\"disabled\":").Append(questBonus.Disabled ? "true" : "false")
.Append(",\"generation\":").Append(questBonus.Generation.ToString(CultureInfo.InvariantCulture))
.Append(",\"count\":").Append(questBonus.Count.ToString(CultureInfo.InvariantCulture))
.Append(",\"status\":\"").Append(Escape(questBonus.Status)).Append('"');
AppendList(sb, "completed", questBonus.Completed);
AppendList(sb, "incomplete", questBonus.Incomplete);
sb.Append('}');
}
sb.Append('}');
return sb.ToString();
static void AppendList(StringBuilder b, string name, IReadOnlyList<string> items)
{
b.Append(",\"").Append(name).Append("\":[");
for (int i = 0; i < items.Count; i++)
{
if (i > 0) b.Append(',');
b.Append('"').Append(Escape(items[i])).Append('"');
}
b.Append(']');
}
}
/// <summary>JSON string body: quotes, backslashes and control characters escaped, anything non-ASCII as \uXXXX.</summary>
private static string Escape(string? s)
{
if (string.IsNullOrEmpty(s)) return string.Empty;
var sb = new StringBuilder(s.Length + 8);
foreach (char c in s)
{
if (c == '"') sb.Append("\\\"");
else if (c == '\\') sb.Append("\\\\");
else if (c < 0x20 || c > 0x7E) sb.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
else sb.Append(c);
}
return sb.ToString();
}
/// <summary>The chat listing for "/ra hub features": one line per feature, ASCII only.</summary>
public static List<string> BuildChatLines(bool iltWorld, Func<string, IltTri> bit)
{
var lines = new List<string>(All.Length + Groups.Length);
foreach (string g in Groups)
{
var parts = new List<string>();
foreach (IltFeatureInfo f in All)
if (f.Group == g) parts.Add($"{f.Label} [{StateText(StateOf(f, iltWorld, bit))}]");
lines.Add($"{g}: {string.Join(", ", parts)}");
}
return lines;
}
}

View file

@ -0,0 +1,255 @@
// IltGames.cs — ILT Hub "Games" tab + hand HUD (P2): Blackjack, Fellowship Blackjack, Powerball.
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Every bet / ticket purchase spends banked luminance, so each one needs a confirm.
// Blackjack is commented out on the current ACECustom build ("Unknown command:
// blackjack"); the pad only appears when the login probe found the command.
// /blackjack <bet>, /hit, /stand, /double, /split (fellowship: /fblackjack, /fhit, ...; max 100B)
// /pb (info), /pb buy <1-500>, /pb tickets
// The HUD is a small always-on-top window shown while a hand is in progress.
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltGames : IIltFeature
{
private const long FBlackjackMaxBet = 100_000_000_000;
private static readonly Regex Dealt = new(@"^You were dealt (?:a |an )?(?<card>.+?)\.$", RegexOptions.Compiled);
private static readonly Regex MyValue = new(@"Your (?:initial )?hand value is (?:now )?(?<v>\d+)", RegexOptions.Compiled);
private static readonly Regex DealerValue = new(@"Rand's (?:current )?hand value is (?<v>\d+)", RegexOptions.Compiled);
private readonly IltHubContext _ctx;
// Hand state (pump thread writes, render thread reads — simple fields / snapshot list)
private volatile bool _handActive;
private volatile bool _fellowshipHand;
private volatile string[] _cards = Array.Empty<string>();
private volatile int _myValue, _dealerValue;
private volatile string _lastResult = string.Empty;
// Powerball info
private volatile string _pbDraw = string.Empty, _pbJackpot = string.Empty, _pbPrice = string.Empty, _pbStatus = string.Empty;
// Render-thread input
private string _bjBetText = string.Empty, _fbjBetText = string.Empty;
public IltGames(IltHubContext ctx) => _ctx = ctx;
private IltGamesState S => _ctx.State.Games;
public bool AnyGameAvailable => _ctx.Options.IsOn(IltFeature.Blackjack) || _ctx.Options.IsOn(IltFeature.FBlackjack)
|| !_ctx.Options.IsOff(IltFeature.Powerball);
// ── Commands (pump thread) ──────────────────────────────────────────────
private void Send(string cmd)
{
if (_ctx.Host.HasInvokeChatParser) _ctx.Host.InvokeChatParser(cmd);
}
private void StartBlackjack(bool fellowship, long bet)
{
_fellowshipHand = fellowship;
_cards = Array.Empty<string>();
_myValue = _dealerValue = 0;
_lastResult = string.Empty;
Send($"/{(fellowship ? "fblackjack" : "blackjack")} {bet}");
}
private void HandAction(string verb) => Send("/" + (_fellowshipHand ? "f" : "") + verb);
public void RequestPowerballInfo()
{
RynthLog.Trace(LogCat.IltGames, $"RequestPowerballInfo()");
if (_ctx.Options.IsOff(IltFeature.Powerball) || _ctx.Capture.IsPending("/pb")) return;
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/pb",
IsResponseLine = t => t.StartsWith("[Powerball]", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("Draw #", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("Jackpot Pool", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("Ticket Price", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 1200,
FirstLineTimeoutMs = 8000,
Eat = true,
OnComplete = r =>
{
if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Powerball, IltTri.Off); return; }
if (r.Lines.Count > 0) _ctx.Options.Set(IltFeature.Powerball, IltTri.On);
foreach (string l in r.Lines) ParsePowerball(l);
RynthLog.Trace(LogCat.IltGames, $"/pb info: {r.Lines.Count} line(s), timedOut={r.TimedOut}");
_pbStatus = r.Lines.Count > 0 ? "updated " + DateTime.Now.ToString("t") : "no reply";
},
});
}
private void ParsePowerball(string l)
{
string t = l.Trim();
if (t.StartsWith("Draw #", StringComparison.OrdinalIgnoreCase)) _pbDraw = t;
else if (t.StartsWith("Jackpot Pool", StringComparison.OrdinalIgnoreCase)) _pbJackpot = t;
else if (t.StartsWith("Ticket Price", StringComparison.OrdinalIgnoreCase)) _pbPrice = t;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs) { }
public bool OnChat(string text)
{
// Powerball lines typed by the player still update the panel.
if (text.StartsWith("[Powerball]", StringComparison.OrdinalIgnoreCase))
{
if (text.Contains("You bought", StringComparison.OrdinalIgnoreCase) || text.Contains("Insufficient", StringComparison.OrdinalIgnoreCase))
_pbStatus = text;
return false;
}
string t = text.Trim();
if (t.StartsWith("Draw #", StringComparison.OrdinalIgnoreCase) || t.StartsWith("Jackpot Pool", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("Ticket Price", StringComparison.OrdinalIgnoreCase))
{
ParsePowerball(t);
return false;
}
// Blackjack
var d = Dealt.Match(text);
if (d.Success)
{
var list = new List<string>(_cards) { d.Groups["card"].Value };
_cards = list.ToArray();
_handActive = true;
return false;
}
var mv = MyValue.Match(text);
if (mv.Success) { _myValue = int.Parse(mv.Groups["v"].Value); _handActive = true; }
var dv = DealerValue.Match(text);
if (dv.Success) _dealerValue = int.Parse(dv.Groups["v"].Value);
if (text.StartsWith("The game begins!", StringComparison.OrdinalIgnoreCase)) _handActive = true;
if (text.StartsWith("Blackjack! You win", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You won with", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("You tied with Rand", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You lost with", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("You busted", StringComparison.OrdinalIgnoreCase))
_lastResult = text;
if (text.StartsWith("The blackjack game has ended", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("You are not currently in a blackjack game", StringComparison.OrdinalIgnoreCase))
_handActive = false;
if (text.StartsWith("You don't have enough luminance to place this bet", StringComparison.OrdinalIgnoreCase))
{
_lastResult = text;
_handActive = false;
}
return false;
}
public void OnLogout()
{
_handActive = false;
_cards = Array.Empty<string>();
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
bool bj = _ctx.Options.IsOn(IltFeature.Blackjack), fbj = _ctx.Options.IsOn(IltFeature.FBlackjack);
if (!bj && !fbj && _ctx.Options.IsOff(IltFeature.Powerball))
{
ImGui.TextColored(IltStyle.ColTextMute, "No games are enabled on this server.");
return;
}
bool hud = _ctx.State.GamesHudVisible;
if (ImGui.Checkbox("Show hand HUD while playing", ref hud)) _ctx.State.GamesHudVisible = hud;
if (bj && ImGui.CollapsingHeader("Blackjack", ImGuiTreeNodeFlags.DefaultOpen)) RenderBlackjack(false, ref _bjBetText);
if (fbj && ImGui.CollapsingHeader("Fellowship Blackjack", ImGuiTreeNodeFlags.DefaultOpen)) RenderBlackjack(true, ref _fbjBetText);
if (!bj && !fbj) ImGui.TextDisabled("Blackjack is not enabled on this server.");
if (!_ctx.Options.IsOff(IltFeature.Powerball) && ImGui.CollapsingHeader("Powerball", ImGuiTreeNodeFlags.DefaultOpen)) RenderPowerball();
}
private void RenderBlackjack(bool fellowship, ref string betText)
{
string id = fellowship ? "fbj" : "bj";
if (betText.Length == 0) betText = IltParse.Compact(fellowship ? S.FellowshipBlackjackBet : S.BlackjackBet).ToLowerInvariant();
ImGui.SetNextItemWidth(160);
ImGui.InputTextWithHint($"Bet (luminance)##{id}", "e.g. 1m, 500k", ref betText, 24u);
bool ok = IltParse.TryParseAmount(betText, out long bet) && (!fellowship || bet <= FBlackjackMaxBet);
ImGui.SameLine();
SafeImGui.TextDisabled(ok ? IltParse.N0(bet) : fellowship ? "invalid (max 100B)" : "invalid");
ImGui.BeginDisabled(!ok || _handActive);
if (ImGui.Button($"Deal...##{id}"))
{
long b = bet;
if (fellowship) S.FellowshipBlackjackBet = b; else S.BlackjackBet = b;
_ctx.Confirm(fellowship ? "Fellowship Blackjack" : "Blackjack",
$"Bet {IltParse.N0(b)} banked luminance on a new hand?", () => StartBlackjack(fellowship, b), "Bet");
}
ImGui.EndDisabled();
if (_handActive && _fellowshipHand == fellowship) RenderHandButtons(id);
if (_lastResult.Length > 0 && _fellowshipHand == fellowship) SafeImGui.TextWrapped(_lastResult);
}
private void RenderHandButtons(string id)
{
ImGui.TextUnformatted($"Hand: {string.Join(", ", _cards)} ({_myValue}) Rand: {(_dealerValue > 0 ? _dealerValue.ToString() : "?")}");
if (ImGui.Button($"Hit##{id}")) _ctx.Post(() => HandAction("hit"));
ImGui.SameLine();
if (ImGui.Button($"Stand##{id}")) _ctx.Post(() => HandAction("stand"));
ImGui.SameLine();
if (ImGui.Button($"Double...##{id}"))
_ctx.Confirm("Double down", "Double your bet on this hand?", () => HandAction("double"), "Double");
ImGui.SameLine();
if (ImGui.Button($"Split...##{id}"))
_ctx.Confirm("Split", "Split this hand (places a second bet)?", () => HandAction("split"), "Split");
}
private void RenderPowerball()
{
if (ImGui.SmallButton("Refresh##pb")) _ctx.Post(RequestPowerballInfo);
ImGui.SameLine();
if (ImGui.SmallButton("My tickets")) _ctx.Post(() => Send("/pb tickets"));
if (_pbDraw.Length > 0) ImGui.TextUnformatted(_pbDraw);
if (_pbJackpot.Length > 0) ImGui.TextUnformatted(_pbJackpot);
if (_pbPrice.Length > 0) ImGui.TextUnformatted(_pbPrice);
// Buying spends banked luminance, so it needs a positive server confirmation of /pb.
if (!_ctx.Options.IsOn(IltFeature.Powerball))
{
ImGui.TextDisabled("Ticket purchases unlock once the server confirms /pb (press Refresh).");
if (_pbStatus.Length > 0) SafeImGui.TextWrapped(_pbStatus);
return;
}
int qty = S.PowerballQuantity;
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Tickets", ref qty)) S.PowerballQuantity = Math.Clamp(qty, 1, 500);
ImGui.SameLine();
if (ImGui.Button("Buy..."))
{
int q = S.PowerballQuantity;
_ctx.Confirm("Powerball", $"Buy {q} Powerball ticket(s)?\n{(_pbPrice.Length > 0 ? _pbPrice : "Tickets cost banked luminance.")}",
() => Send($"/pb buy {q}"), "Buy");
}
if (_pbStatus.Length > 0) SafeImGui.TextWrapped(_pbStatus);
}
/// <summary>Small HUD with the current hand; called every frame by the Hub UI.</summary>
public void RenderHud()
{
if (!_handActive || !_ctx.State.GamesHudVisible) return;
ImGui.SetNextWindowSize(new Vector2(300, 0), ImGuiCond.FirstUseEver);
bool open = true;
if (ImGui.Begin("Blackjack HUD##iltbjhud", ref open, ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoCollapse))
{
SafeImGui.TextColored(IltStyle.ColAmber, _fellowshipHand ? "Fellowship Blackjack" : "Blackjack");
RenderHandButtons("hud");
}
ImGui.End();
if (!open) _ctx.State.GamesHudVisible = false;
}
}

View file

@ -0,0 +1,78 @@
// IltGear.cs — ILT Hub "Gear" tab: the gear tools.
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// The sections are separate modules (buff keepers, chunk/clap, split arrows, equipment suits)
// that this tab just lays out, plus RynthAi's VTank .usd importer (it edits RynthAi's own rules,
// so it stayed in RynthAi and is drawn here through RynthAi.Hub RenderSection). The charm strip (registry charms and the Guardian
// Hand, with their toggles) is the Charms tab now (IltCharms). The Rings inscription chain
// (IltRingChainRunner) is SilentKelpie's RynthAi Crafting > Rings, moved here 2026-10-15.
using ImGuiNET;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltGear : IIltFeature
{
public IltBuffKeepers Keepers { get; }
public IltChunkClap ChunkClap { get; }
public IltSplitArrows Split { get; }
public IltEquipSuits Suits { get; }
public IltRingChainRunner Rings { get; }
private readonly IltHubContext _ctx;
public IltGear(IltHubContext ctx)
{
Keepers = new IltBuffKeepers(ctx);
ChunkClap = new IltChunkClap(ctx);
Split = new IltSplitArrows(ctx);
Suits = new IltEquipSuits(ctx);
// The two pack jobs that answer craft dialogs never run together.
Rings = new IltRingChainRunner(ctx, () => Split.Running);
Split.Blocked = () => Rings.Running;
_ctx = ctx;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
Keepers.Tick(nowMs);
ChunkClap.Tick(nowMs);
Split.Tick(nowMs);
Suits.Tick(nowMs);
Rings.Tick(nowMs);
}
public bool OnChat(string text)
{
bool eat = Keepers.OnChat(text);
eat |= ChunkClap.OnChat(text);
eat |= Split.OnChat(text);
eat |= Suits.OnChat(text);
eat |= Rings.OnChat(text);
return eat;
}
public void OnLogout()
{
Keepers.OnLogout();
ChunkClap.OnLogout();
Split.OnLogout();
Suits.OnLogout();
Rings.OnLogout();
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
if (ImGui.CollapsingHeader("Dispel / Surging Strength", ImGuiTreeNodeFlags.DefaultOpen)) Keepers.Render();
if (ImGui.CollapsingHeader("Chunking / Clap")) ChunkClap.Render();
if (ImGui.CollapsingHeader("Split arrows")) Split.Render();
if (ImGui.CollapsingHeader("Equipment suits")) Suits.Render();
if (ImGui.CollapsingHeader("Rings (inscription chain)")) Rings.Render();
if (ImGui.CollapsingHeader("VirindiTank import") && !_ctx.Ai.RenderSection(RynthCore.Plugin.Shared.RynthAiHub.SectionVTankImport))
ImGui.TextDisabled("The VirindiTank .usd import fills RynthAi's rules: it comes with RynthAi, which isn't loaded.");
ImGui.TextDisabled("Charms and the Guardian Hand are on the Charms tab.");
}
}

View file

@ -0,0 +1,656 @@
// IltGuardian.cs - Temple of Enlightenment guardians (ILT Hub "Guardian" window).
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// * Riddle translator: incoming "Guardian of ... tells you / says" lines (when chat auto-detect
// is on) and pasted text go through IltGuardianPhrasebook; the answer shows here and on the
// Mini Remote.
// * Hand-in: gives one of the answer item to the guardian (GiveObjectTo). For the Temple
// guardian, when none is carried and "buy missing" is on, it first buys one from the open or
// nearest vendor (VendorBuy). Runs as a small pump-thread state machine with timeouts; the
// client busy state is respected between steps.
// * Attribute tracker: IltTempleAttributes.
// * Reader: the same state as JSON with verbs back ("RynthILT.Data" version 3), for RynthOracle's
// Quests tab. The automation (auto hand-in, buy if missing) stays here either way.
//
// Threading: OnChat / Tick / commands run on the pump thread; Render only reads volatile fields
// and posts actions through IltHubContext.Post.
using System;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltGuardian : IIltFeature
{
/// <summary>The same guardian + answer from chat within this window is one prompt (tells repeat lines).</summary>
private const long DebounceMs = 2500;
private const long HandInTimeoutMs = 45_000;
private const long VendorOpenTimeoutMs = 10_000;
private const long BuyTimeoutMs = 10_000;
private const long ItemArriveTimeoutMs = 8_000;
private const long BusyRetryMs = 400;
private const int MaxGiveAttempts = 5;
/// <summary>How far (meters) to look for the guardian and a vendor.</summary>
private const double SearchRangeMeters = 60.0;
/// <summary>
/// PublicWeenieDesc BF_VENDOR. The world cache files vendors as creatures (Monster / Npc), never
/// AcObjectClass.Vendor, so vendors are recognised by this weenie flag.
/// </summary>
private const uint BfVendor = 0x200;
/// <summary>The Mini Remote shows the last answer for this long.</summary>
public static readonly TimeSpan AnswerShownFor = TimeSpan.FromMinutes(10);
private enum Step { Idle, FindItem, OpenVendor, WaitVendor, Buy, WaitBuy, WaitItem, Give }
private readonly IltHubContext _ctx;
private string _lastFingerprint = string.Empty;
private long _lastEmitAt;
// Last prompt (written on the pump thread, read by the render thread).
private volatile string _lastLine = string.Empty;
private volatile string _lastAnswer = string.Empty;
private volatile string _lastNpc = string.Empty;
private long _lastAnswerTicksUtc;
private volatile string _handInStatus = "idle";
// Hand-in state machine (pump thread only).
private Step _step = Step.Idle;
private string _item = string.Empty;
private string _npc = string.Empty;
private bool _asked;
private long _startedAt;
private long _stepDeadline;
private long _nextStepAt;
private uint _vendorId;
private uint _buyRequest;
private int _giveAttempts;
// Render-thread UI state.
private string _input = string.Empty;
public IltGuardian(IltHubContext ctx, IltQuestBonus quests)
{
_ctx = ctx;
Attributes = new IltTempleAttributes(ctx, quests);
}
public IltTempleAttributes Attributes { get; }
private IltGuardianState S => _ctx.State.Guardian;
/// <summary>Last answer item ("" until a guardian prompt was translated).</summary>
public string LastAnswer => _lastAnswer;
/// <summary>Guardian the last answer goes to.</summary>
public string LastNpc => _lastNpc;
/// <summary>The hand-in sequence is running.</summary>
public bool HandInRunning => _step != Step.Idle;
public string HandInStatus => _handInStatus;
/// <summary>Time since the last answer (MaxValue when there is none).</summary>
public TimeSpan LastAnswerAge
{
get
{
long t = System.Threading.Interlocked.Read(ref _lastAnswerTicksUtc);
return t == 0 ? TimeSpan.MaxValue : DateTime.UtcNow - new DateTime(t, DateTimeKind.Utc);
}
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
Attributes.Tick(nowMs);
StepHandIn(nowMs);
}
public bool OnChat(string text)
{
if (!S.AutoDetectFromChat || !IltGuardianPhrasebook.LooksLikeIncomingGuardianLine(text)) return false;
_lastLine = text.Trim();
string answer = IltGuardianPhrasebook.Translate(text);
if (!IltGuardianPhrasebook.IsAnswer(answer)) return false;
string npc = IltGuardianPhrasebook.TurnInNpcFromLine(text);
long now = IltHubContext.NowMs;
string fingerprint = npc + "|" + answer;
if (fingerprint == _lastFingerprint && now - _lastEmitAt < DebounceMs) return false;
_lastFingerprint = fingerprint;
_lastEmitAt = now;
SetAnswer(answer, npc);
_ctx.Chat($"[ILT Guardian] {npc} wants: {answer}");
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] chat answer '{answer}' for {npc}");
if (S.AutoHandIn) StartHandIn(answer, npc, asked: false);
return false; // never hide the guardian's own lines
}
public void OnLogout()
{
StopHandIn("stopped (logout)");
Attributes.OnLogout();
}
private void SetAnswer(string answer, string npc)
{
_lastAnswer = answer;
_lastNpc = npc;
System.Threading.Interlocked.Exchange(ref _lastAnswerTicksUtc, DateTime.UtcNow.Ticks);
}
/// <summary>Translates pasted text; a real answer becomes the current answer. Pump thread.</summary>
public string TranslateManual(string text)
{
string answer = IltGuardianPhrasebook.Translate(text);
if (!IltGuardianPhrasebook.IsAnswer(answer)) return answer;
string npc = IltGuardianPhrasebook.TurnInNpcFromInput(text);
_lastLine = text.Trim();
SetAnswer(answer, npc);
return $"{answer} (give to {npc})";
}
// ── Hand-in ─────────────────────────────────────────────────────────────
/// <summary>Starts giving <paramref name="item"/> to <paramref name="npc"/>. Pump thread.</summary>
public string StartHandIn(string item, string npc, bool asked)
{
if (!IltGuardianPhrasebook.IsAnswer(item)) return "No answer to hand in yet.";
if (!_ctx.Host.HasGiveObjectTo) return SetStatus("can't give items: update the RynthCore engine (API v62+).");
_item = item;
_npc = string.IsNullOrWhiteSpace(npc) ? IltGuardianPhrasebook.AttributeGuardian : npc;
_asked = asked;
_startedAt = IltHubContext.NowMs;
_nextStepAt = 0;
_vendorId = 0;
_buyRequest = 0;
_giveAttempts = 0;
_step = Step.FindItem;
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] hand-in start: '{_item}' -> {_npc} ({(asked ? "asked" : "auto")})");
return SetStatus($"handing {_item} to {_npc}...");
}
/// <summary>Stops a running hand-in.</summary>
public void StopHandIn(string why = "stopped")
{
if (_step == Step.Idle) return;
_step = Step.Idle;
SetStatus(why);
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] hand-in {why}");
}
private string SetStatus(string text)
{
_handInStatus = text;
return text;
}
private void Fail(string why)
{
_step = Step.Idle;
SetStatus("failed: " + why);
_ctx.Chat($"[ILT Guardian] Hand-in failed: {why}");
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] hand-in failed: {why}");
}
private void Next(Step step, long nowMs, long timeoutMs = 0)
{
_step = step;
_stepDeadline = timeoutMs > 0 ? nowMs + timeoutMs : 0;
}
private void StepHandIn(long nowMs)
{
if (_step == Step.Idle || nowMs < _nextStepAt) return;
if (nowMs - _startedAt > HandInTimeoutMs) { Fail("timed out"); return; }
if (_stepDeadline != 0 && nowMs > _stepDeadline) { Fail(TimeoutText(_step)); return; }
var host = _ctx.Host;
switch (_step)
{
case Step.FindItem:
if (FindHandInItem() != null) { Next(Step.Give, nowMs); break; }
if (!IsTempleGuardian(_npc) || !S.BuyMissingFromVendor) { LogItemNearMisses(); Fail($"no {_item} in your packs"); break; }
Next(Step.OpenVendor, nowMs);
break;
case Step.OpenVendor:
{
if (!host.HasVendorTrade) { Fail($"no {_item} carried and vendor buying needs a newer RynthCore engine"); break; }
if (host.TryGetVendorInfo(out var open)) { _vendorId = open.VendorId; Next(Step.Buy, nowMs); break; }
var vendor = Nearest(IsVendor);
if (vendor == null) { LogVendorSearch(); Fail($"no {_item} carried and no vendor within {SearchRangeMeters:0} m"); break; }
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] vendor for '{_item}': {vendor.Name} 0x{(uint)vendor.Id:X8}");
SetStatus($"opening {vendor.Name} to buy {_item}...");
host.UseFor(unchecked((uint)vendor.Id), "IltGuardian", $"buy {_item} for the Temple guardian",
_asked ? UseKind.Asked : UseKind.Auto);
Next(Step.WaitVendor, nowMs, VendorOpenTimeoutMs);
break;
}
case Step.WaitVendor:
if (host.TryGetVendorInfo(out var info) && info.ItemCount > 0) { _vendorId = info.VendorId; Next(Step.Buy, nowMs); }
break;
case Step.Buy:
{
if (!host.TryGetVendorInfo(out var v)) { Fail("the vendor closed"); break; }
if (v.TradeInFlight) { _nextStepAt = nowMs + BusyRetryMs; break; }
string want = NormalizeName(_item);
var match = host.GetVendorItems().FirstOrDefault(i => NormalizeName(i.Name) == want);
if (match == null) { Fail($"{v.Name} doesn't sell {_item}"); break; }
_buyRequest = host.VendorBuy(match.ObjectId, 1, v.VendorId);
if (_buyRequest == 0)
{
string why = host.TryGetVendorTradeStatus(out var st) && st.Message.Length > 0 ? st.Message : "refused";
Fail($"couldn't buy {_item}: {why}");
break;
}
SetStatus($"buying {_item} from {v.Name}...");
Next(Step.WaitBuy, nowMs, BuyTimeoutMs);
break;
}
case Step.WaitBuy:
if (!host.TryGetVendorTradeStatus(out var status) || status.RequestId != _buyRequest || !status.IsFinished) break;
if (!status.Succeeded) { Fail($"couldn't buy {_item}: {(status.Message.Length > 0 ? status.Message : status.Result.ToString())}"); break; }
Next(Step.WaitItem, nowMs, ItemArriveTimeoutMs);
break;
case Step.WaitItem:
if (FindHandInItem() != null) Next(Step.Give, nowMs);
break;
case Step.Give:
GiveStep(nowMs);
break;
}
}
private void GiveStep(long nowMs)
{
if (_ctx.Inventory.IsBusy)
{
SetStatus("waiting for the client (busy)...");
_nextStepAt = nowMs + BusyRetryMs;
return;
}
var item = FindHandInItem();
if (item == null) { LogItemNearMisses(); Fail($"no {_item} in your packs"); return; }
var npc = Nearest(wo => wo.Name.Contains(_npc, StringComparison.OrdinalIgnoreCase));
if (npc == null) { Fail($"{_npc} isn't nearby"); return; }
int stack = _ctx.Inventory.StackSize(item);
bool ok = _ctx.Host.GiveObjectTo(unchecked((uint)item.Id), unchecked((uint)npc.Id), stack > 1 ? 1 : 0);
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] give '{item.Name}' 0x{(uint)item.Id:X8} (stack {stack}) -> {npc.Name} 0x{(uint)npc.Id:X8}: {ok}");
if (ok)
{
_step = Step.Idle;
SetStatus($"gave {item.Name} to {npc.Name}");
_ctx.Chat($"[ILT Guardian] Gave {item.Name} to {npc.Name}.");
return;
}
if (++_giveAttempts >= MaxGiveAttempts) { Fail("the give was refused"); return; }
_nextStepAt = nowMs + BusyRetryMs;
}
private static string TimeoutText(Step step) => step switch
{
Step.WaitVendor => "the vendor didn't open",
Step.WaitBuy => "the vendor didn't answer the purchase",
Step.WaitItem => "the bought item didn't arrive",
_ => "timed out",
};
private static bool IsTempleGuardian(string npc) =>
npc.Contains(IltGuardianPhrasebook.TempleGuardian, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// A carried (not wielded) item named like the answer (case and spacing ignored). Reads AC's
/// live container contents: the cache's inventory set lags a purchase and also holds the open
/// vendor's stock, which can't be given.
/// </summary>
private WorldObject? FindHandInItem()
{
string want = NormalizeName(_item);
return CarriedItems().FirstOrDefault(wo => NormalizeName(wo.Name) == want && !_ctx.Inventory.IsEquipped(wo));
}
/// <summary>Live walk of the player's pack and side packs (falls back to the cache without the engine call).</summary>
private System.Collections.Generic.IReadOnlyList<WorldObject> CarriedItems()
=> _ctx.Inventory.Cache?.GetDirectInventory(forceRefresh: true) ?? Array.Empty<WorldObject>();
/// <summary>Lower-case, trimmed, single-spaced name for comparisons.</summary>
private static string NormalizeName(string name)
=> string.Join(' ', (name ?? string.Empty).Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant();
/// <summary>Logs carried items sharing a word with the answer, so a name mismatch shows in the log.</summary>
private void LogItemNearMisses()
{
var items = CarriedItems();
var words = NormalizeName(_item).Split(' ').Where(w => w.Length > 3).ToArray();
var similar = items.Where(wo => words.Any(w => wo.Name.Contains(w, StringComparison.OrdinalIgnoreCase)))
.Take(8).Select(wo => $"'{wo.Name}' 0x{(uint)wo.Id:X8}").ToArray();
RynthLog.Write(LogCat.IltHub,
$"[IltGuardian] no '{_item}' among {items.Count} carried items; similar names: {(similar.Length > 0 ? string.Join(", ", similar) : "none")}");
}
/// <summary>A vendor (weenie BF_VENDOR flag, or a cache entry already classed Vendor).</summary>
private bool IsVendor(WorldObject wo)
{
if (wo.ObjectClass == AcObjectClass.Vendor) return true;
var host = _ctx.Host;
return host.HasGetObjectBitfield && host.TryGetObjectBitfield(unchecked((uint)wo.Id), out uint bf) && (bf & BfVendor) != 0;
}
/// <summary>Logs every vendor the cache sees with its distance (vendor search found none in range).</summary>
private void LogVendorSearch()
{
var cache = _ctx.Inventory.Cache;
int playerId = unchecked((int)_ctx.Inventory.PlayerId);
if (cache == null || playerId == 0) { RynthLog.Write(LogCat.IltHub, "[IltGuardian] vendor search: no world cache / player"); return; }
var landscape = cache.GetLandscapeObjects().ToList();
var vendors = landscape.Where(IsVendor).Take(8)
.Select(wo => $"'{wo.Name}' 0x{(uint)wo.Id:X8} {cache.Distance(playerId, wo.Id):0.0} m").ToArray();
RynthLog.Write(LogCat.IltHub,
$"[IltGuardian] vendor search: {landscape.Count} landscape objects, bitfield={(_ctx.Host.HasGetObjectBitfield ? "yes" : "no")}, "
+ $"vendors: {(vendors.Length > 0 ? string.Join(", ", vendors) : "none")}");
}
/// <summary>Nearest landscape object matching <paramref name="match"/> within SearchRangeMeters.</summary>
private WorldObject? Nearest(Func<WorldObject, bool> match)
{
var cache = _ctx.Inventory.Cache;
int playerId = unchecked((int)_ctx.Inventory.PlayerId);
if (cache == null || playerId == 0) return null;
WorldObject? best = null;
double bestDist = SearchRangeMeters;
foreach (var wo in cache.GetLandscapeObjects())
{
if (!match(wo)) continue;
double d = cache.Distance(playerId, wo.Id);
if (d <= bestDist) { bestDist = d; best = wo; }
}
return best;
}
// ── Commands ────────────────────────────────────────────────────────────
/// <summary>
/// "/ra guardian translate &lt;text&gt;|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status".
/// "window" is handled by the controller. Pump thread.
/// </summary>
public void HandleCommand(string[] args)
{
string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "status";
string rest = args.Length > 1 ? string.Join(" ", args.Skip(1)) : string.Empty;
switch (sub)
{
case "translate":
case "t":
_ctx.Chat("[ILT Guardian] " + TranslateManual(rest));
break;
case "handin":
case "give":
_ctx.Chat("[ILT Guardian] " + StartHandIn(_lastAnswer, _lastNpc, asked: true));
break;
case "stop":
StopHandIn();
_ctx.Chat("[ILT Guardian] Hand-in stopped.");
break;
case "chat":
S.AutoDetectFromChat = Toggle(rest, S.AutoDetectFromChat);
_ctx.Chat($"[ILT Guardian] Chat auto-detect {(S.AutoDetectFromChat ? "on" : "off")}.");
break;
case "auto":
S.AutoHandIn = Toggle(rest, S.AutoHandIn);
_ctx.Chat($"[ILT Guardian] Auto hand-in {(S.AutoHandIn ? "on" : "off")}.");
break;
case "buy":
S.BuyMissingFromVendor = Toggle(rest, S.BuyMissingFromVendor);
_ctx.Chat($"[ILT Guardian] Buy missing Temple items {(S.BuyMissingFromVendor ? "on" : "off")}.");
break;
case "refresh":
_ctx.Chat("[ILT Guardian] " + Attributes.Refresh());
break;
case "status":
_ctx.Chat($"[ILT Guardian] chat={(S.AutoDetectFromChat ? "on" : "off")} auto={(S.AutoHandIn ? "on" : "off")} buy={(S.BuyMissingFromVendor ? "on" : "off")} "
+ $"answer={(_lastAnswer.Length > 0 ? $"{_lastAnswer} -> {_lastNpc}" : "-")} hand-in: {_handInStatus}");
foreach (var r in Attributes.Snapshot)
_ctx.Chat($"[ILT Guardian] {r.Attribute,-12} {r.Npc,-16} #{r.Count} {r.Status} {r.Eta}");
break;
default:
_ctx.Chat("[ILT Guardian] /ra guardian [window [show|hide]|translate <text>|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status]");
break;
}
}
// ── Reader ("RynthILT.Data" GetGuardianJson / GuardianCommand; RynthOracle's Quests tab) ──
/// <summary>
/// The reader JSON (Plugins/Shared/RynthIltDataApi.cs header has the shape): the switches, the
/// last answer and hand-in status, and the attribute turn-in rows. Built on demand: everything it
/// reads is volatile or an immutable snapshot. Any thread.
/// </summary>
public string ReaderJson(string world)
{
TimeSpan age = LastAnswerAge;
return BuildJson(world, S.AutoDetectFromChat, S.AutoHandIn, S.BuyMissingFromVendor, S.CooldownHoursAssumed,
_lastAnswer, _lastNpc, age == TimeSpan.MaxValue ? -1 : (long)age.TotalSeconds,
IltGuardianPhrasebook.MessageOf(_lastLine), HandInRunning, _handInStatus, Attributes.SyncedUtc, Attributes.Snapshot);
}
/// <summary>The reader JSON from its parts. Pure: the tests drive it.</summary>
internal static string BuildJson(string world, bool chat, bool auto, bool buy, int cooldownHours,
string answer, string npc, long answerAgeSec, string heard, bool running, string status,
DateTime syncedUtc, System.Collections.Generic.IReadOnlyList<IltTempleAttrStatus> rows)
{
var sb = new System.Text.StringBuilder(1024);
sb.Append("{\"available\":true");
Str(sb, "world", world);
sb.Append(",\"chat\":").Append(chat ? "true" : "false");
sb.Append(",\"auto\":").Append(auto ? "true" : "false");
sb.Append(",\"buy\":").Append(buy ? "true" : "false");
sb.Append(",\"cooldownHours\":").Append(cooldownHours);
Str(sb, "answer", answer);
Str(sb, "npc", npc);
sb.Append(",\"answerAgeSec\":").Append(answerAgeSec);
Str(sb, "heard", heard);
sb.Append(",\"running\":").Append(running ? "true" : "false");
Str(sb, "status", status);
Str(sb, "synced", syncedUtc == DateTime.MinValue ? "" : syncedUtc.ToString("yyyy-MM-ddTHH:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture));
sb.Append(",\"rows\":[");
for (int i = 0; i < rows.Count; i++)
{
IltTempleAttrStatus r = rows[i];
if (i > 0) sb.Append(',');
sb.Append('{');
Str(sb, "attribute", r.Attribute, first: true);
Str(sb, "npc", r.Npc);
sb.Append(",\"count\":").Append(r.Count);
Str(sb, "status", r.Status);
Str(sb, "eta", r.Eta);
sb.Append(",\"ready\":").Append(r.Ready ? "true" : "false");
sb.Append(",\"exact\":").Append(r.FromMyQuests ? "true" : "false");
sb.Append('}');
}
sb.Append("]}");
return sb.ToString();
}
private static void Str(System.Text.StringBuilder sb, string name, string? value, bool first = false)
{
if (!first) sb.Append(',');
sb.Append('"').Append(name).Append("\":\"").Append(IltStyle.JsonEscape(value ?? string.Empty)).Append('"');
}
/// <summary>
/// A reader's verb line (header of Plugins/Shared/RynthIltDataApi.cs): handin | stop | refresh |
/// chat on|off | auto on|off | buy on|off. The reader shows the new state, so the switches don't
/// echo in chat; hand-in and refresh report as the Guardian window's buttons do. Pump thread.
/// </summary>
public void RunVerb(string line)
{
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0) return;
string arg = parts.Length > 1 ? parts[1] : "";
switch (parts[0].ToLowerInvariant())
{
case "handin": StartHandIn(_lastAnswer, _lastNpc, asked: true); break;
case "stop": StopHandIn(); break;
case "refresh": _ctx.Chat("[ILT Guardian] " + Attributes.Refresh()); break;
case "chat": S.AutoDetectFromChat = Toggle(arg, S.AutoDetectFromChat); break;
case "auto": S.AutoHandIn = Toggle(arg, S.AutoHandIn); break;
case "buy": S.BuyMissingFromVendor = Toggle(arg, S.BuyMissingFromVendor); break;
default:
RynthLog.Trace(LogCat.IltHub, $"[IltGuardian] reader verb ignored: {line}");
return;
}
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] reader verb: {line}");
}
private static bool Toggle(string mode, bool current) => mode.Trim().ToLowerInvariant() switch
{
"on" or "true" or "1" or "show" => true,
"off" or "false" or "0" or "hide" => false,
_ => !current,
};
// ── UI (render thread) ──────────────────────────────────────────────────
/// <summary>Guardian window body.</summary>
public void Render()
{
if (ImGui.CollapsingHeader("Riddle translator", ImGuiTreeNodeFlags.DefaultOpen)) RenderTranslator();
ImGui.Spacing();
if (ImGui.CollapsingHeader("Attribute turn-ins", ImGuiTreeNodeFlags.DefaultOpen)) RenderTracker();
}
private void RenderTranslator()
{
var s = S;
// Plain bool writes; the pump thread reads them on its next tick.
bool chat = s.AutoDetectFromChat;
if (ImGui.Checkbox("Detect from chat##grdchat", ref chat)) s.AutoDetectFromChat = chat;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Translate the guardians' tells as they arrive and show the answer here and on the Mini Remote.");
ImGui.SameLine();
bool auto = s.AutoHandIn;
if (ImGui.Checkbox("Auto hand-in##grdauto", ref auto)) s.AutoHandIn = auto;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("After a chat answer, give one of the item to the guardian automatically.");
ImGui.SameLine();
bool buy = s.BuyMissingFromVendor;
if (ImGui.Checkbox("Buy if missing##grdbuy", ref buy)) s.BuyMissingFromVendor = buy;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Temple guardian: when you carry none, buy one from the open or nearest vendor first.");
string line = _lastLine;
if (line.Length > 0)
{
ImGui.TextDisabled("Heard:");
ImGui.SameLine();
ImGui.PushTextWrapPos(0f);
SafeImGui.TextDisabled(IltGuardianPhrasebook.MessageOf(line));
ImGui.PopTextWrapPos();
}
string answer = _lastAnswer, npc = _lastNpc;
if (answer.Length > 0)
{
SafeImGui.TextColored(IltStyle.ColTeal, answer);
ImGui.SameLine();
SafeImGui.TextDisabled("-> " + npc);
if (HandInRunning)
{
if (ImGui.SmallButton("Stop##grdstop")) _ctx.Post(() => StopHandIn());
}
else if (ImGui.SmallButton("Hand in##grdgive"))
{
_ctx.Post(() => StartHandIn(answer, npc, asked: true));
}
}
else ImGui.TextDisabled("No guardian answer yet.");
SafeImGui.TextDisabled("Hand-in: " + _handInStatus);
ImGui.Spacing();
ImGui.InputTextMultiline("##grdinput", ref _input, 2048u, new Vector2(-1, 54));
if (ImGui.Button("Translate##grdtr"))
{
string text = _input;
_ctx.Post(() => _ctx.Chat("[ILT Guardian] " + TranslateManual(text)));
}
ImGui.SameLine();
if (ImGui.Button("Clear##grdclr")) _input = string.Empty;
ImGui.SameLine();
ImGui.TextDisabled("Paste a spell word or the riddle's question line.");
}
private void RenderTracker()
{
if (ImGui.SmallButton("Refresh##grdref")) _ctx.Post(() => _ctx.Chat("[ILT Guardian] " + Attributes.Refresh()));
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Re-read /myquests and /qb list (the server allows each once a minute).");
ImGui.SameLine();
DateTime synced = Attributes.SyncedUtc;
SafeImGui.TextDisabled(synced == DateTime.MinValue ? "/qb not read this session" : $"/qb read {synced.ToLocalTime():t}");
ImGui.SameLine();
if (ImGui.SmallButton("Reset counts##grdreset"))
_ctx.Confirm("Reset turn-in counts", "Forget the turn-in counts and cooldown estimates taken from /qb wait stamps? (/myquests counts are not affected.)",
Attributes.ResetCounts, "Reset");
var rows = Attributes.Snapshot;
if (rows.Length > 0 && ImGui.BeginTable("##grdattr", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingStretchProp))
{
ImGui.TableSetupColumn("Attribute", ImGuiTableColumnFlags.None, 1.0f);
ImGui.TableSetupColumn("NPC", ImGuiTableColumnFlags.None, 1.3f);
ImGui.TableSetupColumn("#", ImGuiTableColumnFlags.None, 0.35f);
ImGui.TableSetupColumn("Status", ImGuiTableColumnFlags.None, 0.9f);
ImGui.TableSetupColumn("Next", ImGuiTableColumnFlags.None, 1.5f);
ImGui.TableHeadersRow();
foreach (var r in rows)
{
ImGui.TableNextRow();
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Attribute);
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Npc);
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Count.ToString());
ImGui.TableNextColumn();
var col = r.Ready ? IltStyle.ColGreen
: r.Status == "Unknown" ? IltStyle.ColTextMute
: IltStyle.ColAmber;
SafeImGui.TextColored(col, r.Status);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip(r.FromMyQuests ? "From /myquests (exact)." : "From /qb wait stamps (count and timer are estimates).");
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Eta);
}
ImGui.EndTable();
}
int hours = S.CooldownHoursAssumed;
ImGui.SetNextItemWidth(140);
if (ImGui.SliderInt("Assumed cooldown (h)##grdhours", ref hours, 1, 72)) S.CooldownHoursAssumed = hours;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Used only for rows /myquests doesn't report: how long a /qb wait stamp lasts.");
}
/// <summary>
/// Mini Remote line: the last answer (for AnswerShownFor) with a Give / Stop button.
/// Draws nothing when there is no recent answer. Render thread.
/// </summary>
public void RenderRemoteLine()
{
string answer = _lastAnswer, npc = _lastNpc;
if (answer.Length == 0 || LastAnswerAge > AnswerShownFor) return;
ImGui.TextColored(IltStyle.ColTextMute, "Guardian:");
ImGui.SameLine();
SafeImGui.TextColored(IltStyle.ColTeal, answer);
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"Give to {npc}\nHand-in: {_handInStatus}");
ImGui.SameLine();
if (HandInRunning)
{
if (ImGui.SmallButton("Stop##mrgrd")) _ctx.Post(() => StopHandIn());
}
else if (ImGui.SmallButton("Give##mrgrd"))
{
_ctx.Post(() => StartHandIn(answer, npc, asked: true));
}
}
}

View file

@ -0,0 +1,221 @@
// IltGuardianPhrasebook.cs - Temple of Enlightenment spell words and Guardian of Attribute
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
// Enlightenment riddles mapped to the item each guardian wants (Infinite Leaftide).
//
// Pure functions only (no host calls), so the Guardian window may translate on the render thread.
// The riddle table matches on the closing question line; lead-in lines alone return "No match".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthILT.Hub;
internal static class IltGuardianPhrasebook
{
public const string TempleGuardian = "Guardian of the Temple of Enlightenment";
public const string AttributeGuardian = "Guardian of Attribute Enlightenment";
/// <summary>Chat prefixes of an incoming guardian line ("tells you" or ACE's environmental "says").</summary>
private static readonly string[] IncomingPrefixes =
{
TempleGuardian + " tells you",
AttributeGuardian + " tells you",
TempleGuardian + " says",
AttributeGuardian + " says",
};
/// <summary>Help text returned when nothing was pasted.</summary>
public const string PasteHint = "Paste a spell word or riddle text, then Translate.";
/// <summary>Help text returned when the text didn't match any spell word or riddle.</summary>
public const string NoMatchHint = "No match: paste more lines from the guardian (especially the question line ending with ?).";
private static readonly Dictionary<string, string> TempleSpells = new(StringComparer.OrdinalIgnoreCase)
{
{ "Boquar", "Mugwort" }, { "Feazh", "Damiana" }, { "Kenrak", "Amaranth" },
{ "Puish", "Saffron" }, { "Shurov", "Comfrey" }, { "Volae", "Eyebright" },
{ "Cruath", "Ginseng" }, { "Helkas", "Wormwood" }, { "Malar", "Hyssop" },
{ "Quavosh", "Dragonsblood" }, { "Tugak", "Vervain" }, { "Yanoi", "Bistort" },
{ "Equin", "Mandrake" }, { "Jevak", "Myrrh" }, { "Ozhur", "Frankincense" },
{ "Roiga", "Yarrow" }, { "Uthoi", "Henbane" }, { "Zojak", "Hawthorn" },
};
/// <summary>Spell words longest first so a short word never shadows a longer one.</summary>
private static readonly KeyValuePair<string, string>[] TempleSpellsByLength =
TempleSpells.OrderByDescending(p => p.Key.Length).ToArray();
/// <summary>Normalized riddle phrases (longest first) and the item each answers.</summary>
private static readonly (string Needle, string Item)[] AttributeClues = BuildAttributeClues();
/// <summary>The same riddles split into meaningful words for the fuzzy fallback.</summary>
private static readonly (string Item, string[] Words)[] AttributeClueWords =
AttributeClues.Select(c => (c.Item, TokenizeMeaningfulWords(c.Needle))).ToArray();
private static (string, string)[] BuildAttributeClues()
{
var raw = new (string Phrase, string Item)[]
{
("what stone of shadow wields such arm", "Powdered Onyx"),
("what stone defends the mortal clay", "Powdered Agate"),
("what heavy stone keeps adventurers healed", "Powdered Hematite"),
("what heavy stone keeps adventure's healed", "Powdered Hematite"),
("what honeyed stone bids pain to leave", "Powdered Amber"),
("what draught unweaves that mages send", "Chorizite"),
("what gem of life beats deep within", "Powdered Bloodstone"),
("what ruddy gem calls vigor nigh", "Powdered Carnelian"),
("what lunar gem gives peace to mind", "Powdered Moonstone"),
("what verdant gem reveals the way", "Powdered Malachite"),
("what crystal tunes the life it soothes", "Powdered Quartz"),
("what gem of sky makes items nice", "Powdered Turquoise"),
("what vial holds my burning scar", "Brimstone"),
("which draught brings forth the fire's scent", "Turpeth"),
("race the wind yet leave no trace", "Cadmia"),
("grant the hand a dancer grace", "Cadmia"),
("no wings I bear yet fleet I flee", "Cadmia"),
("what draught awakens speed in thee", "Cadmia"),
("what deaught awakens speed in thee", "Cadmia"),
("what potion turns mana-use to one", "Cinnabar"),
("what azure draught makes thunder weep", "Cobalt"),
("what draught commands the winter's tide", "Colcothar"),
("what pale draught prevents acid's writhe", "Gypsum"),
("whate pale draught prevents acid's writhe", "Gypsum"),
("what liquid turns heart grey between", "Quicksilver"),
("what potion pierces the unseen end", "Realgar"),
("what shadowed draught makes swiftness lie", "Stibnite"),
("what verdant vial hides cuts unseen", "Verdigris"),
("what potion shakes both flesh and floor", "Vitriol"),
("what river wood trades life as art", "Alder Talisman"),
("what wood enchants both bane and skill", "Ashwood Talisman"),
("what pale wood casts the striker's bane", "Birch Talisman"),
("what sacred stem keeps harm outside", "Cedar Talisman"),
("what dark wood diminishes the foe's own tune", "Blackthorn Talisman"),
("what hardwood charm makes others stand", "Ebony Talisman"),
("what aged branch makes circles run", "Elder Talisman"),
("what mystic bough binds here to yore", "Hazel Talisman"),
("what poisoned branch brings creeping death", "Hemlock Talisman"),
("what steadfast wood makes volleys rained", "Oak Talisman"),
("what living wand makes allies mend", "Poplar Talisman"),
("what sacred wood the self amends", "Rowan Talisman"),
("what supple wood restores me here", "Willow Talisman"),
("what ancient bough lets lifeblood grow", "Yew Talisman"),
};
return raw.Select(t => (NormalizePhrase(t.Phrase), t.Item))
.OrderByDescending(t => t.Item1.Length)
.ToArray();
}
/// <summary>Lowercase, curly apostrophes folded, punctuation collapsed to single spaces.</summary>
private static string NormalizePhrase(string s)
{
if (string.IsNullOrWhiteSpace(s)) return string.Empty;
string lower = s.Trim().ToLowerInvariant().Replace('\u2019', '\'');
var sb = new StringBuilder(lower.Length);
bool pendingSpace = false;
foreach (char c in lower)
{
bool wordCh = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '\'';
if (!wordCh) { pendingSpace = true; continue; }
if (pendingSpace && sb.Length > 0) { sb.Append(' '); pendingSpace = false; }
sb.Append(c);
}
return sb.ToString().Trim();
}
/// <summary>Words of 3+ letters minus question / filler words.</summary>
private static string[] TokenizeMeaningfulWords(string normalized) =>
normalized.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Where(w => w.Length >= 3 && w is not ("what" or "which" or "the" or "and" or "for"))
.ToArray();
/// <summary>
/// Typo-tolerant fallback: the riddle whose words overlap the input best, needing at least four
/// shared words and 72% of the riddle's words so a near-miss never maps to the wrong item.
/// </summary>
private static string? TryFuzzyAttributeMatch(string blob)
{
var inputWords = TokenizeMeaningfulWords(blob);
if (inputWords.Length == 0) return null;
var inputSet = new HashSet<string>(inputWords, StringComparer.Ordinal);
string? bestItem = null;
double bestScore = 0d;
foreach (var (item, words) in AttributeClueWords)
{
if (words.Length == 0) continue;
int matches = words.Count(inputSet.Contains);
double score = (double)matches / words.Length;
if (matches >= 4 && score >= 0.72d && score > bestScore)
{
bestScore = score;
bestItem = item;
}
}
return bestItem;
}
/// <summary>Resolves guardian text to an item name, or one of the help strings.</summary>
public static string Translate(string raw)
{
string blob = NormalizePhrase(raw);
if (blob.Length == 0) return PasteHint;
var tokens = Regex.Split(blob, @"[^a-z0-9']+").Where(t => t.Length > 0).ToList();
foreach (var pair in TempleSpellsByLength)
if (tokens.Any(t => t.Equals(pair.Key, StringComparison.OrdinalIgnoreCase)))
return pair.Value;
foreach (var pair in TempleSpellsByLength)
if (blob.Contains(pair.Key.ToLowerInvariant(), StringComparison.Ordinal))
return pair.Value;
foreach (var (needle, item) in AttributeClues)
if (needle.Length > 0 && blob.Contains(needle, StringComparison.Ordinal))
return item;
return TryFuzzyAttributeMatch(blob) ?? NoMatchHint;
}
/// <summary>False for the help strings Translate returns when nothing matched.</summary>
public static bool IsAnswer(string translation) =>
!string.IsNullOrWhiteSpace(translation) && translation != PasteHint && translation != NoMatchHint;
/// <summary>True when the line starts like an incoming guardian tell / say.</summary>
public static bool LooksLikeIncomingGuardianLine(string raw)
{
if (string.IsNullOrWhiteSpace(raw)) return false;
string t = raw.TrimStart();
foreach (string prefix in IncomingPrefixes)
if (t.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
/// <summary>The guardian to give the item to, read from an incoming line (Attribute when unclear).</summary>
public static string TurnInNpcFromLine(string raw)
{
if (!string.IsNullOrEmpty(raw) && raw.Contains(TempleGuardian, StringComparison.OrdinalIgnoreCase))
return TempleGuardian;
return AttributeGuardian;
}
/// <summary>
/// The guardian for manually pasted text: the name in a pasted chat line, else a Temple spell
/// word means the Temple guardian, else the Attribute guardian.
/// </summary>
public static string TurnInNpcFromInput(string raw)
{
if (string.IsNullOrWhiteSpace(raw)) return AttributeGuardian;
if (raw.Contains(TempleGuardian, StringComparison.OrdinalIgnoreCase)) return TempleGuardian;
if (raw.Contains(AttributeGuardian, StringComparison.OrdinalIgnoreCase)) return AttributeGuardian;
foreach (string word in TempleSpells.Keys)
if (raw.Contains(word, StringComparison.OrdinalIgnoreCase))
return TempleGuardian;
return AttributeGuardian;
}
/// <summary>The quoted message of a guardian line ("... tells you, \"text\"" → text); the line itself otherwise.</summary>
public static string MessageOf(string line)
{
int open = line.IndexOf('"');
int close = line.LastIndexOf('"');
return open >= 0 && close > open ? line.Substring(open + 1, close - open - 1).Trim() : line.Trim();
}
}

View file

@ -0,0 +1,114 @@
// IltHubContext.cs — Shared services handed to every ILT Hub feature.
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. What the
// features borrowed from RynthAi's internals now comes through Ai (RynthAi.Hub, RynthAiClient).
//
// Threading contract:
// * Feature Tick / OnChat run on the plugin pump thread and may call the host freely.
// * Feature Render runs on the ImGui render thread and must NOT call AC actions directly.
// It calls Post(...) to run work on the next pump tick, or Confirm(...) to ask the
// player first (the confirmed action is then posted).
using System;
using System.Collections.Concurrent;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>A yes/no question waiting for the player (a modal over the Mini Remote).</summary>
internal sealed class IltConfirmRequest
{
public string Title = "Confirm";
public string Message = string.Empty;
public string YesLabel = "Yes";
/// <summary>Runs on the pump thread after the player clicks Yes.</summary>
public Action? OnYes;
}
internal sealed class IltHubContext
{
private readonly ConcurrentQueue<Action> _posted = new();
private readonly ConcurrentQueue<IltConfirmRequest> _confirms = new();
public IltHubContext(RynthCoreHost host, IltHubState state, IltHubStore store, IltChatCapture capture,
IltServerOptions options, IltInventory inventory, IltSettings settings, RynthAiClient ai)
{
Host = host;
State = state;
Store = store;
Capture = capture;
Options = options;
Inventory = inventory;
Settings = settings;
Ai = ai;
}
public RynthCoreHost Host { get; }
public IltHubState State { get; }
public IltHubStore Store { get; }
public IltChatCapture Capture { get; }
public IltServerOptions Options { get; }
public IltInventory Inventory { get; }
/// <summary>RynthILT's settings (the server list). Edits are saved through <see cref="SaveSettings"/>.</summary>
public IltSettings Settings { get; }
/// <summary>Saves <see cref="Settings"/> (pump thread).</summary>
public void SaveSettings() => IltSettingsStore.Save(Settings);
/// <summary>RynthAi's services (the Mini Remote, /myquests, spell names, loot matching); each says when RynthAi is missing.</summary>
public RynthAiClient Ai { get; }
/// <summary>Logged-in character name (resolved at login).</summary>
public string CharName = string.Empty;
/// <summary>True when the Mini Remote is on screen (features use it to gate auto-refreshes).</summary>
public bool WindowOpen => State.WindowVisible;
/// <summary>
/// Shows the Mini Remote on one of its ILT tabs (set by the controller). Any thread: it only
/// records the tab and the show request, which the next frame applies.
/// </summary>
public Action<IltSection>? ShowTab;
/// <summary>Writes a local chat line (never sent to the server).</summary>
public void Chat(string text)
{
if (Host.HasWriteToChat) Host.WriteToChat(text, 1);
}
/// <summary>Queues work for the next pump tick (safe from the render thread).</summary>
public void Post(Action action) => _posted.Enqueue(action);
/// <summary>Asks the player to confirm before <paramref name="onYes"/> runs on the pump thread.</summary>
public void Confirm(string title, string message, Action onYes, string yesLabel = "Yes")
=> _confirms.Enqueue(new IltConfirmRequest { Title = title, Message = message, OnYes = onYes, YesLabel = yesLabel });
/// <summary>Render thread: takes the next pending confirmation, if any.</summary>
public bool TryTakeConfirm(out IltConfirmRequest request) => _confirms.TryDequeue(out request!);
/// <summary>Pump thread: runs everything posted since the last tick.</summary>
public void DrainPosted()
{
int guard = 0;
while (guard++ < 64 && _posted.TryDequeue(out var a))
{
try { a(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "posted action"); }
}
}
/// <summary>Elapsed-ms clock used for every Hub timer.</summary>
public static long NowMs => Environment.TickCount64;
}
/// <summary>Contract every Hub feature module implements.</summary>
internal interface IIltFeature
{
/// <summary>Pump-thread tick (~every plugin tick).</summary>
void Tick(long nowMs);
/// <summary>Pump-thread chat line. Return true to hide the line from the chat window.</summary>
bool OnChat(string text);
/// <summary>Logout / teardown: stop automation, drop transient state.</summary>
void OnLogout();
}

View file

@ -0,0 +1,913 @@
// IltHubController.cs — Owns the ILT features behind the Mini Remote's ILT tabs: state, services,
// feature modules, commands.
// Originally SilentKelpie's ILT Hub controller (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// RynthILTPlugin creates one controller per login session and forwards:
// OnTick → Tick() (pump thread)
// OnChatWindowText → OnChat() (pump thread; returns true to eat the line)
// OnRender → Render() (render thread: Games HUD, confirmations)
// the ILT "/ra hub ...", "/ra guardian ...", "/ra bounty ..." verbs (RynthAi forwards them
// through RynthILT.Hub Command) and "/ilt ..." → HandleCommand()
// OnLogout / teardown → OnLogout()
// The ILT sections are tabs of RynthAi's Mini Remote (RenderTab, through RynthILT.Hub); the
// Guardian is RynthCore's ILT panel (RenderGuardianPanel, RynthPluginRenderEmbed "guardian"),
// and bounties are RynthILT's Bounties window (RynthCore's ILT button), so "/ra bounty" and
// "/ra guardian window" open those engine panels. The Mini Remote's Quests and Pets tabs are
// RynthAi's (every world); RynthILT adds their ILT sections (the /qb list, the /pets and
// /shinies logs). On any world that isn't ILT-like every feature here stays dormant (no probes,
// no chat, no tabs).
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltHubController
{
private const long SaveIntervalMs = 5000;
private readonly IltHubContext _ctx;
private readonly IltHubUi _ui;
private readonly List<IIltFeature> _features = new();
private long _lastSaveAt;
private int _questGeneration; // RynthAi's /myquests refreshes seen (NoteQuestTrackerOutcome)
private bool _availabilityAnnounced; // "open the Mini Remote" hint printed this session
private volatile int _forceRequest = -1; // SetForceIlt from another thread, applied on the next tick
private long _tabDrawnAt = long.MinValue / 2; // a tab drawn as RynthCore's section view (render thread)
private const long TabDrawnMs = 2000;
// "RynthILT.Data" (Plugins/Shared/RynthIltDataApi.cs): the charms and bank snapshots, rebuilt on
// the pump every DataRebuildMs only while a reader has asked within DataWatchMs.
private const long DataRebuildMs = 2000;
private const long DataWatchMs = 6000;
/// <summary>How often the other characters' saved balances are re-read for the bank export.</summary>
private const long SiblingReadMs = 15_000;
private long _charmsReadAt, _bankReadAt; // set by readers (any thread, Interlocked)
private long _charmsBuiltAt, _bankBuiltAt, _siblingsReadAt;
private volatile string _charmsJson = string.Empty;
private volatile string _bankJson = string.Empty;
// "RynthILT.Server" profile JSON (RynthOracle: feature states, fellowship rules, the /qb list). Rebuilt ~1 s.
private const long ProfileRebuildMs = 1000;
private long _profileBuiltAt;
private volatile string _profileJson = string.Empty;
private List<IltBankExport.Row> _siblings = new();
public IltBanking Banking { get; }
public IltSessionRates Rates { get; }
/// <summary>The quest bonus list (/qb): the Quests tab's section and the Temple tracker's stamps.</summary>
public IltQuestBonus QuestBonus { get; }
/// <summary>The /pets and /shinies logs (the Pets tab's section).</summary>
public IltPetLogs PetLogs { get; }
/// <summary>The pet breeding tracker (the Pets tab's Breeding sub-tab, and the "RynthILT.Data" breeding JSON).</summary>
public IltPetBreeding Breeding { get; }
/// <summary>The Pets tab's ACECustom sections: pet charms, the summon-from-empty refill path, siphon auto-capture.</summary>
public IltPetAutomation PetAutomation { get; }
public IltProgression Progression { get; }
public IltGear Gear { get; }
public IltGames Games { get; }
/// <summary>Registry charm acquired / active / server state (the Charms tab and RynthILTGetCharmsJson).</summary>
public IltCharmTracker Charms { get; }
/// <summary>The Mini Remote's Charms tab (registry charms with toggles, the Guardian Hand).</summary>
public IltCharms CharmsTab { get; }
/// <summary>Temple guardians: riddle translator, hand-in, attribute turn-in tracker.</summary>
public IltGuardian Guardian { get; }
/// <summary>Vaulted Dungeons keeper (Mini Remote tab). ILT-only and behind its master switch (State.VaultedDungeonsEnabled), off by default.</summary>
public IltVaultedDungeons VaultedDungeons { get; }
/// <summary>The Empyrean Handler's lethal ring: asks RynthAi to back away (RynthAi.Hub BackAwayFrom).</summary>
public IltRingEvade RingEvade { get; }
/// <summary>T11 gear: the "/aug" wield counters for RynthAi's loot rules, "/ilt t11".</summary>
public IltT11 T11 { get; }
/// <summary>
/// Dynamic Stamps (from RynthOracle 2026-10-21): the NPC stamps had and missing, RynthNav's way there
/// and the Parchment hand-in (the Mini Remote's Quests section, "/ilt stamps").
/// </summary>
public IltDynamicStamps DynamicStamps { get; }
/// <param name="writesBlocked">True while this character's copy from RynthAi is unfinished (IltHubStore.WritesBlocked).</param>
/// <param name="legacyFolder">The character's RynthAi folder while that copy is unfinished (read-only fallback).</param>
public IltHubController(RynthCoreHost host, string charFolder, IltSettings settings, RynthAiClient ai,
Func<bool>? writesBlocked = null, string? legacyFolder = null)
{
var store = new IltHubStore(host, charFolder);
if (writesBlocked != null) store.WritesBlocked = writesBlocked;
store.LegacyFolder = legacyFolder;
var state = store.LoadState();
var capture = new IltChatCapture(host);
var inventory = new IltInventory(host, new IltObjects(host));
IltHubContext? ctxRef = null;
var options = new IltServerOptions(host, capture, state, text => ctxRef?.Chat(text), () => settings);
_ctx = new IltHubContext(host, state, store, capture, options, inventory, settings, ai);
ctxRef = _ctx;
Banking = new IltBanking(_ctx);
PetLogs = new IltPetLogs(_ctx);
Breeding = new IltPetBreeding(_ctx);
PetAutomation = new IltPetAutomation(_ctx);
Rates = new IltSessionRates(_ctx);
QuestBonus = new IltQuestBonus(_ctx);
Progression = new IltProgression(_ctx);
Gear = new IltGear(_ctx);
Games = new IltGames(_ctx);
Charms = new IltCharmTracker(_ctx);
CharmsTab = new IltCharms(_ctx, Charms);
Guardian = new IltGuardian(_ctx, QuestBonus);
VaultedDungeons = new IltVaultedDungeons(_ctx);
RingEvade = new IltRingEvade(_ctx);
T11 = new IltT11(_ctx);
DynamicStamps = new IltDynamicStamps(_ctx);
_features.AddRange(new IIltFeature[] { Banking, PetLogs, Breeding, PetAutomation, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, VaultedDungeons, Guardian, RingEvade, T11, DynamicStamps });
Banking.BalanceChanged += Rates.OnBankBalanceChanged;
Rates.MovingMoney = () => Banking.MovingMoney;
options.ProbeReplyTap = OnProbeReply;
_ui = new IltHubUi(this, _ctx);
_ctx.ShowTab = section => _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), "show");
RebuildProfile();
}
/// <summary>
/// The latest "RynthILT.Server" profile JSON: Leaftide features, fellowship rules and the /qb
/// list (Plugins/Shared/RynthIltServerApi.cs). Rebuilt on the pump about once a second so any
/// thread (ServerInterface) may read it.
/// </summary>
public string ProfileJson => _profileJson;
/// <summary>Rebuilds <see cref="ProfileJson"/> from the current server options. Pump thread.</summary>
private void RebuildProfile()
{
IltServerOptions o = _ctx.Options;
_profileJson = IltFeatureCatalog.BuildProfileJson(
o.IsIltLikeWorld, o.WorldName, _ctx.State.ForceLeaftideFeatures,
o.Source ?? string.Empty, o.LastRefreshUtc, o.Get,
QuestBonus.Snapshot());
}
/// <summary>
/// The charms JSON ("RynthILT.Data" GetCharmsJson). Reading it marks the charms as watched, so
/// the pump keeps the snapshot fresh while a reader is showing it; "" until the first rebuild
/// after that. Any thread.
/// </summary>
public string CharmsJson
{
get { System.Threading.Interlocked.Exchange(ref _charmsReadAt, IltHubContext.NowMs); return _charmsJson; }
}
/// <summary>The bank JSON ("RynthILT.Data" GetBankJson), as <see cref="CharmsJson"/>.</summary>
public string BankJson
{
get { System.Threading.Interlocked.Exchange(ref _bankReadAt, IltHubContext.NowMs); return _bankJson; }
}
/// <summary>A reader's charm Toggle, posted to the pump (IltCharms checks the id). Any thread.</summary>
public void RequestCharmToggle(uint objectId)
=> _ctx.Post(() =>
{
if (!_ctx.Options.IsIltLikeWorld) return;
if (!CharmsTab.ToggleFromReader(objectId))
RynthLog.Trace(LogCat.IltGear, $"reader toggle refused: 0x{objectId:X8} isn't a carried charm");
_charmsBuiltAt = 0; // show the new state on the next tick
});
/// <summary>
/// The pet breeding JSON ("RynthILT.Data" GetPetBreedingJson).
/// Reading it keeps the tracker scanning; "" off an ILT world or before its first scan. Any thread.
/// </summary>
public string PetBreedingJson => _ctx.Options.IsIltLikeWorld ? Breeding.ReaderJson : string.Empty;
/// <summary>A reader's breeding verb line, posted to the pump (IltPetBreeding.RunVerb). Any thread.</summary>
public void RequestBreedingVerb(string line)
=> _ctx.Post(() =>
{
if (!_ctx.Options.IsIltLikeWorld) return;
Breeding.RunVerb(line);
});
/// <summary>
/// The Temple guardian JSON ("RynthILT.Data" GetGuardianJson): switches, last answer, hand-in
/// status and attribute turn-ins. "" off an ILT world. Any thread.
/// </summary>
public string GuardianJson => _ctx.Options.IsIltLikeWorld ? Guardian.ReaderJson(_ctx.Options.WorldName) : string.Empty;
/// <summary>A reader's guardian verb line, posted to the pump (IltGuardian.RunVerb). Any thread.</summary>
public void RequestGuardianVerb(string line)
=> _ctx.Post(() =>
{
if (!_ctx.Options.IsIltLikeWorld) return;
Guardian.RunVerb(line);
});
/// <summary>A reader's bank verb line, posted to the pump (IltBanking.RunVerb). Any thread.</summary>
public void RequestBankVerb(string line)
=> _ctx.Post(() =>
{
if (!_ctx.Options.IsIltLikeWorld) return;
Banking.RunVerb(line);
_bankBuiltAt = 0;
});
/// <summary>Pump: rebuilds the charms / bank snapshots a reader (or the Banking tab's every-character table) is watching.</summary>
private void RebuildReaderData(long now)
{
if (now - System.Threading.Interlocked.Read(ref _charmsReadAt) < DataWatchMs && now - _charmsBuiltAt >= DataRebuildMs)
{
_charmsBuiltAt = now;
_charmsJson = CharmsTab.BuildReaderJson();
}
bool bankWatched = now - System.Threading.Interlocked.Read(ref _bankReadAt) < DataWatchMs;
Banking.ReaderWatching = bankWatched;
// The Banking tab's every-character table (IltBankRoster) uses the same rows while it is on screen.
bool rosterWatched = now - Banking.RosterWatchedAt < DataWatchMs;
if (!bankWatched && !rosterWatched || now - _bankBuiltAt < DataRebuildMs) return;
_bankBuiltAt = now;
if (_siblingsReadAt == 0 || now - _siblingsReadAt >= SiblingReadMs)
{
_siblingsReadAt = now;
_siblings = IltBankExport.ReadSiblings(_ctx.Store.CharFolder);
}
IltServerOptions o = _ctx.Options;
string me = _ctx.CharName.Length > 0 ? _ctx.CharName : System.IO.Path.GetFileName(_ctx.Store.CharFolder.TrimEnd('\\', '/'));
var rows = new List<IltBankExport.Row>(_siblings.Count + 1) { new(me, true, _ctx.State.Bank) };
rows.AddRange(_siblings);
if (rosterWatched) Banking.PublishRoster(IltBankRoster.Build(rows));
if (!bankWatched) return;
int enabled = o.IsOn(IltFeature.Bank) ? 1 : o.IsOff(IltFeature.Bank) ? 0 : -1;
_bankJson = IltBankExport.Build(o.IsIltLikeWorld, enabled, o.WorldName, me, rows, Banking.LatestResult, Banking.Transactions);
}
public IltHubState State => _ctx.State;
public IltServerOptions Options => _ctx.Options;
internal IltHubContext Context => _ctx;
/// <summary>World is ILT-like and the server has at least one ILT feature on.</summary>
public bool Available => _ctx.Options.IsIltLikeWorld && _ctx.Options.AnyFeatureOn;
/// <summary>
/// Whether a section can be shown now: the ILT tabs and the Guardian need server features.
/// Character (moved to RynthOracle) always answers true so its redirect is never refused.
/// </summary>
public bool SectionAvailable(IltSection section) => section switch
{
IltSection.Character => true,
IltSection.Banking => Available && !_ctx.Options.IsOff(IltFeature.Bank),
IltSection.Games => Available && Games.AnyGameAvailable,
// Content, not a server feature bit: an ILT world and the master switch.
IltSection.VaultedDungeons => _ctx.Options.IsIltLikeWorld && VaultedDungeons.MasterEnabled(),
_ => Available,
};
/// <summary>
/// The Mini Remote offers the Infinite Leaftide tabs: an ILT-like world (or the Force-ILT
/// override from RynthCore Options > Diagnostics). The tabs then follow <see cref="SectionAvailable"/>.
/// </summary>
public bool OffersTabs => _ctx.Options.IsIltLikeWorld;
/// <summary>Whether the Mini Remote's tab bar shows <paramref name="section"/>.</summary>
public bool TabShown(IltSection section) => OffersTabs && IltSections.IsTab(section) && SectionAvailable(section);
/// <summary>Render thread: one Mini Remote ILT tab's body (RynthAi's MiniRemoteHud draws the tab bar).</summary>
public void RenderTab(IltSection section) => _ui.RenderTab(section);
/// <summary>Render thread: a tab was just drawn as RynthCore's section view (it counts as the Mini Remote on screen).</summary>
public void NoteTabDrawn() => System.Threading.Interlocked.Exchange(ref _tabDrawnAt, IltHubContext.NowMs);
/// <summary>
/// Render thread: the ILT session extras (coins, pyreals, item conversions) in RynthCore's Mini
/// Remote "Session Stats" section, below RynthAi's session stats (surface "section:ilt-rates").
/// </summary>
public void RenderRatesSection() => _ui.RenderRatesSection();
/// <summary>Render thread: the /qb list in RynthILT's own Quests section (surface "section:ilt-questbonus").</summary>
public void RenderQuestBonusSection() => _ui.RenderQuestBonusSection();
/// <summary>Render thread: the Guardian panel's body (RynthPluginRenderEmbed "guardian").</summary>
public void RenderGuardianPanel() => _ui.RenderGuardianPanel();
/// <summary>
/// Render thread: the Dynamic Stamps page (surface "section:ilt-dynstamps" in RynthILT's Quests
/// section, and the "/ilt stamps" window); a line saying so off ILT.
/// </summary>
public void RenderDynamicStamps()
{
if (!_ctx.Options.IsIltLikeWorld)
{
ImGuiNET.ImGui.TextDisabled("Dynamic Stamps are an Infinite Leaftide quest line; this world isn't treated as ILT.");
return;
}
DynamicStamps.Render();
}
/// <summary>
/// Render thread: the pet breeding tracker ("/ilt breeding"; RynthAi's Mini Remote also shows it
/// as the Pets tab's Breeding). A line saying so off ILT or where the server has pet breeding off.
/// </summary>
public void RenderBreedingWindowBody()
{
if (!_ctx.Options.IsIltLikeWorld)
{
ImGuiNET.ImGui.TextDisabled("Pet breeding is an Infinite Leaftide feature; this world isn't treated as ILT.");
return;
}
if (_ctx.Options.IsOff(RynthCore.Plugin.Shared.RynthIltHub.FeaturePetBreeding))
{
ImGuiNET.ImGui.TextDisabled("This server has pet breeding switched off.");
return;
}
Breeding.RenderSection();
}
/// <summary>Render thread: one of the sections RynthAi draws (RynthILT.Hub RenderSection); false = nothing drawn.</summary>
public bool RenderSection(string id) => _ui.RenderSection(id);
/// <summary>The Force-ILT world override (world identity only; features still come from the server). Set from any thread.</summary>
public bool ForceIltWorld
{
get => _ctx.State.ForceLeaftideFeatures;
set => _forceRequest = value ? 1 : 0;
}
/// <summary>Re-asks the server which features are on (safe from the render thread: posted to the pump).</summary>
public void RequestOptionsRefresh() => _ctx.Post(() => _ctx.Options.Refresh(manual: true));
// ── Lifecycle ───────────────────────────────────────────────────────────
/// <summary>
/// Login: remember the character, schedule the options check, import UB data once.
/// <paramref name="forceFromMigration"/>: the character's RynthAi profile had "Force enable" ticked.
/// </summary>
public void OnLoginComplete(string charName, bool forceFromMigration)
{
_ctx.CharName = charName ?? string.Empty;
if (forceFromMigration) _ctx.State.ForceLeaftideFeatures = true;
RynthLog.Event(LogEvents.IltLogin, $"login: char='{_ctx.CharName}' world='{_ctx.Options.WorldName}'");
_ctx.Options.OnLoginComplete();
_ctx.Inventory.Reset();
Rates.Reset();
_questGeneration = 0;
if (!_ctx.State.UbSidecarsImported && _ctx.CharName.Length > 0)
{
_ctx.State.UbSidecarsImported = true;
string world = _ctx.Options.WorldName;
Banking.ImportUb(tx => _ctx.Store.ImportUbSidecars(_ctx.State, tx, world, _ctx.CharName));
}
}
/// <summary>A RynthAi /myquests refresh ended since the last look: tell the options (the "quests" bit).</summary>
private void PollQuestOutcome()
{
if (!_ctx.Ai.TryGetQuestStatus(out var st) || st.Generation == _questGeneration) return;
_questGeneration = st.Generation;
if (st.Generation > 0) _ctx.Options.NoteQuestTrackerOutcome(st.Disabled != 0, st.Count);
}
/// <summary>Pump-thread tick.</summary>
public void Tick()
{
long now = IltHubContext.NowMs;
int force = _forceRequest;
if (force >= 0)
{
_forceRequest = -1;
_ctx.State.ForceLeaftideFeatures = force == 1;
}
_ctx.DrainPosted();
_ctx.Capture.Tick();
_ctx.Options.Tick();
PollQuestOutcome();
// The charms / bank snapshots other plugins read (RynthILT.Data), only while watched.
try { RebuildReaderData(now); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "RebuildReaderData"); }
// The profile other plugins read ("RynthILT.Server"): world, feature states, fellowship, /qb.
if (now - _profileBuiltAt >= ProfileRebuildMs)
{
_profileBuiltAt = now;
try { RebuildProfile(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "RebuildProfile"); }
}
// "Mini Remote on screen" gates bank auto-refresh and the gear / split-arrow scans: RynthAi's Mini
// Remote, or one of the tabs drawn as RynthCore's section view in the last couple of seconds.
_ctx.State.WindowVisible = _ctx.Ai.MiniRemoteVisible
|| now - System.Threading.Interlocked.Read(ref _tabDrawnAt) < TabDrawnMs;
// One hint per session once the server confirms ILT features. The Mini Remote is separate
// from the main RynthAi panel, so say how to open it.
if (!_availabilityAnnounced && Available)
{
_availabilityAnnounced = true;
if (!_ctx.State.WindowVisible)
_ctx.Chat("[Mini Remote] ILT server features detected. Open the Mini Remote (bar button, /rc miniremote) for the ILT tabs.");
}
// Every feature here is Infinite Leaftide's: dormant on any other world.
if (_ctx.Options.IsIltLikeWorld)
{
foreach (var f in _features)
{
try { f.Tick(now); }
catch (Exception ex) { RynthLog.Exception(CategoryOf(f), ex, $"{f.GetType().Name}.Tick"); }
}
}
// Expire an unanswered chat confirmation so a stale "/ra hub confirm" can't fire it later.
if (_pendingAction != null && now - _pendingAt > ConfirmWindowMs)
{
RynthLog.Event(LogEvents.IltConfirmation, $"confirmation expired: {_pendingLabel}");
_ctx.Chat($"[Mini Remote] Confirmation for '{_pendingLabel}' expired.");
ClearPending();
}
if (now - _lastSaveAt >= SaveIntervalMs)
{
_lastSaveAt = now;
_ctx.Store.SaveStateIfDirty(_ctx.State);
}
}
/// <summary>A creature's health update from the server (RynthPluginOnUpdateHealth): auto-capture's fallback health read.</summary>
public void OnUpdateHealth(uint objectId, float healthRatio)
{
if (!_ctx.Options.IsIltLikeWorld) return;
PetAutomation.NoteHealth(objectId, healthRatio);
}
/// <summary>
/// The sub-tabs RynthILT adds to one of RynthAi's tabs (RynthILT.Hub GetSubTabs): the Pets tab's
/// Breeding on an ILT world whose server hasn't reported pet breeding off. (Id, label) pairs; the
/// id is a RenderSection id. Any thread.
/// </summary>
public (string Id, string Label)[] SubTabs(string parent)
{
if (!string.Equals(parent, RynthCore.Plugin.Shared.RynthServerHub.TabParentPets, StringComparison.OrdinalIgnoreCase)
|| !_ctx.Options.IsIltLikeWorld || _ctx.Options.IsOff(RynthCore.Plugin.Shared.RynthIltHub.FeaturePetBreeding))
return Array.Empty<(string, string)>();
return new[] { (RynthCore.Plugin.Shared.RynthIltHub.SectionPetBreeding, "Breeding") };
}
/// <summary>
/// RynthILT.Hub GetSetting: a setting another plugin mirrors (RynthServerHub.Setting*), -1 when not offered
/// (unknown key, or off an ILT world: the engine row then hides). Any thread.
/// </summary>
public int GetSetting(string key) => key switch
{
RynthCore.Plugin.Shared.RynthServerHub.SettingVaultedDungeons when _ctx.Options.IsIltLikeWorld
=> _ctx.State.VaultedDungeonsEnabled ? 1 : 0,
_ => -1,
};
/// <summary>
/// RynthILT.Hub GetText: a short text RynthAi shows (RynthServerHub.Text*); "" for an unknown id, and
/// the session tail off ILT. Any thread.
/// </summary>
public string GetText(string id) => id switch
{
RynthCore.Plugin.Shared.RynthServerHub.TextServerId => IltSectionsManifest.Server,
RynthCore.Plugin.Shared.RynthServerHub.TextSessionReport when _ctx.Options.IsIltLikeWorld => _ui.SessionReportTail(),
_ => string.Empty,
};
/// <summary>RynthILT.Hub SetSetting: false for an unknown key. Saved with the state (next periodic save). Any thread.</summary>
public bool SetSetting(string key, int value)
{
if (key != RynthCore.Plugin.Shared.RynthServerHub.SettingVaultedDungeons) return false;
bool on = value != 0;
if (_ctx.State.VaultedDungeonsEnabled != on)
RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons master switch {(on ? "on" : "off")} (Settings window)");
_ctx.State.VaultedDungeonsEnabled = on;
return true;
}
/// <summary>The server's killer notification (pump thread): restarts the Vaulted Dungeons no-kill timer, on ILT only.</summary>
public void OnKillNotification()
{
if (!_ctx.Options.IsIltLikeWorld) return;
try { VaultedDungeons.OnKillNotification(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "VaultedDungeons.OnKillNotification"); }
}
/// <summary>Pump-thread chat line. Returns true when the line should be hidden.</summary>
public bool OnChat(string text, int chatType = -1)
{
if (string.IsNullOrEmpty(text)) return false;
string line = text.TrimEnd('\r', '\n');
_ctx.Options.OnChatLine(line);
bool eat = _ctx.Capture.OnChatLine(line);
if (!_ctx.Options.IsIltLikeWorld) return eat;
// The ring line needs its chat type (a player repeating it is ignored).
try { RingEvade.OnChatLine(line, chatType); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "IltRingEvade.OnChatLine"); }
foreach (var f in _features)
{
try { eat |= f.OnChat(line); }
catch (Exception ex) { RynthLog.Exception(CategoryOf(f), ex, $"{f.GetType().Name}.OnChat"); }
}
return eat;
}
/// <summary>Maps a feature module to its diagnostics category so its trace/exception lines land in its own file.</summary>
private static LogCat CategoryOf(IIltFeature f) => f switch
{
IltBanking => LogCat.IltBanking,
IltPetLogs or IltPetBreeding or IltPetAutomation => LogCat.IltPets,
IltSessionRates => LogCat.IltRates,
IltQuestBonus or IltDynamicStamps => LogCat.IltQuests,
IltProgression => LogCat.IltProgression,
IltGear or IltCharms => LogCat.IltGear,
IltGames => LogCat.IltGames,
IltVaultedDungeons => LogCat.IltHub,
_ => LogCat.IltHub,
};
/// <summary>Logout / teardown: stop automation and flush to disk.</summary>
public void OnLogout()
{
RynthLog.Event(LogEvents.IltLogout, $"logout: stopping features for '{_ctx.CharName}'");
ClearPending();
foreach (var f in _features)
{
try { f.OnLogout(); }
catch (Exception ex) { RynthLog.Exception(CategoryOf(f), ex, $"{f.GetType().Name}.OnLogout"); }
}
_ctx.Capture.Clear();
_ctx.Store.SaveStateIfDirty(_ctx.State);
}
/// <summary>
/// JSON for the engine Skills panel's Progression tab (RynthILTGetProgressionJson).
/// "available" is false off ILT-like worlds; the panel then hides the ILT sections. Pump thread.
/// </summary>
public string BuildProgressionJson()
{
var sb = new System.Text.StringBuilder(2048);
sb.Append("{\"available\":").Append(Available ? "true" : "false");
sb.Append(",\"world\":\"").Append(IltStyle.JsonEscape(_ctx.Options.WorldName ?? string.Empty)).Append("\",");
Progression.AppendSnapshotJson(sb);
sb.Append('}');
return sb.ToString();
}
/// <summary>JSON for RynthILTGetCharmsJson / RynthPluginGetCharmsJson (an older engine's Settings "Charms Tracking" tab). Pump thread.</summary>
public string BuildCharmsJson() => Charms.BuildJson();
/// <summary>Render thread: Games HUD and confirmation popups.</summary>
public void Render() => _ui.Render();
// ── Probe taps: reuse login-probe replies so tabs fill without extra commands ──
private void OnProbeReply(string key, IltChatResult r)
{
if (r.Lines.Count == 0) return;
switch (key)
{
case IltFeature.Aug:
Progression.ApplyAugLines(r.Lines);
// Probe's OnComplete is not RequestAugs' — drain a queued Refresh current / empty retry.
Progression.AfterExternalAugCapture();
break;
case IltFeature.Pets: PetLogs.ApplyRoster(false, r.Lines); break;
case IltFeature.Shinies: PetLogs.ApplyRoster(true, r.Lines); break;
case IltFeature.Qb: QuestBonus.ApplyQbProbe(r.Lines); break;
// Bank lines are parsed passively by IltBanking.OnChat as they arrive.
}
}
// ── Commands ────────────────────────────────────────────────────────────
/// <summary>
/// The ILT verbs: "/ra hub [open &lt;ILT tab&gt; [show|hide|toggle]|tab &lt;ILT tab&gt;|refresh|bank|status|
/// force on|off|servers [list]|profile save|load|list ...|suit list|test|load ...|clap|attr ...|
/// confirm|cancel]" (RynthAi keeps show/hide/toggle and its own Quests / Pets tabs, and forwards
/// the rest here; "/ilt hub ..." comes straight here), "/ra bounty [show|hide|toggle]" (aliases
/// bounties / bountys: RynthCore's ILT Bounties panel), "/ra guardian ..." (window: RynthCore's
/// ILT Guardian panel; the rest IltGuardian.HandleCommand) and "rates reset" (the Mini Remote's
/// Reset XP). Pump thread. Returns false if not handled.
/// </summary>
public bool HandleCommand(string verb, string[] args)
{
RynthLog.Event(LogEvents.IltCommand, $"command: /ra {verb} {string.Join(" ", args)}".TrimEnd());
if (verb.Equals("rates", StringComparison.OrdinalIgnoreCase))
{
// "rates reset": the coin / pyreal session starts over with RynthAi's session stats.
Rates.Reset();
return true;
}
if (IsBountyVerb(verb))
{
// Bounties are RynthILT's Bounties window (RynthCore's ILT button); open that panel.
OpenEnginePanel("bounties", "Bounties", args.Length > 0 ? args[0] : "toggle");
return true;
}
if (verb.Equals("guardian", StringComparison.OrdinalIgnoreCase))
{
// "/ra guardian window [show|hide|toggle]" opens RynthCore's ILT Guardian panel;
// everything else is the Guardian's.
if (args.Length > 0 && args[0].Equals("window", StringComparison.OrdinalIgnoreCase))
OpenEnginePanel("guardian", "Guardian", args.Length > 1 ? args[1] : "toggle");
else
Guardian.HandleCommand(args);
return true;
}
if (!verb.Equals("hub", StringComparison.OrdinalIgnoreCase)) return false;
string cmd = args.Length > 0 ? args[0].ToLowerInvariant() : "help";
string rest = args.Length > 1 ? string.Join(" ", args.Skip(1)) : string.Empty;
switch (cmd)
{
case "show":
case "hide":
case "toggle":
// The Mini Remote is RynthAi's ("/ilt hub show" lands here).
_ctx.Chat("[Mini Remote] " + _ctx.Ai.MiniRemoteTab(IltSections.RemoteTab, cmd));
break;
case "open":
if (args.Length > 1 && IsBountyVerb(args[1]))
{
OpenEnginePanel("bounties", "Bounties", args.Length > 2 ? args[2] : "toggle");
break;
}
if (args.Length < 2 || !IltSections.TryParse(args[1], out IltSection section))
{
// Quests and Pets are RynthAi's tabs: not ours to open.
if (args.Length >= 2 && IltSections.IsUniversalTabName(args[1])) return false;
_ctx.Chat("[Mini Remote] Usage: /ra hub open pets|banking|gear|charms|games|vaulted|guardian|bounties [show|hide|toggle] (character: /ro character, quests: /ro)");
break;
}
OpenSection(section, args.Length > 2 ? args[2] : "toggle");
break;
case "tab":
// The engine's dashboard: it opens its Mini Remote window itself, so only switch tabs.
if (args.Length > 1 && IltSections.TryParse(args[1], out IltSection tab) && IltSections.MovedCommand(tab) is string moved)
OpenMoved(tab, moved);
else if (args.Length > 1 && IltSections.TryParse(args[1], out tab) && IltSections.IsTab(tab))
_ctx.Ai.MiniRemoteTab(IltSections.TabId(tab), "select");
else
return false; // the Remote tab or a RynthAi tab: RynthAi's
break;
case "refresh": _ctx.Options.Refresh(manual: true); break;
case "bank": Banking.RequestRefresh(quiet: false); break;
// "/ilt qb": reads the /qb list again (the Quests tab's quest bonus section).
case "qb": _ctx.Chat("[RynthILT] " + QuestBonus.RefreshQb()); break;
case "status": PrintStatus(); break;
case "features": PrintFeatures(); break;
case "force":
_ctx.State.ForceLeaftideFeatures = !rest.Equals("off", StringComparison.OrdinalIgnoreCase);
_ctx.Chat(IltServerOptions.EngineDecides
? $"[Mini Remote] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")} for this character (RynthCore counts it unless /rc server ilt off). Use /ra hub refresh to re-check the server."
: $"[Mini Remote] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")}. Use /ra hub refresh to re-check the server.");
break;
case "servers": HandleServers(rest); break;
case "profile": HandleProfile(args.Skip(1).ToArray()); break;
case "suit": HandleSuit(args.Skip(1).ToArray()); break;
case "clap": Gear.ChunkClap.ClapNow(manual: true); break;
case "attr": HandleAttr(args.Skip(1).ToArray()); break;
case "confirm": RunPending(); break;
case "cancel":
_ctx.Chat(_pendingAction != null ? $"[Mini Remote] Cancelled '{_pendingLabel}'." : "[Mini Remote] Nothing to cancel.");
ClearPending();
break;
default:
_ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote)|refresh|bank|status|features|force on|off|servers [list]|clap|confirm|cancel");
_ctx.Chat("[Mini Remote] /ra hub open pets|banking|gear|charms|games|vaulted [show|hide|toggle] (Mini Remote tabs; character: /ro character, quests: /ro)");
_ctx.Chat("[Mini Remote] /ilt vaulted [on|off|toggle|status] (Vaulted Dungeons; master switch: /ilt settings or Settings > Navigation > Vaulted Dungeons)");
_ctx.Chat("[Mini Remote] /ra hub profile list|save <name> [shared]|load <name> /ra hub suit list|test|load [name]");
_ctx.Chat("[Mini Remote] /ra hub attr run|stop|costs|status|auto on|off|every <min>|raise <stat> <n> (Skills panel > Progression)");
_ctx.Chat("[Mini Remote] /ra quests refresh (quiet /myquests) /ra pets [show|hide] /ilt qb (the quest bonus list)");
_ctx.Chat("[Mini Remote] /ra guardian [window|translate <text>|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status] (window: ILT button > Guardian)");
_ctx.Chat("[Mini Remote] /ra bounty [show|hide|toggle] (RynthCore's ILT button > Bounties, /rc bounties)");
_ctx.Chat("[Mini Remote] The ILT verbs also work as /ilt hub ..., /ilt guardian ... (RynthILT).");
break;
}
return true;
}
/// <summary>"/ra hub features": every Leaftide feature RynthILT supports, with the server's state for each.</summary>
private void PrintFeatures()
{
IltServerOptions o = _ctx.Options;
string world = o.WorldName.Length > 0 ? o.WorldName : "unknown world";
_ctx.Chat($"[Mini Remote] Leaftide features on {world} ({(o.IsIltLikeWorld ? "ILT world" : "not an ILT world")}, "
+ $"fellowships up to {IltFeatureCatalog.FellowshipMax(o.IsIltLikeWorld)}):");
foreach (string line in IltFeatureCatalog.BuildChatLines(o.IsIltLikeWorld, o.Get))
_ctx.Chat("[Mini Remote] " + line);
}
/// <summary>"/ra hub servers [list | &lt;names, comma separated&gt; | default]": which world names count as Infinite Leaftide.</summary>
private void HandleServers(string rest)
{
string arg = rest.Trim();
if (arg.Length > 0 && !arg.Equals("list", StringComparison.OrdinalIgnoreCase))
{
var list = arg.Equals("default", StringComparison.OrdinalIgnoreCase)
? new List<string>(ServerFeatureGate.DefaultServerNames)
: ServerFeatureGate.ParseList(arg);
if (list.Count == 0) { _ctx.Chat("[Mini Remote] Usage: /ra hub servers <name, *pattern*, ...> | default | list"); return; }
_ctx.Settings.ServerNames = list;
_ctx.SaveSettings();
}
_ctx.Chat("[Mini Remote] ILT world names: " + ServerFeatureGate.FormatList(ServerFeatureGate.Patterns(_ctx.Settings)));
_ctx.Chat("[Mini Remote] " + ServerFeatureGate.Describe(_ctx.Options.WorldName, _ctx.Settings, _ctx.State.ForceLeaftideFeatures));
}
/// <summary>"/ra hub attr ...": the attribute raiser from chat (same verbs as the Progression tab).</summary>
private void HandleAttr(string[] a)
{
var raiser = Progression.Attributes;
string sub = a.Length > 0 ? a[0].ToLowerInvariant() : "status";
switch (sub)
{
case "run": raiser.HandleRemote("attrrun", new[] { "attrrun" }); break;
case "stop": raiser.HandleRemote("attrstop", new[] { "attrstop" }); break;
case "costs": raiser.HandleRemote("attrcosts", new[] { "attrcosts" }); break;
case "auto": raiser.HandleRemote("attrauto", new[] { "attrauto", a.Length > 1 ? a[1] : "off" }); break;
case "every": raiser.HandleRemote("attrevery", new[] { "attrevery", a.Length > 1 ? a[1] : "5" }); break;
case "raise" when a.Length > 2: raiser.HandleRemote("attrraise", new[] { "attrraise", a[1], a[2] }); break;
default:
var c = _ctx.State.Character;
string blocked = raiser.Blocker() ?? "ready";
_ctx.Chat($"[Mini Remote] Attribute raiser: {blocked}; auto={(c.AttrAutoRaise ? $"on every {c.AttrAutoRaiseMinutes}m" : "off")} "
+ $"mode={(IltAttributeRaiser.Mode)c.AttrRaiseMode} keep={IltParse.Compact(c.AttrKeepXp)} "
+ $"stats={(c.AttrRaiseStats.Count > 0 ? string.Join(",", c.AttrOrder.Where(c.AttrRaiseStats.Contains)) : "none ticked")}");
return;
}
}
/// <summary>"/ra bounty", "/ra bounties" and the "/ra bountys" spelling all reach the Bounties panel.</summary>
public static bool IsBountyVerb(string verb)
=> verb.Equals("bounty", StringComparison.OrdinalIgnoreCase)
|| verb.Equals("bounties", StringComparison.OrdinalIgnoreCase)
|| verb.Equals("bountys", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Applies show / hide / toggle to a section: a Mini Remote tab, or for the Guardian
/// RynthCore's ILT panel. Says what happened.
/// </summary>
private void OpenSection(IltSection section, string mode)
{
if (IltSections.MovedCommand(section) is string moved)
{
// Character left the Mini Remote: open its new home instead.
if (!mode.Equals("hide", StringComparison.OrdinalIgnoreCase)) OpenMoved(section, moved);
return;
}
if (!IltSections.IsTab(section))
{
OpenEnginePanel(IltSections.TabId(section), IltSections.Label(section), mode);
return;
}
if (section == IltSection.VaultedDungeons && !SectionAvailable(section))
{
_ctx.Chat(_ctx.Options.IsIltLikeWorld
? "[Mini Remote] The Vaulted Dungeons tab is off: turn on \"Vaulted Dungeons\" in the ILT settings (/ilt settings; also Settings > Navigation) (the master switch, off by default)."
: "[Mini Remote] Vaulted Dungeons is not available on this server (Infinite Leaftide / ACECustom only).");
return;
}
string reply = _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), mode);
if (!SectionAvailable(section) && !mode.Equals("hide", StringComparison.OrdinalIgnoreCase))
reply = $"The {IltSections.Label(section)} tab shows once the server reports that feature on.";
_ctx.Chat("[Mini Remote] " + reply);
}
/// <summary>
/// Opens the new home of a section that moved out of the Mini Remote (RynthOracle's Character
/// tab) by running its chat command, or says where it is when the command can't run (an older
/// RynthCore, or RynthOracle not loaded). Pump thread.
/// </summary>
public void OpenMoved(IltSection section, string command)
{
if (_ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser(command))
return;
_ctx.Chat($"[Mini Remote] {IltSections.Label(section)} moved to RynthOracle's Character tab ({command}); "
+ "the ILT session rates are in the Mini Remote's Session Stats.");
}
/// <summary>
/// Opens / closes one of RynthCore's ILT panels ("/rc bounties|guardian [show|hide|toggle]")
/// through the engine's chat dispatcher. Pump thread.
/// </summary>
public void OpenEnginePanel(string rcVerb, string label, string mode)
{
string m = (mode ?? string.Empty).ToLowerInvariant() switch
{
"show" or "on" or "open" => "show",
"hide" or "off" or "close" => "hide",
_ => "toggle",
};
if (_ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser($"/rc {rcVerb} {m}"))
return;
_ctx.Chat($"[Mini Remote] {label} is a RynthCore ILT panel: the bar's ILT button, or /rc {rcVerb}.");
}
/// <summary>"show"/"on" → true, "hide"/"off" → false, anything else flips <paramref name="current"/>.</summary>
private static bool ResolveToggle(string mode, bool current) => mode switch
{
"show" or "on" or "true" or "1" => true,
"hide" or "off" or "false" or "0" => false,
_ => !current,
};
private void PrintStatus()
{
var o = _ctx.Options;
_ctx.Chat($"[Mini Remote] World '{o.WorldName}' ILT={o.IsIltLikeWorld} force={_ctx.State.ForceLeaftideFeatures} source={(o.Source.Length > 0 ? o.Source : "none")} "
+ $"refreshed={(o.LastRefreshUtc == DateTime.MinValue ? "never" : o.LastRefreshUtc.ToLocalTime().ToString("t"))}");
var bits = o.SnapshotBits();
string on = string.Join(", ", bits.Where(b => b.Value == 1).Select(b => b.Key));
string off = string.Join(", ", bits.Where(b => b.Value == 0).Select(b => b.Key));
_ctx.Chat("[Mini Remote] on: " + (on.Length > 0 ? on : "-"));
_ctx.Chat("[Mini Remote] off: " + (off.Length > 0 ? off : "-"));
}
private void HandleProfile(string[] a)
{
string sub = a.Length > 0 ? a[0].ToLowerInvariant() : "list";
if (sub == "list")
{
var names = _ctx.Store.ListProfiles();
_ctx.Chat("[Mini Remote] Profiles: " + (names.Count > 0 ? string.Join(", ", names) : "(none)"));
return;
}
if (a.Length < 2) { _ctx.Chat("[Mini Remote] Usage: /ra hub profile save <name> [shared] | load <name>"); return; }
if (sub == "save")
{
bool shared = a.Length > 2 && a[2].Equals("shared", StringComparison.OrdinalIgnoreCase);
_ctx.Chat(_ctx.Store.SaveProfile(_ctx.State, a[1], shared, out string err)
? $"[Mini Remote] Saved {(shared ? "shared " : "")}profile '{a[1]}'." : "[Mini Remote] Save failed: " + err);
}
else if (sub == "load")
{
// Loading replaces the Hub's current settings, so it needs an explicit confirm.
string profile = a[1];
RequestConfirm($"load Hub profile '{profile}' (replaces current Hub settings)", () =>
_ctx.Chat(_ctx.Store.LoadProfile(_ctx.State, profile, out string err)
? $"[Mini Remote] Loaded profile '{profile}'." : "[Mini Remote] Load failed: " + err));
}
}
// ── Chat confirmations for destructive commands ─────────────────────────
/// <summary>How long a "/ra hub confirm" stays valid after the prompt.</summary>
private const long ConfirmWindowMs = 20000;
private string? _pendingLabel;
private Action? _pendingAction;
private long _pendingAt;
/// <summary>Arms a single pending action; a newer request replaces an older one.</summary>
private void RequestConfirm(string label, Action action)
{
_pendingLabel = label;
_pendingAction = action;
_pendingAt = IltHubContext.NowMs;
RynthLog.Event(LogEvents.IltConfirmation, $"confirmation requested: {label}");
_ctx.Chat($"[Mini Remote] About to {label}. Type /ra hub confirm within {ConfirmWindowMs / 1000} s, or /ra hub cancel.");
}
/// <summary>Runs the pending action if one is armed and still inside its window.</summary>
private void RunPending()
{
var action = _pendingAction;
string? label = _pendingLabel;
bool fresh = action != null && IltHubContext.NowMs - _pendingAt <= ConfirmWindowMs;
ClearPending();
if (!fresh || action == null) { _ctx.Chat("[Mini Remote] Nothing to confirm."); return; }
RynthLog.Event(LogEvents.IltConfirmation, $"confirmed: {label}");
try { action(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, $"confirmed action '{label}'"); }
}
private void ClearPending()
{
_pendingAction = null;
_pendingLabel = null;
_pendingAt = 0;
}
private void HandleSuit(string[] a)
{
string sub = a.Length > 0 ? a[0].ToLowerInvariant() : "list";
string? name = a.Length > 1 ? string.Join(" ", a.Skip(1)) : null;
switch (sub)
{
case "list":
var list = Gear.Suits.ListProfiles();
_ctx.Chat("[Mini Remote] Suits: " + (list.Count > 0 ? string.Join(", ", list.Select(p => p.Name)) : "(none)"));
break;
case "test":
foreach (string l in Gear.Suits.Test(name)) _ctx.Chat("[Mini Remote] " + l);
break;
case "load":
// Equipping a suit swaps gear mid-session, so it needs an explicit confirm.
RequestConfirm($"equip suit '{name ?? "(auto)"}'", () => _ctx.Chat("[Mini Remote] " + Gear.Suits.Load(name)));
break;
default:
_ctx.Chat("[Mini Remote] Usage: /ra hub suit list|test [name]|load [name]");
break;
}
}
}

View file

@ -0,0 +1,364 @@
// IltHubState.cs — Persisted per-character state for the ILT Hub (Infinite Leaftide tools).
// Originally SilentKelpie's ILT Hub state in RynthAi; moved to RynthILT 2026-10-13.
//
// Lives in %APPDATA%\RynthCore\RynthILT\<world>\<char>\hub.json (IltHubStore). The first
// login with RynthILT copies RynthAi's <charFolder>\ilt-hub.json there (IltMigration), so the
// shape stays compatible with that file: the parts that stayed with RynthAi's universal Mini
// Remote tabs (the Pets tab's settings, the quest tracker's filter and favorites, the VTank
// import path) are simply not read here any more. Serialized with the NativeAOT source-generated
// IltHubJsonContext (IncludeFields = true), so plain public fields are used throughout.
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>Root of everything the Hub remembers between sessions.</summary>
public sealed class IltHubState
{
/// <summary>Bumped when the shape changes in a way that needs a migration.</summary>
public int SchemaVersion = 1;
// ── Window / shell ──────────────────────────────────────────────────────
/// <summary>
/// Hub UI on screen: the Mini Remote or any ILT section window (IltHubController.Tick keeps it
/// current). Bank auto-refresh and the gear / split-arrow scans run only while it is true.
/// </summary>
public bool WindowVisible;
/// <summary>Unused since the tabbed Hub window was retired; kept so old files still load.</summary>
public int SelectedTab;
public bool GamesHudVisible = true;
/// <summary>
/// "This world is an ACECustom/ILT shard even though its name isn't InfiniteLeaftide."
/// World-identity override ONLY: it makes the Hub ask the server for its options, it
/// never turns a feature on by itself.
/// </summary>
public bool ForceLeaftideFeatures;
/// <summary>True once the one-time UtilityBelt sidecar import has run for this character.</summary>
public bool UbSidecarsImported;
/// <summary>
/// True once the RynthAi settings that moved to RynthILT on 2026-10-20 (the Pets tab's ACECustom
/// options, ...) were copied from this character's RynthAi files (IltMigration.ImportRynthAiSettings).
/// </summary>
public bool RynthAiSettingsImported;
/// <summary>Last-seen server feature bits. Cache only — overwritten by every login refresh.</summary>
public IltServerOptionsSnapshot ServerOptions = new();
public IltBankState Bank = new();
public IltPetState Pet = new();
public IltCharacterState Character = new();
public IltGearState Gear = new();
public IltGamesState Games = new();
public IltGuardianState Guardian = new();
/// <summary>Infinite Leaftide combat helpers (moved from RynthAi's profile 2026-10-20).</summary>
public IltCombatState Combat = new();
/// <summary>
/// The Vaulted Dungeons keeper's master switch (off by default): while off it does nothing (no
/// recalls, no /rc quit, no tab). RynthAi's "Vaulted Dungeons" setting until 2026-10-20 (copied once);
/// set in the ILT settings ("/ilt settings") or the engine's Settings > Navigation row (RynthAi
/// mirrors it through RynthILT.Hub GetSetting / SetSetting).
/// </summary>
public bool VaultedDungeonsEnabled;
/// <summary>ACECustom T11 gear (IltT11): the item-aug override (moved from RynthAi's profile 2026-10-20).</summary>
public IltT11State T11 = new();
/// <summary>The ILT sections of RynthAi's Remote tab (moved from RynthAi's huds.json 2026-10-20).</summary>
public IltRemoteState Remote = new();
}
// ── RynthAi's Remote tab ────────────────────────────────────────────────────
public sealed class IltRemoteState
{
/// <summary>The Remote tab's Bank section (ILT bank balances). Was RynthAi's MiniShowBank.</summary>
public bool ShowBank = true;
/// <summary>The Remote tab's Guardian line (the last Temple guardian answer). Was RynthAi's MiniShowGuardian.</summary>
public bool ShowGuardian = true;
}
// ── T11 ─────────────────────────────────────────────────────────────────────
public sealed class IltT11State
{
/// <summary>
/// The item augmentation count T11 wield gates use ("T11: Can Wield" in RynthAi's loot rules) instead
/// of the "/aug" reply's; -1 = automatic (read from /aug). "/ilt t11 augs &lt;n|auto&gt;". Was RynthAi's
/// T11ItemAugsOverride.
/// </summary>
public int ItemAugsOverride = -1;
}
// ── Combat ──────────────────────────────────────────────────────────────────
public sealed class IltCombatState
{
/// <summary>
/// When the Empyrean Handler channels its lethal ring and the character is inside it, have RynthAi
/// back-jump away and re-engage (IltRingEvade; RynthAi acts only while its macro runs with combat
/// on). On by default because it is gated that way. Was RynthAi's HandlerRingEvade.
/// </summary>
public bool HandlerRingEvade = true;
}
/// <summary>Cached result of the server-options check (see IltServerOptions).</summary>
public sealed class IltServerOptionsSnapshot
{
public string WorldName = string.Empty;
/// <summary>"probe" (the login probe) or "" (never refreshed).</summary>
public string Source = string.Empty;
public DateTime LastRefreshUtc = DateTime.MinValue;
/// <summary>Feature key → -1 unknown, 0 off, 1 on.</summary>
public Dictionary<string, int> Bits = new(StringComparer.OrdinalIgnoreCase);
}
// ── Banking ─────────────────────────────────────────────────────────────────
public sealed class IltBankState
{
public long Pyreals;
public long Luminance;
public long LegendaryKeys;
public long MythicalKeys;
public long EnlightenedCoins;
public long WeaklyEnlightenedCoins;
/// <summary>Bound to the character: deposit and withdraw only, never transferred.</summary>
public long PrestigeCoins;
public DateTime LastUpdated = DateTime.MinValue;
/// <summary>Last transfer recipient typed into the transfer form.</summary>
public string TransferTarget = string.Empty;
public int TransferCurrencyIndex;
/// <summary>Transfer form's trade-note denomination (IltBankCommands.NoteDenominations; 9 = MMD).</summary>
public int TransferNoteIndex = 9;
/// <summary>Deposit / withdraw form choices (IltBankCommands.Deposits / Withdrawals / NoteDenominations).</summary>
public int DepositIndex;
public int WithdrawIndex;
public int WithdrawNoteIndex = 9;
/// <summary>Re-issue /bank every N seconds while the Hub is open (0 = manual only).</summary>
public int AutoRefreshSeconds = 120;
}
/// <summary>One "Transferred …" / "Received …" bank line seen in chat.</summary>
public sealed class IltBankTransaction
{
public DateTime Timestamp;
/// <summary>"Sent" or "Received".</summary>
public string Type = string.Empty;
public string Currency = string.Empty;
public long Amount;
public string OtherPlayer = string.Empty;
public string Description = string.Empty;
}
// ── Pet ─────────────────────────────────────────────────────────────────────
public sealed class IltPetState
{
/// <summary>Last captured /pets and /shinies rosters (display only; the Pets tab's logs).</summary>
public List<string> PetLog = new();
public List<string> ShinyLog = new();
/// <summary>The breeding tracker: rules this server showed, growth stage names, recent events (IltPetBreeding).</summary>
public IltBreedingState Breeding = new();
// ACECustom's parts of the Pets tab (IltPetAutomation, moved from RynthAi 2026-10-20; copied once
// from RynthAi's miniremote.json by IltMigration.ImportRynthAiSettings). New names on purpose: an
// old ilt-hub.json copy still carries RynthAi's UsePyrealRefillPath / AutoCaptureEnabled /
// CaptureLensIndex from before 2026-10-13, and those stale values must not be read back.
/// <summary>
/// Summon from an EMPTY essence while the Summon Essence Refill charm is on (the server refills it
/// from banked pyreals). Still needs the server to confirm the feature (RynthAi.Hub's PetManager
/// asks AllowSummonOnEmpty).
/// </summary>
public bool RefillFromEmpty;
/// <summary>Use the chosen siphon lens on the nearest creature once it is weak enough (off by default).</summary>
public bool AutoCapture;
/// <summary>Index into PetCaptureRules.Lenses (Flawed to Asheron's).</summary>
public int CaptureLens;
// The Pets tab's own settings (roster, healing / cosmetic pets) are RynthAi's (its miniremote.json).
}
// ── Character ───────────────────────────────────────────────────────────────
public sealed class IltCharacterState
{
/// <summary>Item → coin conversion table used by the session-rates strip.</summary>
public List<IltItemConversion> ItemConversions = new()
{
new IltItemConversion { ItemName = "Strawberry Jam Jar", ItemsPerConversion = 100, CoinsPerConversion = 10 },
new IltItemConversion { ItemName = "Ancient Pyreal", ItemsPerConversion = 100, CoinsPerConversion = 37 },
};
/// <summary>Augmentation planner targets, keyed by aug type (lowercase).</summary>
public Dictionary<string, int> AugTargets = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Luminance price of one Enlightened Coin (planner math only; 0 = don't price coins).</summary>
public long LumPerEnlightenedCoin;
/// <summary>Enlightenment planner target level (0 = current + 5).</summary>
public int EnlTargetLevel;
public int EnlightenedCoinsPerToken = 20;
/// <summary>
/// Auto-enlighten preference. Even when true it stays DISARMED each session until the
/// player confirms in the Hub, and the server's own Yes/No dialog is never auto-clicked.
/// </summary>
public bool AutoEnlightenEnabled;
public int AutoEnlightenCheckSeconds = 30;
/// <summary>Spend unassigned XP with /attr before sending /enl (enlightening wipes unspent XP).</summary>
public bool AutoEnlightenSpendXpFirst;
// ── Attribute raiser (IltAttributeRaiser; Skills panel > Progression) ──
/// <summary>Spend unassigned XP on the ticked attributes/vitals every AttrAutoRaiseMinutes.</summary>
public bool AttrAutoRaise;
public int AttrAutoRaiseMinutes = 5;
/// <summary>IltAttributeRaiser.Mode: 0 priority (top of the order first), 1 round robin, 2 cheapest first.</summary>
public int AttrRaiseMode;
/// <summary>Unassigned XP the raiser never spends.</summary>
public long AttrKeepXp;
/// <summary>/attr abbreviations in raise-priority order (all nine; repaired on load).</summary>
public List<string> AttrOrder = new(IltAttributeRaiser.DefaultOrder);
/// <summary>/attr abbreviations the raiser may spend on ("Raise now" and auto-raise).</summary>
public List<string> AttrRaiseStats = new();
/// <summary>Quest bonus (/qb) list filter. (The /myquests tracker's filter and favorites are RynthAi's.)</summary>
public string QbFilter = string.Empty;
// The ILT sections are Mini Remote tabs now (HudState.MiniRemoteTab); the old per-section
// "window open" flags in older files are ignored on load.
/// <summary>
/// Registry charms this character has carried, keyed by charm name. Lets the Charms Tracking
/// tab report "acquired" for charms that are now in storage (the client only sees carried items).
/// </summary>
public Dictionary<string, IltCharmSeen> CharmsSeen = new(StringComparer.OrdinalIgnoreCase);
}
/// <summary>Last time a charm was seen in the character's possession, with its best tier.</summary>
public sealed class IltCharmSeen
{
public int Tier;
public int MaxTier;
public DateTime LastSeenUtc;
}
public sealed class IltItemConversion
{
public string ItemName = string.Empty;
public int ItemsPerConversion = 100;
public int CoinsPerConversion;
}
// ── Gear ────────────────────────────────────────────────────────────────────
public sealed class IltGearState
{
// Dispel (Rune of Dispel on harmful debuffs)
public bool AutoDispel;
public int DispelCooldownSeconds = 10;
/// <summary>Spell-name substrings that are ALWAYS dispelled.</summary>
public List<string> DispelInclusions = new();
/// <summary>Spell-name substrings that are NEVER dispelled.</summary>
public List<string> DispelExclusions = new();
// Surging Strength (Empowered Volcanic Ember keeper)
public bool SurgingStrength;
public int SurgingCooldownSeconds = 15;
// Aetheria / corrupted-weapon chunking
public bool AutoChunkAetheria;
public bool AutoChunkCorrupted;
public bool ChunkInCombat;
public int ChunkIntervalMs = 2000;
/// <summary>
/// Only chunk aetheria whose max level is below this (Coalesced Aetheria too). Infinite Leaftide
/// aetheria goes up to level <see cref="IltInventory.AetheriaMaxLevel"/>, so the cap runs to one past it.
/// </summary>
public int ChunkAetheriaUnderLevel = 4;
/// <summary>Never chunk aetheria carrying a Crit rating (C, GearCrit 372; ILT tier-10 sigils of level 6+).</summary>
public bool KeepAetheriaWithCrit = true;
/// <summary>Never chunk aetheria carrying a Crit Damage rating (CD, GearCritDamage 374).</summary>
public bool KeepAetheriaWithCritDamage = true;
/// <summary>Never chunk aetheria carrying a Crit Damage Resist rating (CDR, GearCritDamageResist 375).</summary>
public bool KeepAetheriaWithCritDamageResist = true;
/// <summary>
/// Rating level for the C / CD / CDR keep switches: a rating at or above this keeps the piece,
/// a lower one does not protect it (it chunks if the other rules allow). 1 = any rating keeps.
/// </summary>
public int KeepAetheriaRatingAtLeast = 1;
// Corrupted-weapon keep rules (ub-IT IdleActs > Corr Chunk). All off by default, as in ub-IT:
// the hard rules (unmodified, workmanship, cleaving, never-chunk) always apply on top.
/// <summary>Never chunk a corrupted weapon with Crushing Blow (CriticalFrequency float 147 &gt; 0).</summary>
public bool KeepCorruptedCrushingBlow;
/// <summary>Never chunk a corrupted weapon with Biting Strike (CriticalMultiplier float 136 &gt; 0).</summary>
public bool KeepCorruptedBitingStrike;
/// <summary>Never chunk a corrupted weapon with Armor Cleaving (IgnoreArmor float 155 &gt; 0).</summary>
public bool KeepCorruptedArmorCleaving;
/// <summary>Never chunk a corrupted weapon with any slayer (SlayerCreatureType int 166 &gt; 0).</summary>
public bool KeepCorruptedAnySlayer;
/// <summary>Never chunk a multi-strike corrupted weapon (AttackType int 47 = 160 / 166 / 486).</summary>
public bool KeepCorruptedMultiStrike;
/// <summary>Never chunk a corrupted weapon with an elemental damage bonus (int 204 &gt; 0).</summary>
public bool KeepCorruptedElementalBonus;
/// <summary>Never chunk a corrupted weapon with any spell on it.</summary>
public bool KeepCorruptedAnySpell;
/// <summary>Never chunk a corrupted weapon whose max damage (int 44) is at least this. 0 = off.</summary>
public int KeepCorruptedMaxDamageAtLeast;
/// <summary>Spell ids (comma / space separated): never chunk a corrupted weapon carrying any of them.</summary>
public string KeepCorruptedSpellIds = "";
// Auto-clap (/clap all)
public bool AutoClap;
public int ClapIntervalMinutes = 30;
// Guardian Hand charm (WCID unpublished — name match until set)
public uint GuardianHandWcid;
public string GuardianHandName = "Guardian Hand";
// Split arrows (White Quartz imbue on missile weapons)
public int SplitArrowTarget = 3;
public bool SplitIgnoreImbued = true;
// Equipment profiles (.utl suits). (The VTank .usd import path is RynthAi's: the importer stayed there.)
public string LastEquipProfile = string.Empty;
// Rings inscription chain (IltRingChainRunner; SilentKelpie's, moved from RynthAi's Crafting tab)
/// <summary>Recipe id (IltRingChain.Recipes) to how many times to craft it. Pump thread only.</summary>
public Dictionary<string, int> RingRuns = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Answer the server's craft dialog Yes for the queued combines (engine API v85).</summary>
public bool RingAnswerCraftDialog = true;
/// <summary>Craft and inscribe in combat mode too (servers with combat-mode crafting).</summary>
public bool RingAllowInCombat;
}
// ── Games ───────────────────────────────────────────────────────────────────
public sealed class IltGamesState
{
public long BlackjackBet = 1_000_000;
public long FellowshipBlackjackBet = 1_000_000;
public int PowerballQuantity = 1;
}
// ── Guardian (Temple of Enlightenment) ──────────────────────────────────────
public sealed class IltGuardianState
{
/// <summary>Translate incoming guardian tells and show the answer (Guardian window + Mini Remote).</summary>
public bool AutoDetectFromChat = true;
/// <summary>After a chat answer, give the item to the guardian automatically.</summary>
public bool AutoHandIn;
/// <summary>Temple guardian only: buy one of the item from the nearest vendor when none is carried.</summary>
public bool BuyMissingFromVendor = true;
/// <summary>Assumed attribute turn-in cooldown when only /qb wait stamps are known (hours).</summary>
public int CooldownHoursAssumed = 20;
/// <summary>Turn-ins counted from /qb wait-stamp transitions, keyed by attribute (fallback when /myquests lacks the flag).</summary>
public Dictionary<string, int> TurnInCounts = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Estimated end of each attribute's cooldown (UTC), keyed by attribute (same fallback).</summary>
public Dictionary<string, DateTime> CooldownUntilUtc = new(StringComparer.OrdinalIgnoreCase);
}

View file

@ -0,0 +1,494 @@
// IltHubStore.cs — Disk persistence for the ILT Hub.
// Originally SilentKelpie's ILT Hub store in RynthAi; moved to RynthILT 2026-10-13.
//
// Files (RynthILT's folder, %APPDATA%\RynthCore\RynthILT; <char> = <world>\<character>):
// <char>\hub.json live Hub state (IltHubState)
// <char>\bank-transactions.json bank transaction log (capped)
// <char>\profiles\<n>.json named per-character Hub profiles
// Profiles\<n>.json named profiles shared by every character
// They were ilt-hub.json, ilt-hub-transactions.json, ilt-hub-profiles\ (RynthAi's per-character
// settings folder) and RynthAi\IltHubProfiles\; IltMigration copies them over on the first login.
// Saves are dirty-checked (the serialized JSON is compared to what was last written) so
// the periodic save in Tick costs nothing when nothing changed. A one-time import pulls
// UtilityBelt's bankdata sidecars so players keep their balances and history.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltHubStore
{
/// <summary>Maximum bank transactions kept on disk (oldest dropped first).</summary>
public const int MaxTransactions = 1000;
/// <summary>RynthILT's folder: shared profiles, aug costs and equipment suits (overridable for the tests).</summary>
public static string SharedRoot = RynthILTPlugin.SettingsRoot;
public const string StateFile = "hub.json";
public const string TransactionsFile = "bank-transactions.json";
public const string ProfilesFolder = "profiles";
private readonly RynthCoreHost _host;
private readonly string _charFolder;
private string _lastStateJson = string.Empty;
private string _lastTxJson = string.Empty;
public IltHubStore(RynthCoreHost host, string charFolder)
{
_host = host;
_charFolder = charFolder ?? string.Empty;
}
/// <summary>
/// True while this character's copy from RynthAi is unfinished (IltMigration): the state, the
/// bank log and per-character profiles are not written, so no fresh file shadows a RynthAi
/// original that hasn't been copied yet. Shared profiles still save.
/// </summary>
public Func<bool> WritesBlocked = static () => false;
/// <summary>
/// The character's RynthAi folder while its copy is unfinished: a file RynthILT doesn't have yet
/// is read from there (read only) when it can be; otherwise the Hub runs from the defaults.
/// </summary>
public string? LegacyFolder;
private bool Blocked()
{
try { return WritesBlocked(); }
catch { return true; }
}
/// <summary>A RynthAi original read without locking it (it may be held open elsewhere). Null when it can't be.</summary>
private string? ReadLegacy(string fileName)
{
if (string.IsNullOrEmpty(LegacyFolder)) return null;
string path = Path.Combine(LegacyFolder, fileName);
try
{
if (!File.Exists(path)) return null;
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
using var sr = new StreamReader(fs);
return sr.ReadToEnd();
}
catch (Exception ex)
{
RynthLog.Write(LogCat.IltStore, $"RynthAi's {path} can't be read yet ({ex.Message}); running from the defaults until it is copied.");
return null;
}
}
public string CharFolder => _charFolder;
private string StatePath => Path.Combine(_charFolder, StateFile);
private string TxPath => Path.Combine(_charFolder, TransactionsFile);
private string CharProfileDir => Path.Combine(_charFolder, ProfilesFolder);
internal static string SharedProfileDir => Path.Combine(SharedRoot, "Profiles");
// ── State ───────────────────────────────────────────────────────────────
/// <summary>Loads the live state, returning defaults when the file is missing or unreadable.</summary>
public IltHubState LoadState()
{
try
{
if (_charFolder.Length > 0 && File.Exists(StatePath))
{
string json = File.ReadAllText(StatePath);
var s = JsonSerializer.Deserialize(json, IltHubJsonContext.Default.IltHubState);
if (s != null)
{
Normalize(s);
_lastStateJson = json;
return s;
}
}
else if (ReadLegacy("ilt-hub.json") is string legacyJson)
{
var s = JsonSerializer.Deserialize(legacyJson, IltHubJsonContext.Default.IltHubState);
if (s != null) { Normalize(s); return s; }
}
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {StatePath}"); }
return new IltHubState();
}
/// <summary>Writes the state only when its JSON differs from the last write.</summary>
public void SaveStateIfDirty(IltHubState state)
{
if (_charFolder.Length == 0) return;
try
{
string json = JsonSerializer.Serialize(state, IltHubJsonContext.Default.IltHubState);
if (json == _lastStateJson) return;
if (Blocked()) return; // the copy from RynthAi isn't finished: never shadow its hub.json
// A failure is said in chat once per folder (on ILT) and logged; the next periodic save retries.
if (DataWriteGuard.TrySave("the ILT Hub state", StatePath, () =>
{
Directory.CreateDirectory(_charFolder);
WriteAtomic(StatePath, json);
}))
_lastStateJson = json;
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {StatePath}"); }
}
/// <summary>Repairs null collections / out-of-range values after deserialization.</summary>
private static void Normalize(IltHubState s)
{
s.ServerOptions ??= new IltServerOptionsSnapshot();
s.ServerOptions.Bits = new Dictionary<string, int>(s.ServerOptions.Bits ?? new(), StringComparer.OrdinalIgnoreCase);
s.Bank ??= new IltBankState();
s.Pet ??= new IltPetState();
s.Pet.PetLog ??= new();
s.Pet.ShinyLog ??= new();
s.Pet.Breeding ??= new();
s.Pet.Breeding.Rules ??= new();
s.Pet.Breeding.StageNames ??= new();
s.Pet.Breeding.Log ??= new();
s.Pet.Breeding.LastDebug ??= new();
s.Pet.CaptureLens = Math.Clamp(s.Pet.CaptureLens, 0, PetCaptureRules.Lenses.Length - 1);
s.Pet.Breeding.Rules.RemoveAll(r => r == null || string.IsNullOrEmpty(r.Key));
s.Pet.Breeding.Log.RemoveAll(e => e == null);
for (int i = 0; i < s.Pet.Breeding.StageNames.Count; i++) s.Pet.Breeding.StageNames[i] ??= string.Empty;
if (s.Pet.Breeding.Log.Count > IltBreedingRules.MaxEvents)
s.Pet.Breeding.Log.RemoveRange(0, s.Pet.Breeding.Log.Count - IltBreedingRules.MaxEvents);
s.Character ??= new IltCharacterState();
s.Character.ItemConversions ??= new();
s.Character.AugTargets = new Dictionary<string, int>(s.Character.AugTargets ?? new(), StringComparer.OrdinalIgnoreCase);
s.Character.AttrOrder = IltAttributeRaiser.RepairOrder(s.Character.AttrOrder);
s.Character.AttrRaiseStats = IltAttributeRaiser.RepairSelection(s.Character.AttrRaiseStats);
s.Character.AttrAutoRaiseMinutes = Math.Clamp(s.Character.AttrAutoRaiseMinutes, 1, 1440);
s.Character.AttrRaiseMode = Math.Clamp(s.Character.AttrRaiseMode, 0, 2);
s.Character.AttrKeepXp = Math.Max(0, s.Character.AttrKeepXp);
s.Character.CharmsSeen = new Dictionary<string, IltCharmSeen>(s.Character.CharmsSeen ?? new(), StringComparer.OrdinalIgnoreCase);
s.Gear ??= new IltGearState();
s.Gear.DispelInclusions ??= new();
s.Gear.DispelExclusions ??= new();
s.Gear.RingRuns = new Dictionary<string, int>(s.Gear.RingRuns ?? new(), StringComparer.OrdinalIgnoreCase);
s.Games ??= new IltGamesState();
s.Combat ??= new IltCombatState();
s.T11 ??= new IltT11State();
s.Remote ??= new IltRemoteState();
if (s.T11.ItemAugsOverride < -1) s.T11.ItemAugsOverride = -1;
s.Guardian ??= new IltGuardianState();
s.Guardian.TurnInCounts = new Dictionary<string, int>(s.Guardian.TurnInCounts ?? new(), StringComparer.OrdinalIgnoreCase);
s.Guardian.CooldownUntilUtc = new Dictionary<string, DateTime>(s.Guardian.CooldownUntilUtc ?? new(), StringComparer.OrdinalIgnoreCase);
s.Guardian.CooldownHoursAssumed = Math.Clamp(s.Guardian.CooldownHoursAssumed, 1, 72);
s.SelectedTab = Math.Clamp(s.SelectedTab, 0, 4);
s.Gear.SplitArrowTarget = Math.Clamp(s.Gear.SplitArrowTarget, 0, 10);
}
// ── Transactions ────────────────────────────────────────────────────────
public List<IltBankTransaction> LoadTransactions()
{
try
{
if (_charFolder.Length > 0 && File.Exists(TxPath))
{
string json = File.ReadAllText(TxPath);
var list = JsonSerializer.Deserialize(json, IltHubJsonContext.Default.IltBankTransactionList);
if (list != null) { _lastTxJson = json; return list; }
}
else if (ReadLegacy("ilt-hub-transactions.json") is string legacyJson)
{
var list = JsonSerializer.Deserialize(legacyJson, IltHubJsonContext.Default.IltBankTransactionList);
if (list != null) return list;
}
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {TxPath}"); }
return new List<IltBankTransaction>();
}
public void SaveTransactionsIfDirty(List<IltBankTransaction> list)
{
if (_charFolder.Length == 0) return;
try
{
if (list.Count > MaxTransactions)
list.RemoveRange(0, list.Count - MaxTransactions);
string json = JsonSerializer.Serialize(list, IltHubJsonContext.Default.IltBankTransactionList);
if (json == _lastTxJson) return;
if (Blocked()) return; // as SaveStateIfDirty
if (DataWriteGuard.TrySave("the bank transaction log", TxPath, () =>
{
Directory.CreateDirectory(_charFolder);
WriteAtomic(TxPath, json);
}))
_lastTxJson = json;
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {TxPath}"); }
}
// ── Profiles ────────────────────────────────────────────────────────────
/// <summary>Lists profile names. Shared ones are prefixed "shared:".</summary>
public List<string> ListProfiles()
{
var names = new List<string>();
try
{
if (Directory.Exists(CharProfileDir))
names.AddRange(Directory.GetFiles(CharProfileDir, "*.json").Select(Path.GetFileNameWithoutExtension).OfType<string>());
if (Directory.Exists(SharedProfileDir))
names.AddRange(Directory.GetFiles(SharedProfileDir, "*.json").Select(p => "shared:" + Path.GetFileNameWithoutExtension(p)));
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"list profiles"); }
names.Sort(StringComparer.OrdinalIgnoreCase);
return names;
}
/// <summary>Saves the preference parts of <paramref name="state"/> as a named profile.</summary>
public bool SaveProfile(IltHubState state, string name, bool shared, out string error)
{
error = string.Empty;
string safe = SanitizeName(name);
if (safe.Length == 0) { error = "Profile name is empty."; return false; }
if (!shared && Blocked())
{
error = "this character's Hub data is still being copied from RynthAi (see the log); save it as a shared profile, or try again later.";
return false;
}
try
{
string dir = shared ? SharedProfileDir : CharProfileDir;
var copy = Clone(state);
StripRuntime(copy);
string json = JsonSerializer.Serialize(copy, IltHubJsonContext.Default.IltHubState);
string path = Path.Combine(dir, safe + ".json");
// The player asked for this save: the caller shows the reason (and the fix) itself.
return DataWriteGuard.TrySave("the Hub profile", path, () =>
{
Directory.CreateDirectory(dir);
WriteAtomic(path, json);
}, out error, callerShows: true);
}
catch (Exception ex) { error = ex.Message; return false; }
}
/// <summary>
/// Loads a profile onto <paramref name="target"/>, keeping runtime data (balances,
/// server bits, rosters, import flag) from the current state.
/// </summary>
public bool LoadProfile(IltHubState target, string name, out string error)
{
error = string.Empty;
bool shared = name.StartsWith("shared:", StringComparison.OrdinalIgnoreCase);
string safe = SanitizeName(shared ? name.Substring(7) : name);
string path = Path.Combine(shared ? SharedProfileDir : CharProfileDir, safe + ".json");
try
{
if (!File.Exists(path)) { error = $"Profile not found: {name}"; return false; }
var p = JsonSerializer.Deserialize(File.ReadAllText(path), IltHubJsonContext.Default.IltHubState);
if (p == null) { error = "Profile file is empty."; return false; }
Normalize(p);
target.Pet = KeepRosters(p.Pet, target.Pet);
target.Character = p.Character;
target.Gear = p.Gear;
target.Games = p.Games;
target.Bank.AutoRefreshSeconds = p.Bank.AutoRefreshSeconds;
target.ForceLeaftideFeatures = p.ForceLeaftideFeatures;
target.GamesHudVisible = p.GamesHudVisible;
return true;
}
catch (Exception ex) { error = ex.Message; return false; }
}
private static IltPetState KeepRosters(IltPetState incoming, IltPetState current)
{
incoming.PetLog = current.PetLog;
incoming.ShinyLog = current.ShinyLog;
// The breeding tracker holds this object; it is the character's own (not a profile setting).
incoming.Breeding = current.Breeding;
return incoming;
}
private static IltHubState Clone(IltHubState s)
=> JsonSerializer.Deserialize(JsonSerializer.Serialize(s, IltHubJsonContext.Default.IltHubState),
IltHubJsonContext.Default.IltHubState) ?? new IltHubState();
/// <summary>Removes character-specific runtime data before a profile is written.</summary>
private static void StripRuntime(IltHubState s)
{
s.ServerOptions = new IltServerOptionsSnapshot();
var keepRefresh = s.Bank.AutoRefreshSeconds;
s.Bank = new IltBankState { AutoRefreshSeconds = keepRefresh };
s.Pet.PetLog = new();
s.Pet.ShinyLog = new();
s.Pet.Breeding = new();
s.UbSidecarsImported = false;
s.WindowVisible = false;
}
private static string SanitizeName(string name)
{
var invalid = Path.GetInvalidFileNameChars();
return new string((name ?? string.Empty).Trim().Where(c => !invalid.Contains(c)).ToArray());
}
// ── UtilityBelt sidecar import ──────────────────────────────────────────
/// <summary>
/// One-time import of UB's bankdata (balances, transactions) and item conversions.
/// Searches Documents\Decal Plugins\UtilityBelt\&lt;world&gt;\&lt;char&gt;; when the world is
/// unknown every world folder containing the character is tried. Returns a summary.
/// </summary>
public string ImportUbSidecars(IltHubState state, List<IltBankTransaction> txLog, string world, string charName)
{
if (string.IsNullOrWhiteSpace(charName)) return "character name unknown";
string ubRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Decal Plugins", "UtilityBelt");
if (!Directory.Exists(ubRoot)) return "no UtilityBelt folder";
var charDirs = new List<string>();
if (!string.IsNullOrWhiteSpace(world))
charDirs.Add(Path.Combine(ubRoot, world, charName));
try
{
foreach (string w in Directory.GetDirectories(ubRoot))
{
string d = Path.Combine(w, charName);
if (!charDirs.Contains(d, StringComparer.OrdinalIgnoreCase)) charDirs.Add(d);
}
}
catch { /* unreadable Documents subfolder: fall through with what we have */ }
foreach (string dir in charDirs)
{
string bankDir = Path.Combine(dir, "bankdata");
if (!Directory.Exists(bankDir) && !Directory.Exists(dir)) continue;
int parts = 0;
parts += ImportBalances(Path.Combine(bankDir, "bankbalances.json"), state.Bank) ? 1 : 0;
int tx = ImportTransactions(Path.Combine(bankDir, "transactions.json"), txLog);
int conv = ImportConversions(new[]
{
Path.Combine(bankDir, "itemconversions.json"),
Path.Combine(dir, "itemconversions.json"),
}, state.Character.ItemConversions);
if (parts + tx + conv > 0)
return $"imported from {dir}: balances {(parts > 0 ? "yes" : "no")}, {tx} transactions, {conv} conversions";
}
return "no UtilityBelt bank data found for " + charName;
}
private bool ImportBalances(string path, IltBankState bank)
{
if (!File.Exists(path)) return false;
try
{
using var doc = JsonDocument.Parse(File.ReadAllText(path));
var root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) return false;
bank.Pyreals = ReadLong(root, "Pyreals");
bank.Luminance = ReadLong(root, "Luminance");
bank.LegendaryKeys = ReadLong(root, "LegendaryKeys");
bank.MythicalKeys = ReadLong(root, "MythicalKeys");
bank.EnlightenedCoins = ReadLong(root, "EnlightenedCoins");
bank.WeaklyEnlightenedCoins = ReadLong(root, "WeaklyEnlightenedCoins");
if (TryGetProp(root, "LastUpdated", out var lu) && lu.ValueKind == JsonValueKind.String && lu.TryGetDateTime(out var dt))
bank.LastUpdated = dt;
return true;
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"UB balances import"); return false; }
}
private int ImportTransactions(string path, List<IltBankTransaction> txLog)
{
if (!File.Exists(path)) return 0;
try
{
using var doc = JsonDocument.Parse(File.ReadAllText(path));
if (doc.RootElement.ValueKind != JsonValueKind.Array) return 0;
int added = 0;
foreach (var e in doc.RootElement.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object) continue;
var t = new IltBankTransaction
{
Type = ReadString(e, "Type"),
Currency = ReadString(e, "Currency"),
Amount = ReadLong(e, "Amount"),
OtherPlayer = ReadString(e, "OtherPlayer"),
Description = ReadString(e, "Description"),
};
if (TryGetProp(e, "Timestamp", out var ts) && ts.ValueKind == JsonValueKind.String && ts.TryGetDateTime(out var dt))
t.Timestamp = dt;
// Skip exact duplicates so re-running the import can't double the log.
if (txLog.Any(x => x.Timestamp == t.Timestamp && x.Amount == t.Amount && x.OtherPlayer == t.OtherPlayer)) continue;
txLog.Add(t);
added++;
}
txLog.Sort((a, b) => a.Timestamp.CompareTo(b.Timestamp));
return added;
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"UB transactions import"); return 0; }
}
private int ImportConversions(string[] paths, List<IltItemConversion> table)
{
foreach (string path in paths)
{
if (!File.Exists(path)) continue;
try
{
using var doc = JsonDocument.Parse(File.ReadAllText(path));
if (doc.RootElement.ValueKind != JsonValueKind.Array) continue;
int added = 0;
foreach (var e in doc.RootElement.EnumerateArray())
{
string name = ReadString(e, "ItemName");
if (name.Length == 0) continue;
var existing = table.FirstOrDefault(c => c.ItemName.Equals(name, StringComparison.OrdinalIgnoreCase));
if (existing == null) { existing = new IltItemConversion { ItemName = name }; table.Add(existing); added++; }
existing.ItemsPerConversion = Math.Max(1, (int)ReadLong(e, "ItemsPerConversion"));
existing.CoinsPerConversion = (int)ReadLong(e, "CoinsPerConversion");
}
return added;
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"UB conversions import"); }
}
return 0;
}
// ── JSON helpers (case-insensitive property access) ─────────────────────
private static bool TryGetProp(JsonElement obj, string name, out JsonElement value)
{
foreach (var p in obj.EnumerateObject())
if (p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) { value = p.Value; return true; }
value = default;
return false;
}
private static long ReadLong(JsonElement obj, string name)
{
if (!TryGetProp(obj, name, out var v)) return 0;
if (v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long l)) return l;
if (v.ValueKind == JsonValueKind.String) return IltParse.ParseLeadingLong(v.GetString() ?? string.Empty);
return 0;
}
private static string ReadString(JsonElement obj, string name)
{
if (!TryGetProp(obj, name, out var v)) return string.Empty;
return v.ValueKind switch
{
JsonValueKind.String => v.GetString() ?? string.Empty,
JsonValueKind.Number => v.GetRawText(),
_ => string.Empty,
};
}
/// <summary>Write-then-rename so a crash mid-write never leaves a truncated file.</summary>
private static void WriteAtomic(string path, string contents)
{
string tmp = path + ".tmp";
File.WriteAllText(tmp, contents);
File.Move(tmp, path, overwrite: true);
}
}

View file

@ -0,0 +1,401 @@
// IltHubUi.cs — The ILT sections' ImGui bodies (render thread only).
// Originally SilentKelpie's ILT Hub UI (RynthAi IltHub/); moved to RynthILT 2026-10-13, with the
// ILT parts of RynthAi's Mini Remote (the Remote tab's Bank section and Guardian line, the menu's
// Infinite Leaftide items) that read the Hub's state.
//
// The ILT sections are tabs of RynthAi's Mini Remote (its MiniRemoteHud draws the tab bar and
// calls RenderTab through RynthILT.Hub): Banking, Gear, Charms and Games. A tab is offered only
// while the server reports its feature on. The Character tab left the Mini Remote on 2026-10-13:
// - the session rates are RynthCore's Mini Remote "Session Stats" section (RenderRatesSection,
// surface "section:ilt-rates"), below RynthAi's one session;
// - the character overview and session are RynthOracle's Character tab ("/ro character");
// - the "Treat this world as ILT" override and the ILT world names are RynthCore's
// Options > Diagnostics server selection only ("/ra hub force" and "/ra hub servers" remain).
// The /qb list (RynthAi's Quests tab before it moved to RynthOracle) is RynthILT's own "Quests"
// section on the rail (RenderQuestBonusSection, surface "section:ilt-questbonus").
// RenderSection draws the ILT pieces inside RynthAi's own surfaces (the Remote tab, the Pets tab,
// the Mini Remote menu). The Guardian is a RynthCore ILT panel (the bar's ILT button, next to
// Bounties), drawn through RenderGuardianPanel. Render() keeps the floating extras: the Games HUD and the confirmation
// modal. Augmentations / Enlightenment / XP planning live on the engine Skills panel. All AC
// actions go through IltHubContext.Post / Confirm so nothing here touches the game directly.
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltHubUi
{
private const string ConfirmPopupId = "Confirm##iltconfirm";
private static readonly Vector4 ColLabel = new(0.80f, 0.84f, 0.90f, 1f);
/// <summary>Where a server is forced now (the only place: RynthCore's Options window).</summary>
private const string ForceHint = "To force a server, use RynthCore Options > Diagnostics > server selection (/rc diagnostics).";
/// <summary>RynthCore's command that opens Options > Diagnostics (RynthCore 2026.10.5.54+).</summary>
private const string DiagnosticsCommand = "/rc diagnostics";
private readonly IltHubController _hub;
private readonly IltHubContext _ctx;
private IltConfirmRequest? _confirm;
private bool _confirmOpened;
// The last tab body drawn (for one shown log event per tab change); -1 = none yet.
private int _lastTabLogged = -1;
public IltHubUi(IltHubController hub, IltHubContext ctx)
{
_hub = hub;
_ctx = ctx;
}
/// <summary>The floating extras: Games HUD and the confirmation modal.</summary>
public void Render()
{
_hub.Games.RenderHud();
RenderConfirm();
}
/// <summary>Draws one Mini Remote ILT tab's body into the current (child) window.</summary>
public void RenderTab(IltSection section)
{
if ((int)section != _lastTabLogged)
{
_lastTabLogged = (int)section;
RynthLog.Event(LogEvents.IltWindowShown, $"{IltSections.Label(section)} tab shown (world='{_ctx.Options.WorldName}', available={_hub.Available})");
}
switch (section)
{
case IltSection.Banking: _hub.Banking.Render(); break;
case IltSection.Gear: _hub.Gear.Render(); break;
case IltSection.Charms: _hub.CharmsTab.Render(); break;
case IltSection.Games: _hub.Games.Render(); break;
case IltSection.VaultedDungeons: _hub.VaultedDungeons.Render(); break;
default:
// A saved tab id from before the move: say where the section lives now.
if (IltSections.MovedCommand(section) is string moved)
MovedLink(section, moved);
break;
}
}
/// <summary>
/// The ILT session extras in RynthCore's Mini Remote "Session Stats" section (surface
/// "section:ilt-rates", the Infinite Leaftide group): coins, pyreals and item conversions.
/// XP, luminance and kills are RynthAi's session stats, drawn above it in the same section.
/// </summary>
public void RenderRatesSection()
{
if (!_hub.Available)
{
RenderHeader();
RenderUnavailable();
return;
}
_hub.Rates.Render(extrasOnly: true);
ImGui.TextDisabled("XP planner, Augmentations and Enlightenment: Skills panel > Progression.");
}
/// <summary>
/// The quest bonus list (/qb) in RynthILT's own Mini Remote "Quests" section (surface
/// "section:ilt-questbonus"); it was a section of RynthAi's Quests tab, which moved to RynthOracle.
/// </summary>
public void RenderQuestBonusSection()
{
if (!_ctx.Options.IsIltLikeWorld)
{
RenderHeader();
RenderUnavailable();
return;
}
_hub.QuestBonus.RenderQb();
}
/// <summary>
/// One of the ILT pieces RynthAi draws in its own surfaces (RynthServerHub.Section*, RynthIltHub.Section*). False when
/// there is nothing to draw (unknown id, or not an ILT world).
/// </summary>
public bool RenderSection(string id)
{
var o = _ctx.Options;
switch (id)
{
case RynthServerHub.SectionRemoteBank:
if (!o.IsIltLikeWorld || o.IsOff(IltFeature.Bank) || !_ctx.State.Remote.ShowBank) return false;
RenderRemoteBank();
return true;
case RynthServerHub.SectionRemoteGuardian:
if (!o.IsIltLikeWorld || !_ctx.State.Remote.ShowGuardian) return false;
_hub.Guardian.RenderRemoteLine();
return true;
case RynthServerHub.SectionRemoteStats:
if (!o.IsIltLikeWorld) return false;
RenderRemoteStats();
return true;
case RynthServerHub.SectionRemoteOptions:
if (!o.IsIltLikeWorld) return false;
RenderRemoteOptions();
return true;
case RynthIltHub.SectionQuestBonus:
if (!o.IsIltLikeWorld) return false;
_hub.QuestBonus.RenderSection();
return true;
case RynthServerHub.SectionPetLogs:
if (!o.IsIltLikeWorld) return false;
_hub.PetLogs.RenderSection();
return true;
case RynthIltHub.SectionPetBreeding:
if (!o.IsIltLikeWorld) return false;
_hub.Breeding.RenderSection();
return true;
case RynthServerHub.SectionPetCharms:
if (!o.IsIltLikeWorld) return false;
_hub.PetAutomation.RenderCharms();
return true;
case RynthServerHub.SectionPetCapture:
if (!o.IsIltLikeWorld) return false;
_hub.PetAutomation.RenderCapture();
return true;
case RynthServerHub.SectionServerStatus:
return RenderIltStatus();
case RynthServerHub.SectionServerMenu:
return RenderLocalMenu();
default:
return false;
}
}
/// <summary>
/// The Guardian panel's body (RynthCore's ILT Guardian panel, RynthPluginRenderEmbed
/// "guardian"), or why it's idle while the server hasn't reported ILT features.
/// </summary>
public void RenderGuardianPanel()
{
if (!_hub.SectionAvailable(IltSection.Guardian))
{
RenderHeader();
ImGui.Separator();
RenderUnavailable();
return;
}
_hub.Guardian.Render();
}
/// <summary>A button that opens a moved section's new home (posted: the command runs on the pump).</summary>
private void MovedLink(IltSection section, string command)
{
const string home = "RynthOracle > Character";
SafeImGui.TextDisabled($"{IltSections.Label(section)} moved to {home}; the ILT session rates are in Session Stats.");
if (ImGui.SmallButton($"Open {home}##moved{(int)section}"))
_ctx.Post(() => _hub.OpenMoved(section, command));
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(command);
}
/// <summary>The world and when the server's ILT features were last read, with a Refresh.</summary>
private void RenderHeader()
{
var o = _ctx.Options;
string world = o.WorldName.Length > 0 ? o.WorldName : "unknown world";
SafeImGui.TextColored(o.IsIltLikeWorld ? IltStyle.ColTeal : IltStyle.ColTextMute, world);
ImGui.SameLine();
SafeImGui.TextDisabled(o.IsRefreshing ? "checking server options..."
: o.LastRefreshUtc == DateTime.MinValue ? "server options not checked yet"
: $"options via {o.Source} @ {o.LastRefreshUtc.ToLocalTime():t}");
ImGui.SameLine();
if (ImGui.SmallButton("Refresh##opts")) _ctx.Post(() => o.Refresh(manual: true));
}
private void RenderUnavailable()
{
var o = _ctx.Options;
if (!o.IsIltLikeWorld)
{
SafeImGui.TextWrapped("This is not an Infinite Leaftide / ACECustom world, so the ILT tools are idle. " + ForceHint);
}
else if (o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue)
{
ImGui.TextWrapped("Checking which ILT features this server has enabled...");
}
else
{
ImGui.TextWrapped("The server did not report any ILT features as enabled. Press Refresh to check again.");
}
}
// ── RynthAi's Mini Remote: the Remote tab's Stats lines and Options switches ──
/// <summary>Coins and pyreals per hour under RynthAi's per-hour lines (the Remote tab's Stats).</summary>
private void RenderRemoteStats()
{
var r = _hub.Rates.Summary;
Stat("Coins:", Compact(r.CoinsPerHour) + "/h");
Stat("Pyr:", Compact(r.PyrealsPerHour) + "/h");
}
/// <summary>The Remote tab's ILT sections' switches, in RynthAi's Options popup.</summary>
private void RenderRemoteOptions()
{
var st = _ctx.State.Remote;
bool bank = st.ShowBank, guardian = st.ShowGuardian;
if (ImGui.Checkbox("Bank##iltmrbank", ref bank)) st.ShowBank = bank;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Infinite Leaftide bank balances (RynthILT).");
if (ImGui.Checkbox("Guardian answer##iltmrguardian", ref guardian)) st.ShowGuardian = guardian;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("The last Temple guardian answer with a Give button (RynthILT).");
}
/// <summary>The tail of RynthAi's one-line session report: the coin / pyreal rates (RynthServerHub.TextSessionReport).</summary>
public string SessionReportTail()
{
var r = _hub.Rates.Summary;
return $", Coins {Compact(r.CoinsPerHour)}/h, Pyr {Compact(r.PyrealsPerHour)}/h";
}
// ── RynthAi's Mini Remote: the Remote tab's Bank section ────────────────
private void RenderRemoteBank()
{
var b = _ctx.State.Bank;
if (b.LastUpdated == DateTime.MinValue)
{
// Nothing read yet this install: offer a quiet /bank (the Banking tab has the full view).
ImGui.TextDisabled("Bank: not loaded yet");
ImGui.SameLine();
if (ImGui.SmallButton("Load##mrbank")) _ctx.Post(() => _hub.Banking.RequestRefresh(quiet: true));
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Reads your bank balances (/bank, reply hidden). The Banking tab has the details.");
BankLink();
return;
}
Stat("P:", Compact(b.Pyreals));
Stat("Lum:", Compact(b.Luminance));
BankLink();
if (!ImGui.BeginTable("##mrbank", 2, ImGuiTableFlags.SizingStretchSame)) return;
ImGui.TableNextColumn(); Stat("LK:", Compact(b.LegendaryKeys));
ImGui.TableNextColumn(); Stat("MK:", Compact(b.MythicalKeys));
ImGui.TableNextColumn(); Stat("EC:", Compact(b.EnlightenedCoins));
ImGui.TableNextColumn(); Stat("WE:", Compact(b.WeaklyEnlightenedCoins));
// Prestige Coins (ACECustom 2026-10-04): only once the server has reported some.
if (b.PrestigeCoins > 0) { ImGui.TableNextColumn(); Stat("PC:", Compact(b.PrestigeCoins)); }
ImGui.EndTable();
}
/// <summary>The Bank line's link to RynthILT's own Banking tab (Infinite Leaftide's bank stays RynthILT's).</summary>
private void BankLink()
{
if (!_hub.SectionAvailable(IltSection.Banking)) return;
ImGui.SameLine();
if (ImGui.SmallButton("Bank##mrbanklink"))
_ctx.Ai.MiniRemoteTab(IltSections.TabId(IltSection.Banking), "show");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("The Banking tab: deposits, withdrawals and transfers (/ra hub open banking).");
}
private static void Stat(string label, string value)
{
SafeImGui.TextColored(ColLabel, label);
ImGui.SameLine();
ImGui.TextUnformatted(value);
}
/// <summary>The Mini Remote's compact numbers (RynthAi's HudDraw.Compact): 12.3k, 4.5m, 1.2b.</summary>
private static string Compact(double v)
{
double a = Math.Abs(v);
if (a >= 1e9) return (v / 1e9).ToString("0.0") + "b";
if (a >= 1e6) return (v / 1e6).ToString("0.0") + "m";
if (a >= 1e4) return (v / 1e3).ToString("0.0") + "k";
return v.ToString("0");
}
// ── RynthAi's Mini Remote menu: the Infinite Leaftide section ──────────
/// <summary>
/// Under the Infinite Leaftide section while no ILT feature is on: why, where a server is
/// forced (RynthCore Options > Diagnostics only) and a server-features refresh. False when
/// features are on.
/// </summary>
private bool RenderIltStatus()
{
if (_hub.Available) return false;
var o = _ctx.Options;
SafeImGui.TextDisabled(!o.IsIltLikeWorld ? "Not an ILT world."
: o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue ? "Checking server features..."
: "No ILT features reported.");
if (!o.IsIltLikeWorld && ImGui.MenuItem("Force a server... (Options > Diagnostics)##mrforce", DiagnosticsCommand))
_ctx.Post(() => { if (_ctx.Host.HasInvokeChatParser) _ctx.Host.InvokeChatParser(DiagnosticsCommand); });
if (!o.IsIltLikeWorld && ImGui.IsItemHovered()) SafeImGui.SetTooltip(ForceHint);
if (ImGui.MenuItem("Refresh server features##mrrefresh")) _hub.RequestOptionsRefresh();
return true;
}
/// <summary>
/// RynthILT's own Infinite Leaftide entries, for when RynthCore sends no server list (older
/// RynthCore, or its ImGui layer off): the tabs, where Character went, and the Guardian /
/// Bounties panels.
/// </summary>
private bool RenderLocalMenu()
{
if (!_hub.OffersTabs) return false;
ImGui.Separator();
ImGui.TextDisabled("Server: Infinite Leaftide");
foreach (IltSection section in IltSections.Tabs)
{
if (ImGui.MenuItem(IltSections.Label(section) + "##mrlocal", string.Empty, false, _hub.SectionAvailable(section)))
_ctx.Ai.MiniRemoteTab(IltSections.TabId(section), "show");
}
if (ImGui.MenuItem("Character##mrlocal", IltSections.OracleCharacterCommand))
_ctx.Post(() => _hub.OpenMoved(IltSection.Character, IltSections.OracleCharacterCommand));
if (ImGui.MenuItem("Guardian##mrlocal", "/rc guardian", false, _hub.SectionAvailable(IltSection.Guardian)))
_ctx.Post(() => _hub.OpenEnginePanel("guardian", "Guardian", "show"));
if (ImGui.MenuItem("Bounties##mrlocal", "/rc bounties"))
_ctx.Post(() => _hub.OpenEnginePanel("bounties", "Bounties", "show"));
RenderIltStatus();
return true;
}
// ── Confirmation modal ──────────────────────────────────────────────────
private void RenderConfirm()
{
if (_confirm == null)
{
if (!_ctx.TryTakeConfirm(out var next)) return;
_confirm = next;
_confirmOpened = false;
}
if (!_confirmOpened)
{
ImGui.OpenPopup(ConfirmPopupId);
_confirmOpened = true;
}
ImGui.SetNextWindowSize(new Vector2(420, 0), ImGuiCond.Appearing);
bool keepOpen = true;
if (ImGui.BeginPopupModal(ConfirmPopupId, ref keepOpen, ImGuiWindowFlags.AlwaysAutoResize))
{
SafeImGui.TextColored(IltStyle.ColAmber, _confirm.Title);
ImGui.Separator();
SafeImGui.TextWrapped(_confirm.Message);
ImGui.Spacing();
if (ImGui.Button(_confirm.YesLabel + "##iltyes", new Vector2(120, 0)))
{
var act = _confirm.OnYes;
if (act != null) _ctx.Post(act);
_confirm = null;
ImGui.CloseCurrentPopup();
}
ImGui.SameLine();
if (ImGui.Button("Cancel##iltno", new Vector2(120, 0)))
{
_confirm = null;
ImGui.CloseCurrentPopup();
}
ImGui.EndPopup();
}
else
{
// Closed with the title-bar X (or never opened): treat as cancel.
_confirm = null;
}
if (!keepOpen) _confirm = null;
}
}

View file

@ -0,0 +1,391 @@
// IltInventory.cs — Shared item / player-property helper for every ILT Hub feature.
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. Items come
// from RynthILT's host-backed IltObjects instead of RynthAi's WorldObjectCache.
//
// One place for: WCID lookups (cached — the engine call is cheap but not free), stack
// counting, "is it equipped", appraisal requests (throttled), charm ON/OFF status from the
// appraisal Use text, and player int/bool/quad reads. Features never talk to the cache or
// the host for item facts directly, so behaviour (and its edge cases) stays consistent.
// Pump-thread only.
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Loot;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>
/// Registered ACECustom charm (CharmAbilityRegistry): display name, every known WCID (base +
/// tier variants), the player PropertyBool the server sets while the ability is active (0 when
/// it is kept in memory only, like Auto-Rebuff) and a one-line effect summary.
/// </summary>
internal sealed record IltCharmDef(string Name, uint[] Wcids, uint PlayerFlag = 0, string Effect = "");
internal sealed class IltInventory
{
// ── Well-known WCIDs (ACECustom content) ────────────────────────────────
public const uint WcidPyreal = 273;
public const uint WcidEnlightenedCoin = 300004;
public const uint WcidEnlToken = 300000;
public const uint WcidEnlMedallion = 90000217;
public const uint WcidEnlSigil = 300101189;
public const uint WcidEnlCrest = 98769999;
public const uint WcidEncapsulatedSpirit = 49485;
public const uint WcidRuneOfDispel = 30133;
public const uint WcidSummonRefillCharm = 78780030;
public const uint WcidUniversalMasteryCharm = 78780031;
public static readonly uint[] WcidInfiniteCastingStone = { 777700019, 777700055 };
// Aetheria (ACECustom Aetheria.cs / PlayerCommands /clap). The Coalesced WCIDs stay the same once
// revealed (name "Aetheria", equipment set given), and /clap takes only unrevealed level 1-3 ones.
public const uint WcidBlueCoalescedAetheria = 42635;
public const uint WcidRedCoalescedAetheria = 42636;
public const uint WcidYellowCoalescedAetheria = 42637;
public const uint WcidRedAetheriaChunk = 310147;
public const uint WcidBlueAetheriaChunk = 310149;
public const uint WcidYellowAetheriaChunk = 310150;
public const uint WcidRedAetheriaPowder = 42644;
public const uint WcidBlueAetheriaPowder = 300019;
public const uint WcidEmpyreanTrinket = 34276;
public const uint WcidFalatacotTrinket = 34277;
// ── Property ids used by several features ───────────────────────────────
public const uint IntStackSize = 12;
public const uint IntValidLocations = 9;
public const uint IntLevel = 25;
public const uint IntMaxStructure = 91;
public const uint IntStructure = 92;
public const uint IntNumTimesTinkered = 171;
public const uint IntImbuedEffect = 179;
public const uint IntCleaving = 292;
// Corrupted-weapon chunk rules (ub-IT Leaftide.IsValidCorruptedWep / CorruptedChunkGuard).
/// <summary>ACE PropertyInt.Damage — a weapon's max damage.</summary>
public const uint IntDamage = 44;
/// <summary>ACE PropertyInt.AttackType — 2 = thrust; 160 / 166 / 486 are the multi-strike masks.</summary>
public const uint IntAttackType = 47;
/// <summary>ACE PropertyInt.ItemWorkmanship — loot-gen Craft (salvage-bag workmanship is not on weapons).</summary>
public const uint IntItemWorkmanship = 105;
/// <summary>ACE PropertyInt.WieldSkillType — 41 (Two Handed Combat) for two-handed weapons.</summary>
public const uint IntWieldSkillType = 159;
/// <summary>ACE PropertyInt.SlayerCreatureType.</summary>
public const uint IntSlayerCreatureType = 166;
/// <summary>ACE PropertyInt.ElementalDamageBonus.</summary>
public const uint IntElementalDamageBonus = 204;
/// <summary>ACE PropertyInt.WeaponType — 11 = TwoHanded.</summary>
public const uint IntWeaponType = 353;
/// <summary>ACE PropertyFloat.CriticalMultiplier — Biting Strike.</summary>
public const uint FloatCriticalMultiplier = 136;
/// <summary>ACE PropertyFloat.CriticalFrequency — Crushing Blow.</summary>
public const uint FloatCriticalFrequency = 147;
/// <summary>ACE PropertyFloat.IgnoreArmor — Armor Cleaving.</summary>
public const uint FloatIgnoreArmor = 155;
public const uint IntItemMaxLevel = 319;
/// <summary>Highest aetheria level on Infinite Leaftide (ACECustom AetheriaChance rolls up to 10; retail stops at 5).</summary>
public const int AetheriaMaxLevel = 10;
/// <summary>Gear ratings ILT aetheria can carry: C, CD and CDR (PropertyInt GearCrit / GearCritDamage / GearCritDamageResist).</summary>
public const uint IntGearCrit = 372;
public const uint IntGearCritDamage = 374;
public const uint IntGearCritDamageResist = 375;
public const uint IntSummoningMastery = 362;
public const uint IntEnlightenment = 390;
public const uint IntSplitArrowCount = 9031;
public const uint IntMaterialType = 131;
public const uint IntUses = 92;
/// <summary>ACECustom charm item: current tier (PropertyInt.CharmLevel).</summary>
public const uint IntCharmLevel = 50005;
/// <summary>ACECustom charm item: highest tier for this charm line (PropertyInt.CharmMaxLevel).</summary>
public const uint IntCharmMaxLevel = 50006;
public const uint StrUse = 14;
public const uint QuadTotalXp = 1;
public const uint QuadAvailableXp = 2;
public const uint QuadItemTotalXp = 4;
/// <summary>ACECustom PropertyInt64.BankedLuminance (sent with each XP batch).</summary>
public const uint QuadBankedLuminance = 9005;
public const uint BoolNeverChunk = 9030;
public const uint BoolPyrealRefillActive = 9049;
public const uint BoolUniversalMasteryActive = 50038;
/// <summary>
/// Every charm in ACECustom's CharmAbilityRegistry (WCIDs and player flags match the server's
/// WCIDToAbilityId map and PropertyBool ids). Guardian Hand is not a registry charm and has no
/// published WCID — see IltGear.
/// </summary>
public static readonly IltCharmDef[] Charms =
{
new("Mana Barrier", new uint[] { 777700001, 777700054, 777710004, 777720004 }, 50010,
"Mana absorbs incoming damage (better ratio at higher tiers)."),
new("Infinite Casting", WcidInfiniteCastingStone, 50028,
"Infinite Casting Stone: spells cast without consuming components."),
new("Asheron's Favor", new uint[] { 777700020, 777710002, 777720002 }, 50030,
"+10 / 15 / 20% health and +50 / 100 / 250 natural armor."),
new("Artisan's", new uint[] { 777700021, 777710003, 777720003 }, 50031,
"Imbue success chance +4 / 8 / 12%."),
new("Shrapnel", new uint[] { 777700022 }, 50032,
"Tectonic Rifts cast as Rocky Shrapnel (Rocky Shrapnel must be learned)."),
new("Agony", new uint[] { 777700023 }, 50033,
"Tectonic Rifts I casts as Ring of Unspeakable Agony (the spell must be learned)."),
new("Split Cast", new uint[] { 777700024 }, 50035,
"Streak, Arc and Bolt spells split to several nearby targets."),
new("Explosive Arrow", new uint[] { 777700025, 777710005, 777720005 }, 50036,
"Arrow hits detonate an elemental ring at the target."),
new("Omni Strike", new uint[] { 777700026 }, 50037,
"Melee hits use the damage type the target is weakest to."),
new("Fork", new uint[] { 777700027, 777710007, 777720007 }, 50039,
"Streak, Arc and Bolt projectiles fork to nearby enemies (50 / 75 / 100% damage)."),
new("Auto-Rebuff", new uint[] { 777700300 }, 0,
"Keeps your buffs up automatically."),
new("Summon Essence Refill", new uint[] { WcidSummonRefillCharm }, BoolPyrealRefillActive,
"Refills an empty pet essence from banked pyreals when you summon."),
new("Universal Summoning Mastery", new uint[] { WcidUniversalMasteryCharm }, BoolUniversalMasteryActive,
"Use pet essences of any summoning mastery."),
};
private readonly RynthCoreHost _host;
private readonly IltObjects _cache;
/// <summary>AC's CM_Combat value for peace mode (RynthAi's CombatMode.NonCombat).</summary>
private const int CombatModeNonCombat = 1;
private readonly Dictionary<int, uint> _wcidCache = new();
private readonly Dictionary<int, long> _lastIdRequest = new();
/// <summary>Don't re-request appraisal for the same object more often than this.</summary>
private const long IdRequestThrottleMs = 30_000;
public IltInventory(RynthCoreHost host, IltObjects cache)
{
_host = host;
_cache = cache;
}
public RynthCoreHost Host => _host;
public IltObjects Cache => _cache;
public uint PlayerId => _host.GetPlayerId();
// ── Player state ────────────────────────────────────────────────────────
/// <summary>The client busy hourglass is up (an action is in progress).</summary>
public bool IsBusy => _host.HasGetBusyState && _host.GetBusyState() != 0;
/// <summary>Player is in peace mode (combat mode NonCombat). True when the engine can't tell.</summary>
public bool InPeaceMode => !_host.HasGetCurrentCombatMode || _host.GetCurrentCombatMode() == CombatModeNonCombat;
public int PlayerInt(uint stype, int fallback = 0)
=> _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(PlayerId, stype, out int v) ? v : fallback;
public bool PlayerBool(uint stype)
=> _host.HasGetObjectBoolProperty && _host.TryGetObjectBoolProperty(PlayerId, stype, out bool v) && v;
public long PlayerQuad(uint stype)
=> _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(PlayerId, stype, out long v) ? v : 0;
/// <summary>Current/max health from the engine vitals read (0/0 when unavailable).</summary>
public (uint Cur, uint Max) PlayerHealth()
{
if (_host.HasGetPlayerVitals && _host.TryGetPlayerVitals(out uint h, out uint mh, out _, out _, out _, out _))
return (h, mh);
return (0, 0);
}
// ── Item facts ──────────────────────────────────────────────────────────
/// <summary>All items the player carries or wears (snapshot).</summary>
public IEnumerable<WorldObject> Items() => _cache.GetInventory();
/// <summary>Weenie class id, cached per object (0 when unknown).</summary>
public uint Wcid(WorldObject wo)
{
if (_wcidCache.TryGetValue(wo.Id, out uint w) && w != 0) return w;
if (_host.HasGetObjectWcid && _host.TryGetObjectWcid(unchecked((uint)wo.Id), out w))
_wcidCache[wo.Id] = w;
return w;
}
public int Int(WorldObject wo, uint stype, int fallback = 0) => wo.Values(unchecked((int)stype), fallback);
public bool Bool(WorldObject wo, uint stype)
=> _host.HasGetObjectBoolProperty && _host.TryGetObjectBoolProperty(unchecked((uint)wo.Id), stype, out bool v) && v;
public long Quad(WorldObject wo, uint stype)
=> _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(unchecked((uint)wo.Id), stype, out long v) ? v : 0;
/// <summary>A float (PropertyFloat) value; 0 when the host cannot read it or the item has none.</summary>
public double Double(WorldObject wo, uint stype)
=> _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(unchecked((uint)wo.Id), stype, out double v) ? v : 0;
/// <summary>The spell ids on an item (empty when none or the host cannot read them).</summary>
public IReadOnlyList<int> SpellIds(WorldObject wo)
{
if (!_host.HasGetObjectSpellIds) return Array.Empty<int>();
var buf = new uint[64];
int n = _host.GetObjectSpellIds(unchecked((uint)wo.Id), buf, buf.Length);
if (n <= 0) return Array.Empty<int>();
var ids = new int[Math.Min(n, buf.Length)];
for (int i = 0; i < ids.Length; i++) ids[i] = unchecked((int)buf[i]);
return ids;
}
public string Str(WorldObject wo, uint stype)
=> _host.HasGetObjectStringProperty && _host.TryGetObjectStringProperty(unchecked((uint)wo.Id), stype, out string v) ? v ?? string.Empty : string.Empty;
/// <summary>Stack size (1 for non-stackables).</summary>
public int StackSize(WorldObject wo) => Math.Max(1, Int(wo, IntStackSize, 1));
/// <summary>Remaining uses on a structure item (essences, kits, salvage bags).</summary>
public int Uses(WorldObject wo) => Int(wo, IntStructure, 0);
public bool IsEquipped(WorldObject wo)
=> wo.WieldedLocation > 0 || (wo.Wielder != 0 && unchecked((uint)wo.Wielder) == PlayerId);
public bool HasAppraisal(WorldObject wo)
=> !_host.HasHasAppraisalData || _host.HasAppraisalData(unchecked((uint)wo.Id));
/// <summary>
/// Why an item's property reads cannot be trusted (null = they can). Every property read here
/// answers 0 / false both for "the item has none" and for "the host cannot read it", so a chunk
/// rule that acts on a 0 must first know the read was real: the host must expose the readers
/// and confirm the item's appraisal arrived. <paramref name="quads"/> adds the 64-bit reads
/// (item XP), <paramref name="doubles"/> the float reads and <paramref name="spells"/> the
/// spell list, for the rules that use them.
/// </summary>
public string? ReadGap(WorldObject wo, bool quads = false, bool doubles = false, bool spells = false)
{
if (!_host.HasGetObjectIntProperty) return "int properties";
if (!_host.HasGetObjectBoolProperty) return "bool properties";
if (quads && !_host.HasGetObjectQuadProperty) return "item XP";
if (doubles && !_host.HasGetObjectDoubleProperty) return "float properties";
if (spells && !_host.HasGetObjectSpellIds) return "spells";
if (!_host.HasHasAppraisalData || !_host.HasAppraisalData(unchecked((uint)wo.Id))) return "appraisal";
return null;
}
/// <summary>Requests appraisal data, throttled per object. Returns true if a request was sent.</summary>
public bool RequestAppraisal(WorldObject wo)
{
if (!_host.HasRequestId) return false;
long now = Environment.TickCount64;
if (_lastIdRequest.TryGetValue(wo.Id, out long last) && now - last < IdRequestThrottleMs) return false;
_lastIdRequest[wo.Id] = now;
return _host.RequestId(unchecked((uint)wo.Id));
}
// ── Finders / counters ──────────────────────────────────────────────────
public WorldObject? FindByWcid(params uint[] wcids)
=> Items().FirstOrDefault(wo => Array.IndexOf(wcids, Wcid(wo)) >= 0);
public IEnumerable<WorldObject> AllByWcid(params uint[] wcids)
=> Items().Where(wo => Array.IndexOf(wcids, Wcid(wo)) >= 0);
public WorldObject? FindByName(Func<string, bool> predicate)
=> Items().FirstOrDefault(wo => predicate(wo.Name));
/// <summary>Total stack count of items with any of the given WCIDs.</summary>
public long CountByWcid(params uint[] wcids)
=> AllByWcid(wcids).Sum(wo => (long)StackSize(wo));
/// <summary>Total stack count of items whose name matches exactly (case-insensitive).</summary>
public long CountByName(string name)
=> Items().Where(wo => wo.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).Sum(wo => (long)StackSize(wo));
/// <summary>Total stack count of a sigil-chain item (singular or plural stack name; see IltSigilChain.NameIs).</summary>
public long CountByChainName(string chainName)
=> Items().Where(wo => IltSigilChain.NameIs(wo.Name, chainName)).Sum(wo => (long)StackSize(wo));
/// <summary>
/// True when the player carries spell components or an Infinite Casting Stone that isn't
/// known to be switched OFF (an OFF stone doesn't waive components).
/// </summary>
public bool HasCastingSupplies()
=> AllByWcid(WcidInfiniteCastingStone).Any(stone => CharmStatus(stone) != IltTri.Off)
|| Items().Any(wo => wo.ObjectClass == AcObjectClass.SpellComponent);
/// <summary>Free main-pack slots (best effort: capacity minus direct children; -1 when unknown).</summary>
public int FreeMainPackSlots()
{
var cache = _cache;
int player = unchecked((int)PlayerId);
int capacity = PlayerInt(IltObjects.IntItemsCapacity, 102);
int used = cache.GetDirectInventory()
.Count(wo => wo.Container == player && wo.WieldedLocation <= 0 && wo.ObjectClass != AcObjectClass.Container);
return Math.Max(0, capacity - used);
}
// ── Charms ──────────────────────────────────────────────────────────────
/// <summary>
/// ON/OFF/Unknown from the appraisal Use text ("... Status: ON"). Requests appraisal
/// (throttled) when the text isn't loaded yet.
/// </summary>
public IltTri CharmStatus(WorldObject charm)
{
string use = Str(charm, StrUse);
if (use.Length == 0)
{
RequestAppraisal(charm);
return IltTri.Unknown;
}
if (use.Contains("Status: ON", StringComparison.OrdinalIgnoreCase)) return IltTri.On;
if (use.Contains("Status: OFF", StringComparison.OrdinalIgnoreCase)) return IltTri.Off;
return IltTri.Unknown;
}
/// <summary>
/// Charm tier and max tier from the item's CharmLevel / CharmMaxLevel ints, else parsed from
/// the appraisal Use text ("Charm [Tier 2/3]"). (0, 0) until the appraisal is loaded.
/// </summary>
public (int Tier, int MaxTier) CharmTier(WorldObject charm)
{
int tier = Int(charm, IntCharmLevel, 0), max = Int(charm, IntCharmMaxLevel, 0);
if (tier > 0) return (tier, max);
var m = CharmTierText.Match(Str(charm, StrUse));
if (!m.Success) return (0, 0);
int.TryParse(m.Groups[1].Value, out tier);
if (m.Groups[2].Success) int.TryParse(m.Groups[2].Value, out max);
return (tier, max);
}
private static readonly System.Text.RegularExpressions.Regex CharmTierText =
new(@"Charm \[Tier (\d+)(?:/(\d+))?\]", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
/// <summary>Charm definition for an item (by WCID), or null.</summary>
public IltCharmDef? CharmDefFor(WorldObject wo)
{
uint w = Wcid(wo);
if (w == 0) return null;
return Charms.FirstOrDefault(c => Array.IndexOf(c.Wcids, w) >= 0);
}
/// <summary>
/// Every charm the player carries: registered WCIDs plus anything whose Use text starts
/// with "Charm [Tier" (generic ACECustom charm format, catches charms added later).
/// </summary>
public List<WorldObject> CarriedCharms()
{
var list = new List<WorldObject>();
foreach (var wo in Items())
{
if (CharmDefFor(wo) != null) { list.Add(wo); continue; }
if (wo.ObjectClass is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon or AcObjectClass.Armor
or AcObjectClass.Clothing or AcObjectClass.Container or AcObjectClass.Corpse)
continue;
if (Str(wo, StrUse).StartsWith("Charm [Tier", StringComparison.OrdinalIgnoreCase)
|| wo.Name.EndsWith(" Charm", StringComparison.OrdinalIgnoreCase))
list.Add(wo);
}
return list;
}
// ── Actions ─────────────────────────────────────────────────────────────
public bool Use(WorldObject wo) => _host.HasUseObject && _host.UseObject(unchecked((uint)wo.Id));
public bool UseOn(WorldObject source, uint targetId)
=> _host.HasUseObjectOn && _host.UseObjectOn(unchecked((uint)source.Id), targetId);
/// <summary>Forgets cached WCIDs / appraisal throttles (logout).</summary>
public void Reset()
{
_wcidCache.Clear();
_lastIdRequest.Clear();
_cache.Clear();
}
}

View file

@ -0,0 +1,196 @@
// IltLog.cs - RynthILT's diagnostics log: the ILT features' trace categories and key events,
// written to %APPDATA%\RynthCore\RynthILT\Logs\RynthILT_yyyy-MM-dd.txt.
//
// The ILT Hub logged through RynthAi's RynthLog (LogCat.Ilt*, LogEvents.Ilt*) while it lived in
// RynthAi; the moved code keeps the same calls (RynthLog.Write / Trace / Exception / Event), so
// this is a small RynthLog of RynthILT's own:
// Write file (always) and the engine log
// Trace file, only while that category is traced ("/ilt trace <cat|all> on|off")
// Exception file and the engine log, always
// Event as Write for the key events (login, options refreshed, ...); trace-only events
// as Trace
// "/ilt debug on" echoes trace and exception lines to chat (local only). Lines are queued on any
// thread and written by Pump() on the plugin pump.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Text;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT;
/// <summary>One trace category per ILT feature (the names RynthAi's ILT Hub used).</summary>
internal enum LogCat
{
IltHub,
IltOptions,
IltChat,
IltStore,
IltBanking,
IltPets,
IltQuests,
IltProgression,
IltRates,
IltGear,
IltGames,
}
/// <summary>Named key events (the ILT Hub's catalogue in RynthAi's RynthLog).</summary>
internal static class LogEvents
{
public const string IltLogin = "IltHub.Login";
public const string IltWorldCheck = "IltHub.WorldCheck";
public const string IltOptionsRefreshStart = "IltHub.OptionsRefreshStart";
public const string IltOptionsRefreshed = "IltHub.OptionsRefreshed";
public const string IltWindowShown = "IltHub.WindowShown";
public const string IltWindowHidden = "IltHub.WindowHidden";
public const string IltCommand = "IltHub.Command";
public const string IltConfirmation = "IltHub.Confirmation";
public const string IltLogout = "IltHub.Logout";
/// <summary>/aug ApplyAugLines outcome (Progress Refresh current / login probe).</summary>
public const string IltAugLoad = "IltHub.AugLoad";
/// <summary>Events written as a normal log line; the rest only while their category is traced.</summary>
internal static readonly Dictionary<string, (LogCat Cat, bool Info)> Catalog = new(StringComparer.Ordinal)
{
[IltLogin] = (LogCat.IltHub, true),
[IltWorldCheck] = (LogCat.IltOptions, true),
[IltOptionsRefreshStart] = (LogCat.IltOptions, false),
[IltOptionsRefreshed] = (LogCat.IltOptions, true),
[IltWindowShown] = (LogCat.IltHub, true),
[IltWindowHidden] = (LogCat.IltHub, false),
[IltCommand] = (LogCat.IltHub, false),
[IltConfirmation] = (LogCat.IltHub, false),
[IltLogout] = (LogCat.IltHub, false),
[IltAugLoad] = (LogCat.IltProgression, true),
};
}
internal static class RynthLog
{
private static readonly ConcurrentQueue<string> Pending = new();
private static readonly ConcurrentQueue<string> PendingChat = new();
private static readonly bool[] Traced = new bool[Enum.GetValues<LogCat>().Length];
private static RynthCoreHost _host;
private static bool _hasHost;
private static string _directory = string.Empty;
/// <summary>Echo trace and exception lines to the chat window ("/ilt debug on").</summary>
public static volatile bool DebugToChat;
/// <summary>Where the daily files go (tests point it at a scratch folder).</summary>
public static string Directory => _directory;
public static void Init(RynthCoreHost host, string? directory = null)
{
_host = host;
_hasHost = true;
_directory = directory ?? Path.Combine(RynthILTPlugin.SettingsRoot, "Logs");
}
/// <summary>Drops the host (plugin shutdown): nothing is written to it afterwards.</summary>
public static void Shutdown()
{
Pump();
_hasHost = false;
}
public static void Write(LogCat cat, string message)
{
Enqueue(cat, message);
HostLog(message);
}
public static void Trace(LogCat cat, string message)
{
if (!IsTracing(cat)) return;
Enqueue(cat, message);
if (DebugToChat) Chat($"[RynthILT {cat}] {message}");
}
public static void Exception(LogCat cat, Exception ex, string context = "")
{
string line = $"EXCEPTION {(context.Length > 0 ? context + ": " : "")}{ex.GetType().Name}: {ex.Message}";
Enqueue(cat, line + Environment.NewLine + ex.StackTrace);
HostLog(line);
if (DebugToChat) Chat($"[RynthILT {cat}] {line}");
}
public static void Event(string eventKey, string message)
{
if (!LogEvents.Catalog.TryGetValue(eventKey, out var e)) { Write(LogCat.IltHub, $"[{eventKey}] {message}"); return; }
if (e.Info) Write(e.Cat, $"[{eventKey}] {message}");
else Trace(e.Cat, $"[{eventKey}] {message}");
}
/// <summary>True when <see cref="Event"/> would record the event (an Info event, or a traced Trace one).</summary>
public static bool IsEventEnabled(string eventKey)
=> !LogEvents.Catalog.TryGetValue(eventKey, out var e) || e.Info || IsTracing(e.Cat);
public static bool IsTracing(LogCat cat) => (int)cat >= 0 && (int)cat < Traced.Length && Traced[(int)cat];
public static void SetTracing(LogCat cat, bool on)
{
if ((int)cat >= 0 && (int)cat < Traced.Length) Traced[(int)cat] = on;
}
/// <summary>Every category on or off; returns how many.</summary>
public static int SetTracingAll(bool on)
{
for (int i = 0; i < Traced.Length; i++) Traced[i] = on;
return Traced.Length;
}
public static bool TryParseCategory(string name, out LogCat cat)
{
if (Enum.TryParse(name, ignoreCase: true, out cat)) return true;
return Enum.TryParse("Ilt" + name, ignoreCase: true, out cat);
}
public static string TracedList()
{
var on = new List<string>();
foreach (LogCat c in Enum.GetValues<LogCat>()) if (IsTracing(c)) on.Add(c.ToString());
return on.Count == 0 ? "none" : string.Join(", ", on);
}
/// <summary>Writes the queued lines (plugin pump).</summary>
public static void Pump()
{
int lines = 0;
while (lines++ < 20 && PendingChat.TryDequeue(out string? chat))
{
if (!_hasHost) continue;
try { if (_host.HasWriteToChat) _host.WriteToChat(chat, 1); } catch { }
}
if (Pending.IsEmpty || _directory.Length == 0) return;
var sb = new StringBuilder();
int n = 0;
while (n++ < 2000 && Pending.TryDequeue(out string? line)) sb.Append(line).Append(Environment.NewLine);
try
{
System.IO.Directory.CreateDirectory(_directory);
File.AppendAllText(Path.Combine(_directory, $"RynthILT_{DateTime.Now:yyyy-MM-dd}.txt"), sb.ToString());
}
catch { /* a log that can't be written must never break a feature */ }
}
private static void Enqueue(LogCat cat, string message)
{
if (Pending.Count > 20000) return; // nothing is draining (no pump): don't grow forever
Pending.Enqueue($"{DateTime.Now:HH:mm:ss.fff} [{cat}] {message}");
}
private static void HostLog(string message)
{
if (!_hasHost) return;
try { _host.Log("[RynthILT] " + message); } catch { }
}
/// <summary>Queued for the pump (trace lines can come from the render thread).</summary>
private static void Chat(string text)
{
if (PendingChat.Count < 200) PendingChat.Enqueue(text);
}
}

View file

@ -0,0 +1,344 @@
// IltMigration.cs - Carries the ILT Hub's saved data over from RynthAi (2026-10-13).
//
// While the ILT Hub lived in RynthAi it saved per character in RynthAi's settings folder
// (<RynthAi>\SettingsProfiles\<world or ACEmulator>\<character>\: ilt-hub.json,
// ilt-hub-transactions.json, ilt-hub-profiles\) and for every character in the RynthAi folder
// (IltHubProfiles\, ilt-aug-costs.json); the server list and the "Force enable" override were
// fields of each RynthAi profile (FeatureServerNames, ForceServerFeatures).
//
// RynthILT keeps its own files (IltHubStore, IltSettingsStore). On a character's first login
// with RynthILT (no hub.json yet) the old files are COPIED, never moved or deleted: RynthAi no
// longer reads them, and a rollback to an older RynthAi still finds them. Existing RynthILT files
// are never overwritten. The character's active RynthAi profile adds its world names to
// RynthILT's list and, when it had "Force enable" ticked, ticks this character's "Treat this world
// as ILT". The shared files are copied once (IltSettings.SharedFilesMigrated). Pump thread.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using RynthCore.Install;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>
/// The fields of a RynthAi profile RynthILT reads (the rest of the file is ignored): the two Server
/// Features fields, and the settings that moved to RynthILT on 2026-10-20 (null when the profile
/// predates them: the default applies).
/// </summary>
public sealed class IltLegacyProfileFlags
{
public List<string>? FeatureServerNames;
public bool ForceServerFeatures;
/// <summary>RynthAi's Empyrean Handler ring evade (on by default there too).</summary>
public bool? HandlerRingEvade;
/// <summary>RynthAi's Vaulted Dungeons master switch (off by default).</summary>
public bool? EnableVaultedDungeons;
/// <summary>RynthAi's T11 item-aug override (-1 = automatic).</summary>
public int? T11ItemAugsOverride;
}
/// <summary>The Remote tab switches of RynthAi's huds.json that moved to RynthILT (2026-10-20).</summary>
public sealed class IltLegacyHuds
{
public bool? MiniShowBank;
public bool? MiniShowGuardian;
}
/// <summary>The Pets tab fields of RynthAi's miniremote.json that moved to RynthILT (2026-10-20).</summary>
public sealed class IltLegacyMiniRemote
{
public IltLegacyPetTab? Pet;
}
public sealed class IltLegacyPetTab
{
public bool? UsePyrealRefillPath;
public bool? AutoCaptureEnabled;
public int? CaptureLensIndex;
}
internal static class IltMigration
{
/// <summary>RynthAi's per-server profile folders (overridable for the tests).</summary>
public static string LegacyProfilesBase = Path.Combine(RynthInstallPaths.RynthAiDir, "SettingsProfiles");
/// <summary>RynthAi's folder (shared profiles, aug costs; overridable for the tests).</summary>
public static string LegacySharedRoot = RynthInstallPaths.RynthAiDir;
/// <summary>RynthAi's folder for profiles saved before they went per server.</summary>
private const string LegacyServerFolder = "ACEmulator";
/// <summary>RynthAi's file-name sanitizer (LegacyDashboardRenderer.SanitizeFileName).</summary>
internal static string RynthAiSafeName(string name)
{
var sb = new StringBuilder(name.Length);
foreach (char c in name)
sb.Append(char.IsLetterOrDigit(c) || c == '\'' || c == '-' ? c : '_');
return sb.ToString();
}
/// <summary>RynthAi's settings folder for this character: the world's, else the pre-per-server one. Null when neither exists.</summary>
public static string? FindLegacyCharFolder(string world, string charName)
{
if (string.IsNullOrWhiteSpace(charName)) return null;
string safeChar = RynthAiSafeName(charName.Trim());
var candidates = new List<string>();
if (!string.IsNullOrWhiteSpace(world))
{
string safeWorld = RynthAiSafeName(world.Trim());
if (safeWorld.Length > 0) candidates.Add(Path.Combine(LegacyProfilesBase, safeWorld, safeChar));
}
candidates.Add(Path.Combine(LegacyProfilesBase, LegacyServerFolder, safeChar));
foreach (string dir in candidates)
if (Directory.Exists(dir) && (File.Exists(Path.Combine(dir, "ilt-hub.json"))
|| File.Exists(Path.Combine(dir, "ilt-hub-transactions.json"))
|| Directory.Exists(Path.Combine(dir, "ilt-hub-profiles"))
|| File.Exists(Path.Combine(dir, "active_profile.txt"))
|| File.Exists(Path.Combine(dir, LegacyMiniRemoteFile))
|| File.Exists(Path.Combine(dir, "Default.json"))))
return dir;
return null;
}
/// <summary>Whether <paramref name="charFolder"/>'s copy from RynthAi failed and hasn't been finished yet.</summary>
public static bool IsPending(IltSettings settings, string charFolder)
{
if (string.IsNullOrEmpty(charFolder)) return false;
foreach (string f in settings.PendingCharacterMigrations ?? new List<string>())
if (string.Equals(f, charFolder, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
private static void SetPending(IltSettings settings, string charFolder, bool pending)
{
settings.PendingCharacterMigrations ??= new List<string>();
settings.PendingCharacterMigrations.RemoveAll(f => string.Equals(f, charFolder, StringComparison.OrdinalIgnoreCase));
if (pending) settings.PendingCharacterMigrations.Add(charFolder);
}
/// <summary>
/// First login of a character with RynthILT: copies its RynthAi ILT Hub files into
/// <paramref name="newFolder"/> (only when it has no hub.json yet, or an earlier copy failed
/// part-way) and folds its RynthAi Server Features into <paramref name="settings"/>.
/// <paramref name="forceIlt"/> says whether the profile had "Force enable" ticked. Returns what
/// was done (for the log), empty when nothing. When a file can't be copied the folder is marked
/// pending in <paramref name="settings"/> (save them): the Hub then writes nothing there and the
/// next call copies what is still missing (never overwriting).
/// </summary>
public static List<string> MigrateCharacter(string newFolder, string world, string charName, IltSettings settings, out bool forceIlt)
{
forceIlt = false;
var done = new List<string>();
if (string.IsNullOrEmpty(newFolder)) return done;
bool wasPending = IsPending(settings, newFolder);
if (!wasPending && File.Exists(Path.Combine(newFolder, IltHubStore.StateFile))) return done;
string? legacy = FindLegacyCharFolder(world, charName);
if (legacy == null)
{
// The RynthAi files are gone: nothing left to wait for.
if (wasPending) { SetPending(settings, newFolder, false); done.Add("the RynthAi files of an unfinished copy are gone; RynthILT's own files are used from now on"); }
return done;
}
int failed = 0;
if (CopyIfMissing(Path.Combine(legacy, "ilt-hub.json"), Path.Combine(newFolder, IltHubStore.StateFile), ref failed))
done.Add("ilt-hub.json");
if (CopyIfMissing(Path.Combine(legacy, "ilt-hub-transactions.json"), Path.Combine(newFolder, IltHubStore.TransactionsFile), ref failed))
done.Add("ilt-hub-transactions.json");
int profiles = CopyFolder(Path.Combine(legacy, "ilt-hub-profiles"), Path.Combine(newFolder, IltHubStore.ProfilesFolder), ref failed);
if (profiles > 0) done.Add($"{profiles} Hub profile(s)");
if (failed > 0)
{
SetPending(settings, newFolder, true);
done.Add($"{failed} file(s) NOT copied (see the lines above; the originals in {legacy} are untouched). " +
"The Hub saves nothing for this character until they are; tried again every few minutes and at each login");
}
else if (wasPending)
{
SetPending(settings, newFolder, false);
done.Add("the earlier unfinished copy is complete");
}
if (ReadProfileFlags(legacy, out IltLegacyProfileFlags flags))
{
int added = MergeServerNames(settings, flags.FeatureServerNames);
if (added > 0) done.Add($"{added} server name(s) from the RynthAi profile");
if (flags.ForceServerFeatures)
{
forceIlt = true;
done.Add("\"Force enable\" -> Treat this world as ILT");
}
}
return done;
}
/// <summary>
/// Once for every character: RynthAi's shared Hub profiles and aug-cost table into
/// <paramref name="newRoot"/> (never over a file RynthILT already has). Returns what was done.
/// Marked done only when every copy worked: a failed one is tried again at the next login.
/// </summary>
public static List<string> MigrateShared(IltSettings settings, string newRoot)
{
var done = new List<string>();
if (settings.SharedFilesMigrated) return done;
int failed = 0;
int profiles = CopyFolder(Path.Combine(LegacySharedRoot, "IltHubProfiles"), Path.Combine(newRoot, "Profiles"), ref failed);
if (profiles > 0) done.Add($"{profiles} shared Hub profile(s)");
if (CopyIfMissing(Path.Combine(LegacySharedRoot, "ilt-aug-costs.json"), Path.Combine(newRoot, "ilt-aug-costs.json"), ref failed))
done.Add("ilt-aug-costs.json");
if (failed == 0) settings.SharedFilesMigrated = true;
else done.Add($"{failed} shared file(s) NOT copied; tried again at the next login");
return done;
}
/// <summary>RynthAi's per-character Mini Remote file (the Pets tab's settings).</summary>
public const string LegacyMiniRemoteFile = "miniremote.json";
/// <summary>RynthAi's per-character HUD file (the Remote tab's section switches).</summary>
public const string LegacyHudsFile = "huds.json";
/// <summary>
/// Once per character (IltHubState.RynthAiSettingsImported): the RynthAi settings that moved to
/// RynthILT on 2026-10-20 are copied from the character's RynthAi files into <paramref name="state"/>:
/// from miniremote.json the Pets tab's ACECustom options (summon from empty with the refill
/// charm, siphon auto-capture and its lens); from the active profile (as ReadProfileFlags) the
/// Empyrean Handler ring evade, the Vaulted Dungeons master switch and the T11 item-aug override;
/// from huds.json the Remote tab's Bank / Guardian switches. The RynthAi files are only read (RynthAi keeps the
/// old fields readable and no longer uses them). A character with no RynthAi files keeps
/// RynthILT's defaults. Returns what was copied (for the log); empty when nothing was done.
/// </summary>
public static List<string> ImportRynthAiSettings(IltHubState state, string world, string charName)
{
var done = new List<string>();
if (state.RynthAiSettingsImported || string.IsNullOrWhiteSpace(charName)) return done;
string? legacy = FindLegacyCharFolder(world, charName);
if (legacy != null)
{
if (ReadJson(Path.Combine(legacy, LegacyMiniRemoteFile), IltHubJsonContext.Default.IltLegacyMiniRemote) is { Pet: { } pet })
{
if (pet.UsePyrealRefillPath is bool refill) { state.Pet.RefillFromEmpty = refill; done.Add($"summon from empty essences {(refill ? "on" : "off")}"); }
if (pet.AutoCaptureEnabled is bool capture) { state.Pet.AutoCapture = capture; done.Add($"auto-capture {(capture ? "on" : "off")}"); }
if (pet.CaptureLensIndex is int lens)
{
state.Pet.CaptureLens = Math.Clamp(lens, 0, PetCaptureRules.Lenses.Length - 1);
done.Add("capture lens " + PetCaptureRules.LensAt(state.Pet.CaptureLens).Name);
}
}
if (ReadJson(Path.Combine(legacy, LegacyHudsFile), IltHubJsonContext.Default.IltLegacyHuds) is { } huds)
{
if (huds.MiniShowBank is bool bank) { state.Remote.ShowBank = bank; if (!bank) done.Add("the Remote tab's Bank hidden"); }
if (huds.MiniShowGuardian is bool g) { state.Remote.ShowGuardian = g; if (!g) done.Add("the Remote tab's Guardian line hidden"); }
}
if (ReadProfileFlags(legacy, out IltLegacyProfileFlags flags))
{
if (flags.HandlerRingEvade is bool ring) { state.Combat.HandlerRingEvade = ring; done.Add($"Empyrean Handler ring evade {(ring ? "on" : "off")}"); }
if (flags.EnableVaultedDungeons is bool vaulted) { state.VaultedDungeonsEnabled = vaulted; done.Add($"Vaulted Dungeons master switch {(vaulted ? "on" : "off")}"); }
if (flags.T11ItemAugsOverride is int augs && augs >= 0) { state.T11.ItemAugsOverride = augs; done.Add($"T11 item augmentations fixed at {augs:N0}"); }
}
}
state.RynthAiSettingsImported = true;
if (done.Count == 0) done.Add(legacy == null ? "no RynthAi settings for this character (defaults kept)" : "nothing set in RynthAi (defaults kept)");
return done;
}
/// <summary>A JSON file read with <paramref name="info"/>, or null (missing or unreadable: logged).</summary>
private static T? ReadJson<T>(string path, System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> info) where T : class
{
try
{
return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllText(path), info) : null;
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.IltStore, ex, $"migration: read {path}");
return null;
}
}
/// <summary>The character's active RynthAi profile's Server Features fields.</summary>
internal static bool ReadProfileFlags(string legacyCharFolder, out IltLegacyProfileFlags flags)
{
flags = new IltLegacyProfileFlags();
try
{
string active = "Default";
string marker = Path.Combine(legacyCharFolder, "active_profile.txt");
if (File.Exists(marker))
{
string name = File.ReadAllText(marker).Trim();
if (name.Length > 0) active = name;
}
string path = Path.Combine(legacyCharFolder, active + ".json");
if (!File.Exists(path)) return false;
var f = JsonSerializer.Deserialize(File.ReadAllText(path), IltHubJsonContext.Default.IltLegacyProfileFlags);
if (f == null) return false;
flags = f;
return true;
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.IltStore, ex, "migration: RynthAi profile read");
return false;
}
}
/// <summary>Adds the names the list doesn't have yet (case-insensitive); returns how many.</summary>
internal static int MergeServerNames(IltSettings settings, IEnumerable<string>? names)
{
if (names == null) return 0;
int added = 0;
foreach (string n in ServerFeatureGate.ParseList(string.Join(",", names)))
{
if (settings.ServerNames.Any(have => have.Equals(n, StringComparison.OrdinalIgnoreCase))) continue;
settings.ServerNames.Add(n);
added++;
}
return added;
}
/// <summary>
/// Copies <paramref name="from"/> to <paramref name="to"/> unless the source is missing or the
/// target exists. A failed copy is never silent: it is logged and said in chat once per folder
/// (DataWriteGuard, on ILT), with the reason and the fix and where the original still is, and
/// counted in <paramref name="failed"/>.
/// </summary>
private static bool CopyIfMissing(string from, string to, ref int failed)
{
try
{
if (!File.Exists(from) || File.Exists(to)) return false;
}
catch { return false; }
string fromDir = Path.GetDirectoryName(from) ?? from;
bool ok = DataWriteGuard.TrySave($"{Path.GetFileName(from)} carried over from RynthAi (the original is still in {fromDir})", to, () =>
{
Directory.CreateDirectory(Path.GetDirectoryName(to)!);
File.Copy(from, to);
});
if (!ok) failed++;
return ok;
}
private static int CopyFolder(string from, string to, ref int failed)
{
int n = 0;
string[] files;
try
{
if (!Directory.Exists(from)) return 0;
files = Directory.GetFiles(from, "*.json");
}
catch (Exception ex)
{
failed++;
RynthLog.Exception(LogCat.IltStore, ex, $"migration: list {from}");
return 0;
}
foreach (string f in files)
if (CopyIfMissing(f, Path.Combine(to, Path.GetFileName(f)), ref failed)) n++;
return n;
}
}

View file

@ -0,0 +1,129 @@
// IltParse.cs — Shared parsing / formatting helpers for ILT Hub server output.
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Centralised so every feature uses the same number parsing (commas, k/m/b/t suffixes),
// the same compact K/M/B display, and the same regexes. Regexes are static and built once;
// RegexOptions.Compiled is harmless under NativeAOT (it falls back to the interpreter).
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthILT.Hub;
internal static class IltParse
{
private const RegexOptions Opt = RegexOptions.Compiled | RegexOptions.CultureInvariant;
/// <summary>
/// "/aug" level line: "Creature:1,234", "Duration: 1,234", or "Specialize: 2".
/// Trailing notes ("Triune Weave: 5 (adds ...)") are allowed; the planner only keeps known keys.
/// </summary>
public static readonly Regex AugLine = new(@"^(\w+)\s*:\s*(\d[\d,.\s']*)", Opt);
/// <summary>"/pets" / "/shinies" roster entry: "12. Shiny Drudge Ravener".</summary>
public static readonly Regex RosterLine = new(@"^\s*(\d+)\.\s+(.+)$", Opt);
/// <summary>Bank-command amount entry: "1.5m", "250,000", "2b".</summary>
public static readonly Regex AmountInput = new(@"^([\d,.]+)\s*([kmbt]?)$", Opt | RegexOptions.IgnoreCase);
/// <summary>AC character name: starts with a letter, then letters, spaces, apostrophes or hyphens (max 32).</summary>
public static readonly Regex CharacterName = new(@"^[A-Za-z][A-Za-z '\-]{0,31}$", Opt);
/// <summary>A comma-grouped or plain integer as printed by ACE's N0 format.</summary>
public const string AmountPattern = @"(?:\d{1,3}(?:,\d{3})+|\d+)";
/// <summary>"Transferred 5,000 Pyreals to Bob" (optional " (offline)" / trailing "--- note").</summary>
public static readonly Regex BankSent = new(
@"^Transferred (" + AmountPattern + @") ([^']+?) to ([^-]+?)(?:\s*---.*)?$", Opt);
/// <summary>"Received 5,000 Pyreals from Bob".</summary>
public static readonly Regex BankReceived = new(
@"^Received (" + AmountPattern + @") ([^']+?) from (.+?)(?:\s*---.*)?$", Opt);
/// <summary>"/xp all" cost line: "[XP] Your XP cost for next 1 Strength level is: 1,234".</summary>
public static readonly Regex XpCost = new(@"\[XP\] Your XP cost for next 1 (\w+) level is: ([\d,]+)", Opt);
/// <summary>"/attr" success: "[ATTR] Strength attribute raised by 10, costing 1,234!".</summary>
public static readonly Regex AttrRaised = new(@"^\[ATTR\] (\w+) attribute raised by (\d+), costing ([\d,]+)", Opt);
private static readonly Regex GroupedInt = new(@"^\d{1,3}(?:[,.\s']\d{3})+|^\d+", RegexOptions.CultureInvariant);
/// <summary>
/// The level in an AugLine value: digits grouped by a comma, period, space or apostrophe
/// ("4,300", "4.300", "4 300", "4'300") read as one number; "2 (adds 5)" as 2; "1.5" as 1. 0 when absent.
/// </summary>
public static long ParseAugValue(string text)
{
if (string.IsNullOrEmpty(text)) return 0;
var m = GroupedInt.Match(text.Trim());
if (!m.Success) return 0;
var digits = new System.Text.StringBuilder(m.Value.Length);
foreach (char c in m.Value) if (char.IsDigit(c)) digits.Append(c);
return long.TryParse(digits.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out long v) ? v : 0;
}
/// <summary>Strips commas and parses the leading integer; 0 when absent.</summary>
public static long ParseLeadingLong(string text)
{
if (string.IsNullOrEmpty(text)) return 0;
string s = text.Replace(",", string.Empty).Trim();
int end = 0;
while (end < s.Length && char.IsDigit(s[end])) end++;
return end > 0 && long.TryParse(s.AsSpan(0, end), NumberStyles.None, CultureInfo.InvariantCulture, out long v) ? v : 0;
}
/// <summary>
/// Parses a user-entered amount with optional k/m/b/t suffix ("1.5m" → 1,500,000).
/// Returns false for empty, negative, or overflowing input.
/// </summary>
public static bool TryParseAmount(string input, out long amount)
{
amount = 0;
var m = AmountInput.Match((input ?? string.Empty).Trim());
if (!m.Success) return false;
if (!decimal.TryParse(m.Groups[1].Value.Replace(",", string.Empty), NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture, out decimal baseVal))
return false;
decimal mult = char.ToLowerInvariant(m.Groups[2].Value.Length > 0 ? m.Groups[2].Value[0] : ' ') switch
{
'k' => 1_000m,
'm' => 1_000_000m,
'b' => 1_000_000_000m,
't' => 1_000_000_000_000m,
_ => 1m,
};
decimal total = Math.Floor(baseVal * mult);
if (total <= 0 || total > long.MaxValue) return false;
amount = (long)total;
return true;
}
/// <summary>Compact display: 950 → "950", 12_300 → "12.3K", 4_500_000 → "4.50M", 2e9 → "2.00B".</summary>
public static string Compact(double value)
{
double a = Math.Abs(value);
string s = a >= 1e12 ? (value / 1e12).ToString("0.00", CultureInfo.InvariantCulture) + "T"
: a >= 1e9 ? (value / 1e9).ToString("0.00", CultureInfo.InvariantCulture) + "B"
: a >= 1e6 ? (value / 1e6).ToString("0.00", CultureInfo.InvariantCulture) + "M"
: a >= 1e3 ? (value / 1e3).ToString("0.0", CultureInfo.InvariantCulture) + "K"
: value.ToString("0", CultureInfo.InvariantCulture);
return s;
}
/// <summary>Full grouped display: 1234567 → "1,234,567".</summary>
public static string N0(long value) => value.ToString("N0", CultureInfo.InvariantCulture);
/// <summary>"3d 4h 12m 5s" style duration; "ready" when zero or negative.</summary>
public static string Duration(TimeSpan span)
{
if (span <= TimeSpan.Zero) return "ready";
if (span.TotalDays >= 1) return $"{(int)span.TotalDays}d {span.Hours}h {span.Minutes}m";
if (span.TotalHours >= 1) return $"{span.Hours}h {span.Minutes}m {span.Seconds}s";
if (span.TotalMinutes >= 1) return $"{span.Minutes}m {span.Seconds}s";
return $"{span.Seconds}s";
}
/// <summary>Strips "&lt;Tell:…&gt;" style markup the chat window sometimes leaves on names.</summary>
public static string StripMarkup(string text)
=> Regex.Replace(text ?? string.Empty, @"<[^>]*>", string.Empty).Trim();
}

View file

@ -0,0 +1,394 @@
// IltPetAutomation.cs — ACECustom's parts of RynthAi's Pets tab: the pet charms, the "summon from an
// empty essence" refill path and siphon-lens auto-capture.
// Moved out of RynthAi's MiniRemote/PetsTab.cs 2026-10-20 (originally SilentKelpie's IltPets, ILT
// Hub): summoning is every server's, so the roster, healing and cosmetic pets stay RynthAi's, but
// these three are ACECustom content and live here now.
//
// * Pet charms (section "pets-charms"): Summon Essence Refill (the server refills an empty essence
// from banked pyreals) and Universal Summoning Mastery, read from the charm's appraisal text and
// the player bools the server stamps, plus the "no spell components" warning when the server
// requires them. The refill opt-in feeds RynthAi's PetManager through RynthILT.Hub
// AllowSummonOnEmpty (cached here every tick; an unknown state never spends pyreals).
// * Auto siphon capture (section "pets-capture", ACECustom MonsterCapture): when enabled, uses the
// chosen lens on the nearest attackable creature within 5 m once it is <=20% health or under
// 20 HP (Asheron's Lens skips the health gate). Resonance still needs a prior failed capture on
// the server. Bounded per creature and overall (PetCaptureThrottle).
// Ticks only on an ILT-like world (IltHubController); the sections draw nothing elsewhere.
using System;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltPetAutomation : IIltFeature
{
private const long CaptureThinkMs = 250;
private const long CaptureCooldownMs = 2500;
private const long CaptureFailBackoffMs = 8000;
private const long CharmScanMs = 2000;
private const long GateMs = 500;
private readonly IltHubContext _ctx;
private readonly PetCaptureThrottle _captureThrottle = new();
private long _lastCaptureThink;
private long _captureCooldownUntil;
private long _lastCharmScan;
private long _lastGate;
// Read by the render thread and (AllowSummonOnEmpty) by RynthAi's pump.
private volatile string _captureStatus = "off";
private volatile bool _uiRefillActive;
private volatile bool _uiMasteryActive;
private volatile bool _uiHasCasting = true;
private volatile bool _allowSummonOnEmpty;
// The server's health updates (RynthPluginOnUpdateHealth), for creatures the client has no vitals for.
private const int MaxHealthEntries = 512;
private readonly object _healthGate = new();
private readonly System.Collections.Generic.Dictionary<int, float> _healthRatios = new();
public IltPetAutomation(IltHubContext ctx) => _ctx = ctx;
private IltPetState S => _ctx.State.Pet;
/// <summary>The auto-capture line under the switch (render thread).</summary>
public string CaptureStatus => _captureStatus;
/// <summary>
/// RynthILT.Hub AllowSummonOnEmpty: the last tick's answer, false off an ILT world. Any thread.
/// </summary>
public bool AllowSummonOnEmpty => _ctx.Options.IsIltLikeWorld && _allowSummonOnEmpty;
// ── Charms / gates ──────────────────────────────────────────────────────
/// <summary>Summon Essence Refill charm is carried and switched on (or the server stamped the player bool).</summary>
public bool RefillCharmActive()
{
var inv = _ctx.Inventory;
if (inv.PlayerBool(IltInventory.BoolPyrealRefillActive)) return true;
var charm = inv.FindByWcid(IltInventory.WcidSummonRefillCharm);
return charm != null && inv.CharmStatus(charm) == IltTri.On;
}
public bool MasteryCharmActive()
{
if (_ctx.Options.IsOff(IltFeature.UniversalMastery)) return false;
var inv = _ctx.Inventory;
if (inv.PlayerBool(IltInventory.BoolUniversalMasteryActive)) return true;
var charm = inv.FindByWcid(IltInventory.WcidUniversalMasteryCharm);
return charm != null && inv.CharmStatus(charm) == IltTri.On;
}
/// <summary>
/// Summon from an empty essence (spends banked pyreals) only when the player opted in, the refill
/// charm is active, and the server has positively confirmed the feature: either the feature check
/// reported pet_refill on, or the server stamped the player's refill bool. Pump thread.
/// </summary>
internal bool ComputeAllowSummonOnEmpty()
{
if (!S.RefillFromEmpty || !_ctx.Options.IsIltLikeWorld || !RefillCharmActive()) return false;
bool confirmed = _ctx.Options.IsOn(IltFeature.PetRefill)
|| _ctx.Inventory.PlayerBool(IltInventory.BoolPyrealRefillActive);
if (!confirmed) RynthLog.Trace(LogCat.IltPets, "summon-on-empty refused: pet_refill not confirmed by the server");
return confirmed;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (nowMs - _lastGate >= GateMs)
{
_lastGate = nowMs;
_allowSummonOnEmpty = ComputeAllowSummonOnEmpty();
}
if (nowMs - _lastCharmScan >= CharmScanMs)
{
_lastCharmScan = nowMs;
// Host reads (and appraisal requests) happen here, never on the render thread.
_uiRefillActive = RefillCharmActive();
_uiMasteryActive = MasteryCharmActive();
_uiHasCasting = _ctx.Inventory.HasCastingSupplies();
}
if (nowMs - _lastCaptureThink >= CaptureThinkMs)
{
_lastCaptureThink = nowMs;
TickCapture(nowMs);
}
}
/// <summary>ACECustom MonsterCapture replies: back off after a refuse so lenses aren't burned. Never eats.</summary>
public bool OnChat(string text)
{
if (!S.AutoCapture || string.IsNullOrEmpty(text)) return false;
long now = IltHubContext.NowMs;
if (PetCaptureLines.IsSuccess(text))
{
_captureStatus = "captured";
_captureThrottle.RecordSuccess();
_captureCooldownUntil = now + CaptureCooldownMs;
}
else if (ContainsAny(text,
"too strong",
"blind rage",
"cannot be siphoned",
"cannot be captured",
"No creatures nearby",
"already dead",
"already being captured",
"hasn't failed a capture",
"echo has faded",
"Failed to consume"))
{
_captureStatus = "refused: " + Truncate(text, 48);
_captureCooldownUntil = now + CaptureFailBackoffMs;
}
else if (ContainsAny(text, "siphon failed", "lens shatters", "resisted your capture", "resonance fades"))
{
_captureStatus = "failed (creature may enrage)";
_captureCooldownUntil = now + CaptureFailBackoffMs;
}
return false;
}
/// <summary>A creature's health ratio from the server (RynthPluginOnUpdateHealth; any thread).</summary>
public void NoteHealth(uint objectId, float ratio)
{
if (objectId == 0 || float.IsNaN(ratio)) return;
lock (_healthGate)
{
if (_healthRatios.Count >= MaxHealthEntries) _healthRatios.Clear();
_healthRatios[unchecked((int)objectId)] = Math.Clamp(ratio, 0f, 1f);
}
}
/// <summary>The last health ratio the server sent for a creature, -1 when none.</summary>
private float HealthRatio(int id)
{
lock (_healthGate) return _healthRatios.TryGetValue(id, out float v) ? v : -1f;
}
public void OnLogout()
{
lock (_healthGate) _healthRatios.Clear();
_captureCooldownUntil = 0;
_captureStatus = "off";
_captureThrottle.Reset();
_allowSummonOnEmpty = false;
}
private static bool ContainsAny(string text, params string[] parts)
{
foreach (string p in parts)
if (text.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0) return true;
return false;
}
private static string Truncate(string s, int max) => s.Length <= max ? s : s[..(max - 3)] + "...";
// ── Auto siphon capture (ACECustom MonsterCapture) ───────────────────────
/// <summary>
/// When Auto Capture is on, use the chosen siphon lens on the nearest attackable creature within
/// 5 m once ACECustom's health gate is met (≤20% or under 20 HP; Asheron's skips it). The server
/// picks the nearest creature itself, so this fires only when that nearest candidate is already
/// weak enough: a full-health neighbour closer than the wounded target won't waste a lens.
/// </summary>
internal void TickCapture(long now)
{
if (!S.AutoCapture)
{
_captureStatus = "off";
return;
}
if (_ctx.Options.IsOff(RynthIltHub.FeatureMonsterCapture))
{
_captureStatus = "monster capture disabled on this server";
return;
}
if (now < _captureCooldownUntil)
{
long left = (_captureCooldownUntil - now + 999) / 1000;
if (!_captureStatus.StartsWith("waiting", StringComparison.Ordinal))
_captureStatus = $"waiting {left}s";
return;
}
var inv = _ctx.Inventory;
if (inv.IsBusy) { _captureStatus = "busy"; return; }
var lens = PetCaptureRules.LensAt(S.CaptureLens);
var lensItem = inv.FindByWcid(lens.Wcid);
if (lensItem == null)
{
_captureStatus = $"no {lens.Name} carried";
return;
}
if (!TryFindNearestCaptureTarget(out WorldObject? target, out double distM, out uint curHp, out uint maxHp))
{
_captureStatus = "no attackable creature within 5 m";
return;
}
if (!PetCaptureRules.InRange(distM))
{
_captureStatus = $"{target!.Name} at {distM:0.0} m (need <={PetCaptureRules.CaptureRangeM:0} m)";
return;
}
if (!PetCaptureRules.CanAttempt(lens, curHp, maxHp))
{
float pct = maxHp > 0 ? curHp * 100f / maxHp : -1f;
_captureStatus = pct >= 0
? $"{target!.Name} at {pct:0}% / {curHp} HP (need <={PetCaptureRules.CaptureMaxHealthFraction:P0} or <{PetCaptureRules.CaptureMaxHealthPoints} HP)"
: $"{target!.Name}: health unknown";
return;
}
if (!_captureThrottle.MayAttempt(target!.Id, now))
{
_captureStatus = $"{target.Name}: {PetCaptureThrottle.MaxTriesPerTarget} tries, no capture; left alone for {_captureThrottle.BlockedSecondsLeft(target.Id, now)}s";
return;
}
if (!inv.Use(lensItem))
{
_captureStatus = "UseObject refused";
return;
}
_captureThrottle.RecordAttempt(target.Id, now);
if (_captureThrottle.Exhausted)
{
// Backstop: this many lenses with no recognized capture means something is off. Stop, don't keep burning them.
S.AutoCapture = false;
RynthLog.Write(LogCat.IltPets,
$"auto-capture: {PetCaptureThrottle.MaxTriesWithoutSuccess} lens uses without a capture reply; auto-capture switched off");
}
float shown = maxHp > 0 ? curHp * 100f / maxHp : 0f;
_captureStatus = $"using {lens.Name} on {target.Name} ({shown:0}% / {curHp} HP)";
_captureCooldownUntil = now + CaptureCooldownMs;
RynthLog.Write(LogCat.IltPets,
$"auto-capture: {lens.Name} -> 0x{target.Id:X8} '{target.Name}' d={distM:0.0}m hp={curHp}/{maxHp}");
}
/// <summary>
/// Nearest attackable landscape creature within capture range, with vitals from the host when
/// available, else the server's last health ratio (fraction-only gate). A creature with neither
/// is skipped: no health, no capture decision.
/// </summary>
private bool TryFindNearestCaptureTarget(out WorldObject? best, out double bestDist, out uint curHp, out uint maxHp)
{
best = null;
bestDist = double.MaxValue;
curHp = maxHp = 0;
var host = _ctx.Host;
var objects = _ctx.Inventory.Cache;
uint playerId = _ctx.Inventory.PlayerId;
if (playerId == 0) return false;
int pid = unchecked((int)playerId);
string ownPrefix = _ctx.CharName.Length > 0 ? _ctx.CharName + "'s " : string.Empty;
foreach (var wo in objects.GetLandscape())
{
if (wo == null || wo.Id == pid) continue;
if (wo.ObjectClass != RynthCore.Loot.AcObjectClass.Monster) continue;
if (ownPrefix.Length > 0 && wo.Name.StartsWith(ownPrefix, StringComparison.Ordinal)) continue;
// Skip corpses / non-attackable when the host can tell.
if (host.HasObjectIsAttackable && !host.ObjectIsAttackable(unchecked((uint)wo.Id))) continue;
double d = objects.Distance(pid, wo.Id);
if (d < 0 || d > PetCaptureRules.CaptureRangeM || d >= bestDist) continue;
if (!TryReadCreatureVitals(wo.Id, out uint h, out uint mh)) continue;
if (h == 0) continue; // dead
best = wo;
bestDist = d;
curHp = h;
maxHp = mh;
}
return best != null;
}
/// <summary>
/// Absolute vitals via TryGetTargetVitals when bound; else the health ratio as a 0-1000 scale so
/// only the fraction half of ACECustom's gate can fire.
/// </summary>
private bool TryReadCreatureVitals(int id, out uint cur, out uint max)
{
cur = max = 0;
var host = _ctx.Host;
if (host.HasGetTargetVitals
&& host.TryGetTargetVitals(unchecked((uint)id), out uint h, out uint mh, out _, out _, out _, out _)
&& mh > 0)
{
cur = h;
max = mh;
return true;
}
float ratio = HealthRatio(id);
if (ratio < 0f) return false;
// Synthetic scale: ratio 0.20 -> 200/1000 so IsWeakEnough's fraction half matches.
max = 1000;
cur = (uint)Math.Clamp((int)Math.Round(ratio * 1000f), 1, 1000);
return true;
}
// ── UI (render thread): the Pets tab's ACECustom sections ────────────────
/// <summary>The pet charms and the refill opt-in (section "pets-charms").</summary>
public void RenderCharms()
{
ImGui.Separator();
SafeImGui.TextColored(IltStyle.ColTeal, "Pet charms");
var o = _ctx.Options;
bool refillOff = o.IsOff(IltFeature.PetRefill);
ImGui.TextUnformatted("Summon Essence Refill: " + (refillOff ? "disabled on this server" : _uiRefillActive ? "ON" : "off / not carried"));
ImGui.BeginDisabled(refillOff);
bool usePath = S.RefillFromEmpty;
if (ImGui.Checkbox("Summon from empty essences while the refill charm is ON (spends banked pyreals)", ref usePath))
S.RefillFromEmpty = usePath;
ImGui.EndDisabled();
ImGui.TextUnformatted("Universal Summoning Mastery: "
+ (o.IsOff(IltFeature.UniversalMastery) ? "disabled on this server" : _uiMasteryActive ? "ON" : "off / not carried"));
if (!o.IsOff(IltFeature.RequireComps) && !_uiHasCasting)
SafeImGui.TextColored(IltStyle.ColAmber, "No spell components or Infinite Casting Stone carried.");
}
/// <summary>Siphon-lens auto-capture: enable + which lens to use (section "pets-capture").</summary>
public void RenderCapture()
{
ImGui.Separator();
SafeImGui.TextColored(IltStyle.ColTeal, "Monster capture");
bool captureOff = _ctx.Options.IsOff(RynthIltHub.FeatureMonsterCapture);
ImGui.BeginDisabled(captureOff);
bool en = S.AutoCapture;
if (ImGui.Checkbox("Auto-capture when a creature is weak enough", ref en))
{
S.AutoCapture = en;
_ctx.Post(_captureThrottle.Reset);
}
if (ImGui.IsItemHovered())
{
SafeImGui.SetTooltip(
"Uses the selected siphon lens on the nearest attackable creature within 5 m once it is\n" +
"at or below 20% health or under 20 HP (ACECustom MonsterCapture). Asheron's Lens skips\n" +
"the health gate. Resonance Lens still needs a prior failed capture on the server.\n" +
"Off by default. Stops on its own after 5 tries on one creature (it is left alone for 2 min)\n" +
"or 15 lens uses in a row with no capture.");
}
ImGui.SameLine();
ImGui.SetNextItemWidth(120);
int lens = Math.Clamp(S.CaptureLens, 0, PetCaptureRules.LensNames.Length - 1);
if (ImGui.Combo("##petcapturelens", ref lens, PetCaptureRules.LensNames, PetCaptureRules.LensNames.Length))
S.CaptureLens = lens;
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("Which siphon lens to use. Must be carried in your pack.");
ImGui.EndDisabled();
if (captureOff)
SafeImGui.TextDisabled("Monster capture is disabled on this server.");
else
SafeImGui.TextDisabled("Status: " + _captureStatus);
}
}

View file

@ -0,0 +1,790 @@
// IltPetBreeding.cs - The pet breeding tracker: the Breeding sub-tab of RynthAi's Mini Remote Pets tab,
// drawn here (RynthILT.Hub section "pets-breeding"; RynthAi only hosts it), and the same data as JSON
// for other plugins ("RynthILT.Data" v2 GetPetBreedingJson / PetBreedingCommand).
// Originally SilentKelpie's (2026-10-15, his RynthILT 0.2.7); ported into RynthILT 0.3.1 without his
// RynthOracle Pet Breeding tab: breeding is Leaftide's, so only this plugin draws it.
//
// What it does, on Infinite Leaftide only:
// * reads every carried combat essence (appraisal qualities + the LongDesc breeding block) and
// evaluates it with IltBreedingEssence: stud / dam, each gate that fails, when it clears, growth;
// * counts Ivo's supplies and applies a breeding booster to an essence after the player confirms;
// * runs "@breed-debug" (quietly) for the room check and "@dance" to start the ritual;
// * logs breeding chat (ritual, charge spent, birth, guardian, growth, adulthood, imprint);
// * learns this server's rules from its own text (IltBreedingRules) and reports what it sees to
// the Leaftide feature profile (the pet_breeding / pet_maturity bits).
// Essences are read only while someone is looking (the section drawn, or a reader asking for the
// JSON within WatchMs), so an unwatched tracker costs nothing.
// Threading: Tick / OnChat / actions on the pump; Render on the ImGui thread reads only the
// immutable snapshot and posts actions.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Text;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>Everything the breeding UI and reader JSON show, rebuilt whole on the pump.</summary>
/// <remarks><see cref="RulesView"/> is a frozen copy of the rules: the render thread plans with it while the pump learns.</remarks>
internal sealed record BreedingSnapshot(
IReadOnlyList<BreedEssence> Essences, IReadOnlyList<(BreedSupplyDef Def, long Count)> Supplies,
IReadOnlyList<BreedRuleValue> Rules, IReadOnlyList<IltBreedingEvent> Events, BreedDebugInfo? Debug, DateTime DebugUtc,
IltTri Enabled, IltTri Maturity, IltTri Bond, string Room, int FreeSlots, string Message, double NowUnix, bool Built,
IltBreedingRules RulesView)
{
public static readonly BreedingSnapshot Empty = new(Array.Empty<BreedEssence>(), Array.Empty<(BreedSupplyDef, long)>(),
Array.Empty<BreedRuleValue>(), Array.Empty<IltBreedingEvent>(), null, default, IltTri.Unknown, IltTri.Unknown,
IltTri.Unknown, string.Empty, -1, string.Empty, 0, false, new IltBreedingRules(new IltBreedingState()));
}
internal sealed class IltPetBreeding : IIltFeature
{
/// <summary>Feature bits this tracker reports (IltFeatureCatalog's pet_breeding / pet_maturity rows).</summary>
public const string BitBreeding = RynthIltHub.FeaturePetBreeding;
public const string BitMaturity = "pet_maturity";
/// <summary>ACE commands: the diagnostics reply, and the courtship dance.</summary>
public const string DebugCommand = "@breed-debug";
public const string DanceCommand = "@dance";
// ACECustom pet device qualities (AssessmentProperty, sent with the appraisal).
private const uint StrLongDesc = 16;
private const uint IntUseRequiresLevel = 369;
private const uint IntUseLevelRequirement = 364;
private const uint IntBondLevel = 9053;
private const uint IntPotencyStored = 9056;
private const uint IntMaleCharges = 9057;
private const uint IntMutDamage = 9070, IntMutDamageResist = 9071, IntMutCrit = 9072, IntMutVitality = 9073, IntMutPotency = 9074;
private const uint IntMutationCount = 9075;
private const uint IntMaturityKills = 9077;
private const uint FloatNextBreeding = 9056;
private const uint FloatMaleRefresh = 9057;
private const uint FloatIncense = 9058;
private const uint FloatMaturityXpMult = 9059;
private const uint BoolBondAttuned = 9047;
private const uint BoolNeutered = 9051;
private const uint BoolMaleOverride = 50053;
private const uint BoolJuvenile = 50054;
private const uint BoolCatalyst = 50055;
private const uint BoolOffering = 50056;
/// <summary>The tracker reads essences while it was looked at within this long.</summary>
private const long WatchMs = 6000;
/// <summary>How often a watched tracker re-reads the essences.</summary>
private const long ScanMs = 2000;
/// <summary>Appraisal requests per scan for essences not yet appraised.</summary>
private const int AppraisePerScan = 2;
private readonly IltHubContext _ctx;
private readonly IltBreedingRules _rules;
private long _watchedAt; // Interlocked: render thread and readers mark it
private long _scannedAt;
private bool _refreshAll; // re-appraise every essence on the next scan (after an event)
private string _message = string.Empty;
private volatile BreedingSnapshot _snap = BreedingSnapshot.Empty;
private volatile string _readerJson = string.Empty;
// Render-thread selections (ids of carried essences; 0 = none).
private int _studId, _damId, _targetId;
public IltPetBreeding(IltHubContext ctx)
{
_ctx = ctx;
_rules = new IltBreedingRules(ctx.State.Pet.Breeding);
}
/// <summary>The rules (tests and the controller).</summary>
internal IltBreedingRules Rules => _rules;
/// <summary>The latest snapshot (any thread).</summary>
public BreedingSnapshot Snapshot => _snap;
/// <summary>Someone is looking: keep the essences fresh for a while (any thread).</summary>
public void MarkWatched() => System.Threading.Interlocked.Exchange(ref _watchedAt, IltHubContext.NowMs);
/// <summary>The reader JSON ("RynthILT.Data" GetPetBreedingJson); reading it marks the tracker watched. Any thread.</summary>
public string ReaderJson
{
get { MarkWatched(); return _readerJson; }
}
private static double UnixNow => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000.0;
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (nowMs - System.Threading.Interlocked.Read(ref _watchedAt) > WatchMs) return;
if (_scannedAt != 0 && nowMs - _scannedAt < ScanMs) return;
_scannedAt = nowMs;
Scan();
}
public bool OnChat(string text)
{
if (string.IsNullOrEmpty(text)) return false;
DateTime utc = DateTime.UtcNow;
bool changed = _rules.LearnAll(IltBreedingRules.FromChat(text), utc);
foreach (string raw in text.Split('\n'))
{
string line = raw.Trim();
string? kind = EventKind(line);
if (kind == null) continue;
_rules.AddEvent(kind, line, utc);
changed = true;
if (kind is "ritual" or "birth" or "charge") _ctx.Options.Set(BitBreeding, IltTri.On);
if (kind is "growth" or "adult")
{
_ctx.Options.Set(BitMaturity, IltTri.On);
if (IltBreedingRules.TryParseGrownInto(line, out int stage, out string name)) _rules.LearnStageName(stage, name);
}
// The essences changed on the server (charges, rest, a baby, growth): read them again soon.
if (kind is not "dance") { _refreshAll = true; _scannedAt = 0; }
}
if (changed) RynthLog.Trace(LogCat.IltPets, "breeding: chat updated rules / events");
return false;
}
public void OnLogout()
{
_snap = BreedingSnapshot.Empty;
_readerJson = string.Empty;
_scannedAt = 0;
_message = string.Empty;
}
/// <summary>The event kind of a breeding chat line, or null for any other line.</summary>
internal static string? EventKind(string line)
{
if (line.Length == 0) return null;
if (line.StartsWith("The mating ritual has begun between", StringComparison.OrdinalIgnoreCase)) return "ritual";
if (line.Contains("spent a breeding charge", StringComparison.OrdinalIgnoreCase)) return "charge";
if (line.Contains("A baby pet has been born", StringComparison.OrdinalIgnoreCase)) return "birth";
if (line.StartsWith("The union stirs something", StringComparison.OrdinalIgnoreCase)) return "guardian";
if (line.Contains("yields to its parents", StringComparison.OrdinalIgnoreCase)) return "guardian";
if (line.Contains("Awakened Blessing", StringComparison.OrdinalIgnoreCase)) return "mutation";
if (line.Contains("spectral guardian dissolves", StringComparison.OrdinalIgnoreCase)) return "guardian";
if (line.Contains("has grown into a", StringComparison.OrdinalIgnoreCase)) return "growth";
if (line.Contains("has reached adulthood", StringComparison.OrdinalIgnoreCase)) return "adult";
if (line.Contains("has imprinted on you", StringComparison.OrdinalIgnoreCase)) return "imprint";
if (line.StartsWith("[Breeding] Your pet performs the courtship dance", StringComparison.OrdinalIgnoreCase)) return "dance";
if (line.StartsWith("You administer the Nurturing Draught", StringComparison.OrdinalIgnoreCase)) return "supply";
if (line.StartsWith("You have permanently spayed/neutered", StringComparison.OrdinalIgnoreCase)) return "supply";
return null;
}
// ── Scan (pump) ─────────────────────────────────────────────────────────
/// <summary>Reads every carried combat essence and the supplies, then rebuilds the snapshot and reader JSON.</summary>
private void Scan()
{
IltInventory inv = _ctx.Inventory;
RynthCoreHost host = _ctx.Host;
double now = UnixNow;
DateTime utc = DateTime.UtcNow;
var essences = new List<BreedEssence>();
int appraised = 0;
bool sawBlock = false, sawGrowth = false;
foreach (WorldObject wo in inv.Items())
{
uint wcid = inv.Wcid(wo);
if (!IltBreedingEssence.IsCombatEssence(wcid) && !LooksLikeEssence(wo, inv)) continue;
BreedEssenceFacts f = ReadFacts(host, inv, wo, wcid);
if (f.LongDesc.Contains("Sex:", StringComparison.Ordinal)) sawBlock = true;
if (f.LongDesc.Contains("Growth:", StringComparison.Ordinal)) sawGrowth = true;
_rules.LearnAll(IltBreedingRules.FromAppraisal(f.LongDesc, f.MaleRefreshUnix, now), utc);
if (IltBreedingRules.TryParseGrowth(f.LongDesc, out string stageName, out int stage, out _, out _, out _, out _))
_rules.LearnStageName(stage, stageName);
essences.Add(IltBreedingEssence.Evaluate(f, _rules, now));
// Appraise what isn't loaded (a few per scan), or everything after a breeding event.
if ((_refreshAll || !f.HasId) && appraised < (_refreshAll ? 32 : AppraisePerScan) && inv.RequestAppraisal(wo))
appraised++;
}
_refreshAll = false;
// The server only writes the breeding block while breeding is on: seeing it is the server saying so.
if (sawBlock) _ctx.Options.Set(BitBreeding, IltTri.On);
if (sawGrowth) _ctx.Options.Set(BitMaturity, IltTri.On);
essences.Sort((a, b) =>
{
int c = b.Ready.CompareTo(a.Ready);
if (c != 0) return c;
c = b.Male.CompareTo(a.Male);
return c != 0 ? c : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
});
var supplies = new List<(BreedSupplyDef, long)>(IltBreedingSupplies.All.Length);
foreach (BreedSupplyDef s in IltBreedingSupplies.All) supplies.Add((s, inv.CountByWcid(s.Wcid)));
IltBreedingState st = _rules.State;
BreedDebugInfo? debug = st.LastDebug.Count > 0 ? IltBreedingRules.ParseDebug(st.LastDebug) : null;
var events = st.Log.Select(e => new IltBreedingEvent { Utc = e.Utc, Kind = e.Kind, Text = e.Text }).ToArray();
var snap = new BreedingSnapshot(essences, supplies, _rules.All(), events, debug, st.LastDebugUtc,
EnabledState(), _ctx.Options.Get(BitMaturity), _ctx.Options.Get(IltFeature.PetBond),
_rules.RoomText(), inv.FreeMainPackSlots(), _message, now, true, _rules.Frozen());
_snap = snap;
_readerJson = BuildJson(snap, _rules, _ctx.Options.WorldName);
}
/// <summary>The pet_breeding state the Leaftide profile shows (reported, else the ILT profile's "on").</summary>
private IltTri EnabledState()
{
IltTri t = _ctx.Options.Get(BitBreeding);
return t != IltTri.Unknown ? t : _ctx.Options.IsIltLikeWorld ? IltTri.On : IltTri.Unknown;
}
/// <summary>An essence outside the WCID table (a new family) that the server gave a breeding block.</summary>
private static bool LooksLikeEssence(WorldObject wo, IltInventory inv)
=> wo.Name.EndsWith("Essence", StringComparison.OrdinalIgnoreCase)
&& inv.Str(wo, StrLongDesc).Contains("Sex:", StringComparison.Ordinal);
private static BreedEssenceFacts ReadFacts(RynthCoreHost host, IltInventory inv, WorldObject wo, uint wcid)
{
uint id = unchecked((uint)wo.Id);
var f = new BreedEssenceFacts
{
Id = wo.Id,
Name = wo.Name,
Wcid = wcid,
HasId = inv.HasAppraisal(wo),
Bond = inv.Int(wo, IntBondLevel),
PotencyStored = inv.Int(wo, IntPotencyStored),
MutDamage = inv.Int(wo, IntMutDamage),
MutDamageResist = inv.Int(wo, IntMutDamageResist),
MutCrit = inv.Int(wo, IntMutCrit),
MutVitality = inv.Int(wo, IntMutVitality),
MutPotency = inv.Int(wo, IntMutPotency),
MutationCount = inv.Int(wo, IntMutationCount),
Neutered = TryBool(host, id, BoolNeutered, out bool n) && n,
JuvenileFlag = TryBool(host, id, BoolJuvenile, out bool j) && j,
Catalyst = TryBool(host, id, BoolCatalyst, out bool c) && c,
Offering = TryBool(host, id, BoolOffering, out bool o) && o,
Attuned = TryBool(host, id, BoolBondAttuned, out bool a) && a,
NextBreedUnix = TryDouble(host, id, FloatNextBreeding),
MaleRefreshUnix = TryDouble(host, id, FloatMaleRefresh),
Incense = TryDouble(host, id, FloatIncense),
MaturityXpMult = TryDouble(host, id, FloatMaturityXpMult),
LongDesc = inv.Str(wo, StrLongDesc),
};
f.UseLevel = inv.Int(wo, IntUseRequiresLevel);
if (f.UseLevel <= 0) f.UseLevel = inv.Int(wo, IntUseLevelRequirement);
if (TryBool(host, id, BoolMaleOverride, out bool male)) f.MaleOverride = male;
// Absent and 0 differ for these two: absent = never bred / a full stud.
f.MaturityKills = TryInt(host, id, IntMaturityKills, out int kills) ? kills : -1;
f.MaleCharges = TryInt(host, id, IntMaleCharges, out int charges) ? charges : -1;
return f;
}
private static bool TryBool(RynthCoreHost host, uint id, uint stype, out bool v)
{
v = false;
return host.HasGetObjectBoolProperty && host.TryGetObjectBoolProperty(id, stype, out v);
}
private static bool TryInt(RynthCoreHost host, uint id, uint stype, out int v)
{
v = 0;
return host.HasGetObjectIntProperty && host.TryGetObjectIntProperty(id, stype, out v);
}
private static double TryDouble(RynthCoreHost host, uint id, uint stype)
=> host.HasGetObjectDoubleProperty && host.TryGetObjectDoubleProperty(id, stype, out double v) ? v : 0;
// ── Actions (pump) ──────────────────────────────────────────────────────
/// <summary>Re-appraises every essence and rescans.</summary>
public void RefreshAll()
{
_refreshAll = true;
_scannedAt = 0;
MarkWatched();
}
/// <summary>Runs "@breed-debug" quietly and keeps its reply (the room check, partners nearby).</summary>
public void RequestDebug()
{
if (_ctx.Capture.IsPending(DebugCommand)) return;
_message = "Asking the server for breeding diagnostics...";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = DebugCommand,
IsResponseLine = IltBreedingRules.IsDebugLine,
IsTerminator = IltBreedingRules.IsDebugEnd,
IdleEndMs = 1500,
FirstLineTimeoutMs = 8000,
Eat = true,
OnComplete = ApplyDebug,
});
_scannedAt = 0;
}
private void ApplyDebug(IltChatResult r)
{
if (r.UnknownCommand) { _message = "This server has no @breed-debug (no pet breeding here)."; _ctx.Options.Set(BitBreeding, IltTri.Off); return; }
if (r.NotSent) { _message = "This RynthCore can't send chat commands."; return; }
if (r.Lines.Count == 0) { _message = "No reply to @breed-debug."; return; }
DateTime utc = DateTime.UtcNow;
IltBreedingState st = _rules.State;
st.LastDebug = new List<string>(r.Lines);
st.LastDebugUtc = utc;
foreach (string l in r.Lines) _rules.LearnAll(IltBreedingRules.FromChat(l), utc);
BreedDebugInfo d = IltBreedingRules.ParseDebug(r.Lines);
if (d.Enabled.HasValue) _ctx.Options.Set(BitBreeding, d.Enabled.Value ? IltTri.On : IltTri.Off);
_message = d.Enabled == false ? "The server says breeding is switched off."
: d.LocationOk == true ? $"You're in the breeding room. Partners nearby: {Math.Max(0, d.Partners)}."
: d.LocationOk == false ? $"Not in the breeding room ({_rules.RoomText()})."
: "Diagnostics read.";
_rules.AddEvent("debug", _message, utc);
_scannedAt = 0;
}
/// <summary>Starts the courtship dance ("@dance"); the breed happens when a partner dances in time.</summary>
public void Dance()
{
if (!_ctx.Host.HasInvokeChatParser) { _message = "This RynthCore can't send chat commands."; return; }
_ctx.Host.InvokeChatParser(DanceCommand);
_message = $"Danced. Your partner must *dance* within {_rules.Get(IltBreedingRules.DanceWindow):0.#}s with their pet in the same room.";
_scannedAt = 0;
}
/// <summary>
/// Uses a supply on a carried essence, re-checking both are still here and that the server would
/// take it. Returns a message for the UI. Called after the player confirmed.
/// </summary>
public string ApplySupply(string key, int essenceId)
{
BreedSupplyDef? def = IltBreedingSupplies.Find(key);
if (def == null || !def.Apply) return _message = "That supply isn't applied from here.";
IltInventory inv = _ctx.Inventory;
WorldObject? item = inv.FindByWcid(def.Wcid);
if (item == null) return _message = $"No {def.Name} in your pack.";
BreedEssence? e = _snap.Essences.FirstOrDefault(x => x.Id == essenceId);
if (e == null || !inv.Items().Any(wo => wo.Id == essenceId)) return _message = "That essence isn't in your pack any more.";
string? refuse = IltBreedingSupplies.RefuseReason(def, e, _rules);
if (refuse != null) return _message = refuse;
if (inv.IsBusy) return _message = "You're busy; try again in a moment.";
bool sent = inv.UseOn(item, unchecked((uint)essenceId));
_message = sent ? $"Used {def.Name} on {e.Name}." : $"Couldn't use {def.Name} (the engine refused).";
if (sent) _rules.AddEvent("supply", _message, DateTime.UtcNow);
RefreshAll();
return _message;
}
/// <summary>
/// A reader's verb line ("RynthILT.Data" PetBreedingCommand): refresh, debug, dance,
/// or "apply &lt;supplyKey&gt; &lt;essenceId&gt;" (the reader confirmed it with the player). Pump thread.
/// </summary>
public void RunVerb(string line)
{
string[] parts = (line ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0) return;
switch (parts[0].ToLowerInvariant())
{
case "refresh": RefreshAll(); break;
case "debug": RequestDebug(); break;
case "dance": Dance(); break;
case "apply" when parts.Length == 3 && int.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int id):
ApplySupply(parts[1], id);
break;
default:
RynthLog.Trace(LogCat.IltPets, $"breeding: unknown reader verb '{line}'");
break;
}
}
// ── Reader JSON ─────────────────────────────────────────────────────────
/// <summary>The reader JSON (Plugins/Shared/RynthIltDataApi.cs header has the shape).</summary>
internal static string BuildJson(BreedingSnapshot s, IltBreedingRules r, string world)
{
var sb = new StringBuilder(4096);
sb.Append("{\"available\":true");
Str(sb, "world", world);
Str(sb, "enabled", TriText(s.Enabled));
Str(sb, "maturity", TriText(s.Maturity));
Str(sb, "bond", TriText(s.Bond));
Str(sb, "room", s.Room);
sb.Append(",\"freeSlots\":").Append(s.FreeSlots);
Str(sb, "message", s.Message);
sb.Append(",\"essences\":[");
for (int i = 0; i < s.Essences.Count; i++)
{
BreedEssence e = s.Essences[i];
if (i > 0) sb.Append(',');
sb.Append("{\"id\":").Append(e.Id);
Str(sb, "name", e.Name);
Str(sb, "sex", e.Male ? "M" : "F");
sb.Append(",\"tier\":").Append(e.Tier).Append(",\"bond\":").Append(e.Bond);
sb.Append(",\"ready\":").Append(e.Ready ? "true" : "false");
Str(sb, "status", e.Status);
double readyIn = e.ReadyAtUnix > s.NowUnix ? e.ReadyAtUnix - s.NowUnix : 0;
sb.Append(",\"readyIn\":").Append((long)Math.Ceiling(readyIn));
sb.Append(",\"charges\":").Append(e.Charges).Append(",\"chargesMax\":").Append(e.ChargesMax);
sb.Append(",\"juvenile\":").Append(e.Juvenile ? "true" : "false");
Str(sb, "stage", e.StageName);
sb.Append(",\"kills\":").Append(e.Kills).Append(",\"killsRequired\":").Append(e.KillsRequired);
sb.Append(",\"mutations\":").Append(e.StatMutations).Append(",\"potencyMutations\":").Append(e.MutP);
Arr(sb, "problems", e.Problems);
Arr(sb, "boosters", e.Boosters);
sb.Append('}');
}
sb.Append(']');
// Ready pairings, best odds first (the fewest inherited mutations keeps the decay low).
var studs = s.Essences.Where(e => e.Male && e.Ready).ToList();
var dams = s.Essences.Where(e => !e.Male && e.Ready).ToList();
var pairs = new List<(BreedEssence Stud, BreedEssence Dam, BreedPairPlan Plan)>();
foreach (BreedEssence st in studs)
foreach (BreedEssence d in dams)
pairs.Add((st, d, IltBreedingPlanner.Plan(st, d, r)));
pairs.Sort((a, b) => b.Plan.ChanceBest.CompareTo(a.Plan.ChanceBest));
sb.Append(",\"pairs\":[");
for (int i = 0; i < pairs.Count && i < 6; i++)
{
if (i > 0) sb.Append(',');
sb.Append('{');
Str(sb, "stud", pairs[i].Stud.Name, first: true);
Str(sb, "dam", pairs[i].Dam.Name);
sb.Append(",\"chanceBest\":").Append(pairs[i].Plan.ChanceBest.ToString("0.####", CultureInfo.InvariantCulture));
sb.Append(",\"chanceWorst\":").Append(pairs[i].Plan.ChanceWorst.ToString("0.####", CultureInfo.InvariantCulture));
sb.Append(",\"inheritMin\":").Append(pairs[i].Plan.InheritMin).Append(",\"inheritMax\":").Append(pairs[i].Plan.InheritMax);
sb.Append('}');
}
sb.Append(']');
sb.Append(",\"supplies\":[");
for (int i = 0; i < s.Supplies.Count; i++)
{
(BreedSupplyDef def, long count) = s.Supplies[i];
if (i > 0) sb.Append(',');
sb.Append('{');
Str(sb, "key", def.Key, first: true);
Str(sb, "name", def.Name);
Str(sb, "effect", def.Effect);
sb.Append(",\"count\":").Append(count).Append(",\"price\":").Append(def.Price);
sb.Append(",\"apply\":").Append(def.Apply ? "true" : "false");
// Essences the server would take this on now (the reader's Use buttons).
var targets = def.Apply && count > 0
? s.Essences.Where(e => IltBreedingSupplies.RefuseReason(def, e, r) == null).Select(e => e.Id).ToList()
: new List<int>();
sb.Append(",\"targets\":[").Append(string.Join(',', targets)).Append(']');
sb.Append('}');
}
sb.Append(']');
sb.Append(",\"rules\":[");
for (int i = 0; i < s.Rules.Count; i++)
{
BreedRuleValue v = s.Rules[i];
if (i > 0) sb.Append(',');
sb.Append('{');
Str(sb, "label", v.Def.Label, first: true);
Str(sb, "value", IltBreedingRules.Format(v));
Str(sb, "source", IltBreedingRules.SourceText(v.Source));
Str(sb, "help", v.Def.Help);
sb.Append('}');
}
sb.Append(']');
sb.Append(",\"events\":[");
int start = Math.Max(0, s.Events.Count - 20);
for (int i = s.Events.Count - 1; i >= start; i--)
{
IltBreedingEvent e = s.Events[i];
if (i != s.Events.Count - 1) sb.Append(',');
sb.Append('{');
Str(sb, "when", e.Utc.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture), first: true);
Str(sb, "kind", e.Kind);
Str(sb, "text", e.Text);
sb.Append('}');
}
sb.Append(']');
if (s.Debug != null)
{
BreedDebugInfo d = s.Debug;
sb.Append(",\"debug\":{");
Str(sb, "when", s.DebugUtc.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture), first: true);
Str(sb, "enabled", d.Enabled == null ? "unknown" : d.Enabled.Value ? "on" : "off");
Str(sb, "location", d.Location);
Str(sb, "match", d.LocationOk == null ? "" : d.LocationOk.Value ? "valid" : "invalid");
Str(sb, "pet", d.ActivePet);
Str(sb, "sex", d.PetSex);
sb.Append(",\"partners\":").Append(d.Partners);
sb.Append('}');
}
sb.Append('}');
return sb.ToString();
}
private static string TriText(IltTri t) => t switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" };
private static void Str(StringBuilder sb, string name, string? value, bool first = false)
{
if (!first) sb.Append(',');
sb.Append('"').Append(name).Append("\":\"").Append(IltStyle.JsonEscape(value ?? string.Empty)).Append('"');
}
private static void Arr(StringBuilder sb, string name, IReadOnlyList<string> values)
{
sb.Append(",\"").Append(name).Append("\":[");
for (int i = 0; i < values.Count; i++)
{
if (i > 0) sb.Append(',');
sb.Append('"').Append(IltStyle.JsonEscape(values[i])).Append('"');
}
sb.Append(']');
}
// ── UI (render thread): Mini Remote > Pets > Breeding ───────────────────
/// <summary>The Breeding tab's body (RynthIltHub.SectionPetBreeding).</summary>
public void RenderSection()
{
MarkWatched();
BreedingSnapshot s = _snap;
RenderHeader(s);
if (!s.Built)
{
ImGui.TextDisabled("Reading your essences...");
return;
}
ImGui.Separator();
RenderEssences(s);
RenderPlanner(s);
RenderSupplies(s);
RenderRules(s);
RenderEvents(s);
RenderGuide(s);
}
private void RenderHeader(BreedingSnapshot s)
{
Vector4 col = s.Enabled == IltTri.Off ? IltStyle.ColHp : IltStyle.ColTeal;
SafeImGui.TextColored(col, s.Enabled switch
{
IltTri.Off => "Pet breeding is off on this server.",
IltTri.On => $"Pet breeding: on. Breeding room: {s.Room}.",
_ => "Pet breeding: not confirmed yet (run Diagnostics in the breeding room).",
});
if (s.Bond == IltTri.Off) SafeImGui.TextColored(IltStyle.ColAmber, "Pet bond is off here, so bond can't reach the breeding minimum.");
if (ImGui.SmallButton("Refresh##brrefresh")) _ctx.Post(RefreshAll);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Re-appraise every essence (charges, rest timers, bond, growth).");
ImGui.SameLine();
if (ImGui.SmallButton("Diagnostics##brdebug")) _ctx.Post(RequestDebug);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("@breed-debug: are you in the breeding room, your summoned pet, partners nearby (reply hidden, shown here).");
ImGui.SameLine();
if (ImGui.SmallButton("Dance##brdance"))
_ctx.Confirm("Courtship dance",
"Dance now? If your partner dances within the window with both pets summoned in the same room, the breed happens:" +
" the stud spends a charge, the dam rests, incense is used up and the baby goes to the dam's owner.",
Dance, "Dance");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("@dance (the same as typing *dance*). Both owners must dance within the window.");
if (s.Message.Length > 0) SafeImGui.TextDisabled(s.Message);
if (s.FreeSlots == 0) SafeImGui.TextColored(IltStyle.ColAmber, "Your main pack is full: as the dam's owner you couldn't receive the baby.");
}
private void RenderEssences(BreedingSnapshot s)
{
int ready = s.Essences.Count(e => e.Ready);
if (!ImGui.CollapsingHeader($"Essences ({ready} ready of {s.Essences.Count})###bress", ImGuiTreeNodeFlags.DefaultOpen)) return;
if (s.Essences.Count == 0)
{
ImGui.TextDisabled("No combat pet essences in your pack.");
return;
}
const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.ScrollY;
float h = Math.Min(260f, 26f + s.Essences.Count * ImGui.GetTextLineHeightWithSpacing());
if (!ImGui.BeginTable("##brtable", 6, flags, new Vector2(0, h))) return;
ImGui.TableSetupScrollFreeze(0, 1);
ImGui.TableSetupColumn("Essence", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Sex", ImGuiTableColumnFlags.WidthFixed, 34);
ImGui.TableSetupColumn("Tier", ImGuiTableColumnFlags.WidthFixed, 34);
ImGui.TableSetupColumn("Bond", ImGuiTableColumnFlags.WidthFixed, 38);
ImGui.TableSetupColumn("Breeding", ImGuiTableColumnFlags.WidthFixed, 130);
ImGui.TableSetupColumn("Muts", ImGuiTableColumnFlags.WidthFixed, 40);
ImGui.TableHeadersRow();
for (int i = 0; i < s.Essences.Count; i++)
{
BreedEssence e = s.Essences[i];
ImGui.PushID(i);
ImGui.TableNextRow();
ImGui.TableNextColumn();
bool picked = e.Id == _studId || e.Id == _damId;
if (ImGui.Selectable(SafeText(e.Name) + "##sel", picked, ImGuiSelectableFlags.SpanAllColumns))
{
if (e.Male) _studId = e.Id; else _damId = e.Id;
_targetId = e.Id;
}
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(Tooltip(e));
ImGui.TableNextColumn();
ImGui.TextUnformatted(e.Male ? "M" : "F");
ImGui.TableNextColumn();
ImGui.TextUnformatted(e.Tier > 0 ? e.Tier.ToString(CultureInfo.InvariantCulture) : "?");
ImGui.TableNextColumn();
ImGui.TextUnformatted(e.HasId ? e.Bond.ToString(CultureInfo.InvariantCulture) : "?");
ImGui.TableNextColumn();
Vector4 col = e.Ready ? IltStyle.ColGreen
: e.Gate is BreedGate.Resting or BreedGate.NoCharges or BreedGate.Growing or BreedGate.NeedsId ? IltStyle.ColAmber
: IltStyle.ColTextMute;
SafeImGui.TextColored(col, e.Status);
ImGui.TableNextColumn();
ImGui.TextUnformatted(e.MutP > 0 ? $"{e.StatMutations}+{e.MutP}p" : e.StatMutations.ToString(CultureInfo.InvariantCulture));
ImGui.PopID();
}
ImGui.EndTable();
ImGui.TextDisabled("Click a male to pick the stud, a female for the dam (and the supply target). Hover for details.");
}
private static string Tooltip(BreedEssence e)
{
var sb = new StringBuilder();
sb.Append(e.Name).Append('\n').Append(e.Role).Append(", tier ").Append(e.Tier > 0 ? e.Tier.ToString(CultureInfo.InvariantCulture) : "?")
.Append(", bond ").Append(e.Bond);
if (e.Male) sb.Append("\nCharges ").Append(e.Charges).Append('/').Append(e.ChargesMax);
if (e.Bred) sb.Append(e.Juvenile ? $"\nGrowing: {e.StageName}, {e.KillsToNext} kills to the next stage, {Math.Max(0, e.KillsRequired - e.Kills)} to Adult" : "\nBred: Adult");
if (e.Unbound) sb.Append("\nUnbound: imprints on the first character to summon it.");
sb.Append($"\nMutations: damage {e.MutD}, damage resist {e.MutDR}, crit {e.MutC}, vitality {e.MutV}, potency {e.MutP}");
if (e.Boosters.Count > 0) sb.Append("\nBoosters: ").Append(string.Join(", ", e.Boosters));
foreach (string p in e.Problems) sb.Append("\n- ").Append(p);
return sb.ToString();
}
private void RenderPlanner(BreedingSnapshot s)
{
if (!ImGui.CollapsingHeader("Pair planner###brplan")) return;
BreedEssence? stud = s.Essences.FirstOrDefault(e => e.Id == _studId && e.Male);
BreedEssence? dam = s.Essences.FirstOrDefault(e => e.Id == _damId && !e.Male);
PickCombo("Stud##brstud", s.Essences.Where(e => e.Male).ToList(), stud, id => _studId = id);
PickCombo("Dam##brdam", s.Essences.Where(e => !e.Male).ToList(), dam, id => _damId = id);
if (stud == null || dam == null)
{
ImGui.TextDisabled("Pick a stud and a dam (yours, or an alt's carried here) to see the odds.");
ImGui.TextDisabled("Breeding needs two owners: each dances with their own summoned pet.");
return;
}
BreedPairPlan p = IltBreedingPlanner.Plan(stud, dam, s.RulesView);
if (p.CanBreed) SafeImGui.TextColored(IltStyle.ColGreen, "Both are ready to breed.");
foreach (string b in p.Blockers) SafeImGui.TextColored(IltStyle.ColAmber, b);
SafeImGui.Text($"Stat mutation chance: {Pct(p.ChanceWorst)} to {Pct(p.ChanceBest)} (baby inherits {p.InheritMin}-{p.InheritMax} stat mutations)");
SafeImGui.Text($"Potency mutation chance: {Pct(p.PotencyChance)}" + (p.Incense > 0 ? $"; incense +{p.Incense * 100:0.#}%" : ""));
foreach (string n in p.Notes) SafeImGui.BulletText(n);
}
private static void PickCombo(string label, List<BreedEssence> list, BreedEssence? current, Action<int> set)
{
ImGui.SetNextItemWidth(260);
if (!ImGui.BeginCombo(label, current != null ? SafeText(current.Name) : "(none)")) return;
foreach (BreedEssence e in list)
{
if (ImGui.Selectable($"{SafeText(e.Name)} - {SafeText(e.Status)}##{e.Id}", current != null && current.Id == e.Id)) set(e.Id);
}
ImGui.EndCombo();
}
private void RenderSupplies(BreedingSnapshot s)
{
long carried = s.Supplies.Sum(x => x.Count);
if (!ImGui.CollapsingHeader($"Supplies ({carried} carried)###brsup")) return;
BreedEssence? target = s.Essences.FirstOrDefault(e => e.Id == _targetId);
PickCombo("Use on##brtarget", s.Essences.ToList(), target, id => _targetId = id);
ImGui.TextDisabled("Ivo sells these at the Seedy Motel. Boosters are spent by the essence's next breed.");
for (int i = 0; i < s.Supplies.Count; i++)
{
(BreedSupplyDef def, long count) = s.Supplies[i];
ImGui.PushID("sup" + i);
Vector4 col = count > 0 ? IltStyle.ColGreen : IltStyle.ColTextMute;
SafeImGui.TextColored(col, $"{count,3} {def.Name}");
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"{def.Effect}\nIvo's price: {IltBreedingSupplies.PriceText(def.Price)} pyreals");
if (def.Apply && count > 0 && target != null)
{
ImGui.SameLine(300);
string? refuse = IltBreedingSupplies.RefuseReason(def, target, s.RulesView);
if (refuse != null)
{
ImGui.TextDisabled("can't");
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(refuse);
}
else if (ImGui.SmallButton("Use"))
{
string key = def.Key;
int id = target.Id;
_ctx.Confirm("Use " + def.Name,
$"Use {def.Name} on {target.Name}? {def.Effect}{IltBreedingSupplies.Warning(def, target)}",
() => ApplySupply(key, id), "Use");
}
}
ImGui.PopID();
}
}
private void RenderRules(BreedingSnapshot s)
{
if (!ImGui.CollapsingHeader("Server rules###brrules")) return;
ImGui.TextDisabled("Values this server showed win over the ILT profile, which wins over ACE's defaults.");
foreach (BreedRuleValue v in s.Rules)
{
SafeImGui.Text(v.Def.Label);
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(v.Def.Help);
ImGui.SameLine(200);
SafeImGui.Text(IltBreedingRules.Format(v));
ImGui.SameLine(280);
SafeImGui.TextColored(v.Source == BreedRuleSource.Server ? IltStyle.ColGreen : IltStyle.ColTextMute,
IltBreedingRules.SourceText(v.Source));
}
if (s.Debug != null)
{
ImGui.Separator();
SafeImGui.TextDisabled($"Last diagnostics ({s.DebugUtc.ToLocalTime():g}):");
BreedDebugInfo d = s.Debug;
if (d.Location.Length > 0) SafeImGui.BulletText("You: " + d.Location);
if (d.LocationOk.HasValue) SafeImGui.BulletText(d.LocationOk.Value ? "In the breeding room" : "Not in the breeding room");
if (d.ActivePet.Length > 0) SafeImGui.BulletText("Pet: " + d.ActivePet + (d.PetSex.Length > 0 ? " (" + d.PetSex + ")" : ""));
if (d.Partners >= 0) SafeImGui.BulletText($"Partners nearby: {d.Partners}");
}
}
private static void RenderEvents(BreedingSnapshot s)
{
if (!ImGui.CollapsingHeader($"Recent events ({s.Events.Count})###brevents")) return;
if (s.Events.Count == 0) ImGui.TextDisabled("Nothing yet: rituals, births, growth and charges land here.");
for (int i = s.Events.Count - 1, shown = 0; i >= 0 && shown < 20; i--, shown++)
{
IltBreedingEvent e = s.Events[i];
SafeImGui.TextDisabled(e.Utc.ToLocalTime().ToString("MM-dd HH:mm", CultureInfo.InvariantCulture));
ImGui.SameLine(90);
SafeImGui.TextWrapped(e.Text);
}
}
private static void RenderGuide(BreedingSnapshot s)
{
if (!ImGui.CollapsingHeader("How to breed###brguide")) return;
SafeImGui.BulletText($"Go to the Seedy Motel (portal by Prof. Ruggan in Lin, 54.7S 73.5E); breeding room {s.Room}.");
SafeImGui.BulletText("Two owners: one summons a male (stud), the other a female (dam). Both pets in the same room.");
SafeImGui.BulletText("Both parents: tier 100+, bond 100+, adult, not shiny, not neutered. The stud needs a charge, the dam must have rested.");
SafeImGui.BulletText("Both owners *dance* (or @dance) within a few seconds. The baby goes to the dam's owner (free pack slot needed).");
SafeImGui.BulletText("A mating guardian may rise: both parents kill it in time for an Awakened Blessing mutation.");
SafeImGui.BulletText("The baby imprints on whoever summons it first, and grows up with kills (Nurturing Draught doubles the credit).");
}
private static string Pct(double v) => (v * 100).ToString("0.##", CultureInfo.InvariantCulture) + "%";
/// <summary>Item names go into ImGui labels, where "##" would start the hidden id.</summary>
private static string SafeText(string s) => (s ?? string.Empty).Replace("#", "");
}

View file

@ -0,0 +1,166 @@
// IltPetCaptureRules.cs — ACECustom MonsterCapture thresholds for siphon lenses (pure; no host).
// Moved from RynthAi's Pets tab (MiniRemote/PetCaptureRules.cs) 2026-10-20 with the auto-capture
// itself (IltPetAutomation): monster capture is ACECustom's, so it is RynthILT's.
//
// Copied from ACECustom Source/ACE.Server/Entity/MonsterCapture.cs so the client can tell when
// a creature is weak enough to siphon before using a lens. Keep these numbers in lockstep with
// the server: CaptureMaxHealthFraction / CaptureMaxHealthPoints / CaptureRangeM and the lens
// WCID table in PetGuideController.
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One siphon lens the Pets tab can auto-use (name, WCID, whether health is gated).</summary>
internal readonly struct PetCaptureLens
{
public PetCaptureLens(string name, uint wcid, bool bypassesHealthGate)
{
Name = name;
Wcid = wcid;
BypassesHealthGate = bypassesHealthGate;
}
public string Name { get; }
public uint Wcid { get; }
/// <summary>Asheron's (and Debug) lenses skip the 20% / 20 HP gate.</summary>
public bool BypassesHealthGate { get; }
}
/// <summary>
/// When a siphon lens can be used, matching ACECustom MonsterCapture.UseCaptureCrystal.
/// A creature is weak enough when its health fraction is ≤ 20% OR its current HP is under 20
/// (whichever comes first). Asheron's Lens skips that check.
/// </summary>
internal static class PetCaptureRules
{
/// <summary>A lens targets the nearest attackable creature within this many meters.</summary>
public const float CaptureRangeM = 5.0f;
/// <summary>Siphon once at or below this fraction of max health…</summary>
public const float CaptureMaxHealthFraction = 0.20f;
/// <summary>…or below this many hit points (the gate is OR with the fraction).</summary>
public const int CaptureMaxHealthPoints = 20;
/// <summary>
/// Lenses the player can pick for auto-capture. Order is the combo index.
/// Resonance needs a prior failed capture (server-side); Asheron's bypasses the health gate.
/// </summary>
public static readonly PetCaptureLens[] Lenses =
{
new("Flawed Siphon Lens", 78780001, bypassesHealthGate: false),
new("Pristine Siphon Lens", 78780002, bypassesHealthGate: false),
new("Perfect Siphon Lens", 78780003, bypassesHealthGate: false),
new("Resonance Lens", 78780010, bypassesHealthGate: false),
new("Asheron's Lens", 78780012, bypassesHealthGate: true),
};
/// <summary>Combo labels for the Pets tab (same order as <see cref="Lenses"/>).</summary>
public static readonly string[] LensNames =
{
"Flawed", "Pristine", "Perfect", "Resonance", "Asheron's",
};
public static PetCaptureLens LensAt(int index)
{
int i = Math.Clamp(index, 0, Lenses.Length - 1);
return Lenses[i];
}
/// <summary>
/// True when ACECustom would accept a siphon on this creature for a normal (non-bypass) lens.
/// Pass current/max when known; when only a 0–1 ratio is known, pass ratio as current and 1 as max
/// (then only the fraction half of the gate can fire).
/// </summary>
public static bool IsWeakEnough(uint currentHp, uint maxHp)
{
if (currentHp == 0) return false; // dead — server refuses
if (maxHp == 0) return false;
float pct = (float)currentHp / maxHp;
// Server: refuse when pct > 0.20 AND current >= 20. Allowed otherwise.
return pct <= CaptureMaxHealthFraction || currentHp < CaptureMaxHealthPoints;
}
/// <summary>Same gate from a 0–1 health ratio only (no absolute HP). Dead / unknown = false.</summary>
public static bool IsWeakEnoughRatio(float healthRatio)
{
if (healthRatio <= 0f || healthRatio > 1f) return false;
return healthRatio <= CaptureMaxHealthFraction;
}
/// <summary>True when this lens may be used given the creature's vitals (bypass lenses always, if alive).</summary>
public static bool CanAttempt(PetCaptureLens lens, uint currentHp, uint maxHp)
{
if (currentHp == 0) return false;
if (lens.BypassesHealthGate) return maxHp == 0 || currentHp > 0;
return IsWeakEnough(currentHp, maxHp);
}
/// <summary>Distance gate: ACECustom CaptureRangeM.</summary>
public static bool InRange(double distanceM) => distanceM >= 0 && distanceM <= CaptureRangeM;
}
/// <summary>
/// A brake on the auto-capture loop. Auto-capture fires a lens every couple of seconds and only stops
/// on reply strings it guesses at, so an unrecognized reply (or a creature the server never lets go of)
/// would burn lenses without end. This caps consecutive tries per target and, as a backstop, consecutive
/// tries over all targets; both reset on a recognized success. Pure: the tests drive it.
/// </summary>
internal sealed class PetCaptureThrottle
{
/// <summary>Lens uses on one creature, with no success in between, before it is left alone.</summary>
public const int MaxTriesPerTarget = 5;
/// <summary>How long a creature that used up its tries is left alone (ms).</summary>
public const long TargetBlockMs = 120_000;
/// <summary>Lens uses over all creatures with no success before auto-capture switches itself off.</summary>
public const int MaxTriesWithoutSuccess = 15;
private readonly Dictionary<int, int> _tries = new();
private readonly Dictionary<int, long> _blockedUntil = new();
private int _sinceSuccess;
/// <summary>Consecutive lens uses with no recognized success (all targets).</summary>
public int TriesWithoutSuccess => _sinceSuccess;
/// <summary>True when the backstop was hit: the caller should switch auto-capture off.</summary>
public bool Exhausted => _sinceSuccess >= MaxTriesWithoutSuccess;
/// <summary>False while this target is blocked (it used its tries) or the backstop is hit.</summary>
public bool MayAttempt(int targetId, long nowMs)
{
if (Exhausted) return false;
if (_blockedUntil.TryGetValue(targetId, out long until))
{
if (nowMs < until) return false;
_blockedUntil.Remove(targetId); // block served: a fresh set of tries
_tries.Remove(targetId);
}
return true;
}
/// <summary>Seconds left on this target's block, 0 when it is not blocked.</summary>
public long BlockedSecondsLeft(int targetId, long nowMs)
=> _blockedUntil.TryGetValue(targetId, out long until) && nowMs < until ? (until - nowMs + 999) / 1000 : 0;
/// <summary>Count a lens use on this target; blocks it once it reaches <see cref="MaxTriesPerTarget"/>.</summary>
public void RecordAttempt(int targetId, long nowMs)
{
_sinceSuccess++;
int n = _tries.TryGetValue(targetId, out int t) ? t + 1 : 1;
_tries[targetId] = n;
if (n >= MaxTriesPerTarget) _blockedUntil[targetId] = nowMs + TargetBlockMs;
}
/// <summary>A recognized success reply: everything starts over.</summary>
public void RecordSuccess() => Reset();
public void Reset()
{
_tries.Clear();
_blockedUntil.Clear();
_sinceSuccess = 0;
}
}

View file

@ -0,0 +1,87 @@
// IltPetLogs.cs — The ACECustom /pets and /shinies logs, shown in RynthAi's universal Pets tab
// (RynthILT.Hub section "pets-logs").
// Originally the roster-capture part of SilentKelpie's IltPets (ILT Hub, RynthAi); split out and
// moved to RynthILT 2026-10-13. The Pets tab itself (essence roster, combat / healing / cosmetic
// pets) stayed in RynthAi (MiniRemote/PetsTab.cs): summoning is every server's, these two commands
// are ACECustom's (as are the pet charms, the refill path and siphon capture: IltPetAutomation,
// moved 2026-10-20).
using System;
using System.Collections.Generic;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltPetLogs : IIltFeature
{
private readonly IltHubContext _ctx;
public IltPetLogs(IltHubContext ctx) => _ctx = ctx;
private IltPetState S => _ctx.State.Pet;
/// <summary>Captures /pets or /shinies into the state (quiet).</summary>
public void RequestRoster(bool shinies)
{
RynthLog.Trace(LogCat.IltPets, $"RequestRoster(shinies={shinies})");
string cmd = shinies ? "/shinies" : "/pets";
if (_ctx.Capture.IsPending(cmd)) return;
string header = shinies ? "Your Shiny Log" : "Your Pet Log";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = cmd,
IsResponseLine = t => t.Contains(header, StringComparison.OrdinalIgnoreCase) || IltParse.RosterLine.IsMatch(t),
IsTerminator = t => t.Contains(header + " is empty", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 1500,
FirstLineTimeoutMs = 10000,
Eat = true,
OnComplete = r =>
{
if (r.UnknownCommand) { _ctx.Options.Set(shinies ? IltFeature.Shinies : IltFeature.Pets, IltTri.Off); return; }
if (r.Lines.Count == 0) return;
_ctx.Options.Set(shinies ? IltFeature.Shinies : IltFeature.Pets, IltTri.On);
ApplyRoster(shinies, r.Lines);
},
});
}
/// <summary>Also used by the login probe tap so the roster fills without a second command.</summary>
public void ApplyRoster(bool shinies, List<string> lines)
{
RynthLog.Trace(LogCat.IltPets, $"ApplyRoster(shinies={shinies}, lines={lines.Count})");
var list = new List<string>();
foreach (string l in lines)
{
var m = IltParse.RosterLine.Match(l);
if (m.Success) list.Add(m.Groups[2].Value.Trim());
}
if (shinies) S.ShinyLog = list; else S.PetLog = list;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs) { }
public bool OnChat(string text) => false;
public void OnLogout() { }
// ── UI (render thread): the Pets tab's last section ─────────────────────
public void RenderSection()
{
ImGui.Separator();
RenderRoster("Pet log", false, IltFeature.Pets, S.PetLog);
RenderRoster("Shiny log", true, IltFeature.Shinies, S.ShinyLog);
}
private void RenderRoster(string label, bool shinies, string key, List<string> list)
{
if (_ctx.Options.IsOff(key)) return;
var snap = list.ToArray();
if (ImGui.TreeNode($"{label} ({snap.Length})##{key}"))
{
if (ImGui.SmallButton($"Refresh##{key}")) _ctx.Post(() => RequestRoster(shinies));
foreach (string s in snap) SafeImGui.BulletText(s);
ImGui.TreePop();
}
}
}

View file

@ -0,0 +1,882 @@
// IltProgression.cs — Augmentation and Enlightenment planners, drawn by the engine's
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
// Skills panel (Progression tab) from AppendSnapshotJson; edits arrive via HandleRemote.
//
// Augs : "/aug" levels + the per-server cost rules in IltAugCosts (UB's ILT model by default:
// level i costs base + (i-1)*(base*LP/100), times 1/4/8/16/24 from S1..S4), coins per level.
// Enl : tier material/luminance table, requirement checklist, "/enl" on confirm. The
// server pops its own Yes/No dialog — the host cannot (and must not) click it.
// Optional auto-enlighten is disarmed every session and needs a hard confirm.
// XP : the Skills panel plans attribute/vital raises from the client's exact XP tables;
// this module spends unassigned XP ("/attr") before an auto-enlighten, and owns the
// infinite-attribute raiser (IltAttributeRaiser: server costs from "/xp all", manual
// or timed raises in a chosen order) drawn in the same tab.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltProgression : IIltFeature
{
// ── Augmentation cost rules ─────────────────────────────────────────────
/// <summary>Per-server aug cost rules (UB's ILT model unless this world was changed).</summary>
public IltAugCosts AugCosts { get; } = new();
/// <summary>The rules for the world we're on.</summary>
private IltAugCostProfile AugProfile => AugCosts.For(_ctx.Options.WorldName);
// ── Enlightenment ───────────────────────────────────────────────────────
private const int BaseLevelForEnl = 275;
private const long AutoEnlCooldownMs = 60_000;
private const uint SpellVitae = 666;
/// <summary>Materials for reaching enlightenment level <paramref name="t"/> (one step).</summary>
public static (string Item, uint Wcid, int Count, decimal Lum) EnlStepCost(int t)
{
if (t <= 5) return ("none", 0, 0, 0);
int count = t - 5;
if (t <= 50) return ("Enlightenment Tokens", IltInventory.WcidEnlToken, count, 0);
if (t <= 150) return ("Enlightenment Tokens", IltInventory.WcidEnlToken, count, t * 100_000_000m);
if (t <= 300) return ("Enlightenment Medallions", IltInventory.WcidEnlMedallion, count, t * 1_000_000_000m);
decimal mult = 1m + 0.5m * ((t - 300 - 1) / 50);
decimal lum = Math.Ceiling(t * 2_000_000_000m * mult);
return t <= 325 ? ("Enlightenment Sigils", IltInventory.WcidEnlSigil, count, lum)
: ("Enlightenment Crests", IltInventory.WcidEnlCrest, count, lum);
}
// ── XP ──────────────────────────────────────────────────────────────────
/// <summary>/attr abbreviation, display name, attribute stype (0 = vital), vital stype.</summary>
private static readonly (string Abbr, string Name, uint Attr, uint Vital)[] Stats =
{
("str", "Strength", 1, 0), ("end", "Endurance", 2, 0), ("coo", "Coordination", 4, 0),
("qui", "Quickness", 3, 0), ("foc", "Focus", 5, 0), ("sel", "Self", 6, 0),
("hea", "Health", 0, 1), ("sta", "Stamina", 0, 3), ("man", "Mana", 0, 5),
};
private readonly IltHubContext _ctx;
private readonly Dictionary<string, int> _augLevels = new(StringComparer.OrdinalIgnoreCase);
private volatile string _augStatus = "not loaded";
// Opening the Progression tab pulls "/aug" once per login when nothing has loaded the levels yet.
private bool _augAutoTried;
/// <summary>Second Refresh current while /aug is already queued or in flight (UB coalesces the same way).</summary>
private bool _augRefreshAgain;
/// <summary>One silent retry after the login probe left Current empty (chat-hold / ArmsIdle race).</summary>
private bool _augProbeRetryDone;
/// <summary>Passive /aug window: accept AugLine chat until this tick (like T11's report parser).</summary>
private long _augPassiveUntilMs;
// Cached player facts for the render thread (refreshed in Tick).
private volatile int _enl, _level, _freeSlots;
private long _unassignedXp;
private volatile bool _peace, _hasVitae;
private readonly long[] _enlHave = new long[4]; // tokens, medallions, sigils, crests
// 301-325 sigil chain stock (pack items by name; EnlightenedCoins = bank + pack). Pump thread only.
private IltSigilStock _chain = new();
private long _lastFactsAt;
private readonly uint[] _enchIds = new uint[256];
private readonly double[] _enchExp = new double[256];
// Auto-enlighten (armed only after the in-session confirm).
private bool _autoArmed;
private long _lastAutoCheck;
private long _lastEnlSentAt = -AutoEnlCooldownMs;
private volatile string _enlStatus = string.Empty;
// XP spend-before-enlighten loop.
private bool _spending;
private int _spendIdx, _spendSent, _spendNoProgress;
private long _spendLastAt, _spendLastXp;
private Action? _afterSpend;
/// <summary>Infinite-attribute raiser (Progression tab "Attribute raiser" section).</summary>
public IltAttributeRaiser Attributes { get; }
public IltProgression(IltHubContext ctx)
{
_ctx = ctx;
// Never two /attr spenders at once: the raiser waits while the spend-before-/enl loop runs.
Attributes = new IltAttributeRaiser(ctx) { HoldOff = () => _spending };
}
private IltCharacterState C => _ctx.State.Character;
// ── Commands ────────────────────────────────────────────────────────────
public void RequestAugs()
{
RynthLog.Trace(LogCat.IltProgression, $"RequestAugs()");
if (_ctx.Options.IsOff(IltFeature.Aug))
{
_augStatus = "/aug is off for this world";
return;
}
// Coalesce: a click during an in-flight /aug (login probe or a prior Refresh) runs again
// when that capture finishes — including via AfterExternalAugCapture for the probe.
if (_ctx.Capture.IsPending("/aug"))
{
_augRefreshAgain = true;
_augStatus = "refresh queued (waiting for current /aug)...";
return;
}
_augStatus = "loading...";
_augPassiveUntilMs = IltHubContext.NowMs + 30_000; // also accept lines if capture finishes early
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/aug",
IsResponseLine = t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase) || IltParse.AugLine.IsMatch(t),
// Idle must not start on the banner alone — chat-hold / pump lag used to finish with 0 level lines.
ArmsIdle = t => IltParse.AugLine.IsMatch(t),
IdleEndMs = 2500,
// Login + chat-hold backlog can push Creature: past the old 15s first-line window.
FirstLineTimeoutMs = 30_000,
Eat = true,
OnComplete = r =>
{
if (r.UnknownCommand)
{
_ctx.Options.Set(IltFeature.Aug, IltTri.Off);
_augStatus = "/aug not available";
_augRefreshAgain = false;
return;
}
ApplyAugLines(r.Lines);
if (r.TimedOut)
{
int have;
lock (_augLevels) have = _augLevels.Count;
if (have == 0)
_augStatus = "timed out waiting for /aug level lines";
}
DrainAugRefreshAgain();
},
});
}
/// <summary>
/// Login probe finished its "/aug" capture (or another path applied lines). Drains a queued
/// Refresh current and, if the probe left Current empty, retries once.
/// </summary>
public void AfterExternalAugCapture()
{
if (DrainAugRefreshAgain()) return;
int have;
lock (_augLevels) have = _augLevels.Count;
if (have > 0 || _augProbeRetryDone || _ctx.Options.IsOff(IltFeature.Aug)) return;
if (_ctx.Capture.IsPending("/aug")) return;
_augProbeRetryDone = true;
RynthLog.Event(LogEvents.IltAugLoad, "aug probe left Current empty — retrying /aug once");
RequestAugs();
}
/// <summary>Runs a coalesced Refresh current if one was queued. Returns true when it did.</summary>
private bool DrainAugRefreshAgain()
{
if (!_augRefreshAgain) return false;
_augRefreshAgain = false;
RequestAugs();
return true;
}
/// <summary>Parses "/aug" output (also fed from the login probe and passive chat).</summary>
public void ApplyAugLines(List<string> lines)
{
RynthLog.Trace(LogCat.IltProgression, $"ApplyAugLines(lines={lines.Count})");
int n = 0;
foreach (string l in lines)
{
if (TryApplyAugLine(l)) n++;
}
if (n > 0)
{
_augStatus = $"{n} aug types @ {DateTime.Now:t}";
_augPassiveUntilMs = IltHubContext.NowMs + 8_000;
}
else
{
bool sawBanner = false;
foreach (string l in lines)
{
if (l.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase))
{ sawBanner = true; break; }
}
_augStatus = sawBanner
? "no level lines yet (banner only — waiting / retry)"
: "no aug lines in reply";
// Keep the passive reader open so late Creature: lines still fill Current.
if (sawBanner) _augPassiveUntilMs = IltHubContext.NowMs + 15_000;
}
RynthLog.Event(LogEvents.IltAugLoad, $"ApplyAugLines: {_augStatus} (raw={lines.Count})");
}
/// <summary>Applies one "/aug" Type: N line. Returns true when a known planner key was updated.</summary>
private bool TryApplyAugLine(string raw)
{
var m = IltParse.AugLine.Match((raw ?? string.Empty).Trim());
if (!m.Success) return false;
string key = m.Groups[1].Value.ToLowerInvariant();
if (key == "specialize") key = "specialization";
// Planner rows only; charm / Triune Weave lines are ignored here (T11 reads those).
bool known = false;
foreach (var (k, _) in IltAugCosts.Labels)
if (k.Equals(key, StringComparison.OrdinalIgnoreCase)) { known = true; break; }
if (!known) return false;
lock (_augLevels) _augLevels[key] = (int)IltParse.ParseAugValue(m.Groups[2].Value);
return true;
}
/// <summary>Sends "/enl" (server shows the confirmation dialog). Pump thread.</summary>
public void SendEnlighten(string why)
{
RynthLog.Trace(LogCat.IltProgression, $"SendEnlighten(why='{why}')");
if (!_ctx.Host.HasInvokeChatParser) return;
_lastEnlSentAt = IltHubContext.NowMs;
_ctx.Host.InvokeChatParser("/enl");
_enlStatus = $"/enl sent ({why}) - click Yes in the AC dialog to confirm.";
_ctx.Chat("[Mini Remote] " + _enlStatus);
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (nowMs - _lastFactsAt >= 2000)
{
_lastFactsAt = nowMs;
RefreshFacts();
}
TickSpend(nowMs);
Attributes.Tick(nowMs, holdOff: _spending);
if (_autoArmed && C.AutoEnlightenEnabled && !_spending
&& nowMs - _lastAutoCheck >= Math.Max(10, C.AutoEnlightenCheckSeconds) * 1000L)
{
_lastAutoCheck = nowMs;
TryAutoEnlighten(nowMs);
}
}
public bool OnChat(string text)
{
Attributes.OnChat(text);
// Passive /aug reader: updates Current even when the capture idle finished on the banner alone
// (chat-hold backlog) or the player typed /aug by hand. Window opens on the header.
string t = text;
if (t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase))
_augPassiveUntilMs = IltHubContext.NowMs + 8_000;
else if (IltHubContext.NowMs <= _augPassiveUntilMs && TryApplyAugLine(t))
{
_augPassiveUntilMs = IltHubContext.NowMs + 8_000;
int n;
lock (_augLevels) n = _augLevels.Count;
_augStatus = $"{n} aug types @ {DateTime.Now:t}";
}
if (text.Contains("You have become enlightened", StringComparison.OrdinalIgnoreCase)
|| text.Contains("You have risen to a higher tier of enlightenment", StringComparison.OrdinalIgnoreCase))
{
_enlStatus = "Enlightened! " + DateTime.Now.ToString("t");
_lastFactsAt = 0;
}
return false;
}
public void OnLogout()
{
_autoArmed = false;
_spending = false;
Attributes.OnLogout();
lock (_augLevels) _augLevels.Clear();
_augAutoTried = false;
_augRefreshAgain = false;
_augProbeRetryDone = false;
_augPassiveUntilMs = 0;
_augStatus = "not loaded";
}
// ── Facts / auto ────────────────────────────────────────────────────────
private void RefreshFacts()
{
var inv = _ctx.Inventory;
_enl = inv.PlayerInt(IltInventory.IntEnlightenment);
_level = inv.PlayerInt(IltInventory.IntLevel);
_unassignedXp = inv.PlayerQuad(IltInventory.QuadAvailableXp);
_peace = inv.InPeaceMode;
_freeSlots = inv.FreeMainPackSlots();
_enlHave[0] = inv.CountByWcid(IltInventory.WcidEnlToken);
_enlHave[1] = inv.CountByWcid(IltInventory.WcidEnlMedallion);
_enlHave[2] = inv.CountByWcid(IltInventory.WcidEnlSigil);
_enlHave[3] = inv.CountByWcid(IltInventory.WcidEnlCrest);
_chain = new IltSigilStock
{
Sigils = _enlHave[2],
EnlightenedCoins = _ctx.State.Bank.EnlightenedCoins + inv.CountByWcid(IltInventory.WcidEnlightenedCoin),
AscensionCoins = inv.CountByChainName(IltSigilChain.AscensionCoin),
LifebloodElixirs = inv.CountByChainName(IltSigilChain.LifebloodElixir),
LifebloomResins = inv.CountByChainName(IltSigilChain.LifebloomResin),
YalaniTrinkets = inv.CountByChainName(IltSigilChain.YalaniTrinket),
NecrolyticExtracts = inv.CountByChainName(IltSigilChain.NecrolyticExtract),
LifeSplitters = inv.CountByChainName(IltSigilChain.LifeSplitter),
Plants = inv.CountByChainName(IltSigilChain.Plant),
};
_hasVitae = false;
if (_ctx.Host.HasReadPlayerEnchantments)
{
int n = _ctx.Host.ReadPlayerEnchantments(_enchIds, _enchExp, _enchIds.Length);
for (int i = 0; i < Math.Min(n, _enchIds.Length); i++)
if (_enchIds[i] == SpellVitae) { _hasVitae = true; break; }
}
}
private long HaveFor(uint wcid) => wcid switch
{
IltInventory.WcidEnlToken => _enlHave[0],
IltInventory.WcidEnlMedallion => _enlHave[1],
IltInventory.WcidEnlSigil => _enlHave[2],
IltInventory.WcidEnlCrest => _enlHave[3],
_ => 0,
};
/// <summary>Checks the client-visible requirements for the next enlightenment. Empty = ready.</summary>
private List<string> NextEnlBlockers()
{
var list = new List<string>();
int next = _enl + 1;
if (_level < BaseLevelForEnl + _enl) list.Add($"Need character level {BaseLevelForEnl + _enl} (have {_level}).");
if (!_peace) list.Add("Must be in peace mode.");
if (_hasVitae) list.Add("Must not have vitae.");
var cost = EnlStepCost(next);
if (cost.Count > 0 && HaveFor(cost.Wcid) < cost.Count)
{
// Sigils: the server takes finished sigils only, but say how many the craft chain could still make.
string craft = cost.Wcid == IltInventory.WcidEnlSigil
? $"; the craft chain can make {IltParse.N0(IltSigilChain.Fulfillable(_chain) - _chain.Sigils)} more"
: string.Empty;
list.Add($"Need {cost.Count} {cost.Item} (have {HaveFor(cost.Wcid)}{craft}).");
}
if (cost.Lum > 0 && _ctx.State.Bank.Luminance < cost.Lum) list.Add($"Need {IltParse.Compact((double)cost.Lum)} banked luminance.");
return list;
}
private void TryAutoEnlighten(long now)
{
if (_ctx.Options.IsOff(IltFeature.Enl)) return;
if (Attributes.Running) return; // the raiser is spending XP; check again next interval
if (now - _lastEnlSentAt < AutoEnlCooldownMs) return;
if (NextEnlBlockers().Count > 0) return;
if (C.AutoEnlightenSpendXpFirst && _unassignedXp > 0)
StartSpend(() => SendEnlighten("auto"));
else
SendEnlighten("auto");
}
// ── XP spend loop: cycles /attr <abbr> 1 until unassigned XP stops dropping ──
private void StartSpend(Action then)
{
_spending = true;
_spendIdx = 0;
_spendSent = 0;
_spendNoProgress = 0;
_spendLastAt = 0;
_spendLastXp = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp);
_afterSpend = then;
_enlStatus = "Spending unassigned XP before enlightening...";
}
private void TickSpend(long now)
{
if (!_spending || now - _spendLastAt < 300) return;
_spendLastAt = now;
long xp = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp);
if (xp < _spendLastXp) _spendNoProgress = 0; else if (_spendSent > 0) _spendNoProgress++;
_spendLastXp = xp;
// Stop after a full stat cycle with no XP drop, when XP is gone, or at the safety cap.
if (xp <= 0 || _spendNoProgress >= Stats.Length || _spendSent >= 300)
{
_spending = false;
var next = _afterSpend;
_afterSpend = null;
next?.Invoke();
return;
}
if (_ctx.Inventory.IsBusy) return;
_ctx.Host.InvokeChatParser($"/attr {Stats[_spendIdx].Abbr} 1");
_spendIdx = (_spendIdx + 1) % Stats.Length;
_spendSent++;
}
// ── Engine Skills panel bridge (pump thread) ────────────────────────────
// The engine's Skills panel draws Augmentations and Enlightenment from this snapshot and
// sends edits back as "prog ..." remote commands (HandleRemote). Planner math stays here so
// the Hub and the Skills panel can never disagree. Numbers are preformatted for display.
/// <summary>Appends <c>"aug":{...},"enl":{...},"attr":{...}</c> to <paramref name="sb"/>. Pump thread.</summary>
public void AppendSnapshotJson(StringBuilder sb)
{
// The snapshot is only polled while the Progression tab is open, so this is "on first view".
EnsureAugs();
Attributes.EnsureCosts();
AppendAugJson(sb);
sb.Append(',');
AppendEnlJson(sb);
sb.Append(',');
Attributes.AppendJson(sb);
}
/// <summary>Pulls "/aug" once per login when the levels haven't been loaded (login probe or by hand).</summary>
private void EnsureAugs()
{
if (_augAutoTried || _ctx.Options.IsOff(IltFeature.Aug) || !_ctx.Host.HasInvokeChatParser) return;
bool loaded;
lock (_augLevels) loaded = _augLevels.Count > 0;
_augAutoTried = true;
if (!loaded) RequestAugs();
}
/// <summary>One aug's plan line: current level, clamped target, luminance and coins to get there.</summary>
private readonly record struct AugPlan(IltAugCostRow Def, string Label, int Cur, int Tgt, int Ceiling, decimal Lum, long Coins)
{
public int Inc => Tgt - Cur;
}
private List<AugPlan> BuildAugPlan()
{
Dictionary<string, int> levels;
lock (_augLevels) levels = new Dictionary<string, int>(_augLevels, StringComparer.OrdinalIgnoreCase);
var profile = AugProfile;
var plan = new List<AugPlan>(profile.Augs.Count);
foreach (var a in profile.Augs)
{
int cur = levels.TryGetValue(a.Key, out int c) ? c : 0;
int ceiling = IltAugCosts.Ceiling(a, cur);
int tgt = Math.Clamp(C.AugTargets.TryGetValue(a.Key, out int t) ? t : cur, cur, ceiling);
plan.Add(new AugPlan(a, IltAugCosts.Label(a.Key), cur, tgt, ceiling,
IltAugCosts.LumCost(a, profile.Multipliers, cur, tgt), (long)(tgt - cur) * a.CoinsPerLevel));
}
return plan;
}
private void AppendAugJson(StringBuilder sb)
{
var plan = BuildAugPlan();
sb.Append("\"aug\":{\"off\":").Append(Bool(_ctx.Options.IsOff(IltFeature.Aug)));
Str(sb, "status", _augStatus);
sb.Append(",\"lumPerCoin\":").Append(C.LumPerEnlightenedCoin).Append(",\"rows\":[");
for (int i = 0; i < plan.Count; i++)
{
var p = plan[i];
if (i > 0) sb.Append(',');
sb.Append('{');
Str(sb, "key", p.Def.Key, first: true);
Str(sb, "label", p.Label);
sb.Append(",\"cur\":").Append(p.Cur).Append(",\"tgt\":").Append(p.Tgt).Append(",\"cap\":").Append(p.Ceiling)
.Append(",\"inc\":").Append(p.Inc);
Str(sb, "lum", p.Lum > 0 ? IltParse.Compact((double)p.Lum) : "-");
sb.Append(",\"coins\":").Append(p.Coins).Append('}');
}
sb.Append(']');
decimal totalLum = plan.Sum(p => p.Lum);
long totalCoins = plan.Sum(p => p.Coins);
long bankCoins = _ctx.State.Bank.EnlightenedCoins;
long lumPerCoin = C.LumPerEnlightenedCoin;
long coinsShort = Math.Max(0, totalCoins - bankCoins);
// Totals row (UB's TOTALS line) and the e-coin summary under the table.
sb.Append(",\"totCur\":").Append(plan.Sum(p => p.Cur))
.Append(",\"totTgt\":").Append(plan.Sum(p => p.Tgt))
.Append(",\"totInc\":").Append(plan.Sum(p => p.Inc))
.Append(",\"totCoins\":").Append(totalCoins);
Str(sb, "totLum", totalLum > 0 ? IltParse.Compact((double)totalLum) : "-");
Str(sb, "coinsLine", $"E-coins needed: {IltParse.N0(totalCoins)} banked: {IltParse.N0(bankCoins)} short: {IltParse.N0(coinsShort)}");
Str(sb, "lumToBuy", coinsShort == 0 ? "Lum to buy e-coins: none needed"
: lumPerCoin > 0 ? $"Lum to buy e-coins: ~{IltParse.Compact((double)coinsShort * lumPerCoin)}"
: "Lum to buy e-coins: set Lum per coin");
// Older engine builds read these three.
Str(sb, "total", $"Total: {IltParse.Compact((double)totalLum)} luminance, {IltParse.N0(totalCoins)} coins");
Str(sb, "short", coinsShort > 0
? $"Coins short: {IltParse.N0(coinsShort)}" + (lumPerCoin > 0 ? $" (~{IltParse.Compact((double)coinsShort * lumPerCoin)} luminance to buy)" : "")
: string.Empty);
Str(sb, "banked", $"Banked luminance: {IltParse.Compact(_ctx.State.Bank.Luminance)}");
Str(sb, "copyDiscord", AugDiscordText(plan));
Str(sb, "copyIngame", AugIngameText(plan));
AppendAugCostJson(sb);
sb.Append('}');
}
/// <summary><c>"cfg":{...}</c>: this world's cost rules for the "Cost settings" editor.</summary>
private void AppendAugCostJson(StringBuilder sb)
{
string world = _ctx.Options.WorldName;
var p = AugProfile;
var inv = System.Globalization.CultureInfo.InvariantCulture;
sb.Append(",\"cfg\":{");
Str(sb, "world", world.Length > 0 ? world : "unknown world", first: true);
sb.Append(",\"custom\":").Append(Bool(AugCosts.IsCustom(world))).Append(",\"mults\":[");
for (int i = 0; i < p.Multipliers.Length; i++)
sb.Append(i > 0 ? "," : "").Append(p.Multipliers[i].ToString("R", inv));
sb.Append("],\"rows\":[");
for (int i = 0; i < p.Augs.Count; i++)
{
var r = p.Augs[i];
if (i > 0) sb.Append(',');
sb.Append('{');
Str(sb, "key", r.Key, first: true);
Str(sb, "label", IltAugCosts.Label(r.Key));
sb.Append(",\"base\":").Append(r.Base)
.Append(",\"pct\":").Append(r.LinearPercent.ToString("R", inv))
.Append(",\"coins\":").Append(r.CoinsPerLevel)
.Append(",\"s1\":").Append(r.S1).Append(",\"s2\":").Append(r.S2)
.Append(",\"s3\":").Append(r.S3).Append(",\"s4\":").Append(r.S4)
.Append(",\"cap\":").Append(r.Cap).Append('}');
}
sb.Append("]}");
}
/// <summary>"augcfg &lt;aug&gt; &lt;field&gt; &lt;value&gt;": one cost-rule edit for this world.</summary>
private void EditAugRule(string key, string field, string value)
{
var inv = System.Globalization.CultureInfo.InvariantCulture;
bool isInt = int.TryParse(value, System.Globalization.NumberStyles.Integer, inv, out int iv);
bool isNum = double.TryParse(value, System.Globalization.NumberStyles.Float, inv, out double dv);
long amount = 0;
bool isAmount = field == "base" && IltParse.TryParseAmount(value, out amount);
if (!isInt && !isNum && !isAmount) return;
AugCosts.Edit(_ctx.Options.WorldName, p =>
{
var r = p.Augs.FirstOrDefault(x => x.Key.Equals(key, StringComparison.OrdinalIgnoreCase));
if (r == null) return;
switch (field)
{
case "base": if (isAmount) r.Base = amount; break;
case "pct": if (isNum) r.LinearPercent = dv; break;
case "coins": if (isInt) r.CoinsPerLevel = iv; break;
case "s1": if (isInt) r.S1 = iv; break;
case "s2": if (isInt) r.S2 = iv; break;
case "s3": if (isInt) r.S3 = iv; break;
case "s4": if (isInt) r.S4 = iv; break;
case "cap": if (isInt) r.Cap = iv; break;
}
});
}
/// <summary>
/// UB's "Copy Discord" table in a code block. ASCII only: the engine reads the snapshot as ANSI.
/// </summary>
private string AugDiscordText(List<AugPlan> plan)
{
string name = string.IsNullOrEmpty(_ctx.CharName) ? "character" : _ctx.CharName;
string rule = new('-', 56);
var t = new StringBuilder();
t.Append("```\n").Append("Augmentations - ").Append(name).Append('\n').Append(rule).Append('\n');
t.Append($"{"Type",-15} {"Current",-8} {"Target",-8} {"Inc",-5} {"Lum Cost",-10} {"Coins",-6}\n").Append(rule).Append('\n');
foreach (var p in plan)
{
if (p.Cur <= 0 && p.Tgt <= 0) continue;
string lum = p.Lum > 0 ? IltParse.Compact((double)p.Lum) : "-";
t.Append($"{p.Label,-15} {p.Cur,-8} {p.Tgt,-8} {p.Inc,-5} {lum,-10} {p.Coins,-6}\n");
}
decimal totalLum = plan.Sum(p => p.Lum);
t.Append(rule).Append('\n');
t.Append($"{"TOTALS:",-15} {plan.Sum(p => p.Cur),-8} {plan.Sum(p => p.Tgt),-8} {plan.Sum(p => p.Inc),-5} "
+ $"{(totalLum > 0 ? IltParse.Compact((double)totalLum) : "-"),-10} {plan.Sum(p => p.Coins),-6}\n");
t.Append("```");
return t.ToString();
}
/// <summary>UB's "Copy In-Game": one line of current levels with short names, for pasting into chat.</summary>
private string AugIngameText(List<AugPlan> plan)
{
string name = string.IsNullOrEmpty(_ctx.CharName) ? "character" : _ctx.CharName;
var parts = plan.Where(p => p.Cur > 0).Select(p => $"{AugShortName(p.Def.Key)}: {IltParse.N0(p.Cur)}").ToList();
return parts.Count == 0
? $"Augmentation Levels - {name}: none loaded"
: $"Augmentation Levels - {name} ({IltParse.N0(plan.Sum(p => p.Cur))} total): {string.Join(", ", parts)}";
}
private static string AugShortName(string key) => key switch
{
"creature" => "Crit",
"duration" => "Dur",
"specialization" => "Spec",
"summon" => "Sum",
"melee" => "Mel",
"missile" => "Mis",
_ => char.ToUpperInvariant(key[0]) + key.Substring(1),
};
private void AppendEnlJson(StringBuilder sb)
{
int enl = _enl;
sb.Append("\"enl\":{\"off\":").Append(Bool(_ctx.Options.IsOff(IltFeature.Enl)));
Str(sb, "header", $"Enlightenment {enl} Level {_level} Unassigned XP {IltParse.Compact(_unassignedXp)}");
var next = EnlStepCost(enl + 1);
Str(sb, "next", $"Next ({enl + 1}): " + (next.Count > 0
? $"{next.Count} {next.Item} (have {HaveFor(next.Wcid)})" + (next.Lum > 0 ? $" + {IltParse.Compact((double)next.Lum)} lum" : "")
: "no materials"));
int target = C.EnlTargetLevel <= enl ? enl + 5 : C.EnlTargetLevel;
sb.Append(",\"enl\":").Append(enl).Append(",\"target\":").Append(target).Append(",\"plan\":[");
var totals = new Dictionary<string, long>();
decimal lumTotal = 0;
for (int t = enl + 1; t <= Math.Max(enl + 1, target) && t <= enl + 500; t++)
{
var s = EnlStepCost(t);
if (s.Count > 0) totals[s.Item] = (totals.TryGetValue(s.Item, out long v) ? v : 0) + s.Count;
lumTotal += s.Lum;
}
bool firstLine = true;
foreach (var kv in totals) { StrItem(sb, $"{IltParse.N0(kv.Value)} {kv.Key}", ref firstLine); }
if (lumTotal > 0)
StrItem(sb, $"{IltParse.Compact((double)lumTotal)} luminance (banked {IltParse.Compact(_ctx.State.Bank.Luminance)})", ref firstLine);
sb.Append(']');
int coinsPerToken = C.EnlightenedCoinsPerToken;
sb.Append(",\"coinsPerToken\":").Append(coinsPerToken);
string tokensShort = string.Empty;
if (totals.TryGetValue("Enlightenment Tokens", out long tokNeed) && coinsPerToken > 0)
{
long shortTok = Math.Max(0, tokNeed - _enlHave[0]);
if (shortTok > 0) tokensShort = $"Tokens short: {shortTok} (~{IltParse.N0(shortTok * coinsPerToken)} coins)";
}
Str(sb, "tokensShort", tokensShort);
AppendEnlCalculatorJson(sb, enl, target, totals, lumTotal);
var blockers = NextEnlBlockers();
sb.Append(",\"blockers\":[");
bool firstBlocker = true;
foreach (string b in blockers) StrItem(sb, b, ref firstBlocker);
sb.Append(']');
Str(sb, "serverChecks", $"Server also checks: not in a dungeon, free pack slots ({(_freeSlots >= 0 ? _freeSlots.ToString() : "?")} free), "
+ "all luminance augs (past 10), society master (past 30).");
sb.Append(",\"auto\":").Append(Bool(C.AutoEnlightenEnabled))
.Append(",\"armed\":").Append(Bool(_autoArmed))
.Append(",\"spendFirst\":").Append(Bool(C.AutoEnlightenSpendXpFirst))
.Append(",\"checkEvery\":").Append(C.AutoEnlightenCheckSeconds);
Str(sb, "status", _enlStatus);
sb.Append('}');
}
/// <summary>Per-level rows the calculator lists at most (a bigger range is summarised in the totals).</summary>
private const int EnlLevelRowsMax = 100;
/// <summary>
/// UB-IT's Enlighten calculator: per-level table (green while stock lasts, the sigil chain counted),
/// material summary (still need / have), the 301-325 sigil chain, and the e-coin line shared with
/// token conversion. Appends "levels", "materials", "chain", "chainNote", "ecoins", "ecoinsLum".
/// </summary>
private void AppendEnlCalculatorJson(StringBuilder sb, int enl, int target, Dictionary<string, long> totals, decimal lumTotal)
{
// Simulated stock: tokens, medallions, crests on hand, sigils via the chain, banked luminance.
long tok = _enlHave[0], med = _enlHave[1], crest = _enlHave[3];
decimal lum = (decimal)_ctx.State.Bank.Luminance;
var chain = _chain.Clone();
long sigilCraftable = IltSigilChain.Fulfillable(chain);
sb.Append(",\"levels\":[");
int last = Math.Min(Math.Max(enl + 1, target), enl + EnlLevelRowsMax);
for (int t = enl + 1; t <= last; t++)
{
var s = EnlStepCost(t);
bool ok = lum >= s.Lum;
if (ok && s.Count > 0)
{
switch (s.Wcid)
{
case IltInventory.WcidEnlToken: ok = tok >= s.Count; if (ok) tok -= s.Count; break;
case IltInventory.WcidEnlMedallion: ok = med >= s.Count; if (ok) med -= s.Count; break;
case IltInventory.WcidEnlSigil: ok = sigilCraftable >= s.Count; if (ok) sigilCraftable -= s.Count; break;
default: ok = crest >= s.Count; if (ok) crest -= s.Count; break;
}
}
if (ok) lum -= s.Lum;
if (t > enl + 1) sb.Append(',');
sb.Append("{\"t\":").Append(t);
Str(sb, "item", ShortItem(s.Item));
sb.Append(",\"count\":").Append(s.Count);
Str(sb, "lum", s.Lum > 0 ? IltParse.Compact((double)s.Lum) : "-");
sb.Append(",\"ok\":").Append(Bool(ok)).Append('}');
}
sb.Append(']');
// Material summary: Still need = demand minus what is on hand.
long sigilsNeed = totals.TryGetValue("Enlightenment Sigils", out long sn) ? sn : 0;
var shortfall = IltSigilChain.Shortfall(sigilsNeed, _chain);
decimal bankLum = (decimal)_ctx.State.Bank.Luminance;
sb.Append(",\"materials\":[");
bool firstMat = true;
void Mat(string label, string need, string have, bool ok)
{
if (!firstMat) sb.Append(',');
firstMat = false;
sb.Append('{');
Str(sb, "label", label, first: true);
Str(sb, "need", need);
Str(sb, "have", have);
sb.Append(",\"ok\":").Append(Bool(ok)).Append('}');
}
if (lumTotal > 0)
{
decimal lumStill = Math.Max(0, lumTotal - bankLum);
Mat("Luminance", lumStill > 0 ? IltParse.Compact((double)lumStill) : "0", IltParse.Compact((double)bankLum), lumStill == 0);
}
void Item(string key, string label, long have, bool extraOk = false)
{
if (!totals.TryGetValue(key, out long need)) return;
long still = Math.Max(0, need - have);
Mat(label, IltParse.N0(still), IltParse.N0(have), still == 0 || extraOk);
}
Item("Enlightenment Tokens", "Tokens", _enlHave[0]);
Item("Enlightenment Medallions", "Medallions", _enlHave[1]);
Item("Enlightenment Sigils", "Sigils", _enlHave[2], extraOk: shortfall.Covered);
Item("Enlightenment Crests", "Crests", _enlHave[3]);
sb.Append(']');
// Sigil chain rows (only when the plan reaches 301-325).
sb.Append(",\"chain\":[");
if (sigilsNeed > 0)
{
bool firstRow = true;
void Row(string label, long need, long have, bool ok, bool craft)
{
if (!firstRow) sb.Append(',');
firstRow = false;
sb.Append('{');
Str(sb, "label", label, first: true);
sb.Append(",\"need\":").Append(need).Append(",\"have\":").Append(have)
.Append(",\"ok\":").Append(Bool(ok)).Append(",\"craft\":").Append(Bool(craft)).Append('}');
}
Row("Ascension Coins", shortfall.AscensionToCraft, _chain.AscensionCoins,
shortfall.AscensionToCraft == 0 || (shortfall.CoinsShort == 0 && shortfall.TrinketsShort == 0), true);
Row("Lifeblood Elixirs", shortfall.ElixirsToCraft, _chain.LifebloodElixirs,
shortfall.ElixirsToCraft == 0 || (shortfall.ExtractsShort == 0 && shortfall.SplittersShort == 0 && shortfall.PlantsShort == 0), true);
Row("Lifebloom Resins", shortfall.ResinsToCraft, _chain.LifebloomResins,
shortfall.ResinsToCraft == 0 || (shortfall.SplittersShort == 0 && shortfall.PlantsShort == 0), true);
Row("E-coins", shortfall.CoinsShort, _chain.EnlightenedCoins, shortfall.CoinsShort == 0, false);
Row("Ancient Yalani Trinkets", shortfall.TrinketsShort, _chain.YalaniTrinkets, shortfall.TrinketsShort == 0, false);
Row("Necrolytic Extracts", shortfall.ExtractsShort, _chain.NecrolyticExtracts, shortfall.ExtractsShort == 0, false);
Row("Life Splitters", shortfall.SplittersShort, _chain.LifeSplitters, shortfall.SplittersShort == 0, false);
Row("Plants", shortfall.PlantsShort, _chain.Plants, shortfall.PlantsShort == 0, false);
}
sb.Append(']');
Str(sb, "chainNote", sigilsNeed > 0
? $"Sigil = Lifeblood Elixir + Ascension Coin. {IltParse.N0(shortfall.SigilsToCraft)} to craft; "
+ (shortfall.Covered ? "the chain covers them." : "Need = crafts left (in-between items) or mats to get (raw items).")
: string.Empty);
// E-coins: Ascension Coin crafts first, then token conversion at the shop price.
long tokNeed = totals.TryGetValue("Enlightenment Tokens", out long tn) ? tn : 0;
IltSigilChain.EcoinDemand(_chain.EnlightenedCoins, shortfall.CoinsForCraft, Math.Max(0, tokNeed - _enlHave[0]),
C.EnlightenedCoinsPerToken, out _, out long tokensStill, out long coinsNeeded);
Str(sb, "ecoins", tokNeed > 0 || shortfall.CoinsForCraft > 0
? $"E-coins needed: {IltParse.N0(coinsNeeded)} have {IltParse.N0(_chain.EnlightenedCoins)} (bank + pack)"
+ (shortfall.CoinsForCraft > 0 ? $" Ascension Coins use {IltParse.N0(shortfall.CoinsForCraft)}" : "")
+ (tokensStill > 0 ? $" tokens still {IltParse.N0(tokensStill)}" : "")
: string.Empty);
long lumPerCoin = C.LumPerEnlightenedCoin;
Str(sb, "ecoinsLum", coinsNeeded <= 0 ? string.Empty
: lumPerCoin > 0 ? $"Lum to buy e-coins: ~{IltParse.Compact((double)coinsNeeded * lumPerCoin)}"
: "Lum to buy e-coins: set Lum per e-coin (Augmentations)");
}
/// <summary>Short label for the per-level table's item column.</summary>
private static string ShortItem(string item) => item switch
{
"Enlightenment Tokens" => "Tokens",
"Enlightenment Medallions" => "Medallions",
"Enlightenment Sigils" => "Sigils",
"Enlightenment Crests" => "Crests",
_ => "-",
};
private static string Bool(bool b) => b ? "true" : "false";
private static void Str(StringBuilder sb, string name, string value, bool first = false)
{
if (!first) sb.Append(',');
sb.Append('"').Append(name).Append("\":\"").Append(IltStyle.JsonEscape(value ?? string.Empty)).Append('"');
}
private static void StrItem(StringBuilder sb, string value, ref bool first)
{
if (!first) sb.Append(',');
first = false;
sb.Append('"').Append(IltStyle.JsonEscape(value)).Append('"');
}
/// <summary>
/// "prog" remote command from the engine Skills panel. Pump thread. The panel asks its own
/// confirmation before "enlighten" and "autoenl on|arm", so none is asked here.
/// </summary>
public void HandleRemote(string[] a)
{
if (a.Length == 0) return;
RynthLog.Trace(LogCat.IltProgression, $"HandleRemote({string.Join(" ", a)})");
string arg1 = a.Length > 1 ? a[1] : string.Empty;
int.TryParse(a.Length > 2 ? a[2] : arg1, out int n);
string verb = a[0].ToLowerInvariant();
if (verb.StartsWith("attr", StringComparison.Ordinal) && Attributes.HandleRemote(verb, a)) return;
switch (verb)
{
case "augload": RequestAugs(); break;
case "augreset":
// UB's "Reset Target": every target back to the current level.
lock (_augLevels)
foreach (var (key, _) in IltAugCosts.Labels)
C.AugTargets[key] = _augLevels.TryGetValue(key, out int c) ? c : 0;
break;
case "augtarget" when a.Length > 2:
foreach (var def in AugProfile.Augs)
{
if (!def.Key.Equals(arg1, StringComparison.OrdinalIgnoreCase)) continue;
int cur;
lock (_augLevels) cur = _augLevels.TryGetValue(def.Key, out int c) ? c : 0;
C.AugTargets[def.Key] = Math.Clamp(n, 0, IltAugCosts.Ceiling(def, cur));
break;
}
break;
case "augmult" when a.Length > 2:
// "augmult <tier 0-4> <multiplier>": tier 0 is below S1, tier 4 is from S4 on.
if (int.TryParse(arg1, out int tier) && tier is >= 0 and <= 4
&& double.TryParse(a[2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double mult))
AugCosts.Edit(_ctx.Options.WorldName, p => p.Multipliers[tier] = mult);
break;
case "augcfg" when a.Length > 3:
EditAugRule(arg1, a[2].ToLowerInvariant(), a[3]);
break;
case "augcfgreset":
AugCosts.Reset(_ctx.Options.WorldName);
break;
case "lumpercoin":
if (IltParse.TryParseAmount(arg1, out long lpc)) C.LumPerEnlightenedCoin = Math.Max(0, lpc);
break;
case "enltarget": C.EnlTargetLevel = Math.Max(_enl + 1, n); break;
case "coinspertoken": C.EnlightenedCoinsPerToken = Math.Max(0, n); break;
case "enlighten": SendEnlighten("manual, Skills panel"); break;
case "autoenl":
switch (arg1.ToLowerInvariant())
{
case "on":
C.AutoEnlightenEnabled = true;
_autoArmed = true;
_ctx.Chat("[Mini Remote] Auto-enlighten armed for this session.");
break;
case "arm": if (C.AutoEnlightenEnabled) _autoArmed = true; break;
default: C.AutoEnlightenEnabled = false; _autoArmed = false; break;
}
break;
case "spendfirst": C.AutoEnlightenSpendXpFirst = arg1.Equals("on", StringComparison.OrdinalIgnoreCase); break;
case "checkevery": C.AutoEnlightenCheckSeconds = Math.Max(10, n); break;
}
}
}

View file

@ -0,0 +1,209 @@
// IltQuestBonus.cs — The ACECustom quest bonus list ("/qb list"), shown in RynthAi's universal
// Quests tab (RynthILT.Hub section "quests-qb") and read by the Temple attribute tracker.
// Originally the /qb half of SilentKelpie's IltQuests (ILT Hub, RynthAi); split out and moved to
// RynthILT 2026-10-13. The /myquests tracker half stayed in RynthAi (MiniRemote/QuestsTab.cs):
// /myquests is every server's, /qb is ACECustom's.
//
// "/qb list" prints a completed and an incomplete section; both are tracked separately (UB
// merged them). Server throttles /qb to once per minute.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltQuestBonus : IIltFeature
{
private static readonly Regex KillTaskRegex = new(@"(killtask|killcount|slayerquest|totalgolem.*dead|(kills$))",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex QbFlagLine = new(@"^[a-zA-Z0-9_\-!@\(\)?]+$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private const long QbCooldownMs = 60_000;
private readonly IltHubContext _ctx;
private long _lastQbAt = -QbCooldownMs;
// QB results (replaced wholesale; read by the render thread).
private volatile string[] _qbCompleted = Array.Empty<string>();
private volatile string[] _qbIncomplete = Array.Empty<string>();
private volatile string _qbStatus = "not loaded";
private long _qbCount = -1;
private volatile int _qbGeneration; // bumped per successful "/qb list"; 0 = never loaded this session
public IltQuestBonus(IltHubContext ctx) => _ctx = ctx;
/// <summary>The /myquests flag kinds (RynthAi's QuestsTab.Classify, which the Temple tracker reads by).</summary>
public enum QuestKind { Timed, KillTask, Once }
public static QuestKind Classify(QuestRecord r)
{
if (KillTaskRegex.IsMatch(r.Key) && r.MaxSolves >= 0) return QuestKind.KillTask;
if (r.MaxSolves == 1 && r.Solves <= 1) return QuestKind.Once;
return QuestKind.Timed;
}
/// <summary>Captures "/qb list" (quiet).</summary>
public string RefreshQb()
{
RynthLog.Trace(LogCat.IltQuests, $"RefreshQb()");
if (_ctx.Options.IsOff(IltFeature.Qb)) return "/qb is disabled on this server.";
long now = IltHubContext.NowMs;
if (now - _lastQbAt < QbCooldownMs)
return $"Wait {(QbCooldownMs - (now - _lastQbAt)) / 1000}s (server allows one /qb per minute).";
if (_ctx.Capture.IsPending("/qb list")) return "Already loading...";
_lastQbAt = now;
_qbStatus = "loading...";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/qb list",
IsResponseLine = IsQbLine,
IsTerminator = t => t.Contains("Quest bonus list is empty", StringComparison.OrdinalIgnoreCase)
|| t.Contains("\"qb\" is not currently enabled", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("[QB] This command may only be run once every", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 5000,
FirstLineTimeoutMs = 30000,
Eat = true,
OnComplete = OnQbResult,
});
return "Loading quest bonus list...";
}
private static bool IsQbLine(string t)
{
if (t.StartsWith("Your completed quest bonus list", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("Your incomplete quest bonus list", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase))
return true;
if (!QbFlagLine.IsMatch(t)) return false;
if (t.StartsWith("You ", StringComparison.Ordinal) || t.StartsWith("The ", StringComparison.Ordinal)) return false;
return !(t.Contains("You have", StringComparison.OrdinalIgnoreCase) || t.Contains("command", StringComparison.OrdinalIgnoreCase)
|| t.Contains("enabled", StringComparison.OrdinalIgnoreCase) || t.Contains("list", StringComparison.OrdinalIgnoreCase));
}
private void OnQbResult(IltChatResult r)
{
if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Qb, IltTri.Off); _qbStatus = "/qb not available"; return; }
if (r.TerminatorLine != null)
{
if (r.TerminatorLine.Contains("not currently enabled", StringComparison.OrdinalIgnoreCase))
{ _ctx.Options.Set(IltFeature.Qb, IltTri.Off); _qbStatus = "/qb is disabled on this server"; return; }
if (r.TerminatorLine.Contains("only be run once", StringComparison.OrdinalIgnoreCase))
{ _qbStatus = "rate limited by the server"; return; }
}
if (r.TimedOut) { _qbStatus = "no reply from server"; return; }
_ctx.Options.Set(IltFeature.Qb, IltTri.On);
var done = new List<string>();
var todo = new List<string>();
List<string>? current = null;
foreach (string line in r.Lines)
{
if (line.StartsWith("Your completed quest bonus list", StringComparison.OrdinalIgnoreCase)) { current = done; continue; }
if (line.StartsWith("Your incomplete quest bonus list", StringComparison.OrdinalIgnoreCase)) { current = todo; continue; }
if (line.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase))
{
int colon = line.IndexOf(':');
if (colon > 0) _qbCount = IltParse.ParseLeadingLong(line.Substring(colon + 1));
continue;
}
if (line.Contains("is empty", StringComparison.OrdinalIgnoreCase)) continue;
(current ?? done).Add(line.Trim());
}
done.Sort(StringComparer.OrdinalIgnoreCase);
todo.Sort(StringComparer.OrdinalIgnoreCase);
_qbCompleted = done.ToArray();
_qbIncomplete = todo.ToArray();
_qbStatus = $"{done.Count} completed, {todo.Count} incomplete";
_qbGeneration++;
}
/// <summary>Increments each time a "/qb list" reply is parsed (0 = not loaded this session).</summary>
public int QbGeneration => _qbGeneration;
/// <summary>
/// Snapshot for the "RynthILT.Server" profile JSON (Oracle Quests / Fellowship). Pump thread.
/// </summary>
public IltQuestBonusInfo Snapshot() =>
new(_ctx.Options.IsOff(IltFeature.Qb), _qbGeneration, _qbCount, _qbStatus, _qbCompleted, _qbIncomplete);
/// <summary>True when the last "/qb list" (completed or incomplete) contains the flag.</summary>
public bool QbHasFlag(string flag)
{
if (string.IsNullOrWhiteSpace(flag)) return false;
foreach (string f in _qbCompleted)
if (f.Equals(flag, StringComparison.OrdinalIgnoreCase)) return true;
foreach (string f in _qbIncomplete)
if (f.Equals(flag, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
/// <summary>Login probe tap: "/qb" (no args) prints the count line.</summary>
public void ApplyQbProbe(List<string> lines)
{
RynthLog.Trace(LogCat.IltQuests, $"ApplyQbProbe(lines={lines.Count})");
foreach (string line in lines)
if (line.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase))
{
int colon = line.IndexOf(':');
if (colon > 0) _qbCount = IltParse.ParseLeadingLong(line.Substring(colon + 1));
}
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs) { }
public bool OnChat(string text) => false;
public void OnLogout()
{
_qbCompleted = Array.Empty<string>();
_qbIncomplete = Array.Empty<string>();
_qbCount = -1;
_qbStatus = "not loaded";
_qbGeneration = 0;
}
// ── UI (render thread) ──────────────────────────────────────────────────
/// <summary>The Quests tab's "Quest bonus (/qb)" section (collapsed header; ILT worlds only).</summary>
public void RenderSection()
{
if (ImGui.CollapsingHeader("Quest bonus (/qb)##qbwin")) RenderQb();
}
public void RenderQb()
{
if (_ctx.Options.IsOff(IltFeature.Qb))
{
ImGui.TextColored(IltStyle.ColTextMute, "/qb is disabled on this server.");
return;
}
if (ImGui.SmallButton("Load /qb list")) _ctx.Post(() => _ctx.Chat("[Mini Remote] " + RefreshQb()));
ImGui.SameLine();
long count = _qbCount;
SafeImGui.TextDisabled((count >= 0 ? $"QB count {IltParse.N0(count)} - " : "") + _qbStatus);
string filter = _ctx.State.Character.QbFilter;
ImGui.SetNextItemWidth(220);
if (ImGui.InputTextWithHint("##qbfilter", "filter flags", ref filter, 64u))
_ctx.State.Character.QbFilter = filter;
RenderQbList("Incomplete", _qbIncomplete, filter, IltStyle.ColAmber);
RenderQbList("Completed", _qbCompleted, filter, IltStyle.ColGreen);
}
private static void RenderQbList(string label, string[] items, string filter, Vector4 color)
{
var shown = filter.Length == 0 ? items : items.Where(i => i.Contains(filter, StringComparison.OrdinalIgnoreCase)).ToArray();
if (ImGui.TreeNode($"{label} ({shown.Length})##qb{label}"))
{
if (ImGui.SmallButton($"Copy##qbc{label}")) ImGui.SetClipboardText(string.Join(Environment.NewLine, shown));
foreach (string s in shown) SafeImGui.TextColored(color, s);
ImGui.TreePop();
}
}
}

View file

@ -0,0 +1,130 @@
// IltRingChain.cs - Infinite Leaftide's ring inscription chain (Gear tab > Rings), from UB-IT's
// ImbueSpellCraftDefinitions / SpellcraftInventoryPolicy. SilentKelpie's RynthAi Crafting > Rings
// (MiniRemote/Crafting/RingChain.cs), moved to RynthILT 2026-10-15: it is Leaftide-only.
//
// Step 1: Quill of Infliction used on a Trophy -> Enlightened Quill of Infliction
// Step 2: Enlightened Quill used on Ink of Partition -> partition quill
// Step 3: partition quill used on a Glyph -> "Inscription of ..." scroll
// Then each scroll is used on a ring / jewelry / weapon.
//
// Pure: ingredient matching (case-insensitive substrings with alternates and one exclude), the
// craft queue order and the scroll-to-target pairing. IltRingChainRunner does the using.
using System;
using System.Collections.Generic;
using System.Linq;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One ingredient: the first of <see cref="Names"/> found in an item's name, unless it also has <see cref="Exclude"/>.</summary>
internal sealed record IltRingIngredient(string Label, string[] Names, string Exclude = "");
/// <summary>One combine: <see cref="Tool"/> is used on <see cref="Target"/>.</summary>
/// <param name="Tier">1 quill + trophy, 2 + ink, 3 + glyph: the queue runs every tier-1 run first.</param>
/// <param name="ScrollMarkers">Step 3: the words the resulting inscription scroll's name carries.</param>
internal sealed record IltRingRecipe(string Id, int Tier, string Name, string Notes,
IltRingIngredient Tool, IltRingIngredient Target, string[] ScrollMarkers);
internal static class IltRingChain
{
/// <summary>Every inscription scroll's name has this.</summary>
public const string InscriptionMarker = "Inscription of";
/// <summary>Most runs of one recipe the tab queues.</summary>
public const int MaxRuns = 99;
private static readonly IltRingIngredient PartitionQuill = new("Enlightened Infliction Quill of Partition",
new[] { "Enlightened Infliction Quill of Partition", "Enlightened Quill of Infliction of Partition" });
private static IltRingRecipe Glyph(string id, string element, string scroll) => new(
id, 3, $"Step 3: {element} glyph - {scroll}",
$"Partition quill used on Glyph of {element} -> Inscription of {scroll} scroll.",
PartitionQuill,
// The full glyph name: a short one can match the wrong stack.
new IltRingIngredient($"Glyph of {element}", new[] { $"Glyph of {element}" }),
new[] { scroll, element });
/// <summary>The chain, in UB-IT's order.</summary>
public static readonly IltRingRecipe[] Recipes =
{
new("ring2_step1_quill_trophy", 1, "Step 1: Quill of Infliction + Trophy",
"Quill of Infliction used on a Trophy -> Enlightened Quill of Infliction.",
new IltRingIngredient("Quill of Infliction", new[] { "Quill of Infliction", "Infliction Quill" }, Exclude: "Enlightened"),
// Not plain "Trophy": scrolls and kits carry that word too.
new IltRingIngredient("Trophy", new[] { "Royal Summons", "Empyrean Trophy", "Summoning Gem" }),
Array.Empty<string>()),
new("ring2_step2_ink", 2, "Step 2: Enlightened Quill + Ink of Partition",
"Enlightened Quill of Infliction (from Step 1) used on Ink of Partition -> partition quill.",
new IltRingIngredient("Enlightened Quill of Infliction",
new[] { "Enlightened Quill of Infliction", "Enlightened Infliction Quill", "Enlightened Infliction Quill of" }, Exclude: "Partition"),
new IltRingIngredient("Ink of Partition", new[] { "Ink of Partition", "Partition Ink" }),
Array.Empty<string>()),
Glyph("ring2_glyph_bludgeoning", "Bludgeoning", "Tectonic Rifts"),
Glyph("ring2_glyph_lightning", "Lightning", "Eye of the Storm"),
Glyph("ring2_glyph_piercing", "Piercing", "Nuhmudira's Spines"),
Glyph("ring2_glyph_nether", "Nether", "Clouded Soul"),
Glyph("ring2_glyph_corrosion", "Corrosion", "Searing Disc"),
Glyph("ring2_glyph_frost", "Frost", "Halo of Frost"),
Glyph("ring2_glyph_slashing", "Slashing", "Horizon's Blades"),
Glyph("ring2_glyph_flame", "Flame", "Cassius' Ring of Fire"),
};
/// <summary>True when an item's name is this ingredient.</summary>
public static bool Matches(string? name, IltRingIngredient ing)
{
if (string.IsNullOrEmpty(name)) return false;
if (ing.Exclude.Length > 0 && name.IndexOf(ing.Exclude, StringComparison.OrdinalIgnoreCase) >= 0) return false;
foreach (string n in ing.Names)
if (n.Length > 0 && name.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0) return true;
return false;
}
/// <summary>
/// The craft queue: every Step 1 run, then every Step 2 run, then the glyphs, each tier in
/// definition order (a later tier's ingredients come out of the earlier one).
/// </summary>
public static List<IltRingRecipe> Expand(Func<string, int> runs)
{
var queue = new List<IltRingRecipe>();
foreach (var r in Recipes.OrderBy(r => r.Tier))
{
int n = Math.Clamp(runs(r.Id), 0, MaxRuns);
for (int i = 0; i < n; i++) queue.Add(r);
}
return queue;
}
/// <summary>The glyph recipe a scroll came from (null when its name has no known marker).</summary>
public static IltRingRecipe? GlyphOf(string? scrollName)
{
if (string.IsNullOrEmpty(scrollName)) return null;
foreach (var r in Recipes)
foreach (string m in r.ScrollMarkers)
if (scrollName.IndexOf(m, StringComparison.OrdinalIgnoreCase) >= 0) return r;
return null;
}
public static bool IsInscriptionScroll(string? name)
=> !string.IsNullOrEmpty(name) && name.IndexOf(InscriptionMarker, StringComparison.OrdinalIgnoreCase) >= 0;
/// <summary>The order scrolls are listed and used in: by glyph recipe id, unknown ones last by name.</summary>
public static string ScrollOrderKey(string? scrollName) => GlyphOf(scrollName)?.Id ?? "zzz_" + scrollName;
/// <summary>
/// Pairs scrolls with targets the way UB-IT does: scrolls by glyph recipe id (unknown ones
/// last, by name), targets by object id, one scroll per target.
/// </summary>
public static List<(int Scroll, int Target)> PairScrolls(IEnumerable<(int Id, string Name)> scrolls, IEnumerable<int> targets)
{
var ordered = scrolls
.OrderBy(s => ScrollOrderKey(s.Name), StringComparer.Ordinal)
.ThenBy(s => s.Id)
.ToList();
var pairs = new List<(int, int)>();
int i = 0;
foreach (int t in targets.Distinct().OrderBy(x => x))
{
if (i >= ordered.Count) break;
pairs.Add((ordered[i++].Id, t));
}
return pairs;
}
}

View file

@ -0,0 +1,557 @@
// IltRingChainRunner.cs - Crafts Infinite Leaftide's ring inscription chain and applies the scrolls
// (Gear tab > Rings). SilentKelpie's RynthAi RingChainRunner (MiniRemote/Crafting/), moved to
// RynthILT 2026-10-15 and run on the ILT Hub's context; its settings are the Gear state's
// (IltGearState.RingRuns, RingAnswerCraftDialog, RingAllowInCombat), saved with the Hub.
//
// Tick runs on the pump thread; Render on the render thread reads the volatile snapshots and
// posts the commands (IltHubContext.Post / Confirm).
// Crafting: the queue from IltRingChain.Expand, one combine at a time:
// 1. gates: peace mode (unless allowed in combat for servers with combat crafting), not busy,
// no other ILT pack job (the split-arrow imbuer);
// 2. find the tool and the target by name; a later step's ingredients come out of the earlier
// combine, so a missing one is looked for again for a while (inventory lag) before giving up;
// 3. arm the engine's confirmation answer (API v85; Yes: the player queued it) and use tool on
// target; without v85 (or with the answer off) the player clicks Yes in AC's dialog;
// 4. the combine is done when the tool or the target stack shrinks or the output shows up.
// No sign of it stops the job instead of retrying, so nothing is crafted twice.
// Scrolls: each "Inscription of ..." scroll is used on its target (the item selected in AC, or
// the carried jewelry paired the UB-IT way) and is done when it leaves the pack.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One line of the Rings scan: a recipe header (Found null) or an ingredient.</summary>
/// <param name="State">0 found, 1 comes from an earlier step, 2 missing.</param>
internal sealed record IltRingScanLine(string Text, string? Found, int State);
internal sealed class IltRingChainRunner : IIltFeature
{
private const uint ErrorYoureTooBusy = 0x1D;
private const long StepTimeoutMs = 15_000;
/// <summary>The player answers AC's own dialog: give them time.</summary>
private const long ManualTimeoutMs = 60_000;
private const long StepGapMs = 700;
private const long RetryDelayMs = 1_500;
private const int MaxBusyRetries = 3;
/// <summary>A missing ingredient is looked for this often and this many times (~10 s).</summary>
private const long LookAgainMs = 250;
private const int LookTries = 40;
private const long RunsViewMs = 1000;
private static readonly Regex CannotUse = new(@"^The .+ cannot be used on the .+\.$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private enum Mode { Idle, Craft, Apply }
private readonly IltHubContext _ctx;
/// <summary>True while another ILT job (the split-arrow imbuer) is using the pack.</summary>
private readonly Func<bool> _blocked;
// Job (pump thread)
private Mode _mode;
private List<IltRingRecipe> _queue = new();
private List<(int Scroll, int Target)> _pairs = new();
private int _index, _crafted, _lookTries, _busyRetries, _confSeq, _errSeq;
private bool _waiting, _manual;
private long _stepAt, _nextAt, _runsViewAt;
// Counts before the current combine (craft) / the scroll's stack (apply).
private long _toolBefore, _targetBefore, _outputBefore;
private int _scrollStackBefore;
// Render snapshots
private volatile string _status = "idle";
private volatile IltRingScanLine[] _scan = Array.Empty<IltRingScanLine>();
private volatile (int Id, string Name)[] _scrolls = Array.Empty<(int, string)>();
private volatile (int Id, string Name)[] _jewelry = Array.Empty<(int, string)>();
// Runs per recipe (IltRingChain.Recipes order), copied from the Gear state on the pump.
private volatile int[] _runsView = new int[IltRingChain.Recipes.Length];
private volatile bool _running;
public IltRingChainRunner(IltHubContext ctx, Func<bool> blocked)
{
_ctx = ctx;
_blocked = blocked;
}
public bool Running => _running;
public string Status => _status;
public IltRingScanLine[] ScanLines => _scan;
/// <summary>The inscription scrolls the last scan found.</summary>
public (int Id, string Name)[] Scrolls => _scrolls;
private RynthCoreHost Host => _ctx.Host;
private IltInventory Inv => _ctx.Inventory;
private IltGearState G => _ctx.State.Gear;
/// <summary>Pump thread: the saved run count for a recipe.</summary>
private int Runs(string id) => G.RingRuns.TryGetValue(id, out int n) ? n : 0;
/// <summary>Pump thread: sets a recipe's run count (0 removes it) and the render copy.</summary>
public void SetRuns(string id, int runs)
{
runs = Math.Clamp(runs, 0, IltRingChain.MaxRuns);
if (runs == 0) G.RingRuns.Remove(id);
else G.RingRuns[id] = runs;
PublishRuns();
}
private void PublishRuns()
{
var view = new int[IltRingChain.Recipes.Length];
for (int i = 0; i < view.Length; i++) view[i] = Runs(IltRingChain.Recipes[i].Id);
_runsView = view;
}
// ── Inventory ───────────────────────────────────────────────────────────
private IEnumerable<WorldObject> Carried() => Inv.Items().Where(w => !Inv.IsEquipped(w));
private WorldObject? Find(IltRingIngredient ing) => Carried().FirstOrDefault(w => IltRingChain.Matches(w.Name, ing));
private long Count(IltRingIngredient ing) => Carried().Where(w => IltRingChain.Matches(w.Name, ing)).Sum(w => (long)Inv.StackSize(w));
private long ScrollCount() => Carried().Where(w => IltRingChain.IsInscriptionScroll(w.Name)).Sum(w => (long)Inv.StackSize(w));
/// <summary>What a recipe makes, counted: Step 1 the enlightened quill, Step 2 the partition quill, Step 3 a scroll.</summary>
private long OutputCount(IltRingRecipe r) => r.Tier switch
{
1 => Count(IltRingChain.Recipes[1].Tool),
2 => Count(IltRingChain.Recipes[2].Tool),
_ => ScrollCount(),
};
// ── Scan ────────────────────────────────────────────────────────────────
/// <summary>
/// Lists every queued recipe's ingredients, marking the ones a later step only gets from an
/// earlier combine (UB-IT's "(after Step 1)"), the carried inscription scrolls and the carried
/// jewelry they can go on. Pump thread.
/// </summary>
public void Scan()
{
var lines = new List<IltRingScanLine>();
bool Stocked(int tier) => IltRingChain.Recipes
.Where(r => r.Tier == tier && Runs(r.Id) > 0)
.All(r => Find(r.Tool) != null && Find(r.Target) != null);
bool tier1 = Stocked(1), tier2 = Stocked(2);
bool any = false, blocking = false;
foreach (var r in IltRingChain.Recipes)
{
int runs = Runs(r.Id);
if (runs <= 0) continue;
any = true;
lines.Add(new IltRingScanLine($"{r.Name} x{runs}", null, 0));
foreach (var ing in new[] { r.Tool, r.Target })
{
var found = Find(ing);
if (found != null) { lines.Add(new IltRingScanLine(ing.Label, $"{found.Name} ({Count(ing)})", 0)); continue; }
string? later = r.Tier == 2 && !tier1 ? "(after Step 1)"
: r.Tier == 3 && !tier1 ? "(after Step 1)"
: r.Tier == 3 && !tier2 ? "(after Step 2)"
: null;
if (later == null) blocking = true;
lines.Add(new IltRingScanLine(ing.Label, later ?? "(not found)", later == null ? 2 : 1));
}
}
_scan = lines.ToArray();
RefreshScrolls();
_status = !any ? "set how many times to craft at least one recipe"
: blocking ? "missing ingredients are marked (not found)"
: "ready: Create runs every Step 1, then Step 2, then Step 3";
}
private void RefreshScrolls()
{
_scrolls = Carried().Where(w => IltRingChain.IsInscriptionScroll(w.Name))
.Select(w => (w.Id, w.Name ?? string.Empty))
.OrderBy(s => IltRingChain.ScrollOrderKey(s.Item2), StringComparer.Ordinal)
.ToArray();
_jewelry = Carried().Where(w => w.ObjectClass == AcObjectClass.Jewelry)
.Select(w => (w.Id, w.Name ?? string.Empty))
.OrderBy(j => j.Id)
.ToArray();
}
// ── Job control (pump thread) ───────────────────────────────────────────
/// <summary>Crafts the queued recipes (after the tab's confirm).</summary>
public void Create()
{
if (_running) return;
if (_blocked()) { _status = "the split-arrow imbuer is running"; return; }
var queue = IltRingChain.Expand(Runs);
if (queue.Count == 0) { _status = "set how many times to craft at least one recipe"; return; }
Begin(Mode.Craft);
_queue = queue;
_status = $"crafting {queue.Count} combine(s)";
RynthLog.Write(LogCat.IltGear, $"[Rings] create, {queue.Count} combine(s)");
}
/// <summary>Uses one scroll on the item selected in AC.</summary>
public void ApplyToSelected(int scrollId)
{
uint sel = Host.GetSelectedItemId();
if (sel == 0) { _status = "select the ring or item in AC first"; return; }
if (unchecked((int)sel) == scrollId) { _status = "the scroll itself is selected: select the ring or item"; return; }
ApplyPairs(new List<(int, int)> { (scrollId, unchecked((int)sel)) });
}
/// <summary>Pairs the carried scrolls with these items (the carried jewelry) and uses them.</summary>
public void ApplyToItems(IReadOnlyList<int> targetIds)
{
RefreshScrolls();
if (_scrolls.Length == 0) { _status = "no inscription scroll in the pack (name has \"Inscription of\")"; return; }
if (targetIds.Count == 0) { _status = "no jewelry carried (worn items aren't inscribed)"; return; }
ApplyPairs(IltRingChain.PairScrolls(_scrolls, targetIds));
}
private void ApplyPairs(List<(int Scroll, int Target)> pairs)
{
if (_running) return;
if (_blocked()) { _status = "the split-arrow imbuer is running"; return; }
if (pairs.Count == 0) { _status = "nothing to apply"; return; }
Begin(Mode.Apply);
_pairs = pairs;
_status = $"applying {pairs.Count} inscription(s)";
RynthLog.Write(LogCat.IltGear, $"[Rings] apply {pairs.Count} inscription(s)");
}
private void Begin(Mode mode)
{
_mode = mode;
_index = 0;
_crafted = 0;
_lookTries = 0;
_busyRetries = 0;
_waiting = false;
_nextAt = 0;
_running = true;
}
public void Stop(string why)
{
if (_waiting && Host.HasConfirmationAnswers) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0);
_mode = Mode.Idle;
_waiting = false;
_running = false;
_queue = new List<IltRingRecipe>();
_pairs = new List<(int, int)>();
_status = why;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void OnLogout()
{
Stop("idle");
_scan = Array.Empty<IltRingScanLine>();
_scrolls = Array.Empty<(int, string)>();
_jewelry = Array.Empty<(int, string)>();
}
public void Tick(long nowMs)
{
if (nowMs - _runsViewAt >= RunsViewMs)
{
// A profile load replaces the Gear state: follow it.
_runsViewAt = nowMs;
PublishRuns();
}
if (_mode == Mode.Idle) return;
if (_waiting) { Wait(nowMs); return; }
if (nowMs < _nextAt) return;
if (!G.RingAllowInCombat && !Inv.InPeaceMode) { _status = "waiting for peace mode"; return; }
if (Inv.IsBusy) return;
if (_mode == Mode.Craft) NextCombine(nowMs);
else NextScroll(nowMs);
}
private void NextCombine(long nowMs)
{
if (_index >= _queue.Count)
{
Stop($"done - {_crafted} combine(s)");
RefreshScrolls();
RynthLog.Write(LogCat.IltGear, $"[Rings] done, {_crafted} combine(s)");
return;
}
var r = _queue[_index];
var tool = Find(r.Tool);
var target = Find(r.Target);
if (tool == null || target == null)
{
string label = tool == null ? r.Tool.Label : r.Target.Label;
if (++_lookTries <= LookTries)
{
_nextAt = nowMs + LookAgainMs;
_status = $"{r.Name}: looking for {label}";
return;
}
Stop($"{r.Name}: no {label} in the pack");
return;
}
_lookTries = 0;
_toolBefore = Count(r.Tool);
_targetBefore = Count(r.Target);
_outputBefore = OutputCount(r);
if (!Use(tool, target, $"Rings: {r.Name} ({_index + 1}/{_queue.Count})"))
{
Stop($"{r.Name}: the use request didn't go out");
return;
}
string ask = _manual ? " - click Yes in AC's craft dialog" : "";
_status = $"{r.Name} ({_index + 1}/{_queue.Count}): {tool.Name} on {target.Name}{ask}";
}
private void NextScroll(long nowMs)
{
if (_index >= _pairs.Count)
{
Stop($"done - {_crafted} inscription(s) applied");
RefreshScrolls();
return;
}
var (scrollId, targetId) = _pairs[_index];
var scroll = Inv.Cache?[scrollId];
var target = Inv.Cache?[targetId];
if (scroll == null || target == null)
{
// UB-IT moves on past a pair whose scroll or item is gone.
_status = $"inscription {_index + 1}: the scroll or the item is gone - skipped";
_index++;
_nextAt = nowMs + StepGapMs;
return;
}
if (Inv.IsEquipped(target)) { Stop($"{target.Name} is equipped: take it off to inscribe it"); return; }
_scrollStackBefore = Inv.StackSize(scroll);
if (!Use(scroll, target, $"Rings: {scroll.Name} on {target.Name}"))
{
Stop("the use request didn't go out");
return;
}
string ask = _manual ? " - click Yes in AC's dialog" : "";
_status = $"inscription {_index + 1}/{_pairs.Count}: {scroll.Name} on {target.Name}{ask}";
}
/// <summary>Arms the dialog answer (Yes: the player asked for this) and uses source on target.</summary>
private bool Use(WorldObject source, WorldObject target, string why)
{
_manual = !(G.RingAnswerCraftDialog && Host.HasConfirmationAnswers
&& Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, (int)StepTimeoutMs) == 1);
_confSeq = Host.TryGetLastConfirmation(out int cs, out _, out _, out _, out _) ? cs : 0;
_errSeq = Host.TryGetLastWeenieError(out int es, out _, out _, out _) ? es : 0;
if (!Host.UseOnFor(unchecked((uint)source.Id), unchecked((uint)target.Id), "IltRings", why, UseKind.Asked))
{
if (!_manual) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0);
return false;
}
_waiting = true;
_stepAt = Environment.TickCount64;
return true;
}
private void Wait(long nowMs)
{
if (Host.TryGetLastConfirmation(out int seq, out uint type, out int pct, out int outcome, out _)
&& seq != _confSeq && type == RynthCoreHost.ConfirmationKind.CraftInteraction)
{
_confSeq = seq;
if (outcome == RynthCoreHost.ConfirmationOutcome.Declined) { Stop("the craft dialog was answered No"); return; }
if (outcome is RynthCoreHost.ConfirmationOutcome.Shown or RynthCoreHost.ConfirmationOutcome.SendFailed)
{
_manual = true;
_status = $"click Yes in AC's craft dialog ({(pct >= 0 ? pct + "%" : "chance not shown")})";
}
}
if (Host.TryGetLastWeenieError(out int es, out uint error, out _, out _) && es != _errSeq)
{
_errSeq = es;
// Busy: the server did nothing, so the same combine can go again.
if (error == ErrorYoureTooBusy && ++_busyRetries <= MaxBusyRetries)
{
_waiting = false;
_nextAt = nowMs + RetryDelayMs;
_status = $"server says busy - trying again ({_busyRetries}/{MaxBusyRetries})";
return;
}
Stop($"the server refused it (error 0x{error:X})");
return;
}
if (Done()) { Next(nowMs); return; }
if (nowMs - _stepAt > (_manual ? ManualTimeoutMs : StepTimeoutMs))
Stop(_manual ? "no answer to AC's dialog - stopped" : "no result seen - stopped (check the pack before going on)");
}
/// <summary>The current combine or inscription went through.</summary>
private bool Done()
{
if (_mode == Mode.Craft)
{
var r = _queue[_index];
return Count(r.Tool) < _toolBefore || Count(r.Target) < _targetBefore || OutputCount(r) > _outputBefore;
}
var scroll = Inv.Cache?[_pairs[_index].Scroll];
return scroll == null || Inv.StackSize(scroll) < _scrollStackBefore;
}
private void Next(long nowMs)
{
_waiting = false;
_busyRetries = 0;
_crafted++;
_index++;
_nextAt = nowMs + StepGapMs;
}
/// <summary>"cannot be used on" ends the job: the names didn't match what the server expects. Never eaten.</summary>
public bool OnChat(string text)
{
if (!_waiting || string.IsNullOrEmpty(text)) return false;
if (CannotUse.IsMatch(text)) Stop(text);
return false;
}
// ── UI (render thread) ──────────────────────────────────────────────────
/// <summary>The ring inscription chain: runs per recipe, Scan / Create / Stop, then the scrolls.</summary>
public void Render()
{
ImGui.TextDisabled("Quill of Infliction -> Enlightened Quill -> partition quill -> glyph -> Inscription scroll -> ring.");
int[] runsView = _runsView;
if (ImGui.BeginTable("##ringrecipes", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp))
{
ImGui.TableSetupColumn("Runs", ImGuiTableColumnFlags.WidthFixed, 100);
ImGui.TableSetupColumn("Recipe");
for (int i = 0; i < IltRingChain.Recipes.Length; i++)
{
var r = IltRingChain.Recipes[i];
ImGui.PushID(r.Id);
ImGui.TableNextRow();
ImGui.TableNextColumn();
int n = i < runsView.Length ? runsView[i] : 0;
ImGui.SetNextItemWidth(90);
if (ImGui.InputInt("##runs", ref n, 1))
{
string id = r.Id;
int runs = Math.Clamp(n, 0, IltRingChain.MaxRuns);
var shown = (int[])runsView.Clone();
shown[i] = runs;
_runsView = shown; // shown at once; the pump saves it and republishes
_ctx.Post(() => SetRuns(id, runs));
}
ImGui.TableNextColumn();
ImGui.TextUnformatted(r.Name);
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(r.Notes);
ImGui.PopID();
}
ImGui.EndTable();
}
bool answer = G.RingAnswerCraftDialog, combat = G.RingAllowInCombat;
if (ImGui.Checkbox("Answer the craft dialog##rings", ref answer)) G.RingAnswerCraftDialog = answer;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Answers AC's craft confirmation Yes for each combine you queued (needs RynthCore plugin API v85).\nOff, or on an older RynthCore: click Yes in AC's dialog yourself.");
ImGui.SameLine();
if (ImGui.Checkbox("Allow in combat mode##rings", ref combat)) G.RingAllowInCombat = combat;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Only for servers that allow crafting in combat mode.");
bool running = Running;
bool blocked = _blocked();
ImGui.BeginDisabled(running);
if (ImGui.Button("Scan##rings")) _ctx.Post(Scan);
ImGui.SameLine();
ImGui.BeginDisabled(blocked);
if (ImGui.Button("Create##rings"))
{
int[] view = _runsView;
int total = IltRingChain.Expand(id =>
{
int k = Array.FindIndex(IltRingChain.Recipes, x => x.Id == id);
return k >= 0 && k < view.Length ? view[k] : 0;
}).Count;
_ctx.Confirm("Rings chain", $"Craft {total} combine(s)?\n\nEvery Step 1 run goes first, then Step 2, then Step 3.\nThe ingredients are used up.",
Create, "Create");
}
ImGui.EndDisabled();
ImGui.EndDisabled();
ImGui.SameLine();
ImGui.BeginDisabled(!running);
if (ImGui.Button("Stop##rings")) _ctx.Post(() => Stop("stopped by player"));
ImGui.EndDisabled();
ImGui.SameLine();
if (blocked && !running) ImGui.TextColored(IltStyle.ColAmber, "the split-arrow imbuer is running");
else SafeImGui.TextDisabled(Status);
var lines = ScanLines;
if (lines.Length > 0 && ImGui.BeginTable("##ringscan", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.Borders | ImGuiTableFlags.SizingStretchProp))
{
foreach (var l in lines)
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
if (l.Found == null) { SafeImGui.TextColored(IltStyle.ColTeal, l.Text); continue; }
ImGui.TextUnformatted(" " + l.Text);
ImGui.TableNextColumn();
if (l.State == 0) ImGui.TextUnformatted(l.Found);
else if (l.State == 1) SafeImGui.TextDisabled(l.Found);
else SafeImGui.TextColored(IltStyle.ColAmber, l.Found);
}
ImGui.EndTable();
}
ImGui.Separator();
RenderScrolls(running || blocked);
}
/// <summary>The carried inscription scrolls: one to the selected item, or all to the carried jewelry.</summary>
private void RenderScrolls(bool busy)
{
ImGui.TextColored(IltStyle.ColTeal, "Inscription scrolls");
var scrolls = Scrolls;
if (scrolls.Length == 0) { ImGui.TextDisabled("None carried (Scan to look again)."); return; }
ImGui.BeginDisabled(busy);
foreach (var (id, name) in scrolls)
{
ImGui.PushID(id);
if (ImGui.SmallButton("Apply to selected"))
{
int scrollId = id;
string scrollName = name;
_ctx.Confirm("Ring inscription", $"Use {scrollName} on the item selected in AC?",
() => ApplyToSelected(scrollId), "Apply");
}
ImGui.SameLine();
ImGui.TextUnformatted(name);
ImGui.PopID();
}
// UB-IT pairs the scrolls with a scan's items; here the carried (not worn) jewelry.
var jewelry = _jewelry;
var targets = jewelry.Select(j => j.Id).ToList();
ImGui.BeginDisabled(targets.Count == 0);
if (ImGui.Button($"Apply all to the carried jewelry ({targets.Count})"))
{
int pairs = Math.Min(targets.Count, scrolls.Length);
_ctx.Confirm("Ring inscriptions", $"Use {pairs} inscription scroll(s) on the carried jewelry, one each?",
() => ApplyToItems(targets), "Apply");
}
ImGui.EndDisabled();
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
SafeImGui.SetTooltip("Scrolls in glyph order go on the jewelry in your pack (not worn) in id order (UB-IT's pairing).\n"
+ (jewelry.Length == 0 ? "No jewelry carried (Scan to look again)."
: string.Join("\n", jewelry.Select(j => j.Name))));
ImGui.EndDisabled();
}
}

View file

@ -0,0 +1,121 @@
// IltRingEvade.cs — Infinite Leaftide's Empyrean Handler lethal ring: hear it, and have RynthAi jump clear.
// Moved out of RynthAi's CombatManager 2026-10-20 (Silentkelpie's PR 12): the Handler is ACECustom
// content, so the detection and its setting are RynthILT's; RynthAi keeps the generic back-away it
// does on request (RynthAi.Hub BackAwayFrom: face the danger, run-back jump, hold attacks until the
// jump settles, re-engage the same target; only while its macro runs with combat on).
//
// ACECustom's Handler emote: "The handler briefly channels infused Empyrean hatred to release a lethal
// ring." The ring can't be melee-evaded; inside its cast radius the character dies. On that line, when
// an Empyrean Handler is near, ask RynthAi to back away from the nearest one (12 yards, or Ring Range
// when RynthAi's is larger). One request per HandlerRingCooldownMs.
// Setting: IltHubState.Combat.HandlerRingEvade (on by default; the ILT settings view, "/ilt settings").
using System;
using RynthCore.Loot;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltRingEvade : IIltFeature
{
internal const string ChannelHint = "channels infused Empyrean hatred to release a lethal ring";
internal const string ChannelStart = "The handler briefly channels";
internal const string HandlerName = "Empyrean Handler";
/// <summary>Yards: the Handler's lethal ring is treated as at least this wide (RynthAi widens it to Ring Range).</summary>
internal const float DangerYards = 12f;
/// <summary>Back-jump charge (ms): run-back + jump must clear about the ring's radius.</summary>
internal const int JumpHoldMs = 750;
internal const long CooldownMs = 4_000;
private readonly IltHubContext _ctx;
private long _lastRequestAt = long.MinValue;
public IltRingEvade(IltHubContext ctx) => _ctx = ctx;
/// <summary>What the last ring line did (for the log and the tests).</summary>
public string LastOutcome { get; private set; } = string.Empty;
/// <summary>
/// True when <paramref name="text"/> is the Handler's channel line (not a player repeating it).
/// The channel is an Emote (0x0C), which counts as player speech elsewhere, so it is anchored on
/// the phrase that starts the line; mid-line only for a chat type that can't be player speech.
/// </summary>
internal static bool IsChannelLine(string? text, int chatType)
{
if (string.IsNullOrEmpty(text)) return false;
bool anchored =
ChatSource.StartsWithMarker(text, ChannelStart, StringComparison.OrdinalIgnoreCase)
|| (ChatSource.StartsWithMarker(text, "The handler", StringComparison.OrdinalIgnoreCase)
&& text.IndexOf(ChannelHint, StringComparison.OrdinalIgnoreCase) >= 0);
if (anchored) return true;
// Mid-line only when the type is clearly not player speech (some clients strip "The ").
if (chatType is ChatSource.Speech or ChatSource.Tell or ChatSource.OutgoingTell or ChatSource.Channel
or ChatSource.ChannelSend or ChatSource.Allegiance or ChatSource.Fellowship)
return false;
if (text.IndexOf(ChannelHint, StringComparison.OrdinalIgnoreCase) < 0) return false;
return text.IndexOf(" says,", StringComparison.OrdinalIgnoreCase) < 0
&& text.IndexOf(" tells you,", StringComparison.OrdinalIgnoreCase) < 0;
}
/// <summary>
/// A chat line with its type (pump thread; IltHubController.OnChat, ILT only). On the Handler's
/// channel line asks RynthAi to back away from the nearest Handler. Never eats the line.
/// </summary>
public void OnChatLine(string text, int chatType)
{
if (!_ctx.State.Combat.HandlerRingEvade || !IsChannelLine(text, chatType)) return;
long now = IltHubContext.NowMs;
if (_lastRequestAt != long.MinValue && now - _lastRequestAt < CooldownMs) return;
if (!TryFindNearestHandler(out int handlerId, out double dist))
{
Outcome("Handler lethal-ring channel heard, but no Empyrean Handler is nearby: no jump.");
return;
}
_lastRequestAt = now;
int r = _ctx.Ai.BackAwayFrom(unchecked((uint)handlerId), DangerYards, JumpHoldMs);
Outcome(r switch
{
RynthAiHub.BackAwayStarted => $"Empyrean Handler lethal ring: RynthAi backs away from it ({dist:0.0} m).",
RynthAiHub.BackAwayOutside => $"Empyrean Handler lethal ring: the Handler is {dist:0.0} m away, outside the ring; staying put.",
RynthAiHub.BackAwayUnknownObject => "Empyrean Handler lethal ring: RynthAi has no position for the Handler; no jump.",
RynthAiHub.BackAwayJumpRefused => "Empyrean Handler lethal ring: in range, but RynthAi's back-jump did not start.",
int.MinValue => "Empyrean Handler lethal ring: " + RynthAiClient.NotLoaded + " (the back-away is RynthAi's).",
_ => "Empyrean Handler lethal ring: RynthAi isn't fighting (macro or combat off), so it doesn't take the keyboard.",
});
}
private void Outcome(string text)
{
LastOutcome = text;
RynthLog.Write(LogCat.IltHub, "[RingEvade] " + text);
}
/// <summary>The nearest Empyrean Handler the client knows (a creature with that in its name).</summary>
private bool TryFindNearestHandler(out int id, out double dist)
{
id = 0;
dist = double.MaxValue;
var objects = _ctx.Inventory.Cache;
int me = unchecked((int)_ctx.Inventory.PlayerId);
if (me == 0) return false;
foreach (var wo in objects.GetLandscape())
{
if (wo == null || wo.ObjectClass != AcObjectClass.Monster) continue;
if (wo.Name.IndexOf(HandlerName, StringComparison.OrdinalIgnoreCase) < 0) continue;
double d = objects.Distance(me, wo.Id);
if (d >= dist) continue;
dist = d;
id = wo.Id;
}
return id != 0;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs) { }
/// <summary>Unused: the controller passes the chat type (OnChatLine).</summary>
public bool OnChat(string text) => false;
public void OnLogout() => _lastRequestAt = long.MinValue;
}

View file

@ -0,0 +1,81 @@
// IltSalvage.cs - Infinite Leaftide's own tinkering salvage, for the Mini Remote's Crafting tab.
//
// Served through RynthILT's "RynthServer.Profile" JSON (ProfileInterface.cs, the "salvage" list),
// which RynthAi's Crafting tab shows under "Server tinkering" on ILT; RynthAi itself knows no
// server's recipes. Taken from UB-IT's LeaftideImbueHelper via SilentKelpie (his RynthAi Crafting
// tab, rynth/RynthSuite PR 12, moved here 2026-10-15): the weapon crit lines (Yellow Garnet,
// Turquoise, White Quartz, Abyssal-Touched Gems, Tourmaline, Wool), Tiger Eye on missile weapons,
// Leather as the post-cap tink, the jewelry rating salvages (Silver, Copper, Green Jade,
// Tourmaline, and Serpentine + Steel sharing a cap of 10) and the trinket tiers (Diamond, Ruby,
// Gromnie Hide, Pyreal, prepared on Ammunition). ILT's recipes live in its database, so their
// chances are the server's: the Crafting runner reads the confirmation's percent.
using RynthCore.Plugin.ServerPack;
namespace RynthCore.Plugin.RynthILT.Hub;
internal static class IltSalvage
{
/// <summary>
/// Leaftide trinkets (compass, goggles, scarab, watch, puzzle box, tops): jewelry that takes the
/// Trinkets bench's recipes (UB-IT's IsLeaftideTrinketJewelry; RynthAi's TinkerCatalog.IsTrinket until
/// 2026-10-20). Sent in the profile's "trinkets" (RynthServer.Profile).
/// </summary>
internal static readonly string[] TrinketNames = { "compass", "goggles", "scarab", "watch", "puzzle box", "top" };
/// <summary>"top" but not "topaz".</summary>
internal static readonly string[] TrinketExcept = { "topaz" };
// MaterialType (131) ids.
private const int Wool = 8, BlackGarnet = 15, Diamond = 20, GreenJade = 24, Ruby = 38, TigerEye = 42, Tourmaline = 43,
Turquoise = 44, WhiteQuartz = 46, YellowGarnet = 48, Leather = 52, GromnieHide = 54, Copper = 59, Pyreal = 62,
Silver = 63, Steel = 64, Serpentine = 71;
// ILT's flag ints on the item: 2 = that salvage is on.
public const int IntJewelCopper = 370, IntJewelGreenJade = 371, IntJewelSilver = 374, IntJewelTourmaline = 375;
public const int IntTrinketDiamond = 384, IntTrinketRuby = 385, IntTrinketGromnie = 386, IntTrinketPyreal = 387;
/// <summary>Steel and Serpentine stack on ILT jewelry, at most this many combined.</summary>
public const string JewelryStackGroup = "jewelry-stack";
public const int JewelryStackCap = 10;
private const string Once = "once", Tink = "tink";
private const string PostCap = "100% tink once the 10 ordinary tinks are on";
public static readonly ServerSalvage[] Rows =
{
new("melee", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70),
new("melee", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80),
new("melee", WhiteQuartz, "Cleaving (no tink slot)", Once, UsesTinkSlot: false, Order: 90),
new("melee", BlackGarnet, "Crit line (bag of Abyssal-Touched Gems)", Once, NameMatch: "Abyssal", Order: 100),
new("melee", Tourmaline, "Crit line (no tink slot)", Once, UsesTinkSlot: false, Order: 104),
new("melee", Wool, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 108),
new("melee", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true),
new("missile", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70),
new("missile", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80),
new("missile", BlackGarnet, "Crit line (bag of Abyssal-Touched Gems)", Once, NameMatch: "Abyssal", Order: 100),
new("missile", Tourmaline, "Crit line (no tink slot)", Once, UsesTinkSlot: false, Order: 104),
new("missile", Wool, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 108),
new("missile", TigerEye, "+missile defense bonus", Tink, Order: 230),
new("missile", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true),
new("caster", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70),
new("caster", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80),
new("caster", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true),
// ILT keeps these in their own ints (370-376) with their own cap, not the 10 tinker slots.
new("jewelry", Silver, "+1 critical damage rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelSilver, Order: 10),
new("jewelry", Copper, "+1 damage rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelCopper, Order: 20),
new("jewelry", GreenJade, "+1 damage resist rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelGreenJade, Order: 30),
new("jewelry", Tourmaline, "+1 critical damage resist rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelTourmaline, Order: 40),
new("jewelry", Serpentine, "+1 critical rating (stacks with Steel, 10 max)", Tink, UsesTinkSlot: false, Order: 50,
StackGroup: JewelryStackGroup, StackCap: JewelryStackCap),
new("jewelry", Steel, "Steel stack tier (stacks with Serpentine, 10 max)", Tink, UsesTinkSlot: false, Order: 60,
StackGroup: JewelryStackGroup, StackCap: JewelryStackCap),
// UB-IT's trinket imbues, in its order: Diamond, Ruby, Gromnie Hide, Pyreal.
new("trinkets", Diamond, "Trinket tier: Diamond", Once, UsesTinkSlot: false, AppliedInt: IntTrinketDiamond, Prepared: true, Order: 10),
new("trinkets", Ruby, "Trinket tier: Ruby", Once, UsesTinkSlot: false, AppliedInt: IntTrinketRuby, Prepared: true, Order: 20),
new("trinkets", GromnieHide, "Trinket tier: Gromnie Hide", Once, UsesTinkSlot: false, AppliedInt: IntTrinketGromnie, Prepared: true, Order: 30),
new("trinkets", Pyreal, "Trinket tier: Pyreal", Once, UsesTinkSlot: false, AppliedInt: IntTrinketPyreal, Prepared: true, Order: 40),
};
}

View file

@ -0,0 +1,144 @@
// IltSections.cs - The Infinite Leaftide tabs of RynthAi's Mini Remote and the Guardian panel.
// Originally SilentKelpie's ILT Hub sections (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Banking, Gear, Charms, Games and Vaulted Dungeons are Mini Remote tabs: RynthAi's MiniRemoteHud draws the tab bar
// (after its Remote, Pets and Crafting tabs) and asks RynthILT for each tab's body (RynthILT.Hub
// GetTabs / RenderTab); "/ra hub open <section>" picks one, and with RynthCore's sections rail
// RynthAi lists them as "section:<tab>" views (Inventory). Guardian is a RynthCore ILT panel
// instead (the bar's ILT button, next to Bounties; "/rc guardian"), drawn by this plugin through
// RynthPluginRenderEmbed("guardian"). The Pets tab is RynthAi's (every server: summoning essences
// aren't ILT's); quests are RynthOracle's.
//
// Character was a Mini Remote tab until 2026-10-13. It moved out:
// the character overview and session -> RynthOracle's Character tab ("/ro character");
// the ILT session rates -> RynthCore's Mini Remote "Session Stats" section
// (RynthILT's own surface "section:ilt-rates");
// the force-server override -> RynthCore Options > Diagnostics only.
// Its names still parse, so old links and commands land on the new home (MovedCommand). Charms and
// Banking are Infinite Leaftide's own screens and stay RynthILT's tabs.
using System;
using System.Numerics;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>ILT sections: the Mini Remote's ILT tabs, the one that moved out, then the Guardian panel.</summary>
internal enum IltSection
{
/// <summary>Moved out (2026-10-13): RynthOracle's Character tab and the Session Stats section.</summary>
Character,
Banking,
Gear,
Games,
/// <summary>
/// Vaulted Dungeons keeper (portal-recall gem + kill-client). A Mini Remote tab on ILT worlds only,
/// and only while its "Vaulted Dungeons" master switch (/ilt settings, Settings > Navigation) is on.
/// </summary>
VaultedDungeons,
/// <summary>Registry charms (acquired / status / tier / server) and the Guardian Hand.</summary>
Charms,
// Keep Guardian last.
Guardian,
}
internal static class IltSections
{
/// <summary>The ILT tabs, in tab-bar order (RynthAi puts them after its own tabs).</summary>
public static readonly IltSection[] Tabs =
{
IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games, IltSection.VaultedDungeons,
};
/// <summary>The Mini Remote's own tab (the remote itself): its tab id.</summary>
public const string RemoteTab = "";
/// <summary>RynthOracle's Character tab: the character overview and this session.</summary>
public const string OracleCharacterCommand = "/ro character";
public static string Label(IltSection s) => s switch
{
IltSection.Character => "Character",
IltSection.Banking => "Banking",
IltSection.Gear => "Gear",
IltSection.Games => "Games",
IltSection.VaultedDungeons => "Vaulted Dungeons",
IltSection.Charms => "Charms",
IltSection.Guardian => "Guardian",
_ => s.ToString(),
};
/// <summary>
/// The section's tab id: saved as RynthAi's HudState.MiniRemoteTab and sent by the engine's
/// dashboard ("/ra hub tab &lt;id&gt;", "/rc miniremote tab &lt;id&gt;"). TryParse reads it back.
/// </summary>
public static string TabId(IltSection s) => s switch
{
IltSection.Character => "character",
IltSection.Banking => "banking",
IltSection.Gear => "gear",
IltSection.Games => "games",
IltSection.VaultedDungeons => "vaulted",
IltSection.Charms => "charms",
IltSection.Guardian => "guardian",
_ => s.ToString().ToLowerInvariant(),
};
/// <summary>True for the sections drawn as Mini Remote tabs (Banking, Gear, Charms, Games, Vaulted Dungeons).</summary>
public static bool IsTab(IltSection s) => s is IltSection.Banking or IltSection.Gear or IltSection.Charms or IltSection.Games
or IltSection.VaultedDungeons;
/// <summary>
/// Where a section that moved out of the Mini Remote lives now, as the chat command that opens
/// it; null for a section that is still RynthILT's (a tab or the Guardian panel).
/// </summary>
public static string? MovedCommand(IltSection s) => s switch
{
IltSection.Character => OracleCharacterCommand,
_ => null,
};
/// <summary>"quests" / "pets" (and their aliases): not ILT sections (RynthAi's Pets tab, RynthOracle's quests).</summary>
public static bool IsUniversalTabName(string text) => (text ?? string.Empty).Trim().ToLowerInvariant() switch
{
"quests" or "quest" or "pets" or "pet" => true,
_ => false,
};
/// <summary>Parses a "/ra hub open" section name (a few aliases accepted).</summary>
public static bool TryParse(string text, out IltSection section)
{
switch ((text ?? string.Empty).Trim().ToLowerInvariant())
{
case "character": case "char": case "rates": section = IltSection.Character; return true;
case "banking": case "bank": section = IltSection.Banking; return true;
case "gear": section = IltSection.Gear; return true;
case "games": case "game": section = IltSection.Games; return true;
case "vaulted": case "vaulteddungeons": case "vaulted-dungeons":
section = IltSection.VaultedDungeons; return true;
case "charms": case "charm": section = IltSection.Charms; return true;
case "guardian": case "temple": case "riddle": section = IltSection.Guardian; return true;
default: section = IltSection.Gear; return false;
}
}
/// <summary>
/// Size of a Mini Remote tab's body (the old section window's default size): the tab draws in a
/// child this big, and the Mini Remote (or the engine window hosting it) fits to it.
/// </summary>
public static Vector2 TabSize(IltSection section) => section switch
{
IltSection.Banking => new Vector2(560, 520),
IltSection.Gear => new Vector2(560, 520),
IltSection.Charms => new Vector2(560, 520),
IltSection.Games => new Vector2(520, 440),
IltSection.VaultedDungeons => new Vector2(360, 420),
_ => new Vector2(520, 440),
};
/// <summary>"show" / "hide" / "toggle" (anything else toggles) applied to the current state.</summary>
public static bool Resolve(string mode, bool current) => (mode ?? string.Empty).ToLowerInvariant() switch
{
"show" or "on" or "open" => true,
"hide" or "off" or "close" => false,
_ => !current,
};
}

View file

@ -0,0 +1,376 @@
// IltServerOptions.cs — Per-feature enable bits for the ILT Hub, read from the server.
// Originally SilentKelpie's ILT Hub (RynthAi); moved to RynthILT 2026-10-13.
//
// UB gated every Leaftide tool on a single test (WorldName == "InfiniteLeaftide" or a
// Force checkbox). That lies on shards where the operator turned Powerball, /myquests or
// a charm off. This module instead keeps one tri-state bit per feature:
// * World identity: ServerFeatureGate (RynthILT's server list, or this character's
// override / the Hub's ForceLeaftideFeatures) decides whether we even ASK — it never
// switches a feature on by itself.
// * Everything is decided on the Rynth side: the server is never asked for a feature list
// (ACECustom has none; "/ilt features" prints "Coming Soon"). IltFeatureCatalog's ILT
// profile says what the server runs, and these bits only record what the server returned:
// * Login probe: one pass of read-only commands (/bank, /aug, /qb, /pets, /shinies, /xp,
// /pb, /blackjack, /fblackjack, /clap with no args). Replies are eaten.
// /enl is NEVER probed — it opens the enlightenment confirmation dialog.
// * Passive: explicit server refusals seen in chat at any time flip a bit to Off
// ("Powerball lottery is not currently active", "myquests is not currently enabled", ...),
// and lines only an enabled feature sends flip it On (a summon-time pyreal refill).
// Unknown bits are treated as OFF by anything that spends currency or runs automation.
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthILT.IltSettingsView;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>Feature keys used by the gate table.</summary>
internal static class IltFeature
{
public const string Bank = "bank";
public const string Aug = "aug";
public const string Enl = "enl";
public const string Qb = "qb";
public const string Pets = "pets";
public const string Shinies = "shinies";
public const string Xp = "xp";
public const string Blackjack = "blackjack";
public const string FBlackjack = "fblackjack";
public const string Powerball = "powerball";
public const string Quests = "quests";
public const string Clap = "clap";
public const string PetRefill = "pet_refill";
public const string UniversalMastery = "universal_mastery";
public const string RequireComps = "require_spell_comps";
public const string PetBond = "pet_bond";
public const string PetPotency = "pet_potency";
/// <summary>Key for a per-charm "enabled" bit, e.g. Charm("Guardian Hand") → "charm:guardianhand".</summary>
public static string Charm(string charmName)
{
var chars = (charmName ?? string.Empty).Where(char.IsLetterOrDigit).Select(char.ToLowerInvariant).ToArray();
return "charm:" + new string(chars);
}
}
/// <summary>Tri-state feature value.</summary>
internal enum IltTri { Unknown = -1, Off = 0, On = 1 }
internal sealed class IltServerOptions
{
private readonly RynthCoreHost _host;
private readonly IltChatCapture _capture;
private readonly IltHubState _state;
private readonly Action<string> _chat;
private readonly Func<IltSettings?> _settings;
/// <summary>Feeds probe replies to features that can reuse them (e.g. /bank → Banking balances).</summary>
public Action<string, IltChatResult>? ProbeReplyTap;
private bool _refreshInFlight;
private int _probesOutstanding;
private long _loginAt;
private bool _loginRefreshDone;
/// <summary>Wait this long after login before the one-shot refresh so chat/world are settled.</summary>
private const long LoginRefreshDelayMs = 6000;
/// <summary>
/// Upper bound on waiting for the world name. The engine hook / launch-context file can report
/// it well after the 6 s delay (late inject, Decal coexistence); deciding "not ILT" on an empty
/// name would leave every feature bit Unknown and the Hub hidden for the whole session.
/// </summary>
private const long WorldNameWaitMs = 60000;
public IltServerOptions(RynthCoreHost host, IltChatCapture capture, IltHubState state, Action<string> chat,
Func<IltSettings?>? settings = null)
{
_host = host;
_capture = capture;
_state = state;
_chat = chat;
_settings = settings ?? (() => null);
}
// ── Identity ────────────────────────────────────────────────────────────
/// <summary>World name as reported by the engine login hook (empty if unknown).</summary>
public string WorldName
{
get
{
if (_host.HasGetWorldName && _host.TryGetWorldName(out string n) && !string.IsNullOrWhiteSpace(n))
return n.Trim();
return _state.ServerOptions.WorldName ?? string.Empty;
}
}
/// <summary>RynthCore's id for Infinite Leaftide in its server verdicts.</summary>
public const string EngineServerId = "ilt";
/// <summary>
/// RynthCore (2026.10.5.47+) decides whether this is Infinite Leaftide: one world check for
/// the engine and every plugin, with its per-character override ("/rc server ilt on|off|auto").
/// True once its first verdict has arrived (IltEngineVerdict).
/// </summary>
public static bool EngineDecides => IltEngineVerdict.Active.HasValue;
/// <summary>
/// RynthILT's own verdict: the world name is in the server list (IltSettings), or this
/// character's "Treat this world as ILT" is on (ServerFeatureGate). This is what the status
/// export reports to the engine, which adds it to its own detection (never echo the engine's
/// verdict back, or it would latch on).
/// </summary>
public bool IsIltLikeWorldLocal
{
get
{
if (_state.ForceLeaftideFeatures) return true;
IltSettings? s;
try { s = _settings(); } catch { s = null; }
return ServerFeatureGate.IsEnabled(WorldName, s, _state.ForceLeaftideFeatures);
}
}
/// <summary>
/// True when the world is (or is declared to be) an ACECustom/ILT shard. With a RynthCore
/// that sends server verdicts, its verdict (which already includes ours, IsIltLikeWorldLocal,
/// unless this character's override is off); otherwise our own.
/// </summary>
public bool IsIltLikeWorld
{
get
{
bool? engine = IltEngineVerdict.Active;
return engine ?? IsIltLikeWorldLocal;
}
}
/// <summary>True while the login probe is running.</summary>
public bool IsRefreshing => _refreshInFlight;
public string Source => _state.ServerOptions.Source;
public DateTime LastRefreshUtc => _state.ServerOptions.LastRefreshUtc;
// ── Bit access ──────────────────────────────────────────────────────────
public IltTri Get(string key)
=> _state.ServerOptions.Bits.TryGetValue(key, out int v) ? (IltTri)Math.Clamp(v, -1, 1) : IltTri.Unknown;
/// <summary>True only when the server positively reported the feature as available.</summary>
public bool IsOn(string key) => Get(key) == IltTri.On;
/// <summary>True when the server positively reported the feature as unavailable.</summary>
public bool IsOff(string key) => Get(key) == IltTri.Off;
public void Set(string key, IltTri value)
{
// Every feature gate reads these bits, so each transition is traced (IltOptions).
IltTri old = Get(key);
_state.ServerOptions.Bits[key] = (int)value;
if (old != value) RynthLog.Trace(LogCat.IltOptions, $"feature '{key}': {old} -> {value}");
}
/// <summary>At least one feature bit is On (Hub window shows only then, unless Force is on).</summary>
public bool AnyFeatureOn => _state.ServerOptions.Bits.Values.Any(v => v == 1);
/// <summary>All known bits for the status display.</summary>
public IReadOnlyList<KeyValuePair<string, int>> SnapshotBits()
=> _state.ServerOptions.Bits.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase).ToList();
// ── Lifecycle ───────────────────────────────────────────────────────────
/// <summary>Called at login: schedules the one-shot refresh (never a recurring timer).</summary>
public void OnLoginComplete()
{
_loginAt = Environment.TickCount64;
_loginRefreshDone = false;
}
/// <summary>
/// Pump-thread tick: fires the delayed login refresh once. While the world name is still
/// unknown it keeps checking (a cheap string compare per tick) until the name arrives or
/// WorldNameWaitMs expires; only a known non-ILT world, or the timeout, ends the wait.
/// </summary>
public void Tick()
{
if (_loginRefreshDone || _loginAt == 0) return;
long sinceLogin = Environment.TickCount64 - _loginAt;
if (sinceLogin < LoginRefreshDelayMs) return;
if (IsIltLikeWorld)
{
_loginRefreshDone = true;
RynthLog.Event(LogEvents.IltWorldCheck,
$"world check: '{WorldName}' is ILT-like (force={_state.ForceLeaftideFeatures}) - refreshing server options");
Refresh(manual: false);
return;
}
// World not reported yet: try again next tick rather than concluding "not ILT". RynthCore's
// verdict trails the world name by up to a second (its push), and before its first push
// there is none: keep checking for the same window rather than conclude early.
if ((string.IsNullOrEmpty(WorldName) || EngineDecides || !IltEngineVerdict.Pushed)
&& sinceLogin < WorldNameWaitMs)
return;
_loginRefreshDone = true;
RynthLog.Event(LogEvents.IltWorldCheck,
$"world check: '{WorldName}' is not ILT-like - login refresh skipped (waited {sinceLogin / 1000}s)");
}
/// <summary>
/// Runs the probe refresh. Manual refreshes report progress in chat; the login refresh is
/// silent.
/// </summary>
public void Refresh(bool manual)
{
if (_refreshInFlight)
{
if (manual) _chat("[Mini Remote] Server options refresh already running.");
return;
}
if (!IsIltLikeWorld)
{
if (manual)
_chat(EngineDecides
? "[Mini Remote] RynthCore doesn't treat this world as Infinite Leaftide (/rc server ilt on forces it for this character; /rc server names ilt add <name> adds the world)."
: "[Mini Remote] This world is not in the Server Features list (Settings > Misc: add it, or tick the override).");
return;
}
_refreshInFlight = true;
_state.ServerOptions.WorldName = WorldName;
RynthLog.Event(LogEvents.IltOptionsRefreshStart, $"refresh start (manual={manual}, world='{WorldName}')");
if (manual) _chat("[Mini Remote] Refreshing server options...");
_state.ServerOptions.Source = "probe";
RunProbes(manual);
}
// ── Probe ───────────────────────────────────────────────────────────────
/// <summary>One read-only probe: command, reply recogniser, feature key.</summary>
private readonly record struct Probe(string Key, string Command, Func<string, bool> IsReply);
private static readonly Probe[] Probes =
{
new(IltFeature.Bank, "/bank", t => t.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase)
|| t.Contains("not permitted to use bank", StringComparison.OrdinalIgnoreCase)),
new(IltFeature.Aug, "/aug", t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase)
|| IltParse.AugLine.IsMatch(t)),
new(IltFeature.Qb, "/qb", t => t.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("[QB]", StringComparison.OrdinalIgnoreCase)),
new(IltFeature.Pets, "/pets", t => t.Contains("Your Pet Log", StringComparison.OrdinalIgnoreCase)
|| IltParse.RosterLine.IsMatch(t) || t.Contains("Professor Ruggan", StringComparison.OrdinalIgnoreCase)),
new(IltFeature.Shinies, "/shinies", t => t.Contains("Your Shiny Log", StringComparison.OrdinalIgnoreCase)
|| IltParse.RosterLine.IsMatch(t) || t.Contains("Shiny creatures", StringComparison.OrdinalIgnoreCase)),
new(IltFeature.Xp, "/xp", t => t.StartsWith("[XP]", StringComparison.OrdinalIgnoreCase)),
new(IltFeature.Powerball, "/pb", t => t.StartsWith("[Powerball]", StringComparison.OrdinalIgnoreCase)),
new(IltFeature.Blackjack, "/blackjack", IsParamErrorOr("blackjack", "bet amount")),
new(IltFeature.FBlackjack,"/fblackjack", IsParamErrorOr("blackjack", "bet amount")),
new(IltFeature.Clap, "/clap", IsParamErrorOr("clap", "AutoCraftingEnabled")),
};
/// <summary>Recognises ACE's wrong-parameter-count reply (command exists) or a keyword reply.</summary>
private static Func<string, bool> IsParamErrorOr(string keyword, string keyword2) => t =>
t.StartsWith("Invalid parameter count", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("Usage:", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("@" + keyword, StringComparison.OrdinalIgnoreCase)
|| t.Contains(keyword2, StringComparison.OrdinalIgnoreCase)
|| (t.Contains(keyword, StringComparison.OrdinalIgnoreCase) && !t.StartsWith("<Tell", StringComparison.OrdinalIgnoreCase));
private void RunProbes(bool manual)
{
var todo = Probes.ToList();
// /enl is never probed (it pops the enlightenment confirmation). On an ILT-like
// world the command is part of ACECustom, so it is assumed present.
Set(IltFeature.Enl, IltTri.On);
_probesOutstanding = todo.Count;
if (_probesOutstanding == 0) { CompleteRefresh(manual); return; }
foreach (var p in todo)
{
var probe = p;
_capture.Enqueue(new IltChatRequest
{
Command = probe.Command,
IsResponseLine = probe.IsReply,
// /aug: banner alone must not end the probe before Creature:/Item: lines arrive.
ArmsIdle = probe.Key == IltFeature.Aug ? t => IltParse.AugLine.IsMatch(t) : null,
IdleEndMs = 1500,
FirstLineTimeoutMs = 8000,
Eat = true,
OnComplete = r =>
{
// Unknown command → Off. Any recognised reply → On. Silence → leave Unknown.
if (r.UnknownCommand) Set(probe.Key, IltTri.Off);
else if (r.Lines.Count > 0) Set(probe.Key, IltTri.On);
RynthLog.Trace(LogCat.IltOptions, $"probe {probe.Command}: lines={r.Lines.Count} unknown={r.UnknownCommand} timedOut={r.TimedOut}");
try { ProbeReplyTap?.Invoke(probe.Key, r); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltOptions, ex, $"probe tap {probe.Key}"); }
if (--_probesOutstanding <= 0) CompleteRefresh(manual);
},
});
}
}
private void CompleteRefresh(bool manual)
{
_refreshInFlight = false;
_state.ServerOptions.LastRefreshUtc = DateTime.UtcNow;
int on = _state.ServerOptions.Bits.Values.Count(v => v == 1);
int off = _state.ServerOptions.Bits.Values.Count(v => v == 0);
// Building the per-bit list is skipped unless the event is actually going to be recorded.
if (RynthLog.IsEventEnabled(LogEvents.IltOptionsRefreshed))
RynthLog.Event(LogEvents.IltOptionsRefreshed, $"options refreshed via {Source} (manual={manual}): {on} on, {off} off - " +
string.Join(" ", _state.ServerOptions.Bits.Select(b => $"{b.Key}={b.Value}")));
if (manual)
_chat($"[Mini Remote] Server options refreshed via {Source}: {on} on, {off} off.");
}
// ── Passive refusals ────────────────────────────────────────────────────
/// <summary>
/// Watches every chat line for explicit server refusals (bit Off) and for lines only an
/// enabled feature sends (bit On). Cheap substring checks; runs on the pump thread.
/// </summary>
public void OnChatLine(string text)
{
if (text.Contains("Powerball lottery is not currently active", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.Powerball, IltTri.Off);
else if (text.Contains("\"myquests\" is not currently enabled", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.Quests, IltTri.Off);
else if (text.Contains("\"qb\" is not currently enabled", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.Qb, IltTri.Off);
else if (text.Contains("must have received the AutoCraftingEnabled quest stamp", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.Clap, IltTri.Off);
else if (text.Contains("Universal Summoning Mastery is not enabled on this server", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.UniversalMastery, IltTri.Off);
else if (text.Contains("Auto-Rebuff Charm is currently disabled globally", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.Charm("Auto-Rebuff"), IltTri.Off);
else if (text.Contains("not permitted to use bank commands", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.Bank, IltTri.Off);
else if (IsPyrealRefillLine(text))
Set(IltFeature.PetRefill, IltTri.On);
}
/// <summary>
/// ACECustom's summon-time refill messages (PetDevice.TryApplyPyrealAutoRefillBeforeSummon). The
/// server sends them only while pet_device_pyreal_auto_refill_enabled is on, so any of them
/// proves the refill is on even when the profile says it's off.
/// </summary>
internal static bool IsPyrealRefillLine(string text)
=> text.Contains("charge on your summoning essence", StringComparison.OrdinalIgnoreCase)
|| text.Contains("pyreals to auto-replenish your summoning essence", StringComparison.OrdinalIgnoreCase);
/// <summary>Records what the login /myquests refresh learned (called by the Hub after the Meta tracker finishes).</summary>
public void NoteQuestTrackerOutcome(bool disabled, int recordCount)
{
if (disabled) Set(IltFeature.Quests, IltTri.Off);
else if (recordCount > 0) Set(IltFeature.Quests, IltTri.On);
}
}

View file

@ -0,0 +1,291 @@
// IltSessionRates.cs — Session earnings / per-hour rates for Infinite Leaftide: the coins, pyreals and
// item conversions RynthCore's Mini Remote "Session Stats" section shows under "Server: Infinite
// Leaftide" (surface "section:ilt-rates", 2026-10-13; it was the ILT Character tab before).
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Sources (all passive — nothing is sent to the server except the optional bank refresh
// the Banking tab already does):
// XP, luminance (total, last 5 min, allegiance pass-up) and kills: RynthAi's Mini Remote
// session stats (RynthAi.Hub SessionStats) — RynthTracker's SessionStats code, so this
// table, the Mini Remote and the Tracker panel count them the same way (2026-10-11).
// Without RynthAi those rows are left out.
// Coins positive bank Enlightened Coins deltas + carried coin (WCID 300004) gains.
// Pyreals positive bank pyreal deltas + carried pyreal (WCID 273) gains; MMD = 250k.
// Items gains of each item in the item→coin conversion table (carried count),
// converted to potential coins with ItemsPerConversion / CoinsPerConversion.
// A deposit or withdrawal only moves money between pack and bank: while Banking reports one
// (MovingMoney) the coin and pyreal baselines follow along without counting a gain.
using System;
using System.Collections.Generic;
using System.Linq;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltSessionRates : IIltFeature
{
private const long PyrealsPerMmd = 250_000;
private const long SampleIntervalMs = 5000;
private const long RowsIntervalMs = 1000;
private const string PassUpLabel = " pass-up";
private readonly IltHubContext _ctx;
private DateTime _start = DateTime.UtcNow;
private long _coins;
private long _pyreals;
// Carried-item baselines (last seen counts) for gain tracking.
private long _lastInvCoins = -1;
private long _lastInvPyreals = -1;
private readonly Dictionary<string, long> _lastItemCounts = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, long> _itemGains = new(StringComparer.OrdinalIgnoreCase);
private long _lastSampleAt;
private long _lastRowsAt;
// Render snapshot.
private volatile RateRow[] _rows = Array.Empty<RateRow>();
// Shared = one of RynthAi's session stats rows (XP, luminance, kills), which the Session Stats
// section already shows above this table; the embedded view leaves those out.
private sealed record RateRow(string Label, string Total, string PerHour, bool Shared = false);
/// <summary>Coin and pyreal per-hour figures for the Mini Remote HUD (rebuilt every sample).</summary>
public sealed record RateSummary(double CoinsPerHour, double PyrealsPerHour);
private static readonly RateSummary EmptySummary = new(0, 0);
private volatile RateSummary _summary = EmptySummary;
/// <summary>Latest coin / pyreal summary (safe from the render thread).</summary>
public RateSummary Summary => _summary;
/// <summary>When the coin / pyreal session (or the last Reset) started.</summary>
public DateTime SessionStartUtc => _start;
public IltSessionRates(IltHubContext ctx) => _ctx = ctx;
/// <summary>True while money moves between pack and bank (set by the controller from Banking). Pump thread.</summary>
public Func<bool>? MovingMoney { get; set; }
private bool Moving => MovingMoney?.Invoke() ?? false;
/// <summary>Banking hook: bank balance changed (pump thread).</summary>
public void OnBankBalanceChanged(string key, long oldValue, long newValue)
{
RynthLog.Trace(LogCat.IltRates, $"balance {key}: {oldValue} -> {newValue}");
// The first read after login only establishes the baseline (old value is the stale cache).
if (_lastSampleAt == 0) return;
if (Moving) return; // a deposit, not income
long delta = newValue - oldValue;
if (delta <= 0) return; // spending / sending isn't income
if (key == "EnlightenedCoins") _coins += delta;
else if (key == "Pyreals") _pyreals += delta;
}
/// <summary>Coins, pyreals and item gains start over (login, or with <see cref="ResetAll"/>).</summary>
public void Reset()
{
RynthLog.Trace(LogCat.IltRates, $"Reset()");
_start = DateTime.UtcNow;
_coins = _pyreals = 0;
_lastInvCoins = _lastInvPyreals = -1;
_lastItemCounts.Clear();
_itemGains.Clear();
_lastSampleAt = 0;
_lastRowsAt = 0;
_summary = EmptySummary;
}
/// <summary>The player's reset (this tab, the Mini Remote): coins here and the shared session stats together. Pump thread.</summary>
public void ResetAll()
{
Reset();
_ctx.Ai.ResetSessionStats();
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
FollowSharedSession();
// The shared stats move every 0.5 s; their rows refresh each second, coins every 5 s.
if (nowMs - _lastSampleAt < SampleIntervalMs)
{
if (nowMs - _lastRowsAt >= RowsIntervalMs) { _lastRowsAt = nowMs; BuildRows(); }
return;
}
_lastSampleAt = nowMs;
_lastRowsAt = nowMs;
var inv = _ctx.Inventory;
long coinGain = Gain(ref _lastInvCoins, inv.CountByWcid(IltInventory.WcidEnlightenedCoin));
long pyrealGain = Gain(ref _lastInvPyreals, inv.CountByWcid(IltInventory.WcidPyreal));
// A withdrawal: the baselines moved, nothing earned.
if (!Moving)
{
_coins += coinGain;
_pyreals += pyrealGain;
}
// ToArray: the render thread edits this table.
foreach (var conv in _ctx.State.Character.ItemConversions.ToArray())
{
if (string.IsNullOrWhiteSpace(conv.ItemName)) continue;
long count = inv.CountByName(conv.ItemName);
long last = _lastItemCounts.TryGetValue(conv.ItemName, out long l) ? l : -1;
long gain = Gain(ref last, count);
_lastItemCounts[conv.ItemName] = last;
if (gain > 0) _itemGains[conv.ItemName] = (_itemGains.TryGetValue(conv.ItemName, out long g) ? g : 0) + gain;
}
BuildRows();
}
private long _sharedStartTicks; // RynthAi's session start as last seen (0 = not yet)
/// <summary>
/// The coins / pyreals start over with RynthAi's shared session (its Reset XP, or a session that
/// restarted): one clock for both, without RynthAi telling RynthILT. Pump thread.
/// </summary>
private void FollowSharedSession()
{
if (!_ctx.Ai.TryGetSessionStats(out SessionStatsV1 s) || s.StartUtcTicks == 0) return;
if (_sharedStartTicks != 0 && s.StartUtcTicks > _sharedStartTicks)
{
RynthLog.Trace(LogCat.IltRates, "RynthAi's session restarted: coins and pyreals start over too");
Reset();
}
_sharedStartTicks = s.StartUtcTicks;
}
/// <summary>Positive change since the last sample; the first sample only sets the baseline.</summary>
private static long Gain(ref long last, long current)
{
if (last < 0) { last = current; return 0; }
long d = current - last;
last = current;
return d > 0 ? d : 0;
}
// Luminance chat goes to RynthAi's session stats (its OnChatWindowText).
public bool OnChat(string text) => false;
public void OnLogout() => Reset();
// ── Rows ────────────────────────────────────────────────────────────────
private void BuildRows()
{
double hours = Math.Max((DateTime.UtcNow - _start).TotalHours, 1.0 / 3600);
_summary = new RateSummary(_coins / hours, _pyreals / hours);
var rows = new List<RateRow>();
if (_ctx.Ai.TryGetSessionStats(out SessionStatsV1 s))
{
rows.Add(new RateRow("XP", IltParse.Compact(s.Xp), IltParse.Compact(s.XpPerHour), Shared: true));
rows.Add(new RateRow("Luminance", IltParse.Compact(s.Lum), IltParse.Compact(s.LumPerHour), Shared: true));
// Per hour at the last five minutes' pace.
rows.Add(new RateRow(" last 5 min", IltParse.Compact(s.LumLast5Min), IltParse.Compact(s.LumLast5Min * 12.0), Shared: true));
if (s.PassUpTracked != 0)
rows.Add(new RateRow(PassUpLabel, IltParse.Compact(s.LumPassUp), IltParse.Compact(s.PassUpPerHour), Shared: true));
rows.Add(new RateRow("Kills", s.Kills.ToString(), s.KillsPerHour.ToString("0"), Shared: true));
}
rows.Add(new RateRow("Enlightened Coins", IltParse.Compact(_coins), IltParse.Compact(_coins / hours)));
rows.Add(new RateRow("Pyreals", IltParse.Compact(_pyreals), IltParse.Compact(_pyreals / hours)));
rows.Add(new RateRow(" as MMD", (_pyreals / (double)PyrealsPerMmd).ToString("0.0"), (_pyreals / (double)PyrealsPerMmd / hours).ToString("0.0")));
double potentialCoins = 0;
foreach (var conv in _ctx.State.Character.ItemConversions.ToArray())
{
if (!_itemGains.TryGetValue(conv.ItemName, out long gained) || gained == 0) continue;
double coins = conv.ItemsPerConversion > 0 ? gained / (double)conv.ItemsPerConversion * conv.CoinsPerConversion : 0;
potentialCoins += coins;
rows.Add(new RateRow(" " + conv.ItemName, IltParse.N0(gained), IltParse.Compact(gained / hours)));
}
if (potentialCoins > 0)
rows.Add(new RateRow("Potential coins (items)", potentialCoins.ToString("0"), (potentialCoins / hours).ToString("0.0")));
_rows = rows.ToArray();
}
/// <summary>What the pass-up figure is (shared with the Mini Remote's Stats).</summary>
public const string PassUpTooltip =
"Luminance that reached your bank without a \"You've banked\" line: your vassals' pass-up.\n"
+ "Fellowship and Zone Share splits arrive the same silent way and are included.";
// ── UI (render thread) ──────────────────────────────────────────────────
/// <param name="extrasOnly">
/// True in the Mini Remote's Session Stats section: RynthAi's XP / luminance / kills rows are
/// drawn there already (one session), so only the ILT coins, pyreals and items are listed.
/// </param>
public void Render(bool extrasOnly = false)
{
// The session clock is RynthAi's session stats' (it and the coins reset together).
var start = _ctx.Ai.TryGetSessionStats(out SessionStatsV1 v) && v.SessionSeconds > 0 && v.StartUtcTicks > 0
? new DateTime(v.StartUtcTicks, DateTimeKind.Utc) : _start;
SafeImGui.TextDisabled($"Session {IltParse.Duration(DateTime.UtcNow - start)}");
ImGui.SameLine();
if (ImGui.SmallButton("Reset##rates")) _ctx.Post(ResetAll);
if (ImGui.BeginTable("##iltrates", 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV))
{
ImGui.TableSetupColumn("Metric");
ImGui.TableSetupColumn("Session");
ImGui.TableSetupColumn("Per hour");
ImGui.TableHeadersRow();
foreach (var r in _rows)
{
if (extrasOnly && r.Shared) continue;
ImGui.TableNextRow();
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Label);
if (ReferenceEquals(r.Label, PassUpLabel) && ImGui.IsItemHovered()) SafeImGui.SetTooltip(PassUpTooltip);
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Total);
ImGui.TableNextColumn(); SafeImGui.TextColored(IltStyle.ColTeal, r.PerHour);
}
ImGui.EndTable();
}
if (ImGui.TreeNode("Item -> coin conversions"))
{
RenderConversionEditor();
ImGui.TreePop();
}
}
private string _newItemName = string.Empty;
private void RenderConversionEditor()
{
var list = _ctx.State.Character.ItemConversions;
int remove = -1;
for (int i = 0; i < list.Count; i++)
{
var c = list[i];
ImGui.PushID(i);
ImGui.TextUnformatted(c.ItemName);
ImGui.SameLine(220);
int items = c.ItemsPerConversion, coins = c.CoinsPerConversion;
ImGui.SetNextItemWidth(70);
if (ImGui.InputInt("items", ref items, 0)) c.ItemsPerConversion = Math.Max(1, items);
ImGui.SameLine();
ImGui.SetNextItemWidth(70);
if (ImGui.InputInt("coins", ref coins, 0)) c.CoinsPerConversion = Math.Max(0, coins);
ImGui.SameLine();
if (ImGui.SmallButton("x")) remove = i;
ImGui.PopID();
}
if (remove >= 0)
{
var victim = list[remove];
_ctx.Post(() => list.Remove(victim));
}
ImGui.SetNextItemWidth(200);
ImGui.InputTextWithHint("##newconv", "exact item name", ref _newItemName, 96u);
ImGui.SameLine();
if (ImGui.SmallButton("Add") && _newItemName.Trim().Length > 0
&& !list.Any(c => c.ItemName.Equals(_newItemName.Trim(), StringComparison.OrdinalIgnoreCase)))
{
var added = new IltItemConversion { ItemName = _newItemName.Trim(), ItemsPerConversion = 100, CoinsPerConversion = 0 };
_ctx.Post(() => list.Add(added));
_newItemName = string.Empty;
}
}
}

View file

@ -0,0 +1,95 @@
// IltSettings.cs - RynthILT's own settings (every character): which world names are Infinite
// Leaftide. Lives in %APPDATA%\RynthCore\RynthILT\settings.json.
//
// The list was RynthAi's Settings > Misc "Server Features" (FeatureServerNames, saved with each
// RynthAi profile). RynthILT keeps one list for every character; the first time a character
// logs in with RynthILT, IltMigration folds that character's RynthAi list into this one.
// Edited with "/ilt servers <list>" (the Character tab's editor went with the tab, 2026-10-13;
// RynthCore Options > Diagnostics lists the world names RynthCore uses).
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
public sealed class IltSettings
{
public int SchemaVersion = 1;
/// <summary>World-name patterns that count as Infinite Leaftide ('*' wildcard, case-insensitive).</summary>
public List<string> ServerNames = new(ServerFeatureGate.DefaultServerNames);
/// <summary>The shared RynthAi files (Hub profiles, aug costs) were copied over once.</summary>
public bool SharedFilesMigrated;
/// <summary>
/// RynthILT character folders whose copy from RynthAi failed part-way (IltMigration). Until it
/// succeeds the Hub writes nothing there (a fresh file would shadow the RynthAi original and
/// stop it ever being copied); the copy is retried at each login and every few minutes.
/// </summary>
public List<string> PendingCharacterMigrations = new();
}
/// <summary>Loads and saves <see cref="IltSettings"/>; a broken or missing file reads as the defaults.</summary>
internal static class IltSettingsStore
{
public const string FileName = "settings.json";
/// <summary>Overridable for the tests.</summary>
public static string Folder = RynthILTPlugin.SettingsRoot;
public static string FilePath => Path.Combine(Folder, FileName);
public static IltSettings Load()
{
try
{
if (File.Exists(FilePath))
{
var s = JsonSerializer.Deserialize(File.ReadAllText(FilePath), IltHubJsonContext.Default.IltSettings);
if (s != null)
{
s.ServerNames = ServerFeatureGate.ParseList(string.Join(",", s.ServerNames ?? new List<string>()));
if (s.ServerNames.Count == 0) s.ServerNames = new List<string>(ServerFeatureGate.DefaultServerNames);
return s;
}
}
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {FilePath}"); }
return new IltSettings();
}
public static void Save(IltSettings settings)
{
try
{
string json = JsonSerializer.Serialize(settings, IltHubJsonContext.Default.IltSettings);
DataWriteGuard.TrySave("RynthILT's settings", FilePath, () =>
{
Directory.CreateDirectory(Folder);
string tmp = FilePath + ".tmp";
File.WriteAllText(tmp, json);
File.Move(tmp, FilePath, overwrite: true);
});
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {FilePath}"); }
}
}
// Source-generated System.Text.Json only (NativeAOT; never reflection-serialize plugin types:
// the reflection cache keeps the old plugin generation alive across a hot reload).
[JsonSerializable(typeof(IltSettings))]
[JsonSerializable(typeof(IltHubState))]
[JsonSerializable(typeof(List<IltBankTransaction>), TypeInfoPropertyName = "IltBankTransactionList")]
[JsonSerializable(typeof(IltAugCostFile))]
[JsonSerializable(typeof(IltLegacyProfileFlags))]
[JsonSerializable(typeof(IltLegacyMiniRemote))]
[JsonSerializable(typeof(IltLegacyHuds))]
[JsonSourceGenerationOptions(
WriteIndented = true,
IncludeFields = true,
PropertyNameCaseInsensitive = true)]
internal partial class IltHubJsonContext : JsonSerializerContext { }

View file

@ -0,0 +1,115 @@
// IltSigilChain.cs - The Enlightenment Sigil craft chain for /enl 301-325 (ACECustom tier 5:
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
// T - 5 sigils and T x 2B luminance per target level T). Every craft is one plus one makes one:
// Enlightened Coin + Ancient Yalani Trinket = Ascension Coin
// Life Splitter + Plant = Lifebloom Resin
// Lifebloom Resin + Necrolytic Extract = Lifeblood Elixir
// Lifeblood Elixir + Ascension Coin = Enlightenment Sigil
// Pure math (no host access) so the planner and the host tests share it. Mirrors UB-IT's
// EnlightenmentSigilChainPolicy.
using System;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>Stack counts of every item in the sigil chain.</summary>
internal sealed class IltSigilStock
{
public long Sigils, AscensionCoins, LifebloodElixirs, LifebloomResins;
public long EnlightenedCoins, YalaniTrinkets, NecrolyticExtracts, LifeSplitters, Plants;
public IltSigilStock Clone() => (IltSigilStock)MemberwiseClone();
}
/// <summary>
/// What a sigil demand still needs after using stock from the top of the chain down. "ToCraft" are
/// crafts left to do (intermediates); "Short" are raw materials left to get.
/// </summary>
internal sealed class IltSigilShortfall
{
public long SigilsNeeded, SigilsToCraft, AscensionToCraft, ElixirsToCraft, ResinsToCraft;
/// <summary>E-coins the Ascension Coin crafts use (before stock).</summary>
public long CoinsForCraft;
public long CoinsShort, TrinketsShort, ExtractsShort, SplittersShort, PlantsShort;
/// <summary>Stock (with the whole chain) covers every sigil.</summary>
public bool Covered => CoinsShort == 0 && TrinketsShort == 0 && ExtractsShort == 0 && SplittersShort == 0 && PlantsShort == 0;
}
internal static class IltSigilChain
{
public const int FirstTarget = 301;
public const int LastTarget = 325;
// Item names (ACECustom ships no WCIDs for these yet, so they are counted by name).
public const string AscensionCoin = "Ascension Coin";
public const string YalaniTrinket = "Ancient Yalani Trinket";
public const string LifeSplitter = "Life Splitter";
public const string Plant = "Plant";
public const string LifebloomResin = "Lifebloom Resin";
public const string NecrolyticExtract = "Necrolytic Extract";
public const string LifebloodElixir = "Lifeblood Elixir";
public static bool IsSigilTarget(int t) => t >= FirstTarget && t <= LastTarget;
/// <summary>Sigils for target levels current+1 .. target that fall inside 301-325 (T - 5 each).</summary>
public static long SigilsForRange(int current, int target)
{
long total = 0;
for (int t = Math.Max(current + 1, FirstTarget); t <= Math.Min(target, LastTarget); t++)
total += Math.Max(0, t - 5);
return total;
}
/// <summary>Shortfall for <paramref name="sigilsNeeded"/>: sigils first, then coins / elixirs, then resins, then raws.</summary>
public static IltSigilShortfall Shortfall(long sigilsNeeded, IltSigilStock stock)
{
var s = new IltSigilShortfall { SigilsNeeded = Math.Max(0, sigilsNeeded) };
if (s.SigilsNeeded == 0) return s;
stock ??= new IltSigilStock();
s.SigilsToCraft = Short(s.SigilsNeeded, stock.Sigils);
s.AscensionToCraft = Short(s.SigilsToCraft, stock.AscensionCoins);
s.ElixirsToCraft = Short(s.SigilsToCraft, stock.LifebloodElixirs);
s.CoinsForCraft = s.AscensionToCraft;
s.CoinsShort = Short(s.AscensionToCraft, stock.EnlightenedCoins);
s.TrinketsShort = Short(s.AscensionToCraft, stock.YalaniTrinkets);
s.ResinsToCraft = Short(s.ElixirsToCraft, stock.LifebloomResins);
s.ExtractsShort = Short(s.ElixirsToCraft, stock.NecrolyticExtracts);
s.SplittersShort = Short(s.ResinsToCraft, stock.LifeSplitters);
s.PlantsShort = Short(s.ResinsToCraft, stock.Plants);
return s;
}
/// <summary>Sigils the stock can make: finished sigils plus the scarcer of the two craft paths.</summary>
public static long Fulfillable(IltSigilStock stock)
{
if (stock == null) return 0;
long coins = stock.AscensionCoins + Math.Min(stock.EnlightenedCoins, stock.YalaniTrinkets);
long resins = stock.LifebloomResins + Math.Min(stock.LifeSplitters, stock.Plants);
long elixirs = stock.LifebloodElixirs + Math.Min(resins, stock.NecrolyticExtracts);
return stock.Sigils + Math.Min(coins, elixirs);
}
/// <summary>
/// Splits the e-coin pool between Ascension Coin crafts (served first) and token conversion.
/// <paramref name="coinsNeeded"/> is what is still to get for both.
/// </summary>
public static void EcoinDemand(long coinsHave, long coinsForSigils, long tokensShort, int coinsPerToken,
out long tokensFromCoins, out long tokensStill, out long coinsNeeded)
{
long rate = Math.Max(1, coinsPerToken);
long have = Math.Max(0, coinsHave), sigil = Math.Max(0, coinsForSigils), tok = Math.Max(0, tokensShort);
tokensFromCoins = Math.Min(tok, Math.Max(0, have - sigil) / rate);
tokensStill = tok - tokensFromCoins;
coinsNeeded = Math.Max(0, sigil - have) + tokensStill * rate;
}
/// <summary>True for a chain item name (stack names may be plural; "Plant" must be the whole name).</summary>
public static bool NameIs(string itemName, string chainName)
{
string n = (itemName ?? string.Empty).Trim();
return n.Equals(chainName, StringComparison.OrdinalIgnoreCase)
|| n.Equals(chainName + "s", StringComparison.OrdinalIgnoreCase);
}
private static long Short(long demand, long have) => Math.Max(0, demand - Math.Max(0, have));
}

View file

@ -0,0 +1,210 @@
// IltSplitArrows.cs — Split-arrow imbuer (Gear tab, P2).
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// ILT missile weapons carry a split-arrow count (int 9031). Each White Quartz salvage
// application adds one split and uses one tink. Per weapon:
// needed = min(target - current, 10 - tinks, 10 - current)
// The imbuer applies full (100-unit) White Quartz bags, lowest workmanship first, with
// UseObjectOn(salvage, weapon). AC then shows its own craft confirmation — the player
// clicks it; the imbuer waits (20 s) for the "successfully applies" / "fails to apply"
// line before the next step. Nothing is ever applied without the Hub confirm first.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltSplitArrows : IIltFeature
{
private const int MaterialWhiteQuartz = 46;
private const uint IntNumItemsInMaterial = 170;
private const uint IntItemWorkmanship = 105;
private const long StepTimeoutMs = 20_000;
private static readonly Regex Applied = new(
@"^(?<character>[\w\s]+) successfully applies the (?<salvage>[\w\s\-]+?)(\sSalvage.*)(\s?\(100\))?\s\(workmanship (?<workmanship>\d+\.\d+)\) to the (?<item>[\w\s\'\-]+)\.$",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex Failed = new(
@"^(?<character>[\w\s]+) fails to apply the (?<salvage>[\w\s\-]+?)(\sSalvage.*)(\s?\(100\))?\s\(workmanship (?<workmanship>\d+\.\d+)\) to the (?<item>[\w\s\'\-]+)\.",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
private readonly IltHubContext _ctx;
// Job state (pump thread)
private int _weaponId;
private int _remaining;
private bool _waiting;
private long _stepStartedAt;
private volatile string _status = "idle";
// Render snapshot of eligible weapons
private volatile WeaponRow[] _weapons = Array.Empty<WeaponRow>();
private long _lastScan;
private sealed record WeaponRow(int Id, string Name, int Splits, int Tinks, bool Imbued, int Needed);
public IltSplitArrows(IltHubContext ctx) => _ctx = ctx;
private IltGearState G => _ctx.State.Gear;
public bool Running => _weaponId != 0;
/// <summary>True while another ILT pack job (the Rings chain) is running: no imbue starts then.</summary>
public Func<bool>? Blocked;
private int Needed(WorldObject w)
{
var inv = _ctx.Inventory;
int cur = inv.Int(w, IltInventory.IntSplitArrowCount);
int tinks = inv.Int(w, IltInventory.IntNumTimesTinkered);
int target = Math.Clamp(G.SplitArrowTarget, 0, 10);
return Math.Max(0, Math.Min(target - cur, Math.Min(10 - tinks, 10 - cur)));
}
/// <summary>Full White Quartz bags, lowest workmanship first.</summary>
private List<WorldObject> QuartzBags()
{
var inv = _ctx.Inventory;
return inv.Items()
.Where(wo => wo.ObjectClass == AcObjectClass.Salvage
&& (inv.Int(wo, IltInventory.IntMaterialType) == MaterialWhiteQuartz || wo.Name.Contains("White Quartz", StringComparison.OrdinalIgnoreCase))
&& inv.Uses(wo) >= 100)
.OrderBy(Workmanship)
.ToList();
}
private double Workmanship(WorldObject bag)
{
int total = _ctx.Inventory.Int(bag, IntItemWorkmanship);
int items = Math.Max(1, _ctx.Inventory.Int(bag, IntNumItemsInMaterial, 1));
return total / (double)items;
}
/// <summary>Starts imbuing one weapon (pump thread, after the UI confirm).</summary>
public void Start(int weaponId)
{
var w = _ctx.Inventory.Cache?[weaponId];
if (w == null) { _status = "weapon not found"; return; }
if (Blocked?.Invoke() == true) { _status = "the Rings chain is running"; return; }
if (_ctx.Inventory.IsEquipped(w)) { _status = "unequip the weapon first"; return; }
int need = Needed(w);
if (need <= 0) { _status = $"{w.Name} needs no more splits"; return; }
_weaponId = weaponId;
_remaining = need;
_waiting = false;
_status = $"imbuing {w.Name}: {need} application(s)";
}
public void Stop(string why)
{
_weaponId = 0;
_waiting = false;
_status = why;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (nowMs - _lastScan >= 3000 && _ctx.WindowOpen)
{
_lastScan = nowMs;
ScanWeapons();
}
if (_weaponId == 0) return;
if (_waiting)
{
if (nowMs - _stepStartedAt > StepTimeoutMs) Stop("no result within 20 s (craft dialog not confirmed?) - stopped");
return;
}
if (_remaining <= 0) { Stop("done"); return; }
if (_ctx.Inventory.IsBusy) return;
var bag = QuartzBags().FirstOrDefault();
if (bag == null) { Stop("out of full White Quartz bags"); return; }
if (_ctx.Inventory.UseOn(bag, unchecked((uint)_weaponId)))
{
_waiting = true;
_stepStartedAt = nowMs;
_status = $"applying {bag.Name} - confirm the craft dialog in AC ({_remaining} left)";
}
}
public bool OnChat(string text)
{
if (!_waiting) return false;
if (Applied.IsMatch(text))
{
_waiting = false;
_remaining--;
_status = $"applied ({_remaining} left)";
}
else if (Failed.IsMatch(text))
{
// A failed tink still consumes a tink slot — recompute from the weapon.
_waiting = false;
var w = _ctx.Inventory.Cache?[_weaponId];
_remaining = w != null ? Math.Min(_remaining, Needed(w)) : 0;
_status = $"application failed ({_remaining} left)";
}
return false;
}
public void OnLogout() => Stop("idle");
private void ScanWeapons()
{
var inv = _ctx.Inventory;
var rows = new List<WeaponRow>();
foreach (var wo in inv.Items())
{
if (wo.ObjectClass != AcObjectClass.MissileWeapon) continue;
bool imbued = inv.Int(wo, IltInventory.IntImbuedEffect) != 0;
if (imbued && G.SplitIgnoreImbued) continue;
rows.Add(new WeaponRow(wo.Id, wo.Name, inv.Int(wo, IltInventory.IntSplitArrowCount),
inv.Int(wo, IltInventory.IntNumTimesTinkered), imbued, Needed(wo)));
}
_weapons = rows.OrderByDescending(r => r.Needed).ThenBy(r => r.Name).ToArray();
_bagCount = QuartzBags().Count;
}
private volatile int _bagCount;
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
ImGui.TextColored(IltStyle.ColTeal, "Split arrows (White Quartz)");
int tgt = G.SplitArrowTarget;
ImGui.SetNextItemWidth(120);
if (ImGui.SliderInt("Target splits", ref tgt, 0, 10)) G.SplitArrowTarget = tgt;
ImGui.SameLine();
bool skip = G.SplitIgnoreImbued;
if (ImGui.Checkbox("Skip imbued weapons", ref skip)) G.SplitIgnoreImbued = skip;
SafeImGui.TextDisabled($"Full White Quartz bags carried: {_bagCount}");
foreach (var w in _weapons)
{
ImGui.PushID(w.Id);
ImGui.TextUnformatted($"{w.Name} splits {w.Splits}, tinks {w.Tinks}{(w.Imbued ? ", imbued" : "")}");
ImGui.SameLine();
ImGui.BeginDisabled(w.Needed <= 0 || Running);
if (ImGui.SmallButton($"Imbue +{w.Needed}"))
{
var row = w;
_ctx.Confirm("Split-arrow imbue",
$"Apply {row.Needed} White Quartz bag(s) to {row.Name}?\n\nEach application uses a tink and can fail.\n"
+ "AC will ask you to confirm every craft.",
() => Start(row.Id), "Start");
}
ImGui.EndDisabled();
ImGui.PopID();
}
if (_weapons.Length == 0) ImGui.TextDisabled("No missile weapons carried.");
if (Running && ImGui.SmallButton("Stop imbuing")) _ctx.Post(() => Stop("stopped by player"));
SafeImGui.TextDisabled("Status: " + _status);
}
}

View file

@ -0,0 +1,59 @@
// IltStyle.cs - The colours the ILT tabs and panels draw with (RynthAi's dashboard palette, so
// the tabs look the same inside RynthAi's Mini Remote as when they lived there), the dashboard
// style for RynthILT's own windows, and a JSON string escaper for the hand-built exports.
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Plugin.RynthILT.Hub;
internal static class IltStyle
{
internal static readonly Vector4 ColTeal = new(0.15f, 0.85f, 0.90f, 1.00f);
internal static readonly Vector4 ColAmber = new(0.91f, 0.70f, 0.20f, 1.00f);
internal static readonly Vector4 ColGreen = new(0.25f, 0.85f, 0.45f, 1.00f);
internal static readonly Vector4 ColTextMute = new(0.55f, 0.65f, 0.75f, 1.00f);
internal static readonly Vector4 ColHp = new(0.85f, 0.20f, 0.20f, 1.00f);
/// <summary>
/// RynthAi's dashboard colours for a window of RynthILT's own (Games HUD, confirmations, the
/// Guardian panel). Returns how many colours to pop. Inside RynthAi's Mini Remote the style
/// is already pushed.
/// </summary>
internal static int PushDashboardStyle()
{
ImGui.PushStyleColor(ImGuiCol.FrameBg, new Vector4(0.18f, 0.22f, 0.28f, 1.00f));
ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, new Vector4(0.24f, 0.30f, 0.38f, 1.00f));
ImGui.PushStyleColor(ImGuiCol.FrameBgActive, new Vector4(0.30f, 0.38f, 0.48f, 1.00f));
ImGui.PushStyleColor(ImGuiCol.CheckMark, new Vector4(0.85f, 0.90f, 1.00f, 1.00f));
ImGui.PushStyleColor(ImGuiCol.PopupBg, new Vector4(0.10f, 0.14f, 0.20f, 0.98f));
ImGui.PushStyleColor(ImGuiCol.Header, new Vector4(0.20f, 0.28f, 0.36f, 1.00f));
ImGui.PushStyleColor(ImGuiCol.HeaderHovered, new Vector4(0.26f, 0.36f, 0.46f, 1.00f));
ImGui.PushStyleColor(ImGuiCol.HeaderActive, new Vector4(0.32f, 0.44f, 0.58f, 1.00f));
ImGui.PushStyleColor(ImGuiCol.TitleBg, new Vector4(0.14f, 0.18f, 0.24f, 1.00f));
ImGui.PushStyleColor(ImGuiCol.TitleBgActive, new Vector4(0.22f, 0.30f, 0.40f, 1.00f));
ImGui.PushStyleColor(ImGuiCol.TitleBgCollapsed, new Vector4(0.10f, 0.14f, 0.20f, 0.85f));
return 11;
}
/// <summary>Minimal JSON string escaper for hand-built export JSON.</summary>
internal static string JsonEscape(string s)
{
var sb = new System.Text.StringBuilder(s.Length + 8);
foreach (char c in s)
{
switch (c)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4"));
else sb.Append(c);
break;
}
}
return sb.ToString();
}
}

View file

@ -0,0 +1,213 @@
// IltT11.cs — ACECustom T11 (tier 11+ gear): the player's wield counters for RynthAi's loot rules, and
// "/ilt t11" (also "/ra t11", which RynthAi passes on).
// Moved out of RynthAi 2026-10-20 (RynthAiT11Command.cs and its "/aug" chat feed): the counters and the
// command are ACECustom's, so RynthILT reads them; RynthAi keeps the loot keys and the evaluator
// (Loot/T11ItemSupport.cs, users' .utl profiles use them) and gets the counters through RynthAi.Hub
// SetPlayerCounter.
//
// * Counters: ACECustom doesn't send them at login ([SendOnLogin] is off), so they come from the
// "/aug" reply (RynthILT's login probe asks for it on ILT), read by the shared T11AugReportParser.
// The item-aug override (IltHubState.T11.ItemAugsOverride, "/ilt t11 augs <n|auto>") replaces the
// /aug Item count. Each change is reported to RynthAi, and every ResendMs anyway (RynthAi may have
// reloaded or logged in later); -1 = unknown.
// * "/ilt t11 [status | augs <n|auto> | refresh | item [0xId]]": the counters, the override, a fresh
// "/aug", and how the selected item's T11 text reads (tier, grade, modifiers, the loot keys' values).
// Ticks only on an ILT-like world (IltHubController): elsewhere RynthAi's counters stay unknown.
using System;
using System.Globalization;
using System.Linq;
using RynthCore.Loot.T11;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltT11 : IIltFeature
{
private const long ResendMs = 5_000;
// ACE string properties of an item's appraisal (RynthAi's StringValueKey).
private const uint StrName = 1, StrUse = 14, StrLongDesc = 16;
private readonly IltHubContext _ctx;
private readonly T11AugReportParser _parser = new();
private long _sentAt = long.MinValue;
private bool _dirty = true;
private int _overrideApplied = int.MinValue;
public IltT11(IltHubContext ctx) => _ctx = ctx;
/// <summary>The counters this character's "/aug" reply gave, with the override applied.</summary>
public T11PlayerAugs Player { get; } = new();
/// <summary>How many counters the last report to RynthAi carried (for the tests).</summary>
public int LastReported { get; private set; }
private IltT11State S => _ctx.State.T11;
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
int ov = S.ItemAugsOverride;
if (ov != _overrideApplied)
{
_overrideApplied = ov;
Player.ItemAugOverride = ov >= 0 ? ov : null;
_dirty = true;
}
if (!_dirty && _sentAt != long.MinValue && nowMs - _sentAt < ResendMs) return;
Report();
_sentAt = nowMs;
_dirty = false;
}
/// <summary>The "/aug" reply's counter lines. Never eats (the login probe's capture decides that).</summary>
public bool OnChat(string text)
{
if (_parser.Feed(text, IltHubContext.NowMs, Player)) _dirty = true;
return false;
}
public void OnLogout()
{
Player.Clear();
_dirty = true;
_sentAt = long.MinValue;
}
/// <summary>Every counter to RynthAi (-1 for an unknown one). Pump thread.</summary>
private void Report()
{
int n = 0;
foreach ((T11Counter counter, _) in T11Catalog.CounterNames)
{
long? v = Player.Get(counter);
if (_ctx.Ai.SetPlayerCounter(unchecked((uint)counter), v ?? -1)) n++;
}
LastReported = n;
}
// ── "/ilt t11 ..." ──────────────────────────────────────────────────────
/// <summary>"/ilt t11 [status | augs &lt;n|auto&gt; | refresh | item [0xId]]" (args after "t11"). Pump thread.</summary>
public void HandleCommand(string[] args)
{
string sub = args.Length >= 1 ? args[0].ToLowerInvariant() : string.Empty;
switch (sub)
{
case "":
case "status":
PrintStatus();
break;
case "augs":
SetOverride(args.Length >= 2 ? args[1] : string.Empty);
break;
case "refresh":
if (!_ctx.Host.HasInvokeChatParser) { _ctx.Chat("[RynthILT] This engine can't send chat commands."); break; }
_ctx.Host.InvokeChatParser("/aug");
_ctx.Chat("[RynthILT] T11: sent /aug - the counters update from its reply.");
break;
case "item":
PrintItem(args.Length >= 2 ? args[1] : null);
break;
default:
_ctx.Chat("[RynthILT] Usage: /ilt t11 [augs <n|auto> | refresh | item [0xId]] (also /ra t11)");
break;
}
}
/// <summary>The counters the "T11: Can Wield" loot key compares wield gates against.</summary>
private void PrintStatus()
{
string updated = Player.UpdatedUtc is DateTime t ? t.ToLocalTime().ToString("t", CultureInfo.CurrentCulture) : "never";
_ctx.Chat($"[RynthILT] === T11 loot (last /aug read: {updated}) ===");
foreach ((T11Counter counter, string name) in T11Catalog.CounterNames)
{
long? v = Player.Get(counter);
string source = counter == T11Counter.ItemAugmentations && S.ItemAugsOverride >= 0 ? " (override)" : string.Empty;
_ctx.Chat($"[RynthILT] {name}: {(v.HasValue ? v.Value.ToString("N0", CultureInfo.CurrentCulture) : "unknown")}{source}");
}
if (Player.UpdatedUtc == null && S.ItemAugsOverride < 0)
_ctx.Chat("[RynthILT] Unknown counters make \"T11: Can Wield\" -1. Use /ilt t11 refresh, or /ilt t11 augs <n>.");
if (!_ctx.Ai.Available)
_ctx.Chat("[RynthILT] (The loot rules are RynthAi's; it isn't loaded, so nothing uses these yet.)");
}
/// <summary>"/ilt t11 augs &lt;n|auto&gt;": the item-aug override (-1 = read from /aug), saved with the Hub's state.</summary>
private void SetOverride(string arg)
{
int value;
if (arg.Equals("auto", StringComparison.OrdinalIgnoreCase) || arg == "-1")
value = -1;
else if (!int.TryParse(arg.Replace(",", string.Empty), NumberStyles.Integer, CultureInfo.InvariantCulture, out value) || value < 0)
{
_ctx.Chat("[RynthILT] Usage: /ilt t11 augs <n|auto> (n = your item augmentation count)");
return;
}
S.ItemAugsOverride = value;
Tick(IltHubContext.NowMs); // applied and reported now
_ctx.Chat(value < 0
? "[RynthILT] T11: item augmentations now come from /aug."
: $"[RynthILT] T11: item augmentations fixed at {value:N0} for loot rules.");
}
/// <summary>"/ilt t11 item [0xId]": the parsed T11 text of an item (the selected item by default).</summary>
private void PrintItem(string? idArg)
{
var host = _ctx.Host;
uint id = 0;
if (!string.IsNullOrEmpty(idArg))
uint.TryParse(idArg.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? idArg[2..] : idArg,
NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id);
if (id == 0 && host.HasGetSelectedItemId) id = host.GetSelectedItemId();
if (id == 0) { _ctx.Chat("[RynthILT] T11: select an item first (or pass 0xId)."); return; }
int iid = unchecked((int)id);
var inv = _ctx.Inventory;
WorldObject? item = inv.Cache[iid];
string name = item?.Name ?? string.Empty;
if (item == null) { _ctx.Chat($"[RynthILT] T11: the client doesn't know 0x{id:X8}."); return; }
if (name.Length == 0) name = inv.Str(item, StrName);
var server = new T11ServerProps(inv.Int(item, (uint)T11Catalog.PropZcTier, 0),
inv.Int(item, (uint)T11Catalog.PropWeaponAugScaleTier, 0),
inv.Int(item, (uint)T11Catalog.PropWeaponAugScaleQuality, -1));
T11ItemInfo info = T11ItemInfo.Parse(name, inv.Str(item, StrLongDesc), inv.Str(item, StrUse), server);
if (!info.IsT11)
{
bool appraised = !host.HasHasAppraisalData || host.HasAppraisalData(id);
_ctx.Chat(appraised
? $"[RynthILT] T11: {name} is not a T11 item."
: $"[RynthILT] T11: {name} isn't appraised yet - ID it and try again.");
return;
}
_ctx.Chat($"[RynthILT] === T11: {name} (0x{id:X8}) ===");
_ctx.Chat($"[RynthILT] Tier {(info.TierIsExact ? info.Tier.ToString(CultureInfo.InvariantCulture) : "~" + info.Tier.ToString(CultureInfo.InvariantCulture))}"
+ (info.Grade != null ? $", grade {info.Grade} ({info.DamagePercent}% of max damage)" : string.Empty)
+ (info.WeaponQuality >= 0 ? $", quality {info.WeaponQuality}/1000" : string.Empty)
+ (info.GearGrade != null ? $", gear grade {info.GearGrade} ({info.GearGradeLines} lines)" : string.Empty)
+ (info.ZoneLocked ? ", zone locked" : string.Empty));
if (info.PropertySlots >= 0 || info.Tainted)
_ctx.Chat("[RynthILT] Properties "
+ (info.PropertySlots < 0 ? "?" : info.PropertySlotCap > 0 ? $"{info.PropertySlots} of {info.PropertySlotCap}" : info.PropertySlots.ToString(CultureInfo.InvariantCulture))
+ (info.Tainted ? ", tainted (bags no longer work)" : string.Empty));
foreach (T11WieldGate g in info.WieldGates)
_ctx.Chat($"[RynthILT] Wield requires {g.Amount:N0} {T11Catalog.CounterName(g.Counter)}");
foreach (T11Modifier m in info.Modifiers)
{
string band = m.Min.HasValue && m.Max.HasValue ? $" [{m.Min}-{m.Max}] roll {m.RollPercent}%" : string.Empty;
string marks = (m.Tinkered != 0 ? $" ({m.Tinkered:+#;-#} tinkered)" : string.Empty)
+ (m.BuiltIn ? " (built-in)" : string.Empty) + (m.Locked ? " (locked)" : string.Empty);
_ctx.Chat($"[RynthILT] Mod {m.Name} {(m.IsSlotSpecial ? "(special)" : "+" + m.Value)}{band}{marks}");
}
foreach ((string proc, double chance) in info.Procs)
_ctx.Chat($"[RynthILT] Cast on strike: {proc} ({chance.ToString("0.#", CultureInfo.CurrentCulture)}%)");
int canWield = T11Keys.TryGetValue(info, T11Keys.CanWield, Player, out int cw) ? cw : -1;
_ctx.Chat($"[RynthILT] Can wield: {(canWield == 1 ? "yes" : canWield == 0 ? "no" : "unknown (no /aug read, or not appraised)")}"
+ $", modifier ratings {info.ModifierRatingTotal}, average roll {info.AverageRollPercent}%");
string keys = string.Join(", ", T11Keys.Names()
.Where(k => k.Id < T11Keys.ModifierBase)
.Select(k => $"{k.Name.Replace("T11: ", string.Empty)}={(T11Keys.TryGetValue(info, k.Id, Player, out int v) ? v : 0)}"));
_ctx.Chat($"[RynthILT] Loot keys (RynthAi's loot rules read the same): {keys}");
}
}

View file

@ -0,0 +1,296 @@
// IltTempleAttributes.cs - Temple of Enlightenment attribute turn-in tracker (Guardian window).
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// One row per Fiun attribute NPC plus the Guardian of Attribute Enlightenment riddle. Each row
// prefers the timed flag from /myquests (solves + exact cooldown). When /myquests lacks the flag
// it falls back to the "/qb list" wait stamp: a stamp appearing between two lists counts one
// turn-in and starts an estimated cooldown (CooldownHoursAssumed). Fallback counts and timers
// persist in IltGuardianState.
//
// Rows come from "infi attribute.csv" (RynthAi folder, then Documents\Asheron's Call - the UB
// location) when present: npc, attribute, stamp [, myQuestsKey]. Built-in rows missing from the
// file are appended. Pump thread computes; the render thread only reads Snapshot.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One tracked turn-in: the NPC, its attribute, the /qb wait flag and the /myquests keys to try.</summary>
internal sealed class IltTempleAttrRow
{
public IltTempleAttrRow(string npc, string attribute, string stamp, string? myQuestsKey = null)
{
Npc = npc.Trim();
Attribute = attribute.Trim();
QbWaitFlag = ExtractQbFlag(stamp);
var keys = new List<string>();
void Add(string? k)
{
if (string.IsNullOrWhiteSpace(k)) return;
string t = k.Trim().ToLowerInvariant();
if (!keys.Contains(t)) keys.Add(t);
}
Add(myQuestsKey);
Add(QbWaitFlag);
if (QbWaitFlag.EndsWith("Wait", StringComparison.OrdinalIgnoreCase) && QbWaitFlag.Length > 4)
Add(QbWaitFlag[..^4]);
MyQuestsKeys = keys.ToArray();
}
public string Npc { get; }
public string Attribute { get; }
/// <summary>/qb flag name (e.g. TempleAttributeStrengthWait).</summary>
public string QbWaitFlag { get; }
/// <summary>Lowercase /myquests keys in lookup order: CSV override, the wait flag, the flag without "Wait".</summary>
public string[] MyQuestsKeys { get; }
/// <summary>"You've stamped X!" → "X"; a bare flag name is returned trimmed.</summary>
private static string ExtractQbFlag(string stamp)
{
string s = (stamp ?? string.Empty).Trim();
const string prefix = "You've stamped ";
if (s.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) s = s[prefix.Length..];
return s.Trim().TrimEnd('!', ' ', '\t', '\r', '\n');
}
}
/// <summary>What the Guardian window shows for one row.</summary>
internal sealed record IltTempleAttrStatus(string Attribute, string Npc, int Count, string Status, string Eta, bool Ready, bool FromMyQuests);
internal sealed class IltTempleAttributes
{
private const long RebuildIntervalMs = 1000;
private const string CsvName = "infi attribute.csv";
private static readonly IltTempleAttrRow[] DefaultRows =
{
new("Fiun Luunere", "Strength", "TempleAttributeStrengthWait"),
new("Fiun Bayaas", "Coordination", "TempleAttributeCoordinationWait"),
new("Fiun Ruun", "Endurance", "TempleAttributeEnduranceWait"),
new("Fiun Riish", "Quickness", "TempleAttributeQuicknessWait"),
new("Fiun Vasherr", "Focus", "TempleAttributeFocusWait"),
new("Fiun Noress", "Willpower", "TempleAttributeSelfWait"),
new("Fiun Vaelesh", "Health", "TempleAttributeHealthWait"),
new("Fiun Torrun", "Stamina", "TempleAttributeStamWait"),
new("Fiun Saeluun", "Mana", "TempleAttributeManaWait"),
new("Guardian (Attr)", "Riddle", "TempleAttributeRiddleWait"),
};
private readonly IltHubContext _ctx;
private readonly IltQuestBonus _quests;
private readonly IltTempleAttrRow[] _rows;
// Wait-stamp presence per attribute at the previous "/qb list" (session only: a transition
// needs two lists in the same session).
private readonly Dictionary<string, bool> _lastHadWait = new(StringComparer.OrdinalIgnoreCase);
private int _seenQbGeneration;
private long _lastRebuildAt = -RebuildIntervalMs;
private volatile IltTempleAttrStatus[] _snapshot = Array.Empty<IltTempleAttrStatus>();
private DateTime _syncedUtc = DateTime.MinValue;
public IltTempleAttributes(IltHubContext ctx, IltQuestBonus quests)
{
_ctx = ctx;
_quests = quests;
_rows = LoadRows(out string source);
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] attribute rows: {_rows.Length} from {source}");
}
/// <summary>Rows as last computed (render thread reads this).</summary>
public IltTempleAttrStatus[] Snapshot => _snapshot;
/// <summary>When the quest data behind the rows last changed (MinValue = never this session).</summary>
public DateTime SyncedUtc => _syncedUtc;
private IltGuardianState S => _ctx.State.Guardian;
// ── Rows file ───────────────────────────────────────────────────────────
/// <summary>The CSV in RynthILT's folder, the RynthAi folder (where it lived), else UB's Documents location; built-in rows otherwise.</summary>
private static IltTempleAttrRow[] LoadRows(out string source)
{
string[] candidates =
{
Path.Combine(IltHubStore.SharedRoot, CsvName),
Path.Combine(RynthInstallPaths.RynthAiDir, CsvName),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Asheron's Call", CsvName),
};
foreach (string path in candidates)
{
try
{
if (!File.Exists(path)) continue;
var rows = ParseCsv(File.ReadAllLines(path));
if (rows.Count == 0) continue;
source = path;
return MergeMissingDefaults(rows);
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, $"read {path}"); }
}
source = "built-in table";
return DefaultRows;
}
/// <summary>npc, attribute, stamp [, myQuestsKey]; a header row and blank lines are skipped.</summary>
private static List<IltTempleAttrRow> ParseCsv(string[] lines)
{
var rows = new List<IltTempleAttrRow>();
foreach (string raw in lines)
{
string line = raw.Trim().TrimStart('\uFEFF');
if (line.Length == 0) continue;
if (line.StartsWith("npc", StringComparison.OrdinalIgnoreCase) && line.Contains("attribute", StringComparison.OrdinalIgnoreCase))
continue;
string[] seg = line.Split(',');
if (seg.Length < 3) continue;
string npc = seg[0].Trim(), attr = seg[1].Trim();
string stamp;
string? key = null;
if (seg.Length == 4) { stamp = seg[2].Trim(); key = seg[3].Trim(); }
else stamp = string.Join(",", seg.Skip(2)).Trim(); // a full stamp chat line may contain commas
if (npc.Length == 0 || attr.Length == 0 || stamp.Length == 0) continue;
rows.Add(new IltTempleAttrRow(npc, attr, stamp, key));
}
return rows;
}
private static IltTempleAttrRow[] MergeMissingDefaults(List<IltTempleAttrRow> loaded)
{
var seen = new HashSet<string>(loaded.Select(r => r.QbWaitFlag), StringComparer.OrdinalIgnoreCase);
foreach (var def in DefaultRows)
if (seen.Add(def.QbWaitFlag)) loaded.Add(def);
return loaded.ToArray();
}
// ── Pump thread ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
int gen = _quests.QbGeneration;
if (gen != _seenQbGeneration)
{
_seenQbGeneration = gen;
if (gen > 0) ApplyQbTransitions();
_syncedUtc = DateTime.UtcNow;
}
if (nowMs - _lastRebuildAt < RebuildIntervalMs) return;
_lastRebuildAt = nowMs;
Rebuild();
}
/// <summary>Re-asks the server for /myquests and "/qb list" (each limited to once a minute).</summary>
public string Refresh() => $"{_ctx.Ai.RefreshQuests()} {_quests.RefreshQb()}";
/// <summary>Forgets the counted turn-ins and estimated cooldowns (the /qb fallback only).</summary>
public void ResetCounts()
{
S.TurnInCounts.Clear();
S.CooldownUntilUtc.Clear();
_lastRebuildAt = long.MinValue / 2;
}
public void OnLogout()
{
_lastHadWait.Clear();
_seenQbGeneration = 0;
_syncedUtc = DateTime.MinValue;
}
private bool TryQuest(IltTempleAttrRow row, out QuestRecord rec)
{
rec = null!;
// /myquests is RynthAi's quest tracker (RynthAi.Hub); without RynthAi the /qb stamps decide.
foreach (string key in row.MyQuestsKeys)
if (_ctx.Ai.TryGetQuestFlag(key, out rec)) return true;
return false;
}
/// <summary>A new "/qb list" arrived: count wait stamps that appeared since the previous list.</summary>
private void ApplyQbTransitions()
{
int hours = Math.Max(1, S.CooldownHoursAssumed);
foreach (var row in _rows)
{
string key = row.Attribute;
bool hasWait = _quests.QbHasFlag(row.QbWaitFlag);
if (!TryQuest(row, out _))
{
if (_lastHadWait.TryGetValue(key, out bool had) && !had && hasWait)
{
S.TurnInCounts[key] = (S.TurnInCounts.TryGetValue(key, out int n) ? n : 0) + 1;
S.CooldownUntilUtc[key] = DateTime.UtcNow.AddHours(hours);
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] {key} turn-in counted from /qb (now {S.TurnInCounts[key]})");
}
if (!hasWait) S.CooldownUntilUtc.Remove(key);
}
_lastHadWait[key] = hasWait;
}
}
private void Rebuild()
{
bool qbLoaded = _quests.QbGeneration > 0;
int hours = Math.Max(1, S.CooldownHoursAssumed);
var list = new IltTempleAttrStatus[_rows.Length];
for (int i = 0; i < _rows.Length; i++)
{
var row = _rows[i];
if (TryQuest(row, out var rec))
{
list[i] = FromQuest(row, rec);
continue;
}
string key = row.Attribute;
int count = S.TurnInCounts.TryGetValue(key, out int c) ? c : 0;
if (!qbLoaded)
{
list[i] = new(key, row.Npc, count, "Unknown", "Refresh", false, false);
continue;
}
if (!_quests.QbHasFlag(row.QbWaitFlag))
{
list[i] = new(key, row.Npc, count, "Ready", "-", true, false);
continue;
}
// Wait stamp present: show the estimated cooldown, starting one if none is known.
if (!S.CooldownUntilUtc.TryGetValue(key, out DateTime until))
S.CooldownUntilUtc[key] = until = DateTime.UtcNow.AddHours(hours);
until = AsUtc(until);
TimeSpan left = until - DateTime.UtcNow;
list[i] = left > TimeSpan.Zero
? new(key, row.Npc, count, "Wait stamp", $"~{IltParse.Duration(left)} (est.)", false, false)
: new(key, row.Npc, count, "Wait stamp", "ready? (est.)", false, false);
}
_snapshot = list;
}
/// <summary>A row backed by its /myquests flag: exact solves and cooldown.</summary>
private static IltTempleAttrStatus FromQuest(IltTempleAttrRow row, QuestRecord rec)
{
switch (IltQuestBonus.Classify(rec))
{
case IltQuestBonus.QuestKind.KillTask:
return new(row.Attribute, row.Npc, rec.Solves, "Kill task", $"{rec.Solves}/{rec.MaxSolves}", false, true);
case IltQuestBonus.QuestKind.Once:
return new(row.Attribute, row.Npc, rec.Solves, "Once", rec.Solves >= 1 ? "done" : "-", false, true);
default:
if (rec.IsReady()) return new(row.Attribute, row.Npc, rec.Solves, "Ready", "now", true, true);
TimeSpan left = rec.TimeUntilReady();
string at = DateTime.Now.Add(left).ToString("ddd HH:mm");
return new(row.Attribute, row.Npc, rec.Solves, "Cooldown", $"{IltParse.Duration(left)} ({at})", false, true);
}
}
/// <summary>Stored times may load as Unspecified; they were written as UTC.</summary>
private static DateTime AsUtc(DateTime dt) => dt.Kind switch
{
DateTimeKind.Utc => dt,
DateTimeKind.Local => dt.ToUniversalTime(),
_ => DateTime.SpecifyKind(dt, DateTimeKind.Utc),
};
}

View file

@ -0,0 +1,920 @@
// IltVaultedDungeons.cs — Mini Remote "Vaulted Dungeons" tab (ILT / ACECustom only).
// Written by Silentkelpie (RynthSuite PR #12), a port of the UtilityBelt VaultedDungeons.lua script
// (owner 2026-09-27 / 2026-10-03): keeps the character in one Vaulted Dungeon via a tied Portal
// Recall Gem, and optionally /rc quit after N minutes without a kill.
//
// Safety rules (the owner's, added when it was taken in):
// * ILT only. The module does nothing (no tick work, no recall, no quit, no tab) unless
// IltServerOptions.IsIltLikeWorld says this is an Infinite Leaftide / ACECustom world, the same
// verdict every other ILT feature follows. A command answers "not available on this server".
// * Master switch, off by default: IltHubState.VaultedDungeonsEnabled (the ILT settings, and the
// engine's Settings > Navigation row RynthAi mirrors; RynthAi's profile setting until 2026-10-20,
// copied once). It is the only copy. While it is off the module
// ignores AutoStart, never ticks, sends no recall and no /rc quit, and the tab is hidden. Turning
// it off while running stops the keeper at once and says so once.
// * Active is never resumed from the saved settings. It starts when the player turns it on, or on
// arriving in the chosen dungeon with Auto Start On Arrival on (master on); a relog starts Off.
// * No recall gem while RynthAi is in combat, buffing or waiting on the server, or the client is
// busy: the recall waits until it is clear (a warning on the normal 30 s cadence).
// * /rc quit goes out at most once per activation, and only if Active, ILT and the master are all
// still true at the moment of sending.
// * The no-kill timer restarts on the luminance line, on the server's killer notification (a
// killing blow of yours) and on a pet-capture success reply. Kills by pets or fellows that pay
// no luminance still don't count; the tab says so.
using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One known Vaulted Dungeon (landblock high word; the client does not see the layer).</summary>
internal readonly record struct VaultedDungeon(string Name, uint Landblock);
internal sealed class IltVaultedDungeons : IIltFeature
{
// Keep order stable: saved picks are by 1-based index into this list.
private static readonly VaultedDungeon[] Dungeons =
{
new("Tyrant's Quarry", 0x01F7),
new("Tusgian Barracks", 0x8C03),
new("Wailing Cells", 0x01C2),
new("Chamber of Idols", 0x5649),
new("Fiun Redoubt", 0x0178), // added 2026-09-27
new("Tumerok Tunnels", 0x5754), // added 2026-10-03
};
private static readonly string[] GemNames =
{
"Primary Portal Recall Gem",
"Secondary Portal Recall Gem",
};
private static readonly (string Name, float Value)[] Powers =
{
("Fast", 0f), ("Medium", 0.5f), ("Full Power", 1f),
};
private static readonly int[] QuitPresets = { 1, 2, 5, 10, 15, 30 };
private const long FirstRecallAfterMs = 1000;
private const long RecallAfterMs = 5000;
private const int QuitMin = 1, QuitMax = 30;
private const long WarnEveryMs = 30_000;
private const string SettingsFileName = "settings.json";
private const string SettingsBadFileName = "settings.unreadable.json";
private const string CmdMetaOff = "/vt opt set EnableMeta False";
private const string CmdNavOff = "/vt opt set EnableNav False";
private const string CmdRepeatOn = "/ub playeroption AutoRepeatAttack on";
private const string CmdAttackBar = "/vt setattackbar ";
private const string CmdQuit = "/rc quit";
// System line only (no player sender): "You've banked 1,234 Luminance."
private static readonly Regex KillLine = new(
@"^You've banked [\d,]+ Luminance\.\s*$",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
/// <summary>Why the keeper is idle (<see cref="Snapshot.Gate"/>): "" = it may run.</summary>
private const string GateWorld = "world", GateMaster = "master";
private readonly IltHubContext _ctx;
private readonly object _gate = new();
private Cfg _cfg = new();
private bool _loaded;
private bool _dirty;
private string? _lastGoodJson;
// Seams (the tests fake them): the master switch, what RynthAi is doing, the clock, the gem use.
internal Func<bool> MasterEnabled;
internal Func<RynthAiActivity?> Activity;
internal Func<long> Clock = () => IltHubContext.NowMs;
/// <summary>Uses the named gem from the pack; false when the pack has none.</summary>
internal Func<string, bool> UseGem;
// Runtime (pump thread).
private long _outSinceMs;
private long _lastRecallMs;
private long _clockStartMs;
private long _realKillMs;
private bool _wasInside;
private bool _quitSent;
private long _lastWarnMs = -WarnEveryMs;
private string _publishedGate = "?";
private string _state = "paused"; // paused / setup / in / out / portal / nogem
private long? _quitLeftMs;
private bool? _presentBefore;
private long _idleSecs;
private long _inSinceMs;
private long _portalSinceMs;
private int _kills;
private long _dungeonSecs;
private long _lastTickMs;
// Snapshot for the render thread (copied under _gate).
private Snapshot _snap = Snapshot.Empty;
public IltVaultedDungeons(IltHubContext ctx)
{
_ctx = ctx;
MasterEnabled = () => _ctx.State.VaultedDungeonsEnabled;
Activity = () => _ctx.Ai.Activity();
UseGem = gemName =>
{
var gem = _ctx.Inventory.FindByName(n => n.Equals(gemName, StringComparison.OrdinalIgnoreCase));
if (gem == null) return false;
_ctx.Inventory.Use(gem);
return true;
};
}
/// <summary>Whether the keeper is running (tests, status).</summary>
internal bool IsActive => _cfg.Active;
private long Now() => Clock();
/// <summary>
/// The two hard rules, asked fresh each time: an ILT-like world, and the master switch on.
/// <paramref name="gate"/> says which one failed ("" when allowed).
/// </summary>
private bool Allowed(out string gate)
{
gate = !_ctx.Options.IsIltLikeWorld ? GateWorld : !MasterEnabled() ? GateMaster : string.Empty;
return gate.Length == 0;
}
/// <summary>Same, for commands and the tab: why the keeper can't be used now (null = it can).</summary>
private static string? GateReply(string gate) => gate switch
{
GateWorld => "Not available on this server (Infinite Leaftide / ACECustom only).",
GateMaster => "Off: turn on \"Vaulted Dungeons\" in the ILT settings (/ilt settings; also Settings > Navigation) first (the master switch, off by default).",
_ => null,
};
// ── Persistence ─────────────────────────────────────────────────────────
private string SettingsDir => Path.Combine(_ctx.Store.CharFolder, "VaultedDungeons");
private string SettingsPath => Path.Combine(SettingsDir, SettingsFileName);
private void EnsureLoaded()
{
if (_loaded) return;
_loaded = true;
try
{
string path = SettingsPath;
if (!File.Exists(path)) return;
string text = File.ReadAllText(path);
var cfg = JsonSerializer.Deserialize(text, IltVaultedDungeonsJsonContext.Default.Cfg);
if (cfg == null) return;
_cfg = Sanitize(cfg);
_lastGoodJson = text;
}
catch (Exception ex)
{
RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons: settings load failed: {ex.Message}");
}
}
private void SaveIfDirty()
{
if (!_dirty) return;
_dirty = false;
try
{
Directory.CreateDirectory(SettingsDir);
string path = SettingsPath;
// Corrupt / mid-write: keep a copy, then rewrite from last good + current cfg.
if (File.Exists(path))
{
try
{
string existing = File.ReadAllText(path);
if (_lastGoodJson == null)
JsonSerializer.Deserialize(existing, IltVaultedDungeonsJsonContext.Default.Cfg); // throws if bad
}
catch
{
try
{
File.Copy(path, Path.Combine(SettingsDir, SettingsBadFileName), overwrite: true);
_ctx.Chat("[Vaulted Dungeons] settings.json would not read — kept a copy as "
+ SettingsBadFileName + ".");
}
catch { /* best effort */ }
}
}
string json = JsonSerializer.Serialize(_cfg, IltVaultedDungeonsJsonContext.Default.Cfg);
File.WriteAllText(path, json);
_lastGoodJson = json;
}
catch (Exception ex)
{
RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons: settings save failed: {ex.Message}");
}
}
private static Cfg Sanitize(Cfg c)
{
// Never resumed from disk: the file keeps its "active" field, but a relog (or turning the
// master switch back on) starts Off. Auto Start On Arrival is the only way back in by itself.
c.Active = false;
c.Dungeon = ClampInt(c.Dungeon, 0, Dungeons.Length, 0);
c.Gem = ClampInt(c.Gem, 0, GemNames.Length, 0);
c.QuitMinutes = ClampInt(c.QuitMinutes, QuitMin, QuitMax, 2);
c.AttackPower = Powers[PowerIndex(c.AttackPower)].Value;
return c;
}
private static int ClampInt(int v, int lo, int hi, int def)
=> v < lo || v > hi ? def : v;
private static int PowerIndex(float v)
{
int best = 0;
float bestGap = float.MaxValue;
for (int i = 0; i < Powers.Length; i++)
{
float gap = Math.Abs(Powers[i].Value - v);
if (gap < bestGap) { best = i; bestGap = gap; }
}
return best;
}
private static string PowerText(float p)
{
string t = p.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture);
return t;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
// The hard rules first: ILT only, master switch on. Nothing below runs otherwise (not even
// reading the settings file), and a keeper that was running is stopped on the spot.
if (!Allowed(out string gate))
{
StopForGate(gate);
PublishGate(gate);
return;
}
EnsureLoaded();
SaveIfDirty();
// Time in dungeon (kills/hour): only while last state was "in".
if (_lastTickMs > 0 && _state == "in")
_dungeonSecs += Math.Max(0, (nowMs - _lastTickMs) / 1000);
_lastTickMs = nowMs;
if (!_ctx.Host.HasGetPlayerPose || !_ctx.Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _) || cell == 0)
{
Publish();
return;
}
uint landblock = cell >> 16;
bool portaling = _ctx.Host.HasIsPortaling && _ctx.Host.IsPortaling();
VaultedDungeon? dungeon = _cfg.Dungeon > 0 && _cfg.Dungeon <= Dungeons.Length
? Dungeons[_cfg.Dungeon - 1]
: null;
// Present check (for Auto Start / arrive actions) even while Off.
if (dungeon == null)
_presentBefore = null;
else if (!portaling)
{
bool here = landblock == dungeon.Value.Landblock;
if (here && _presentBefore != true) OnArrive(dungeon.Value, nowMs);
_presentBefore = here;
}
_quitLeftMs = null;
if (!_cfg.Active)
{
_state = "paused";
_outSinceMs = 0;
Publish();
return;
}
string? gemName = _cfg.Gem > 0 && _cfg.Gem <= GemNames.Length ? GemNames[_cfg.Gem - 1] : null;
if (dungeon == null || gemName == null)
{
_state = "setup";
_wasInside = false;
Warn(nowMs, dungeon == null
? "Pick a dungeon in the Vaulted Dungeons tab."
: "Pick a recall gem in the Vaulted Dungeons tab.");
Publish();
return;
}
bool inside = landblock == dungeon.Value.Landblock;
if (inside && !portaling)
{
if (!_wasInside)
{
_clockStartMs = nowMs;
_inSinceMs = nowMs;
}
_wasInside = true;
_outSinceMs = 0;
_portalSinceMs = 0;
_state = "in";
_idleSecs = Math.Max(0, (nowMs - _clockStartMs) / 1000);
if (_cfg.Quit)
{
long quitAfterMs = _cfg.QuitMinutes * 60_000L;
_quitLeftMs = Math.Max(0, quitAfterMs - (nowMs - _clockStartMs));
if (nowMs - _clockStartMs >= quitAfterMs && !_quitSent)
{
// Once per activation, and only if ILT, the master switch and Active are all
// still true right now (asked again: they may have changed since the top of the tick).
string nowGate = string.Empty;
if (!_cfg.Active || !Allowed(out nowGate))
{
StopForGate(nowGate);
PublishGate(nowGate);
return;
}
_quitSent = true;
_ctx.Chat($"[Vaulted Dungeons] No kill in {_cfg.QuitMinutes} minute"
+ (_cfg.QuitMinutes == 1 ? "" : "s") + " — quitting.");
Invoke(CmdQuit);
}
}
Publish();
return;
}
_wasInside = false;
if (portaling)
{
_state = "portal";
_outSinceMs = 0;
if (_portalSinceMs == 0) _portalSinceMs = nowMs;
Publish();
return;
}
_portalSinceMs = 0;
if (_outSinceMs == 0) _outSinceMs = nowMs;
_state = "out";
bool tried = _lastRecallMs >= _outSinceMs;
bool due = (!tried && nowMs - _outSinceMs >= FirstRecallAfterMs)
|| (tried && nowMs - _lastRecallMs >= RecallAfterMs);
if (due)
{
// Not in the middle of a fight, a buff chain or an unanswered use/cast: the recall waits
// (still due, so it goes out on the first clear tick) and says so on the normal cadence.
string? busy = BusyReason();
if (busy != null)
{
_state = "busy";
Warn(nowMs, $"Waiting to use the {gemName}: {busy}.");
}
else if (UseGem(gemName))
{
_lastRecallMs = nowMs;
_ctx.Chat($"[Vaulted Dungeons] Not in {dungeon.Value.Name} — using the {gemName}.");
}
else
{
_state = "nogem";
Warn(nowMs, $"No {gemName} in your pack.");
}
}
Publish();
}
/// <summary>
/// Why a recall gem must not be used now, or null when it may. RynthAi's activity (its "RynthAi.Activity"
/// bits: combat, buffing, loot, salvage, crafting, a use/cast waiting on the server) and the client's
/// busy hourglass; RynthAi not answering counts as busy (nothing is known, so nothing is used).
/// </summary>
private string? BusyReason()
{
RynthAiActivity? a = Activity();
if (a is null) return "RynthAi is not ready";
RynthAiActivity f = a.Value;
if ((f & RynthAiActivity.Combat) != 0) return "RynthAi is in combat";
if ((f & RynthAiActivity.Buffing) != 0) return "RynthAi is buffing";
if ((f & RynthAiActivity.ServerAction) != 0) return "RynthAi is waiting on the server";
if ((f & RynthAiActivity.Looting) != 0) return "RynthAi is looting";
if ((f & RynthAiActivity.Salvaging) != 0) return "RynthAi is salvaging";
if ((f & RynthAiActivity.Crafting) != 0) return "RynthAi is crafting";
if (_ctx.Inventory.IsBusy) return "the client is busy";
return null;
}
/// <summary>
/// A rule failed (not ILT any more, or the master switch went off): a running keeper stops at once
/// and says so once; an idle one has nothing to do. Safe to call every tick.
/// </summary>
private void StopForGate(string gate)
{
_outSinceMs = 0;
_wasInside = false;
_quitLeftMs = null;
_presentBefore = null;
if (!_cfg.Active) return;
_cfg.Active = false;
_dirty = true;
_state = "paused";
_ctx.Chat("[Vaulted Dungeons] Stopped: " + (gate == GateWorld
? "this is not an Infinite Leaftide / ACECustom world."
: "\"Vaulted Dungeons\" (the master switch) was turned off."));
SaveIfDirty();
}
/// <summary>The idle snapshot (only when the reason changes: nothing else runs while gated).</summary>
private void PublishGate(string gate)
{
if (gate == _publishedGate) return;
_publishedGate = gate;
Publish(gate);
}
public bool OnChat(string text)
{
if (string.IsNullOrEmpty(text)) return false;
string line = text.TrimEnd();
bool luminance = KillLine.IsMatch(line);
// A pet-capture success counts as a kill for the timer too (the same replies RynthAi's Pets
// tab matches); nothing else is guessed.
if (!luminance && !PetCaptureLines.IsSuccess(line)) return false;
if (!_cfg.Active || !Allowed(out _)) return false;
NoteKill(Now(), countKill: luminance);
return false; // never eat the luminance line
}
/// <summary>
/// The server's killer notification: this character landed a killing blow (RynthILTPlugin
/// .OnKillNotification, pump thread). Restarts the no-kill timer, like the luminance line.
/// </summary>
public void OnKillNotification()
{
if (!_cfg.Active || !Allowed(out _)) return;
NoteKill(Now(), countKill: false);
}
/// <summary>Restarts the Kill Client timer. The kill counter moves only on the luminance line (one per kill).</summary>
private void NoteKill(long now, bool countKill)
{
_clockStartMs = now;
_realKillMs = now;
if (countKill && _state == "in") _kills++;
Publish();
}
public void OnLogout()
{
// Logging out ends the run: Active is never carried over (see Sanitize).
_cfg.Active = false;
SaveIfDirty();
_wasInside = false;
_outSinceMs = 0;
_presentBefore = null;
_state = "paused";
Publish();
}
// ── Arrive / commands ───────────────────────────────────────────────────
private void OnArrive(VaultedDungeon dungeon, long nowMs)
{
// Only called while ILT and the master switch are on (Tick's gate), so Auto Start is honoured here only.
if (_cfg.AutoStart && !_cfg.Active)
{
Activate(nowMs);
_ctx.Chat($"[Vaulted Dungeons] Arrived in {dungeon.Name} — switched On (Auto Start On Arrival).");
}
// The arrival settings are part of running the keeper: nothing is sent while it is Off.
if (!_cfg.Active) return;
if (_cfg.DisableMeta) Invoke(CmdMetaOff);
if (_cfg.DisableNav) Invoke(CmdNavOff);
if (_cfg.RepeatAttack) Invoke(CmdRepeatOn);
if (_cfg.SetPower) Invoke(CmdAttackBar + PowerText(_cfg.AttackPower));
}
private void Invoke(string cmd)
{
if (_ctx.Host.HasInvokeChatParser) _ctx.Host.InvokeChatParser(cmd);
}
private void Warn(long nowMs, string text)
{
if (nowMs - _lastWarnMs < WarnEveryMs) return;
_lastWarnMs = nowMs;
_ctx.Chat("[Vaulted Dungeons] " + text);
}
/// <summary>Pump-thread: /ilt vaulted [on|off|toggle|status].</summary>
public bool HandleCommand(string[] args)
{
// ILT only, master switch on: otherwise the only answer is why (the keeper itself stays idle).
if (!Allowed(out string gate))
{
if (_cfg.Active) StopForGate(gate);
_ctx.Chat("[Vaulted Dungeons] " + GateReply(gate));
return true;
}
EnsureLoaded();
string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "status";
switch (sub)
{
case "on":
case "start":
SetActive(true);
return true;
case "off":
case "stop":
SetActive(false);
_ctx.Chat("[Vaulted Dungeons] Off.");
return true;
case "toggle":
SetActive(!_cfg.Active);
if (!_cfg.Active) _ctx.Chat("[Vaulted Dungeons] Off.");
return true;
default:
string d = _cfg.Dungeon > 0 && _cfg.Dungeon <= Dungeons.Length
? Dungeons[_cfg.Dungeon - 1].Name : "(none)";
string g = _cfg.Gem > 0 && _cfg.Gem <= GemNames.Length
? GemNames[_cfg.Gem - 1] : "(none)";
_ctx.Chat($"[Vaulted Dungeons] {(_cfg.Active ? "On" : "Off")} — dungeon={d}, gem={g}, "
+ $"kill-client={(_cfg.Quit ? $"{_cfg.QuitMinutes}m" : "off")}, state={_state}.");
_ctx.Chat("[Vaulted Dungeons] /ilt vaulted [on|off|toggle|status] (Mini Remote tab; master switch: /ilt settings or Settings > Navigation > Vaulted Dungeons)");
return true;
}
}
/// <summary>Starts the keeper (the player's own action, or Auto Start On Arrival). Pump thread; ILT and master already checked.</summary>
private void Activate(long nowMs)
{
_cfg.Active = true;
_dirty = true;
_outSinceMs = 0;
_wasInside = false; // the no-kill clock starts when the first in-dungeon tick sees us inside
_clockStartMs = nowMs;
_quitSent = false; // /rc quit: once per activation
_lastRecallMs = 0;
Publish();
}
private void SetActive(bool value)
{
if (value)
{
// From the tab's button too (posted to the pump): re-check, the switch may have gone off since.
if (!Allowed(out string gate))
{
_ctx.Chat("[Vaulted Dungeons] " + GateReply(gate));
return;
}
EnsureLoaded();
if (!_cfg.Active)
{
Activate(Now());
_ctx.Chat("[Vaulted Dungeons] On.");
}
return;
}
_cfg.Active = false;
_outSinceMs = 0;
_dirty = true;
_clockStartMs = Now();
_wasInside = false;
_quitLeftMs = null;
_state = "paused";
Publish();
}
// ── Render snapshot ─────────────────────────────────────────────────────
private void Publish(string gate = "")
{
_publishedGate = gate;
lock (_gate)
{
_snap = new Snapshot(
_cfg.Active, _cfg.Dungeon, _cfg.Gem, _cfg.Quit, _cfg.QuitMinutes,
_cfg.ShowInDungeon, _cfg.AutoStart, _cfg.DisableMeta, _cfg.DisableNav,
_cfg.RepeatAttack, _cfg.SetPower, _cfg.AttackPower,
_state, _quitLeftMs, _idleSecs, _inSinceMs, _outSinceMs, _portalSinceMs,
_realKillMs, _kills, _dungeonSecs, Now(), gate);
}
}
private Snapshot Take()
{
lock (_gate) return _snap;
}
// ── UI (render thread) ──────────────────────────────────────────────────
private bool _showAdvanced;
// Pending edits from the UI, applied on the next pump tick via Post.
private void PostEdit(Action<Cfg> edit)
{
_ctx.Post(() =>
{
if (!Allowed(out _)) return; // gated while it waited: an edit changes nothing
EnsureLoaded();
edit(_cfg);
_dirty = true;
Publish();
});
}
public void Render()
{
// Settings load on the pump (Tick); the window only reads the snapshot.
Snapshot s = Take();
Vector4 colLabel = new(0.53f, 0.53f, 0.53f, 1f);
Vector4 colValue = new(1f, 1f, 1f, 1f);
Vector4 colGreen = new(0.27f, 0.80f, 0.40f, 1f);
Vector4 colAmber = new(0.95f, 0.65f, 0.20f, 1f);
Vector4 colRed = new(0.90f, 0.30f, 0.30f, 1f);
Vector4 colPurple = new(0.72f, 0.52f, 0.95f, 1f);
Vector4 colTitleRed = new(0.85f, 0.25f, 0.25f, 1f);
// Title row: Vaulted (red) Dungeons (white) + On/Off + Advanced.
ImGui.TextColored(colTitleRed, "Vaulted");
ImGui.SameLine(0, ImGui.CalcTextSize(" ").X);
ImGui.TextColored(colValue, "Dungeons");
// Not offered right now (the tab is hidden then; this covers a stale frame or a direct open).
if (s.Gate.Length > 0)
{
ImGui.Separator();
ImGui.TextWrapped(GateReply(s.Gate) ?? "Not available.");
return;
}
ImGui.SameLine(0, 16);
Vector4 pill = s.Active ? colGreen : new(0.85f, 0.10f, 0.10f, 1f);
ImGui.PushStyleColor(ImGuiCol.Button, pill);
ImGui.PushStyleColor(ImGuiCol.ButtonHovered, pill);
ImGui.PushStyleColor(ImGuiCol.ButtonActive, pill);
ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.05f, 0.05f, 0.05f, 1f));
if (ImGui.SmallButton((s.Active ? " On " : " Off ") + "##vdactive"))
_ctx.Post(() => SetActive(!s.Active));
ImGui.PopStyleColor(4);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(s.Active
? "On: keeping this character in the chosen dungeon.\nClick: turn off."
: "Off: doing nothing.\nClick: turn on.");
ImGui.SameLine();
if (ImGui.SmallButton("Advanced##vdoptions")) _showAdvanced = !_showAdvanced;
ImGui.Separator();
float labelW = ImGui.CalcTextSize("Recall Gem").X + 12;
void Label(string text)
{
ImGui.AlignTextToFramePadding();
ImGui.TextColored(colLabel, text);
ImGui.SameLine(labelW);
}
// Status
var (statusWord, statusCol) = s.State switch
{
"in" => ("In Dungeon", colGreen),
"out" => ("Recalling", colAmber),
"portal" => ("Portal Space", colPurple),
"setup" => ("Setup Needed", colAmber),
"nogem" => ("No Gem", colRed),
"busy" => ("Waiting (busy)", colAmber),
_ => ("Not Running", colRed),
};
long since = s.State == "in" ? s.InSinceMs
: s.State == "out" ? s.OutSinceMs
: s.State == "portal" ? s.PortalSinceMs : 0;
string statusText = statusWord;
if (since > 0)
{
long secs = Math.Max(0, (s.NowMs - since) / 1000);
long h = secs / 3600, m = (secs / 60) % 60, sec = secs % 60;
statusText += h > 0 ? $" ({h}:{m:D2}:{sec:D2})" : $" ({m}:{sec:D2})";
}
Label("Status");
ImGui.TextColored(statusCol, statusText);
// Dungeon combo (0 = pick, 1..N = Dungeons[i-1])
Label("Dungeon");
string[] dungeonChoices = BuildDungeonChoices();
int dungeonIdx = s.Dungeon;
ImGui.SetNextItemWidth(260);
if (ImGui.Combo("##vddungeon", ref dungeonIdx, dungeonChoices, dungeonChoices.Length))
PostEdit(c => { c.Dungeon = dungeonIdx; });
Label("Recall Gem");
string[] gemChoices = { "Pick a gem", GemNames[0], GemNames[1] };
int gemIdx = s.Gem;
ImGui.SetNextItemWidth(260);
if (ImGui.Combo("##vdgem", ref gemIdx, gemChoices, gemChoices.Length))
PostEdit(c => { c.Gem = gemIdx; });
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Tie this gem to the dungeon's portal first.");
Label("Last Kill");
if (s.State == "in" && s.RealKillMs > 0)
ImGui.TextUnformatted($"{(s.NowMs - s.RealKillMs) / 1000} s ago");
else
ImGui.TextUnformatted("-");
Label("Session");
string perHour = s.DungeonSecs < 60 ? "-"
: Commas((long)(s.Kills * 3600.0 / Math.Max(1, s.DungeonSecs)));
ImGui.TextUnformatted($"{Commas(s.Kills)} kills ({perHour} Per Hour)");
if (s.QuitLeftMs is long left && s.QuitMinutes > 0)
{
float frac = (float)(left / (double)(s.QuitMinutes * 60_000L));
string barLabel = $"Kill Client ({left / 60_000}:{(left / 1000) % 60:D2})";
ImGui.ProgressBar(Math.Clamp(frac, 0f, 1f), new Vector2(-1, ImGui.GetTextLineHeight()), barLabel);
}
if (_showAdvanced)
{
ImGui.Separator();
ImGui.TextColored(colValue, "Advanced");
bool quit = s.Quit;
if (ImGui.Checkbox("Kill Client##vdquit", ref quit))
{
bool on = quit;
_ctx.Post(() =>
{
if (!Allowed(out _)) return;
EnsureLoaded();
_cfg.Quit = on;
_cfg.QuitMinutes = ClampInt(_cfg.QuitMinutes, QuitMin, QuitMax, 2);
_clockStartMs = Now();
_dirty = true;
Publish();
});
}
if (ImGui.IsItemHovered())
ImGui.SetTooltip("No kill for the set minutes in the dungeon: /rc quit closes the client (once per run).\n"
+ "The timer restarts on the server's \"You've banked N Luminance.\" line, on your own killing blow,\n"
+ "and on a successful pet capture. Kills by pets or fellows that pay you no luminance\n"
+ "do NOT restart it, so keep the minutes generous if you hunt with pets.");
ImGui.SameLine();
ImGui.TextColored(colLabel, "after");
ImGui.SameLine();
if (ImGui.SmallButton($"{s.QuitMinutes} minute{(s.QuitMinutes == 1 ? "" : "s")}##vdmincycle"))
_ctx.Post(() =>
{
if (!Allowed(out _)) return;
EnsureLoaded();
_cfg.QuitMinutes = StepPreset(_cfg.QuitMinutes, +1);
_clockStartMs = Now();
_dirty = true;
Publish();
});
if (ImGui.IsItemClicked(ImGuiMouseButton.Right))
_ctx.Post(() =>
{
if (!Allowed(out _)) return;
EnsureLoaded();
_cfg.QuitMinutes = StepPreset(_cfg.QuitMinutes, -1);
_clockStartMs = Now();
_dirty = true;
Publish();
});
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Minutes with no kill before Kill Client quits.\nClick: longer. Right-click: shorter. (1, 2, 5, 10, 15, 30)");
BoolRow("Auto Start On Arrival##vdautostart", s.AutoStart,
v => PostEdit(c => c.AutoStart = v),
"Switch On by itself when you arrive in the chosen dungeon (logging in there counts).");
BoolRow("Disable Meta##vdnometa", s.DisableMeta,
v => PostEdit(c => c.DisableMeta = v),
"On arriving: " + CmdMetaOff);
BoolRow("Disable Nav##vdnonav", s.DisableNav,
v => PostEdit(c => c.DisableNav = v),
"On arriving: " + CmdNavOff);
BoolRow("Repeat Attacks On##vdrepeat", s.RepeatAttack,
v => PostEdit(c => c.RepeatAttack = v),
"On arriving: " + CmdRepeatOn);
BoolRow("Set Attack Power##vdpower", s.SetPower,
v => PostEdit(c => c.SetPower = v),
"On arriving: " + CmdAttackBar + PowerText(s.AttackPower));
ImGui.SameLine();
int pi = PowerIndex(s.AttackPower);
if (ImGui.SmallButton(Powers[pi].Name + "##vdpowercycle"))
PostEdit(c => c.AttackPower = Powers[(pi + 1) % Powers.Length].Value);
if (ImGui.IsItemClicked(ImGuiMouseButton.Right))
PostEdit(c => c.AttackPower = Powers[(pi - 1 + Powers.Length) % Powers.Length].Value);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Fast (0), Medium (0.5) or Full Power (1).\nClick: next. Right-click: back.");
}
ImGui.Spacing();
ImGui.TextDisabled("Note: the client sees the landblock, not the layer - standing in the retail copy also counts as \"in it\".");
ImGui.TextDisabled("Kill Client: pet or fellow kills that pay you no luminance do not restart its timer.");
ImGui.TextDisabled("Recalls wait while RynthAi is in combat, buffing or waiting on the server.");
ImGui.TextDisabled("/ilt vaulted [on|off|toggle|status]");
}
private static void BoolRow(string id, bool value, Action<bool> set, string tip)
{
bool v = value;
if (ImGui.Checkbox(id, ref v)) set(v);
if (ImGui.IsItemHovered()) ImGui.SetTooltip(tip);
}
private static string[] BuildDungeonChoices()
{
var list = new string[Dungeons.Length + 1];
list[0] = "Pick a dungeon";
for (int i = 0; i < Dungeons.Length; i++) list[i + 1] = Dungeons[i].Name;
return list;
}
private static int StepPreset(int current, int dir)
{
if (dir > 0)
{
foreach (int m in QuitPresets) if (m > current) return m;
return QuitPresets[0];
}
for (int i = QuitPresets.Length - 1; i >= 0; i--)
if (QuitPresets[i] < current) return QuitPresets[i];
return QuitPresets[^1];
}
private static string Commas(long n)
{
string s = Math.Abs(n).ToString();
var chars = new List<char>();
for (int i = 0; i < s.Length; i++)
{
if (i > 0 && (s.Length - i) % 3 == 0) chars.Add(',');
chars.Add(s[i]);
}
return (n < 0 ? "-" : "") + new string(chars.ToArray());
}
// ── Config / snapshot types ─────────────────────────────────────────────
// internal (not private) so the source-generated IltVaultedDungeonsJsonContext can reach it.
internal sealed class Cfg
{
public bool Active { get; set; }
/// <summary>0 = none, 1..N = Dungeons index.</summary>
public int Dungeon { get; set; }
/// <summary>0 = none, 1 = primary, 2 = secondary.</summary>
public int Gem { get; set; }
public bool Quit { get; set; }
public int QuitMinutes { get; set; } = 2;
public bool ShowInDungeon { get; set; }
public bool AutoStart { get; set; }
public bool DisableMeta { get; set; }
public bool DisableNav { get; set; }
public bool RepeatAttack { get; set; }
public bool SetPower { get; set; }
public float AttackPower { get; set; }
}
private readonly record struct Snapshot(
bool Active, int Dungeon, int Gem, bool Quit, int QuitMinutes,
bool ShowInDungeon, bool AutoStart, bool DisableMeta, bool DisableNav,
bool RepeatAttack, bool SetPower, float AttackPower,
string State, long? QuitLeftMs, long IdleSecs, long InSinceMs, long OutSinceMs, long PortalSinceMs,
long RealKillMs, int Kills, long DungeonSecs, long NowMs, string Gate)
{
/// <summary>Before the first tick (the tab is only offered while the keeper may run).</summary>
public static Snapshot Empty => new(false, 0, 0, false, 2,
false, false, false, false, false, false, 0f,
"paused", null, 0, 0, 0, 0, 0, 0, 0, 0, string.Empty);
}
}
// Source-generated JSON only: the NativeAOT build (what the installer ships) has reflection-based
// serialization turned off, so JsonSerializer.Deserialize<Cfg>(text, options) failed there and the
// Vaulted Dungeons settings never loaded or saved. Same file format as before (camelCase,
// indented, nulls left out, case-sensitive property names on read).
[JsonSerializable(typeof(IltVaultedDungeons.Cfg))]
[JsonSourceGenerationOptions(
WriteIndented = true,
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
internal partial class IltVaultedDungeonsJsonContext : JsonSerializerContext { }

View file

@ -0,0 +1,294 @@
// IltWorld.cs - RynthILT's view of the game's objects, read straight from the host.
//
// The ILT Hub read items through RynthAi's WorldObjectCache while it lived in RynthAi. RynthILT
// has no cache of its own events, so this asks the client directly (the way RynthSort's
// InventoryReader does): the player's pack and side packs through GetContainerContents (the
// main pack's list also holds the side packs and the worn and wielded items), everything
// else the client knows through GetLiveObjectIds. Names, classes and container links are taken
// at each scan; property reads (Values) are live. A scan is kept for ScanMs, so the many
// Items() calls of one tick cost one walk; GetDirectInventory(forceRefresh: true) walks again.
// Pump thread only (the render thread only ever sees snapshots the features built).
using System;
using System.Collections.Generic;
using RynthCore.Loot;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One object as RynthILT sees it: identity from the last scan, properties read live.</summary>
internal sealed class WorldObject
{
private readonly IltObjects _owner;
internal WorldObject(IltObjects owner, int id, string name, AcObjectClass objectClass, int container)
{
_owner = owner;
Id = id;
Name = name ?? string.Empty;
ObjectClass = objectClass;
DirectContainerId = container;
}
public int Id { get; }
public string Name { get; }
public AcObjectClass ObjectClass { get; }
/// <summary>The container the scan found it in (the player or a side pack); 0 off the player.</summary>
public int DirectContainerId { get; }
/// <summary>The container it is in now (live), else where the scan found it.</summary>
public int Container => _owner.ContainerOf(Id, DirectContainerId);
/// <summary>Who wields it (live; 0 = nobody).</summary>
public int Wielder => _owner.WielderOf(Id);
/// <summary>Where it is wielded (live; 0 = not wielded).</summary>
public int WieldedLocation => _owner.WieldedLocationOf(Id);
/// <summary>An int property, read live (<paramref name="defaultValue"/> when unknown).</summary>
public int Values(int key, int defaultValue) => _owner.IntProperty(Id, unchecked((uint)key), defaultValue);
}
/// <summary>The player's items and the objects around, from host calls.</summary>
internal sealed class IltObjects
{
// Property and type ids (AC's).
internal const uint IntItemsCapacity = 6;
internal const uint IntCurrentWieldedLocation = 10;
internal const uint IntDamageType = 45;
private const uint ItemTypeCreature = 0x00000010;
private const uint ItemTypeContainer = 0x00000200;
private const long ScanMs = 1000;
private const int MainPackSlots = 102;
private readonly RynthCoreHost _host;
private uint[] _buf = new uint[512];
private List<WorldObject> _inventory = new();
private Dictionary<int, WorldObject> _byId = new();
private long _scannedAt = long.MinValue;
private uint _scannedPlayer;
public IltObjects(RynthCoreHost host) => _host = host;
/// <summary>Forgets the last scan (logout).</summary>
public void Clear()
{
_inventory = new List<WorldObject>();
_byId = new Dictionary<int, WorldObject>();
_scannedAt = long.MinValue;
_scannedPlayer = 0;
}
// ── Inventory ───────────────────────────────────────────────────────────
/// <summary>Everything the player carries or wears (a snapshot, at most ScanMs old).</summary>
public IEnumerable<WorldObject> GetInventory() => Scan(force: false);
/// <summary>The same walk; <paramref name="forceRefresh"/> reads the client again now.</summary>
public IReadOnlyList<WorldObject> GetDirectInventory(bool forceRefresh = false) => Scan(forceRefresh);
/// <summary>A carried item by id, else any object the client knows by id (null when it knows none).</summary>
public WorldObject? this[int id]
{
get
{
Scan(force: false);
if (_byId.TryGetValue(id, out var wo)) return wo;
uint uid = unchecked((uint)id);
if (id == 0 || !_host.HasGetObjectName || !_host.TryGetObjectName(uid, out string name)) return null;
return new WorldObject(this, id, name, Classify(uid), 0);
}
}
private List<WorldObject> Scan(bool force)
{
long now = Environment.TickCount64;
uint player = _host.GetPlayerId();
if (!force && player == _scannedPlayer && now - _scannedAt < ScanMs) return _inventory;
_scannedAt = now;
_scannedPlayer = player;
if (player == 0 || !_host.HasGetContainerContents) { _inventory = new(); _byId = new(); return _inventory; }
var list = new List<WorldObject>(256);
var byId = new Dictionary<int, WorldObject>(256);
int pid = unchecked((int)player);
foreach (uint id in Contents(player))
{
if (id == 0) continue;
uint type = ItemType(id);
Add(list, byId, id, type, pid);
// Side packs: containers with room for items (foci hold none).
if ((type & ItemTypeContainer) == 0) continue;
if (!_host.TryGetObjectIntProperty(id, IntItemsCapacity, out int cap) || cap <= 0) continue;
foreach (uint inner in Contents(id))
if (inner != 0) Add(list, byId, inner, ItemType(inner), unchecked((int)id));
}
_inventory = list;
_byId = byId;
return list;
}
private void Add(List<WorldObject> list, Dictionary<int, WorldObject> byId, uint id, uint type, int container)
{
int iid = unchecked((int)id);
if (byId.ContainsKey(iid)) return;
string name = _host.HasGetObjectName && _host.TryGetObjectName(id, out string n) ? n ?? string.Empty : string.Empty;
var wo = new WorldObject(this, iid, name, ClassifyByItemType(type), container);
list.Add(wo);
byId[iid] = wo;
}
private uint[] Contents(uint container)
{
int n = _host.GetContainerContents(container, _buf);
if (n >= _buf.Length)
{
_buf = new uint[Math.Max(n + 64, _buf.Length * 2)];
n = _host.GetContainerContents(container, _buf);
}
if (n <= 0) return Array.Empty<uint>();
var ids = new uint[Math.Min(n, _buf.Length)];
Array.Copy(_buf, ids, ids.Length);
return ids;
}
// ── The world around ────────────────────────────────────────────────────
/// <summary>Creatures the client knows (monsters, NPCs, vendors, pets), not carried.</summary>
public IEnumerable<WorldObject> GetLandscape() => Around(creaturesOnly: true);
/// <summary>Every object the client knows that the player doesn't carry.</summary>
public IEnumerable<WorldObject> GetLandscapeObjects() => Around(creaturesOnly: false);
private List<WorldObject> Around(bool creaturesOnly)
{
var result = new List<WorldObject>();
if (!_host.HasGetLiveObjectIds) return result;
Scan(force: false);
uint player = _host.GetPlayerId();
foreach (uint id in _host.GetLiveObjectIds())
{
if (id == 0 || id == player || _byId.ContainsKey(unchecked((int)id))) continue;
uint type = ItemType(id);
if (creaturesOnly && (type & ItemTypeCreature) == 0) continue;
if (!_host.HasGetObjectName || !_host.TryGetObjectName(id, out string name) || string.IsNullOrEmpty(name)) continue;
result.Add(new WorldObject(this, unchecked((int)id), name, ClassifyByItemType(type), 0));
}
return result;
}
/// <summary>Metres between two objects (double.MaxValue when either position can't be read).</summary>
public double Distance(int id1, int id2)
{
if (!_host.TryGetObjectPosition(unchecked((uint)id1), out uint cell1, out float x1, out float y1, out float z1)) return double.MaxValue;
if (!_host.TryGetObjectPosition(unchecked((uint)id2), out uint cell2, out float x2, out float y2, out float z2)) return double.MaxValue;
float gx1 = ((cell1 >> 24) & 0xFF) * 192f + x1;
float gy1 = ((cell1 >> 16) & 0xFF) * 192f + y1;
float gx2 = ((cell2 >> 24) & 0xFF) * 192f + x2;
float gy2 = ((cell2 >> 16) & 0xFF) * 192f + y2;
float dx = gx1 - gx2, dy = gy1 - gy2, dz = z1 - z2;
double d = Math.Sqrt(dx * dx + dy * dy + dz * dz);
return double.IsFinite(d) ? d : double.MaxValue;
}
// ── Live reads ──────────────────────────────────────────────────────────
internal int IntProperty(int id, uint stype, int defaultValue)
=> _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(unchecked((uint)id), stype, out int v) ? v : defaultValue;
internal int ContainerOf(int id, int scanned)
{
if (_host.HasGetObjectOwnershipInfo && _host.TryGetObjectOwnershipInfo(unchecked((uint)id), out uint container, out _, out _))
return unchecked((int)container);
return scanned;
}
internal int WielderOf(int id)
{
if (_host.HasGetObjectOwnershipInfo && _host.TryGetObjectOwnershipInfo(unchecked((uint)id), out _, out uint wielder, out _))
return unchecked((int)wielder);
return _host.HasGetObjectWielderInfo && _host.TryGetObjectWielderInfo(unchecked((uint)id), out uint w, out _) ? unchecked((int)w) : 0;
}
internal int WieldedLocationOf(int id)
{
if (_host.HasGetObjectOwnershipInfo && _host.TryGetObjectOwnershipInfo(unchecked((uint)id), out _, out uint wielder, out uint location) && wielder != 0)
return unchecked((int)location);
return Math.Max(0, IntProperty(id, IntCurrentWieldedLocation, 0));
}
private uint ItemType(uint id) => _host.HasGetItemType && _host.TryGetItemType(id, out uint t) ? t : 0;
private AcObjectClass Classify(uint id) => ClassifyByItemType(ItemType(id));
// ── Packs ───────────────────────────────────────────────────────────────
/// <summary>
/// A side pack with at least <paramref name="requireFree"/> free slots (the one with the most),
/// else the main pack when <paramref name="includeMainPack"/> and it has a slot, else 0. Foci
/// and packs whose capacity isn't known never qualify (a move into a full pack crashes the
/// client). RynthAi's WorldObjectCache.FindPackFor, on this view.
/// </summary>
public static int FindPackFor(RynthCoreHost host, IltObjects? objects, bool includeMainPack, int requireFree)
{
if (objects == null) return 0;
int playerId = unchecked((int)host.GetPlayerId());
if (playerId == 0) return 0;
if (requireFree < 1) requireFree = 1;
var inv = objects.GetDirectInventory(forceRefresh: true);
int bestPack = 0, bestFree = 0, mainUsed = 0;
foreach (var p in inv)
{
if (p.DirectContainerId != playerId) continue;
bool isPack = p.ObjectClass == AcObjectClass.Container;
bool isFoci = p.ObjectClass == AcObjectClass.Foci || p.Name.IndexOf("Foci", StringComparison.OrdinalIgnoreCase) >= 0;
if (!isPack && !isFoci && p.WieldedLocation <= 0 && p.Wielder == 0) mainUsed++;
if (!isPack || isFoci) continue;
int capacity = p.Values(unchecked((int)IntItemsCapacity), 0);
if (capacity <= 0) continue;
int used = 0;
foreach (var it in inv)
if (it.DirectContainerId == p.Id && it.ObjectClass != AcObjectClass.Container) used++;
int free = capacity - used;
if (free >= requireFree && free > bestFree) { bestFree = free; bestPack = p.Id; }
}
if (bestPack != 0) return bestPack;
if (!includeMainPack) return 0;
return MainPackSlots - mainUsed > 0 ? playerId : 0;
}
// ── Classification (RynthAi's WorldObjectCache.ClassifyByItemType) ──────
internal static AcObjectClass ClassifyByItemType(uint t)
{
if (t == 0) return AcObjectClass.Unknown;
if ((t & 0x00000010) != 0) return AcObjectClass.Monster;
if ((t & 0x00040000) != 0) return AcObjectClass.TradeNote;
if ((t & 0x00080000) != 0) return AcObjectClass.ManaStone;
if ((t & 0x00001000) != 0) return AcObjectClass.SpellComponent;
if ((t & 0x00000800) != 0) return AcObjectClass.Gem;
if ((t & 0x00004000) != 0) return AcObjectClass.Key;
if ((t & 0x10000000) != 0) return AcObjectClass.Lifestone;
if ((t & 0x40000000) != 0) return AcObjectClass.Salvage;
if ((t & 0x20000000) != 0) return AcObjectClass.Ust;
if ((t & 0x00400000) != 0) return AcObjectClass.BaseCooking;
if ((t & 0x00800000) != 0) return AcObjectClass.BaseAlchemy;
if ((t & 0x02000000) != 0) return AcObjectClass.BaseFletching;
if ((t & 0x04000000) != 0) return AcObjectClass.CraftedAlchemy;
if ((t & 0x08000000) != 0) return AcObjectClass.CraftedFletching;
if ((t & 0x00100000) != 0) return AcObjectClass.Services;
if ((t & 0x00010000) != 0) return AcObjectClass.Portal;
if ((t & 0x00002000) != 0) return AcObjectClass.Book;
if ((t & 0x00000200) != 0) return AcObjectClass.Container;
if ((t & 0x00008000) != 0) return AcObjectClass.WandStaffOrb;
if ((t & 0x00000100) != 0) return AcObjectClass.MissileWeapon;
if ((t & 0x00000002) != 0) return AcObjectClass.Armor;
if ((t & 0x00000001) != 0) return AcObjectClass.MeleeWeapon;
if ((t & 0x00000004) != 0) return AcObjectClass.Clothing;
if ((t & 0x00000008) != 0) return AcObjectClass.Jewelry;
if ((t & 0x00000020) != 0) return AcObjectClass.Food;
if ((t & 0x00000040) != 0) return AcObjectClass.Money;
if ((t & 0x00000080) != 0) return AcObjectClass.Misc;
return AcObjectClass.Unknown;
}
}

View file

@ -0,0 +1,317 @@
// RynthAiClient.cs - RynthILT's side of the "RynthAi.Hub" interface (Plugins/Shared/RynthAiHubApi.cs):
// the Mini Remote that hosts the ILT tabs, the /myquests tracker, spell names, VTank loot-profile
// matching, the .usd importer and the Mini Remote's session stats.
//
// The table is looked up through the host (API v68) and kept for RecheckMs; Reset() (login, logout,
// shutdown) and a table whose Version went to 0 (RynthAi shut down) force a fresh lookup, so a
// RynthAi that loads after RynthILT, is reloaded or isn't installed is handled: every call then
// reports "no RynthAi" and the ILT features that need it say so. The pointer is kept in a volatile
// field so the render thread (RenderSection) can use what the pump looked up; the table is never
// freed by RynthAi (its Version is zeroed instead), so a stale pointer is safe to read.
using System;
using System.Runtime.InteropServices;
using System.Text;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One /myquests flag as RynthAi has it (QuestRecord's fields the Temple tracker reads).</summary>
internal sealed class QuestRecord
{
public string Key = string.Empty;
public int Solves;
public int MaxSolves;
public DateTime CompletedOn = DateTime.MinValue;
public TimeSpan RepeatTime = TimeSpan.Zero;
/// <summary>RynthAi's QuestRecord.IsReady (UB's): the timer ran out and it isn't a once-only flag.</summary>
public bool IsReady()
{
if ((CompletedOn + RepeatTime) > DateTime.UtcNow) return false;
return !(MaxSolves == 1 && Solves <= 1);
}
/// <summary>Time until the flag can be solved again (zero when ready).</summary>
public TimeSpan TimeUntilReady()
{
var left = (CompletedOn + RepeatTime) - DateTime.UtcNow;
return left > TimeSpan.Zero ? left : TimeSpan.Zero;
}
}
internal sealed unsafe class RynthAiClient
{
public const string NotLoaded = "needs RynthAi (not loaded)";
private const long RecheckMs = 3000;
private readonly RynthCoreHost _host;
private RynthAiHubApiV1* _t; // pump-thread copy
private IntPtr _renderTable; // what the render thread uses (volatile)
private bool _checked;
private long _checkedAt;
private bool _pinned; // tests: a table handed in, never looked up
public RynthAiClient(RynthCoreHost host) => _host = host;
/// <summary>Tests only: use <paramref name="table"/> (a fake RynthAi's table) and never look it up.</summary>
internal void UseTableForTests(IntPtr table)
{
_pinned = true;
_t = (RynthAiHubApiV1*)table;
_checked = true;
System.Threading.Volatile.Write(ref _renderTable, table);
}
/// <summary>Forget the table; the next call looks it up again (login, logout, RynthAi reload).</summary>
public void Reset()
{
if (_pinned) return;
_t = null;
_checked = false;
System.Threading.Volatile.Write(ref _renderTable, IntPtr.Zero);
}
/// <summary>The table, looked up at most every RecheckMs (pump thread).</summary>
private RynthAiHubApiV1* Table
{
get
{
if (_pinned) return _t;
long now = Environment.TickCount64;
if (_checked && now - _checkedAt < RecheckMs && (_t == null || _t->Version >= 1)) return _t;
_checked = true;
_checkedAt = now;
_t = null;
if (_host.HasGetPluginInterface)
{
var t = (RynthAiHubApiV1*)_host.GetPluginInterface(RynthAiHub.PluginName, RynthAiHubApiV1.InterfaceName, RynthAiHubApiV1.InterfaceVersion);
if (t != null && t->Version >= 1 && t->StructSize >= RynthAiHubApiV1.BaseStructSize) _t = t;
}
System.Threading.Volatile.Write(ref _renderTable, (IntPtr)_t);
return _t;
}
}
/// <summary>Pump thread: refreshes the lookup (the render thread only reads what this found).</summary>
public void Tick() => _ = Table;
/// <summary>True when RynthAi's interface is there (pump thread).</summary>
public bool Available => Table != null;
/// <summary>Any thread: the table the pump last found, if RynthAi hasn't shut down since.</summary>
private RynthAiHubApiV1* AnyThreadTable
{
get
{
var t = (RynthAiHubApiV1*)System.Threading.Volatile.Read(ref _renderTable);
return t != null && t->Version >= 1 ? t : null;
}
}
// ── Mini Remote ─────────────────────────────────────────────────────────
/// <summary>Puts the Mini Remote on a tab (any thread). The reply, or why it couldn't.</summary>
public string MiniRemoteTab(string tabId, string mode)
{
var t = AnyThreadTable;
if (t == null || t->MiniRemoteTab == null) return "The Mini Remote is RynthAi's; RynthAi isn't loaded.";
byte* reply = stackalloc byte[256];
reply[0] = 0;
using var id = new Utf8(tabId);
using var m = new Utf8(mode);
int ok = t->MiniRemoteTab(id.P, m.P, reply, 256);
string text = Marshal.PtrToStringUTF8((IntPtr)reply) ?? string.Empty;
return ok != 0 ? text : (text.Length > 0 ? text : "The Mini Remote is not available yet.");
}
/// <summary>True while the Mini Remote is on screen (any thread).</summary>
public bool MiniRemoteVisible
{
get
{
var t = AnyThreadTable;
return t != null && t->MiniRemoteVisible != null && t->MiniRemoteVisible() != 0;
}
}
// ── Vaulted Dungeons (activity) ─────────────────────────────────────────
// The master switch is RynthILT's own since 2026-10-20 (IltHubState.VaultedDungeonsEnabled);
// RynthAi.Hub VaultedDungeonsEnabled is no longer read.
/// <summary>
/// What RynthAi is doing now (its "RynthAi.Activity" interface: combat, buffing, loot, a use or cast
/// waiting on the server...); null when RynthAi isn't loaded or isn't ready. Resolved again every
/// call, as that interface requires (a RynthAi reload frees its table). Pump thread.
/// </summary>
public RynthAiActivity? Activity()
{
if (!_host.HasGetPluginInterface) return null;
try
{
var act = (RynthAiActivityApiV1*)_host.GetPluginInterface(RynthAiHub.PluginName, RynthAiActivityApiV1.InterfaceName, RynthAiActivityApiV1.InterfaceVersion);
if (act == null || act->Version < 1 || act->StructSize < (uint)sizeof(RynthAiActivityApiV1) || act->GetActivityFlags == null) return null;
uint flags = 0;
return act->GetActivityFlags(&flags) != 0 ? (RynthAiActivity)flags : null;
}
catch
{
return null; // a RynthAi mid-reload: not there this tick
}
}
// ── Combat ──────────────────────────────────────────────────────────────
/// <summary>
/// Asks RynthAi to back away from <paramref name="objectId"/> (RynthAi.Hub BackAwayFrom): a
/// RynthAiHub.BackAway* result, or int.MinValue when RynthAi isn't loaded or is older than the
/// call. Pump thread.
/// </summary>
public int BackAwayFrom(uint objectId, float radiusYards, int holdMs)
{
var t = Table;
if (t == null || !RynthAiHubApiV1.Has(t, RynthAiHubApiV1.BackAwayFromOffset) || t->BackAwayFrom == null) return int.MinValue;
return t->BackAwayFrom(objectId, radiusYards, holdMs);
}
/// <summary>
/// Reports one player wield counter to RynthAi's loot rules (RynthAi.Hub SetPlayerCounter; the T11
/// "Can Wield" key): <paramref name="value"/> &lt; 0 = unknown. False without RynthAi (or an older one). Pump thread.
/// </summary>
public bool SetPlayerCounter(uint propertyId, long value)
{
var t = Table;
return t != null && RynthAiHubApiV1.Has(t, RynthAiHubApiV1.SetPlayerCounterOffset)
&& t->SetPlayerCounter != null && t->SetPlayerCounter(propertyId, value) != 0;
}
// ── Quests (/myquests) ──────────────────────────────────────────────────
/// <summary>A /myquests flag from RynthAi's tracker (pump thread).</summary>
public bool TryGetQuestFlag(string key, out QuestRecord rec)
{
rec = null!;
var t = Table;
if (t == null || t->QuestFlag == null || string.IsNullOrWhiteSpace(key)) return false;
QuestFlagV1 f = default;
using var k = new Utf8(key);
if (t->QuestFlag(k.P, &f) == 0) return false;
rec = new QuestRecord
{
Key = key.ToLowerInvariant(),
Solves = f.Solves,
MaxSolves = f.MaxSolves,
CompletedOn = new DateTime(Math.Max(0, f.CompletedOnUtcTicks), DateTimeKind.Utc),
RepeatTime = TimeSpan.FromSeconds(Math.Max(0, f.RepeatSeconds)),
};
return true;
}
/// <summary>The tracker's state (pump thread); false without RynthAi or before login.</summary>
public bool TryGetQuestStatus(out QuestStatusV1 status)
{
status = default;
var t = Table;
if (t == null || t->QuestStatus == null) return false;
QuestStatusV1 s = default;
if (t->QuestStatus(&s) == 0) return false;
status = s;
return true;
}
/// <summary>A quiet /myquests refresh through RynthAi's Quests tab (its cooldown applies). Pump thread.</summary>
public string RefreshQuests()
{
var t = Table;
if (t == null || t->QuestRefresh == null) return "The quest tracker " + NotLoaded + ".";
byte* reply = stackalloc byte[256];
reply[0] = 0;
t->QuestRefresh(reply, 256);
return Marshal.PtrToStringUTF8((IntPtr)reply) ?? string.Empty;
}
// ── Spells, loot profiles ───────────────────────────────────────────────
/// <summary>A spell's name from RynthAi's spell table ("" when unknown or no RynthAi). Pump thread.</summary>
public string SpellName(int spellId)
{
var t = Table;
if (t == null || t->SpellName == null || spellId <= 0) return string.Empty;
byte* buf = stackalloc byte[160];
int n = t->SpellName(unchecked((uint)spellId), buf, 160);
return n <= 0 ? string.Empty : Marshal.PtrToStringUTF8((IntPtr)buf) ?? string.Empty;
}
/// <summary>
/// Evaluates a VTank .utl profile on <paramref name="ids"/>: keep[i] is true when that item's
/// first matching rule is Keep. False (with the reason) when it couldn't. Pump thread.
/// </summary>
public bool LootKeeps(string utlPath, uint[] ids, out bool[] keep, out string error)
{
keep = new bool[ids.Length];
error = string.Empty;
var t = Table;
if (t == null || t->LootKeeps == null) { error = "equipment suits " + NotLoaded; return false; }
byte[] flags = new byte[ids.Length];
byte* err = stackalloc byte[256];
err[0] = 0;
int ok;
using (var p = new Utf8(utlPath))
fixed (uint* pids = ids)
fixed (byte* pf = flags)
ok = t->LootKeeps(p.P, pids, ids.Length, pf, err, 256);
if (ok == 0) { error = Marshal.PtrToStringUTF8((IntPtr)err) ?? "could not read profile"; return false; }
for (int i = 0; i < ids.Length; i++) keep[i] = flags[i] != 0;
return true;
}
// ── Session stats ───────────────────────────────────────────────────────
/// <summary>The Mini Remote's session (any thread); false without RynthAi or before login.</summary>
public bool TryGetSessionStats(out SessionStatsV1 stats)
{
stats = default;
var t = AnyThreadTable;
if (t == null || t->SessionStats == null) return false;
SessionStatsV1 s = default;
if (t->SessionStats(&s) == 0) return false;
stats = s;
return true;
}
/// <summary>Starts the Mini Remote's session over (any thread).</summary>
public void ResetSessionStats()
{
var t = AnyThreadTable;
if (t != null && t->SessionReset != null) t->SessionReset();
}
// ── RynthAi's sections drawn in RynthILT's tabs ─────────────────────────
/// <summary>Render thread: draws one of RynthAi's sections; false (nothing drawn) without RynthAi.</summary>
public bool RenderSection(string id)
{
var t = AnyThreadTable;
if (t == null || t->RenderSection == null) return false;
using var s = new Utf8(id);
return t->RenderSection(s.P) != 0;
}
/// <summary>A NUL-terminated UTF-8 copy of a string for one call.</summary>
private readonly struct Utf8 : IDisposable
{
public readonly byte* P;
public Utf8(string? s)
{
s ??= string.Empty;
int n = Encoding.UTF8.GetByteCount(s);
P = (byte*)NativeMemory.Alloc((nuint)(n + 1));
fixed (char* c = s) Encoding.UTF8.GetBytes(c, s.Length, P, n);
P[n] = 0;
}
public void Dispose() => NativeMemory.Free(P);
}
}

View file

@ -0,0 +1,115 @@
// ServerFeatureGate.cs — Which worlds get the ILT / infinite-attribute features.
// Originally part of SilentKelpie's ILT Hub in RynthAi; moved to RynthILT 2026-10-13.
//
// One gate for everything ILT-shaped: the Mini Remote's ILT tabs, the Guardian, the Skills
// panel's Progression planners and the attribute raiser. A world is "on" when:
// * its name matches one of the server patterns (IltSettings.ServerNames, '*' wildcard,
// case-insensitive; defaults cover InfiniteLeaftide; "/ilt servers"
// edits them — they were RynthAi's Settings > Misc "Server Features" list), or
// * this character's override is on ("Treat this world as ILT",
// "/ra hub force on"; also set by migration from RynthAi's "Force enable" profile flag).
// The gate only decides whether RynthILT ASKS the server; each feature still follows the
// server's own report (IltServerOptions bits), so a shard with /xp off keeps the raiser off.
using System;
using System.Collections.Generic;
using System.Linq;
namespace RynthCore.Plugin.RynthILT.Hub;
internal static class ServerFeatureGate
{
/// <summary>Patterns a fresh install starts with (the names the old hard-coded check accepted).</summary>
public static readonly string[] DefaultServerNames = { "InfiniteLeaftide", "*Leaftide*" };
/// <summary>The patterns in force (null settings: the defaults).</summary>
public static IReadOnlyList<string> Patterns(IltSettings? settings)
=> settings?.ServerNames is { Count: > 0 } list ? list : DefaultServerNames;
/// <summary>True when <paramref name="world"/> matches one of <paramref name="patterns"/>.</summary>
public static bool NameMatches(string world, IEnumerable<string>? patterns, out string matched)
{
matched = string.Empty;
if (string.IsNullOrWhiteSpace(world) || patterns == null) return false;
foreach (string p in patterns)
{
if (string.IsNullOrWhiteSpace(p)) continue;
if (!Matches(world.Trim(), p.Trim())) continue;
matched = p.Trim();
return true;
}
return false;
}
/// <summary>Case-insensitive match where '*' stands for any run of characters (anywhere in the pattern).</summary>
public static bool Matches(string text, string pattern)
{
if (pattern.Length == 0) return false;
if (!pattern.Contains('*')) return text.Equals(pattern, StringComparison.OrdinalIgnoreCase);
string[] parts = pattern.Split('*');
int pos = 0;
for (int i = 0; i < parts.Length; i++)
{
string part = parts[i];
if (part.Length == 0) continue;
if (i == 0)
{
if (!text.StartsWith(part, StringComparison.OrdinalIgnoreCase)) return false;
pos = part.Length;
continue;
}
if (i == parts.Length - 1)
return text.Length - pos >= part.Length && text.EndsWith(part, StringComparison.OrdinalIgnoreCase);
int at = text.IndexOf(part, pos, StringComparison.OrdinalIgnoreCase);
if (at < 0) return false;
pos = at + part.Length;
}
return true;
}
/// <summary>
/// RynthILT's own gate: the character's override, or the world name in the list. RynthCore's
/// verdict, once it sends one, takes over in IltServerOptions.IsIltLikeWorld; this stays ours
/// (it is what the status export reports, IltServerOptions.IsIltLikeWorldLocal).
/// </summary>
public static bool IsEnabled(string world, IltSettings? settings, bool forceOn)
=> forceOn || NameMatches(world, Patterns(settings), out _);
/// <summary>"InfiniteLeaftide, *Leaftide*" → trimmed, de-duplicated list (case-insensitive).</summary>
public static List<string> ParseList(string? text)
{
var list = new List<string>();
if (string.IsNullOrWhiteSpace(text)) return list;
foreach (string raw in text.Split(new[] { ',', ';', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries))
{
string p = raw.Trim();
if (p.Length > 0 && !list.Contains(p, StringComparer.OrdinalIgnoreCase)) list.Add(p);
}
return list;
}
public static string FormatList(IEnumerable<string>? patterns)
=> patterns == null ? string.Empty : string.Join(", ", patterns.Where(p => !string.IsNullOrWhiteSpace(p)));
/// <summary>One status line: the world, whether the features are on, and why.</summary>
public static string Describe(string world, IltSettings? settings, bool forceOn)
{
world = (world ?? string.Empty).Trim();
string shown = world.Length > 0 ? $"'{world}'" : "(not logged in)";
var engine = IltSettingsView.IltEngineVerdict.Server;
if (engine != null)
{
string why = engine.Force == "on" ? "forced on for this character"
: engine.Force == "off" ? "forced off for this character"
: engine.Detected ? "RynthCore recognises the world" : "RynthCore doesn't recognise the world";
return $"This world {shown}: {(engine.Active ? "ON" : "OFF")} - {why}.";
}
if (NameMatches(world, Patterns(settings), out string matched))
return $"This world {shown}: ON - matches '{matched}'.";
if (forceOn)
return $"This world {shown}: ON - \"Treat this world as ILT\" is ticked.";
return world.Length > 0
? $"This world {shown}: OFF - not in the list. Add it, or tick \"Treat this world as ILT\"."
: "This world: not logged in yet.";
}
}

View file

@ -0,0 +1,280 @@
// HubInterface.cs - RynthILT's side of the "RynthServer.Hub" interface (Plugins/Shared/RynthServerHubApi.cs), served also
// under its own older name "RynthILT.Hub" (RynthIltHubApi.cs): the table RynthPluginQueryInterface hands RynthAi, and the functions behind it.
//
// The table is allocated once per loaded copy of RynthILT and never freed (a plugin DLL is never
// unloaded, so its functions stay callable): RynthAi's render thread may still hold the pointer
// while plugins shut down, and every function here returns "nothing" once Release() has run
// (Version 0, no plugin). Threads as the interface says: the render-thread functions draw into
// the caller's current ImGui window; the pump-thread Command runs the ILT verb at once.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT;
internal static unsafe class HubInterface
{
private static RynthServerHubApiV1* _table;
private static volatile bool _released;
/// <summary>The live controller, or null (before login, after logout, after shutdown).</summary>
private static IltHubController? Hub => _released ? null : PluginExports.Runtime.Plugin?.Hub;
/// <summary>The table for (<paramref name="iface"/>, <paramref name="version"/>), or 0 when it isn't ours.</summary>
public static IntPtr Query(string iface, uint version)
{
// Its own name, and the neutral one RynthAi asks the active server's owner for (the same table).
if ((iface != RynthIltHub.InterfaceName && iface != RynthServerHubApiV1.InterfaceName)
|| version < 1 || version > RynthServerHubApiV1.InterfaceVersion || _released)
return IntPtr.Zero;
if (_table == null)
{
var t = (RynthServerHubApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerHubApiV1));
t->StructSize = (uint)sizeof(RynthServerHubApiV1);
t->IsServerWorld = &IsIltWorld;
t->GetFeature = &GetFeature;
t->GetRates = &GetRates;
t->GetForceServer = &GetForceIlt;
t->SetForceServer = &SetForceIlt;
t->GetTabs = &GetTabs;
t->RenderTab = &RenderTab;
t->RenderSection = &RenderSection;
t->Command = &Command;
t->AllowSummonOnEmpty = &AllowSummonOnEmpty;
t->GetSubTabs = &GetSubTabs;
t->GetSetting = &GetSetting;
t->SetSetting = &SetSetting;
t->GetText = &GetText;
t->Version = RynthServerHubApiV1.InterfaceVersion;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>Plugin shutdown: callers see Version 0 and re-query; the functions answer "nothing".</summary>
public static void Release()
{
_released = true;
if (_table != null) _table->Version = 0;
}
private static string? Utf8(byte* p) => p == null ? null : Marshal.PtrToStringUTF8((IntPtr)p);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int IsIltWorld()
{
try { return Hub?.Options.IsIltLikeWorld == true ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetFeature(byte* key)
{
try
{
var hub = Hub;
string? k = Utf8(key);
if (hub == null || string.IsNullOrEmpty(k) || !hub.Options.IsIltLikeWorld) return -1;
return (int)hub.Options.Get(k);
}
catch { return -1; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetRates(double* coinsPerHour, double* pyrealsPerHour)
{
try
{
var hub = Hub;
if (hub == null || !hub.Options.IsIltLikeWorld) return 0;
var r = hub.Rates.Summary;
if (coinsPerHour != null) *coinsPerHour = r.CoinsPerHour;
if (pyrealsPerHour != null) *pyrealsPerHour = r.PyrealsPerHour;
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetForceIlt()
{
try { return Hub?.ForceIltWorld == true ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void SetForceIlt(int on)
{
try
{
var hub = Hub;
if (hub != null) hub.ForceIltWorld = on != 0;
}
catch { }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetTabs(ServerHubTabV1* tabs, int capacity)
{
try
{
var hub = Hub;
if (hub == null) return 0;
var all = IltSections.Tabs;
if (tabs != null)
{
for (int i = 0; i < all.Length && i < capacity; i++)
{
IltSection s = all[i];
ServerHubTabV1* t = &tabs[i];
WriteUtf8(IltSections.TabId(s), t->Id, 24);
WriteUtf8(IltSections.Label(s), t->Label, 32);
var size = IltSections.TabSize(s);
t->Width = size.X;
t->Height = size.Y;
uint flags = 0;
if (hub.TabShown(s)) flags |= RynthServerHub.TabShown;
if (hub.SectionAvailable(s)) flags |= RynthServerHub.TabAvailable;
t->Flags = flags;
}
}
return all.Length;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int RenderTab(byte* id)
{
try
{
var hub = Hub;
if (hub == null || !IltSections.TryParse(Utf8(id) ?? string.Empty, out IltSection s) || !IltSections.IsTab(s)) return 0;
hub.RenderTab(s);
return 1;
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.IltHub, ex, "RenderTab");
return 0;
}
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int RenderSection(byte* id)
{
try
{
var hub = Hub;
string? s = Utf8(id);
return hub != null && s != null && hub.RenderSection(s) ? 1 : 0;
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.IltHub, ex, "RenderSection");
return 0;
}
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Command(byte* text)
{
try
{
var plugin = _released ? null : PluginExports.Runtime.Plugin;
string? line = Utf8(text);
if (plugin == null || string.IsNullOrWhiteSpace(line) || line.Length > 512) return 0;
return plugin.RunForwardedCommand(line) ? 1 : 0;
}
catch { return 0; }
}
/// <summary>The Pets tab's summon-from-empty gate (IltPetAutomation's last tick; 0 off ILT).</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int AllowSummonOnEmpty()
{
try { return Hub?.PetAutomation.AllowSummonOnEmpty == true ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetSubTabs(byte* parent, ServerHubTabV1* tabs, int capacity)
{
try
{
var hub = Hub;
string? p = Utf8(parent);
if (hub == null || p == null) return 0;
var all = hub.SubTabs(p);
if (tabs != null)
{
for (int i = 0; i < all.Length && i < capacity; i++)
{
ServerHubTabV1* t = &tabs[i];
WriteUtf8(all[i].Id, t->Id, 24);
WriteUtf8(all[i].Label, t->Label, 32);
t->Width = 0;
t->Height = 0;
t->Flags = RynthServerHub.TabShown | RynthServerHub.TabAvailable;
}
}
return all.Length;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetSetting(byte* key)
{
try
{
var hub = Hub;
string? k = Utf8(key);
return hub == null || k == null ? -1 : hub.GetSetting(k);
}
catch { return -1; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetSetting(byte* key, int value)
{
try
{
var hub = Hub;
string? k = Utf8(key);
return hub != null && k != null && hub.SetSetting(k, value) ? 1 : 0;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetText(byte* id, byte* buffer, int capacity)
{
try
{
var hub = Hub;
string? k = Utf8(id);
if (hub == null || k == null || buffer == null || capacity <= 0) return 0;
string text = hub.GetText(k);
if (text.Length == 0) { buffer[0] = 0; return 0; }
WriteUtf8(text, buffer, capacity);
int n = 0;
while (n < capacity && buffer[n] != 0) n++;
return n;
}
catch { return 0; }
}
/// <summary>Writes <paramref name="s"/> as NUL-terminated UTF-8 into a fixed buffer, truncated to fit.</summary>
private static void WriteUtf8(string s, byte* dest, int capacity)
{
byte[] bytes = Encoding.UTF8.GetBytes(s);
int n = Math.Min(bytes.Length, capacity - 1);
for (int i = 0; i < n; i++) dest[i] = bytes[i];
dest[n] = 0;
}
}

View file

@ -0,0 +1,62 @@
// IltFellowshipCommands.cs - Infinite Leaftide's fellowship chat commands (ACECustom /fship).
//
// ACECustom (Source/ACE.Server/Command/Handlers/PlayerCommands.cs, "fship") adds these on top
// of retail's fellowship panel; its fellowships hold up to 29 (Fellowship.MaxFellows). The list
// is kept in the shared "servercommands" form (Plugins/Shared/ServerCommandShare.cs) and drawn by
// RynthILT's fellowship window (IltFellowshipUi, "/ilt fellow").
// A name with spaces is sent quoted; ACE's command parser joins "two words". Pure: no ImGui, no host.
using System;
using System.Collections.Generic;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.IltFellowship;
internal static class IltFellowshipCommands
{
/// <summary>The RynthCore section the commands belong to.</summary>
public const string Section = "fellowship";
/// <summary>RynthCore's server id for Infinite Leaftide.</summary>
public const string ServerId = "ilt";
/// <summary>The server's display name.</summary>
public const string ServerName = "Infinite Leaftide";
/// <summary>ACECustom's fellowship size (Fellowship.MaxFellows; retail is 9).</summary>
public const int MaxFellows = 29;
/// <summary>The /fship commands, in button order.</summary>
public static readonly IReadOnlyList<ServerCommand> Commands = new[]
{
new ServerCommand("Create", "/fship create", "A",
"Create a fellowship with the name in the box (you lead it). Up to " + MaxFellows + " members on ILT."),
new ServerCommand("Invite", "/fship add", "a",
"Invite the player named in the box, or your selected player when the box is empty."),
new ServerCommand("Dismiss", "/fship remove", "ac",
"Leader: remove the player named in the box, or your selected player when the box is empty."),
new ServerCommand("Invite landblock", "/fship landblock", "c",
"Invite every player in your landblock (not in the Marketplace). Over level 50, only level 50+ players are invited."),
new ServerCommand("List nearby", "/fship list", "",
"The fellowships in your area and their leaders (wider in VOD and T10). Once every 10 seconds."),
new ServerCommand("Leave", "/fship leave", "c",
"Leave your fellowship."),
new ServerCommand("Disband", "/fship disband", "c",
"Leader: disband your fellowship."),
new ServerCommand("Help", "/fship", "",
"The server's /fship help."),
};
/// <summary>The set while ILT is active; with no commands when it isn't (a receiver drops it).</summary>
public static ServerCommandSet Set(bool active) =>
new(Section, ServerId, ServerName, active ? Commands : Array.Empty<ServerCommand>());
/// <summary>The "servercommands" payload for <see cref="Set"/>.</summary>
public static string Payload(bool active) => ServerCommandShare.Build(Set(active));
/// <summary>
/// ILT is active: RynthCore's verdict once it has sent one (<paramref name="engineActive"/>),
/// else the world name has "Leaftide" in it (RynthCore's default ILT names).
/// </summary>
public static bool IsActive(bool? engineActive, string? worldName) =>
engineActive ?? (worldName ?? string.Empty).IndexOf("Leaftide", StringComparison.OrdinalIgnoreCase) >= 0;
}

View file

@ -0,0 +1,44 @@
// IltFellowshipUi.cs - The "ILT fellowship" view: Infinite Leaftide's /fship commands as buttons.
//
// Drawn in its own window ("/ilt fellow"). Clicks queue the chat command for the plugin tick.
// Render thread only.
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.IltFellowship;
internal sealed class IltFellowshipUi
{
private const string WindowTitle = "ILT fellowship (RynthILT)##rynthilt_fellowship";
private static readonly ServerCommandSet Set = IltFellowshipCommands.Set(active: true);
private readonly ServerCommandPanel _panel = new("iltfship");
private readonly Func<string, bool> _send;
/// <summary>The standalone window is open ("/ilt fellow").</summary>
public bool WindowOpen;
/// <param name="send">Queues a chat command for the plugin tick; false when it can't.</param>
public IltFellowshipUi(Func<string, bool> send) => _send = send;
/// <summary>The standalone window, while open.</summary>
public void RenderWindow()
{
if (!WindowOpen) return;
ImGui.SetNextWindowSize(new Vector2(420, 170), ImGuiCond.FirstUseEver);
bool open = WindowOpen;
if (ImGui.Begin(WindowTitle, ref open)) RenderBody();
ImGui.End();
WindowOpen = open;
}
/// <summary>The view's content, into the current window.</summary>
public void RenderBody()
{
SafeImGui.TextDisabled("Infinite Leaftide /fship (up to " + IltFellowshipCommands.MaxFellows + " members)");
_panel.Render(Set, _send);
}
}

View file

@ -0,0 +1,133 @@
// IltSectionsManifest.cs - What RynthILT adds to RynthCore's Mini Remote sections (RynthPluginGetSectionsJson,
// schema 1: UI/Sections/SectionManifest.cs in RynthCore).
//
// always (Infinite Leaftide views, shown while RynthCore treats this world as ILT)
// Session Stats ("char") the ILT session extras section:ilt-rates
// Fellowship ILT's /fship commands section:ilt-fellowship
// Quests (RynthILT's own) the /qb list section:ilt-questbonus
// Dynamic Stamps (RynthOracle's section:ilt-dynstamps
// until 2026-10-21)
// while the Hub shows them (an ILT world; each once the server reports its feature)
// Inventory Gear, Charms, Banking section:gear|charms|banking
// Games (RynthILT's own) Games section:games
// Nav Vaulted Dungeons (master switch) section:vaulted
// The Mini Remote tabs were listed by RynthAi, which hosted them, until 2026-10-20; RynthILT lists and
// draws them itself now (RynthPluginRenderEmbed "section:<tab>"), so RynthAi's manifest names no
// server's tabs. Their names stay the same, so "/rc miniremote tab charms|banking" finds them.
// Pure: the tabs come in as a list, so the tests build it offline.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
using RynthCore.Plugin.RynthILT.Hub;
namespace RynthCore.Plugin.RynthILT;
internal static class IltSectionsManifest
{
/// <summary>RynthCore's id for Infinite Leaftide.</summary>
public const string Server = "ilt";
/// <summary>One Mini Remote tab as the Hub has it now.</summary>
internal readonly record struct Tab(string Id, float Width, float Height, bool Shown, bool Available);
private const string NotReportedNote = "Shows once the server reports this ILT feature on (the ILT settings can ask again).";
/// <summary>Where each tab goes: section, label, order, tooltip. A tab not listed here isn't offered.</summary>
internal static readonly Dictionary<string, (string Section, string Label, int Order, string Tooltip)> Placement = new()
{
["gear"] = ("inventory", "Gear", 210, "ILT gear tools (RynthILT)."),
["charms"] = ("inventory", "Charms", 220, "ILT charms and Guardian Hands: acquired, status, tier, toggles (RynthILT)."),
["banking"] = ("inventory", "Banking", 230, "Your ILT bank: balances, deposits, withdrawals and transfers (RynthILT)."),
["games"] = ("games", "Games", 100, "ILT games (RynthILT)."),
// Listed only while the Hub shows the tab: the master switch is on, on an ILT world.
["vaulted"] = ("nav", "Vaulted Dungeons", 220,
"Keep the character in one Vaulted Dungeon (RynthILT; master switch: /ilt settings or Settings > Navigation)."),
};
/// <summary>The surface of a tab's view ("section:gear").</summary>
public static string SurfaceOf(string tabId) => "section:" + tabId;
/// <summary>The tab a "section:&lt;tab&gt;" surface draws, when it names one placed here.</summary>
public static bool TryTabOf(string surface, out IltSection section)
{
section = IltSection.Gear;
if (!surface.StartsWith("section:", System.StringComparison.Ordinal)) return false;
string id = surface.Substring("section:".Length);
if (!Placement.ContainsKey(id) || !IltSections.TryParse(id, out section) || !IltSections.IsTab(section)) return false;
return IltSections.TabId(section) == id;
}
/// <summary>The Hub's tabs now (empty without a Hub). Render thread.</summary>
public static List<Tab> TabsOf(IltHubController? hub)
{
var list = new List<Tab>();
if (hub == null) return list;
foreach (IltSection s in IltSections.Tabs)
{
var size = IltSections.TabSize(s);
list.Add(new Tab(IltSections.TabId(s), size.X, size.Y, hub.TabShown(s), hub.SectionAvailable(s)));
}
return list;
}
/// <summary>The manifest JSON (UTF-8 text, schema 1).</summary>
public static string Build(IReadOnlyList<Tab> tabs)
{
using var stream = new MemoryStream(4096);
using (var w = new Utf8JsonWriter(stream))
{
w.WriteStartObject();
w.WriteNumber("version", 1);
w.WriteStartArray("sections");
Section(w, "quests", "Quests", 1160);
Section(w, "games", "Games", 1150);
w.WriteEndArray();
w.WriteStartArray("contributions");
View(w, "char", "ILT session rates (RynthILT)", RynthILTPlugin.RatesSurface, primary: false, 0, 220, enabled: true, note: "",
"Enlightened Coins, pyreals and item conversions this session, on the same clock as RynthAi's session stats (RynthILT).", 120);
View(w, "fellowship", "ILT fellowship (RynthILT)", RynthILTPlugin.FellowshipSurface, primary: false, 0, 110, enabled: true, note: "",
"Infinite Leaftide's /fship commands: create, invite, dismiss, invite your landblock, list nearby, leave, disband (RynthILT; also /ilt fellow).", 120);
View(w, "quests", "Quest bonus (/qb)", RynthILTPlugin.QuestBonusSurface, primary: true, 520, 440, enabled: true, note: "",
"Infinite Leaftide's quest bonus list: completed and incomplete /qb flags (RynthILT; the quest list, timers and rewards are RynthOracle's, /ro).", 100);
View(w, "quests", "Dynamic Stamps", RynthILTPlugin.DynamicStampsSurface, primary: true, 600, 560, enabled: true, note: "",
"Infinite Leaftide's Dynamic Stamps: the NPC stamps you have and are missing, RynthNav's way there and the Parchment hand-in (RynthILT; also /ilt stamps).", 110);
foreach (Tab t in tabs)
{
if (!t.Shown || !Placement.TryGetValue(t.Id, out var place)) continue;
View(w, place.Section, place.Label, SurfaceOf(t.Id), primary: true, t.Width, t.Height, t.Available,
t.Available ? string.Empty : NotReportedNote, place.Tooltip, place.Order);
}
w.WriteEndArray();
w.WriteEndObject();
}
return Encoding.UTF8.GetString(stream.ToArray());
}
private static void Section(Utf8JsonWriter w, string id, string label, int order)
{
w.WriteStartObject();
w.WriteString("id", id);
w.WriteString("label", label);
w.WriteNumber("order", order);
w.WriteEndObject();
}
private static void View(Utf8JsonWriter w, string section, string label, string surface, bool primary, float width, float height,
bool enabled, string note, string tooltip, int order)
{
w.WriteStartObject();
w.WriteString("section", section);
w.WriteString("server", Server);
w.WriteString("label", label);
w.WriteString("surface", surface);
w.WriteBoolean("primary", primary);
if (width > 0) w.WriteNumber("width", width);
if (height > 0) w.WriteNumber("height", height);
w.WriteBoolean("enabled", enabled);
if (note.Length > 0) w.WriteString("note", note);
if (tooltip.Length > 0) w.WriteString("tooltip", tooltip);
w.WriteNumber("order", order);
w.WriteEndObject();
}
}

View file

@ -0,0 +1,32 @@
// IltEngineVerdict.cs - RynthCore's Infinite Leaftide verdict as RynthILT last heard it.
//
// RynthCore decides whether this world is ILT once, for itself and every plugin, with this
// character's Auto / On / Off override ("/rc server ilt"). RynthILT reads that verdict from the
// engine's server list (plugin API v86, GetServerStateJson; the plugin tick polls it into
// IltSettingsModel.Engine). The Hub's world check (IltServerOptions, ServerFeatureGate) follows it
// once one has arrived; before that, or on an engine older than v86, RynthILT's own server list
// and "Treat this world as ILT" decide.
//
// RynthILT's status export must keep reporting its own verdict, not this one: the engine adds
// RynthILT's verdict to its detection, and an echo would keep ILT on after "/rc ilt auto".
// Any thread: one volatile reference read.
using System.Threading;
namespace RynthCore.Plugin.RynthILT.IltSettingsView;
internal static class IltEngineVerdict
{
private static IltSettingsModel? _model;
/// <summary>The model the plugin feeds from RynthCore's server list (RynthILTPlugin's constructor).</summary>
public static void Attach(IltSettingsModel? model) => Volatile.Write(ref _model, model);
/// <summary>RynthCore has sent its server list at least once since login (it may list no ILT).</summary>
public static bool Pushed => Volatile.Read(ref _model)?.Engine != null;
/// <summary>RynthCore's ILT entry; null until a RynthCore with the server list (v86) has sent one.</summary>
public static IltServerView? Server => Volatile.Read(ref _model)?.Engine?.Server;
/// <summary>RynthCore's verdict for this world; null when it hasn't given one.</summary>
public static bool? Active => Server?.Active;
}

View file

@ -0,0 +1,114 @@
// IltSettingsModel.cs - RynthILT's copy of the Infinite Leaftide settings (the "ILT settings" view).
//
// Nothing here is decided by RynthILT; it shows and edits what others own:
// * RynthCore owns the world verdict, this character's Auto / On / Off override and the ILT
// world-name list. RynthILT reads the verdict from its server list (plugin API v86,
// GetServerStateJson, parsed by Plugins/Shared/EngineServerState.cs): the plugin tick polls
// it every 2 s and publishes the "ilt" entry here (ApplyServerState). The world names aren't
// in that list; "/rc server names ilt" prints them. Edits go back as RynthCore commands:
// "/rc server ilt auto|on|off" and "/rc server names ilt add|remove <pattern>".
// * RynthILT's own Hub reads which ILT features the server has on; the plugin tick publishes
// them (PublishFeatures).
// Each is one immutable snapshot published with a single reference write, so the render thread
// always reads a whole one. Pure (no host calls): RynthILT.Tests covers it.
using System;
using System.Collections.Generic;
using System.Threading;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.IltSettingsView;
/// <summary>RynthCore's verdict for Infinite Leaftide.</summary>
internal sealed record IltServerView(string Name, bool Active, string Force, bool Detected, string Reason);
/// <summary>What RynthCore's server list says: the ILT verdict (null if it lists no "ilt").</summary>
internal sealed record IltEngineView(IltServerView? Server);
/// <summary>The Hub's server read: the world, its last check, and each feature (-1 unknown, 0 off, 1 on).</summary>
internal sealed record IltFeatureView(string World, string Source, string LastCheck, bool Checking, bool IltLike,
KeyValuePair<string, int>[] Features);
internal sealed class IltSettingsModel
{
/// <summary>RynthCore's id for Infinite Leaftide.</summary>
public const string ServerId = Hub.IltServerOptions.EngineServerId;
/// <summary>Longest pattern RynthCore keeps (EngineSettings.MaxIltServerNameLength).</summary>
public const int MaxPattern = 64;
/// <summary>The RynthCore command that prints the ILT world names (and hosts) in chat.</summary>
public const string NamesListCommand = "/rc server names " + ServerId;
private IltEngineView? _engine;
private IltFeatureView? _features;
/// <summary>The last server list from RynthCore (null until one arrives). Any thread.</summary>
public IltEngineView? Engine => Volatile.Read(ref _engine);
/// <summary>The last feature read (null until the Hub publishes one). Any thread.</summary>
public IltFeatureView? Features => Volatile.Read(ref _features);
/// <summary>RynthCore's server list (GetServerStateJson); null (no answer) keeps the last one. Any thread.</summary>
public void ApplyServerState(EngineServerState? state)
{
IltEngineView? view = FromServerState(state);
if (view != null) Volatile.Write(ref _engine, view);
}
/// <summary>The Hub's own feature read (plugin tick); null clears it. Any thread.</summary>
public void PublishFeatures(IltFeatureView? view) => Volatile.Write(ref _features, view);
/// <summary>Logout: the next character's world and features come fresh.</summary>
public void Clear()
{
Volatile.Write(ref _engine, null);
Volatile.Write(ref _features, null);
}
/// <summary>The ILT verdict from RynthCore's server list; null for no list.</summary>
public static IltEngineView? FromServerState(EngineServerState? state)
{
if (state == null) return null;
EngineServer? s = state.Find(ServerId);
return new IltEngineView(s == null ? null
: new IltServerView(s.Name.Length > 0 ? s.Name : "Infinite Leaftide", s.Active, NormalizeForce(s.Force), s.Detected, s.Reason));
}
/// <summary>"auto", "on" or "off" (anything else is shown as auto).</summary>
public static string NormalizeForce(string? force) => (force ?? string.Empty).Trim().ToLowerInvariant() switch
{
"on" => "on",
"off" => "off",
_ => "auto",
};
/// <summary>The RynthCore command that sets this character's override; "" for an unknown mode.</summary>
public static string ForceCommand(string mode) => mode switch
{
"auto" or "on" or "off" => "/rc server " + ServerId + " " + mode,
_ => string.Empty,
};
/// <summary>
/// The RynthCore command that adds or removes a world-name pattern, or "" (with
/// <paramref name="error"/>) when the pattern can't be sent: empty, longer than
/// <see cref="MaxPattern"/>, or with a control character or '/' (it is spliced into a command).
/// </summary>
public static string NamesCommand(bool add, string? pattern, out string error)
{
error = string.Empty;
string p = (pattern ?? string.Empty).Trim();
if (p.Length == 0) { error = "Enter a world name ('*' matches any text)."; return string.Empty; }
if (p.Length > MaxPattern) { error = $"At most {MaxPattern} characters."; return string.Empty; }
foreach (char c in p)
if (char.IsControl(c) || c == '/' || c >= 128)
{
error = "World names are plain text (no '/', line breaks or special characters).";
return string.Empty;
}
return "/rc server names " + ServerId + (add ? " add " : " remove ") + p;
}
/// <summary>A feature's state as text.</summary>
public static string StateText(int value) => value switch { 1 => "on", 0 => "off", _ => "unknown" };
}

View file

@ -0,0 +1,237 @@
// IltSettingsUi.cs - The "ILT settings" view: RynthILT's copy of the Infinite Leaftide settings.
//
// Drawn in its own window ("/ilt settings"). Shows RynthCore's verdict and reason, this character's
// Auto / On / Off override, the ILT world names (edited through RynthCore), this character's ILT
// options (the settings that moved here from RynthAi on 2026-10-20: the Empyrean Handler ring
// evade, ...; saved in the Hub's state), and every ILT feature with the state RynthILT's Hub read
// from the server (IltSettingsModel has where each comes from).
// Edits are RynthCore commands, queued for the plugin tick; the next server-list poll shows the
// result. Render thread only.
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.IltSettingsView;
internal sealed class IltSettingsUi
{
private static readonly Vector4 Teal = new(0.30f, 0.85f, 0.80f, 1f);
private static readonly Vector4 Mute = new(0.60f, 0.62f, 0.66f, 1f);
private static readonly Vector4 Warn = new(0.95f, 0.55f, 0.45f, 1f);
private const string WindowTitle = "ILT settings (RynthILT)##rynthilt_settings";
private readonly IltSettingsModel _model;
private readonly Action<string> _runCommand;
private readonly Func<bool> _refreshFeatures;
private readonly Func<IltHubController?> _hub;
private string _newName = string.Empty;
private string _status = string.Empty;
/// <summary>The standalone window is open ("/ilt settings").</summary>
public bool WindowOpen;
/// <param name="runCommand">Queues a RynthCore command (run on the plugin tick).</param>
/// <param name="refreshFeatures">Asks the Hub to read the server's features again; false before it exists.</param>
/// <param name="hub">This character's Hub (its options live in the Hub's state); null before login.</param>
public IltSettingsUi(IltSettingsModel model, Action<string> runCommand, Func<bool> refreshFeatures, Func<IltHubController?>? hub = null)
{
_model = model;
_runCommand = runCommand;
_refreshFeatures = refreshFeatures;
_hub = hub ?? (() => null);
}
/// <summary>The standalone window, while open.</summary>
public void RenderWindow()
{
if (!WindowOpen) return;
ImGui.SetNextWindowSize(new Vector2(440, 480), ImGuiCond.FirstUseEver);
bool open = WindowOpen;
if (ImGui.Begin(WindowTitle, ref open)) RenderBody();
ImGui.End();
WindowOpen = open;
}
/// <summary>The view's content, into the current window.</summary>
public void RenderBody()
{
RenderVerdict();
ImGui.Separator();
RenderCharacterOptions();
ImGui.Separator();
RenderFeatures();
if (_status.Length > 0)
{
ImGui.Separator();
SafeImGui.TextWrapped(_status);
}
}
private void RenderVerdict()
{
IltEngineView? engine = _model.Engine;
if (engine == null)
{
ImGui.TextWrapped("Waiting for RynthCore's server list (it needs plugin API v86). Until then RynthILT's own "
+ "world list and this character's 'Treat this world as ILT' (/ra hub force on|off) decide.");
return;
}
IltServerView? s = engine.Server;
if (s == null)
{
ImGui.TextDisabled("RynthCore doesn't list Infinite Leaftide.");
}
else
{
SafeImGui.TextColored(s.Active ? Teal : Mute, s.Active ? s.Name + ": on for this world" : s.Name + ": not this world");
if (s.Reason.Length > 0)
{
ImGui.PushStyleColor(ImGuiCol.Text, Mute);
SafeImGui.TextWrapped(s.Reason);
ImGui.PopStyleColor();
}
// Read only: a server is forced in one place, RynthCore Options > Diagnostics (2026-10-13).
string force = s.Force switch { "on" => "forced on", "off" => "forced off", _ => "auto (detected)" };
SafeImGui.TextDisabled("This character: " + force + " (change it in RynthCore Options > Diagnostics)");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("RynthCore's server selection (Options > Diagnostics) forces a server for this character,\nor /rc server ilt auto|on|off in chat.");
}
ImGui.Spacing();
ImGui.TextUnformatted("ILT world names");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Worlds whose name matches one of these count as Infinite Leaftide ('*' matches any text).\nThe launch host is checked too. Kept by RynthCore for every character.");
ImGui.SameLine();
if (ImGui.SmallButton("List in chat##iltnames"))
{
_runCommand(IltSettingsModel.NamesListCommand);
_status = "RynthCore lists the names in chat (" + IltSettingsModel.NamesListCommand + ").";
}
ImGui.SetNextItemWidth(220);
bool enter = ImGui.InputTextWithHint("##iltnewname", "world name, * = any text", ref _newName, (uint)IltSettingsModel.MaxPattern,
ImGuiInputTextFlags.EnterReturnsTrue);
ImGui.SameLine();
if (ImGui.Button("Add##iltname") || enter)
{
string cmd = IltSettingsModel.NamesCommand(true, _newName, out string err);
if (Send(cmd, err, "Adding '" + _newName.Trim() + "'...")) _newName = string.Empty;
}
ImGui.SameLine();
if (ImGui.Button("Remove##iltname"))
{
string cmd = IltSettingsModel.NamesCommand(false, _newName, out string err);
if (Send(cmd, err, "Removing '" + _newName.Trim() + "'...")) _newName = string.Empty;
}
}
/// <summary>
/// This character's Infinite Leaftide options: the ones that were RynthAi settings until
/// 2026-10-20 (copied over once). Saved with the Hub's state.
/// </summary>
private void RenderCharacterOptions()
{
ImGui.TextUnformatted("This character");
IltHubController? hub = _hub();
if (hub == null)
{
ImGui.TextDisabled("Shown once this character is logged in.");
return;
}
IltHubState st = hub.State;
bool vaulted = st.VaultedDungeonsEnabled;
if (ImGui.Checkbox("Vaulted Dungeons (the keeper's master switch)##iltvaulted", ref vaulted)) st.VaultedDungeonsEnabled = vaulted;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Off by default. While off the Vaulted Dungeons keeper does nothing: no recalls, no /rc quit, no Mini\n"
+ "Remote tab. On: the \"Vaulted Dungeons\" tab shows, where you pick a dungeon and a tied Portal Recall\n"
+ "Gem and start it (/ilt vaulted on). Also in RynthCore's Settings > Navigation (it was a RynthAi setting).");
bool ring = st.Combat.HandlerRingEvade;
if (ImGui.Checkbox("Evade the Empyrean Handler's lethal ring##iltring", ref ring)) st.Combat.HandlerRingEvade = ring;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When an Empyrean Handler channels its lethal ring and you are within 12 yards (or RynthAi's\n"
+ "Ring Range if larger), RynthAi back-jumps away and re-engages. Only while RynthAi's macro\n"
+ "is running with combat on. On by default (it was RynthAi's \"Evade Handler Ring\").");
int augs = st.T11.ItemAugsOverride;
SafeImGui.TextDisabled(augs >= 0
? $"T11 item augmentations: fixed at {augs:N0} for RynthAi's loot rules (/ilt t11 augs auto to read /aug)"
: "T11 item augmentations: read from /aug (/ilt t11 augs <n> fixes them; /ilt t11 shows the counters)");
}
/// <summary>
/// The server's ILT features, one collapsible section per group (Character, Items, Pets,
/// Fellowship, Combat, Activities, then the charms and any other bit chat or a probe set), with
/// how many are on and each feature's state; the tooltip says where the Rynth tools handle it.
/// </summary>
private void RenderFeatures()
{
IltFeatureView? f = _model.Features;
ImGui.TextUnformatted("Server features");
ImGui.SameLine();
if (ImGui.SmallButton("Refresh##iltfeatures"))
_status = _refreshFeatures() ? "Checking the server again..." : "Not ready yet (log in first).";
if (f == null)
{
ImGui.TextWrapped("RynthILT reads which ILT features the server has on once this character is logged in. Not read yet.");
return;
}
string when = f.Checking ? "checking the server..." : f.LastCheck.Length == 0 ? "not checked yet" : "checked " + f.LastCheck;
SafeImGui.TextDisabled((f.World.Length > 0 ? f.World : "unknown world") + " - " + when
+ (f.Source.Length > 0 ? " (" + f.Source + ")" : string.Empty));
if (!f.IltLike) ImGui.TextDisabled("This world isn't treated as Infinite Leaftide, so the server isn't asked.");
if (f.Features.Length == 0)
{
ImGui.TextDisabled("The server hasn't reported any ILT features yet.");
return;
}
var groups = new Dictionary<string, List<(string Label, string Tooltip, int State)>>(StringComparer.Ordinal);
foreach (var kv in f.Features)
{
var (label, group, tooltip) = IltFeatureCatalog.Describe(kv.Key);
if (!groups.TryGetValue(group, out var rows)) groups[group] = rows = new();
rows.Add((label, tooltip, kv.Value));
}
foreach (string group in FeatureGroups())
{
if (!groups.TryGetValue(group, out var rows)) continue;
int on = 0, off = 0;
foreach (var r in rows) { if (r.State == 1) on++; else if (r.State == 0) off++; }
if (!ImGui.CollapsingHeader($"{group} ({on} of {rows.Count} on)##iltfg_{group}")) continue;
for (int i = 0; i < rows.Count; i++)
{
var r = rows[i];
SafeImGui.TextColored(r.State == 1 ? Teal : r.State == 0 ? Warn : Mute, IltSettingsModel.StateText(r.State));
ImGui.SameLine(80);
SafeImGui.Text(r.Label);
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(r.Tooltip);
}
}
}
/// <summary>The feature sections in display order: the catalog's groups, then Charms and Other.</summary>
private static IEnumerable<string> FeatureGroups()
{
foreach (string g in IltFeatureCatalog.Groups) yield return g;
yield return IltFeatureCatalog.GroupCharms;
yield return IltFeatureCatalog.GroupOther;
}
/// <summary>Queues <paramref name="command"/>, or shows <paramref name="error"/> when it is empty.</summary>
private bool Send(string command, string error, string pending)
{
if (command.Length == 0)
{
_status = error;
return false;
}
_runCommand(command);
_status = pending;
return true;
}
}

View file

@ -0,0 +1,312 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT;
public static unsafe class PluginExports
{
internal static readonly RynthPluginRuntime<RynthILTPlugin> Runtime = new();
// Typed interfaces (host GetPluginInterface, API v68): "RynthILT.Hub" v1, the ILT tabs and
// sections RynthAi's Mini Remote hosts (Plugins/Shared/RynthServerHubApi.cs, HubInterface.cs), and
// "RynthServer.Profile" v1, ILT's settings and tinkering salvage for any reader, as every server
// plugin serves its own (Plugins/Shared/RynthServerProfileApi.cs, ProfileInterface.cs), and
// "RynthILT.Data" v1..v3, the charms list and bank balances with their actions, the pet breeding
// tracker and the Temple guardians (Plugins/Shared/RynthIltDataApi.cs, DataInterface.cs), and
// "RynthILT.Server" v1, the Leaftide feature / fellowship / quest bonus profile RynthOracle reads
// (Plugins/Shared/RynthIltServerApi.cs, ServerInterface.cs).
// Fixed signature: void* (const char* iface, uint version).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version)
{
try
{
string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? "";
IntPtr table = HubInterface.Query(iface, version);
if (table != IntPtr.Zero) return table;
table = ServerInterface.Query(iface, version);
if (table != IntPtr.Zero) return table;
table = ProfileInterface.Query(iface, version);
return table != IntPtr.Zero ? table : DataInterface.Query(iface, version);
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown()
{
// An exception escaping an UnmanagedCallersOnly export fail-fasts the client under NativeAOT.
try { Runtime.Shutdown(); } catch { }
try { HubInterface.Release(); } catch { }
try { ServerInterface.Release(); } catch { }
try { ProfileInterface.Release(); } catch { }
try { DataInterface.Release(); } catch { }
foreach (IntPtr p in new[] { Interlocked.Exchange(ref _bountiesPtr, IntPtr.Zero), Interlocked.Exchange(ref _progressionPtr, IntPtr.Zero),
Interlocked.Exchange(ref _statusPtr, IntPtr.Zero), Interlocked.Exchange(ref _sectionsPtr, IntPtr.Zero) })
if (p != IntPtr.Zero) Marshal.FreeCoTaskMem(p);
_sectionsJson = null;
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => RynthILTPlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => RynthILTPlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
// Bounty lines (and eating the reply to the tracker's own /bounty list).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag)
=> Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
// The ILT Hub's floating windows (Games HUD, confirmations) in the engine's ImGui frame.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Render() => Runtime.OnRender();
/// <summary>The engine calls this instead of RynthPluginRender while its ImGui shell is off.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderOverlay", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void RenderOverlay()
{
try { Runtime.Plugin?.OnRenderOverlay(); }
catch { /* an exception crossing UnmanagedCallersOnly would fail-fast the client */ }
}
/// <summary>
/// Engine panels drawn by RynthILT (render thread): "guardian" is the engine's Guardian ILT
/// panel (RynthCore's GuardianFace); "section:ilt-rates" (the ILT session extras, Session Stats),
/// "section:ilt-fellowship" (the /fship commands), "section:ilt-questbonus" (the /qb list,
/// RynthILT's Quests section) and "section:ilt-settings" (the ILT settings, for an engine that
/// still asks) are RynthCore's Mini Remote sections. ":popout" is added when one is popped out
/// into a window of its own, and RynthILT draws in the engine's current context either way. The
/// Guardian panel is user-sized (want echoes the size given); a section reports the height it
/// used. "section:gear|charms|banking|games|vaulted" are the Mini Remote ILT tabs as RynthCore's
/// section views (RynthILT lists them since 2026-10-20; RynthAi did before), sized to the tab.
/// 1 = drawn, 0 = not ready / unknown surface.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })]
public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight)
{
try
{
if (surface == null) return 0;
ReadOnlySpan<byte> name = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(surface);
if (name.EndsWith(":popout"u8)) name = name[..^":popout"u8.Length];
var plugin = Runtime.Plugin;
if (plugin == null) return 0;
if (name.SequenceEqual("guardian"u8))
{
if (!plugin.RenderEmbeddedGuardian()) return 0;
if (wantWidth != null) *wantWidth = width;
if (wantHeight != null) *wantHeight = height;
return 1;
}
string? view = name.SequenceEqual("section:ilt-settings"u8) ? RynthILTPlugin.SettingsSurface
: name.SequenceEqual("section:ilt-fellowship"u8) ? RynthILTPlugin.FellowshipSurface
: name.SequenceEqual("section:ilt-rates"u8) ? RynthILTPlugin.RatesSurface
: name.SequenceEqual("section:ilt-questbonus"u8) ? RynthILTPlugin.QuestBonusSurface
: null;
if (view == null)
{
// "section:gear", "section:banking", ...: the Mini Remote ILT tabs RynthILT lists (IltSectionsManifest).
if (name.Length > 64 || !name.StartsWith("section:"u8)) return 0;
if (!plugin.RenderEmbeddedTab(System.Text.Encoding.UTF8.GetString(name), out float tabW, out float tabH)) return 0;
if (wantWidth != null) *wantWidth = tabW > 0 ? tabW : width;
if (wantHeight != null) *wantHeight = tabH > 0 ? tabH : height;
return 1;
}
if (!plugin.RenderEmbedded(view, out float wantH)) return 0;
if (wantWidth != null) *wantWidth = width;
if (wantHeight != null) *wantHeight = wantH;
return 1;
}
catch
{
return 0; // an exception crossing UnmanagedCallersOnly would fail-fast the client
}
}
// "/ilt ..." commands, and noticing a /bounty the player typed (its reply is never eaten).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag)
=> Runtime.OnChatBarEnter(textUtf16, eatFlag);
// Creatures' health from the server (siphon auto-capture's fallback health read, IltPetAutomation).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
=> Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
// This character's kills re-read the bounty list (while the Bounties window is open).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnKillNotification", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnKillNotification(IntPtr textUtf16) => Runtime.OnKillNotification(textUtf16);
// ── Bounties bridge (the engine's ImGui Bounties window, UI/Data/BountiesData.cs) ──────
// UTF-8 both ways. Polling the getter is what keeps the tracker's reads running, so only
// the engine's Bounties source may call it (on the plugin pump, 1 s, on ILT only).
// Alloc-new → swap → free-old: the previous reply stays valid until the next call.
private static IntPtr _bountiesPtr = IntPtr.Zero;
/// <summary>The tracked bounties as JSON (BountyBridgePayload); 0 before login.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthILTGetBountiesJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetBountiesJson()
{
try
{
string? json = Runtime.Plugin?.Bounties?.BuildJson();
return json == null ? IntPtr.Zero : Utf8Swap(ref _bountiesPtr, json);
}
catch { return IntPtr.Zero; }
}
/// <summary>"refresh" or "set {option} {value}" (BountyTracker.Command).</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthILTBountyCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void BountyCommand(IntPtr utf8Text)
{
try
{
if (utf8Text == IntPtr.Zero) return;
string? text = Marshal.PtrToStringUTF8(utf8Text);
if (string.IsNullOrEmpty(text) || text.Length > 256) return;
Runtime.Plugin?.Bounties?.Command(text);
}
catch { }
}
// ── The ILT Hub for the engine (the Skills panel's Progression tab, IltInfo) ─────────
private static IntPtr _progressionPtr = IntPtr.Zero;
/// <summary>
/// The Skills panel's Progression tab (ILT augmentations / enlightenment / the attribute raiser),
/// as RynthAi's RynthPluginGetProgressionJson was: {"available":false} until the Hub exists and
/// off ILT. UTF-8; the previous reply stays valid until the next call. Engine pump thread only.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthILTGetProgressionJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetProgressionJson()
{
try
{
string json = Runtime.Plugin?.Hub?.BuildProgressionJson() ?? "{\"available\":false}";
return Utf8Swap(ref _progressionPtr, json);
}
catch { return IntPtr.Zero; }
}
/// <summary>
/// One command from the engine (UTF-8): "prog ..." (the Progression tab's edits) or an ILT
/// "/ra" verb without "/ra" ("hub refresh", "guardian handin"). Engine pump thread.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthILTCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Command(IntPtr utf8Text)
{
try
{
if (utf8Text == IntPtr.Zero) return;
string? text = Marshal.PtrToStringUTF8(utf8Text);
if (string.IsNullOrWhiteSpace(text) || text.Length > 512) return;
Runtime.Plugin?.RunEngineCommand(text);
}
catch { }
}
/// <summary>
/// (action, value) from the engine's plugin-command broker (Host.SendPluginCommand): "prog" with
/// the Progression tab's arguments (RynthAi forwards an older engine's "prog" here), or an ILT
/// verb. Copied and run on RynthILT's next tick.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi)
{
try
{
string action = actionAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(actionAnsi) ?? string.Empty) : string.Empty;
if (action.Length == 0 || action.Length > 32) return;
var plugin = Runtime.Plugin;
if (plugin == null) return;
if (RynthILTPlugin.IsParsedRemoteAction(action))
{
// RynthCore's "servermenu" push (a few KB): answered here, never queued as an ILT verb.
plugin.ApplyRemoteCommand(action, valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty);
return;
}
string value = valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty;
if (action.Length + value.Length > 512) return;
plugin.EnqueueRemoteCommand(action, value);
}
catch { /* never let a managed exception cross the native boundary */ }
}
private static IntPtr _statusPtr = IntPtr.Zero;
/// <summary>
/// What RynthILT knows about the world (UTF-8 JSON, previous reply valid until the next call):
/// {"loaded":true,"ilt":bool,"forced":bool,"available":bool,"world":"..."}. "ilt" is RynthILT's
/// own verdict (its server list or this character's "Treat this world as ILT"), never the
/// engine's verdict echoed back: the engine's IltInfo adds it to its own detection, and an
/// echo would keep ILT on after "/rc ilt auto". Engine pump thread.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthILTGetStatusJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetStatusJson()
{
try
{
var hub = Runtime.Plugin?.Hub;
string json = hub == null
? "{\"loaded\":true,\"ilt\":false,\"forced\":false,\"available\":false,\"world\":\"\"}"
: "{\"loaded\":true,\"ilt\":" + (hub.Options.IsIltLikeWorldLocal ? "true" : "false")
+ ",\"forced\":" + (hub.ForceIltWorld ? "true" : "false")
+ ",\"available\":" + (hub.Available ? "true" : "false")
+ ",\"world\":\"" + RynthCore.Plugin.RynthILT.Hub.IltStyle.JsonEscape(hub.Options.WorldName) + "\"}";
return Utf8Swap(ref _statusPtr, json);
}
catch { return IntPtr.Zero; }
}
private static IntPtr _sectionsPtr = IntPtr.Zero;
private static string? _sectionsJson;
/// <summary>
/// RynthCore 2026.10.5.46+ (optional): what RynthILT adds to the Mini Remote's sections (UTF-8
/// JSON, schema 1; RynthILTPlugin.BuildSectionsJson). Null before login. An unchanged manifest
/// keeps the same buffer.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetSectionsJson()
{
try
{
string? json = Runtime.Plugin?.BuildSectionsJson();
if (json == null) return IntPtr.Zero;
if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr;
_sectionsJson = json;
return Utf8Swap(ref _sectionsPtr, json);
}
catch { return IntPtr.Zero; }
}
private static IntPtr Utf8Swap(ref IntPtr slot, string json)
{
IntPtr newPtr = Marshal.StringToCoTaskMemUTF8(json);
IntPtr oldPtr = Interlocked.Exchange(ref slot, newPtr);
if (oldPtr != IntPtr.Zero) Marshal.FreeCoTaskMem(oldPtr);
return newPtr;
}
}

View file

@ -0,0 +1,105 @@
// ProfileInterface.cs - RynthILT's side of "RynthServer.Profile" (Plugins/Shared/RynthServerProfileApi.cs):
// Infinite Leaftide's settings as JSON for other plugins, the same interface and JSON writer the
// server plugins use (Plugins/Shared/ServerPack/ServerPackProfile.cs). RynthCore's GetServerStateJson
// names RynthILT as the owner of "ilt"; a reader (RynthAi's Crafting tab, ...) then asks it for this.
// The profile carries ILT's tinkering salvage (Hub/IltSalvage.cs).
//
// As ServerPackInterface: the table is allocated once per loaded copy of RynthILT and never freed;
// after Release() it reports Version 0 and GetProfileJson answers 0. Before the Hub is up the profile
// still describes the server (active false, no world).
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.ServerPack;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT;
internal static unsafe class ProfileInterface
{
private static RynthServerProfileApiV1* _table;
private static volatile bool _released;
/// <summary>What RynthILT knows about its server (identity from the csproj's manifest properties).</summary>
internal static readonly ServerPackInfo Info =
new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames)
{
Emulator = "ACE",
Salvage = IltSalvage.Rows,
// Leaftide trinkets (UB-IT's IsLeaftideTrinketJewelry): the Crafting tab's Trinkets bench, not Jewelry.
TrinketNames = IltSalvage.TrinketNames,
TrinketExcept = IltSalvage.TrinketExcept,
Source = "RynthILT; salvage from UB-IT's LeaftideImbueHelper (via SilentKelpie)",
};
/// <summary>The last JSON handed out, and what it was built for (rebuilt only when that changes).</summary>
private sealed record Snapshot(bool Active, string World, string Json);
private static Snapshot? _last;
/// <summary>The table for (<paramref name="iface"/>, <paramref name="version"/>), or 0 when it isn't ours.</summary>
public static IntPtr Query(string iface, uint version)
{
if (iface != RynthServerProfileApiV1.InterfaceName || version < 1 || version > RynthServerProfileApiV1.InterfaceVersion || _released)
return IntPtr.Zero;
if (_table == null)
{
var t = (RynthServerProfileApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerProfileApiV1));
t->StructSize = (uint)sizeof(RynthServerProfileApiV1);
t->GetProfileJson = &GetProfileJson;
t->Version = RynthServerProfileApiV1.InterfaceVersion;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>Plugin shutdown: readers see Version 0 and re-query; GetProfileJson answers 0.</summary>
public static void Release()
{
_released = true;
if (_table != null) _table->Version = 0;
}
/// <summary>
/// The JSON to hand out for RynthILT's verdict (<paramref name="active"/>) and the world name.
/// Any thread.
/// </summary>
internal static string CurrentJson(bool active, string? world)
{
world ??= string.Empty;
Snapshot? last = Volatile.Read(ref _last);
if (last != null && last.Active == active && last.World == world) return last.Json;
string json = ServerPackProfile.BuildJson(Info, RynthPluginInfo.Name, RynthPluginInfo.Version, active, world);
Volatile.Write(ref _last, new Snapshot(active, world, json));
return json;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetProfileJson(byte* buffer, int capacity)
{
try
{
if (_released) return 0;
IltHubController? hub = PluginExports.Runtime.Plugin?.Hub;
string json = CurrentJson(hub?.Options.IsIltLikeWorld == true, hub?.Options.WorldName);
return Write(json, buffer, capacity);
}
catch { return 0; }
}
/// <summary>
/// Copies <paramref name="json"/> as NUL-terminated UTF-8 into the caller's buffer when it fits,
/// and returns its byte length either way (length >= capacity: too small, nothing written).
/// </summary>
internal static int Write(string json, byte* buffer, int capacity)
{
int length = Encoding.UTF8.GetByteCount(json);
if (buffer == null || capacity <= length) return length;
fixed (char* src = json)
Encoding.UTF8.GetBytes(src, json.Length, buffer, capacity);
buffer[length] = 0;
return length;
}
}

View file

@ -0,0 +1,244 @@
Area,Place,Npc,Reward,Stamp,Note
"Facility Hub","Folthid Cellar","Raxanza Folthid","O-Yoroi Leggings","Dynamic_1_Aq2hMsFmW!",""
"Facility Hub","Folthid Cellar","Felscuda","Healing Rabbit Pie","Dynamic_1_&9jiyTB!","8.8S, 53.1E"
"Facility Hub","Folthid Cellar","Mi Krau-Li","examines your Parchment","Dynamic_1_WAuFukcRLoL5!",""
"Looking Around","","Le-Ai Rea","Blue Molly","Dynamic_1_XH!!nh#^NaRp!","75.9S 57.3E"
"Looking Around","Frost Haven","Robert","Greater Celdon Shadow Sleeves","Dynamic_1_HLq&!",""
"Looking Around","Frost Haven","Elijah","Homemade Stout","Dynamic_1_MpBeVDU!",""
"Looking Around","Frost Haven","Emma","Frost Slingshot","Dynamic_1_bEt6H5ECwGb2!",""
"Looking Around","Frost Haven","Chef Pleist","Stone Mace","Dynamic_1_HgaUKA#hxa!",""
"Looking Around","Frost Haven","The Mayor","Fried Egg","Dynamic_1_MRfxp5!g!",""
"Looking Around","Frost Haven","Numb","Perfect Coruscating Isparian Mace","Dynamic_1_z8LpGZpe4rq!",""
"Looking Around","Land Bridge Staging Complex","Director's Majordomo","Spitter Trochanter Metamorphi","Dynamic_1_FZYLYrAW1Zb!",""
"Looking Around","Frost Haven","Mossy Chamber","Broken Virindi","Dynamic_1_ANND",""
"Looking Around","Freebooter","Jusad the Collector","Renegade Atlatl of the Mountains","Dynamic_1_!mqkm9M!",""
"Looking Around","Lum Seer","Shade of Lady Adja","Frost Board with Nail","Dynamic_1_ps6iG^P!ndH!",""
"Looking Around","Frost Haven","Ka'hiri","Hearty Spiced Applesauce","Dynamic_1_s5MAzDcP9!",""
"Looking Around","Frost Haven","Liam of Gelid","Composite Crossbow with Handle","Dynamic_1_7cv3O^MTLLKzs&!",""
"Looking Around","84.1N, 44.1E","Aerlinthe Node Golem","Silifi of Crimson Stars","Dynamic_1_D6YxLUyUIW!","84.1N, 44.1E"
"Looking Around","62.0N, 18.0E","Esper Node Golem","Composite Bow with Handle","Dynamic_1_LE5V8SVHG!","62.0N, 18.0E"
"Looking Around","93.8N, 67.4W","Halaetan Node Golem","Slashing Longbow","Dynamic_1_QfLhcZJ64Hkold!","93.8N, 67.4W"
"Looking Around","64.8S, 59.3E","Linvak Node Golem","Greater Celdon Shadow Girth","Dynamic_1_V8&t5$!","64.8S, 59.3E"
"Looking Around","Ulgrim Island","Ulgrim the Unappreciated","Applesauce","Dynamic_1_x!zs79y!",""
"Looking Around","Fake Niffis Crate Quest","Chef Jonus","Fish","Dynamic_1_j&T!ZrQwKvo!",""
"Looking Around","Frost Haven","Larnia","Acid Hand Axe","Dynamic_1_88P$YBwEl!",""
"Looking Around","Tanada Chamber of Scroll / Fire","Tanada Han-Tu","Hearty Ice Cream","Dynamic_1_STjY86!0Iu8x!",""
"Looking Around","Frost Haven","Tanada Hido","Acid Mace","Dynamic_1_3ZhBEF!",""
"Looking Around","Frost Haven","Tanada Shouka","Pouch of Dried Meat","Dynamic_1_YgClBFy!",""
"Looking Around","Gerent's Compound at 87.2S, 17.5W","Representative of the Singularity","Fish","Dynamic_1_qkU0b^i!","87.2S, 17.5W"
"Odd Stamps","93.2N, 48.2W in the Shattered Outlands","Arialle du Bellenesse","Healing Holtburger","Dynamic_1_ADm5RsrDGCbT!","93.2N, 48.2W"
"Odd Stamps","Crater","Silencia's Magma Golem","Slicing Royal Atlatl","Dynamic_1_fR730X5VsPULE5!",""
"Odd Stamps","Colosseum","Master Arbitrator","Palenqual's Tewhate","Dynamic_1_XnFt&!",""
"Odd Stamps","","Colosseum Ticket Vendor","Silifi of Crimson Stars","Dynamic_1_luguukhgZg!",""
"Odd Stamps","Beach Fort","Suzuhara Sheshumi","Silifi of Crimson Stars","Dynamic_1_n5u2imCs!",""
"Odd Stamps","Obsidian Plains","Varetha","Major Smoldering Atlan Bow","Dynamic_1_P1&xxk5!","44.3S, 62.5W"
"Odd Stamps","Crystal Crag","Oorjit","Perfect Shimmering Isparian Bow","Dynamic_1_lPn&BaZ!",""
"Odd Stamps","","Jyotsana","Cragstone Farms Mac&Cheese","Dynamic_1_YCGJJ7cA!",""
"Odd Stamps","","Tokashi Ando","Perfect Dissolving Isparian Crossbow","Dynamic_1_R#HIf!",""
"Odd Stamps","Ries Woron's Story","Thrungus","Expired Stamina Draught","Dynamic_1_eMJVhyPzaa$aGn!",""
"Odd Stamps","Mite Maze","Roderick","Apple Pie","Dynamic_1_#C^p&w0gV$$!",""
"Odd Stamps","Sawato","Ssavish","Composite Bow with Handle","Dynamic_1_NMlDXfx2t!",""
"Odd Stamps","dryreach rescue","Dansha-Ki","Composite Bow with Handle","Dynamic_1_FnXoHWS&kaM!",""
"Odd Stamps","Seat of Knorr","Arikas, Warden of Knorr","Hearty Healing Rabbit Noodle","Dynamic_1_aWOWTc30f4",""
"Odd Stamps","Swamp Garden","Terese","Diforsa Bracers","Dynamic_1_PTy0kqqTLP1Dn^!",""
"Odd Stamps","Dark Isle","Tyrina of Arwic","Major Shadow Gauntlets","Dynamic_1_zJNxGBc!","84.7n 58.7e"
"Odd Stamps","Dark Isle","Francois di Terli","Habraeloi","Dynamic_1_3!Og!",""
"Odd Stamps 2","Aun Settlement 82.7N 21.2E.","Aun Tikakhe","Good Chilling Isparian Mace","Dynamic_1_hafO$cQvbkg!","82.7N 21.2E"
"Odd Stamps 2","","Aun Saritea","Health Tonic","Dynamic_1_7yW17JvMHKu!",""
"Odd Stamps 2","","Aun Aulakhe","Mana Rabbit Pie","Dynamic_1_5xE2TM!",""
"Odd Stamps 2","Lost Wish Cottages (Arwic) 42.6n 62.4e","Lartorus","Pants","Dynamic_1_$GB72K!","42.6n 62.4e"
"Odd Stamps 2","Catacombs of Opposition","Ripper","Gladiatorial Tunic","Dynamic_1_69Rjbany2pKD!",""
"Odd Stamps 2","","Rat Nose","Fine Atlan Staff","Dynamic_1_eBlku!",""
"Odd Stamps 2","","Nanoc, Basher of Bugs","Mana Potion","Dynamic_1_XCTiy!",""
"Odd Stamps 2","","Narg","Iron Rusted Mace","Dynamic_1_S!AhI!",""
"Odd Stamps 2","","Scout Luzumin Abigwei","Alduressa Helm","Dynamic_1_NFf5!",""
"Odd Stamps 2","","Teela","Orange Molly","Dynamic_1_Bl#Y!",""
"Odd Stamps 2","","Scout Tel al-Arat","Envoy's Heaume","Dynamic_1_AJ3Wm9Bk!",""
"Odd Stamps 2","","Pincer Danta","Olthoi Sollerets","Dynamic_1_VezOOBWbn43KU!!",""
"Odd Stamps 2","Vissidal","Merwart Pelagurg","Superior Smoldering Atlan Staff","Dynamic_1_DOIC1!",""
"Odd Stamps 2","Vissidal","Merwart Urglurg","Butter Knife of Slaying","Dynamic_1_&!iRR#RrhnGA!",""
"Odd Stamps 2","Vissidal","Dayla Bint Kazm","Hearty Healing Chicken Pie","Dynamic_1_nDAXG!",""
"Odd Stamps 2","Vissidal","Peng-Ya","Major Dissolving Isparian Crossbow","Dynamic_1_sx^9H^&Mnqp!",""
"Odd Stamps 2","Vissidal","Colista Fluress","Lesser Amuli Shadow Leggings","Dynamic_1_Ej!Zz!",""
"Odd Stamps 2","99.7S 96.7W","Surloshen Realaidain","Hammer of Lightning","Dynamic_1_tiiFC!","99.7S 96.7W"
"Odd Stamps 2","Silyiun - 89.1N 47.6W","Fiun Gaya","Enhanced Shadow Gauntlets","Dynamic_1_hev0!","89.1N 47.6W"
"Odd Stamps 2","Hermit - Thrungus Hole","Hermit","Scored Amuli Leggings","Dynamic_1_rDBG!",""
"Odd Stamps 2","93.2N 48.2W - Eastwatch","Commander Rylane di Cinghalle","Acid Crossbow","Dynamic_1_pZpx41&!","93.2N 48.2W"
"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Arbelests","Healing Carrot Soup","Dynamic_1_L3Hb3O!","32.0N, 43.2W"
"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Fists","Platemail Breastplate","Dynamic_1_xj&USOHNL9K&!","32.0N, 43.2W"
"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Bows","Tasty Stout","Dynamic_1_hw2LNdjT6!","32.0N, 43.2W"
"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Atlatls","Composite Crossbow with Handle","Dynamic_1_P6!!","32.0N, 43.2W"
"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Axes","Three Eyed Guppy","Dynamic_1_xX^IHjOo##J$8E!","32.0N, 43.2W"
"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Blades","Flaming Weeping Dagger","Dynamic_1_iFuvP!","32.0N, 43.2W"
"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Staves","Composite Crossbow","Dynamic_1_J$JV&VKf!","32.0N, 43.2W"
"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Orbs","Health Tincture","Dynamic_1_S&JMdWiBDy!","32.0N, 43.2W"
"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Maces","Wooden Scarecrow Guise","Dynamic_1_^pTx!","32.0N, 43.2W"
"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Knives","Scalemail Hauberk","Dynamic_1_6ZR$k^$Srwc3g!","32.0N, 43.2W"
"Odd Stamps 2","83.4S 97.2E - Ithaenc","Abbess Zik'Lir","Hearty Fish Noodle","Dynamic_1_jmCfm1p5a!","83.4S 97.2E"
"Odd Stamps 2","72.8N,25.0W - Stonehold nearby","Lord Pyrovor","Enhanced Shadow Greaves","Dynamic_1_Tw$7Zwmutan!","72.8N,25.0W"
"Odd Stamps 2","VoD Encampment","Guard Alfric","Bowl of Rice","Dynamic_1_LZkvsu4Ln2$h!",""
"Odd Stamps 2","VoD Encampment","Guard Taziq","Blackfire Shadow Sollerets","Dynamic_1_t9uxr!",""
"Odd Stamps 2","VoD Encampment","Guard Q'alia","Ancient Relic Gauntlets","Dynamic_1_m1KeUXELMuH!",""
"Odd Stamps 2","VoD Encampment","Guard Li","Frost Hatchet","Dynamic_1_XgrV$!",""
"Odd Stamps 2","77.7S 97.0E Ithaenc","Shah-hi","Katar","Dynamic_1_G3N9HSXlowLT$!","77.7S 97.0E"
"Odd Stamps 2","Releasing the Light - Reward Room","Calitoth","Fish","Dynamic_1_mu^91#T!",""
"Odd Stamps 2","VoD Encampment","Guardian of the Forbidden","Princely Runed Dart Flinger","Dynamic_1_#BELoT72Ib!","Small Creepy Statue"
"Odd Stamps 2","Shattered Outlands 94.0n 45.9w","Torgash","examines your Parchment","Dynamic_1_S","94.0n 45.9w"
"Odd Stamps 2","Hoshino Must Die last room","Spirit of Bist'elle","Enhanced Shadow Breastplate","Dynamic_1_b!",""
"Bandit Castle","","Karwin, the Lunatic","Chainmail Pauldrons","Dynamic_1_HIlMkY!",""
"Bandit Castle","","Kiriel Shadowborn","Healing Apple Pie","Dynamic_1_WBzVFJpFUzHkC!",""
"Bandit Castle","","Jourgensson","Hearty Healing Mushroom Pie","Dynamic_1_$W&Pl4!",""
"Bandit Castle","","Gillian the Poacher","Peppermint Ice Cream","Dynamic_1_5oLp!",""
"Bandit Castle","","Alison Dulane","Amuli Shadow Leggings","Dynamic_1_079u9!",""
"Bandit Castle","","Arianna the Adept","Expired Stamina Draught","Dynamic_1_hZIsyYE!!OmcQ!",""
"Bandit Castle","","Shanrek the Forger","Sparring Shirt","Dynamic_1_fbcmDRC!",""
"Bandit Castle","","Neela Nashua","Perfect Dissolving Isparian Spear","Dynamic_1_4tXQFu&&o!",""
"Bandit Castle","","Gwillim, the Apprentice","Lightning Flanged Mace","Dynamic_1_is#X6rBaprU!",""
"Bur","","Drogur","Frost Yari","Dynamic_1_KS8e32dtk7t!",""
"Bur","","Collector Golem","Upper Exoskeleton Metamorphi","Dynamic_1_4xdYA1QvaiDf^!",""
"Bur","","Kuurak","Hearty Healing Chicken Noodle","Dynamic_1_Zapx!",""
"Bur","","Furgal","Spitter Thorax Metamorphi","Dynamic_1_4rk&MTz!",""
"Bur","","Tibik","Gear Crossbow","Dynamic_1_!Ce^d!",""
"Bur","","Nimeruuk","Greater Celdon Shadow Sleeves","Dynamic_1_zIX1Sf6FJt!",""
"Bur","","Kurket","Acidic Rejuvenation","Dynamic_1_snVaz#0Ze3R#4M!",""
"Bur","","Brogosh","Lugian Morning Star","Dynamic_1_$9YdvC2jYTxWZ!",""
"Bur","","Mohor","Quality Isparian Crossbow","Dynamic_1_qpXiWqwBTN4!",""
"Bur","","Kushuk","Silifi of Crimson Stars","Dynamic_1_3ISBG!",""
"Bur","","Borsh","Health Tonic","Dynamic_1_Jh4!",""
"Bur","","Kuuru","Electric Compound Bow","Dynamic_1_vNktko1!",""
"Bur","","Torgluuk, High Shaman of Kor-Gursha","Stout","Dynamic_1_2yxpXSMY!",""
"Bur","","Scout Leader Tmauruk","Hood","Dynamic_1_fEiU!",""
"Bur","","Gruuk'lar","Rynthid Tentacle Dagger","Dynamic_1_xFipmT1!",""
"Gear Knight","Inner Sea Gearknight Invasion","Lieutenant Micham","Dabus","Dynamic_1_CQxkFJvoJrVx!",""
"Gear Knight","Inner Sea Gearknight Invasion","Sir Oakley","Composite Crossbow with Handle","Dynamic_1_lh9wOaXR0!",""
"Gear Knight","Inner Sea Gearknight Invasion","Lieutenant Faen","Blunt Bow","Dynamic_1_Vz#gp!",""
"Gear Knight","Inner Sea Gearknight Invasion","Sir Stavitor","Red Tea","Dynamic_1_ogt05i!",""
"Gear Knight","Inner Sea Gearknight Invasion","Dame Alistra","Superb Flaming Isparian Claw","Dynamic_1_y!",""
"Gear Knight","Direland Gearknight Invasion","Sir Yanov","Major Shadow Greaves","Dynamic_1_BlAckAuHU#!",""
"Gear Knight","Direland Gearknight Invasion","Sir Durnstad","Silifi of Crimson Stars","Dynamic_1_#Dfd!",""
"Gear Knight","Direland Gearknight Invasion","Squire Tylaen","Good Coruscating Isparian Atlatl","Dynamic_1_i1Cxg8Bt!",""
"Gear Knight","Direland Gearknight Invasion","Dame Trielle","Frost Yari","Dynamic_1_h^MdsKZ$6SSD!",""
"Gear Knight","Direland Gearknight Invasion","T'ing Douzen","Panaq","Dynamic_1_p0BEy$e!",""
"Gear Knight","Atamarr Tasks Dungeon","Bronze Gauntlet Knight-Commander","Frost Greataxe","Dynamic_1_REv&biyDw!",""
"Gear Knight","Direland Gearknight Invasion","Copper Cog Craftsmaster","Greater Amuli Leggings of Frost","Dynamic_1_4uls5J!",""
"Wai Jhou","","Kreavon","Skeleton Fish","Dynamic_1_KrPl9N5!",""
"Wai Jhou","","Aun Teverea","Singularity Crossbow","Dynamic_1_Y9wg!RfKHoyL!",""
"Wai Jhou","","Nona","Fish","Dynamic_1_JrzQr8U!",""
"Wai Jhou","","Zho Heishan","Bandit Dagger","Dynamic_1_Abm8qK2!",""
"Wai Jhou","","Sarkin Killcrane","Shadow Tassets","Dynamic_1_mb7NAtZEdBaz!",""
"Wai Jhou","","Riordin Nightbane","Hafted Serpent Spear","Dynamic_1_cCzQdsl5JxLC!",""
"Wai Jhou","","Lacarra Avanthi","Shou-jen Shozoku Trousers","Dynamic_1_ip&NsyQ!",""
"Wai Jhou","","Xanda Har","Gold Fish","Dynamic_1_1CiKW8^x^$!",""
"Rynthid","","Lohrn","Shreth Hide Shoes","Dynamic_1_cS!mivYZ^b!cAA!",""
"Rynthid","","Rhys","Plate Leggings","Dynamic_1_A!!",""
"Rynthid","","Morgethais","Silifi of Crimson Stars","Dynamic_1_wDTf#!",""
"Rynthid","","Geilla","Audetaunga's Korua of the Mountains","Dynamic_1_&dNG5U4!",""
"Rynthid","","Rinne Gorber","Brilliant Celdon Leggings","Dynamic_1_ln!Lx!",""
"Rynthid","","Aun Ol'tra","Small Beer","Dynamic_1_&^3Hve4JXH^!",""
"Rynthid","","Ranulf","Prismatic Celdon Sleeves","Dynamic_1_8n2l!",""
"Rynthid","","Sylvanus","Ursuin Hide Coat","Dynamic_1_veaD!",""
"Rynthid","","Marcus","Fish","Dynamic_1_bpNCu!rsf45Fk!",""
"Rynthid","","Ilte Krongal","Hearty Mana Rabbit Noodle","Dynamic_1_AusVgDl!",""
"Rynthid","","The Bringer of Light","Peppermint Hot Chocolate","Dynamic_1_LrpV!62!",""
"Paradox Camp","Paradox Olthoi Camp","Ethan Wintermaine","Superb Flaming Isparian Bow","Dynamic_1_PPtO6!7dB!",""
"Paradox Camp","","Adrien Swiftblade","Oak Stormwood Crossbow","Dynamic_1_R^1Uv!J8k!",""
"Paradox Camp","","Alicia Swiftblade","Badlands Siraluun Dress","Dynamic_1_G0Rn1lOZKj7C!",""
"Paradox Camp","","Tomihino","Dart Flinger","Dynamic_1_!$cc!",""
"Paradox Camp","North Olthoi Burrow","Peda's Assistant","examines your Parchment","Dynamic_1_3ddaHUzi!",""
"Paradox Camp","North Olthoi Burrow","Peda","examines your Parchment","Dynamic_1_1R9O85L$b!",""
"Paradox Camp","North Olthoi Burrow","Crusher","examines your Parchment","Dynamic_1_a&Z2!",""
"Paradox Camp","North Olthoi Burrow","Deena","examines your Parchment","Dynamic_1_cIZV2uDB6B!",""
"Paradox Camp","North Olthoi Burrow","Mac","examines your Parchment","Dynamic_1_5x^G2$X9!",""
"Paradox Camp","North Olthoi Burrow","Swift-Eye","examines your Parchment","Dynamic_1_o$yT7al7ZTxv!",""
"Paradox Camp","North Olthoi Burrow","Sasha","examines your Parchment","Dynamic_1_CvzZIz!",""
"Paradox Camp","North Olthoi Burrow","Dead-Eye","examines your Parchment","Dynamic_1_fP9y!",""
"Paradox Camp","North Olthoi Burrow","Lash","examines your Parchment","Dynamic_1_AniHdl4wtIuF0!",""
"Paradox Camp","North Olthoi Burrow","Long-Shot","examines your Parchment","Dynamic_1_jJ^yEFc#m^M!",""
"Graveyard","","Renata","Singularity Spear","Dynamic_1_1fDZO3!",""
"Graveyard","","Yoite","Composite Bow with Handle","Dynamic_1_OG6jdId!",""
"Graveyard","","Gadi","Scored Celdon Girth","Dynamic_1_ELgh#!",""
"Graveyard","","Aethelswith","Leather Helm","Dynamic_1_cF!",""
"Graveyard","","Mhoire Soldier","Superb Isparian Bow","Dynamic_1_VgB#WcZOIA!","North Soldier - Opposite side of bunker"
"Graveyard","","Mhoire Soldier","Hafted Gromnie Banner with Crest","Dynamic_1_z$DX!","South Soldier - Opposite side of bunker"
"Graveyard","","Apep-tek the Tolerant","Spectacular Lager","Dynamic_1_Y55^MqgC!","Above ground, outside bunker 65.3w 44.0w"
"Graveyard","","Laylana","Stiletto","Dynamic_1_&SRgbH!","Above ground, outside bunker 65.2s 44.3w"
"Graveyard","","Lo Shoen","Amateur Explorer Pants","Dynamic_1_102!pkgn8wAYSe!","Floating Platform - Level 50 req"
"Graveyard","","Slubbley","Healing Cake","Dynamic_1_mDaEh7!",""
"Graveyard","","Jailer","Good Shimmering Isparian Bow","Dynamic_1_2Hm6DL!","NE bunker aboveground 64.9s 44.1w"
"Graveyard","","Kousu Temo","Fried Mushroom Rice Dough","Dynamic_1_QUXbn6!","EW Initiation guy, 64.2s 44.0w"
"Graveyard","","Candrus Steady-Hand","Academy Mana Potion","Dynamic_1_BKq6N6nXoR!","CH Initiation guy, 65.8s 45.3w"
"Graveyard","","Ancient Stones","Bandit Flaming Jambiya","Dynamic_1_xL!g4ZoCuv!H","Pile of stones at 66.5s 44.7w"
"Graveyard","Mhoire Castle - Great Hall","Ancient Throne","Taiaha","Dynamic_1_&y4ettwcivZ5Nm!",""
"Graveyard","Mhoire Castle - Great Hall","Shade of Antemy","Left Peg Leg","Dynamic_1_CphV&!",""
"Graveyard","Mhoire Castle - Great Hall","Shade of Fordroth","Perfect Chilling Isparian Atlatl","Dynamic_1_M0u7js^$E!",""
"Graveyard","Mhoire Castle - Great Hall","Shade of Terelev","Silifi of Crimson Stars","Dynamic_1_XPvw!",""
"Graveyard","Mhoire Castle - Great Hall","Guliant","Celdon Girth of Acid","Dynamic_1_aCEEdQil42!",""
"Neftet","","T'ing Setsuko","Flaming Broad Sword","Dynamic_1_JfmjJmY0O8r!",""
"Neftet","","Nephthys","Red Tea","Dynamic_1_mnJCjm5QR$s&!",""
"Neftet","","Fahneph","Gear Crossbow","Dynamic_1_owGS9WGJ1Q!",""
"Neftet","","Nekshla","Mana Pumpkin Pie","Dynamic_1_AAQ1#!",""
"Neftet","","Sir Hassim bin Tamarek","Enhanced Shadow Greaves","Dynamic_1_r7zID$U!",""
"Neftet","","Sir Adarl","Bobo's Stout","Dynamic_1_SoBgM6JPckOY9!",""
"Neftet","","Sir Ibreh bin Kassim","Expired Mana Tincture","Dynamic_1_aVMuY!",""
"Neftet","","Sir Daeglan","Quality Coruscating Isparian Crossbow","Dynamic_1_n!",""
"Neftet","","Bemeth the Gatherer","Lesser Koujia Breastplate of Acid","Dynamic_1_bda1WYoI!",""
"Neftet","","Hammah al Rundik","Olthoi Greaves","Dynamic_1_9v^POv6ADt3r!",""
"Neftet","22.2S 8.7E","Kaltus","Composite Bow with Handle","Dynamic_1_xWYS3fqIjPN!","22.2S 8.7E Not Dangerous run"
"Frozen Valley","","Sir Donovan","Pickled Egg","Dynamic_1_ypu2L!",""
"Frozen Valley","","Sir Learth","Royal Cabbage","Dynamic_1_xpAJDzm$!",""
"Frozen Valley","","Lady Daenerah","Acid Spadone","Dynamic_1_$SDp1uWx8wq$!",""
"Frozen Valley","","Gregoria, Gurog Destroyer","Chocolate Gromnie","Dynamic_1_!vr&1c1Ug1XI!",""
"Frozen Valley","","Hunter","Hearty Healing Chicken Pie","Dynamic_1_Sy!9l0FAJFI!",""
"Frozen Valley","","Leilah","Lightning Silifi","Dynamic_1_uyoL!",""
"Frozen Valley","","Halvor","Noble Quarterstaff","Dynamic_1_LfLac!",""
"Frozen Valley","","Kumiko","Expired Health Potion","Dynamic_1_TB!q!",""
"Frozen Valley","","Archmage Ichihiri","Arbalest","Dynamic_1_HzvCs4B2!",""
"Hoshino Tent","","Sergeant Trebuus","Soldier Pincer Metamorphi","Dynamic_1_GQIb1mF!",""
"Hoshino Tent","","Sergeant Freng","Lightning War Axe","Dynamic_1_wVJm&#Lpz7AQ#F",""
"Hoshino Tent","","Aun Kirtal","Arena Bow","Dynamic_1_V9ffGx!",""
"Hoshino Tent","","Lieutenant Aurin","Enhanced Smoldering Atlan Sword","Dynamic_1_4qlVcAWbM!",""
"Hoshino Tent","","Lord Eorlinde","Major Shadow Gauntlets","Dynamic_1_zkzTna!",""
"Hoshino Tent","","Griffon","Mana Elixir","Dynamic_1_b4^F&M1^uG!",""
"Hoshino Tent","","Hanamoto Aki'ko","Lightning Nekode","Dynamic_1_3Qlg!",""
"Hoshino Tent","","Corporal Irashi","Lesser Koujia Shadow Leggings","Dynamic_1_2DBoreKEH!",""
"Hoshino Tent","","Lieutenant Takamaki","Silifi of Crimson Stars","Dynamic_1_#hzL!",""
"Hoshino Tent","","Lieutenant Roothe","Fried Rabbit","Dynamic_1_XuH!z7l!",""
"Viridian Rise","","Brellegia","Greater Celdon Breastplate of Acid","Dynamic_1_mCyu9F!","Requires Viridian Rise Recall Gem"
"Viridian Rise","","Summercrown","Tachi","Dynamic_1_R8H6nh!",""
"Viridian Rise","","Aangesilus","Slashing Compound Bow","Dynamic_1_2LJyvGJL!",""
"Viridian Rise","","Dridge","Greater Amuli Leggings of Flame","Dynamic_1_LP3Ee7tH!",""
"Viridian Rise","","Kervim'telek","Ursuin Hide Coat","Dynamic_1_E5$S!",""
"Viridian Rise","","Swift","Fried Chicken","Dynamic_1_hYVV!",""
"Ayan","","Aludi al-Jaladh","Seasoned Explorer Gauntlets","Dynamic_1_7$I7bC!",""
"Ayan","","Aun Javhalrea, the Game Warden","Frost Ono","Dynamic_1_UdRA9W!",""
"Ayan","","Aun Khekierea","Rich Mocha","Dynamic_1_Yt1uiSkCgK!",""
"Ayan","","Aun Aukherea","Chocolate Cookie","Dynamic_1_G$iqi763E!",""
"Ayan","","Shuthoth","Silifi of Crimson Stars","Dynamic_1_CkuPj0IwP!",""
"Ayan","","Yuan Hanzu","Acid Hatchet","Dynamic_1_t^CiJAt2TBz17!",""
"Ayan","","Joku Shunja","Dho Life Apprentice Robe","Dynamic_1_&X4EDhy!",""
"Ayan","","Aaminah","Upgraded Marksman's Robe","Dynamic_1_YlHC^cbS!",""
"Ayan","","Anfram Mellow","Ulgrim's Bunny Slippers","Dynamic_1_$MJj0ytiSy0CKN!",""
"Ayan","","Alishia bint Aldan","Lightning Hatchet","Dynamic_1_87z&&Ok2o&jo!",""
"Ayan","","Vierana du Canamorra","Fine Shadow Atlan Mace","Dynamic_1_qtZdY0C!ae!",""
"Ayan","","Qurakh al-Taal","Hearty Mana Beef Stew","Dynamic_1_Ug2snTqb44!",""
"Ayan","","Laedron the Geomancer","Fine Stinging Atlan Spear","Dynamic_1_2lXQdqHWxPU!",""
"Ayan","","Rohula bint Ludun","Arena Staff","Dynamic_1_SjjPqyCHNigY!",""
"Ayan","","Guard Winterborn","Silifi of Crimson Stars","Dynamic_1_!fzudXFZV0Je3!",""
"Ayan","","Ennio di Cinghalle","Perfect Chilling Isparian Claw","Dynamic_1_fYP!",""
"Ayan","","Lydda","Pathwarden Scale Hauberk","Dynamic_1_neYBz15!",""
"Ayan","","Gaston Shadowbound","Major Shadow Tassets","Dynamic_1_jdMT!",""
"Ayan","","Harkwull the Discreet","Quality Flaming Isparian Crossbow","Dynamic_1_Bq7Brhg!",""
"Ayan","","Tanami Kei","Souldrinker","Dynamic_1_en!",""
"Ayan","","Lamorda Loschi","Major Shadow Sollerets","Dynamic_1_2xn4LwsUdh!",""
"Ayan","","Soju Bo-Ki","Composite Crossbow with Handle","Dynamic_1_ADDKG!",""
"Ayan","","Hoshar ibn Jalaq","High Balance Testing Coat","Dynamic_1_bZ4bc!",""
"Ayan","","Guard Bey","Tasty Stout","Dynamic_1_&!4f5YlXZ!",""
"Ayan","","Ishaq the Philosopher","Enhanced Skeletal Atlatl","Dynamic_1_H3UNETkRXTX!",""
"Candeth Keep","","Morathe gives you","Superb Isparian Atlatl","Dynamic_1_g9M7bV3z3#S!",""
"Candeth Keep","","Aun Autuorea gives you","Singularity Katar","Dynamic_1_5kEI0!",""
"Candeth Keep","","Talira Dain","Composite Bow","Dynamic_1_5i1z1Mb!","No text about being given item, it just shows up in backpack"
"Candeth Keep","","Dalius Kendmar gives you","Undead Guise","Dynamic_1_YFrw!",""
"Candeth Keep","","Grania the Bold gives you","Composite Crossbow with Handle","Dynamic_1_DaevbVP!",""
"Candeth Keep","","Yukara Miko the Collector","Acid Longbow","Dynamic_1_F1r^qTQ!",""
"Candeth Keep","","Ryukai Hiro","Good Olthoi Pauldrons","Dynamic_1_HeucrAy6c!",""
"Candeth Keep","","Garaena the Emissary","Seasoned Explorer Arbalest","Dynamic_1_es^0FY!","Aerlinthe Portal NPC"
1 Area Place Npc Reward Stamp Note
2 Facility Hub Folthid Cellar Raxanza Folthid O-Yoroi Leggings Dynamic_1_Aq2hMsFmW!
3 Facility Hub Folthid Cellar Felscuda Healing Rabbit Pie Dynamic_1_&9jiyTB! 8.8S, 53.1E
4 Facility Hub Folthid Cellar Mi Krau-Li examines your Parchment Dynamic_1_WAuFukcRLoL5!
5 Looking Around Le-Ai Rea Blue Molly Dynamic_1_XH!!nh#^NaRp! 75.9S 57.3E
6 Looking Around Frost Haven Robert Greater Celdon Shadow Sleeves Dynamic_1_HLq&!
7 Looking Around Frost Haven Elijah Homemade Stout Dynamic_1_MpBeVDU!
8 Looking Around Frost Haven Emma Frost Slingshot Dynamic_1_bEt6H5ECwGb2!
9 Looking Around Frost Haven Chef Pleist Stone Mace Dynamic_1_HgaUKA#hxa!
10 Looking Around Frost Haven The Mayor Fried Egg Dynamic_1_MRfxp5!g!
11 Looking Around Frost Haven Numb Perfect Coruscating Isparian Mace Dynamic_1_z8LpGZpe4rq!
12 Looking Around Land Bridge Staging Complex Director's Majordomo Spitter Trochanter Metamorphi Dynamic_1_FZYLYrAW1Zb!
13 Looking Around Frost Haven Mossy Chamber Broken Virindi Dynamic_1_ANND
14 Looking Around Freebooter Jusad the Collector Renegade Atlatl of the Mountains Dynamic_1_!mqkm9M!
15 Looking Around Lum Seer Shade of Lady Adja Frost Board with Nail Dynamic_1_ps6iG^P!ndH!
16 Looking Around Frost Haven Ka'hiri Hearty Spiced Applesauce Dynamic_1_s5MAzDcP9!
17 Looking Around Frost Haven Liam of Gelid Composite Crossbow with Handle Dynamic_1_7cv3O^MTLLKzs&!
18 Looking Around 84.1N, 44.1E Aerlinthe Node Golem Silifi of Crimson Stars Dynamic_1_D6YxLUyUIW! 84.1N, 44.1E
19 Looking Around 62.0N, 18.0E Esper Node Golem Composite Bow with Handle Dynamic_1_LE5V8SVHG! 62.0N, 18.0E
20 Looking Around 93.8N, 67.4W Halaetan Node Golem Slashing Longbow Dynamic_1_QfLhcZJ64Hkold! 93.8N, 67.4W
21 Looking Around 64.8S, 59.3E Linvak Node Golem Greater Celdon Shadow Girth Dynamic_1_V8&t5$! 64.8S, 59.3E
22 Looking Around Ulgrim Island Ulgrim the Unappreciated Applesauce Dynamic_1_x!zs79y!
23 Looking Around Fake Niffis Crate Quest Chef Jonus Fish Dynamic_1_j&T!ZrQwKvo!
24 Looking Around Frost Haven Larnia Acid Hand Axe Dynamic_1_88P$YBwEl!
25 Looking Around Tanada Chamber of Scroll / Fire Tanada Han-Tu Hearty Ice Cream Dynamic_1_STjY86!0Iu8x!
26 Looking Around Frost Haven Tanada Hido Acid Mace Dynamic_1_3ZhBEF!
27 Looking Around Frost Haven Tanada Shouka Pouch of Dried Meat Dynamic_1_YgClBFy!
28 Looking Around Gerent's Compound at 87.2S, 17.5W Representative of the Singularity Fish Dynamic_1_qkU0b^i! 87.2S, 17.5W
29 Odd Stamps 93.2N, 48.2W in the Shattered Outlands Arialle du Bellenesse Healing Holtburger Dynamic_1_ADm5RsrDGCbT! 93.2N, 48.2W
30 Odd Stamps Crater Silencia's Magma Golem Slicing Royal Atlatl Dynamic_1_fR730X5VsPULE5!
31 Odd Stamps Colosseum Master Arbitrator Palenqual's Tewhate Dynamic_1_XnFt&!
32 Odd Stamps Colosseum Ticket Vendor Silifi of Crimson Stars Dynamic_1_luguukhgZg!
33 Odd Stamps Beach Fort Suzuhara Sheshumi Silifi of Crimson Stars Dynamic_1_n5u2imCs!
34 Odd Stamps Obsidian Plains Varetha Major Smoldering Atlan Bow Dynamic_1_P1&xxk5! 44.3S, 62.5W
35 Odd Stamps Crystal Crag Oorjit Perfect Shimmering Isparian Bow Dynamic_1_lPn&BaZ!
36 Odd Stamps Jyotsana Cragstone Farms Mac&Cheese Dynamic_1_YCGJJ7cA!
37 Odd Stamps Tokashi Ando Perfect Dissolving Isparian Crossbow Dynamic_1_R#HIf!
38 Odd Stamps Ries Woron's Story Thrungus Expired Stamina Draught Dynamic_1_eMJVhyPzaa$aGn!
39 Odd Stamps Mite Maze Roderick Apple Pie Dynamic_1_#C^p&w0gV$$!
40 Odd Stamps Sawato Ssavish Composite Bow with Handle Dynamic_1_NMlDXfx2t!
41 Odd Stamps dryreach rescue Dansha-Ki Composite Bow with Handle Dynamic_1_FnXoHWS&kaM!
42 Odd Stamps Seat of Knorr Arikas, Warden of Knorr Hearty Healing Rabbit Noodle Dynamic_1_aWOWTc30f4
43 Odd Stamps Swamp Garden Terese Diforsa Bracers Dynamic_1_PTy0kqqTLP1Dn^!
44 Odd Stamps Dark Isle Tyrina of Arwic Major Shadow Gauntlets Dynamic_1_zJNxGBc! 84.7n 58.7e
45 Odd Stamps Dark Isle Francois di Terli Habraeloi Dynamic_1_3!Og!
46 Odd Stamps 2 Aun Settlement 82.7N 21.2E. Aun Tikakhe Good Chilling Isparian Mace Dynamic_1_hafO$cQvbkg! 82.7N 21.2E
47 Odd Stamps 2 Aun Saritea Health Tonic Dynamic_1_7yW17JvMHKu!
48 Odd Stamps 2 Aun Aulakhe Mana Rabbit Pie Dynamic_1_5xE2TM!
49 Odd Stamps 2 Lost Wish Cottages (Arwic) 42.6n 62.4e Lartorus Pants Dynamic_1_$GB72K! 42.6n 62.4e
50 Odd Stamps 2 Catacombs of Opposition Ripper Gladiatorial Tunic Dynamic_1_69Rjbany2pKD!
51 Odd Stamps 2 Rat Nose Fine Atlan Staff Dynamic_1_eBlku!
52 Odd Stamps 2 Nanoc, Basher of Bugs Mana Potion Dynamic_1_XCTiy!
53 Odd Stamps 2 Narg Iron Rusted Mace Dynamic_1_S!AhI!
54 Odd Stamps 2 Scout Luzumin Abigwei Alduressa Helm Dynamic_1_NFf5!
55 Odd Stamps 2 Teela Orange Molly Dynamic_1_Bl#Y!
56 Odd Stamps 2 Scout Tel al-Arat Envoy's Heaume Dynamic_1_AJ3Wm9Bk!
57 Odd Stamps 2 Pincer Danta Olthoi Sollerets Dynamic_1_VezOOBWbn43KU!!
58 Odd Stamps 2 Vissidal Merwart Pelagurg Superior Smoldering Atlan Staff Dynamic_1_DOIC1!
59 Odd Stamps 2 Vissidal Merwart Urglurg Butter Knife of Slaying Dynamic_1_&!iRR#RrhnGA!
60 Odd Stamps 2 Vissidal Dayla Bint Kazm Hearty Healing Chicken Pie Dynamic_1_nDAXG!
61 Odd Stamps 2 Vissidal Peng-Ya Major Dissolving Isparian Crossbow Dynamic_1_sx^9H^&Mnqp!
62 Odd Stamps 2 Vissidal Colista Fluress Lesser Amuli Shadow Leggings Dynamic_1_Ej!Zz!
63 Odd Stamps 2 99.7S 96.7W Surloshen Realaidain Hammer of Lightning Dynamic_1_tiiFC! 99.7S 96.7W
64 Odd Stamps 2 Silyiun - 89.1N 47.6W Fiun Gaya Enhanced Shadow Gauntlets Dynamic_1_hev0! 89.1N 47.6W
65 Odd Stamps 2 Hermit - Thrungus Hole Hermit Scored Amuli Leggings Dynamic_1_rDBG!
66 Odd Stamps 2 93.2N 48.2W - Eastwatch Commander Rylane di Cinghalle Acid Crossbow Dynamic_1_pZpx41&! 93.2N 48.2W
67 Odd Stamps 2 32.0N, 43.2W - Virindi Crafters Crafter of Arbelests Healing Carrot Soup Dynamic_1_L3Hb3O! 32.0N, 43.2W
68 Odd Stamps 2 32.0N, 43.2W - Virindi Crafters Crafter of Fists Platemail Breastplate Dynamic_1_xj&USOHNL9K&! 32.0N, 43.2W
69 Odd Stamps 2 32.0N, 43.2W - Virindi Crafters Crafter of Bows Tasty Stout Dynamic_1_hw2LNdjT6! 32.0N, 43.2W
70 Odd Stamps 2 32.0N, 43.2W - Virindi Crafters Crafter of Atlatls Composite Crossbow with Handle Dynamic_1_P6!! 32.0N, 43.2W
71 Odd Stamps 2 32.0N, 43.2W - Virindi Crafters Crafter of Axes Three Eyed Guppy Dynamic_1_xX^IHjOo##J$8E! 32.0N, 43.2W
72 Odd Stamps 2 32.0N, 43.2W - Virindi Crafters Crafter of Blades Flaming Weeping Dagger Dynamic_1_iFuvP! 32.0N, 43.2W
73 Odd Stamps 2 32.0N, 43.2W - Virindi Crafters Crafter of Staves Composite Crossbow Dynamic_1_J$JV&VKf! 32.0N, 43.2W
74 Odd Stamps 2 32.0N, 43.2W - Virindi Crafters Crafter of Orbs Health Tincture Dynamic_1_S&JMdWiBDy! 32.0N, 43.2W
75 Odd Stamps 2 32.0N, 43.2W - Virindi Crafters Crafter of Maces Wooden Scarecrow Guise Dynamic_1_^pTx! 32.0N, 43.2W
76 Odd Stamps 2 32.0N, 43.2W - Virindi Crafters Crafter of Knives Scalemail Hauberk Dynamic_1_6ZR$k^$Srwc3g! 32.0N, 43.2W
77 Odd Stamps 2 83.4S 97.2E - Ithaenc Abbess Zik'Lir Hearty Fish Noodle Dynamic_1_jmCfm1p5a! 83.4S 97.2E
78 Odd Stamps 2 72.8N,25.0W - Stonehold nearby Lord Pyrovor Enhanced Shadow Greaves Dynamic_1_Tw$7Zwmutan! 72.8N,25.0W
79 Odd Stamps 2 VoD Encampment Guard Alfric Bowl of Rice Dynamic_1_LZkvsu4Ln2$h!
80 Odd Stamps 2 VoD Encampment Guard Taziq Blackfire Shadow Sollerets Dynamic_1_t9uxr!
81 Odd Stamps 2 VoD Encampment Guard Q'alia Ancient Relic Gauntlets Dynamic_1_m1KeUXELMuH!
82 Odd Stamps 2 VoD Encampment Guard Li Frost Hatchet Dynamic_1_XgrV$!
83 Odd Stamps 2 77.7S 97.0E Ithaenc Shah-hi Katar Dynamic_1_G3N9HSXlowLT$! 77.7S 97.0E
84 Odd Stamps 2 Releasing the Light - Reward Room Calitoth Fish Dynamic_1_mu^91#T!
85 Odd Stamps 2 VoD Encampment Guardian of the Forbidden Princely Runed Dart Flinger Dynamic_1_#BELoT72Ib! Small Creepy Statue
86 Odd Stamps 2 Shattered Outlands 94.0n 45.9w Torgash examines your Parchment Dynamic_1_S 94.0n 45.9w
87 Odd Stamps 2 Hoshino Must Die last room Spirit of Bist'elle Enhanced Shadow Breastplate Dynamic_1_b!
88 Bandit Castle Karwin, the Lunatic Chainmail Pauldrons Dynamic_1_HIlMkY!
89 Bandit Castle Kiriel Shadowborn Healing Apple Pie Dynamic_1_WBzVFJpFUzHkC!
90 Bandit Castle Jourgensson Hearty Healing Mushroom Pie Dynamic_1_$W&Pl4!
91 Bandit Castle Gillian the Poacher Peppermint Ice Cream Dynamic_1_5oLp!
92 Bandit Castle Alison Dulane Amuli Shadow Leggings Dynamic_1_079u9!
93 Bandit Castle Arianna the Adept Expired Stamina Draught Dynamic_1_hZIsyYE!!OmcQ!
94 Bandit Castle Shanrek the Forger Sparring Shirt Dynamic_1_fbcmDRC!
95 Bandit Castle Neela Nashua Perfect Dissolving Isparian Spear Dynamic_1_4tXQFu&&o!
96 Bandit Castle Gwillim, the Apprentice Lightning Flanged Mace Dynamic_1_is#X6rBaprU!
97 Bur Drogur Frost Yari Dynamic_1_KS8e32dtk7t!
98 Bur Collector Golem Upper Exoskeleton Metamorphi Dynamic_1_4xdYA1QvaiDf^!
99 Bur Kuurak Hearty Healing Chicken Noodle Dynamic_1_Zapx!
100 Bur Furgal Spitter Thorax Metamorphi Dynamic_1_4rk&MTz!
101 Bur Tibik Gear Crossbow Dynamic_1_!Ce^d!
102 Bur Nimeruuk Greater Celdon Shadow Sleeves Dynamic_1_zIX1Sf6FJt!
103 Bur Kurket Acidic Rejuvenation Dynamic_1_snVaz#0Ze3R#4M!
104 Bur Brogosh Lugian Morning Star Dynamic_1_$9YdvC2jYTxWZ!
105 Bur Mohor Quality Isparian Crossbow Dynamic_1_qpXiWqwBTN4!
106 Bur Kushuk Silifi of Crimson Stars Dynamic_1_3ISBG!
107 Bur Borsh Health Tonic Dynamic_1_Jh4!
108 Bur Kuuru Electric Compound Bow Dynamic_1_vNktko1!
109 Bur Torgluuk, High Shaman of Kor-Gursha Stout Dynamic_1_2yxpXSMY!
110 Bur Scout Leader Tmauruk Hood Dynamic_1_fEiU!
111 Bur Gruuk'lar Rynthid Tentacle Dagger Dynamic_1_xFipmT1!
112 Gear Knight Inner Sea Gearknight Invasion Lieutenant Micham Dabus Dynamic_1_CQxkFJvoJrVx!
113 Gear Knight Inner Sea Gearknight Invasion Sir Oakley Composite Crossbow with Handle Dynamic_1_lh9wOaXR0!
114 Gear Knight Inner Sea Gearknight Invasion Lieutenant Faen Blunt Bow Dynamic_1_Vz#gp!
115 Gear Knight Inner Sea Gearknight Invasion Sir Stavitor Red Tea Dynamic_1_ogt05i!
116 Gear Knight Inner Sea Gearknight Invasion Dame Alistra Superb Flaming Isparian Claw Dynamic_1_y!
117 Gear Knight Direland Gearknight Invasion Sir Yanov Major Shadow Greaves Dynamic_1_BlAckAuHU#!
118 Gear Knight Direland Gearknight Invasion Sir Durnstad Silifi of Crimson Stars Dynamic_1_#Dfd!
119 Gear Knight Direland Gearknight Invasion Squire Tylaen Good Coruscating Isparian Atlatl Dynamic_1_i1Cxg8Bt!
120 Gear Knight Direland Gearknight Invasion Dame Trielle Frost Yari Dynamic_1_h^MdsKZ$6SSD!
121 Gear Knight Direland Gearknight Invasion T'ing Douzen Panaq Dynamic_1_p0BEy$e!
122 Gear Knight Atamarr Tasks Dungeon Bronze Gauntlet Knight-Commander Frost Greataxe Dynamic_1_REv&biyDw!
123 Gear Knight Direland Gearknight Invasion Copper Cog Craftsmaster Greater Amuli Leggings of Frost Dynamic_1_4uls5J!
124 Wai Jhou Kreavon Skeleton Fish Dynamic_1_KrPl9N5!
125 Wai Jhou Aun Teverea Singularity Crossbow Dynamic_1_Y9wg!RfKHoyL!
126 Wai Jhou Nona Fish Dynamic_1_JrzQr8U!
127 Wai Jhou Zho Heishan Bandit Dagger Dynamic_1_Abm8qK2!
128 Wai Jhou Sarkin Killcrane Shadow Tassets Dynamic_1_mb7NAtZEdBaz!
129 Wai Jhou Riordin Nightbane Hafted Serpent Spear Dynamic_1_cCzQdsl5JxLC!
130 Wai Jhou Lacarra Avanthi Shou-jen Shozoku Trousers Dynamic_1_ip&NsyQ!
131 Wai Jhou Xanda Har Gold Fish Dynamic_1_1CiKW8^x^$!
132 Rynthid Lohrn Shreth Hide Shoes Dynamic_1_cS!mivYZ^b!cAA!
133 Rynthid Rhys Plate Leggings Dynamic_1_A!!
134 Rynthid Morgethais Silifi of Crimson Stars Dynamic_1_wDTf#!
135 Rynthid Geilla Audetaunga's Korua of the Mountains Dynamic_1_&dNG5U4!
136 Rynthid Rinne Gorber Brilliant Celdon Leggings Dynamic_1_ln!Lx!
137 Rynthid Aun Ol'tra Small Beer Dynamic_1_&^3Hve4JXH^!
138 Rynthid Ranulf Prismatic Celdon Sleeves Dynamic_1_8n2l!
139 Rynthid Sylvanus Ursuin Hide Coat Dynamic_1_veaD!
140 Rynthid Marcus Fish Dynamic_1_bpNCu!rsf45Fk!
141 Rynthid Ilte Krongal Hearty Mana Rabbit Noodle Dynamic_1_AusVgDl!
142 Rynthid The Bringer of Light Peppermint Hot Chocolate Dynamic_1_LrpV!62!
143 Paradox Camp Paradox Olthoi Camp Ethan Wintermaine Superb Flaming Isparian Bow Dynamic_1_PPtO6!7dB!
144 Paradox Camp Adrien Swiftblade Oak Stormwood Crossbow Dynamic_1_R^1Uv!J8k!
145 Paradox Camp Alicia Swiftblade Badlands Siraluun Dress Dynamic_1_G0Rn1lOZKj7C!
146 Paradox Camp Tomihino Dart Flinger Dynamic_1_!$cc!
147 Paradox Camp North Olthoi Burrow Peda's Assistant examines your Parchment Dynamic_1_3ddaHUzi!
148 Paradox Camp North Olthoi Burrow Peda examines your Parchment Dynamic_1_1R9O85L$b!
149 Paradox Camp North Olthoi Burrow Crusher examines your Parchment Dynamic_1_a&Z2!
150 Paradox Camp North Olthoi Burrow Deena examines your Parchment Dynamic_1_cIZV2uDB6B!
151 Paradox Camp North Olthoi Burrow Mac examines your Parchment Dynamic_1_5x^G2$X9!
152 Paradox Camp North Olthoi Burrow Swift-Eye examines your Parchment Dynamic_1_o$yT7al7ZTxv!
153 Paradox Camp North Olthoi Burrow Sasha examines your Parchment Dynamic_1_CvzZIz!
154 Paradox Camp North Olthoi Burrow Dead-Eye examines your Parchment Dynamic_1_fP9y!
155 Paradox Camp North Olthoi Burrow Lash examines your Parchment Dynamic_1_AniHdl4wtIuF0!
156 Paradox Camp North Olthoi Burrow Long-Shot examines your Parchment Dynamic_1_jJ^yEFc#m^M!
157 Graveyard Renata Singularity Spear Dynamic_1_1fDZO3!
158 Graveyard Yoite Composite Bow with Handle Dynamic_1_OG6jdId!
159 Graveyard Gadi Scored Celdon Girth Dynamic_1_ELgh#!
160 Graveyard Aethelswith Leather Helm Dynamic_1_cF!
161 Graveyard Mhoire Soldier Superb Isparian Bow Dynamic_1_VgB#WcZOIA! North Soldier - Opposite side of bunker
162 Graveyard Mhoire Soldier Hafted Gromnie Banner with Crest Dynamic_1_z$DX! South Soldier - Opposite side of bunker
163 Graveyard Apep-tek the Tolerant Spectacular Lager Dynamic_1_Y55^MqgC! Above ground, outside bunker 65.3w 44.0w
164 Graveyard Laylana Stiletto Dynamic_1_&SRgbH! Above ground, outside bunker 65.2s 44.3w
165 Graveyard Lo Shoen Amateur Explorer Pants Dynamic_1_102!pkgn8wAYSe! Floating Platform - Level 50 req
166 Graveyard Slubbley Healing Cake Dynamic_1_mDaEh7!
167 Graveyard Jailer Good Shimmering Isparian Bow Dynamic_1_2Hm6DL! NE bunker aboveground 64.9s 44.1w
168 Graveyard Kousu Temo Fried Mushroom Rice Dough Dynamic_1_QUXbn6! EW Initiation guy, 64.2s 44.0w
169 Graveyard Candrus Steady-Hand Academy Mana Potion Dynamic_1_BKq6N6nXoR! CH Initiation guy, 65.8s 45.3w
170 Graveyard Ancient Stones Bandit Flaming Jambiya Dynamic_1_xL!g4ZoCuv!H Pile of stones at 66.5s 44.7w
171 Graveyard Mhoire Castle - Great Hall Ancient Throne Taiaha Dynamic_1_&y4ettwcivZ5Nm!
172 Graveyard Mhoire Castle - Great Hall Shade of Antemy Left Peg Leg Dynamic_1_CphV&!
173 Graveyard Mhoire Castle - Great Hall Shade of Fordroth Perfect Chilling Isparian Atlatl Dynamic_1_M0u7js^$E!
174 Graveyard Mhoire Castle - Great Hall Shade of Terelev Silifi of Crimson Stars Dynamic_1_XPvw!
175 Graveyard Mhoire Castle - Great Hall Guliant Celdon Girth of Acid Dynamic_1_aCEEdQil42!
176 Neftet T'ing Setsuko Flaming Broad Sword Dynamic_1_JfmjJmY0O8r!
177 Neftet Nephthys Red Tea Dynamic_1_mnJCjm5QR$s&!
178 Neftet Fahneph Gear Crossbow Dynamic_1_owGS9WGJ1Q!
179 Neftet Nekshla Mana Pumpkin Pie Dynamic_1_AAQ1#!
180 Neftet Sir Hassim bin Tamarek Enhanced Shadow Greaves Dynamic_1_r7zID$U!
181 Neftet Sir Adarl Bobo's Stout Dynamic_1_SoBgM6JPckOY9!
182 Neftet Sir Ibreh bin Kassim Expired Mana Tincture Dynamic_1_aVMuY!
183 Neftet Sir Daeglan Quality Coruscating Isparian Crossbow Dynamic_1_n!
184 Neftet Bemeth the Gatherer Lesser Koujia Breastplate of Acid Dynamic_1_bda1WYoI!
185 Neftet Hammah al Rundik Olthoi Greaves Dynamic_1_9v^POv6ADt3r!
186 Neftet 22.2S 8.7E Kaltus Composite Bow with Handle Dynamic_1_xWYS3fqIjPN! 22.2S 8.7E Not Dangerous run
187 Frozen Valley Sir Donovan Pickled Egg Dynamic_1_ypu2L!
188 Frozen Valley Sir Learth Royal Cabbage Dynamic_1_xpAJDzm$!
189 Frozen Valley Lady Daenerah Acid Spadone Dynamic_1_$SDp1uWx8wq$!
190 Frozen Valley Gregoria, Gurog Destroyer Chocolate Gromnie Dynamic_1_!vr&1c1Ug1XI!
191 Frozen Valley Hunter Hearty Healing Chicken Pie Dynamic_1_Sy!9l0FAJFI!
192 Frozen Valley Leilah Lightning Silifi Dynamic_1_uyoL!
193 Frozen Valley Halvor Noble Quarterstaff Dynamic_1_LfLac!
194 Frozen Valley Kumiko Expired Health Potion Dynamic_1_TB!q!
195 Frozen Valley Archmage Ichihiri Arbalest Dynamic_1_HzvCs4B2!
196 Hoshino Tent Sergeant Trebuus Soldier Pincer Metamorphi Dynamic_1_GQIb1mF!
197 Hoshino Tent Sergeant Freng Lightning War Axe Dynamic_1_wVJm&#Lpz7AQ#F
198 Hoshino Tent Aun Kirtal Arena Bow Dynamic_1_V9ffGx!
199 Hoshino Tent Lieutenant Aurin Enhanced Smoldering Atlan Sword Dynamic_1_4qlVcAWbM!
200 Hoshino Tent Lord Eorlinde Major Shadow Gauntlets Dynamic_1_zkzTna!
201 Hoshino Tent Griffon Mana Elixir Dynamic_1_b4^F&M1^uG!
202 Hoshino Tent Hanamoto Aki'ko Lightning Nekode Dynamic_1_3Qlg!
203 Hoshino Tent Corporal Irashi Lesser Koujia Shadow Leggings Dynamic_1_2DBoreKEH!
204 Hoshino Tent Lieutenant Takamaki Silifi of Crimson Stars Dynamic_1_#hzL!
205 Hoshino Tent Lieutenant Roothe Fried Rabbit Dynamic_1_XuH!z7l!
206 Viridian Rise Brellegia Greater Celdon Breastplate of Acid Dynamic_1_mCyu9F! Requires Viridian Rise Recall Gem
207 Viridian Rise Summercrown Tachi Dynamic_1_R8H6nh!
208 Viridian Rise Aangesilus Slashing Compound Bow Dynamic_1_2LJyvGJL!
209 Viridian Rise Dridge Greater Amuli Leggings of Flame Dynamic_1_LP3Ee7tH!
210 Viridian Rise Kervim'telek Ursuin Hide Coat Dynamic_1_E5$S!
211 Viridian Rise Swift Fried Chicken Dynamic_1_hYVV!
212 Ayan Aludi al-Jaladh Seasoned Explorer Gauntlets Dynamic_1_7$I7bC!
213 Ayan Aun Javhalrea, the Game Warden Frost Ono Dynamic_1_UdRA9W!
214 Ayan Aun Khekierea Rich Mocha Dynamic_1_Yt1uiSkCgK!
215 Ayan Aun Aukherea Chocolate Cookie Dynamic_1_G$iqi763E!
216 Ayan Shuthoth Silifi of Crimson Stars Dynamic_1_CkuPj0IwP!
217 Ayan Yuan Hanzu Acid Hatchet Dynamic_1_t^CiJAt2TBz17!
218 Ayan Joku Shunja Dho Life Apprentice Robe Dynamic_1_&X4EDhy!
219 Ayan Aaminah Upgraded Marksman's Robe Dynamic_1_YlHC^cbS!
220 Ayan Anfram Mellow Ulgrim's Bunny Slippers Dynamic_1_$MJj0ytiSy0CKN!
221 Ayan Alishia bint Aldan Lightning Hatchet Dynamic_1_87z&&Ok2o&jo!
222 Ayan Vierana du Canamorra Fine Shadow Atlan Mace Dynamic_1_qtZdY0C!ae!
223 Ayan Qurakh al-Taal Hearty Mana Beef Stew Dynamic_1_Ug2snTqb44!
224 Ayan Laedron the Geomancer Fine Stinging Atlan Spear Dynamic_1_2lXQdqHWxPU!
225 Ayan Rohula bint Ludun Arena Staff Dynamic_1_SjjPqyCHNigY!
226 Ayan Guard Winterborn Silifi of Crimson Stars Dynamic_1_!fzudXFZV0Je3!
227 Ayan Ennio di Cinghalle Perfect Chilling Isparian Claw Dynamic_1_fYP!
228 Ayan Lydda Pathwarden Scale Hauberk Dynamic_1_neYBz15!
229 Ayan Gaston Shadowbound Major Shadow Tassets Dynamic_1_jdMT!
230 Ayan Harkwull the Discreet Quality Flaming Isparian Crossbow Dynamic_1_Bq7Brhg!
231 Ayan Tanami Kei Souldrinker Dynamic_1_en!
232 Ayan Lamorda Loschi Major Shadow Sollerets Dynamic_1_2xn4LwsUdh!
233 Ayan Soju Bo-Ki Composite Crossbow with Handle Dynamic_1_ADDKG!
234 Ayan Hoshar ibn Jalaq High Balance Testing Coat Dynamic_1_bZ4bc!
235 Ayan Guard Bey Tasty Stout Dynamic_1_&!4f5YlXZ!
236 Ayan Ishaq the Philosopher Enhanced Skeletal Atlatl Dynamic_1_H3UNETkRXTX!
237 Candeth Keep Morathe gives you Superb Isparian Atlatl Dynamic_1_g9M7bV3z3#S!
238 Candeth Keep Aun Autuorea gives you Singularity Katar Dynamic_1_5kEI0!
239 Candeth Keep Talira Dain Composite Bow Dynamic_1_5i1z1Mb! No text about being given item, it just shows up in backpack
240 Candeth Keep Dalius Kendmar gives you Undead Guise Dynamic_1_YFrw!
241 Candeth Keep Grania the Bold gives you Composite Crossbow with Handle Dynamic_1_DaevbVP!
242 Candeth Keep Yukara Miko the Collector Acid Longbow Dynamic_1_F1r^qTQ!
243 Candeth Keep Ryukai Hiro Good Olthoi Pauldrons Dynamic_1_HeucrAy6c!
244 Candeth Keep Garaena the Emissary Seasoned Explorer Arbalest Dynamic_1_es^0FY! Aerlinthe Portal NPC

View file

@ -0,0 +1,152 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
RynthILT: features for Infinite Leaftide (ILT), the ACECustom server. ILT features live here,
not in RynthAi or the engine core. The engine shows its panels (the bar's ILT button: Bounties,
Guardian; /rc bounties, /rc guardian; the Skills panel's Progression tab) only on ILT
(RynthCore Compatibility/IltInfo.cs, which also asks RynthILT).
Bounty/ the Bounties window's tracker (ported from SilentKelpie's rynth/RynthSuite PR #11).
Hub/ the ILT Hub (SilentKelpie's): the Mini Remote's ILT tabs (Character, Banking, Gear,
Charms, Games), the Guardian, the progression planners and the attribute raiser,
server feature detection, the Rings inscription chain (Gear tab). Moved out of
RynthAi 2026-10-13: RynthAi's Mini Remote hosts the tabs through RynthILT.Hub, and
RynthILT borrows from RynthAi through RynthAi.Hub (Plugins/Shared/RynthServerHubApi.cs,
RynthAiHubApi.cs).
IltSettingsView/ a copy of the ILT settings (RynthCore's verdict, this character's override, the
ILT world names, the Hub's feature read) in its own window ("/ilt settings"),
with this character's ILT options (Vaulted Dungeons master switch, Handler
ring evade, T11 item augs).
Moved out of RynthAi 2026-10-20 (Hub/): the Pets tab's ACECustom parts (IltPetAutomation:
pet charms, summon from empty, siphon capture), the Empyrean Handler ring
detection (IltRingEvade; RynthAi does the back-away), the T11 /aug counters
and "/ilt t11" (IltT11; RynthAi keeps the loot keys), the Vaulted Dungeons
switch, the Remote tab's ILT parts, the Mini Remote tab views on the rail
(IltSectionsManifest.cs) and the Leaftide trinket list (the profile).
IltFellowship/ ILT's /fship commands as buttons ("/ilt fellow").
Moved out of RynthOracle 2026-10-21 (Hub/): the Dynamic Stamps (IltDynamicStamps, RynthILT's own
Quests section page and "/ilt stamps"; SilentKelpie's) and a window for the
pet breeding tracker ("/ilt breeding").
-->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.RynthILT</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthILT</AssemblyName>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Nothing above the v66 baseline: every
newer call (plugin interfaces v68, live object ids v69, vendor trade v67, confirmation
answers v85, the server list v86, ...) is behind its Has* check, as it was in RynthAi. -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<!-- RynthILT is ILT's server plugin: RynthCore loads it only for clients connecting to ILT, or late
when the world announces an ILT name (SilentKelpie's server plugins). Same lists as RynthCore's
IltDetect defaults. -->
<RynthPluginServerId>ilt</RynthPluginServerId>
<RynthPluginServerName>Infinite Leaftide</RynthPluginServerName>
<RynthPluginServerHosts>infiniteleaftide.online</RynthPluginServerHosts>
<RynthPluginServerWorldNames>InfiniteLeaftide|*Leaftide*</RynthPluginServerWorldNames>
<RynthPluginDescription>Infinite Leaftide (ACECustom) features: the ILT Hub (the Mini Remote's ILT tabs: banking, gear, charms, games, Vaulted Dungeons; the Pets tab's charms, siphon capture and breeding), the Guardian, the Dynamic Stamps, bounties, progression, the attribute raiser, the ring inscription chain, the Empyrean Handler ring evade, the T11 loot counters, the ILT settings and the /fship fellowship commands.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>
<!-- RynthAi hosts the ILT tabs in its Mini Remote and lends its quest tracker, spell names and
loot matching (RynthAi.Hub). Optional: without it the panels and commands still work. -->
<RynthPluginDependency Include="RynthAi" Optional="true" />
</ItemGroup>
<ItemGroup>
<!-- The two interfaces between RynthILT and RynthAi (linked into both plugins): RynthServer.Hub, which
RynthILT serves (also as "RynthILT.Hub", RynthIltHubApi.cs: its own names), and RynthAi.Hub. -->
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\RynthServerHubApi.cs" Link="Shared\RynthServerHubApi.cs" />
<Compile Include="..\Shared\RynthIltHubApi.cs" Link="Shared\RynthIltHubApi.cs" />
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\RynthAiHubApi.cs" Link="Shared\RynthAiHubApi.cs" />
<!-- Chat types and the line-start marker (the Empyrean Handler's ring line, Hub/IltRingEvade.cs). -->
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\ChatSource.cs" Link="Shared\ChatSource.cs" />
<!-- "RynthAi.Activity": what the bot is doing (the Vaulted Dungeons keeper waits out combat and buffing). -->
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<!-- The pet-capture success lines (shared with RynthAi's Pets tab): they count as a kill for Vaulted Dungeons' timer. -->
<Compile Include="..\Shared\PetCaptureLines.cs" Link="Shared\PetCaptureLines.cs" />
<!-- "RynthILT.Data": the charms list and bank balances for other plugins (DataInterface.cs). -->
<Compile Include="..\Shared\RynthIltDataApi.cs" Link="Shared\RynthIltDataApi.cs" />
<!-- "RynthILT.Server": the feature / fellowship / quest bonus profile for other plugins (ServerInterface.cs). -->
<Compile Include="..\Shared\RynthIltServerApi.cs" Link="Shared\RynthIltServerApi.cs" />
<!-- RynthCore's server list (API v86): the ILT verdict the Hub follows (IltSettingsView/). -->
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\EngineServerState.cs" Link="Shared\EngineServerState.cs" />
<!-- "RynthServer.Profile": ILT's settings and tinkering salvage (Hub/IltSalvage.cs) for other
plugins (ProfileInterface.cs), with the server plugins' own record and JSON writer. -->
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\RynthServerProfileApi.cs" Link="Shared\RynthServerProfileApi.cs" />
<Compile Include="..\Shared\ServerPack\ServerPackInfo.cs" Link="ServerPack\ServerPackInfo.cs" />
<Compile Include="..\Shared\ServerPack\ServerPackProfile.cs" Link="ServerPack\ServerPackProfile.cs" />
<!-- ImGui.NET bound to the engine's cimgui (the tabs draw inside RynthAi's Mini Remote). -->
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<!-- ImGui text calls for non-literal text ('%' escaped; RynthAi links the same file). -->
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
<!-- Install-folder resolver (the ILT Hub files left in the RynthAi folder). -->
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- One logged, guarded way to use an object (the Guardian's vendor). -->
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
<!-- Save failures (its own files and the copies migrated from RynthAi) said in chat with the
reason and the fix, as RynthAi's are. -->
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\DataWriteGuard.cs" Link="Shared\DataWriteGuard.cs" />
<!-- T11 (ACECustom tier 11+ gear): the "/aug" reader, the counters and the item text parser (Hub/IltT11.cs,
"/ilt t11"). RynthAi keeps the loot keys and evaluator; RynthILT reports the counters to it. -->
<Compile Include="$(RynthSuiteRoot)Shared\RynthCore.LootSdk\T11\T11Catalog.cs" Link="Shared\T11\T11Catalog.cs" />
<Compile Include="$(RynthSuiteRoot)Shared\RynthCore.LootSdk\T11\T11ItemInfo.cs" Link="Shared\T11\T11ItemInfo.cs" />
<Compile Include="$(RynthSuiteRoot)Shared\RynthCore.LootSdk\T11\T11Keys.cs" Link="Shared\T11\T11Keys.cs" />
<Compile Include="$(RynthSuiteRoot)Shared\RynthCore.LootSdk\T11\T11PlayerAugs.cs" Link="Shared\T11\T11PlayerAugs.cs" />
<!-- AcObjectClass (the item classes the gear tools check). -->
<Compile Include="$(RynthSuiteRoot)Shared\RynthCore.LootSdk\AcGameEnums.cs" Link="Shared\AcGameEnums.cs" />
<!-- ILT's /fship commands (IltFellowship/): the shared command list format and its button panel. -->
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\ServerCommandShare.cs" Link="Shared\ServerCommandShare.cs" />
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\ServerCommandPanel.cs" Link="Shared\ServerCommandPanel.cs" />
<!-- Dynamic Stamps (Hub/IltDynamicStamps.cs, from RynthOracle 2026-10-21): RynthOracle's /myquests parser
and its helpers, linked as RynthConquest links them, so both read the flags alike; and its
coordinates reader (the stamps' RynthNav targets). -->
<Compile Include="$(RynthSuiteRoot)Plugins\RynthCore.Plugin.RynthOracle\Data\QuestFlags.cs" Link="Shared\Oracle\QuestFlags.cs" />
<Compile Include="$(RynthSuiteRoot)Plugins\RynthCore.Plugin.RynthOracle\Data\TimeText.cs" Link="Shared\Oracle\TimeText.cs" />
<Compile Include="$(RynthSuiteRoot)Plugins\RynthCore.Plugin.RynthOracle\Data\Csv.cs" Link="Shared\Oracle\Csv.cs" />
<Compile Include="$(RynthSuiteRoot)Plugins\RynthCore.Plugin.RynthOracle\Data\NavTargets.cs" Link="Shared\Oracle\NavTargets.cs" />
</ItemGroup>
<ItemGroup>
<!-- Infinite Leaftide's Dynamic Stamps (the players' ExtraDyn sheet, 10.13.2026): Hub/IltDynamicStampList.cs. -->
<EmbeddedResource Include="Resources\dynstamps.csv" LogicalName="RynthILT.dynstamps.csv" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
</ItemGroup>
<ItemGroup>
<TrimmerRootAssembly Include="ImGui.NET" />
</ItemGroup>
<ItemGroup>
<!-- Offline tests (Tools\RynthILT.Tests) reach internal types. Test-only; no runtime effect. -->
<InternalsVisibleTo Include="RynthILT.Tests" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
<!-- The engine supplies cimgui (RynthCore.cimgui.dll); ImGui.NET's own never ships beside the plugin. -->
<Target Name="RemoveBundledImGuiNativeFromBuild" AfterTargets="Build">
<Delete Files="$(OutputPath)cimgui.dll" Condition="Exists('$(OutputPath)cimgui.dll')" />
</Target>
<Target Name="RemoveBundledImGuiNativeFromPublish" AfterTargets="Publish" Condition="'$(PublishDir)' != ''">
<Delete Files="$(PublishDir)cimgui.dll" Condition="Exists('$(PublishDir)cimgui.dll')" />
</Target>
</Project>

View file

@ -0,0 +1,13 @@
using System.Text.Json.Serialization;
using RynthCore.Plugin.RynthILT.Bounty;
namespace RynthCore.Plugin.RynthILT;
// Source-generated System.Text.Json only: never reflection-serialize plugin types (the
// reflection cache keeps the old plugin generation alive across a hot reload).
[JsonSerializable(typeof(BountyState))]
[JsonSerializable(typeof(BountyBridgePayload))]
[JsonSourceGenerationOptions(
IncludeFields = true,
PropertyNameCaseInsensitive = true)]
internal partial class RynthILTJsonContext : JsonSerializerContext { }

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,82 @@
// ServerInterface.cs - RynthILT's side of the "RynthILT.Server" interface (Plugins/Shared/RynthIltServerApi.cs):
// the profile JSON other plugins read (RynthOracle's Quests qb list and feature list until 2026-10-21;
// RynthILT's own Quests section and settings window show them now):
// the Leaftide feature list with the server's state for each, and the server's fellowship rules.
//
// Restored 2026-10-16: this export was dropped when "RynthServer.Profile" (salvage / identity) was
// added, so Oracle still detected ILT via RynthCore but never received feature / qb / fellowship
// data from RynthILT. Hub + Data stay separate; this table is the feature-profile channel.
//
// The table is allocated once per loaded copy of RynthILT and never freed (a plugin DLL is never
// unloaded); after Release() it reports Version 0 and GetProfileJson answers 0. Before login there
// is no controller, so the profile is the not-ILT default (every feature unknown, retail fellowships).
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT;
internal static unsafe class ServerInterface
{
private static RynthIltServerApiV1* _table;
private static volatile bool _released;
/// <summary>The profile before any login: not an ILT world, nothing known (built once).</summary>
private static readonly string NotLoggedInJson =
IltFeatureCatalog.BuildProfileJson(false, string.Empty, false, string.Empty, DateTime.MinValue, _ => IltTri.Unknown);
/// <summary>The table for (<paramref name="iface"/>, <paramref name="version"/>), or 0 when it isn't ours.</summary>
public static IntPtr Query(string iface, uint version)
{
if (iface != RynthIltServerApiV1.InterfaceName || version < 1 || version > RynthIltServerApiV1.InterfaceVersion || _released)
return IntPtr.Zero;
if (_table == null)
{
var t = (RynthIltServerApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthIltServerApiV1));
t->StructSize = (uint)sizeof(RynthIltServerApiV1);
t->GetProfileJson = &GetProfileJson;
t->Version = RynthIltServerApiV1.InterfaceVersion;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>Plugin shutdown: readers see Version 0 and re-query; GetProfileJson answers 0.</summary>
public static void Release()
{
_released = true;
if (_table != null) _table->Version = 0;
}
/// <summary>The JSON to hand out now: the live controller's snapshot, or the not-logged-in default.</summary>
internal static string CurrentJson()
=> (_released ? null : PluginExports.Runtime.Plugin?.Hub?.ProfileJson) ?? NotLoggedInJson;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetProfileJson(byte* buffer, int capacity)
{
try
{
if (_released) return 0;
return ProfileInterface.Write(CurrentJson(), buffer, capacity);
}
catch { return 0; }
}
/// <summary>
/// Copies <paramref name="json"/> as NUL-terminated UTF-8 into the caller's buffer when it fits,
/// and returns its byte length either way (length >= capacity: too small, nothing written).
/// </summary>
internal static int Write(string json, byte* buffer, int capacity)
{
int length = Encoding.UTF8.GetByteCount(json);
if (buffer == null || capacity <= length) return length;
fixed (char* src = json)
Encoding.UTF8.GetBytes(src, json.Length, buffer, capacity);
buffer[length] = 0;
return length;
}
}