Snapshot for release 2026.10.13.2 (internal 6cd69e2)

This commit is contained in:
Tom Bohar 2026-10-13 15:07:08 -04:00
commit 56b9f6c813
94 changed files with 5793 additions and 1637 deletions

View file

@ -692,17 +692,23 @@ internal sealed class BountyTracker
_lastSaveMs = NowMs;
if (!_dirty || _filePath.Length == 0) { _dirty = false; return; }
_dirty = false;
try
{
string? dir = Path.GetDirectoryName(_filePath);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
string tmp = _filePath + ".tmp";
File.WriteAllText(tmp, JsonSerializer.Serialize(_s, RynthILTJsonContext.Default.BountyState));
File.Move(tmp, _filePath, overwrite: true);
}
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,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,113 @@
// 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 2026-10-11):
// /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 (IltBanking); Prestige Coins can't be transferred.
// 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;
namespace RynthCore.Plugin.RynthILT.Hub;
internal static class IltBankCommands
{
/// <summary>A deposit choice: label, and the command's argument after "/b d" ("" = all).</summary>
public static readonly (string Label, string Args)[] Deposits =
{
("Everything", ""),
("Pyreals", "p"),
("Pyreal peas", "ps"),
("Luminance", "l"),
("Luminance tokens", "lum"),
("Legendary keys", "k"),
("Mythical keys", "mk"),
("Enlightened coins", "e"),
("Weakly enlightened coins", "we"),
("Prestige coins", "pc"),
("Trade notes", "n"),
};
/// <summary>A withdraw choice: label and the server code; "n" is trade notes (by denomination).</summary>
public static readonly (string Label, string Code)[] Withdrawals =
{
("Pyreals", "p"),
("Luminance", "l"),
("Legendary keys", "k"),
("Mythical keys", "mk"),
("Enlightened coins", "e"),
("Weakly enlightened coins", "we"),
("Prestige coins", "pc"),
("Trade notes", "n"),
};
/// <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.</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 == "lum" ? "/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 != "n") return $"/b w {code} {amount}";
if (denomination < 0 || denomination >= NoteDenominations.Length) { error = "Pick a note denomination."; return string.Empty; }
if (amount > MaxNoteCount) { error = $"At most {MaxNoteCount:N0} notes at a time."; return string.Empty; }
return $"/b w n {NoteDenominations[denomination].Code} {amount}";
}
/// <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);
}
}

View file

@ -0,0 +1,572 @@
// IltBanking.cs — ILT Hub "Banking" tab: /bank balances, deposits, withdrawals, confirmed
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
// transfers, transaction log.
//
// 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}".
// Codes: p pyreals, l luminance, k legendary keys, mk mythical keys, e enl coins, we weak coins.
// Prestige Coins (pc) are bound: deposit and withdraw 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).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Plugin.RynthILT.Hub;
internal sealed class IltBanking : IIltFeature
{
/// <summary>Transfer currency table: display name, /bank t code.</summary>
public static readonly (string Name, string Code)[] Currencies =
{
("Pyreals", "p"),
("Luminance", "l"),
("Legendary Keys", "k"),
("Mythical Keys", "mk"),
("Enlightened Coins", "e"),
("Weakly Enlightened Coins", "we"),
};
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;
// 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>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;
_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. Pump thread.
/// Returns an error message, or empty when the command was queued.
/// </summary>
public string SendTransfer(int currencyIndex, long amount, string target)
{
RynthLog.Trace(LogCat.IltBanking, $"SendTransfer(currency={currencyIndex}, amount={amount}, target='{target}')");
if (!Enabled) return "Bank is not available on this server.";
if (currencyIndex < 0 || currencyIndex >= Currencies.Length) return "Pick a currency.";
if (amount <= 0) return "Amount must be positive.";
target = (target ?? string.Empty).Trim();
if (target.Length == 0) return "Enter a recipient.";
// The recipient is spliced into a chat command, so only character-name characters are
// allowed: no '/', control characters or line breaks that could start a second command.
if (!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.";
long now = IltHubContext.NowMs;
if (now - _lastBankCommandAt < BankCommandSpacingMs) return "Bank commands are limited to one every 5 seconds.";
_lastBankCommandAt = now;
string cmd = $"/bank t {Currencies[currencyIndex].Code} {amount} {target}";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = cmd,
IsResponseLine = t => t.StartsWith("Transferred ", StringComparison.Ordinal)
|| t.StartsWith("Character '", StringComparison.Ordinal)
|| t.StartsWith("You cannot transfer", StringComparison.Ordinal)
|| t.StartsWith("You don't have enough", StringComparison.Ordinal)
|| t.StartsWith("[Transfer]", StringComparison.Ordinal),
IdleEndMs = 500,
FirstLineTimeoutMs = 8000,
Eat = false,
OnComplete = r =>
{
_lastResult = r.Lines.Count > 0 ? r.Lines[^1] : (r.TimedOut ? "No reply from server." : string.Empty);
// 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;
_refreshDueAt = IltHubContext.NowMs + RefreshAfterActionMs;
},
});
return string.Empty;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
// Periodic quiet refresh only while the Hub is open and the server has /bank.
int every = Bank.AutoRefreshSeconds;
if (Enabled && _ctx.WindowOpen && 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))
{
ParseBalanceLine(text);
return false; // eating is decided by the capture queue
}
// 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 ─────────────────────────────────────────────────────────────
private void ParseBalanceLine(string text)
{
string body = text.Substring("[BANK]".Length).Trim();
int colon = body.IndexOf(':');
if (colon <= 0) return;
string label = body.Substring(0, colon).Trim();
long value = IltParse.ParseLeadingLong(body.Substring(colon + 1));
if (body.Substring(colon + 1).Trim().Length == 0) return; // header "Your balances are:"
// Order matters: "Weakly Enlightened Coins" also contains "Enlightened Coins".
if (label.Contains("Prestige", StringComparison.OrdinalIgnoreCase)) Apply("PrestigeCoins", ref Bank.PrestigeCoins, value);
else if (label.Contains("Weakly", StringComparison.OrdinalIgnoreCase)) Apply("WeaklyEnlightenedCoins", ref Bank.WeaklyEnlightenedCoins, value);
else if (label.Contains("Enlightened", StringComparison.OrdinalIgnoreCase)) Apply("EnlightenedCoins", ref Bank.EnlightenedCoins, value);
else if (label.Contains("Mythical", StringComparison.OrdinalIgnoreCase)) Apply("MythicalKeys", ref Bank.MythicalKeys, value);
else if (label.Contains("Legendary", StringComparison.OrdinalIgnoreCase)) Apply("LegendaryKeys", ref Bank.LegendaryKeys, value);
else if (label.Contains("Luminance", StringComparison.OrdinalIgnoreCase)) Apply("Luminance", ref Bank.Luminance, value);
else if (label.Contains("Pyreal", StringComparison.OrdinalIgnoreCase)) Apply("Pyreals", ref Bank.Pyreals, value);
else return;
Bank.LastUpdated = DateTime.Now;
_ctx.Options.Set(IltFeature.Bank, IltTri.On);
}
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)
{
ImGui.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();
ImGui.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);
ImGui.Separator();
RenderDepositWithdraw();
ImGui.Separator();
RenderTransferForm();
ImGui.Separator();
RenderTransactionLog();
}
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())
ImGui.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) ImGui.TextDisabled("= " + IltParse.N0(amount * IltBankCommands.NoteDenominations[denom].Value) + " pyreals");
else ImGui.TextDisabled("= " + IltParse.N0(amount));
}
string result = _actionResult;
if (result.Length > 0) ImGui.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;
ImGui.SetNextItemWidth(200);
ImGui.InputTextWithHint("Amount##xfer", "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;
bool amountOk = IltParse.TryParseAmount(_amountText, out long amount);
if (_amountText.Length > 0)
{
ImGui.SameLine();
if (amountOk) ImGui.TextDisabled("= " + IltParse.N0(amount));
else ImGui.TextColored(IltStyle.ColHp, "invalid amount");
}
ImGui.BeginDisabled(!amountOk || string.IsNullOrWhiteSpace(Bank.TransferTarget));
if (ImGui.Button("Send transfer..."))
{
int cur = idx;
long amt = amount;
string who = Bank.TransferTarget.Trim();
_ctx.Confirm("Confirm bank transfer",
$"Send {IltParse.N0(amt)} {Currencies[cur].Name} to {who}?\n\nThis cannot be undone.",
() =>
{
string err = SendTransfer(cur, amt, who);
_lastResult = err.Length > 0 ? err : "Transfer sent...";
},
"Send");
}
ImGui.EndDisabled();
if (_lastResult.Length > 0) ImGui.TextWrapped(_lastResult);
}
private void RenderTransactionLog()
{
var snap = _txSnapshot;
ImGui.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();
ImGui.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,255 @@
// 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;
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);
ImGui.TextDisabled("Status: " + _dispelStatus);
var harm = _harmfulNow;
if (harm.Length > 0) ImGui.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;
ImGui.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++)
{
ImGui.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,142 @@
// 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("\"}");
}
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,217 @@
// IltCharms.cs — The Mini Remote's "Charms" ILT tab: every ACECustom registry charm in one table.
// 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;
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)
}
// ── 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)
{
ImGui.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);
ImGui.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 ImGui.TextColored(IltStyle.ColTextMute, r.Def.Name);
if (ImGui.IsItemHovered() && r.Def.Effect.Length > 0) ImGui.SetTooltip(r.Def.Effect);
ImGui.TableNextColumn();
if (carried) ImGui.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)
ImGui.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) ImGui.TextDisabled($"{h.Name} - disabled on this server");
else
{
var col = h.Status == IltTri.On ? IltStyle.ColGreen
: h.Status == IltTri.Off ? IltStyle.ColTextMute : IltStyle.ColAmber;
ImGui.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,200 @@
// 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,
// /ilt features, the login probe, ...) 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: 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>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;
if (gotAny && now - _lastLineAt >= _active.IdleEndMs)
Finish();
else if (!gotAny && 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);
_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;
_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;
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,282 @@
// 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 a Lugian (Aetheria) Hammer on eligible items, one at a time:
// Aetheria — "Aetheria"/"Coalesced Aetheria" gems, not equipped, appraised, not flagged
// never-chunk (bool 9030), never levelled (ItemTotalXp quad 4 == 0), and
// max level (int 319) under the configured cap (Coalesced always qualifies).
// Corrupted — "Corrupted" melee/missile weapons with no tinks (171), no imbue (179),
// not equipped, not never-chunk, cleave (292) <= 1.
// Peace mode only unless ChunkInCombat; waits for the result line (10 s max).
// Clap: "/clap all" converts aetheria chunks + trinkets into coins server-side. 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;
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;
// 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 ───────────────────────────────────────────────────────────────
private WorldObject? FindHammer()
=> _ctx.Inventory.FindByName(n => n.Equals("Lugian Aetheria Hammer", StringComparison.OrdinalIgnoreCase)
|| n.Equals("Lugian Hammer", StringComparison.OrdinalIgnoreCase)
|| n.EndsWith(" Lugian Hammer", StringComparison.OrdinalIgnoreCase));
/// <summary>True/false when decidable; null when appraisal is still needed.</summary>
private bool? IsChunkableAetheria(WorldObject wo)
{
if (wo.ObjectClass != AcObjectClass.Gem) return false;
bool coalesced = wo.Name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase);
if (!coalesced && (!wo.Name.Contains("Aetheria", StringComparison.OrdinalIgnoreCase) || wo.Name.Contains("Chunk", StringComparison.OrdinalIgnoreCase)))
return false;
var inv = _ctx.Inventory;
if (inv.IsEquipped(wo)) return false;
if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return null; }
if (inv.Bool(wo, IltInventory.BoolNeverChunk)) return false;
if (inv.Quad(wo, IltInventory.QuadItemTotalXp) != 0) return false;
return coalesced || inv.Int(wo, IltInventory.IntItemMaxLevel) < Math.Max(1, G.ChunkAetheriaUnderLevel);
}
private bool? IsChunkableCorrupted(WorldObject wo)
{
if (wo.ObjectClass is not (AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon)) return false;
if (!wo.Name.Contains("Corrupted", StringComparison.OrdinalIgnoreCase)) return false;
var inv = _ctx.Inventory;
if (inv.IsEquipped(wo)) return false;
if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return null; }
if (inv.Bool(wo, IltInventory.BoolNeverChunk)) return false;
if (inv.Int(wo, IltInventory.IntNumTimesTinkered) != 0 || inv.Int(wo, IltInventory.IntImbuedEffect) != 0) return false;
return inv.Int(wo, IltInventory.IntCleaving) <= 1;
}
private WorldObject? NextChunkTarget()
{
foreach (var wo in _ctx.Inventory.Items())
{
if (_skip.Contains(wo.Id)) continue;
if ((G.AutoChunkAetheria || _manualPass) && IsChunkableAetheria(wo) == true) return wo;
if ((G.AutoChunkCorrupted || _manualPass) && IsChunkableCorrupted(wo) == true) return wo;
}
return null;
}
/// <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;
_chunkStatus = "manual pass started";
}
private void TickChunk(long now)
{
if (!G.AutoChunkAetheria && !G.AutoChunkCorrupted && !_manualPass) return;
if (_waitingOn != 0)
{
if (now - _waitStartedAt < ChunkResultWaitMs) return;
_skip.Add(_waitingOn); // no result line — don't hammer the same item forever
_waitingOn = 0;
}
if (now - _lastChunkAt < Math.Max(500, G.ChunkIntervalMs)) return;
_lastChunkAt = now;
if (!G.ChunkInCombat && !_ctx.Inventory.InPeaceMode) { _chunkStatus = "waiting for peace mode"; return; }
if (_ctx.Inventory.IsBusy) return;
var hammer = FindHammer();
if (hammer == null) { _chunkStatus = "no Lugian Hammer carried"; _manualPass = false; return; }
var target = NextChunkTarget();
if (target == null)
{
_chunkStatus = _chunked > 0 ? $"nothing left to chunk ({_chunked} this session)" : "nothing eligible";
_manualPass = false;
return;
}
if (_ctx.Inventory.UseOn(hammer, unchecked((uint)target.Id)))
{
_waitingOn = target.Id;
_waitStartedAt = now;
_chunkStatus = "chunking " + target.Name;
}
}
// ── Clap ────────────────────────────────────────────────────────────────
private bool HasClapMaterials()
{
var inv = _ctx.Inventory;
foreach (var wo in inv.Items())
{
uint w = inv.Wcid(wo);
if ((w == IltInventory.WcidRedAetheriaChunk || w == IltInventory.WcidBlueAetheriaChunk)
&& inv.Int(wo, IltInventory.IntItemMaxLevel) <= 3)
return true;
string n = wo.Name;
if (n.Equals("Red Aetheria Chunk", StringComparison.OrdinalIgnoreCase) || n.Equals("Blue Aetheria Chunk", StringComparison.OrdinalIgnoreCase)
|| n.Equals("Ancient Empyrean Trinket", StringComparison.OrdinalIgnoreCase) || n.Equals("Ancient Falatacot Trinket", StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
/// <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 materials carried"; 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);
}
public bool OnChat(string text)
{
if (_waitingOn == 0) return false;
if (text.StartsWith("You're too busy", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You are too busy", StringComparison.OrdinalIgnoreCase))
{
_waitingOn = 0; // retry the same item next interval
return false;
}
if (ChunkDoneLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase)))
{
_chunked++;
_waitingOn = 0;
}
else if (ChunkRefusedLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase)))
{
_skip.Add(_waitingOn);
_waitingOn = 0;
}
return false;
}
public void OnLogout()
{
_waitingOn = 0;
_skip.Clear();
_manualPass = false;
_clapWasEnabled = false;
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
ImGui.TextColored(IltStyle.ColTeal, "Chunking (Lugian Hammer)");
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 = Math.Clamp(under, 1, 6);
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");
ImGui.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();
ImGui.TextDisabled(_clapStatus);
}
}

View file

@ -0,0 +1,264 @@
// 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;
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)
{
ImGui.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"));
}
}
ImGui.TextDisabled("Status: " + _status);
foreach (string l in _preview) ImGui.BulletText(l);
}
}

View file

@ -0,0 +1,254 @@
// 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;
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();
ImGui.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) ImGui.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) ImGui.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) ImGui.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))
{
ImGui.TextColored(IltStyle.ColAmber, _fellowshipHand ? "Fellowship Blackjack" : "Blackjack");
RenderHandButtons("hud");
}
ImGui.End();
if (!open) _ctx.State.GamesHudVisible = false;
}
}

View file

@ -0,0 +1,69 @@
// 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).
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; }
private readonly IltHubContext _ctx;
public IltGear(IltHubContext ctx)
{
Keepers = new IltBuffKeepers(ctx);
ChunkClap = new IltChunkClap(ctx);
Split = new IltSplitArrows(ctx);
Suits = new IltEquipSuits(ctx);
_ctx = ctx;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
Keepers.Tick(nowMs);
ChunkClap.Tick(nowMs);
Split.Tick(nowMs);
Suits.Tick(nowMs);
}
public bool OnChat(string text)
{
bool eat = Keepers.OnChat(text);
eat |= ChunkClap.OnChat(text);
eat |= Split.OnChat(text);
eat |= Suits.OnChat(text);
return eat;
}
public void OnLogout()
{
Keepers.OnLogout();
ChunkClap.OnLogout();
Split.OnLogout();
Suits.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("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,570 @@
// 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.
//
// 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;
}
}
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);
ImGui.TextDisabled(IltGuardianPhrasebook.MessageOf(line));
ImGui.PopTextWrapPos();
}
string answer = _lastAnswer, npc = _lastNpc;
if (answer.Length > 0)
{
ImGui.TextColored(IltStyle.ColTeal, answer);
ImGui.SameLine();
ImGui.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.");
ImGui.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;
ImGui.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;
ImGui.TextColored(col, r.Status);
if (ImGui.IsItemHovered())
ImGui.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();
ImGui.TextColored(IltStyle.ColTeal, answer);
if (ImGui.IsItemHovered()) ImGui.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,587 @@
// 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
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; }
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; }
/// <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);
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);
_features.AddRange(new IIltFeature[] { Banking, PetLogs, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, Guardian });
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");
}
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. Character always can (it explains why the ILT tabs are
/// idle and holds the Force-ILT override); the rest need server features.
/// </summary>
public bool SectionAvailable(IltSection section) => section switch
{
IltSection.Character => true,
IltSection.Banking => Available && !_ctx.Options.IsOff(IltFeature.Bank),
IltSection.Games => Available && Games.AnyGameAvailable,
_ => Available,
};
/// <summary>
/// The Mini Remote offers the Infinite Leaftide tabs: an ILT-like world (or the Force-ILT
/// override). The Character tab then always shows; the others 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: the Guardian panel's body (RynthPluginRenderEmbed "guardian").</summary>
public void RenderGuardianPanel() => _ui.RenderGuardianPanel();
/// <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();
// "Mini Remote on screen" gates bank auto-refresh and the gear / split-arrow scans.
_ctx.State.WindowVisible = _ctx.Ai.MiniRemoteVisible;
// 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>Pump-thread chat line. Returns true when the line should be hidden.</summary>
public bool OnChat(string text)
{
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;
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 => LogCat.IltPets,
IltSessionRates => LogCat.IltRates,
IltQuestBonus => LogCat.IltQuests,
IltProgression => LogCat.IltProgression,
IltGear or IltCharms => LogCat.IltGear,
IltGames => LogCat.IltGames,
_ => 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); 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 character|quests|pets|banking|gear|charms|games|guardian|bounties [show|hide|toggle]");
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.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;
case "status": PrintStatus(); break;
case "force":
_ctx.State.ForceLeaftideFeatures = !rest.Equals("off", StringComparison.OrdinalIgnoreCase);
_ctx.Chat($"[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|force on|off|servers [list]|clap|confirm|cancel");
_ctx.Chat("[Mini Remote] /ra hub open character|quests|pets|banking|gear|charms|games [show|hide|toggle] (Mini Remote tabs)");
_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|check <regex>|window [show|hide]|favhud [show|hide]] /ra pets [show|hide]");
_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 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.IsTab(section))
{
OpenEnginePanel(IltSections.TabId(section), IltSections.Label(section), mode);
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 / 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,247 @@
// 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>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>Cached result of the server-options check (see IltServerOptions).</summary>
public sealed class IltServerOptionsSnapshot
{
public string WorldName = string.Empty;
/// <summary>"ilt-features" (structured dump), "probe" (command probing) 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>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();
// The Pets tab's own settings (roster, healing / cosmetic pets, refill path) are RynthAi's
// (its miniremote.json); older ilt-hub.json files still carry them, and they are ignored here.
}
// ── 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 always chunks).</summary>
public int ChunkAetheriaUnderLevel = 4;
// 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;
}
// ── 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,475 @@
// 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.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.Games ??= new IltGamesState();
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;
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.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,369 @@
// 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): Character (world status, Force-ILT, server names,
// profiles, session rates), Banking, Gear, Charms and Games. A tab is offered only while the
// server reports its feature on. RenderSection draws the ILT pieces inside RynthAi's own
// surfaces (the Remote tab, the Quests and Pets tabs, 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);
private readonly IltHubController _hub;
private readonly IltHubContext _ctx;
private IltConfirmRequest? _confirm;
private bool _confirmOpened;
private string _profileName = string.Empty;
private bool _profileShared;
private string[] _profileList = Array.Empty<string>();
private int _profileIdx;
private string? _serverNamesEdit;
// 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.Character: RenderCharacterBody(); break;
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;
}
}
/// <summary>
/// One of the ILT pieces RynthAi draws in its own surfaces (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 RynthIltHub.SectionRemoteBank:
if (!o.IsIltLikeWorld || o.IsOff(IltFeature.Bank)) return false;
RenderRemoteBank();
return true;
case RynthIltHub.SectionRemoteGuardian:
if (!o.IsIltLikeWorld) return false;
_hub.Guardian.RenderRemoteLine();
return true;
case RynthIltHub.SectionQuestBonus:
if (!o.IsIltLikeWorld) return false;
_hub.QuestBonus.RenderSection();
return true;
case RynthIltHub.SectionPetLogs:
if (!o.IsIltLikeWorld) return false;
_hub.PetLogs.RenderSection();
return true;
case RynthIltHub.SectionIltStatus:
return RenderIltStatus();
case RynthIltHub.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>Character tab: world / options header, then session rates (or why the ILT tabs are idle).</summary>
private void RenderCharacterBody()
{
RenderHeader();
ImGui.Separator();
if (!_hub.Available) { RenderUnavailable(); return; }
if (ImGui.CollapsingHeader("Session rates", ImGuiTreeNodeFlags.DefaultOpen)) _hub.Rates.Render();
ImGui.Spacing();
ImGui.TextDisabled("XP planner, Augmentations and Enlightenment are on the Skills panel's Progression tab");
ImGui.TextDisabled("(right-click the dashboard's Char button > Progression).");
}
private void RenderHeader()
{
var o = _ctx.Options;
string world = o.WorldName.Length > 0 ? o.WorldName : "unknown world";
ImGui.TextColored(o.IsIltLikeWorld ? IltStyle.ColTeal : IltStyle.ColTextMute, world);
ImGui.SameLine();
ImGui.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));
bool force = _ctx.State.ForceLeaftideFeatures;
if (ImGui.Checkbox("Treat this world as ILT", ref force)) _hub.ForceIltWorld = force;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("World-identity override only: the Mini Remote asks the server which ILT features exist.\nIt never turns a feature on by itself.");
ImGui.SameLine();
if (ImGui.SmallButton("Servers...")) { _serverNamesEdit = null; ImGui.OpenPopup("##iltservers"); }
ImGui.SameLine();
if (ImGui.SmallButton("Profiles...")) { ImGui.OpenPopup("##iltprofiles"); _ctx.Post(() => _profileList = _ctx.Store.ListProfiles().ToArray()); }
RenderServersPopup();
RenderProfilesPopup();
}
/// <summary>
/// The world names that count as Infinite Leaftide (RynthAi's Settings > Misc "Server Features"
/// list before the move; one list for every character now).
/// </summary>
private void RenderServersPopup()
{
if (!ImGui.BeginPopup("##iltservers")) return;
ImGui.TextColored(IltStyle.ColTeal, "Infinite Leaftide world names");
ImGui.TextDisabled(ServerFeatureGate.Describe(_ctx.Options.WorldName, _ctx.Settings, _ctx.State.ForceLeaftideFeatures));
string text = _serverNamesEdit ?? ServerFeatureGate.FormatList(ServerFeatureGate.Patterns(_ctx.Settings));
ImGui.SetNextItemWidth(320);
bool enter = ImGui.InputTextWithHint("##iltservernames", "InfiniteLeaftide, *Leaftide*", ref text, 512, ImGuiInputTextFlags.EnterReturnsTrue);
_serverNamesEdit = text;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Comma-separated world names that turn on the ILT tabs, the Guardian, the Progression\n" +
"planners and the attribute raiser. * is a wildcard (*Leaftide* matches any\n" +
"name containing Leaftide). Case does not matter. Also: /ra hub servers <list>.");
ImGui.SameLine();
if (ImGui.SmallButton("Save") || enter)
{
var list = ServerFeatureGate.ParseList(_serverNamesEdit);
if (list.Count > 0)
_ctx.Post(() => { _ctx.Settings.ServerNames = list; _ctx.SaveSettings(); });
_serverNamesEdit = null;
}
ImGui.SameLine();
if (ImGui.SmallButton("Default"))
{
_ctx.Post(() => { _ctx.Settings.ServerNames = new(ServerFeatureGate.DefaultServerNames); _ctx.SaveSettings(); });
_serverNamesEdit = null;
}
ImGui.EndPopup();
}
private void RenderProfilesPopup()
{
if (!ImGui.BeginPopup("##iltprofiles")) return;
ImGui.TextColored(IltStyle.ColTeal, "ILT profiles (settings only; no balances)");
ImGui.SetNextItemWidth(180);
ImGui.InputTextWithHint("##profname", "profile name", ref _profileName, 64u);
ImGui.SameLine();
ImGui.Checkbox("shared", ref _profileShared);
ImGui.SameLine();
if (ImGui.SmallButton("Save"))
{
string n = _profileName; bool sh = _profileShared;
_ctx.Post(() =>
{
_ctx.Chat(_ctx.Store.SaveProfile(_ctx.State, n, sh, out string err) ? $"[Mini Remote] Saved profile '{n}'." : "[Mini Remote] Save failed: " + err);
_profileList = _ctx.Store.ListProfiles().ToArray();
});
}
var list = _profileList;
if (list.Length > 0)
{
_profileIdx = Math.Clamp(_profileIdx, 0, list.Length - 1);
ImGui.SetNextItemWidth(180);
ImGui.Combo("##proflist", ref _profileIdx, list, list.Length);
ImGui.SameLine();
if (ImGui.SmallButton("Load"))
{
string n = list[_profileIdx];
_ctx.Confirm("Load ILT profile", $"Replace the current ILT settings with profile '{n}'?",
() => _ctx.Chat(_ctx.Store.LoadProfile(_ctx.State, n, out string err) ? $"[Mini Remote] Loaded profile '{n}'." : "[Mini Remote] Load failed: " + err),
"Load");
}
}
else ImGui.TextDisabled("No saved profiles.");
ImGui.EndPopup();
}
private void RenderUnavailable()
{
var o = _ctx.Options;
if (!o.IsIltLikeWorld)
{
ImGui.TextWrapped("This is not an Infinite Leaftide / ACECustom world, so the ILT tabs are idle. "
+ "If this shard runs ACECustom under another name, tick 'Treat this world as ILT' and press Refresh.");
}
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 Bank section ────────────────
private void RenderRemoteBank()
{
var b = _ctx.State.Bank;
if (b.LastUpdated == DateTime.MinValue) { ImGui.TextDisabled("Bank: not loaded (Options > Banking)"); return; }
Stat("P:", Compact(b.Pyreals));
Stat("Lum:", Compact(b.Luminance));
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();
}
private static void Stat(string label, string value)
{
ImGui.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, this character's
/// "Treat this world as ILT" override and a server-features refresh. False when features are on.
/// </summary>
private bool RenderIltStatus()
{
if (_hub.Available) return false;
var o = _ctx.Options;
ImGui.TextDisabled(!o.IsIltLikeWorld ? "Not an ILT world."
: o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue ? "Checking server features..."
: "No ILT features reported.");
bool force = _hub.ForceIltWorld;
if (ImGui.Checkbox("Treat this world as ILT##mrforce", ref force)) _hub.ForceIltWorld = force;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("World-identity override only: RynthILT asks the server which features exist.\nIt never turns a feature on by itself.");
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, 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("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))
{
ImGui.TextColored(IltStyle.ColAmber, _confirm.Title);
ImGui.Separator();
ImGui.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,319 @@
// 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 };
public const uint WcidRedAetheriaChunk = 42636;
public const uint WcidBlueAetheriaChunk = 42635;
// ── 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;
public const uint IntItemMaxLevel = 319;
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;
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>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,193 @@
// 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>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),
};
}
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,249 @@
// 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 two Server Features fields of a RynthAi profile (the rest of the file is ignored).</summary>
public sealed class IltLegacyProfileFlags
{
public List<string>? FeatureServerNames;
public bool ForceServerFeatures;
}
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, "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>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,110 @@
// 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".</summary>
public static readonly Regex AugLine = new(@"^(\w+):\s*([\d,]+)$", 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);
/// <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,85 @@
// 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, the refill charm path) stayed in RynthAi (MiniRemote/PetsTab.cs): summoning is every
// server's, these two commands are ACECustom's.
using System;
using System.Collections.Generic;
using ImGuiNET;
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) ImGui.BulletText(s);
ImGui.TreePop();
}
}
}

View file

@ -0,0 +1,776 @@
// 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;
// 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) || _ctx.Capture.IsPending("/aug")) return;
_augStatus = "loading...";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/aug",
IsResponseLine = t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase) || IltParse.AugLine.IsMatch(t),
IdleEndMs = 2000,
FirstLineTimeoutMs = 15000,
Eat = true,
OnComplete = r =>
{
if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Aug, IltTri.Off); _augStatus = "/aug not available"; return; }
ApplyAugLines(r.Lines);
},
});
}
/// <summary>Parses "/aug" output (also fed from the login probe).</summary>
public void ApplyAugLines(List<string> lines)
{
RynthLog.Trace(LogCat.IltProgression, $"ApplyAugLines(lines={lines.Count})");
int n = 0;
foreach (string l in lines)
{
var m = IltParse.AugLine.Match(l.Trim());
if (!m.Success) continue;
string key = m.Groups[1].Value.ToLowerInvariant();
if (key == "specialize") key = "specialization";
lock (_augLevels) _augLevels[key] = (int)IltParse.ParseLeadingLong(m.Groups[2].Value);
n++;
}
_augStatus = n > 0 ? $"{n} aug types @ {DateTime.Now:t}" : "no aug lines in reply";
}
/// <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);
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;
_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,202 @@
// 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;
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>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;
ImGui.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) ImGui.TextColored(color, s);
ImGui.TreePop();
}
}
}

View file

@ -0,0 +1,111 @@
// 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.
//
// Character, Banking, Gear, Charms and Games are Mini Remote tabs: RynthAi's MiniRemoteHud draws
// the tab bar (after its Remote, Quests and Pets tabs) and asks RynthILT for each tab's body
// (RynthILT.Hub GetTabs / RenderTab); "/ra hub open <section>" picks one. 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 Quests and Pets tabs are RynthAi's
// (every server: /myquests and summoning essences aren't ILT's).
using System;
using System.Numerics;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>ILT sections: the Mini Remote's ILT tabs, then the Guardian panel.</summary>
internal enum IltSection
{
Character,
Banking,
Gear,
Games,
/// <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.Character, IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games,
};
/// <summary>The Mini Remote's own tab (the remote itself): its tab id.</summary>
public const string RemoteTab = "";
public static string Label(IltSection s) => s switch
{
IltSection.Character => "Character",
IltSection.Banking => "Banking",
IltSection.Gear => "Gear",
IltSection.Games => "Games",
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.Charms => "charms",
IltSection.Guardian => "guardian",
_ => s.ToString().ToLowerInvariant(),
};
/// <summary>True for the sections drawn as Mini Remote tabs (all but the Guardian panel).</summary>
public static bool IsTab(IltSection s) => s != IltSection.Guardian;
/// <summary>"quests" / "pets" (and their aliases): RynthAi's universal tabs, not ILT sections.</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 "charms": case "charm": section = IltSection.Charms; return true;
case "guardian": case "temple": case "riddle": section = IltSection.Guardian; return true;
default: section = IltSection.Character; 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.Character => new Vector2(520, 440),
IltSection.Banking => new Vector2(560, 520),
IltSection.Gear => new Vector2(560, 520),
IltSection.Charms => new Vector2(560, 520),
IltSection.Games => new Vector2(520, 440),
_ => 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,409 @@
// 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.
// * Preferred source: a structured "/ilt features" dump (ILTFEATURE key=0|1 lines) once
// ACECustom ships it. Today the server prints "Coming Soon", so:
// * Fallback: a one-shot login probe 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", ...).
// 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.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>
/// True when the world is (or is declared to be) an ACECustom/ILT shard: its name is in the
/// server list (IltSettings), or this character's override is on (ServerFeatureGate).
/// </summary>
public bool IsIltLikeWorld
{
get
{
if (_state.ForceLeaftideFeatures) return true;
IltSettings? s;
try { s = _settings(); } catch { s = null; }
return ServerFeatureGate.IsEnabled(WorldName, s, _state.ForceLeaftideFeatures);
}
}
/// <summary>True while a refresh (dump or 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".
if (string.IsNullOrEmpty(WorldName) && 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 dump-then-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("[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...");
// Step 1: structured dump. Lines start with "=== ILT Custom Features ===".
_capture.Enqueue(new IltChatRequest
{
Command = "/ilt features",
IsResponseLine = t => t.StartsWith("ILTFEATURE", StringComparison.OrdinalIgnoreCase)
|| t.Contains("ILT Custom Features", StringComparison.OrdinalIgnoreCase)
|| t.Equals("Coming Soon", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 1200,
FirstLineTimeoutMs = 8000,
Eat = true,
OnComplete = r => OnFeatureDump(r, manual),
});
}
private void OnFeatureDump(IltChatResult r, bool manual)
{
var fromDump = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string line in r.Lines)
{
if (!line.StartsWith("ILTFEATURE", StringComparison.OrdinalIgnoreCase)) continue;
foreach (var kv in ParseFeatureLine(line))
{
Set(kv.Key, kv.Value);
fromDump.Add(kv.Key);
}
}
_state.ServerOptions.Source = fromDump.Count > 0 ? "ilt-features" : "probe";
RynthLog.Trace(LogCat.IltOptions, $"feature dump: {fromDump.Count} key(s) (timedOut={r.TimedOut}, unknown={r.UnknownCommand}) → source={_state.ServerOptions.Source}");
RunProbes(fromDump, manual);
}
/// <summary>
/// Parses "ILTFEATURE bank=1 powerball=0 charms=infinitecasting:1,guardianhand:0".
/// ServerConfig-style names ("powerball_enabled") are mapped onto Hub keys.
/// </summary>
internal static IEnumerable<KeyValuePair<string, IltTri>> ParseFeatureLine(string line)
{
string body = line.Substring("ILTFEATURE".Length).Trim();
foreach (string token in body.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
int eq = token.IndexOf('=');
if (eq <= 0) continue;
string key = token.Substring(0, eq).Trim();
string val = token.Substring(eq + 1).Trim();
if (key.Equals("charms", StringComparison.OrdinalIgnoreCase))
{
foreach (string pair in val.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
int c = pair.IndexOf(':');
if (c <= 0) continue;
yield return new(IltFeature.Charm(pair.Substring(0, c)), ParseTri(pair.Substring(c + 1)));
}
continue;
}
yield return new(MapServerKey(key), ParseTri(val));
}
}
private static IltTri ParseTri(string v)
{
v = v.Trim().ToLowerInvariant();
return v is "1" or "on" or "true" or "yes" ? IltTri.On
: v is "0" or "off" or "false" or "no" ? IltTri.Off
: IltTri.Unknown;
}
private static string MapServerKey(string key)
{
string k = key.Trim().ToLowerInvariant();
return k switch
{
"powerball_enabled" => IltFeature.Powerball,
"quest_info_enabled" => IltFeature.Quests,
"pet_device_pyreal_auto_refill_enabled" => IltFeature.PetRefill,
"pet_charm_universal_summoning_mastery_enabled" => IltFeature.UniversalMastery,
"pet_bond_enabled" => IltFeature.PetBond,
"pet_potency_enabled" => IltFeature.PetPotency,
_ => k.EndsWith("_enabled", StringComparison.Ordinal) ? k.Substring(0, k.Length - "_enabled".Length) : k,
};
}
// ── 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(HashSet<string> alreadyKnown, bool manual)
{
var todo = Probes.Where(p => !alreadyKnown.Contains(p.Key)).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 unless the
// dump said otherwise.
if (!alreadyKnown.Contains(IltFeature.Enl))
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,
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 and flips the matching bit Off.
/// 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);
}
/// <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,264 @@
// IltSessionRates.cs — Session earnings / per-hour rates for the ILT Hub Character tab.
// 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>();
private sealed record RateRow(string Label, string Total, string PerHour);
/// <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)
{
// 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();
}
/// <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)));
rows.Add(new RateRow("Luminance", IltParse.Compact(s.Lum), IltParse.Compact(s.LumPerHour)));
// 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)));
if (s.PassUpTracked != 0)
rows.Add(new RateRow(PassUpLabel, IltParse.Compact(s.LumPassUp), IltParse.Compact(s.PassUpPerHour)));
rows.Add(new RateRow("Kills", s.Kills.ToString(), s.KillsPerHour.ToString("0")));
}
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) ──────────────────────────────────────────────────
public void Render()
{
// 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;
ImGui.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)
{
ImGui.TableNextRow();
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Label);
if (ReferenceEquals(r.Label, PassUpLabel) && ImGui.IsItemHovered()) ImGui.SetTooltip(PassUpTooltip);
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Total);
ImGui.TableNextColumn(); ImGui.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,92 @@
// 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 from the Character tab and "/ilt servers <list>".
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))]
[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,205 @@
// 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;
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;
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 (_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;
ImGui.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"));
ImGui.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,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,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,254 @@
// 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;
public RynthAiClient(RynthCoreHost host) => _host = host;
/// <summary>Forget the table; the next call looks it up again (login, logout, RynthAi reload).</summary>
public void Reset()
{
_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
{
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 >= (uint)sizeof(RynthAiHubApiV1)) _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;
}
}
// ── 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,103 @@
// 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" or the Character tab
// edits them — they were RynthAi's Settings > Misc "Server Features" list), or
// * this character's override is on (the Character tab's "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>The gate itself: the character's override, or the world name in the list.</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)";
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,197 @@
// HubInterface.cs - RynthILT's side of the "RynthILT.Hub" interface (Plugins/Shared/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 RynthIltHubApiV1* _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)
{
if (iface != RynthIltHubApiV1.InterfaceName || version < 1 || version > RynthIltHubApiV1.InterfaceVersion || _released)
return IntPtr.Zero;
if (_table == null)
{
var t = (RynthIltHubApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthIltHubApiV1));
t->StructSize = (uint)sizeof(RynthIltHubApiV1);
t->IsIltWorld = &IsIltWorld;
t->GetFeature = &GetFeature;
t->GetRates = &GetRates;
t->GetForceIlt = &GetForceIlt;
t->SetForceIlt = &SetForceIlt;
t->GetTabs = &GetTabs;
t->RenderTab = &RenderTab;
t->RenderSection = &RenderSection;
t->Command = &Command;
t->Version = RynthIltHubApiV1.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(IltTabV1* 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];
IltTabV1* 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 |= RynthIltHub.TabShown;
if (hub.SectionAvailable(s)) flags |= RynthIltHub.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>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

@ -9,13 +9,38 @@ namespace RynthCore.Plugin.RynthILT;
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<RynthILTPlugin> Runtime = new();
internal static readonly RynthPluginRuntime<RynthILTPlugin> Runtime = new();
// Typed interface for RynthAi (host GetPluginInterface, API v68): "RynthILT.Hub" v1, the ILT
// tabs and sections its Mini Remote hosts (Plugins/Shared/RynthIltHubApi.cs, HubInterface.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) ?? "";
return HubInterface.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() => Runtime.Shutdown();
public static void Shutdown()
{
// An exception escaping an UnmanagedCallersOnly export fail-fasts the client under NativeAOT.
try { Runtime.Shutdown(); } catch { }
try { HubInterface.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) })
if (p != IntPtr.Zero) Marshal.FreeCoTaskMem(p);
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => RynthILTPlugin.NamePointer;
@ -37,6 +62,45 @@ public static unsafe class PluginExports
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); ":popout" is added when it is popped out into a window of
/// its own, and RynthILT draws in the engine's current context either way. The panel is
/// user-sized: want echoes the size given. 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];
if (!name.SequenceEqual("guardian"u8)) return 0;
var plugin = Runtime.Plugin;
if (plugin == null || !plugin.RenderEmbeddedGuardian()) return 0;
if (wantWidth != null) *wantWidth = width;
if (wantHeight != null) *wantHeight = height;
return 1;
}
catch
{
return 0;
}
}
// "/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)
@ -79,6 +143,86 @@ public static unsafe class PluginExports
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;
string value = valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty;
if (action.Length == 0 || action.Length + value.Length > 512) return;
Runtime.Plugin?.EnqueueRemoteCommand(action, value);
}
catch { }
}
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"); the engine's
/// IltInfo adds it to its own detection. 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.IsIltLikeWorld ? "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 Utf8Swap(ref IntPtr slot, string json)
{
IntPtr newPtr = Marshal.StringToCoTaskMemUTF8(json);

View file

@ -1,10 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
RynthILT: features for Infinite Leaftide (ILT), the ACECustom server. The engine shows its
panels (the bar's ILT button, /rc bounties) only on ILT (RynthCore Compatibility/IltInfo.cs).
First feature: the Bounties window's tracker (Bounty/, ported from SilentKelpie's
rynth/RynthSuite PR #11). ILT features live here, not in RynthAi or the engine core.
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. 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/RynthIltHubApi.cs, RynthAiHubApi.cs).
-->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
@ -22,16 +28,61 @@
<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: chat
commands, world and object names are behind HasInvokeChatParser / HasGetWorldName /
HasGetObjectName. -->
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, ...) is behind
its Has* check, as it was in RynthAi. -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Infinite Leaftide (ACECustom) features: the Bounties window.</RynthPluginDescription>
<RynthPluginDescription>Infinite Leaftide (ACECustom) features: the ILT Hub (the Mini Remote's ILT tabs: banking, gear, charms, games), the Guardian, bounties, progression and the attribute raiser.</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). -->
<Compile Include="..\Shared\RynthIltHubApi.cs" Link="Shared\RynthIltHubApi.cs" />
<Compile Include="..\Shared\RynthAiHubApi.cs" Link="Shared\RynthAiHubApi.cs" />
<!-- ImGui.NET bound to the engine's cimgui (the tabs draw inside RynthAi's Mini Remote). -->
<Compile Include="..\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<!-- Install-folder resolver (the ILT Hub files left in the RynthAi folder). -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- One logged, guarded way to use an object (the Guardian's vendor). -->
<Compile Include="..\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="..\Shared\DataWriteGuard.cs" Link="Shared\DataWriteGuard.cs" />
<!-- AcObjectClass (the item classes the gear tools check). -->
<Compile Include="..\..\Shared\RynthCore.LootSdk\AcGameEnums.cs" Link="Shared\AcGameEnums.cs" />
</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

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