Snapshot for release 2026.10.20.1 (internal 7116fab)

This commit is contained in:
Tom Bohar 2026-10-20 21:28:18 -04:00
commit bfcd48950d
215 changed files with 16200 additions and 2838 deletions

View file

@ -1,8 +1,20 @@
// Moved here from RynthOracle (Data/AelrynthBoards.cs) on 2026-10-20: Aelrynth-only features live in RynthAelrynth.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using RynthCore.Plugin.ServerPack;
namespace RynthCore.Plugin.RynthOracle.Data;
namespace RynthCore.Plugin.RynthAelrynth;
/// <summary>A row of a leaderboard.</summary>
internal sealed class BoardRow
{
public int Rank;
public string Name = "";
public string Value = "";
public string Extra = "";
public bool IsYou;
}
/// <summary>A board in Aelrynth's /top overview.</summary>
internal sealed class AelrynthBoardSummary
@ -26,7 +38,7 @@ internal sealed class TrialDungeon
}
/// <summary>
/// Aelrynth's leaderboards (tag Aelrynth), read from the replies of the server's own commands
/// Aelrynth's leaderboards, read from the replies of the server's own commands
/// (ACEPublic Mods: Aeshnidae.Leaderboard /top, Aeshnidae.Trials /trial; one Broadcast line
/// each, numbers with thousands separators). Formats (Commands.cs):
/// /top "Leaderboards - N characters, refreshed X. /top &lt;board&gt; ..."
@ -38,8 +50,8 @@ internal sealed class TrialDungeon
/// /trial &lt;dungeon&gt; "Dungeon (LLLL) - top 10, best per character, any tier:"
/// then " r. m:ss Name (tier T, K kills, d MMM)" and " records per tier/you/this week" lines
/// Entry lines only count right after their header (within a few seconds), so ordinary chat
/// can't add rows. The two commands share /top with ConquestAC's very different reply, which is
/// why each parser only runs on its own server.
/// can't add rows. Conquest answers /top in a very different shape (RynthConquest's parser), which is
/// why each server plugin reads only its own server's replies.
/// </summary>
internal sealed class AelrynthBoards
{
@ -81,7 +93,7 @@ internal sealed class AelrynthBoards
private Block _block;
private long _blockMs;
private readonly ChatRequest _topReq = new(), _trialReq = new();
private readonly ServerChatRequest _topReq = new(), _trialReq = new();
public void Clear()
{
@ -110,7 +122,7 @@ internal sealed class AelrynthBoards
private void Start(Block b, long now) { _block = b; _blockMs = now; }
/// <summary>A chat line: true when it was a leaderboard reply; <paramref name="ours"/> = it answers RynthOracle's request.</summary>
/// <summary>A chat line: true when it was a leaderboard reply; <paramref name="ours"/> = it answers RynthAelrynth's request.</summary>
public bool OnChatLine(string text, long now, out bool ours)
{
ours = false;
@ -255,7 +267,7 @@ internal sealed class AelrynthBoards
return false;
}
private bool Mine(ChatRequest req, long now, out bool ours)
private bool Mine(ServerChatRequest req, long now, out bool ours)
{
ours = req.Awaiting(now);
req.Extend(now);

View file

@ -0,0 +1,106 @@
// AelrynthFeature.cs - What RynthAelrynth does on Aelrynth, without the host (AelrynthPlugin.cs wires it
// to the engine, AelrynthPages.cs draws it). Moved out of RynthOracle on 2026-10-20 so that only players
// who installed RynthAelrynth carry Aelrynth's features:
// * reads the replies of Aelrynth's own commands (AelrynthBoards: /top, /top me, /trial) and hides
// the replies to its own requests when HideOwnReplies is on;
// * reads the account vault (VaultFeed: /mule-data, moved here from RynthInventory, which asked every
// server for it) a few seconds after login and every ten minutes, and hands it to RynthInventory
// through the generic storage feed (Plugins/Shared/StorageFeed.cs), so it shows in Global Inventory.
// Settings: rynthaelrynth.json (ServerPackSettings); "hide own replies" is taken over once from
// rynthoracle.json (it was RynthOracle's hideOwnQuestReplies).
// Threads: everything here runs under Gate (chat and tick from the pump, the pages on the render thread).
// Pure: RynthServerPack.Tests covers it.
using System;
using RynthCore.Plugin.ServerPack;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAelrynth;
internal sealed class AelrynthFeature
{
public const string SettingHideOwnReplies = "hideOwnReplies";
/// <summary>Set once rynthoracle.json's setting was taken over (it's never read again).</summary>
public const string MigrationMarker = "migratedFromRynthOracle";
/// <summary>RynthAelrynth's pages (AelrynthPages draws them): id, label, tooltip.</summary>
public static readonly (string Id, string Label, string Tooltip)[] PageList =
{
("boards", "Leaderboards", "Aelrynth's /top leaderboards and /trial dungeon records (RynthAelrynth)."),
};
/// <summary>Held for everything below (pump and render thread).</summary>
public readonly object Gate = new();
public readonly AelrynthBoards Boards = new();
/// <summary>Hide the replies to RynthAelrynth's own requests (a command typed by hand always shows).</summary>
public bool HideOwnReplies = true;
/// <summary>Sends a chat command as if typed (the vault's /mule-data); the plugin sets it (AelrynthPlugin).</summary>
public Func<string, bool> SendCommand = _ => false;
/// <summary>The account vault reader.</summary>
public readonly VaultFeed Vault;
private long _nextVaultAskMs;
/// <summary>What happened to the last vault read on its way to RynthInventory ("" before one).</summary>
public string VaultHandOff = string.Empty;
public AelrynthFeature() => Vault = new VaultFeed(cmd => SendCommand(cmd));
/// <summary>Takes over RynthOracle's reply-hiding choice once (default: hidden, as it was there).</summary>
public static bool Migrate(ServerPackSettings settings, string oraclePath) => settings.MigrateOnce(MigrationMarker, s =>
{
if (ServerPackSettings.ReadBoolFrom(oraclePath, "hideOwnQuestReplies") is bool hide) s.SetBool(SettingHideOwnReplies, hide);
});
public void LoadSettings(ServerPackSettings s) => HideOwnReplies = s.GetBool(SettingHideOwnReplies, true);
public void SaveSettings(ServerPackSettings s)
{
if (s.SetBool(SettingHideOwnReplies, HideOwnReplies)) s.Save();
}
/// <summary>Login and logout: the boards and the vault are read fresh.</summary>
public void Reset()
{
Boards.Clear();
Vault.Reset();
_nextVaultAskMs = 0;
VaultHandOff = string.Empty;
}
/// <summary>
/// An incoming chat line on Aelrynth: true when it should be hidden. The vault's data lines (and
/// the unknown-command reply to our own probe) always are; a leaderboard reply to our own request
/// is when HideOwnReplies is on.
/// </summary>
public bool OnChatLine(string text, int chatType, long nowMs)
{
if (Vault.ShouldEat(text, chatType)) return true;
return Boards.OnChatLine(text.TrimEnd('\r', '\n'), nowMs, out bool ours) && ours && HideOwnReplies;
}
/// <summary>
/// The vault's timing (plugin tick, on Aelrynth): the first read <see cref="VaultFeed.FirstAskMs"/>
/// after login, then every <see cref="VaultFeed.RefreshMs"/> unless the server has no vault.
/// Returns the record to hand to RynthInventory when a read just finished, else null.
/// </summary>
public StorageFeedRecord? VaultTick(long nowMs, string account)
{
if (_nextVaultAskMs == 0) _nextVaultAskMs = nowMs + VaultFeed.FirstAskMs;
else if (nowMs >= _nextVaultAskMs && Vault.Status != VaultFeed.State.Unsupported)
{
_nextVaultAskMs = nowMs + VaultFeed.RefreshMs;
Vault.Ask(nowMs);
}
Vault.Tick(nowMs, account);
return Vault.TakeChanged() ? Vault.Record : null;
}
/// <summary>"/rserver vault": a read now (even on a server that said it has none); the next timed one in ten minutes.</summary>
public bool VaultAskNow(long nowMs)
{
_nextVaultAskMs = nowMs + VaultFeed.RefreshMs;
return Vault.Ask(nowMs, force: true);
}
}

View file

@ -0,0 +1,252 @@
// RynthOracle's Leaderboards tab, Aelrynth's half (Views/BoardsTab.cs), moved here on 2026-10-20 and
// redrawn with ImGui as RynthAelrynth's Leaderboards page: a sub-tab of the Mini Remote's Server
// section while on Aelrynth, and a tab of the /rserver window.
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.ServerPack;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAelrynth;
/// <summary>
/// Aelrynth's /top boards (every board's leader, one board's top 10, your own standings) and the
/// /trial dungeon records. Render thread: draws holding the feature's lock, and queues what it sends.
/// </summary>
internal sealed class AelrynthPages
{
private static readonly Vector4 Gold = new(1.00f, 0.84f, 0.30f, 1f);
private static readonly Vector4 Red = new(0.95f, 0.45f, 0.40f, 1f);
private static readonly Vector4 Selected = new(0.26f, 0.45f, 0.70f, 1f);
private readonly AelrynthFeature _f;
private readonly Func<bool> _active;
private readonly Action<Action> _runOnTick;
private readonly Func<string, bool> _send;
private readonly Action<string> _print;
private readonly Action _saveSettings;
private readonly ServerRefreshRow _refresh = new();
private int _view; // 0 boards, 1 me, 2 trials
private string _boardArg = "";
private string _trialArg = "";
public AelrynthPages(AelrynthFeature feature, Func<bool> active, Action<Action> runOnTick, Func<string, bool> send,
Action<string> print, Action saveSettings)
{
_f = feature;
_active = active;
_runOnTick = runOnTick;
_send = send;
_print = print;
_saveSettings = saveSettings;
}
public ServerPage[] Pages()
{
var list = AelrynthFeature.PageList;
return new[] { new ServerPage(list[0].Id, list[0].Label, list[0].Tooltip, DrawBoards) };
}
/// <summary>Logout: the next character's status lines start empty.</summary>
public void Reset() => _refresh.Reset();
private void DrawBoards()
{
if (!_active())
{
SafeImGui.TextWrapped("This page is for Aelrynth. RynthCore doesn't see this world as Aelrynth "
+ "(check RynthCore Options > Diagnostics, or /rserver info).");
return;
}
lock (_f.Gate)
{
AelrynthBoards a = _f.Boards;
if (Toggle("Boards##ab_v0", _view == 0)) _view = 0;
ImGui.SameLine();
if (Toggle("Me##ab_v1", _view == 1)) _view = 1;
ImGui.SameLine();
if (Toggle("Trials##ab_v2", _view == 2)) _view = 2;
_refresh.Draw("ab" + _view, BoardsHelp(), RefreshBoards);
ImGui.Separator();
if (a.LastError.Length > 0) SafeImGui.TextColored(Red, a.LastError);
if (_view == 1) DrawMe(a);
else if (_view == 2) DrawTrials(a);
else DrawOverview(a);
ImGui.Spacing();
bool hide = _f.HideOwnReplies;
if (ImGui.Checkbox("Hide the replies to RynthAelrynth's own requests##ab_hide", ref hide))
{
_f.HideOwnReplies = hide;
_runOnTick(_saveSettings);
}
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("/top and /trial when RynthAelrynth sends them. A command you type yourself always shows its reply.");
}
}
private void DrawMe(AelrynthBoards a)
{
if (ImGui.BeginChild("##ab_me", new Vector2(0f, 300f), ImGuiChildFlags.Borders))
{
foreach (AelrynthStanding s in a.Standings)
{
SafeImGui.Text(Cut(s.Title, 34));
ImGui.SameLine(260f);
SafeImGui.Text(s.Rank > 0 ? $"#{s.Rank} of {s.Of}" : "-");
if (s.Value.Length > 0) { ImGui.SameLine(380f); SafeImGui.Text(s.Value); }
}
if (a.Standings.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh.");
}
ImGui.EndChild();
}
private void DrawTrials(AelrynthBoards a)
{
ImGui.SetNextItemWidth(220f);
ImGui.InputText("Dungeon##ab_trialarg", ref _trialArg, 48);
ImGui.SameLine();
if (ImGui.SmallButton("Top 10##ab_trialtop") && _trialArg.Trim().Length > 0) Ask(a, isTrial: true, _trialArg);
if (ImGui.BeginChild("##ab_trials", new Vector2(0f, 300f), ImGuiChildFlags.Borders))
{
int i = 0;
foreach (TrialDungeon d in a.Trials)
{
TrialDungeon row = d;
if (ImGui.Selectable($"{d.Name} ({d.Landblock})##ab_t{i++}"))
{
_trialArg = row.Name;
Ask(a, isTrial: true, row.Name);
}
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("Click for this dungeon's top 10.");
ImGui.TextDisabled(" record:"); ImGui.SameLine(90f); SafeImGui.TextWrapped(d.Record);
ImGui.TextDisabled(" you:"); ImGui.SameLine(90f); SafeImGui.Text(d.You);
ImGui.TextDisabled(" this week:"); ImGui.SameLine(90f); SafeImGui.Text(d.Week);
}
foreach (string line in a.TrialLines) if (!line.StartsWith("Trials - ", StringComparison.Ordinal)) SafeImGui.TextWrapped(line);
if (a.TrialBoardTitle.Length > 0)
{
ImGui.SeparatorText(a.TrialBoardTitle);
foreach (BoardRow r in a.TrialRows)
{
SafeImGui.Text($"{r.Rank,2}. {r.Value}");
ImGui.SameLine(90f);
SafeImGui.Text(Cut(r.Name, 28));
ImGui.SameLine(300f);
SafeImGui.TextDisabled(Cut(r.Extra, 40));
}
foreach (string n in a.TrialNotes) SafeImGui.TextWrapped(n);
}
if (a.Trials.Count == 0 && a.TrialBoardTitle.Length == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh.");
}
ImGui.EndChild();
}
private void DrawOverview(AelrynthBoards a)
{
if (ImGui.SmallButton("All boards##ab_all")) Ask(a, isTrial: false, "");
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("Sends /top: every board's leader.");
ImGui.SameLine();
ImGui.SetNextItemWidth(160f);
ImGui.InputText("Board##ab_arg", ref _boardArg, 32);
ImGui.SameLine();
if (ImGui.SmallButton("Top 10##ab_board") && _boardArg.Trim().Length > 0) Ask(a, isTrial: false, _boardArg);
if (a.OverviewNote.Length > 0) SafeImGui.TextDisabled(a.OverviewNote);
if (a.BoardTitle.Length > 0)
{
ImGui.SeparatorText($"{a.BoardTitle} ({a.BoardNote})");
if (a.BoardYou.Length > 0) SafeImGui.TextColored(Gold, a.BoardYou);
if (ImGui.BeginChild("##ab_rows", new Vector2(0f, 300f), ImGuiChildFlags.Borders))
{
ImGui.TextDisabled("Rank"); ImGui.SameLine(60f); ImGui.TextDisabled("Name"); ImGui.SameLine(280f); ImGui.TextDisabled("Value");
foreach (BoardRow r in a.BoardRows)
{
SafeImGui.Text(r.Rank.ToString());
ImGui.SameLine(60f);
if (r.IsYou) SafeImGui.TextColored(Gold, Cut(r.Name, 30));
else SafeImGui.Text(Cut(r.Name, 30));
ImGui.SameLine(280f);
SafeImGui.Text(r.Value);
if (r.Extra.Length > 0) { ImGui.SameLine(420f); SafeImGui.TextDisabled(Cut(r.Extra, 40)); }
}
if (a.BoardRows.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh.");
}
ImGui.EndChild();
return;
}
if (ImGui.BeginChild("##ab_overview", new Vector2(0f, 300f), ImGuiChildFlags.Borders))
{
int i = 0;
foreach (AelrynthBoardSummary s in a.Overview)
{
AelrynthBoardSummary row = s;
if (ImGui.Selectable(Cut(s.Title, 30) + "##ab_o" + i++, false, ImGuiSelectableFlags.None, new Vector2(230f, 0f)))
{
_boardArg = row.Key;
Ask(a, isTrial: false, row.Key);
}
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"/top {s.Key}");
ImGui.SameLine(240f);
SafeImGui.Text(Cut(s.Leader, 24));
if (s.Value.Length > 0) { ImGui.SameLine(430f); SafeImGui.Text(s.Value); }
}
if (a.Overview.Count == 0) ImGui.TextDisabled("Nothing read yet. Press All boards.");
}
ImGui.EndChild();
}
// ── Refresh (RynthOracle's RefreshBar, Aelrynth's part) ─────────────
private ServerRefreshResult RefreshBoards()
{
AelrynthBoards a = _f.Boards;
string key = _view switch { 1 => "top me", 2 => "trial", _ => "top " + _boardArg };
if (_refresh.CoolingDown(key, Environment.TickCount64)) return new ServerRefreshResult(ServerRefreshRow.TooSoon);
int before = a.Revision;
string cmd = _view switch
{
1 => Ask(a, isTrial: false, "me"),
2 => Ask(a, isTrial: true, ""),
_ => Ask(a, isTrial: false, a.BoardTitle.Length > 0 ? _boardArg : ""),
};
return new ServerRefreshResult($"Sent {cmd}.", () => a.Revision != before);
}
private string BoardsHelp() => _view switch
{
1 => "Sends /top me and reads the reply.",
2 => "Sends /trial and reads the dungeon list.",
_ => "Sends /top (every board's leader), or asks again for the board that is open.",
};
/// <summary>
/// "/top [arg]" or "/trial [arg]" on the next tick, marked as RynthAelrynth's own (its reply can
/// be hidden); returns the command.
/// </summary>
private string Ask(AelrynthBoards a, bool isTrial, string arg)
{
string cmd = string.IsNullOrWhiteSpace(arg) ? (isTrial ? "/trial" : "/top") : (isTrial ? "/trial " : "/top ") + arg.Trim();
_runOnTick(() =>
{
lock (_f.Gate)
{
if (isTrial) a.RequestTrial(arg, Environment.TickCount64);
else a.RequestTop(arg, Environment.TickCount64);
}
if (!_send(cmd)) _print($"Couldn't send {cmd} (not in the world).");
});
return cmd;
}
private static bool Toggle(string label, bool selected)
{
if (selected) ImGui.PushStyleColor(ImGuiCol.Button, Selected);
bool clicked = ImGui.SmallButton(label);
if (selected) ImGui.PopStyleColor();
return clicked;
}
private static string Cut(string s, int max) => s.Length <= max ? s : s.Substring(0, Math.Max(0, max - 3)) + "...";
}

View file

@ -1,31 +1,34 @@
// Moved here from RynthInventory (Scanning/VaultFeed.cs) on 2026-10-20: RynthInventory asked every server
// for an Aelrynth vault; now only RynthAelrynth asks, on Aelrynth, and hands the vault to RynthInventory
// through the generic storage feed (Plugins/Shared/StorageFeed.cs).
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Text.Json;
using RynthCore.Plugin.RynthInventory.Data;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthInventory.Scanning;
namespace RynthCore.Plugin.RynthAelrynth;
/// <summary>
/// The Aelrynth account vault (the Aeshnidae.Mule mod): item storage the retail client is never
/// shown, so the only way to see inside is to ask. The plugin types /mule-data, exactly as a
/// shown, so the only way to see inside is to ask. RynthAelrynth types /mule-data, exactly as a
/// player could, and the server answers one chat line a page:
///
/// ~ael1 {"t":"mule","ready":true,"page":1,"pages":3,"count":57,"max":1000,"items":[{...}]}
///
/// (the same "~ael1" lines the Aelrynth Companion reads; only lines whose "t" is "mule" are ours).
/// The pages are collected into one StorageRecord and kept with the character's storage, so the
/// vault is searched, shown with icons and merged across characters like any other storage; the
/// newest copy wins, and a vault belongs to the account, so every character sees the same one.
/// The pages are collected into one StorageFeedRecord, which RynthAelrynth sends to RynthInventory
/// (StorageFeed): it is kept with the character's storage, so the vault is searched, shown with
/// icons and merged across characters like any other storage; the newest copy wins, and a vault
/// belongs to the account, so every character sees the same one.
///
/// A server without the command is asked once after login; its "Unknown command" reply is eaten
/// and the plugin stays quiet. A vault the server says is not ready yet is asked again a few
/// times, and is never recorded as empty.
/// A server without the command (Aelrynth without the mod, or a world wrongly taken for Aelrynth)
/// is asked once after login; its "Unknown command" reply is eaten and the feed stays quiet. A
/// vault the server says is not ready yet is asked again a few times, and is never recorded as empty.
///
/// Threads: <see cref="ShouldEat"/> may run on AC's thread (it only queues); everything else runs
/// on the plugin tick.
/// Threads: <see cref="ShouldEat"/> only queues; everything else runs on the plugin tick.
/// Pure: RynthServerPack.Tests covers it.
/// </summary>
internal sealed class VaultFeed
{
@ -33,6 +36,8 @@ internal sealed class VaultFeed
public const string Prefix = "~ael1 ";
public const string Label = "Account vault";
public const string VaultName = "Aelrynth vault";
/// <summary>After login, before the first /mule-data; then every <see cref="RefreshMs"/>.</summary>
public const long FirstAskMs = 8_000, RefreshMs = 10 * 60_000;
public enum State { Idle, Asking, Unsupported, Waiting }
@ -47,17 +52,17 @@ internal sealed class VaultFeed
private volatile bool _expecting;
private int _readyTries;
private long _retryAtMs;
private readonly List<ItemRecord> _pages = new();
private readonly List<StorageFeedItem> _pages = new();
private bool _changed;
public VaultFeed(Func<string, bool> send) => _send = send;
public State Status { get; private set; } = State.Idle;
/// <summary>The vault once a full read finished (null until then).</summary>
public StorageRecord? Record { get; private set; }
public StorageFeedRecord? Record { get; private set; }
public int Max { get; private set; }
/// <summary>For /ginv status.</summary>
/// <summary>For /rserver info.</summary>
public string Describe() => Status switch
{
State.Unsupported => "no vault on this server",
@ -69,12 +74,16 @@ internal sealed class VaultFeed
/// <summary>True once after <see cref="Record"/> was replaced.</summary>
public bool TakeChanged() { bool c = _changed; _changed = false; return c; }
/// <summary>Login and logout: a fresh read (the record from before is forgotten).</summary>
public void Reset()
{
Status = State.Idle;
_expecting = false;
_pages.Clear();
_readyTries = 0;
Record = null;
_changed = false;
Max = 0;
while (_lines.TryDequeue(out _)) { }
}
@ -142,7 +151,7 @@ internal sealed class VaultFeed
if (Status == State.Waiting && nowMs >= _retryAtMs) SendPage(nowMs, 1);
else if (Status == State.Asking && nowMs - _sentAtMs > AnswerWindowMs)
{
// Nothing came back: a server without the mod, or a lost line. The next /ginv vault retries.
// Nothing came back: a server without the mod, or a lost line. The next refresh retries.
_expecting = false;
Status = State.Idle;
_pages.Clear();
@ -190,15 +199,7 @@ internal sealed class VaultFeed
{
Status = State.Waiting; _retryAtMs = nowMs + RetryReadyMs; _pages.Clear(); return;
}
Record = new StorageRecord
{
Id = VaultId(account),
Name = VaultName,
Label = Label,
Cell = 0,
SeenUtc = DateTime.UtcNow,
Items = new List<ItemRecord>(_pages),
};
Record = new StorageFeedRecord(VaultId(account), VaultName, Label, new List<StorageFeedItem>(_pages));
_pages.Clear();
_changed = true;
Status = State.Idle;
@ -210,29 +211,15 @@ internal sealed class VaultFeed
}
}
private static ItemRecord Item(JsonElement e)
{
var it = new ItemRecord
{
Id = UInt(e, "o"),
Wcid = UInt(e, "w"),
Name = Str(e, "n"),
Icon = UInt(e, "i"),
Underlay = UInt(e, "u"),
Overlay = UInt(e, "v"),
Stack = Math.Max(1, Int(e, "s", 1)),
MaxStack = Int(e, "m", 0),
ItemType = UInt(e, "y"),
Place = ItemPlace.Storage,
};
it.Category = ItemCategory.FromItemType(it.ItemType);
return it;
}
private static StorageFeedItem Item(JsonElement e) => new(
UInt(e, "o"), UInt(e, "w"), Str(e, "n"), UInt(e, "i"), UInt(e, "u"), UInt(e, "v"),
Math.Max(1, Int(e, "s", 1)), Int(e, "m", 0), UInt(e, "y"));
/// <summary>
/// A stand-in container id for the account's vault. Storage is merged by (server, id) with the
/// newest copy winning, so the same id on every character of the account shows ONE vault. It is
/// in the top of the id space, where no object the client has seen lives.
/// in the top of the id space, where no object the client has seen lives (StorageFeed.IsStandInId).
/// The same formula as RynthInventory used, so vaults saved before the move are replaced, not doubled.
/// </summary>
public static uint VaultId(string account)
{

View file

@ -0,0 +1,127 @@
// AelrynthPlugin.cs - RynthAelrynth's own features, through the shared server plugin's hooks
// (Plugins/Shared/ServerPack/ServerPackPlugin.cs). Aelrynth-specific code that RynthOracle and
// RynthInventory used to carry lives here since 2026-10-20 (Aelrynth/AelrynthFeature.cs says what),
// so a player without RynthAelrynth gets none of it, and no other server is asked for a vault.
using System;
using System.IO;
using RynthCore.Plugin.RynthAelrynth;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.ServerPack;
public sealed partial class ServerPackPlugin
{
private readonly AelrynthFeature _aelrynth = new();
private AelrynthPages? _aelrynthPages;
// The last vault read, until RynthInventory took it (it may load after the read).
private StorageFeedRecord? _vaultToHandOff;
private long _nextVaultHandOffMs;
private const long VaultHandOffRetryMs = 30_000;
/// <summary>Where RynthOracle kept the reply-hiding choice before it moved here (read once).</summary>
internal static string OracleSettingsPath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthoracle.json");
partial void ServerPages(System.Collections.Generic.List<ServerPage> pages)
{
_aelrynthPages = new AelrynthPages(_aelrynth, () => Active, RunOnTick, Send,
text => ChatLine($"[{RynthPluginInfo.Name}] {text}"), SaveAelrynthSettings);
pages.AddRange(_aelrynthPages.Pages());
}
partial void ServerCommandVerbs(System.Collections.Generic.List<string> verbs) => verbs.Add("vault");
partial void ServerInitialize()
{
_aelrynth.SendCommand = Send;
if (AelrynthFeature.Migrate(Settings, OracleSettingsPath))
LogTagged("Took over RynthOracle's reply-hiding choice from rynthoracle.json.");
lock (_aelrynth.Gate) _aelrynth.LoadSettings(Settings);
}
private void SaveAelrynthSettings()
{
lock (_aelrynth.Gate) _aelrynth.SaveSettings(Settings);
}
partial void ServerLoginComplete()
{
lock (_aelrynth.Gate) _aelrynth.Reset();
_vaultToHandOff = null;
_aelrynthPages?.Reset();
}
partial void ServerLogout()
{
lock (_aelrynth.Gate) _aelrynth.Reset();
_vaultToHandOff = null;
_aelrynthPages?.Reset();
}
partial void ServerShutdown() => SaveAelrynthSettings();
partial void ServerChatText(string text, int chatType, ref bool eat)
{
if (!Active) return;
bool hide;
lock (_aelrynth.Gate) hide = _aelrynth.OnChatLine(text, chatType, Environment.TickCount64);
if (hide) eat = true;
}
partial void ServerTick(bool active)
{
if (!active || !Host.HasInvokeChatParser) return;
long now = Environment.TickCount64;
uint player = Host.HasGetPlayerId ? Host.GetPlayerId() : 0;
if (player == 0) return; // the vault belongs to the account; wait for the character
string account = Host.TryGetAccountName(out string a) && a.Trim().Length > 0 ? a.Trim() : "unknown";
StorageFeedRecord? read;
lock (_aelrynth.Gate) read = _aelrynth.VaultTick(now, account);
if (read != null) { _vaultToHandOff = read; _nextVaultHandOffMs = 0; }
if (_vaultToHandOff != null && now >= _nextVaultHandOffMs) HandOffVault(now);
}
/// <summary>
/// The vault to RynthInventory (StorageFeed), which files it with the character's storage. Kept and
/// offered again now and then while RynthInventory isn't there to take it.
/// </summary>
private void HandOffVault(long now)
{
StorageFeedRecord? vault = _vaultToHandOff;
if (vault == null) return;
bool taken = Host.HasSendPluginCommand
&& Host.SendPluginCommand(StorageFeed.TargetPlugin, StorageFeed.Action, StorageFeed.ToJson(vault));
string note = taken
? $"{vault.Items.Count} item(s) handed to RynthInventory at {DateTime.Now:HH:mm}"
: "RynthInventory isn't loaded (or is too old), so the vault isn't in Global Inventory";
lock (_aelrynth.Gate) _aelrynth.VaultHandOff = note;
if (taken) _vaultToHandOff = null;
else _nextVaultHandOffMs = now + VaultHandOffRetryMs;
}
partial void ServerChatCommand(string[] parts, ref bool handled)
{
if (parts.Length < 2 || !parts[1].Equals("vault", StringComparison.OrdinalIgnoreCase)) return;
handled = true;
string tag = $"[{RynthPluginInfo.Name}] ";
if (!Active) { ChatLine(tag + "The account vault is Aelrynth's; RynthCore doesn't see this world as Aelrynth."); return; }
bool asked;
string state;
lock (_aelrynth.Gate)
{
asked = _aelrynth.VaultAskNow(Environment.TickCount64);
state = _aelrynth.Vault.Describe();
}
ChatLine(tag + (asked ? "Reading the account vault (/mule-data)..." : "The vault is already being read: " + state));
}
partial void ServerInfoLines(Action<string> line)
{
lock (_aelrynth.Gate)
{
string handOff = _aelrynth.VaultHandOff.Length > 0 ? "; " + _aelrynth.VaultHandOff : "";
line("Account vault: " + _aelrynth.Vault.Describe() + handOff + " (/rserver vault reads it now).");
line("Own replies (/top, /trial) " + (_aelrynth.HideOwnReplies ? "hidden" : "shown") + ".");
}
}
}

View file

@ -2,17 +2,26 @@
<!-- RynthAelrynth: the Aelrynth server plugin. "aelrynth" is one of RynthCore's built-in server ids, so the
engine's own Aelrynth detection decides when it is active (the hosts here only pick it at load).
The build is shared (..\Shared\ServerPack\ServerPlugin.props); ServerData.cs holds what is known. -->
The build is shared (..\Shared\ServerPack\ServerPlugin.props); ServerData.cs holds what is known.
Aelrynth's own features (AelrynthPlugin.cs, Aelrynth\) came from RynthOracle and RynthInventory on
2026-10-20: the /top leaderboards and /trial records (a page of the Mini Remote's Server section),
and the account vault (/mule-data), handed to RynthInventory's Global Inventory. -->
<PropertyGroup>
<AssemblyName>RynthCore.Plugin.RynthAelrynth</AssemblyName>
<Version>0.1.0</Version>
<Version>0.2.0</Version>
<RynthPluginServerId>aelrynth</RynthPluginServerId>
<RynthPluginServerName>Aelrynth</RynthPluginServerName>
<RynthPluginServerHosts>aelrynth.com</RynthPluginServerHosts>
<RynthPluginServerWorldNames>Aelrynth*|Aeshnidae*</RynthPluginServerWorldNames>
<RynthPluginDescription>Aelrynth only: the server card (its mods, links, account setup) in the Mini Remote.</RynthPluginDescription>
<RynthPluginDescription>Aelrynth only: the server card (its mods, links, account setup), Aelrynth's leaderboards and Trials records in the Mini Remote, and the account vault in Global Inventory.</RynthPluginDescription>
</PropertyGroup>
<Import Project="..\Shared\ServerPack\ServerPlugin.props" />
<ItemGroup>
<!-- The vault's server lines vs a player's copy of them, and the storage feed RynthInventory reads. -->
<Compile Include="..\Shared\ChatSource.cs" Link="Shared\ChatSource.cs" />
<Compile Include="..\Shared\StorageFeed.cs" Link="Shared\StorageFeed.cs" />
</ItemGroup>
</Project>

View file

@ -16,8 +16,9 @@ internal static class ServerData
{
"Bank mod: Radiance and Luminance banking (RynthCore reads its totals).",
"Skill Mastery mod (RynthCore shows mastery progress).",
"Account vault for mules (RynthCore reads its contents).",
"Account vault for mules (RynthCore reads its contents; RynthAelrynth puts it in Global Inventory, /rserver vault).",
"RynthOracle has an Aelrynth quest pack (quests.aelrynth.csv).",
"RynthAelrynth's Leaderboards page (Server section, or /rserver): the /top boards and /trial dungeon records.",
"The world was named Aeshnidae before; both names count.",
},
Website = "https://aelrynth.com",

View file

@ -1987,10 +1987,15 @@ public partial class BuffManager : IDisposable
// for the wand and back (slow, and the 10-06 stalls began at those switches), so a stamina
// potion listed in Consumables goes before it. A potion drunk under 2.5 s ago: no Revitalize
// on top of it. In Magic stance (a caster) Revitalize stays first.
int sentBefore = _vitalActionsSent;
if (curStamPct < stamThreshold && AttemptStaminaChain())
{
_isRechargingStamina = true;
if (_restamRun) _restamRunCasts++;
// Only a cast, kit or potion actually sent counts toward the run's cap. The chain also
// answers "handled" while it waits for the last cast to finish, and counting those ticks
// ended every run after one Robustification (2.3 s of waiting = the 4-cast cap): Re-stam To
// 90 stopped near 60 (Drakkon, 2026-10-20).
if (_restamRun && _vitalActionsSent != sentBefore) _restamRunCasts++;
return true;
}
@ -2077,11 +2082,21 @@ public partial class BuffManager : IDisposable
private bool _restamRun;
private int _restamRunCasts;
internal const int RestamRunMaxCasts = 4;
// Vital casts, kits and potions actually sent (a wait for the last one isn't one).
private int _vitalActionsSent;
/// <summary>The stamina % to recharge under now (see the fields above).</summary>
internal static int StaminaLine(bool inCombat, int stamPct, LegacyUiSettings s, ref bool run, ref int casts)
{
if (!inCombat) { run = false; return s.TopOffStam; }
if (!inCombat)
{
// A recharge started in the fight finishes to Re-stam To when the fight ends, instead of
// dropping to the top-off line (Top Stam can be lower than Re-stam To).
if (run && s.RestamTo > s.RestamAt && stamPct < s.RestamTo && casts < RestamRunMaxCasts)
return Math.Max(s.RestamTo, s.TopOffStam);
run = false;
return s.TopOffStam;
}
if (s.RestamTo <= s.RestamAt) { run = false; return s.RestamAt; }
if (stamPct < s.RestamAt)
{
@ -2272,6 +2287,7 @@ public partial class BuffManager : IDisposable
return VitalNo($"the client refused the cast (spell {spellId})");
}
sent = true;
_vitalActionsSent++;
_lastVitalCastAt = DateTime.Now;
if (IsRecoveryVital(what)) NoteRecoveryAttempt();
NoteCastIssued(spellId);
@ -2329,6 +2345,7 @@ public partial class BuffManager : IDisposable
_host.Log($"[RynthAi] Vitals: drinking {rule.Name} ({rule.Type})" + (potion.Id != rule.Id ? " from a new stack." : "."));
_host.UseFor(unchecked((uint)potion.Id), "Buff", $"vitals: drink {rule.Name} ({rule.Type}) from the Items list");
_lastPotionAt = DateTime.Now;
_vitalActionsSent++;
_lastCastAttempt = DateTime.Now;
if (IsHealthPotionType(types)) NoteHealSent(rule.Name);
return true;
@ -2345,6 +2362,7 @@ public partial class BuffManager : IDisposable
_host.Log($"[RynthAi] Vitals: using {wo.Name} from the pack ({kind}).");
_host.UseFor(unchecked((uint)wo.Id), "Buff", $"vitals: {kind} potion from the pack");
_lastPotionAt = DateTime.Now;
_vitalActionsSent++;
_lastCastAttempt = DateTime.Now;
if (IsHealthPotionType(types)) NoteHealSent(wo.Name ?? "health potion");
return true;
@ -2528,6 +2546,7 @@ public partial class BuffManager : IDisposable
if (HeldCastBlocksItemUse(out _)) return false;
_host.Log($"[RynthAi] Vitals: using {kit.Name} from the pack.");
_host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: stamina kit on yourself");
_vitalActionsSent++;
_lastCastAttempt = DateTime.Now;
MarkKitUsed(stamina: true);
return true;

View file

@ -1147,6 +1147,7 @@ public partial class CombatManager : IDisposable
_waitingForDebuffResult = false;
_pendingDebuffTargetId = 0;
}
_debuffs.Forget(id);
}
public void SetPlayerId(uint playerId)
{
@ -1181,14 +1182,13 @@ public partial class CombatManager : IDisposable
private uint _playerId;
private MonsterMatchEvaluator? _monsterMatchEval;
private readonly HashSet<string> _confirmedDebuffs = new();
// Failed tries (fizzle/resist/refusal) per "{target}_{debuff}", cleared with _confirmedDebuffs.
private readonly Dictionary<string, int> _debuffFailures = new();
private const int DebuffMaxFailures = 3;
// The rule's debuffs per target: landed ones renewed before they wear off, failed tries counted.
private readonly DebuffTimers _debuffs = new();
private int _lastDebuffTargetId = 0;
private string? _pendingDebuffKey = null;
private int _pendingDebuffTargetId = 0;
private int _pendingDebuffSpellId = 0;
private int _pendingDebuffTier = 0;
private bool _waitingForDebuffResult = false;
private DateTime _pendingDebuffCastTime = DateTime.MinValue;
@ -1749,8 +1749,7 @@ public partial class CombatManager : IDisposable
// "ou cast …". IndexOf matches both "You cast" and "ou cast".
if (text.IndexOf("ou cast ", StringComparison.OrdinalIgnoreCase) >= 0)
{
string key = $"{_pendingDebuffTargetId}_{_pendingDebuffKey}";
_confirmedDebuffs.Add(key);
NoteDebuffLanded();
_waitingForDebuffResult = false;
_lastSpellCast = DateTime.Now;
return;
@ -1780,19 +1779,15 @@ public partial class CombatManager : IDisposable
/// <summary>
/// A debuff didn't land (fizzle, resist, refusal). Recast it, but only up to
/// DebuffMaxFailures times per target: a mob the character's Creature Magic can't land
/// DebuffTimers.MaxFailures times per target: a mob the character's Creature Magic can't land
/// on used to get the same debuff forever, and the bot never reached its attack spells
/// (debuffs don't feed the no-damage blacklist either).
/// </summary>
private void NoteDebuffFailed(string what)
{
string key = $"{_pendingDebuffTargetId}_{_pendingDebuffKey}";
_debuffFailures.TryGetValue(key, out int n);
_debuffFailures[key] = ++n;
if (n >= DebuffMaxFailures)
if (_debuffs.Failed(_pendingDebuffTargetId, _pendingDebuffKey ?? "")) // skip it for this target
{
_confirmedDebuffs.Add(key); // skip it for this target
_host.WriteToChat($"[RynthAi] {what}: {_pendingDebuffKey} — {n} tries on this target, skipping it", 2);
_host.WriteToChat($"[RynthAi] {what}: {_pendingDebuffKey} — {DebuffTimers.MaxFailures} tries on this target, skipping it", 2);
}
else
{
@ -1802,6 +1797,20 @@ public partial class CombatManager : IDisposable
_lastSpellCast = DateTime.Now;
}
/// <summary>
/// The pending debuff landed (or its result never came, taken as landed): timed by the
/// spell's duration so it is cast again just before it wears off; a spell with no duration
/// is cast once per target, as all of them were before 2026-10-20. Archmage's Endurance
/// isn't counted, so with it a renewal comes early rather than late.
/// </summary>
private void NoteDebuffLanded()
{
int seconds = SpellDatabase.DurationSeconds(_pendingDebuffSpellId);
_debuffs.Landed(_pendingDebuffTargetId, _pendingDebuffKey ?? "", seconds, DateTime.Now);
if (seconds > 0)
_host.Log($"[CombatCast] debuff {_pendingDebuffKey} on 0x{(uint)_pendingDebuffTargetId:X8}: lasts {seconds} s, renewed in {seconds - DebuffTimers.Lead(seconds):0} s");
}
// ── Position re-sync after casts that land nothing (2026-10-12) ──────────────────────────
// Flight 63260: after a stray stop burst rode with a cast, every projectile cast (Corruption
// VII, Nether Arc VII) was answered - components burned, UseDone - and nothing landed, until a
@ -1885,104 +1894,80 @@ public partial class CombatManager : IDisposable
/// <summary>Test seam: one judged magic cast with no damage.</summary>
internal void MagicMissForTest(int tid) => NoteMagicMissForResync(tid);
// ── Empyrean Handler lethal-ring evade (chat-triggered back-jump) ─────────
// ACECustom Handler emote: "The handler briefly channels infused Empyrean hatred
// to release a lethal ring." The ring can't be melee-evaded — if the character is
// inside its cast radius they die. On that line, when still in range of a Handler,
// cancel the current swing/cast and back-jump away, then resume combat (target kept).
private const string HandlerRingChannelHint = "channels infused Empyrean hatred to release a lethal ring";
private const string HandlerRingChannelStart = "The handler briefly channels";
private const string HandlerNameHint = "Empyrean Handler";
/// <summary>Yards: Handler lethal ring is treated as at least this wide (RingRange when larger).</summary>
internal const double HandlerRingDangerYards = 12.0;
/// <summary>Back-jump charge (ms) — run-back + jump must clear ~ring radius.</summary>
private const int HandlerRingJumpHoldMs = 750;
private const double HandlerRingEvadeCooldownMs = 4_000;
// ── Back away from a danger point (RynthAi.Hub BackAwayFrom) ──────────────
// A generic "get out of this radius now", asked for by a server plugin that knows its server's
// dangers: face the object, run-back jump away from it (Jumper "xs"; facing away and jumping back
// would leap into it), hold attacks until the jump settles, then re-engage the same target.
// RynthILT asks for it when Infinite Leaftide's Empyrean Handler channels its lethal ring (the
// detection and its setting moved there 2026-10-20; Silentkelpie's PR 12). Only while the macro is
// running with combat on: an idle character, or one driven by hand or by a meta, never has the
// keyboard taken.
private DateTime _handlerRingEvadeAt = DateTime.MinValue;
private DateTime _handlerRingEvadeUntil = DateTime.MinValue;
private int _handlerRingEvadeId;
private bool _handlerRingJumpStarted;
/// <summary>BackAwayFrom results (RynthAi.Hub BackAwayFrom passes them on as they are).</summary>
internal const int BackAwayStarted = 1, BackAwayNotNow = 0, BackAwayOutside = 2, BackAwayUnknownObject = 3, BackAwayJumpRefused = -1;
/// <summary>The jump charge range a caller may ask for (ms).</summary>
internal const int BackAwayMinHoldMs = 100, BackAwayMaxHoldMs = 3000;
/// <summary>After the jump: turn, land and one re-engage tick before attacks resume (ms).</summary>
private const int BackAwaySettleMs = 2_200;
private DateTime _backAwayUntil = DateTime.MinValue;
private bool _backAwayJumpStarted;
/// <summary>
/// Plugin wires this to <c>Jumper.Start("xs", faceHeading, ms)</c> — face the Handler
/// then run-back jump (x+s) so the body moves away. Returns false if the jumper refused.
/// Plugin wires this to <c>Jumper.Start("xs", faceHeading, ms)</c> — face the danger, then
/// run-back jump (x+s) so the body moves away. Returns false if the jumper refused.
/// </summary>
public Func<float, int, bool>? RequestBackJump { get; set; }
/// <summary>True while the wired jumper is mid-turn / charge / settle.</summary>
public Func<bool>? JumpBusy { get; set; }
/// <summary>True while a Handler-ring evade is holding combat (jump or settle).</summary>
public bool RingEvadeActive =>
_handlerRingEvadeUntil != DateTime.MinValue && DateTime.Now < _handlerRingEvadeUntil;
/// <summary>True while a back-away is holding combat (jump or settle).</summary>
public bool BackAwayActive =>
_backAwayUntil != DateTime.MinValue && DateTime.Now < _backAwayUntil;
/// <summary>
/// Chat line from RynthAiPlugin.OnChatWindowText. Starts a back-jump evade when the
/// Handler channels its lethal ring and the character is still inside ring range.
/// Backs the character away from <paramref name="objectId"/> when it is within the danger radius:
/// <paramref name="radiusYards"/>, or Ring Range when that is larger (anything a ring reaches).
/// <paramref name="holdMs"/> is the jump's charge (clamped to 100-3000 ms). Cancels the swing or
/// cast in progress, keeps the target. <paramref name="reason"/> is only for the log. Returns a
/// BackAway* result: started, not now (macro stopped, combat off, already backing away), outside
/// the radius, unknown object (no position), or the jump didn't start. Pump thread.
/// </summary>
public void HandleChatForRingEvade(string? text, int chatType = -1)
public int BackAwayFrom(int objectId, double radiusYards, int holdMs, string reason)
{
if (string.IsNullOrEmpty(text)) return;
// Gate: only while the macro is running with combat on, and only if the setting allows it.
// Otherwise a Handler line heard while the character is idle or being driven by hand (or by a
// meta) would take over the keyboard for a back-jump.
if (!_settings.HandlerRingEvade || !_settings.IsMacroRunning || !_settings.EnableCombat) return;
// Handler channel is an Emote (0x0C). ChatSource.IsPlayerAuthored treats Emote as
// player speech, which would skip every real Handler line — anchor on the unique
// phrase starting the line instead (player copies are "Name says, \"...\").
bool anchored =
RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, HandlerRingChannelStart, StringComparison.OrdinalIgnoreCase)
|| (RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, "The handler", StringComparison.OrdinalIgnoreCase)
&& text.IndexOf(HandlerRingChannelHint, StringComparison.OrdinalIgnoreCase) >= 0);
if (!anchored)
string why = string.IsNullOrWhiteSpace(reason) ? "a server plugin's request" : reason.Trim();
if (!_settings.IsMacroRunning || !_settings.EnableCombat) return BackAwayNotNow;
if (BackAwayActive) return BackAwayNotNow;
uint me = _host.GetPlayerId();
if (me == 0 || objectId == 0) return BackAwayUnknownObject;
double dist = _worldFilter.Distance(unchecked((int)me), objectId);
if (dist < 0 || dist == double.MaxValue || double.IsNaN(dist))
{
// Mid-line only when the type is clearly not player speech (some clients strip "The ").
if (chatType is RynthCore.Plugin.Shared.ChatSource.Speech
or RynthCore.Plugin.Shared.ChatSource.Tell
or RynthCore.Plugin.Shared.ChatSource.OutgoingTell
or RynthCore.Plugin.Shared.ChatSource.Channel
or RynthCore.Plugin.Shared.ChatSource.ChannelSend
or RynthCore.Plugin.Shared.ChatSource.Allegiance
or RynthCore.Plugin.Shared.ChatSource.Fellowship)
return;
if (text.IndexOf(HandlerRingChannelHint, StringComparison.OrdinalIgnoreCase) < 0) return;
if (text.IndexOf(" says,", StringComparison.OrdinalIgnoreCase) >= 0
|| text.IndexOf(" tells you,", StringComparison.OrdinalIgnoreCase) >= 0)
return;
_host.Log($"[CombatEvade] Back away ({why}): 0x{objectId:X8} has no position - no jump.");
return BackAwayUnknownObject;
}
DateTime now = DateTime.Now;
if (_handlerRingEvadeAt != DateTime.MinValue
&& (now - _handlerRingEvadeAt).TotalMilliseconds < HandlerRingEvadeCooldownMs)
return;
if (!TryFindHandlerForRingEvade(out int handlerId, out double dist, out string name))
{
_host.Log("[CombatEvade] Handler lethal-ring channel heard, but no Empyrean Handler is nearby — no jump.");
return;
}
double danger = Math.Max(HandlerRingDangerYards, Math.Max(1, _settings.RingRange));
string name = _worldFilter[objectId]?.Name ?? $"0x{objectId:X8}";
double danger = Math.Max(double.IsNaN(radiusYards) ? 0 : radiusYards, Math.Max(1, _settings.RingRange));
if (dist > danger)
{
_host.Log($"[CombatEvade] Handler lethal-ring channel; '{name}' at {dist:0.0} m (outside {danger:0.#} m) — staying put.");
return;
_host.Log($"[CombatEvade] Back away ({why}): '{name}' at {dist:0.0} m (outside {danger:0.#} m) - staying put.");
return BackAwayOutside;
}
// Face the Handler, then Jumper "xs" (back + run) moves the body away from it.
// Facing away + back-jump would leap into the ring.
float faceHandler = 0f;
if (TryGetHeadingTo(handlerId, out double toHandler, out _))
faceHandler = (float)(toHandler % 360.0);
else if (_host.TryGetPlayerHeading(out float curr))
faceHandler = curr;
// Face the danger, then Jumper "xs" (back + run) moves the body away from it.
float face = 0f;
if (TryGetHeadingTo(objectId, out double toIt, out _))
face = (float)(toIt % 360.0);
else if (PlayerCompass.TryGet(_host, out float curr))
face = curr;
_handlerRingEvadeAt = now;
_handlerRingEvadeId = handlerId;
_handlerRingJumpStarted = false;
int hold = Math.Clamp(holdMs, BackAwayMinHoldMs, BackAwayMaxHoldMs);
_backAwayJumpStarted = false;
// Hold combat long enough for turn + charge + land + one re-engage tick.
_handlerRingEvadeUntil = now.AddMilliseconds(HandlerRingJumpHoldMs + 2_200);
_backAwayUntil = DateTime.Now.AddMilliseconds(hold + BackAwaySettleMs);
// Stop the bound melee/missile attack so the jump isn't eaten by the swing servo.
try
@ -1992,100 +1977,50 @@ public partial class CombatManager : IDisposable
}
catch { }
bool started = RequestBackJump?.Invoke(faceHandler, HandlerRingJumpHoldMs) == true;
if (started)
if (RequestBackJump?.Invoke(face, hold) == true)
{
_handlerRingJumpStarted = true;
_host.Log($"[CombatEvade] Empyrean Handler lethal ring — back-jump away from '{name}' " +
$"at {dist:0.0} m (danger {danger:0.#} m), face {faceHandler:0}° then xs.");
}
else
{
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_host.Log("[CombatEvade] Empyrean Handler lethal ring heard in range, but the back-jump did not start.");
_backAwayJumpStarted = true;
_host.Log($"[CombatEvade] Back away ({why}): back-jump away from '{name}' " +
$"at {dist:0.0} m (danger {danger:0.#} m), face {face:0} then xs.");
return BackAwayStarted;
}
_backAwayUntil = DateTime.MinValue;
_host.Log($"[CombatEvade] Back away ({why}): '{name}' in range, but the back-jump did not start.");
return BackAwayJumpRefused;
}
/// <summary>
/// Holds Think from attacking while the Handler-ring back-jump runs. Keeps the target
/// so combat re-engages as soon as the jumper settles.
/// Holds Think from attacking while a back-away jump runs. Keeps the target so combat
/// re-engages as soon as the jumper settles.
/// </summary>
private bool TickRingEvade()
private bool TickBackAway()
{
if (_handlerRingEvadeUntil == DateTime.MinValue) return false;
if (_backAwayUntil == DateTime.MinValue) return false;
DateTime now = DateTime.Now;
bool jumperBusy = JumpBusy?.Invoke() == true;
// Jump never started / failed: clear early.
if (_handlerRingJumpStarted && !jumperBusy && now >= _handlerRingEvadeUntil)
if (_backAwayJumpStarted && !jumperBusy && now >= _backAwayUntil)
{
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_handlerRingJumpStarted = false;
_host.Log("[CombatEvade] Handler ring evade done — re-engaging.");
_backAwayUntil = DateTime.MinValue;
_backAwayJumpStarted = false;
_host.Log("[CombatEvade] Back away done - re-engaging.");
return false;
}
if (jumperBusy || now < _handlerRingEvadeUntil)
if (jumperBusy || now < _backAwayUntil)
{
LastCombatSkipReason = "handler-ring-evade";
LastCombatSkipReason = "back-away";
_tickWait = CombatLatencyTracker.Wait.Other;
return true;
}
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_handlerRingJumpStarted = false;
_host.Log("[CombatEvade] Handler ring evade done — re-engaging.");
_backAwayUntil = DateTime.MinValue;
_backAwayJumpStarted = false;
_host.Log("[CombatEvade] Back away done - re-engaging.");
return false;
}
/// <summary>Nearest Empyrean Handler (active target preferred when it is one).</summary>
private bool TryFindHandlerForRingEvade(out int handlerId, out double dist, out string name)
{
handlerId = 0; dist = double.MaxValue; name = "";
int me = _host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId();
if (me == 0) return false;
int bestId = 0;
double bestDist = double.MaxValue;
string bestName = "";
void Consider(int id, string? nm)
{
if (id == 0 || string.IsNullOrEmpty(nm)) return;
if (nm.IndexOf(HandlerNameHint, StringComparison.OrdinalIgnoreCase) < 0) return;
double d = _worldFilter.Distance(me, id);
if (d < 0 || d >= bestDist) return;
bestDist = d; bestId = id; bestName = nm;
}
if (activeTargetId != 0)
Consider(activeTargetId, _worldFilter[activeTargetId]?.Name);
foreach (var s in _scannedTargets)
Consider(s.Id, s.Name);
// Landscape fallback when the scan hasn't listed it yet (channel can land mid-approach).
if (bestId == 0)
{
try
{
foreach (WorldObject wo in _worldFilter.GetLandscape())
{
if ((int)wo.ObjectClass != (int)AcObjectClass.Monster) continue;
Consider(wo.Id, wo.Name);
}
}
catch { }
}
if (bestId == 0) return false;
handlerId = bestId; dist = bestDist; name = bestName;
return true;
}
public void ReportDamageOnTarget(int targetId)
{
_magicMissesSinceHit = 0; // something we cast landed: the server's position is fine
@ -3098,9 +3033,9 @@ public partial class CombatManager : IDisposable
return true;
}
// Empyrean Handler lethal-ring back-jump: hold casts/swings until the jump settles,
// then fall through and re-engage the same target.
if (TickRingEvade())
// A back-away (a server plugin's danger, e.g. RynthILT's Empyrean Handler ring): hold
// casts/swings until the jump settles, then fall through and re-engage the same target.
if (TickBackAway())
return true;
double acDistanceLimit = _settings.MonsterRange;
@ -6522,7 +6457,7 @@ public partial class CombatManager : IDisposable
{
if ((DateTime.Now - _pendingDebuffCastTime).TotalMilliseconds > DEBUFF_RESULT_TIMEOUT_MS)
{
_confirmedDebuffs.Add($"{_pendingDebuffTargetId}_{_pendingDebuffKey}");
NoteDebuffLanded();
_waitingForDebuffResult = false;
}
else
@ -6534,8 +6469,7 @@ public partial class CombatManager : IDisposable
if (activeTargetId != _lastDebuffTargetId)
{
_confirmedDebuffs.Clear();
_debuffFailures.Clear();
_debuffs.NewTarget(DateTime.Now);
_lastDebuffTargetId = activeTargetId;
}
@ -6545,10 +6479,11 @@ public partial class CombatManager : IDisposable
if (rule != null)
{
var pendingDebuffs = BuildDebuffList(rule, element);
DateTime now = DateTime.Now;
foreach (var debuffKey in pendingDebuffs)
{
string key = $"{activeTargetId}_{debuffKey}";
if (_confirmedDebuffs.Contains(key)) continue;
if (_debuffs.IsOn(activeTargetId, debuffKey, now)) continue;
bool renewal = _debuffs.RenewAt(activeTargetId, debuffKey) != null;
int spellId = 0;
int castTier = 0;
@ -6571,10 +6506,11 @@ public partial class CombatManager : IDisposable
_lastCastWasRing = false;
_pendingDebuffKey = debuffKey;
_pendingDebuffTargetId = activeTargetId;
_pendingDebuffSpellId = spellId;
_pendingDebuffTier = castTier;
_waitingForDebuffResult = true;
_pendingDebuffCastTime = DateTime.Now;
_host.WriteToChat($"[RynthAi] Casting: {debuffKey} (T{castTier}) on {target.Name}", 5);
_host.WriteToChat($"[RynthAi] {(renewal ? "Renewing" : "Casting")}: {debuffKey} (T{castTier}) on {target.Name}", 5);
}
catch { }
return;
@ -6768,8 +6704,9 @@ public partial class CombatManager : IDisposable
private bool HasPendingDebuffs(MonsterRule rule, string element)
{
if (rule == null) return false;
DateTime now = DateTime.Now;
foreach (var debuffKey in BuildDebuffList(rule, element))
if (!_confirmedDebuffs.Contains($"{activeTargetId}_{debuffKey}")) return true;
if (!_debuffs.IsOn(activeTargetId, debuffKey, now)) return true;
return false;
}

View file

@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Which of a monster rule's debuffs (Imperil, the vulns, Fester, Yield, Broadside, Gravity
/// Well, custom ones) are on which target, and when each is due again. A landed debuff with a
/// known duration is renewed a little before it wears off (2026-10-20: they were cast once
/// per target, so a long fight with a high-HP monster lost them after 4-5 minutes). One with
/// no known duration, or given up on after <see cref="MaxFailures"/> fizzles or resists, is
/// not cast at that target again until the fight moves to another one.
/// Timers live across target switches (a monster fought again keeps them) and go when they
/// fall due or the monster does. CombatManager's thread only; no host calls.
/// </summary>
internal sealed class DebuffTimers
{
public const int MaxFailures = 3;
/// <summary>Renew this long before the end, at most (a fifth of a short debuff's length).</summary>
public const double MaxLeadSeconds = 5.0;
private const int MaxTimers = 256;
private readonly Dictionary<(int Target, string Key), DateTime> _renewAt = new();
private readonly HashSet<(int Target, string Key)> _done = new();
private readonly Dictionary<(int Target, string Key), int> _failures = new();
/// <summary>On the target and not due yet, or not to be cast at it again.</summary>
public bool IsOn(int target, string key, DateTime now) =>
_done.Contains((target, key)) || (_renewAt.TryGetValue((target, key), out DateTime at) && now < at);
/// <summary>When a landed debuff is due again; null when it has no timer.</summary>
public DateTime? RenewAt(int target, string key) =>
_renewAt.TryGetValue((target, key), out DateTime at) ? at : null;
/// <summary>
/// It landed (or no result line came back in time, taken as landed). With a duration it is
/// due again <see cref="Lead"/> before it wears off; without one, never on this target.
/// </summary>
public void Landed(int target, string key, double durationSeconds, DateTime now)
{
_failures.Remove((target, key)); // a renewal gets its own tries
if (durationSeconds <= 0)
{
_done.Add((target, key));
return;
}
if (_renewAt.Count >= MaxTimers && !_renewAt.ContainsKey((target, key))) Prune(now);
_renewAt[(target, key)] = now.AddSeconds(durationSeconds - Lead(durationSeconds));
}
/// <summary>How long before a debuff of this length runs out it is cast again.</summary>
public static double Lead(double durationSeconds) => Math.Min(MaxLeadSeconds, durationSeconds * 0.2);
/// <summary>A fizzle, resist or refusal. True when that was the last try (given up on this target).</summary>
public bool Failed(int target, string key)
{
_failures.TryGetValue((target, key), out int n);
_failures[(target, key)] = ++n;
if (n < MaxFailures) return false;
_done.Add((target, key));
return true;
}
public int Failures(int target, string key) => _failures.TryGetValue((target, key), out int n) ? n : 0;
/// <summary>The fight moved to another target: the once-only and given-up marks start over, timers stay.</summary>
public void NewTarget(DateTime now)
{
_done.Clear();
_failures.Clear();
Prune(now);
}
/// <summary>The monster is gone (dead or out of view): its timers too.</summary>
public void Forget(int target)
{
if (_renewAt.Count == 0) return;
List<(int, string)>? drop = null;
foreach (var k in _renewAt.Keys)
if (k.Target == target) (drop ??= new()).Add(k);
if (drop != null) foreach (var k in drop) _renewAt.Remove(k);
}
public int TimerCount => _renewAt.Count;
private void Prune(DateTime now)
{
if (_renewAt.Count == 0) return;
List<(int, string)>? drop = null;
foreach (var kv in _renewAt)
if (kv.Value <= now) (drop ??= new()).Add(kv.Key);
if (drop != null) foreach (var k in drop) _renewAt.Remove(k);
// Still full of live timers (hundreds of monsters debuffed at once): drop the soonest due.
while (_renewAt.Count >= MaxTimers)
{
(int, string) soonest = default;
DateTime best = DateTime.MaxValue;
foreach (var kv in _renewAt)
if (kv.Value < best) { best = kv.Value; soonest = kv.Key; }
_renewAt.Remove(soonest);
}
}
}

View file

@ -13,6 +13,9 @@ public static class SpellDatabase
// names ("Slithering Flames"), so a wall is found by its category and ranked by its power.
private static readonly Dictionary<int, (int Category, int Power)> _spellMeta = new();
private static readonly Dictionary<int, List<int>> _idsByCategory = new();
// How long an enchantment lasts, in seconds before Archmage's Endurance (column 6): the
// debuff renewal times landed debuffs by it (2026-10-20). Absent or 0: no timer.
private static readonly Dictionary<int, int> _durations = new();
private static bool _loaded = false;
private static readonly Dictionary<int, string> _builtinSpells = new Dictionary<int, string>
@ -45,6 +48,7 @@ public static class SpellDatabase
_spellNames.Clear();
_spellMeta.Clear();
_idsByCategory.Clear();
_durations.Clear();
_loaded = false;
try
@ -76,6 +80,8 @@ public static class SpellDatabase
_idsByCategory[category] = ids = new List<int>();
ids.Add(spellId);
}
if (columns.Length >= 6 && int.TryParse(columns[5].Trim(), out int seconds) && seconds > 0)
_durations[spellId] = seconds;
}
}
@ -137,6 +143,9 @@ public static class SpellDatabase
return false;
}
/// <summary>How long the spell's enchantment lasts in seconds (before Archmage's Endurance), 0 when it has none.</summary>
public static int DurationSeconds(int spellId) => _durations.TryGetValue(spellId, out int s) ? s : 0;
/// <summary>Every spell id of a category (ACE SpellCategory), in data order.</summary>
public static IReadOnlyList<int> IdsInCategory(int category)
=> _idsByCategory.TryGetValue(category, out List<int>? ids) ? ids : Array.Empty<int>();

View file

@ -616,6 +616,19 @@ public class WorldObjectCache
_inventory.Remove(id);
_landscape.Add(id);
}
else if (uid < 0x80000000u)
{
// A static id is a world object (a door, a sign, a lever), never something carried.
// One created before its position was readable - a dungeon's objects arrive while the
// character is still in portal space - was filed as inventory here for good, so the
// door scans (which walk the landscape) never saw the door: "Open Doors" on, a closed
// door in the way, no door use at all (Dargoth Hera, Infested Mine, 2026-10-19). It is
// Unknown landscape, as when its position is known; the scans read the position then.
_creatures.Remove(id);
_inventory.Remove(id);
_landscape.Add(id);
cls = AcObjectClass.Unknown;
}
else
{
_inventory.Add(id);

View file

@ -577,6 +577,8 @@ public sealed partial class RynthAiPlugin
public override void OnVendorClose(uint vendorId)
{
_metaManager?.OnVendorClose(vendorId);
// /mt vendor addbuy / addsell lists belong to the vendor that was open.
ClearMtVendorLists();
var autoVendor = _autoVendor;
if (autoVendor != null)

View file

@ -0,0 +1,272 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Key and mouse input posted to AC's own window, for the Mag-Tools <c>/mt</c> verbs that drive the
/// client directly: <c>send</c>, <c>click</c>, <c>movement</c>, <c>strafe</c>, <c>get xy</c>,
/// <c>client</c>. A port of Mag-Tools' PostMessageTools (Mag-Plugins\Shared\PostMessageTools.cs):
/// the same virtual keys, scan codes (lParam) and click spots, so metas written for Mag-Tools
/// behave the same.
///
/// The window is the one in this process with AC's class ("Turbine Device Class"), found once.
/// PostMessage is safe from any thread. A key held for a time is released from <see cref="Pump"/>
/// (the plugin tick), not from a timer: nothing here may outlive the plugin's Shutdown.
///
/// Nothing in this class decides whether input is allowed. Every caller goes through
/// RynthAiPlugin.KeystrokesAllowed (the setting "Allow metas to send keystrokes", off by
/// default) first; <see cref="PostAttempts"/> counts every post so a test can prove that.
/// </summary>
internal static class GameInput
{
private const uint WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_MOUSEMOVE = 0x0200,
WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202;
private const byte VK_RETURN = 0x0D, VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_PAUSE = 0x13,
VK_SPACE = 0x20, VK_DELETE = 0x2E, VK_F4 = 0x73, VK_F12 = 0x7B;
private const int SW_MINIMIZE = 6, SW_RESTORE = 9;
// A key held longer than this is a mistake (a meta typed 1500000 for 1500).
public const int MaxHoldMs = 10_000;
// The longest line /mt send msg types.
public const int MaxMessageChars = 200;
private static IntPtr _hwnd;
// Pending key releases, run by Pump when due (or at once by Shutdown).
private static readonly System.Collections.Generic.List<(long DueMs, Action Release)> Pending = new();
/// <summary>Every message this class tried to post (counted before the window is looked up).</summary>
public static int PostAttempts { get; private set; }
/// <summary>Tests only: receives (message, wParam, lParam) instead of a window, which then counts as found.</summary>
internal static Action<uint, uint, uint>? TestSink;
/// <summary>AC's game window in this process, or IntPtr.Zero.</summary>
public static IntPtr GameWindow
{
get
{
if (TestSink != null) return (IntPtr)1;
if (_hwnd != IntPtr.Zero && IsWindow(_hwnd)) return _hwnd;
// Every top-level AC window on the desktop, keeping this process's (several clients run).
// FindWindowEx rather than EnumWindows: no callback delegate to marshal under NativeAOT.
uint pid = (uint)Environment.ProcessId;
IntPtr found = IntPtr.Zero, h = IntPtr.Zero;
for (int i = 0; i < 64; i++)
{
h = FindWindowEx(IntPtr.Zero, h, "Turbine Device Class", null);
if (h == IntPtr.Zero) break;
GetWindowThreadProcessId(h, out uint p);
if (p == pid) { found = h; break; }
}
_hwnd = found;
return found;
}
}
public static bool Available => GameWindow != IntPtr.Zero;
// ── Keys (Mag-Tools PostMessageTools) ──────────────────────────────────────
public static void SendEnter() => Key(VK_RETURN, 0x001C0001, 0xC01C0001);
public static void SendPause() => Key(VK_PAUSE, 0x00450001, 0xC0450001);
public static void SendDel() => Key(VK_DELETE, 0x01530001, 0x01530001);
/// <summary>F4: opens / closes the fellowship panel.</summary>
public static void SendF4() => Key(VK_F4, 0x003E0001, 0xC03E0001);
/// <summary>F12: opens / closes the main pack.</summary>
public static void SendF12() => Key(VK_F12, 0x00580001, 0xC0580001);
/// <summary>Ctrl + a letter.</summary>
public static void SendCntrl(char ch)
{
Post(WM_KEYDOWN, VK_CONTROL, 0x001D0001);
Post(WM_KEYDOWN, CharCode(ch), 0x00100001);
Post(WM_KEYUP, CharCode(ch), 0xC0100001);
Post(WM_KEYUP, VK_CONTROL, 0xC01D0001);
}
/// <summary>Types <paramref name="msg"/> key by key (letters, space and "/"; as Mag-Tools).</summary>
public static void SendMsg(string msg)
{
if (msg.Length > MaxMessageChars) msg = msg[..MaxMessageChars];
foreach (char ch in msg)
{
uint lparam = (uint)((ScanCode(ch) << 16) | 1);
Post(WM_KEYDOWN, CharCode(ch), lparam);
Post(WM_KEYUP, CharCode(ch), 0xC0000000 | lparam);
}
}
/// <summary>Space (a jump), held <paramref name="msToHoldDown"/> ms, with the shift / w z x c keys
/// pressed as it is released (Mag-Tools /mt jump).</summary>
public static void SendSpace(int msToHoldDown = 0, bool shift = false, bool w = false, bool z = false, bool x = false, bool c = false)
{
Post(WM_KEYDOWN, VK_SPACE, 0x00390001);
void Release()
{
if (shift) Post(WM_KEYDOWN, VK_SHIFT, 0x002A0001);
if (w) Post(WM_KEYDOWN, CharCode('w'), 0x00110001);
if (z) Post(WM_KEYDOWN, CharCode('z'), 0x002C0001);
if (x) Post(WM_KEYDOWN, CharCode('x'), 0x002D0001);
if (c) Post(WM_KEYDOWN, CharCode('c'), 0x002E0001);
Post(WM_KEYUP, VK_SPACE, 0xC0390001);
if (w) Post(WM_KEYUP, CharCode('w'), 0xC0110001);
if (z) Post(WM_KEYUP, CharCode('z'), 0xC02C0001);
if (x) Post(WM_KEYUP, CharCode('x'), 0xC02D0001);
if (c) Post(WM_KEYUP, CharCode('c'), 0xC02E0001);
if (shift) Post(WM_KEYUP, VK_SHIFT, 0xC02A0001);
}
After(msToHoldDown, Release);
}
/// <summary>A movement key (a letter of AC's keymap) held <paramref name="msToHoldDown"/> ms.</summary>
public static void SendMovement(char ch, int msToHoldDown = 0)
{
uint scan = (uint)ScanCode(ch) * 0x10000;
Post(WM_KEYDOWN, CharCode(ch), 0x00000001 + scan);
After(msToHoldDown, () => Post(WM_KEYUP, CharCode(ch), 0xC0000001 + scan));
}
// ── Mouse ─────────────────────────────────────────────────────────────────
/// <summary>A left click at window coordinates (<paramref name="x"/>, <paramref name="y"/>).</summary>
public static void SendMouseClick(int x, int y)
{
uint loc = (uint)((y << 16) | (x & 0xFFFF));
Post(WM_MOUSEMOVE, 0, loc);
Post(WM_LBUTTONDOWN, 1, loc);
Post(WM_LBUTTONUP, 0, loc);
}
// AC's confirmation box buttons, relative to the window's centre. Three heights each, as Mag-Tools:
// windowed and windowless clients put the box a few pixels apart.
public static void ClickOK() => ClickCentre(0);
public static void ClickYes() => ClickCentre(-80);
public static void ClickNo() => ClickCentre(80);
private static void ClickCentre(int dx)
{
RECT r;
if (TestSink != null) r = new RECT { Right = 800, Bottom = 600 };
else if (!GetWindowRect(GameWindow, out r)) return;
int w = r.Right - r.Left, h = r.Bottom - r.Top;
foreach (int dy in new[] { 18, 25, 31 })
SendMouseClick(w / 2 + dx, h / 2 + dy);
}
/// <summary>The cursor relative to the game window's top-left (Mag-Tools /mt get xy), or false.</summary>
public static bool TryCursorInWindow(out int x, out int y)
{
x = y = 0;
if (!GetCursorPos(out POINT p) || !GetWindowRect(GameWindow, out RECT r)) return false;
x = p.X - r.Left;
y = p.Y - r.Top;
return true;
}
// ── Window ───────────────────────────────────────────────────────────────
public static bool Minimize() => TestSink != null ? Sink(0xFFF0, SW_MINIMIZE) : ShowWindow(GameWindow, SW_MINIMIZE);
public static bool Restore() => TestSink != null ? Sink(0xFFF0, SW_RESTORE) : ShowWindow(GameWindow, SW_RESTORE);
private static bool Sink(uint msg, uint wParam)
{
PostAttempts++;
TestSink!(msg, wParam, 0);
return true;
}
// ── Internals ────────────────────────────────────────────────────────────
private static void Key(byte vk, uint down, uint up)
{
Post(WM_KEYDOWN, vk, down);
Post(WM_KEYUP, vk, up);
}
private static void Post(uint msg, uint wParam, uint lParam)
{
PostAttempts++;
if (TestSink != null) { TestSink(msg, wParam, lParam); return; }
IntPtr h = GameWindow;
if (h != IntPtr.Zero) PostMessage(h, msg, (IntPtr)wParam, (IntPtr)unchecked((int)lParam));
}
/// <summary>Runs <paramref name="action"/> now, or from <see cref="Pump"/> after <paramref name="ms"/>.</summary>
private static void After(int ms, Action action)
{
if (ms <= 0) { action(); return; }
ms = Math.Min(ms, MaxHoldMs);
lock (Pending) Pending.Add((Environment.TickCount64 + ms, action));
}
/// <summary>Releases the keys whose hold time is up. Called every plugin tick.</summary>
public static void Pump()
{
if (Pending.Count == 0) return;
List<Action>? due = null;
long now = Environment.TickCount64;
lock (Pending)
{
for (int i = Pending.Count - 1; i >= 0; i--)
{
if (Pending[i].DueMs > now) continue;
(due ??= new()).Insert(0, Pending[i].Release);
Pending.RemoveAt(i);
}
}
if (due == null) return;
foreach (var release in due)
{
try { release(); }
catch (Exception ex) { Debug.WriteLine("GameInput release failed: " + ex.Message); }
}
}
/// <summary>Plugin shutdown: releases every key still held, then forgets the window.</summary>
public static void Shutdown()
{
List<Action> all;
lock (Pending)
{
all = new List<Action>(Pending.Count);
foreach (var p in Pending) all.Add(p.Release);
Pending.Clear();
}
foreach (var release in all)
{
try { release(); }
catch (Exception ex) { Debug.WriteLine("GameInput release failed: " + ex.Message); }
}
_hwnd = IntPtr.Zero;
}
private static byte ScanCode(char ch) => char.ToLowerInvariant(ch) switch
{
'a' => 0x1E, 'b' => 0x30, 'c' => 0x2E, 'd' => 0x20, 'e' => 0x12, 'f' => 0x21, 'g' => 0x22, 'h' => 0x23,
'i' => 0x17, 'j' => 0x24, 'k' => 0x25, 'l' => 0x26, 'm' => 0x32, 'n' => 0x31, 'o' => 0x18, 'p' => 0x19,
'q' => 0x10, 'r' => 0x13, 's' => 0x1F, 't' => 0x14, 'u' => 0x16, 'v' => 0x2F, 'w' => 0x11, 'x' => 0x2D,
'y' => 0x15, 'z' => 0x2C, '/' => 0x35, ' ' => 0x39,
_ => 0,
};
private static byte CharCode(char ch)
{
char c = char.ToLowerInvariant(ch);
if (c >= 'a' && c <= 'z') return (byte)(0x41 + (c - 'a'));
return c == '/' ? (byte)0xBF : (byte)0x20;
}
[StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; }
[DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string? title);
[DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
[DllImport("user32.dll")] private static extern bool IsWindow(IntPtr hWnd);
[DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
[DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT p);
[DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int cmd);
}

View file

@ -45,6 +45,8 @@ internal static unsafe class HubInterface
t->SessionReset = &SessionReset;
t->SessionStatsMore = &SessionStatsMore;
t->VaultedDungeonsEnabled = &VaultedDungeonsEnabled;
t->BackAwayFrom = &BackAwayFrom;
t->SetPlayerCounter = &SetPlayerCounter;
t->Version = RynthAiHubApiV1.InterfaceVersion;
_table = t;
}
@ -251,7 +253,7 @@ internal static unsafe class HubInterface
catch { return 0; }
}
/// <summary>RynthAi's Vaulted Dungeons setting: RynthILT's keeper runs only while it is on (off by default).</summary>
/// <summary>Obsolete slot: the profile's old Vaulted Dungeons value (RynthILT's own setting since 2026-10-20; an older RynthILT reads this).</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int VaultedDungeonsEnabled()
{
@ -259,6 +261,22 @@ internal static unsafe class HubInterface
catch { return 0; }
}
/// <summary>A server plugin's back-away (RynthILT: the Empyrean Handler's ring); BackAway* results, 0 before login.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int BackAwayFrom(uint objectId, float radiusYards, int holdMs)
{
try { return Plugin?.BackAwayForServer(objectId, radiusYards, holdMs) ?? RynthAiHub.BackAwayNotNow; }
catch { return RynthAiHub.BackAwayNotNow; }
}
/// <summary>A wield counter from the server plugin (T11 "Can Wield"); 0 for an id that is no counter, or after shutdown.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetPlayerCounter(uint propertyId, long value)
{
try { return !_released && T11ItemSupport.SetCounter(propertyId, value) ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void SessionReset()
{

View file

@ -40,11 +40,12 @@ public sealed class HudState
public bool MiniShowPet = true;
public bool MiniShowGems = true;
public bool MiniShowToggles = true;
/// <summary>Obsolete since 2026-10-20 (kept so huds.json loads): the Bank section's switch is RynthILT's (copied once).</summary>
public bool MiniShowBank = true;
public bool MiniShowRebuff = true;
/// <summary>Chat translator row: on/off, receive / send language swap.</summary>
public bool MiniShowTranslate = true;
/// <summary>Temple guardian row: the last riddle answer with a Give button (only while one is recent).</summary>
/// <summary>Obsolete since 2026-10-20 (kept so huds.json loads): the Guardian line's switch is RynthILT's (copied once).</summary>
public bool MiniShowGuardian = true;
/// <summary>Gem grid slots, row-major from the top-left (empty Name = unassigned).</summary>
public List<HudItemEntry> MiniRemoteSlots = new();

View file

@ -1,13 +1,11 @@
// MiniRemoteHud.cs — The Mini Remote (UtilityBelt-style) for RynthAi. Render thread only.
//
// One window with tabs: Remote (the sections below), the universal tabs Pets and Crafting (every
// world, MiniRemote/; the Quests tab moved to RynthOracle 2026-10-13), and on Infinite Leaftide
// the RynthILT plugin's ILT tabs (Banking, Gear, Charms, Games; its Character tab moved to
// RynthOracle's Character tab 2026-10-13: RynthILT.Hub GetTabs / RenderTab through IltClient; an ILT tab
// shows once the server reports its feature on, and never without RynthILT). The tab bar's
// selection is saved (HudState.MiniRemoteTab) and "/ra hub open <section>" or RynthCore's
// dashboard switch it (RequestTab). The Guardian and Bounties are RynthILT's RynthCore ILT
// panels (the bar's ILT button).
// world, MiniRemote/; the Quests tab moved to RynthOracle 2026-10-13), then whatever tabs the active
// server plugin offers (its hub: GetTabs / RenderTab through ServerHubClient; RynthILT's Banking, Gear,
// Charms, Games and Vaulted Dungeons on Infinite Leaftide). Nothing server-specific is drawn here
// without one. The tab bar's selection is saved (HudState.MiniRemoteTab) and "/ra hub open
// <section>" or RynthCore's dashboard switch it (RequestTab).
// Right-click on the remote: "Character" (Spells, Pets, Crafting, RynthOracle's Character, Quests,
// Quest Timers and Fellowship, Skills, Inventory, Item Count, Inventory HUDs: windows every server
// has), then "Server: <name>", i.e. the installed server plugins' windows for the world you're on,
@ -18,19 +16,20 @@
// The V/H button stacks the sections (vertical) or lays them out in three columns (horizontal).
//
// Remote sections (each can be hidden from the Options menu):
// Stats session time and per-hour XP / luminance / kills, plus coins / pyreals (RynthILT's rates on ILT)
// Stats session time and per-hour XP / luminance / kills, then the server plugin's own rate lines
// (section "remote-stats": RynthILT's coins / pyreals per hour)
// Target the creature combat is attacking: name, health bar, distance
// Pet the summon that is out (health bar, time left), else the next combat essence and
// whether it is ready
// Pet the summon that is out (health bar, time left), else (while a server plugin is active)
// the next combat essence and whether it is ready
// Slots 5 × 6 quick-use item grid; click uses the item (an empty slot takes the selected
// pack item), right-click assigns / clears, and items dragged from the game's
// inventory or the RynthCore Inventory window drop straight into a slot. Ctrl+wheel
// over the grid (or Options > Slot size) grows / shrinks the boxes.
// Toggles macro and subsystem switches (same as the dashboard buttons; not in the drawer)
// Bank ILT bank balances (pyreals, luminance, keys, coins; drawn by RynthILT)
// Rebuff force rebuff / cancel rebuff
// Translate chat translator on/off and the receive <-> send language swap
// Guardian the last Temple guardian answer with a Give button (only while it is recent; RynthILT)
// + the server plugin's Remote sections around them (RynthILT: Bank, Guardian answer; their
// switches are its own, drawn in the Options popup through section "remote-options")
// All game actions are posted to the pump thread.
//
// RenderEmbedded draws the same sections and Options menu inside the engine's RynthAi dashboard
@ -85,11 +84,14 @@ internal sealed class MiniRemoteHud
private bool _openOptions;
// The header's Options button was right-clicked this frame: its popup opens, not the remote's menu.
private bool _headerRightClick;
/// <summary>One tab after Remote: a universal one (drawn here) or RynthILT's.</summary>
private readonly record struct TabEntry(string Id, string Label, Vector2 Size, bool Ilt);
/// <summary>One tab after Remote: a universal one (drawn here) or the server plugin's.</summary>
private readonly record struct TabEntry(string Id, string Label, Vector2 Size, bool FromServer);
// The tabs offered this frame (reused, so a frame doesn't allocate).
private readonly List<TabEntry> _tabs = new();
// The server plugin drew one of its Remote sections (Bank, Guardian) in the last frame: the
// horizontal layout keeps their column for it.
private bool _serverEconomyDrawn;
public MiniRemoteHud(HudController hud) => _hud = hud;
@ -127,7 +129,7 @@ internal sealed class MiniRemoteHud
RenderBody(s, _hud.Remote(), allowTabs: true);
// Right-click on the remote opens the Character / server menu, unless a slot's own menu is
// open (the ILT tabs have their own right-click menus).
// open (a server plugin's tabs have their own right-click menus).
if (_onRemoteTab && _slotMenuIndex < 0 && !_headerRightClick && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right))
ImGui.OpenPopup(MenuPopup);
RenderOptions(s, embedded: false);
@ -175,8 +177,8 @@ internal sealed class MiniRemoteHud
// ── Tabs ────────────────────────────────────────────────────────────────
/// <summary>
/// The tab bar (when <paramref name="allowTabs"/>: the universal tabs on every world, RynthILT's
/// tabs on Infinite Leaftide) and the selected tab: the remote, or a tab's body in a child of its
/// The tab bar (when <paramref name="allowTabs"/>: the universal tabs on every world, then the
/// server plugin's tabs on its server) and the selected tab: the remote, or a tab's body in a child of its
/// fixed size. Returns the width the content wants (never narrower than the tab bar's labels).
/// </summary>
private float RenderBody(HudState s, MiniRemoteController? remote, bool allowTabs)
@ -187,9 +189,9 @@ internal sealed class MiniRemoteHud
if (allowTabs && remote != null)
{
foreach (string id in MiniRemoteTabs.Universal)
_tabs.Add(new TabEntry(id, MiniRemoteTabs.Label(id), MiniRemoteTabs.Size(id), Ilt: false));
foreach (IltTabInfo t in remote.Ilt.Tabs())
if (t.Shown) _tabs.Add(new TabEntry(t.Id, t.Label, new Vector2(t.Width, t.Height), Ilt: true));
_tabs.Add(new TabEntry(id, MiniRemoteTabs.Label(id), MiniRemoteTabs.Size(id), FromServer: false));
foreach (ServerTabInfo t in remote.ServerHub.Tabs())
if (t.Shown) _tabs.Add(new TabEntry(t.Id, t.Label, new Vector2(t.Width, t.Height), FromServer: true));
}
if (_tabs.Count == 0)
{
@ -221,8 +223,8 @@ internal sealed class MiniRemoteHud
s.MiniRemoteTab = tab.Id;
// The tab draws into a child of its own size; tables in it scroll inside it.
ImGui.BeginChild(TabBodyId(tab.Id), tab.Size, ImGuiChildFlags.None, ImGuiWindowFlags.None);
bool drawn = tab.Ilt ? remote!.Ilt.RenderTab(tab.Id) : remote!.RenderTab(tab.Id);
if (!drawn) SafeImGui.TextDisabled(tab.Ilt ? "RynthILT isn't drawing this tab (not loaded, or not ready yet)." : "Not ready.");
bool drawn = tab.FromServer ? remote!.ServerHub.RenderTab(tab.Id) : remote!.RenderTab(tab.Id);
if (!drawn) SafeImGui.TextDisabled(tab.FromServer ? "The server plugin isn't drawing this tab (not loaded, or not ready yet)." : "Not ready.");
ImGui.EndChild();
width = Math.Max(width, tab.Size.X);
ImGui.EndTabItem();
@ -233,7 +235,7 @@ internal sealed class MiniRemoteHud
}
// Tab labels as NUL-terminated UTF-8 and the tab body child ids, built once per tab so the tab
// bar doesn't allocate per frame (RynthILT's tabs arrive by id at run time).
// bar doesn't allocate per frame (a server plugin's tabs arrive by id at run time).
private static readonly byte[] RemoteTabLabel = Utf8Z("Remote##mrtab");
private readonly Dictionary<string, byte[]> _tabLabels = new(StringComparer.Ordinal);
private readonly Dictionary<string, string> _tabBodyIds = new(StringComparer.Ordinal);
@ -308,7 +310,7 @@ internal sealed class MiniRemoteHud
int cols = 0;
if (s.MiniShowStats || s.MiniShowTarget || s.MiniShowPet) cols++;
if (s.MiniShowGems || ShowToggles(s)) cols++;
if (s.MiniShowBank || s.MiniShowRebuff || s.MiniShowTranslate || s.MiniShowGuardian) cols++;
if (s.MiniShowRebuff || s.MiniShowTranslate || _serverEconomyDrawn) cols++;
cols = Math.Max(1, cols);
return cols * colW + (cols - 1) * ImGui.GetStyle().ItemSpacing.X;
}
@ -394,7 +396,7 @@ internal sealed class MiniRemoteHud
RenderActionSections(s);
ImGui.EndChild();
}
if (s.MiniShowBank || s.MiniShowRebuff || s.MiniShowTranslate || s.MiniShowGuardian)
if (s.MiniShowRebuff || s.MiniShowTranslate || _serverEconomyDrawn)
{
BeginColumn("##mrcoleconomy", colW);
RenderEconomySections(s, remote);
@ -449,17 +451,19 @@ internal sealed class MiniRemoteHud
private void RenderEconomySections(HudState s, MiniRemoteController? remote)
{
// Bank and Guardian are RynthILT's (nothing is drawn off ILT or without it).
if (s.MiniShowBank) remote?.Ilt.RenderSection(RynthIltHub.SectionRemoteBank);
// The server plugin's Remote sections (RynthILT: Bank, Guardian answer) decide themselves whether
// they show (their switches are the plugin's); nothing is drawn without one.
bool drawn = remote?.ServerHub.RenderSection(RynthIltHub.SectionRemoteBank) == true;
if (s.MiniShowRebuff) RenderRebuff();
if (s.MiniShowTranslate && _hud.Translate is { } translate) translate.RenderHubSection();
if (s.MiniShowGuardian) remote?.Ilt.RenderSection(RynthIltHub.SectionRemoteGuardian);
drawn |= remote?.ServerHub.RenderSection(RynthIltHub.SectionRemoteGuardian) == true;
_serverEconomyDrawn = drawn;
}
// ── Sections ────────────────────────────────────────────────────────────
/// <summary>An Infinite Leaftide world, as RynthILT sees it (false without RynthILT).</summary>
private static bool IltActive(MiniRemoteController? remote) => remote != null && remote.Ilt.IsIltWorld;
/// <summary>A server plugin is active for this world (RynthILT on Infinite Leaftide); false without one.</summary>
private static bool ServerActive(MiniRemoteController? remote) => remote != null && remote.ServerHub.ServerActive;
private static void Stat(string label, string value)
{
@ -470,7 +474,7 @@ internal sealed class MiniRemoteHud
/// <summary>
/// Session stats on every world: the shared SessionStats (RynthTracker's code, so these match the
/// Tracker panel), plus ILT coins and pyreals (RynthILT's rates).
/// Tracker panel), plus the server plugin's own rate lines (RynthILT's coins and pyreals).
/// </summary>
private void RenderStats(MiniRemoteController? remote)
{
@ -486,9 +490,7 @@ internal sealed class MiniRemoteHud
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"{v.LumPassUp:N0} this session.\n{PassUpTooltip}");
}
Stat("Kills:", HudDraw.Compact(v.KillsPerHour) + "/h");
if (remote == null || !remote.Ilt.TryGetRates(out double coins, out double pyreals)) return;
Stat("Coins:", HudDraw.Compact(coins) + "/h");
Stat("Pyr:", HudDraw.Compact(pyreals) + "/h");
remote?.ServerHub.RenderSection(RynthIltHub.SectionRemoteStats);
}
/// <summary>
@ -561,7 +563,7 @@ internal sealed class MiniRemoteHud
HealthBar("##mrtargethp", c.TargetHealth);
}
/// <summary>The live summon when one is out, else the Pets tab's next-essence line (ILT worlds).</summary>
/// <summary>The live summon when one is out, else (with a server plugin active) the Pets tab's next-essence line.</summary>
private static void RenderPet(MiniRemoteController? remote, CombatHudSnapshot c)
{
if (c.PetId != 0)
@ -569,7 +571,7 @@ internal sealed class MiniRemoteHud
RenderSummon(remote, c);
return;
}
if (!IltActive(remote)) { ImGui.TextDisabled("Summon: none"); return; }
if (!ServerActive(remote)) { ImGui.TextDisabled("Summon: none"); return; }
string name = remote!.Pets.HudPetName;
string status = remote.Pets.HudPetStatus;
if (name.Length == 0) { ImGui.TextDisabled("No combat pet set"); return; }
@ -583,7 +585,7 @@ internal sealed class MiniRemoteHud
ImGui.TextColored(ColLabel, "Summon:");
ImGui.SameLine();
ImGui.TextUnformatted(c.PetName);
if (IltActive(remote) && remote!.Pets.HudPetStatus == "Healing")
if (ServerActive(remote) && remote!.Pets.HudPetStatus == "Healing")
{
ImGui.SameLine();
ImGui.TextColored(ColBusy, "Healing");
@ -641,13 +643,9 @@ internal sealed class MiniRemoteHud
{
float w = (ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) * 0.5f;
w = Math.Max(w, 70f);
if (ImGui.Button("Reset XP", new Vector2(w, 0)))
_hud.Post(() =>
{
_hud.SessionStats?.RequestReset();
_hud.Remote()?.Ilt.Command("rates reset"); // RynthILT's coin / pyreal session too
});
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Start the session stats over (RynthTracker, RynthOracle and RynthILT follow this session).");
// A server plugin's own rates follow this session (RynthILT restarts its coins when it restarts).
if (ImGui.Button("Reset XP", new Vector2(w, 0))) _hud.Post(() => _hud.SessionStats?.RequestReset());
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Start the session stats over (RynthTracker, RynthOracle and a server plugin's rates follow this session).");
ImGui.SameLine();
if (ImGui.Button("Report", new Vector2(w, 0))) _hud.Post(ReportToChat);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Print the session rates in your chat window (local only).");
@ -662,8 +660,7 @@ internal sealed class MiniRemoteHud
+ $"({HudDraw.Compact(v.LumLast5Min)} last 5m)";
if (v.PassUpTracked) line += $", Pass-up {HudDraw.Compact(v.PassUpPerHour)}/h";
line += $", Kills {HudDraw.Compact(v.KillsPerHour)}/h ({v.Kills:N0})";
if (_hud.Remote()?.Ilt.TryGetRates(out double coins, out double pyreals) == true)
line += $", Coins {HudDraw.Compact(coins)}/h, Pyr {HudDraw.Compact(pyreals)}/h";
line += _hud.Remote()?.ServerHub.Text(RynthIltHub.TextSessionReport) ?? string.Empty; // the server plugin's rates
_hud.Chat(line);
}
@ -832,10 +829,10 @@ internal sealed class MiniRemoteHud
Flag("Item slots", ref s.MiniShowGems);
// The drawer's dashboard has these switches already; the setting is for the windows.
if (!InDrawer) Flag("Toggles", ref s.MiniShowToggles);
Flag("Bank", ref s.MiniShowBank);
Flag("Rebuff", ref s.MiniShowRebuff);
Flag("Translate", ref s.MiniShowTranslate);
Flag("Guardian answer", ref s.MiniShowGuardian);
// The server plugin's Remote sections (RynthILT: Bank, Guardian answer): its own switches.
_hud.Remote()?.ServerHub.RenderSection(RynthIltHub.SectionRemoteOptions);
ImGui.Separator();
Flag("Horizontal layout", ref s.MiniRemoteHorizontal);
RenderSlotSizeSlider(s);
@ -875,9 +872,6 @@ internal sealed class MiniRemoteHud
// ── Right-click menu: Character, then this server's plugin windows ─────────
/// <summary>RynthCore's server id for Infinite Leaftide (UI/ServerMenus.cs), the one RynthILT has tabs for.</summary>
private const string IltServerId = "ilt";
/// <summary>
/// The right-click menu. Top, "Character": windows every server has. Bottom: the server
/// section, i.e. the installed server plugins' windows for the world you're on (RynthCore
@ -915,8 +909,8 @@ internal sealed class MiniRemoteHud
if (_hud.Host.HasInvokeChatParser)
{
// RynthOracle's commands (it toggles its own windows; without RynthOracle nothing answers "/ro").
// The character overview and its session are RynthOracle's Character tab (2026-10-13);
// Infinite Leaftide's charms and bank stay RynthILT's tabs (the server section below).
// The character overview and its session are RynthOracle's Character tab (2026-10-13); a
// server's own screens are its plugin's (the server section below).
if (ImGui.MenuItem("Character##mrcharacter", MovedTabs.OracleCharacter)) _hud.RunEngineCommand(MovedTabs.OracleCharacter);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthOracle's Character tab: the character and this session.");
if (ImGui.MenuItem("Quests##mrquests", "/ro")) _hud.RunEngineCommand("/ro");
@ -933,25 +927,28 @@ internal sealed class MiniRemoteHud
}
/// <summary>
/// The server section. Each section RynthCore marks active is listed, and so is Infinite
/// Leaftide while this character's "Treat this world as ILT" is on (RynthILT's override).
/// Without RynthCore's list it falls back to RynthILT's own ILT entries.
/// The server section. Each section RynthCore marks active is listed, and so is the server
/// plugin's own server while this character forces it (the plugin's override, e.g. RynthILT's
/// "Treat this world as ILT"). Without RynthCore's list it falls back to the server plugin's own
/// menu entries (its "server-menu" section).
/// </summary>
private void RenderServerMenu(MiniRemoteController? remote)
{
ServerMenuGroup[]? groups = ServerMenuModel.Groups;
if (groups == null)
{
remote?.Ilt.RenderSection(RynthIltHub.SectionServerMenu);
remote?.ServerHub.RenderSection(RynthIltHub.SectionServerMenu);
return;
}
if (groups.Length == 0) return; // no server plugin installed
// The server the active server plugin's tabs and status belong to (RynthILT: "ilt"); "" without one.
string pluginServer = remote?.ServerHub.Text(RynthIltHub.TextServerId) ?? string.Empty;
bool any = false;
foreach (ServerMenuGroup g in groups)
{
bool ilt = g.Id.Equals(IltServerId, StringComparison.OrdinalIgnoreCase);
bool forcedHere = ilt && remote?.Ilt.ForceIlt == true;
bool ours = pluginServer.Length > 0 && g.Id.Equals(pluginServer, StringComparison.OrdinalIgnoreCase);
bool forcedHere = ours && remote?.ServerHub.ServerForced == true;
if (!g.Active && !forcedHere) continue;
any = true;
ImGui.Separator();
@ -971,7 +968,8 @@ internal sealed class MiniRemoteHud
if (item.Tooltip.Length > 0 && ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
SafeImGui.SetTooltip(enabled ? item.Tooltip : item.Tooltip + "\nShows once the server reports this feature on.");
}
if (ilt) remote?.Ilt.RenderSection(RynthIltHub.SectionIltStatus);
// The plugin's status under its server (RynthILT: why no ILT feature is on, Refresh).
if (ours) remote?.ServerHub.RenderSection(RynthIltHub.SectionIltStatus);
}
if (any) return;
@ -992,11 +990,11 @@ internal sealed class MiniRemoteHud
else if (item.Command.Length > 0) _hud.RunEngineCommand(item.Command);
}
/// <summary>RynthILT reports that ILT tab's feature on (false without RynthILT).</summary>
/// <summary>The server plugin reports that tab's feature on (false without one).</summary>
private static bool TabAvailable(MiniRemoteController? remote, string tab)
{
if (remote == null) return false;
foreach (IltTabInfo t in remote.Ilt.Tabs())
foreach (ServerTabInfo t in remote.ServerHub.Tabs())
if (string.Equals(t.Id, tab, StringComparison.OrdinalIgnoreCase)) return t.Available;
return false;
}

View file

@ -4,8 +4,8 @@
// RynthOracle's Character tab ("/ro character"), its ILT session rates to RynthCore's Mini Remote
// "Session Stats" section (RynthILT's own "section:ilt-rates"), and the force-server override to
// RynthCore Options > Diagnostics ("/rc diagnostics"). Infinite Leaftide's own screens stay
// RynthILT's: Charms and Banking are still Mini Remote ILT tabs (SectionsManifest places them on
// the rail), drawn by RynthILT.
// RynthILT's: Charms and Banking are still Mini Remote ILT tabs (RynthILT's own manifest places
// them on the rail since 2026-10-20), drawn by RynthILT.
// Old saved tab ids, links and "/ra hub open|tab <name>" land on the new home through CommandFor.
//
// Pure: the host tests check the mapping offline.

View file

@ -4,22 +4,15 @@
// Stats - id "char" -, Map, Skills, Combat, Nav, Inventory, Crafting, Spells, Chat, Friends,
// Fellowship, Pets) and any a plugin adds. It reads each plugin's optional
// RynthPluginGetSectionsJson export every couple of seconds (schema: UI/Sections/SectionManifest.cs
// in RynthCore). RynthAi fills:
// every world Session Stats (the one session: RynthTracker, RynthOracle and RynthILT read the
// same numbers, and RynthCore drops its own overview for it), Pets, Crafting,
// Spells and Fellowship (the views of those core sections)
// Infinite RynthILT's tabs, hosted here as they are in RynthAi's own Mini Remote (RynthILT.Hub,
// Leaftide MiniRemote/IltClient.cs): Gear, Charms and Banking in Inventory, and a Games
// section of RynthAi's own
// Quests are RynthOracle's (since 2026-10-13), and RynthILT draws its ILT session extras, /fship
// and /qb views itself (its own manifest), so neither is listed here. RynthILT's Character tab
// moved out on 2026-10-13 (MovedTabs.cs): RynthOracle's Character tab and the ILT session rates in
// Session Stats. Charms and Banking stay RynthILT's tabs (Infinite Leaftide's own screens), so the
// engine's "/rc miniremote tab charms|banking" finds them here as "section:charms|banking".
// Each view is a surface "section:<name>" RynthCore draws through RynthPluginRenderEmbed. An ILT
// view whose feature the server hasn't reported is listed but not enabled, with a note.
// in RynthCore). RynthAi fills, on every world: Session Stats (the one session: RynthTracker,
// RynthOracle and RynthILT read the same numbers, and RynthCore drops its own overview for it),
// Pets, Crafting, Spells and Fellowship (the views of those core sections).
// Nothing server-specific is listed here: a server plugin lists its own views (since 2026-10-20
// RynthILT lists its Mini Remote tabs, Gear / Charms / Banking / Games / Vaulted Dungeons, and its
// Games section itself; RynthAi hosted them until then). Quests are RynthOracle's (since 2026-10-13).
// Each view is a surface "section:<name>" RynthCore draws through RynthPluginRenderEmbed.
//
// Pure: RynthILT's tabs come in as a list, so the host tests build it offline.
// Pure, so the host tests build it offline.
using System;
using System.Collections.Generic;
using System.IO;
@ -42,12 +35,6 @@ internal static class SectionsManifest
/// <summary>The session stats (RynthCore's Session Stats section, "char").</summary>
public const string SessionSurface = SurfacePrefix + "session";
/// <summary>RynthCore's id for Infinite Leaftide.</summary>
public const string IltServer = "ilt";
/// <summary>Longest tab id taken from RynthILT (its ids are short ASCII words).</summary>
public const int MaxTabIdLength = 32;
/// <summary>One view RynthAi puts in a section.</summary>
internal sealed record View(string Section, string Server, string Label, string Surface, bool Primary,
Vector2 Size, bool Enabled, string Note, string Tooltip, int Order);
@ -55,37 +42,14 @@ internal static class SectionsManifest
/// <summary>A section of RynthAi's own (beyond RynthCore's core twelve).</summary>
internal sealed record Section(string Id, string Label, int Order);
/// <summary>RynthAi's own sections: Games (ILT) after Pets.</summary>
public static readonly Section[] OwnSections =
{
new("games", "Games", 1150),
};
/// <summary>RynthAi's own sections beyond the core ones: none (Games went with RynthILT's tabs, 2026-10-20).</summary>
public static readonly Section[] OwnSections = Array.Empty<Section>();
private const string NotReportedNote = "Shows once the server reports this ILT feature on (RynthILT's ILT settings can ask again).";
/// <summary>Where each of RynthILT's tabs goes: section, label, order, tooltip. Unknown ids aren't listed.</summary>
private static readonly Dictionary<string, (string Section, string Label, int Order, string Tooltip)> IltPlacement =
new(StringComparer.OrdinalIgnoreCase)
{
["gear"] = ("inventory", "Gear", 210, "ILT gear tools (RynthILT)."),
["charms"] = ("inventory", "Charms", 220, "ILT charms and Guardian Hands: acquired, status, tier, toggles (RynthILT)."),
["banking"] = ("inventory", "Banking", 230, "Your ILT bank: balances, deposits, withdrawals and transfers (RynthILT)."),
["games"] = ("games", "Games", 100, "ILT games (RynthILT)."),
// Listed only while RynthILT shows the tab: the Vaulted Dungeons master switch (RynthAi
// Settings > Navigation) is on, on an ILT world.
["vaulted"] = ("nav", "Vaulted Dungeons", 220,
"Keep the character in one Vaulted Dungeon (RynthILT; Settings > Navigation > Vaulted Dungeons)."),
};
/// <summary>The surface name of a tab's view ("section:gear").</summary>
/// <summary>The surface name of a tab's view ("section:pets").</summary>
public static string SurfaceOf(string tabId) => SurfacePrefix + tabId;
/// <summary>
/// Every view, from what is available now: RynthAi's own (every world) and
/// <paramref name="iltTabs"/> (RynthILT's tabs with their sizes and whether the server has
/// each feature on; empty without RynthILT or off ILT).
/// </summary>
public static List<View> Views(IReadOnlyList<IltTabInfo> iltTabs)
/// <summary>Every view RynthAi offers (the same on every world).</summary>
public static List<View> Views()
{
var views = new List<View>
{
@ -95,21 +59,12 @@ internal static class SectionsManifest
new("pets", string.Empty, "Pets", PetsSurface, true, MiniRemoteTabs.Size(MiniRemoteTabs.Pets), true, string.Empty,
"Combat pets: the summon out, essences, and the pet picker (RynthAi).", 100),
new("crafting", string.Empty, "Crafting", CraftingSurface, true, MiniRemoteTabs.Size(MiniRemoteTabs.Crafting), true, string.Empty,
"Tinkering benches, chunking / clap and split arrows (RynthAi).", 100),
"Tinkering benches: retail tinks, your own rows and the server plugin's salvage (RynthAi).", 100),
new("spells", string.Empty, "Spells", SpellsSurface, true, new Vector2(900, 560), true, string.Empty,
"The spell catalog and buff profiles (RynthAi).", 100),
new("fellowship", string.Empty, "Fellowship", FellowshipSurface, true, new Vector2(380, 360), true, string.Empty,
"Your fellowship: members, leader, XP sharing (RynthAi; also RynthOracle's Fellowship tab).", 100),
};
// Infinite Leaftide: RynthILT's tabs that it shows on this world.
foreach (IltTabInfo tab in iltTabs)
{
if (!tab.Shown || !IsTabId(tab.Id) || !IltPlacement.TryGetValue(tab.Id, out var place)) continue;
var size = new Vector2(MathF.Max(0f, tab.Width), MathF.Max(0f, tab.Height));
views.Add(new View(place.Section, IltServer, place.Label, SurfaceOf(tab.Id.ToLowerInvariant()), true, size,
tab.Available, tab.Available ? string.Empty : NotReportedNote, place.Tooltip, place.Order));
}
return views;
}
@ -166,23 +121,4 @@ internal static class SectionsManifest
return tabId.Length > 0;
}
/// <summary>The RynthILT tab a "section:&lt;tab&gt;" surface draws, if it names one we place.</summary>
public static bool TryIltTabOf(string surface, out string tabId)
{
tabId = string.Empty;
if (!surface.StartsWith(SurfacePrefix, StringComparison.Ordinal)) return false;
string id = surface.Substring(SurfacePrefix.Length);
if (!IsTabId(id) || !IltPlacement.ContainsKey(id)) return false;
tabId = id;
return true;
}
/// <summary>A short lowercase-ASCII id (letters, digits, '-'): nothing else is spliced into a surface name.</summary>
private static bool IsTabId(string? id)
{
if (string.IsNullOrEmpty(id) || id.Length > MaxTabIdLength) return false;
foreach (char c in id)
if (!(c is >= 'a' and <= 'z' or >= 'A' and <= 'Z' or >= '0' and <= '9' or '-')) return false;
return true;
}
}

View file

@ -34,8 +34,59 @@ internal sealed class Jumper
private bool _pausedNav;
private bool _prevEnableNavigation;
// Face only (/mt face, /ub face; ub-IT's DoFace): navigation is held while turning, the turn
// is sent again every 100 ms until the heading is within 1 degree, and given up after 5 s.
private bool _faceOnly;
private DateTime _lastFaceTurnAt;
private const double FaceToleranceDeg = 1.0;
private static readonly TimeSpan FaceRetry = TimeSpan.FromMilliseconds(100);
private static readonly TimeSpan FaceTimeout = TimeSpan.FromSeconds(5);
public bool IsBusy => _isTurning || _needToJump || _charging || _waitingForJump;
/// <summary>Turns to <paramref name="heading"/> (any degrees; normalized to 0-360), holding nav meanwhile.</summary>
public bool Face(double heading)
{
if (IsBusy && !_faceOnly)
{
_chat("[RynthAi] You are jumping. Try again later.");
return false;
}
if (!_host.HasTurnToHeading)
{
_chat("[RynthAi] TurnToHeading not available.");
return false;
}
_targetHeading = (float)(((heading % 360) + 360) % 360);
if (!_faceOnly) PauseNav();
_faceOnly = true;
_isTurning = true;
_turningStartedAt = _lastFaceTurnAt = DateTime.UtcNow;
_host.TurnToHeadingBy("Face", _targetHeading);
RynthLog.Write(LogCat.Jumper, $"[Jumper] Face -> {_targetHeading:F1}");
return true;
}
/// <summary>The face turn: done within <see cref="FaceToleranceDeg"/>, else turn again; nav back when done.</summary>
private void TickFace()
{
DateTime now = DateTime.UtcNow;
if (now - _lastFaceTurnAt < FaceRetry) return;
_lastFaceTurnAt = now;
bool read = PlayerCompass.TryGet(_host, out float current);
double off = read ? Math.Abs(((current - _targetHeading) % 360 + 540) % 360 - 180) : 0;
if (read && off >= FaceToleranceDeg && now - _turningStartedAt < FaceTimeout)
{
_host.TurnToHeadingBy("Face", _targetHeading);
return;
}
_isTurning = _faceOnly = false;
RestoreNav();
RynthLog.Write(LogCat.Jumper, read && off >= FaceToleranceDeg
? $"[Jumper] Face {_targetHeading:F1}: still {off:F1} deg off after {FaceTimeout.TotalSeconds:0} s, gave up"
: $"[Jumper] Face {_targetHeading:F1} done (heading {(read ? current.ToString("F1") : "?")})");
}
public Jumper(RynthCoreHost host, LegacyUiSettings settings, Action<string> chat)
{
_host = host;
@ -45,6 +96,12 @@ internal sealed class Jumper
public bool Start(string directionLetters, float? faceHeading, int msToHoldDown)
{
// A face still turning (a meta's "/mt face 90" then "/ub jumpw 90") gives way to the jump.
if (_faceOnly)
{
_faceOnly = _isTurning = false;
RestoreNav();
}
if (IsBusy)
{
_chat("[RynthAi] You are already jumping. Try again later.");
@ -77,7 +134,7 @@ internal sealed class Jumper
}
else
{
_targetHeading = _host.TryGetPlayerHeading(out float curr) ? curr : 0f;
_targetHeading = PlayerCompass.TryGet(_host, out float curr) ? curr : 0f;
}
PauseNav();
@ -101,7 +158,7 @@ internal sealed class Jumper
public void Cancel()
{
RestoreNav();
_isTurning = _needToJump = _charging = _waitingForJump = false;
_isTurning = _needToJump = _charging = _waitingForJump = _faceOnly = false;
_addW = _addX = _addZ = _addC = _addShift = false;
}
@ -111,13 +168,18 @@ internal sealed class Jumper
try
{
if (_faceOnly)
{
TickFace();
return;
}
// TurnToHeading is an instant quaternion snap; the heading read
// doesn't always reflect it immediately, so just wait a short
// settle window rather than polling for a match.
if (_isTurning && DateTime.UtcNow - _turningStartedAt >= TimeSpan.FromMilliseconds(150))
{
_isTurning = false;
if (_host.TryGetPlayerHeading(out float current))
if (PlayerCompass.TryGet(_host, out float current))
RynthLog.Write(LogCat.Jumper, $"[Jumper] Turn done heading={current:F1}");
}

View file

@ -463,6 +463,17 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SliderInt("Give Interval (ms)", ref _settings.GiveQueueIntervalMs, 0, 2000);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Minimum gap between two gives sent by /ra givea commands.\n0 = send the next give the moment the server answers the last (fastest).\nThe queue always waits for the server's answer first.");
ImGui.Separator();
ImGui.Spacing();
ImGui.Text("Meta Compatibility");
ImGui.Checkbox("Allow metas to send keystrokes (/mt send)", ref _settings.AllowMetaKeystrokes);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Mag-Tools metas press keys and click inside the game window with /mt send, /mt click,\n" +
"/mt movement, /mt strafe, /mt client minimize|restore and the key form of /mt jump.\n" +
"Off (the default): those verbs log once and do nothing. Turn it on only for a meta you trust:\n" +
"the keys go to the game window as if you pressed them. /mt send /command (a chat command)\n" +
"is not a key press and works either way.");
break;
case "Recharge":
@ -741,9 +752,6 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetTooltip("Drop a locked target only past this distance (hysteresis).\n0 or <= Monster Range = auto (Monster Range + 3).");
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Ring Range", ref _settings.RingRange);
ImGui.Checkbox("Evade Handler Ring", ref _settings.HandlerRingEvade);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Empyrean Handler: when it channels its lethal ring and you are within 12 yards (or Ring Range if larger),\nback-jump away and re-engage. Acts only while the macro is running with combat on.");
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Approach Range", ref _settings.ApproachRange);

View file

@ -1100,6 +1100,20 @@ internal sealed partial class LegacyDashboardRenderer
// ── Settings bridge (engine-side Avalonia SettingsPanel) ─────────────────
/// <summary>
/// The active server plugin's mirrored settings (RynthILT.Hub GetSetting / SetSetting, through the
/// Mini Remote's server client): the value, or -1 when none is offered. Set by RynthAiPlugin.
/// </summary>
public Func<string, int>? ServerSettingGet { get; set; }
public Action<string, int>? ServerSettingSet { get; set; }
/// <summary>A mirrored server setting as a nullable bool (null = not offered: the engine row hides).</summary>
private bool? ServerSettingBool(string key)
{
int v = ServerSettingGet?.Invoke(key) ?? -1;
return v < 0 ? null : v != 0;
}
public string BuildSettingsJson()
{
try
@ -1139,7 +1153,6 @@ internal sealed partial class LegacyDashboardRenderer
BlacklistCastSettleMs = s.BlacklistCastSettleMs,
TargetNoProgressTimeoutSec = s.TargetNoProgressTimeoutSec,
GiveQueueIntervalMs = s.GiveQueueIntervalMs,
T11ItemAugsOverride = s.T11ItemAugsOverride,
// Recharge
HealAt = s.HealAt,
UsePotions = s.UsePotions,
@ -1197,6 +1210,10 @@ internal sealed partial class LegacyDashboardRenderer
SpellCastIntervalMs = s.SpellCastIntervalMs,
AttackSpellIntervalMs = s.AttackSpellIntervalMs,
CastDispelSelf = s.CastDispelSelf,
UseDispelItems = s.UseDispelItems,
AutoFellowMgmt = s.AutoFellowMgmt,
MChargesWhenOff = s.MChargesWhenOff,
CustomPetRange = s.CustomPetRange,
MinRingTargets = s.MinRingTargets,
BlastRange = s.BlastRange,
MinBlastTargets = s.MinBlastTargets,
@ -1221,7 +1238,7 @@ internal sealed partial class LegacyDashboardRenderer
CorpseApproachRangeMin = s.CorpseApproachRangeMin,
// Navigation
BoostNavPriority = s.BoostNavPriority,
EnableVaultedDungeons = s.EnableVaultedDungeons,
EnableVaultedDungeons = ServerSettingBool(RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons), // RynthILT's (null: the row hides)
FollowNavMin = s.FollowNavMin,
NavRingThickness = s.NavRingThickness,
NavLineThickness = s.NavLineThickness,
@ -1393,7 +1410,6 @@ internal sealed partial class LegacyDashboardRenderer
if (p.BlacklistCastSettleMs > 0) s.BlacklistCastSettleMs = p.BlacklistCastSettleMs;
s.TargetNoProgressTimeoutSec = p.TargetNoProgressTimeoutSec;
s.GiveQueueIntervalMs = p.GiveQueueIntervalMs;
s.T11ItemAugsOverride = p.T11ItemAugsOverride ?? -1;
// Recharge
s.HealAt = p.HealAt;
s.UsePotions = p.UsePotions;
@ -1453,6 +1469,11 @@ internal sealed partial class LegacyDashboardRenderer
s.SpellCastIntervalMs = p.SpellCastIntervalMs;
if (p.AttackSpellIntervalMs is int attackDelay) s.AttackSpellIntervalMs = attackDelay; // absent = unchanged
s.CastDispelSelf = p.CastDispelSelf;
// Absent (an engine without them) = unchanged.
if (p.UseDispelItems is bool useDispelItems) s.UseDispelItems = useDispelItems;
if (p.AutoFellowMgmt is bool autoFellow) s.AutoFellowMgmt = autoFellow;
if (p.MChargesWhenOff is bool mCharges) s.MChargesWhenOff = mCharges;
if (p.CustomPetRange is int petRange) s.CustomPetRange = Math.Clamp(petRange, 1, 50);
s.MinRingTargets = p.MinRingTargets;
s.BlastRange = p.BlastRange;
s.MinBlastTargets = p.MinBlastTargets;
@ -1477,7 +1498,8 @@ internal sealed partial class LegacyDashboardRenderer
s.CorpseApproachRangeMin = p.CorpseApproachRangeMin;
// Navigation
s.BoostNavPriority = p.BoostNavPriority;
if (p.EnableVaultedDungeons is bool vaulted) s.EnableVaultedDungeons = vaulted; // absent = unchanged
if (p.EnableVaultedDungeons is bool vaulted) // absent = unchanged
ServerSettingSet?.Invoke(RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons, vaulted ? 1 : 0); // RynthILT's switch
s.FollowNavMin = p.FollowNavMin;
s.NavRingThickness = p.NavRingThickness;
s.NavLineThickness = p.NavLineThickness;
@ -1966,7 +1988,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.TargetSelection = Math.Clamp(tmp.TargetSelection, 0, 3);
dst.TargetLock = tmp.TargetLock;
dst.RingRange = tmp.RingRange;
dst.HandlerRingEvade = tmp.HandlerRingEvade; // a profile saved before this setting loads it as on
dst.HandlerRingEvade = tmp.HandlerRingEvade; // obsolete (RynthILT's now): carried so the profile keeps it for RynthILT's one-time import
dst.ApproachRange = tmp.ApproachRange;
dst.MinRingTargets = tmp.MinRingTargets;
dst.BlastRange = tmp.BlastRange;
@ -1989,7 +2011,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.CorpseApproachRangeMax = NormalizeCorpseRangeYards(tmp.CorpseApproachRangeMax, 10.0);
dst.CorpseApproachRangeMin = NormalizeCorpseRangeYards(tmp.CorpseApproachRangeMin, 2.0);
dst.BoostNavPriority = tmp.BoostNavPriority;
dst.EnableVaultedDungeons = tmp.EnableVaultedDungeons;
dst.EnableVaultedDungeons = tmp.EnableVaultedDungeons; // obsolete (RynthILT's now): carried for its one-time import
dst.BoostLootPriority = tmp.BoostLootPriority;
dst.OpenDoors = tmp.OpenDoors;
dst.OpenDoorRange = tmp.OpenDoorRange;
@ -2118,6 +2140,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.AutoTradeAutoAccept = tmp.AutoTradeAutoAccept;
dst.AutoTradeAutoAcceptChars = tmp.AutoTradeAutoAcceptChars ?? new();
dst.MetaDebug = tmp.MetaDebug;
dst.AllowMetaKeystrokes = tmp.AllowMetaKeystrokes;
dst.StartMacroOnLogin = tmp.StartMacroOnLogin;
dst.PatrolOnLogin = tmp.PatrolOnLogin;
dst.YieldToVTank = tmp.YieldToVTank;
@ -2127,7 +2150,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.NavLabelMode = NavLabelModes.Clamp(tmp.NavLabelMode);
dst.NavGuideLine = tmp.NavGuideLine;
dst.GiveQueueIntervalMs = tmp.GiveQueueIntervalMs;
dst.T11ItemAugsOverride = tmp.T11ItemAugsOverride;
dst.T11ItemAugsOverride = tmp.T11ItemAugsOverride; // obsolete (RynthILT's now): carried for its one-time import
dst.SpellCastIntervalMs = tmp.SpellCastIntervalMs;
dst.StuckCastBreakMs = tmp.StuckCastBreakMs;
dst.RecoveryRetryMs = tmp.RecoveryRetryMs;

View file

@ -38,6 +38,15 @@ public sealed class LegacyUiSettings
public bool EnableRaycasting = true;
public bool MetaDebug;
/// <summary>
/// "Allow metas to send keystrokes (/mt send)". Off by default (2026-10-19). Mag-Tools' /mt send,
/// click, movement, strafe, client minimize|restore and the key fallback of /mt jump post raw
/// key and mouse messages to the game window; with this off they log once and do nothing.
/// Deliberately not in the expression settings map, /mt opt or the phone's settings: a meta
/// must not be able to switch it on for itself.
/// </summary>
public bool AllowMetaKeystrokes;
public int MovementMode;
public float NavStopTurnAngle = 20f;
public float NavResumeTurnAngle = 10f;
@ -207,9 +216,10 @@ public sealed class LegacyUiSettings
// setting loads it as on.
public bool TargetLock = true;
public int RingRange = 5;
// Empyrean Handler lethal ring (CombatManager.HandleChatForRingEvade): when the Handler channels the
// ring and the character is inside its danger radius, back-jump away and re-engage. Only acts while
// the macro is running with combat on. On by default because it is gated that way.
// Obsolete since 2026-10-20 (unused here, kept so profiles still load and carry it): the Empyrean
// Handler lethal-ring evade is Infinite Leaftide's and lives in RynthILT now (its ILT settings,
// "/ilt settings"), which copied this value once. RynthAi keeps only the generic back-away it
// asks for (CombatManager.BackAwayFrom, RynthAi.Hub BackAwayFrom).
public bool HandlerRingEvade = true;
public int ApproachRange = 4;
public int MinRingTargets = 4;
@ -257,10 +267,10 @@ public sealed class LegacyUiSettings
public bool BoostNavPriority;
/// <summary>
/// Options > Navigation > Vaulted Dungeons: the MASTER switch of RynthILT's Vaulted Dungeons
/// keeper (Infinite Leaftide / ACECustom only). Off by default. RynthILT reads it through
/// "RynthAi.Hub" VaultedDungeonsEnabled; while it is off the keeper does nothing (no recalls,
/// no /rc quit, no tab). This is the one place the switch lives.
/// Obsolete since 2026-10-20 (kept so profiles still load and carry it): the Vaulted Dungeons
/// keeper's master switch is RynthILT's own setting now, copied from here once. RynthAi only
/// mirrors RynthILT's value into the engine's Settings > Navigation row (ServerSettingGet / Set)
/// and answers this old value through RynthAi.Hub VaultedDungeonsEnabled for an older RynthILT.
/// </summary>
public bool EnableVaultedDungeons;
public bool BoostLootPriority;
@ -414,9 +424,9 @@ public sealed class LegacyUiSettings
public int GiveQueueIntervalMs = 0;
/// <summary>
/// Item augmentation count used for T11 wield gates in loot rules ("T11: Can Wield").
/// -1 = automatic (read from the server's "/aug" reply). ACECustom doesn't send the count
/// at login, so this is the fallback when "/aug" is unavailable. Set with /ra t11 augs.
/// Obsolete since 2026-10-20 (kept so profiles still load and carry it): the item augmentation
/// count override for the T11 "Can Wield" loot key is RynthILT's now ("/ilt t11 augs", copied from
/// here once), and RynthILT reports the counters it reads from "/aug" (RynthAi.Hub SetPlayerCounter).
/// </summary>
public int T11ItemAugsOverride = -1;
@ -608,7 +618,9 @@ public sealed class LegacyUiSettings
public int BuffMinSkillLevelTier7 = 335;
public int BuffMinSkillLevelTier8 = 435;
public bool EnableManaTapping = false;
// On for a new character (2026-10-20): with it off only stones already charged refill worn gear, and
// nothing charges them, so suits ran dry for players who never found the switch. A saved profile keeps its choice.
public bool EnableManaTapping = true;
public int ManaTapMinMana = 2500;
public int ManaStoneKeepCount = 5;
@ -951,7 +963,7 @@ public sealed class ItemsBridgePayload
{
public List<ItemRule> Weapons { get; set; } = new();
public List<ConsumableRule> Consumables { get; set; } = new();
public bool EnableManaTapping { get; set; }
public bool EnableManaTapping { get; set; } = true; // absent from an old profile = the new default
public int ManaTapMinMana { get; set; }
public int ManaStoneKeepCount { get; set; }
public string CurrentTargetName { get; set; } = string.Empty;
@ -1138,6 +1150,12 @@ public sealed class SettingsBridgePayload
// Nullable since 0 became a real value (2026-10-08): a file without it keeps the default.
public int? AttackSpellIntervalMs { get; set; }
public bool CastDispelSelf { get; set; }
// VTank's options page (the engine's Classic dashboard, Main tab; 2026-10-19). Nullable: an engine
// without them sends none, and the saved values stay.
public bool? UseDispelItems { get; set; }
public bool? AutoFellowMgmt { get; set; }
public bool? MChargesWhenOff { get; set; }
public int? CustomPetRange { get; set; }
public int MinRingTargets { get; set; }
public int BlastRange { get; set; }
public int MinBlastTargets { get; set; } = 3; // absent from an older engine: keep the default
@ -1168,8 +1186,9 @@ public sealed class SettingsBridgePayload
// Navigation
public bool BoostNavPriority { get; set; }
/// <summary>
/// Options > Navigation > Vaulted Dungeons: the keeper's master switch (off by default). Nullable:
/// an engine that predates the row omits it, and absent = unchanged (never switches it off or on).
/// Options > Navigation > Vaulted Dungeons: RynthILT's keeper master switch, mirrored (RynthILT.Hub
/// GetSetting / SetSetting). Null when no server plugin offers it (no RynthILT, or off ILT): the
/// engine row then hides. Received: absent = unchanged; a value goes to RynthILT.
/// </summary>
public bool? EnableVaultedDungeons { get; set; }
public float FollowNavMin { get; set; }

View file

@ -425,7 +425,7 @@ public sealed class InventoryManager
internal static bool MergeProgressed(int targetBefore, int sourceBefore, int targetNow, int sourceNow)
=> targetBefore > 0 && sourceBefore > 0 && (targetNow > targetBefore || sourceNow < sourceBefore);
private static int GetMaxStackSize(WorldObject item)
internal static int GetMaxStackSize(WorldObject item)
{
int max = item.Values(LongValueKey.MaxStackSize, 0);
if (max > 1) return max;

View file

@ -8,15 +8,17 @@ namespace RynthCore.Plugin.RynthAi.Loot;
/// T11 (tier 11+ ACECustom) loot support for <see cref="WorldObject.Values(int, int)"/>:
/// answers the virtual T11 keys (<see cref="T11Keys"/>) and puts back the wield-requirement and
/// rating properties the server strips from T11 appraisals. Parsed item text is cached per
/// object and re-parsed only when the text changes. Holds the player's "/aug" counters for
/// the "Can Wield" key. One character per process, so the state is static.
/// object and re-parsed only when the text changes. Holds the player's wield counters for the
/// "Can Wield" key; since 2026-10-20 the server plugin reports them (RynthILT reads ACECustom's
/// "/aug" reply and applies its item-aug override, then calls RynthAi.Hub SetPlayerCounter), so
/// without one they stay unknown, as on any retail-like server. One character per process, so
/// the state is static.
/// </summary>
internal static class T11ItemSupport
{
/// <summary>The logged-in character's T11 wield counters.</summary>
public static T11PlayerAugs Player { get; } = new();
private static readonly T11AugReportParser AugParser = new();
private static readonly object Gate = new();
private static readonly Dictionary<int, Entry> Parsed = new();
@ -103,12 +105,19 @@ internal static class T11ItemSupport
}
}
/// <summary>Feeds a chat line to the "/aug" reader. Returns true when a counter changed.</summary>
public static bool OnChat(string? text) => AugParser.Feed(text, Environment.TickCount64, Player);
/// <summary>Applies the saved item-aug override (-1 = automatic). Cheap; called every tick.</summary>
public static void SyncOverride(int itemAugsOverride)
=> Player.ItemAugOverride = itemAugsOverride >= 0 ? itemAugsOverride : null;
/// <summary>
/// A wield counter from the server plugin (RynthAi.Hub SetPlayerCounter): <paramref name="propertyId"/>
/// is the counter's Int64 property id (T11Counter), <paramref name="value"/> &lt; 0 = unknown again.
/// False for an id that is no T11 counter. Any thread.
/// </summary>
public static bool SetCounter(uint propertyId, long value)
{
if (!Enum.IsDefined(typeof(T11Counter), unchecked((int)propertyId))) return false;
var counter = (T11Counter)unchecked((int)propertyId);
if (value < 0) Player.Forget(counter);
else Player.Set(counter, value);
return true;
}
/// <summary>Drops the cached parse of a deleted object.</summary>
public static void Forget(int objectId)

View file

@ -0,0 +1,506 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// The rest of Mag-Tools' <c>/mt</c> verbs (2026-10-17; checked against Mag-Tools PluginCore and
/// ub-IT's MagToUbCommandTranslator): send (keys), jump / sjump, trade, vendor buy/sell lists,
/// autopack, dumpspells, click, get xy, movement, client, plus ub-IT's config and strafe.
/// Partial class of RynthAiPlugin; dispatched from <see cref="HandleMtCommand"/>.
/// </summary>
public sealed partial class RynthAiPlugin
{
// /mt vendor addbuy/addsell lists, sent by "/mt vendor buy" / "sell" (Mag-Tools keeps them in Decal).
private readonly List<(uint Id, string Name, int Amount)> _mtBuyList = new();
private readonly List<(uint Id, string Name)> _mtSellList = new();
// ── Safety gates (2026-10-19) ───────────────────────────────────────────────
//
// Two kinds of /mt verb can do real damage if a shared meta (or a stray chat line) drives them:
// * raw input into the game window (send, click, movement, strafe, client, the jump fallback):
// off unless the setting "Allow metas to send keystrokes (/mt send)" is on (default off);
// * acting on a vendor or a trade (vendor buy / sell, trade accept): only while a meta that is
// running executes the line. A typed line, a delayed line that did not come from a meta, or
// any other path is refused.
// Nesting count of the meta chat-command handler (HandleMetaChatCommand) on the call stack.
private int _metaCommandDepth;
// Verbs already told "off" this session (one chat line and one log line each, not one per meta pulse).
private readonly HashSet<string> _keystrokeRefusalSaid = new(StringComparer.OrdinalIgnoreCase);
/// <summary>True while a running meta (macro on, Meta on) is executing the line being handled:
/// inside one of its actions (MetaManager.IsExecutingAction) or a line replayed on its behalf.</summary>
internal bool MetaCommandActive
=> (_metaCommandDepth > 0 || _metaManager?.IsExecutingAction == true)
&& _dashboard?.Settings is { IsMacroRunning: true, EnableMeta: true };
/// <summary>Runs <paramref name="action"/> as a line a meta executes (see <see cref="MetaCommandActive"/>).</summary>
private T RunAsMeta<T>(Func<T> action)
{
_metaCommandDepth++;
try { return action(); }
finally { _metaCommandDepth--; }
}
/// <summary>
/// The setting "Allow metas to send keystrokes (/mt send)". False (and said once per verb) when
/// it is off, which is the default: the verb then does nothing.
/// </summary>
private bool KeystrokesAllowed(string verb)
{
if (_dashboard?.Settings.AllowMetaKeystrokes == true) return true;
if (_keystrokeRefusalSaid.Add(verb))
{
string msg = $"[RynthAi] {verb} ignored: it sends keys or clicks to the game window, and 'Allow metas to send keystrokes (/mt send)' is off (Settings, Advanced). Said once.";
Log(msg);
ChatLine(msg);
}
return false;
}
/// <summary>
/// True only when a running meta executes this line. Otherwise says why not and returns false,
/// so <paramref name="verb"/> (an action on a vendor or a trade) is never run from a typed or
/// unrelated line.
/// </summary>
private bool RequireRunningMeta(string verb)
{
if (MetaCommandActive) return true;
string msg = $"[RynthAi] {verb} only runs from a meta that is running (macro and Meta on); refused.";
Log(msg);
ChatLine(msg);
return false;
}
/// <summary>The verbs this file handles, from <see cref="HandleMtCommand"/>'s default branch.</summary>
private bool TryHandleMtExtra(string cmd, string[] parts, string fullCommand)
{
// jump, sjump, jumpw, sjumpwz ... (Mag-Tools matches "jump" anywhere after /mt).
if (cmd.StartsWith("jump", StringComparison.Ordinal) || cmd.StartsWith("sjump", StringComparison.Ordinal))
return HandleMtJump(cmd, parts);
switch (cmd)
{
case "test":
ChatLine("[RynthAi] /mt test: Mag-Tools' debug command - nothing to do.");
return true;
case "trade": return HandleMtTrade(parts);
case "vendor": return HandleMtVendor(parts);
case "autopack":
// Mag-Tools packs by its own rules; RynthAi's equivalent is a cram + stack pass.
_inventoryManager?.RunManual(cram: true, stack: true);
ChatLine("[RynthAi] Autopack: cramming items into side packs and stacking them.");
return true;
case "dumpspells": return HandleMtDumpSpells();
case "click": return HandleMtClick(parts);
case "get":
if (parts.Length >= 3 && parts[2].Equals("xy", StringComparison.OrdinalIgnoreCase)) return HandleMtCursor();
ChatLine("[RynthAi] Usage: /mt get xy");
return true;
case "cursor": return HandleMtCursor();
case "movement": return HandleMtMovement(parts);
case "strafe": return HandleMtStrafe(parts);
case "client": return HandleMtClient(parts);
case "config":
// ub-IT: /mt config = /mt opt (list when bare).
return parts.Length < 3 ? HandleMtOpt(new[] { "/mt", "opt", "list" }) : HandleMtOpt(parts);
default:
return false;
}
}
// ── send: keys, as Mag-Tools ────────────────────────────────────────────────
/// <summary>
/// /mt send enter|pause|del|space|f4|f12|cntrl+&lt;letter&gt;|msg &lt;text&gt;: presses keys in the
/// game window, as Mag-Tools. A line starting with "/" is still sent as a chat command (what
/// this verb did before, which some metas use).
/// </summary>
private bool HandleMtSend(string[] parts, string fullCommand)
{
if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /mt send enter|pause|del|space|f4|f12|cntrl+<letter>|msg <text>"); return true; }
string arg = parts[2].ToLowerInvariant();
if (parts[2].StartsWith('/'))
{
if (Host.HasInvokeChatParser) Host.InvokeChatParser(string.Join(" ", parts, 2, parts.Length - 2));
return true;
}
if (!KeystrokesAllowed("/mt send")) return true;
if (!GameInput.Available) { ChatLine("[RynthAi] /mt send: the game window wasn't found."); return true; }
Log($"[RynthAi] /mt send {string.Join(" ", parts, 2, Math.Min(parts.Length - 2, 2))}: keys posted to the game window");
switch (arg)
{
case "enter": GameInput.SendEnter(); return true;
case "pause": GameInput.SendPause(); return true;
case "del": GameInput.SendDel(); return true;
case "space": GameInput.SendSpace(); return true;
case "f4": GameInput.SendF4(); return true;
case "f12": GameInput.SendF12(); return true;
case "msg":
int at = fullCommand.IndexOf(" msg ", StringComparison.OrdinalIgnoreCase);
if (at < 0 || at + 5 >= fullCommand.Length) { ChatLine("[RynthAi] Usage: /mt send msg <text>"); return true; }
GameInput.SendMsg(fullCommand[(at + 5)..]);
return true;
}
if (arg.StartsWith("cntrl+", StringComparison.Ordinal) && arg.Length >= 7)
{
GameInput.SendCntrl(arg[6]);
return true;
}
ChatLine("[RynthAi] Usage: /mt send enter|pause|del|space|f4|f12|cntrl+<letter>|msg <text>");
return true;
}
// ── jump ─────────────────────────────────────────────────────────────────────
/// <summary>/mt jump[w|z|x|c] [ms] and /mt sjump... (shift): RynthAi's jumper (the engine's own
/// jump), else the keys as Mag-Tools.</summary>
private bool HandleMtJump(string cmd, string[] parts)
{
bool shift = cmd.StartsWith("sjump", StringComparison.Ordinal);
string suffix = cmd[(shift ? 5 : 4)..];
bool w = suffix.Contains('w'), z = suffix.Contains('z'), x = suffix.Contains('x'), c = suffix.Contains('c');
int ms = 0;
if (parts.Length >= 3) int.TryParse(parts[2], out ms);
ms = Math.Clamp(ms, 0, 1000);
string letters = (w ? "w" : "") + (x ? "x" : "") + (z ? "z" : "") + (c ? "c" : "") + (shift ? "s" : "");
if (_jumper != null && _jumper.Start(letters, null, ms)) return true;
if (_jumper?.IsBusy == true) return true; // it said so in chat
if (!KeystrokesAllowed("/mt jump (keys)")) return true;
if (!GameInput.Available) { ChatLine("[RynthAi] /mt jump: no jump hook and no game window."); return true; }
GameInput.SendSpace(ms, shift, w, z, x, c);
return true;
}
// ── trade ────────────────────────────────────────────────────────────────────
/// <summary>/mt trade add|addp &lt;item&gt; | accept | decline | reset | end.</summary>
private bool HandleMtTrade(string[] parts)
{
if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /mt trade add|addp <item> | accept | decline | reset | end"); return true; }
string sub = parts[2].ToLowerInvariant();
// Completing a trade is only ever a running meta's doing (checked before anything else).
if (sub == "accept" && !RequireRunningMeta("/mt trade accept")) return true;
if (!Host.HasTrade) { ChatLine("[RynthAi] Trading needs a newer RynthCore engine."); return true; }
switch (sub)
{
case "add":
case "addp":
{
if (parts.Length < 4) { ChatLine($"[RynthAi] Usage: /mt trade {sub} <item>"); return true; }
string name = string.Join(" ", parts, 3, parts.Length - 3);
var item = FindObject(name, inv: true, land: false, partial: sub == "addp");
if (item == null) { ChatLine($"[RynthAi] Item not found: '{name}'"); return true; }
ChatLine(Host.TradeAdd(unchecked((uint)item.Id))
? $"[RynthAi] Added {item.Name} to the trade." : "[RynthAi] Could not add it to the trade.");
return true;
}
case "accept":
Log("[RynthAi] /mt trade accept (from the running meta)");
Host.TradeAccept();
return true;
case "decline": Host.TradeDecline(); return true;
case "reset": Host.TradeReset(); return true;
case "end": Host.TradeClose(); return true;
default:
ChatLine("[RynthAi] Usage: /mt trade add|addp <item> | accept | decline | reset | end");
return true;
}
}
// ── vendor ───────────────────────────────────────────────────────────────────
/// <summary>
/// /mt vendor addbuy|addbuyp &lt;item&gt; [count] | addsell|addsellp &lt;item&gt; | buy | clearbuy | sell |
/// clearsell, with a vendor open: lists kept here, sent in one transaction by buy / sell.
/// </summary>
private bool HandleMtVendor(string[] parts)
{
const string usage = "[RynthAi] Usage: /mt vendor addbuy|addbuyp <item> [count] | addsell|addsellp <item> | buy | clearbuy | sell | clearsell";
if (parts.Length < 3) { ChatLine(usage); return true; }
// Spending or selling is only ever a running meta's doing (checked before anything else).
string verb = parts[2].ToLowerInvariant();
if (verb == "buy" && !RequireRunningMeta("/mt vendor buy")) return true;
if (verb == "sell" && !RequireRunningMeta("/mt vendor sell")) return true;
if (!Host.HasVendorTrade) { ChatLine("[RynthAi] Vendor trading needs a newer RynthCore engine."); return true; }
if (!Host.TryGetVendorInfo(out VendorInfo info) || info.VendorId == 0)
{
ChatLine("[RynthAi] No vendor is open.");
return true;
}
string sub = parts[2].ToLowerInvariant();
switch (sub)
{
case "addbuy":
case "addbuyp":
{
if (parts.Length < 4) { ChatLine($"[RynthAi] Usage: /mt vendor {sub} <item> [count]"); return true; }
var words = parts.Skip(3).ToList();
int count = 1;
if (words.Count > 1 && int.TryParse(words[^1], out int n) && n > 0) { count = n; words.RemoveAt(words.Count - 1); }
string name = string.Join(" ", words);
bool partial = sub == "addbuyp";
VendorItem? item = Host.GetVendorItems().FirstOrDefault(v => partial
? v.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0
: string.Equals(v.Name, name, StringComparison.OrdinalIgnoreCase));
if (item == null) { ChatLine($"[RynthAi] {info.Name} doesn't sell '{name}'."); return true; }
_mtBuyList.Add((item.ObjectId, item.Name, count));
ChatLine($"[RynthAi] Buy list: {count} x {item.Name} ({_mtBuyList.Count} entr{(_mtBuyList.Count == 1 ? "y" : "ies")}).");
return true;
}
case "addsell":
case "addsellp":
{
if (parts.Length < 4) { ChatLine($"[RynthAi] Usage: /mt vendor {sub} <item>"); return true; }
string name = string.Join(" ", parts, 3, parts.Length - 3);
var item = FindObject(name, inv: true, land: false, partial: sub == "addsellp");
if (item == null) { ChatLine($"[RynthAi] Item not found: '{name}'"); return true; }
uint id = unchecked((uint)item.Id);
if (!_mtSellList.Any(s => s.Id == id)) _mtSellList.Add((id, item.Name));
ChatLine($"[RynthAi] Sell list: {item.Name} ({_mtSellList.Count} item(s)).");
return true;
}
case "buy":
{
if (_mtBuyList.Count == 0) { ChatLine("[RynthAi] The buy list is empty (/mt vendor addbuy <item> [count])."); return true; }
var entries = _mtBuyList.Select(b => new VendorTradeEntryNative(b.Id, b.Amount)).ToList();
Log($"[RynthAi] /mt vendor buy (from the running meta): {_mtBuyList.Count} entr{(_mtBuyList.Count == 1 ? "y" : "ies")} from {info.Name} 0x{info.VendorId:X8}: "
+ string.Join(", ", _mtBuyList.Select(b => $"{b.Amount} x {b.Name}")));
uint sent = Host.VendorBuy(info.VendorId, entries);
ChatLine(sent != 0 ? $"[RynthAi] Buying {_mtBuyList.Count} entr{(_mtBuyList.Count == 1 ? "y" : "ies")} from {info.Name}."
: "[RynthAi] The buy could not be sent.");
if (sent != 0) _mtBuyList.Clear();
return true;
}
case "clearbuy":
_mtBuyList.Clear();
ChatLine("[RynthAi] Buy list cleared.");
return true;
case "sell":
{
if (_mtSellList.Count == 0) { ChatLine("[RynthAi] The sell list is empty (/mt vendor addsell <item>)."); return true; }
// Checked again now, not only when the item was listed: it may have been worn since,
// and RynthAi's own gear and consumables are never sold by a meta.
var toSell = new List<(uint Id, string Name)>();
foreach (var (sid, sname) in _mtSellList)
{
WorldObject? so = _objectCache?[unchecked((int)sid)];
string? why = so == null ? null : ItemProtectionReason(so, includeLootKeep: false);
if (why != null) Log($"[RynthAi] /mt vendor sell: skipped {sname} 0x{sid:X8} ({why}).");
else toSell.Add((sid, sname));
}
if (toSell.Count == 0)
{
_mtSellList.Clear();
ChatLine("[RynthAi] Nothing left to sell: every listed item is protected.");
return true;
}
Log($"[RynthAi] /mt vendor sell (from the running meta): {toSell.Count} item(s) to {info.Name} 0x{info.VendorId:X8}: "
+ string.Join(", ", toSell.Select(s => s.Name)));
uint sent = Host.VendorSell(info.VendorId, toSell.Select(s => s.Id).ToList());
ChatLine(sent != 0 ? $"[RynthAi] Selling {toSell.Count} item(s) to {info.Name}." : "[RynthAi] The sell could not be sent.");
if (sent != 0) _mtSellList.Clear();
return true;
}
case "clearsell":
_mtSellList.Clear();
ChatLine("[RynthAi] Sell list cleared.");
return true;
default:
ChatLine(usage);
return true;
}
}
/// <summary>
/// Why a meta verb must not give or sell this item, or null when it may. Equipped gear, the
/// items RynthAi itself uses (the Weapons and Consumables lists, every monster rule's weapon and
/// off hand) and items the server won't let go (attuned, retained) are always protected.
/// <paramref name="includeLootKeep"/> adds the active loot profile's Keep / Keep # rules.
/// </summary>
internal string? ItemProtectionReason(WorldObject wo, bool includeLootKeep)
{
if (WorldObjectCache.IsWieldedByPlayer(Host, wo)) return "equipped";
var s = _dashboard?.Settings;
if (s != null)
{
try
{
foreach (var r in s.ItemRules.ToList()) if (r.Id == wo.Id) return "on RynthAi's Weapons list";
foreach (var c in s.ConsumableRules.ToList()) if (c.Id == wo.Id) return "on RynthAi's Consumables list";
foreach (var m in s.MonsterRules.ToList())
if (m.WeaponId == wo.Id || m.OffhandId == wo.Id) return "a monster rule's weapon";
}
catch { return "RynthAi's item lists could not be read"; }
}
if (wo.Values(114 /* Attuned */, 0) > 0) return "attuned";
uint id = unchecked((uint)wo.Id);
if (Host.HasGetObjectBitfield && Host.TryGetObjectBitfield(id, out uint bf) && (bf & 0x01000000u) != 0) return "retained";
if (Host.HasGetObjectBoolProperty && Host.TryGetObjectBoolProperty(id, 91 /* Retained */, out bool retained) && retained) return "retained";
if (includeLootKeep && IsKeptByLootProfile(wo)) return "kept by the loot profile";
return null;
}
/// <summary>The vendor closed: its buy / sell lists no longer mean anything.</summary>
private void ClearMtVendorLists()
{
_mtBuyList.Clear();
_mtSellList.Clear();
}
// ── dumpspells ───────────────────────────────────────────────────────────────
/// <summary>/mt dumpspells: the spell table to RynthAi's folder (spelldump.txt: id, name, family, difficulty).</summary>
private bool HandleMtDumpSpells()
{
try
{
Dictionary<string, int> byName = SpellDatabase.BuildNameToIdMap();
var rows = byName.Select(kv => (Id: kv.Value, Name: kv.Key)).Distinct().OrderBy(r => r.Id).ToList();
string path = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "spelldump.txt");
using (var w = new StreamWriter(path, false, new System.Text.UTF8Encoding(false)))
{
w.WriteLine("Id\tName\tFamily\tDifficulty");
foreach (var (id, name) in rows)
{
SpellDatabase.TryGetSpellMeta(id, out int family, out int difficulty);
w.WriteLine($"{id}\t{name}\t{family}\t{difficulty}");
}
}
ChatLine($"[RynthAi] {rows.Count} spells written to {path}");
}
catch (Exception ex) { ChatLine($"[RynthAi] /mt dumpspells failed: {ex.Message}"); }
return true;
}
// ── /ra equipfor (VTank /vt equipitemsfor) ───────────────────────────────────
/// <summary>
/// /ra equipfor &lt;monster&gt; (VTank's /vt equipitemsfor): wield the weapon and off hand set on that
/// monster's rule (the rule named exactly, else one whose name the monster's contains, else
/// Default). Items already wielded are left; a rule with no set weapon says so (combat picks
/// one itself when it fights).
/// </summary>
private void HandleEquipForCommand(string[] parts)
{
if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /ra equipfor <monster name>"); return; }
var rules = _dashboard?.Settings?.MonsterRules;
if (rules == null || rules.Count == 0) { ChatLine("[RynthAi] No monster rules loaded."); return; }
string monster = string.Join(" ", parts, 2, parts.Length - 2).Trim();
var rule = rules.FirstOrDefault(r => string.Equals(r.Name, monster, StringComparison.OrdinalIgnoreCase))
?? rules.Where(r => !string.Equals(r.Name, "Default", StringComparison.OrdinalIgnoreCase)
&& r.Name.Length > 0 && monster.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0)
.OrderByDescending(r => r.Name.Length).FirstOrDefault()
?? rules.FirstOrDefault(r => string.Equals(r.Name, "Default", StringComparison.OrdinalIgnoreCase));
if (rule == null) { ChatLine($"[RynthAi] No monster rule for '{monster}'."); return; }
var ids = new List<int>();
if (rule.WeaponId != 0) ids.Add(rule.WeaponId);
if (rule.OffhandId != 0) ids.Add(rule.OffhandId);
if (ids.Count == 0)
{
ChatLine($"[RynthAi] '{rule.Name}' has no set weapon (combat picks one when it fights '{monster}').");
return;
}
if (!Host.HasUseObject) { ChatLine("[RynthAi] UseObject not available."); return; }
int sent = 0;
foreach (int id in ids)
{
var wo = _objectCache?[id];
if (wo == null) { ChatLine($"[RynthAi] '{rule.Name}': item 0x{(uint)id:X8} isn't carried."); continue; }
if (wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0) continue; // already wielded
Host.UseFor(unchecked((uint)id), "Command", "/ra equipfor", UseKind.Asked);
sent++;
}
ChatLine(sent > 0 ? $"[RynthAi] Equipping for '{monster}' ({rule.Name}): {sent} item(s)."
: $"[RynthAi] '{rule.Name}' gear for '{monster}' is already wielded.");
}
// ── click, cursor, movement, strafe, client ─────────────────────────────────
/// <summary>/mt click ok|yes|no|&lt;x&gt; &lt;y&gt;: a click in the game window (window coordinates).</summary>
private bool HandleMtClick(string[] parts)
{
if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /mt click ok|yes|no|<x> <y>"); return true; }
if (!KeystrokesAllowed("/mt click")) return true;
if (!GameInput.Available) { ChatLine("[RynthAi] /mt click: the game window wasn't found."); return true; }
switch (parts[2].ToLowerInvariant())
{
case "ok": GameInput.ClickOK(); return true;
case "yes": GameInput.ClickYes(); return true;
case "no": GameInput.ClickNo(); return true;
}
if (parts.Length >= 4 && int.TryParse(parts[2], out int x) && int.TryParse(parts[3], out int y))
{
GameInput.SendMouseClick(x, y);
return true;
}
ChatLine("[RynthAi] Usage: /mt click ok|yes|no|<x> <y>");
return true;
}
/// <summary>/mt get xy (and ub-IT's /mt cursor): the cursor relative to the game window.</summary>
private bool HandleMtCursor()
{
ChatLine(GameInput.TryCursorInWindow(out int x, out int y)
? $"[RynthAi] Current cursor position: {x},{y}"
: "[RynthAi] The cursor position couldn't be read.");
return true;
}
/// <summary>/mt movement &lt;key&gt; &lt;ms&gt;: hold a movement key (AC's keymap letter) for ms.</summary>
private bool HandleMtMovement(string[] parts)
{
if (parts.Length != 4 || parts[2].Length != 1 || !int.TryParse(parts[3], out int ms) || ms < 0)
{
ChatLine("[RynthAi] Usage: /mt movement <key> <ms> (e.g. /mt movement w 1500)");
return true;
}
if (!KeystrokesAllowed("/mt movement")) return true;
if (!GameInput.Available) { ChatLine("[RynthAi] /mt movement: the game window wasn't found."); return true; }
GameInput.SendMovement(parts[2][0], ms);
return true;
}
/// <summary>ub-IT's /mt strafe left|l|right|r &lt;ms&gt;: hold the side-step key (Z / C) for ms.</summary>
private bool HandleMtStrafe(string[] parts)
{
if (parts.Length != 4 || !int.TryParse(parts[3], out int ms) || ms < 0)
{
ChatLine("[RynthAi] Usage: /mt strafe left|l|right|r <ms>");
return true;
}
char key = parts[2].ToLowerInvariant() switch { "left" or "l" => 'z', "right" or "r" => 'c', _ => '\0' };
if (key == '\0') { ChatLine("[RynthAi] /mt strafe: left, l, right or r."); return true; }
if (!KeystrokesAllowed("/mt strafe")) return true;
if (!GameInput.Available) { ChatLine("[RynthAi] /mt strafe: the game window wasn't found."); return true; }
GameInput.SendMovement(key, ms);
return true;
}
/// <summary>/mt client minimize|restore (ub-IT's frame apply|restore points to Settings > Display).</summary>
private bool HandleMtClient(string[] parts)
{
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : "";
switch (sub)
{
case "minimize": if (KeystrokesAllowed("/mt client")) GameInput.Minimize(); return true;
case "restore": if (KeystrokesAllowed("/mt client")) GameInput.Restore(); return true;
case "frame":
ChatLine("[RynthAi] The window frame is RynthCore's: Settings > Display (Borderless Windowed, Reset Window Borders) or /rc window reset.");
return true;
default:
ChatLine("[RynthAi] Usage: /mt client minimize | restore");
return true;
}
}
}

View file

@ -92,14 +92,14 @@ public sealed partial class RynthAiPlugin
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc quit");
return true;
// ── Send a chat line / slash command (VTank /mt send) ────────────
// ── Keys in the game window (Mag-Tools /mt send); a "/" line is still sent as a command ──
case "send":
if (parts.Length >= 3 && Host.HasInvokeChatParser)
Host.InvokeChatParser(string.Join(" ", parts, 2, parts.Length - 2));
return true;
return HandleMtSend(parts, fullCommand);
default:
return false;
// jump, trade, vendor, autopack, dumpspells, click, get xy, movement, client, config,
// strafe, test (MagToolsCommands.Extra.cs).
return TryHandleMtExtra(cmd, parts, fullCommand);
}
}
@ -302,11 +302,45 @@ public sealed partial class RynthAiPlugin
private bool HandleMtFace(string[] parts)
{
// /mt face <degrees>
if (parts.Length < 3 || !float.TryParse(parts[2], out float degrees)) return false;
if (!Host.HasTurnToHeading) { ChatLine("[RynthAi] TurnToHeading not available."); return true; }
// /mt face <degrees> (Mag-Tools) and /ub face <degrees> (ub-IT, translated here). The heading
// may have decimals (getheadingto[] gives them), read the same on every PC; or a coordinate
// ("42.1N, 33.6E") to face that spot.
if (parts.Length < 3) return false;
string arg = string.Join(" ", parts, 2, parts.Length - 2).Trim();
double heading;
if (double.TryParse(arg, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double deg))
heading = deg;
else if (!TryHeadingToCoords(arg, out heading))
return false;
Host.TurnToHeadingBy("Command", degrees);
// The jumper holds navigation while it turns (nav would turn the character back) and turns
// again until it faces the heading, as ub-IT does; without it, one plain turn.
if (_jumper != null) _jumper.Face(heading);
else if (Host.HasTurnToHeading) Host.TurnToHeadingBy("Command", (float)(((heading % 360) + 360) % 360));
else ChatLine("[RynthAi] TurnToHeading not available.");
return true;
}
private static readonly System.Text.RegularExpressions.Regex FaceCoordsRx = new(
@"^\s*(?<ns>\d+(?:\.\d+)?)\s*(?<nsc>[NnSs])[\s,]*(?<ew>\d+(?:\.\d+)?)\s*(?<ewc>[EeWw])\s*$",
System.Text.RegularExpressions.RegexOptions.CultureInvariant);
/// <summary>
/// The heading from the character to a "42.1N, 33.6E" coordinate (AC's: 0 north, 90 east, the
/// same as getheadingto[]). False when the text isn't a coordinate or our position is unknown.
/// </summary>
private bool TryHeadingToCoords(string text, out double heading)
{
heading = 0;
var m = FaceCoordsRx.Match(text);
if (!m.Success || !NavCoordinateHelper.TryGetNavCoords(Host, out double myNs, out double myEw)) return false;
var inv = System.Globalization.CultureInfo.InvariantCulture;
double ns = double.Parse(m.Groups["ns"].Value, inv) * (char.ToUpperInvariant(m.Groups["nsc"].Value[0]) == 'S' ? -1 : 1);
double ew = double.Parse(m.Groups["ew"].Value, inv) * (char.ToUpperInvariant(m.Groups["ewc"].Value[0]) == 'W' ? -1 : 1);
double dNs = ns - myNs, dEw = ew - myEw;
if (Math.Abs(dNs) < 1e-6 && Math.Abs(dEw) < 1e-6) return false;
heading = Math.Atan2(dEw, dNs) * (180.0 / Math.PI);
if (heading < 0) heading += 360.0;
return true;
}

View file

@ -996,7 +996,10 @@ internal sealed class ManaStoneManager
if (_tapTargetCooldownUntil.TryGetValue(item.Id, out long until) && now < until)
continue;
// Skip equipped items
// Skip equipped items: worn per the tracker (a wield record can read 0 for worn gear), or
// per the item's own slot.
if (EquippedState.IsWielded(_host, item.Id) == true)
continue;
if (_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield)
&& wield != 0)
continue;
@ -1060,12 +1063,22 @@ internal sealed class ManaStoneManager
if (IsManaStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
// The live slot read can fail off AC's thread; the cache's copy (what /ra wielded
// uses) is the fallback.
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield) || wield == 0)
wield = item.Values(LongValueKey.CurrentWieldedLocation, 0);
if (wield == 0)
continue;
// What is worn: the engine's tracker of the server's wield/move messages (API v87) when it
// has one. An item's own wield record goes stale once it is moved to a pack: those counted
// as worn ("worn=41" for a character wearing 20, 2026-10-20) and took the one appraisal a
// pass, while gear really worn whose mana couldn't be read waited, skipped as unreadable.
// Without a tracker: the live slot read, then the cache's copy (what /ra wielded uses).
if (EquippedState.IsWielded(_host, item.Id) is bool tracked)
{
if (!tracked) continue;
}
else
{
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield) || wield == 0)
wield = item.Values(LongValueKey.CurrentWieldedLocation, 0);
if (wield == 0)
continue;
}
worn++;
// Only items that actually consume mana matter. Off AC's thread an item's mana is

View file

@ -0,0 +1,373 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.Meta;
/// <summary>
/// ub-IT expression functions that were missing (2026-10-18 meta-compatibility pass), with
/// ub-IT's names, arguments and return values. Where RynthAi has no matching data (character
/// select, Decal views, ub-IT's own HUDs) the function still answers, with the value ub-IT gives
/// when there is nothing to report, so an expression that calls it keeps working.
/// </summary>
internal sealed partial class ExpressionEngine
{
/// <summary>Corpses this character has opened (the plugin's loot bookkeeping), for
/// hascorpsebeenopenedbyme[] and getcorpsesunopenedbyme[]. Null: none known.</summary>
internal Func<int, bool>? CorpseOpenedByMe { get; set; }
/// <summary>The meta manager's '/vt opt set' (VTank names, distances in landblock units, the
/// special options), for vtsetsetting[]; null: the plain settings map (an engine without one).</summary>
internal Func<string, string, bool>? VtOptionSetter { get; set; }
/// <summary>The meta manager's '/vt opt get' (values read back in VTank's units), for vtgetsetting[].</summary>
internal Func<string, string?>? VtOptionGetter { get; set; }
// getcooldownexpiration: shared cooldowns are enchantments whose spell id has this bit.
private const uint CooldownSpellFlag = 0x8000;
// ub-IT's QuestRefreshCooldownSeconds default (canrefreshquests[]).
private const double QuestRefreshCooldownSeconds = 60;
// Character property ids (PropertyInt64): total experience, available luminance.
private const uint QuadTotalExperience = 1;
private const uint QuadAvailableLuminance = 6;
// PropertyInt StackSize.
private const uint IntStackSize = 12;
// XP meter (xpreset/xpmeter/xpduration/xptotal/lumtotal/xpavg/lumavg). Starts on the
// first call after login or a reset; luminance counts gains only (spending isn't earning).
private long _xpStartMs = -1;
private long _xpBase, _lumLast, _lumGained;
// Functions with no RynthAi data already logged (one line each per session).
private readonly HashSet<string> _ubNoDataLogged = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// The functions above. Returns false for any other name, so the caller's unknown-function
/// fallback still logs real typos.
/// </summary>
private bool TryEvalUbCompat(string funcName, List<string> rawArgs, Func<int, string> A, out string value)
{
value = funcName switch
{
// ── Inventory actions (1 = attempted, 0 = busy or not possible) ──────
"actiontrymove" => EvalActionTryMove(A(0), A(1), rawArgs.Count > 2 ? A(2) : "0", rawArgs.Count > 3 ? A(3) : "1"),
"actiontrysplit" => EvalActionTrySplit(A(0), A(1), rawArgs.Count > 2 ? A(2) : "", rawArgs.Count > 3 ? A(3) : "0"),
"actiontrydrop" => NoData("actiontrydrop", "0"),
// ── Vitals of an object (current values; the selected target or yourself) ──
"wobjectgethealthvalue" => EvalWobjectVital(A(0), 0),
"wobjectgetstaminavalue" => EvalWobjectVital(A(0), 1),
"wobjectgetmanavalue" => EvalWobjectVital(A(0), 2),
// ── Corpses ──────────────────────────────────────────────────────────
"hascorpsebeenopenedbyme" => EvalCorpseOpenedByMe(A(0)),
"getcorpsesunopenedbyme" => EvalCorpsesUnopenedByMe(),
// ── Casting, cooldowns, spell data ───────────────────────────────────
"iscasting" => _host.HasGetCastBusyState && _host.GetCastBusyState() != 0 ? "1" : "0",
"getcooldownexpiration" => EvalCooldownExpiration(A(0)),
"spelldata" => EvalSpellData(A(0)),
// ── Macro state and delayed expressions ──────────────────────────────
"vtmacroenabled" => _settings?.IsMacroRunning == true ? "1" : "0",
"clearexec" => EvalClearExec(A(0)),
// ── Quests (myquests throttle; ACECustom quest bonus lives in RynthILT) ──
"canrefreshquests" => EvalCanRefreshQuests(),
"testquestbonus" => NoData("testquestbonus", "0"),
"isrefreshingquestbonuses" => "0",
"enlightenmentmaterials" => EvalEnlightenmentTokens(A(0), A(1)),
// ── XP meter ─────────────────────────────────────────────────────────
"xpreset" => EvalXpReset(),
"xpduration" => FormatNumber(XpSeconds()),
"xptotal" => FormatNumber(XpTotal()),
"lumtotal" => FormatNumber(LumTotal()),
"xpavg" => FormatNumber(PerHour(XpTotal())),
"lumavg" => FormatNumber(PerHour(LumTotal())),
"xpmeter" => EvalXpMeterText(),
// ── No RynthAi equivalent: ub-IT's "nothing here" values ─────────────
"getcharacterindex" => NoData("getcharacterindex", "-1"),
"setnextlogin" => NoData("setnextlogin", "0"),
"clearnextlogin" => NoData("clearnextlogin", "1"),
"netclients" => NoData("netclients", "[]"),
"statushud" => NoData("statushud", "1"),
"statushudcolored" => NoData("statushudcolored", "1"),
// Decal views: none exist here, so no view is found or shown.
"uiviewexists" => NoData("uiviewexists", "0"),
"uiviewvisible" => NoData("uiviewvisible", "0"),
"uisetvisible" => NoData("uisetvisible", "0"),
"uisetlabel" => NoData("uisetlabel", "0"),
"uigetcontrol" => NoData("uigetcontrol", "0"),
_ => null!,
};
return value != null;
}
/// <summary>The fixed answer of a function RynthAi has no data for; logged once per session.</summary>
private string NoData(string funcName, string result)
{
if (_ubNoDataLogged.Add(funcName))
_host.Log($"[RynthAi] Expression {funcName}[]: ub-IT feature with no RynthAi equivalent; returns {result}.");
return result;
}
// ── Inventory actions ────────────────────────────────────────────────────
private bool IsBusy() => _host.HasGetBusyState && _host.GetBusyState() > 0;
private int StackSizeOf(uint id)
{
if (_worldObjectCache != null)
{
int n = _worldObjectCache.GetIntProperty(unchecked((int)id), IntStackSize, 0);
if (n > 0) return n;
}
return 1;
}
/// <summary>actiontrymove[obj, container, slot=0, addToStack=1]: into a stack of the same
/// name in that container when there is one (and addToStack), else into the slot.</summary>
private string EvalActionTryMove(string objArg, string destArg, string slotArg, string stackArg)
{
if (!TryParseWobjectHandle(objArg, out uint id, out _) || id == 0) return "0";
if (!TryParseWobjectHandle(destArg, out uint dest, out _) || dest == 0) return "0";
if (IsBusy()) return "0";
if (ToBool(stackArg) && _worldObjectCache != null && _host.HasMergeStackInternal)
{
string name = _worldObjectCache[unchecked((int)id)]?.Name ?? "";
foreach (var wo in _worldObjectCache.GetContainedItems(unchecked((int)dest)))
{
if (unchecked((uint)wo.Id) == id || !string.Equals(wo.Name, name, StringComparison.Ordinal)) continue;
if (StackSizeOf(unchecked((uint)wo.Id)) <= 1 && StackSizeOf(id) <= 1) continue;
return _host.MergeStackInternal(id, unchecked((uint)wo.Id)) ? "1" : "0";
}
}
if (!_host.HasMoveItemInternal) return "0";
int slot = (int)Math.Max(0, ToDouble(slotArg));
return _host.MoveItemInternal(id, dest, slot, StackSizeOf(id)) ? "1" : "0";
}
/// <summary>actiontrysplit[obj, newStackSize, container=player, slot=0]: splits newStackSize off the stack.</summary>
private string EvalActionTrySplit(string objArg, string countArg, string destArg, string slotArg)
{
if (!TryParseWobjectHandle(objArg, out uint id, out _) || id == 0) return "0";
int count = (int)ToDouble(countArg);
if (count < 1 || count >= StackSizeOf(id)) return "0";
uint dest = TryParseWobjectHandle(destArg, out uint d, out _) && d != 0 ? d : _playerId;
if (dest == 0 || IsBusy() || !_host.HasSplitStackInternal) return "0";
int slot = (int)Math.Max(0, ToDouble(slotArg));
return _host.SplitStackInternal(id, dest, slot, count) ? "1" : "0";
}
// ── Vitals ───────────────────────────────────────────────────────────────
/// <summary>Current health (0), stamina (1) or mana (2) of the object; -1 when unknown. The
/// game reports these for yourself and for the target you've selected (as ub-IT notes).</summary>
private string EvalWobjectVital(string objArg, int which)
{
if (!TryParseWobjectHandle(objArg, out uint id, out _) || id == 0) return "-1";
uint hp, st, mp;
if (id == _playerId)
{
if (!_host.TryGetPlayerVitals(out hp, out _, out st, out _, out mp, out _)) return "-1";
}
else if (!_host.TryGetTargetVitals(id, out hp, out _, out st, out _, out mp, out _))
{
return "-1";
}
uint v = which switch { 0 => hp, 1 => st, _ => mp };
return v.ToString(CultureInfo.InvariantCulture);
}
// ── Corpses ──────────────────────────────────────────────────────────────
private string EvalCorpseOpenedByMe(string objArg)
{
if (!TryParseWobjectHandle(objArg, out uint id, out _) || id == 0) return "0";
return CorpseOpenedByMe?.Invoke(unchecked((int)id)) == true ? "1" : "0";
}
/// <summary>Corpses in view this character hasn't opened, as a list of objects.</summary>
private string EvalCorpsesUnopenedByMe()
{
if (_worldObjectCache == null) return "[]";
var items = new List<string>();
var seen = new HashSet<int>();
foreach (var wo in _worldObjectCache.GetLandscape())
{
if (wo.ObjectClass != AcObjectClass.Corpse || !seen.Add(wo.Id)) continue;
if (CorpseOpenedByMe?.Invoke(wo.Id) == true) continue;
items.Add(MakeWobjectHandle(unchecked((uint)wo.Id), wo.Name));
}
return NewList(items);
}
// ── Casting, cooldowns, spell data ───────────────────────────────────────
/// <summary>Seconds until shared cooldown <paramref name="idArg"/> ends; 0 when it isn't running.</summary>
private string EvalCooldownExpiration(string idArg)
{
int want = (int)ToDouble(idArg);
if (want <= 0 || !_host.HasReadPlayerEnchantments || !_host.HasGetServerTime) return "0";
double now = _host.GetServerTime();
if (now <= 0) return "0";
const int Max = 512;
uint[] ids = new uint[Max];
double[] expiry = new double[Max];
int count = _host.ReadPlayerEnchantments(ids, expiry, Max);
for (int i = 0; i < count; i++)
{
if ((ids[i] & CooldownSpellFlag) == 0 || (ids[i] & 0xFFF) != want) continue;
double left = expiry[i] - now;
return left > 0 ? ((int)Math.Ceiling(left)).ToString(CultureInfo.InvariantCulture) : "0";
}
return "0";
}
/// <summary>spelldata[id]: a dictionary of what RynthAi's spell table knows (Id, Name, Family,
/// Difficulty, Category, Power, Level). Empty for an unknown spell, as in ub-IT.</summary>
private string EvalSpellData(string idArg)
{
int id = (int)ToDouble(idArg);
var d = new Dictionary<string, string>(StringComparer.Ordinal);
if (id > 0 && SpellDatabase.HasSpell(id))
{
d["Id"] = id.ToString(CultureInfo.InvariantCulture);
d["Name"] = SpellDatabase.GetSpellName(id);
if (SpellDatabase.TryGetSpellMeta(id, out int family, out int difficulty))
{
d["Family"] = family.ToString(CultureInfo.InvariantCulture);
d["Difficulty"] = difficulty.ToString(CultureInfo.InvariantCulture);
}
if (SpellDatabase.TryGetCategoryAndPower(id, out int category, out int power))
{
d["Category"] = category.ToString(CultureInfo.InvariantCulture);
d["Power"] = power.ToString(CultureInfo.InvariantCulture);
d["Level"] = SpellDatabase.LevelFromPower(power).ToString(CultureInfo.InvariantCulture);
}
}
return NewDict(d);
}
// ── Delayed expressions ──────────────────────────────────────────────────
/// <summary>clearexec[id]: cancels the delayexec that returned that id. 1 if one was pending.</summary>
private string EvalClearExec(string idArg)
{
long id = (long)ToDouble(idArg);
int removed = _delayedExecs.RemoveAll(e => e.Id == id);
return removed > 0 ? "1" : "0";
}
// ── Quests ───────────────────────────────────────────────────────────────
private string EvalCanRefreshQuests()
{
if (_questTracker == null) return "1";
if (_questTracker.IsRefreshing) return "0";
return (DateTime.UtcNow - _questTracker.LastRefreshUtc).TotalSeconds >= QuestRefreshCooldownSeconds ? "1" : "0";
}
/// <summary>enlightenmentmaterials[current, target]: ub-IT's token count. Levels 6-150 cost
/// (level - 5) tokens each; levels 1-5 cost none and later levels cost other items.</summary>
private static string EvalEnlightenmentTokens(string curArg, string tgtArg)
{
int cur = (int)ToDouble(curArg), tgt = (int)ToDouble(tgtArg);
long tokens = 0;
for (int level = Math.Max(cur + 1, 6); level <= Math.Min(tgt, 150); level++)
tokens += level - 5;
return tokens.ToString(CultureInfo.InvariantCulture);
}
// ── XP meter ─────────────────────────────────────────────────────────────
private long ReadQuad(uint stype)
=> _playerId != 0 && _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(_playerId, stype, out long v) ? v : 0;
/// <summary>Starts the meter on first use and folds in luminance gained since the last look.</summary>
private void SampleXpMeter()
{
long lum = ReadQuad(QuadAvailableLuminance);
if (_xpStartMs < 0)
{
_xpStartMs = TickMs();
_xpBase = ReadQuad(QuadTotalExperience);
_lumLast = lum;
_lumGained = 0;
return;
}
if (lum > _lumLast) _lumGained += lum - _lumLast;
_lumLast = lum;
}
/// <summary>Forgets the meter when the character changes (called from SetPlayerId).</summary>
private void ResetXpMeter() => _xpStartMs = -1;
private string EvalXpReset()
{
ResetXpMeter();
SampleXpMeter();
return "1";
}
private double XpSeconds()
{
SampleXpMeter();
return Math.Max(0, (TickMs() - _xpStartMs) / 1000.0);
}
private double XpTotal()
{
SampleXpMeter();
return Math.Max(0, ReadQuad(QuadTotalExperience) - _xpBase);
}
private double LumTotal()
{
SampleXpMeter();
return _lumGained;
}
private double PerHour(double amount)
{
double s = XpSeconds();
return s <= 0 ? 0 : amount / s * 3600;
}
/// <summary>ub-IT's meter text: "500m XP and 2k LUM, 51s, 35.39b XP/hr and 140k LUM/hr".</summary>
private string EvalXpMeterText()
{
double xp = XpTotal(), lum = LumTotal(), s = XpSeconds();
string head = lum > 0 ? $"{ShortNumber(xp)} XP and {ShortNumber(lum)} LUM" : $"{ShortNumber(xp)} XP";
string rate = lum > 0 ? $"{ShortNumber(PerHour(xp))} XP/hr and {ShortNumber(PerHour(lum))} LUM/hr" : $"{ShortNumber(PerHour(xp))} XP/hr";
return $"{head}, {ShortDuration(s)}, {rate}";
}
private static string FormatNumber(double v) => Math.Round(v, 2).ToString("0.##", CultureInfo.InvariantCulture);
/// <summary>1234 -> 1.23k, 5.6e8 -> 560m, as ub-IT's formatExperience.</summary>
private static string ShortNumber(double v)
{
string[] units = { "", "k", "m", "b", "t", "q" };
int u = 0;
while (Math.Abs(v) >= 1000 && u < units.Length - 1) { v /= 1000; u++; }
return (u == 0 ? Math.Round(v).ToString("0", CultureInfo.InvariantCulture)
: v.ToString("0.##", CultureInfo.InvariantCulture)) + units[u];
}
private static string ShortDuration(double seconds)
{
var t = TimeSpan.FromSeconds(Math.Max(0, seconds));
if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h {t.Minutes}m";
if (t.TotalMinutes >= 1) return $"{t.Minutes}m {t.Seconds}s";
return $"{t.Seconds}s";
}
}

View file

@ -33,7 +33,7 @@ namespace RynthCore.Plugin.RynthAi.Meta;
/// Lists are text ("[a,b]"); the list functions that change a list write it back to the
/// variable it came from. Dictionaries and stopwatches are handles ("D:0", "SW:0").
/// </summary>
internal sealed class ExpressionEngine
internal sealed partial class ExpressionEngine
{
private readonly RynthCoreHost _host;
private WorldObjectCache? _worldObjectCache;
@ -71,7 +71,7 @@ internal sealed class ExpressionEngine
if (_pvars != null) foreach (string v in _pvars.Values) Scan(v);
if (_gvars != null) foreach (string v in _gvars.Values) Scan(v);
foreach (string v in _options.Values) Scan(v);
foreach (var (_, expr) in _delayedExecs) Scan(expr);
foreach (var (_, _, expr) in _delayedExecs) Scan(expr);
while (todo.Count > 0)
foreach (var (k, v) in _dicts[todo.Dequeue()]) { Scan(k); Scan(v); }
@ -133,7 +133,8 @@ internal sealed class ExpressionEngine
// hot-reload to fire into a freed engine). Instance-scoped so a hot-reload
// discards pending execs. Single-threaded access (Evaluate and the pump
// both run on the plugin-tick thread) → no lock needed.
private readonly List<(long DueMs, string Expr)> _delayedExecs = new();
private readonly List<(long Id, long DueMs, string Expr)> _delayedExecs = new();
private long _nextDelayedExecId;
private uint _playerId;
private LegacyUiSettings? _settings;
@ -187,6 +188,7 @@ internal sealed class ExpressionEngine
FlushVars(force: true); // persist the old char's pending pvars first
_pvars = null;
_pvarPathCached = null;
ResetXpMeter();
}
_playerId = id;
}
@ -557,8 +559,12 @@ internal sealed class ExpressionEngine
// UB vtgetmeta[]: the loaded meta's name (file name without extension).
"vtgetmeta" or "ragetmeta" => string.IsNullOrEmpty(_settings?.CurrentMetaPath)
? "" : Path.GetFileNameWithoutExtension(_settings!.CurrentMetaPath),
"rasetsetting" or "vtsetsetting" => EvalVtSetSetting(Text(0), A(1)),
"ragetsetting" or "vtgetsetting" or "vtankgetsetting" => EvalVtGetSetting(Text(0)),
// vt*: VTank option names and units (landblock distances), the same as '/vt opt set|get';
// ra*: RynthAi's own setting names, as they are.
"vtsetsetting" => VtOptionSetter != null && Text(0).Length > 0 ? (VtOptionSetter(Text(0), A(1)) ? "1" : "0") : EvalVtSetSetting(Text(0), A(1)),
"vtgetsetting" or "vtankgetsetting" => VtOptionGetter != null && Text(0).Length > 0 ? VtOptionGetter(Text(0)) ?? "" : EvalVtGetSetting(Text(0)),
"rasetsetting" => EvalVtSetSetting(Text(0), A(1)),
"ragetsetting" => EvalVtGetSetting(Text(0)),
// ── Dynamic evaluation ────────────────────────────────────────────
"exec" => Evaluate(A(0)),
@ -583,7 +589,8 @@ internal sealed class ExpressionEngine
// "Strings support slices like arrays. ie test[1:]": a word that isn't a function,
// followed by [start:stop].
_ when TopLevelColon(argsStr) >= 0 => SliceBy(expr.Substring(0, lb).Trim(), argsStr),
_ => EvalUnknownFunction(funcName)
// ub-IT's remaining functions (ExpressionEngine.UbCompat.cs), then a real unknown.
_ => TryEvalUbCompat(funcName, rawArgs, A, out string ubValue) ? ubValue : EvalUnknownFunction(funcName)
};
}
@ -3681,6 +3688,7 @@ internal sealed class ExpressionEngine
["CorpseApproachRangeMin"] = (() => D(s.CorpseApproachRangeMin), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.CorpseApproachRangeMin = d; }),
["ManaStoneKeepCount"] = (() => I(s.ManaStoneKeepCount), v => { if (int.TryParse(v, out int i)) s.ManaStoneKeepCount = i; }),
["RebuffSecondsRemaining"] = (() => I(s.RebuffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffSecondsRemaining = i; }),
["BlacklistTimeoutSec"] = (() => I(s.BlacklistTimeoutSec), v => { if (double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) && d >= 0) s.BlacklistTimeoutSec = (int)Math.Round(d); }),
["RebuffTopOffSecondsRemaining"] = (() => I(s.RebuffTopOffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffTopOffSecondsRemaining = i; }),
["CastBuffsOverItemBuffs"] = (() => B(s.CastBuffsOverItemBuffs), v => s.CastBuffsOverItemBuffs = ToDouble(v) != 0),
["FastBuffChain"] = (() => B(s.FastBuffChain), v => s.FastBuffChain = ToDouble(v) != 0),
@ -3738,8 +3746,10 @@ internal sealed class ExpressionEngine
CultureInfo.InvariantCulture, out double delayMs))
delayMs = 0;
long ms = (long)Math.Max(0, delayMs);
_delayedExecs.Add((TickMs() + ms, exprArg));
return "1";
// ub-IT returns the job's id (for clearexec); ids start at 1 so the result stays true.
long id = ++_nextDelayedExecId;
_delayedExecs.Add((id, TickMs() + ms, exprArg));
return id.ToString(CultureInfo.InvariantCulture);
}
/// <summary>

View file

@ -658,7 +658,8 @@ ifthen[value, trueexpr, falseexpr]
delayexec[delay, text]
Schedules text to be evaluated as an expression after delay milliseconds.
Returns "1" immediately. The evaluation runs on a background thread —
Returns the job's id (1, 2, 3 ... as ub-IT), which clearexec[id] cancels. The
evaluation runs on a background thread —
avoid using delayexec with expressions that modify shared variables
concurrently with the meta tick loop.
delay: milliseconds (1 second = 1000).
@ -1690,6 +1691,23 @@ ragetsetting[setting]
Example: ragetsetting[MonsterRange] → "50"
Example: cnumber[ragetsetting[MonsterRange]] → 50 (as number)
vtsetsetting[option, value] / vtgetsetting[option]
The same as '/vt opt set|get': VTank option names and VTank units. A VTank
distance option (AttackDistance, ApproachDistance, DoorOpenRange, OpenDoorRange,
AttackRange, RingDistance, CorpseApproachRange[-Min|-Max], PetCustomRange,
NavCloseStopRange) given as a value up to 1 is landblock units (x240 = yards);
a value above 1 is taken as yards already. vtgetsetting reads such a distance
back in landblock units. No other option is scaled. rasetsetting/ragetsetting use
RynthAi's own names and units, always.
ub-IT functions answered here (ExpressionEngine.UbCompat.cs): actiontrymove, actiontrysplit,
actiontrydrop (always "0": nothing drops items), wobjectgethealthvalue / staminavalue /
manavalue, hascorpsebeenopenedbyme, getcorpsesunopenedbyme, iscasting, getcooldownexpiration,
spelldata, vtmacroenabled, clearexec, canrefreshquests, enlightenmentmaterials, xpreset /
xpmeter / xpduration / xptotal / lumtotal / xpavg / lumavg. Functions about ub-IT's own HUDs,
Decal views and character select (statushud, uiview*, getcharacterindex, netclients, ...)
answer with the value ub-IT gives when there is nothing to report.
Supported setting names:
Booleans: EnableCombat, EnableBuffing, EnableNavigation, EnableLooting,
EnableMeta, EnableRaycasting, EnableAutostack, EnableAutocram,

View file

@ -179,6 +179,15 @@ internal sealed class MetaManager
_expressions?.SetKillClock(clock);
}
// Corpses this character opened (the plugin's loot bookkeeping), for ub-IT's
// hascorpsebeenopenedbyme[] / getcorpsesunopenedbyme[].
private Func<int, bool>? _corpseOpenedByMe;
public void SetCorpseOpenedCheck(Func<int, bool>? check)
{
_corpseOpenedByMe = check;
if (_expressions != null) _expressions.CorpseOpenedByMe = check;
}
public void SetPlayerId(uint id)
{
_playerId = id;
@ -231,6 +240,10 @@ internal sealed class MetaManager
engine.SetSettings(_settings);
engine.SetCreatureStore(_creatureStore);
engine.SetKillClock(_killClock);
engine.CorpseOpenedByMe = _corpseOpenedByMe;
// vtsetsetting[] / vtgetsetting[] take VTank names and units, as '/vt opt set|get' does.
engine.VtOptionSetter = TrySetVtOption;
engine.VtOptionGetter = GetVtOption;
return engine;
}
@ -824,7 +837,20 @@ internal sealed class MetaManager
// ── Action execution ─────────────────────────────────────────────────────
// Depth of ExecuteAction on the call stack: a rule's action (a chat command, a chat expression,
// an expression action) is running. The plugin's MetaCommandActive reads it, so a command is
// known to come from a running meta whichever way it reaches the plugin.
private int _actionDepth;
internal bool IsExecutingAction => _actionDepth > 0;
private void ExecuteAction(MetaRule rule)
{
_actionDepth++;
try { ExecuteActionCore(rule); }
finally { _actionDepth--; }
}
private void ExecuteActionCore(MetaRule rule)
{
string ProcessData(string raw)
{
@ -1171,6 +1197,39 @@ internal sealed class MetaManager
return true;
}
// /vt e — VTank's macro toggle (ub-IT sends it to switch VTank on or off).
if (sub == "e")
{
_raCommandHandler?.Invoke(_settings.IsMacroRunning ? "/ra stop" : "/ra start");
return true;
}
// /vt jump [heading] [shift true|false] [holdms] — VTank's jump (universalremote.met, ub-IT):
// RynthAi's jumper through /ra jump[s] [heading] [holdtime].
if (sub == "jump")
{
string heading = parts.Length >= 3 ? parts[2] : "";
bool shift = parts.Length >= 4 && (parts[3].Equals("true", StringComparison.OrdinalIgnoreCase) || parts[3] == "1");
string hold = parts.Length >= 5 ? parts[4] : "";
_raCommandHandler?.Invoke(("/ra jump" + (shift ? "s" : "") + " " + heading + " " + hold).Trim());
return true;
}
// /vt tapjump — a quick jump with no charge.
if (sub == "tapjump")
{
if (!(_host.HasTapJump && _host.TapJump()))
_host.WriteToChat("[RynthAi] /vt tapjump: the engine's jump isn't available.", 1);
return true;
}
// /vt equipitemsfor <monster> — wield what that monster's rule names (weapon, off hand).
if (sub == "equipitemsfor" && parts.Length >= 3)
{
_raCommandHandler?.Invoke("/ra equipfor " + string.Join(" ", parts, 2, parts.Length - 2));
return true;
}
// /vt meta load <name> — the same load as /ra meta load (LegacyDashboardRenderer.LoadMetaByName):
// a meta in MetaFiles, or, when there is none by that name, a new blank one (2026-10-13).
if (sub == "meta" && parts.Length >= 4 &&
@ -1193,8 +1252,8 @@ internal sealed class MetaManager
return true;
}
// /vt loot load <name> — load a loot profile
if ((sub == "loot" || sub == "lootprofile") && parts.Length >= 4 &&
// /vt loot load <name> — load a loot profile ("looting load" too: FoundryIzexi.met, Meta_Society.met)
if ((sub == "loot" || sub == "lootprofile" || sub == "looting") && parts.Length >= 4 &&
parts[2].Equals("load", StringComparison.OrdinalIgnoreCase))
{
string name = string.Join(" ", parts, 3, parts.Length - 3).Trim().Trim('"');
@ -1231,8 +1290,20 @@ internal sealed class MetaManager
return true;
}
// /vt settings load / loadchar — ignore silently
if (sub == "settings") return true;
// /vt settings loadchar|savechar <name> — RynthAi's settings profiles (/ra settings ...);
// universalremote.met switches profiles this way. Any other /vt settings verb is ignored.
if (sub == "settings")
{
if (parts.Length >= 4 && (parts[2].Equals("loadchar", StringComparison.OrdinalIgnoreCase)
|| parts[2].Equals("savechar", StringComparison.OrdinalIgnoreCase)))
_raCommandHandler?.Invoke($"/ra settings {parts[2].ToLowerInvariant()} {string.Join(" ", parts, 3, parts.Length - 3)}");
return true;
}
// /vt <option> <value> — an option written as a verb (DerethExploration: "/vt navclosestoprange
// 0.005"): the same as /vt opt set, for the VTank options RynthAi maps.
if (parts.Length == 3 && (VtOptionMap.ContainsKey(sub) || IsSpecialVtOption(sub)))
return TrySetVtOption(sub, parts[2]);
// /vt <verb> aliases → existing /ra handlers (Phase 1.3 VTank-meta migration).
// Re-dispatch through the /ra path (_raCommandHandler → HandleRaCommand).
@ -1249,10 +1320,23 @@ internal sealed class MetaManager
System.Globalization.CultureInfo.InvariantCulture, out double bar))
{
int pct = Math.Clamp((int)Math.Round(bar * 100), 0, 100);
_lastAttackBarPct = pct;
_raCommandHandler?.Invoke("/ra power " + pct.ToString(System.Globalization.CultureInfo.InvariantCulture));
return true;
}
// /vt deletemonster (S_Colo, leaving the arena): no RynthAi equivalent is known. Accepted so
// it doesn't go on to AC's chat parser as an unknown command; logged once.
if (sub == "deletemonster")
{
if (!_deleteMonsterLogged)
{
_deleteMonsterLogged = true;
RynthLog.Write(LogCat.Meta, "[Meta] /vt deletemonster accepted and ignored (no RynthAi equivalent).");
}
return true;
}
// /vt reverseroute — reverse the active nav route in place (shared settings;
// the engine re-reads CurrentRoute each tick, so the flip takes effect next tick).
if (sub == "reverseroute")
@ -1351,15 +1435,143 @@ internal sealed class MetaManager
// converts it into FollowNavMin, the nav point reach (see ExpressionEngine).
["navclosestoprange"] = "NavCloseStopRange",
["follownavmin"] = "FollowNavMin", // RynthAi's own name, yards
// 2026-10-17: options the metas in MetaFiles / MetaProfiles set that had no mapping.
["navclosetoprange"] = "NavCloseStopRange", // the same option, misspelt in some metas
["attackrange"] = "MonsterRange",
["ringdistance"] = "RingRange",
["minimumringtargets"] = "MinRingTargets",
["corpseapproachrange"] = "CorpseApproachRangeMax",
["corpseapproachrange-max"] = "CorpseApproachRangeMax",
["corpseapproachrange-min"] = "CorpseApproachRangeMin",
// 2026-10-18: the sample metas (S_*, Colo) set these and nothing read them.
["rebufftimeremainingseconds"] = "RebuffSecondsRemaining", // VTank's spelling (the one above is a typo)
["petcustomrange"] = "CustomPetRange", // landblock units -> whole yards
["blacklistmonstertimeoutseconds"] = "BlacklistTimeoutSec",
};
/// <summary>VTank options given in landblock units (x240 = yards) whose RynthAi setting is yards.
/// NavCloseStopRange converts itself (the settings map takes landblock units).</summary>
private static readonly HashSet<string> VtDistanceOptions = new(StringComparer.OrdinalIgnoreCase)
{
"attackdistance", "attackrange", "approachdistance", "dooropenrange", "opendoorrange", "ringdistance",
"corpseapproachrange", "corpseapproachrange-max", "corpseapproachrange-min", "petcustomrange",
};
/// <summary>RynthAi distance settings kept in whole yards (their setter refuses a decimal).</summary>
private static readonly HashSet<string> IntYardSettings = new(StringComparer.Ordinal)
{
"MonsterRange", "ApproachRange", "RingRange", "CustomPetRange",
};
/// <summary>A RynthAi yards value as VTank's landblock units (yards / 240), for reading a distance back.</summary>
internal static string YardsToVtDistance(string yards)
{
if (!double.TryParse(yards, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double v))
return yards;
return (v / 240.0).ToString("0.######", System.Globalization.CultureInfo.InvariantCulture);
}
/// <summary>
/// A VTank distance as RynthAi yards: a value up to 1 is landblock units (x240; VTank's own
/// unit), a larger one is taken as yards already (typed by hand). Invariant culture.
/// </summary>
internal static string VtDistanceToYards(string value, bool wholeYards)
{
if (!double.TryParse(value, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double v))
return value; // not a number (an unexpanded expression): left for the setter to refuse
double yards = v > 0 && v <= 1.0 ? v * 240.0 : v;
return wholeYards
? Math.Max(0, (int)Math.Round(yards)).ToString(System.Globalization.CultureInfo.InvariantCulture)
: yards.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture);
}
/// <summary>VTank options handled by <see cref="TrySetSpecialVtOption"/> (no 1:1 RynthAi setting).</summary>
private static bool IsSpecialVtOption(string vtName) => vtName.ToLowerInvariant() is
"defaultmeleeattackheight" or "lootfellowcorpses" or "lootallcorpses" or "usearcs" or "minimumhealkitsuccesschance"
or "autoattackpower";
// The last /vt setattackbar power (percent), for AutoAttackPower false after it was on (-1 = none yet).
private int _lastAttackBarPct = -1;
private bool _deleteMonsterLogged;
/// <summary>
/// The VTank options whose value means something else in RynthAi:
/// DefaultMeleeAttackHeight 1-3 (low/medium/high) is RynthAi's 0-2; LootFellowCorpses /
/// LootAllCorpses pick the loot-ownership mode (my kills / fellowship / all); UseArcs is a VTank
/// mode number (2, 3 in the metas) for RynthAi's on/off; MinimumHealKitSuccessChance is a
/// percent (a fraction up to 1 is scaled). False when <paramref name="vtName"/> isn't one of them.
/// </summary>
private bool TrySetSpecialVtOption(string vtName, string value)
{
var inv = System.Globalization.CultureInfo.InvariantCulture;
bool num = double.TryParse(value, System.Globalization.NumberStyles.Float, inv, out double n);
switch (vtName.ToLowerInvariant())
{
case "defaultmeleeattackheight":
if (!num) return true;
_settings.MeleeAttackHeight = Math.Clamp((int)Math.Round(n) - 1, 0, 2);
return true;
case "lootfellowcorpses":
if (!num) return true;
if (n != 0 && _settings.LootOwnership < 1) _settings.LootOwnership = 1;
else if (n == 0 && _settings.LootOwnership == 1) _settings.LootOwnership = 0;
return true;
case "lootallcorpses":
if (!num) return true;
if (n != 0) _settings.LootOwnership = 2;
else if (_settings.LootOwnership == 2) _settings.LootOwnership = 0;
return true;
case "usearcs":
if (!num) return true;
_settings.UseArcs = n != 0;
return true;
case "minimumhealkitsuccesschance":
if (!num) return true;
_settings.KitMinSuccessPct = Math.Clamp((int)Math.Round(n > 0 && n <= 1 ? n * 100 : n), 0, 100);
return true;
case "autoattackpower":
// On: RynthAi picks the power itself (-1, its "auto"). Off: the attack bar's value,
// the last /vt setattackbar (a power already set by hand stays as it is).
if (!num) return true;
if (n != 0)
{
_settings.MeleeAttackPower = _settings.MissileAttackPower = -1;
}
else if (_settings.MeleeAttackPower < 0 || _settings.MissileAttackPower < 0)
{
if (_lastAttackBarPct >= 0)
_settings.MeleeAttackPower = _settings.MissileAttackPower = _lastAttackBarPct;
else
RynthLog.Write(LogCat.Meta, "[Meta] AutoAttackPower off with no /vt setattackbar value yet: attack power stays automatic.");
}
return true;
default:
return false;
}
}
/// <summary>The special options as VTank reads them back (height 1-3, ownership as two flags).</summary>
private string? GetSpecialVtOption(string vtName) => vtName.ToLowerInvariant() switch
{
"defaultmeleeattackheight" => (_settings.MeleeAttackHeight + 1).ToString(System.Globalization.CultureInfo.InvariantCulture),
"lootfellowcorpses" => _settings.LootOwnership >= 1 ? "true" : "false",
"lootallcorpses" => _settings.LootOwnership == 2 ? "true" : "false",
"usearcs" => _settings.UseArcs ? "true" : "false",
"minimumhealkitsuccesschance" => _settings.KitMinSuccessPct.ToString(System.Globalization.CultureInfo.InvariantCulture),
"autoattackpower" => _settings.MeleeAttackPower < 0 ? "true" : "false",
_ => null,
};
/// <summary>A VTank option's current value (mapped setting, else a stored generic option).</summary>
private string? GetVtOption(string vtName)
{
if (GetSpecialVtOption(vtName) is string special) return special;
var map = Expressions.BuildSettingsMapPublic();
if (VtOptionMap.TryGetValue(vtName, out string? raName))
{
if (map.TryGetValue(raName, out var entry)) return entry.Get();
// Distances read back in VTank's landblock units, as they were set (6 yd reads 0.025).
if (map.TryGetValue(raName, out var entry))
return VtDistanceOptions.Contains(vtName) ? YardsToVtDistance(entry.Get()) : entry.Get();
}
// A RynthAi setting named directly (EnableCombat, OpenDoors, NavCloseStopRange...).
if (map.TryGetValue(vtName, out var direct)) return direct.Get();
@ -1372,6 +1584,15 @@ internal sealed class MetaManager
// Translate VTank bool strings to numeric
string value = NormalizeVtValue(vtValue);
// Options whose value means something else in RynthAi (a scale, an offset, a mode).
if (TrySetSpecialVtOption(vtName, value)) return true;
// VTank distances are in landblock units (1 = 240 yd: AttackDistance .01666 is 4 yd); RynthAi's
// are yards. Converted here, rounded where RynthAi keeps whole yards (an int setting refused
// "0.01666" outright, so every meta's attack / approach distance was dropped).
if (VtDistanceOptions.Contains(vtName) && VtOptionMap.TryGetValue(vtName, out string? distName))
value = VtDistanceToYards(value, IntYardSettings.Contains(distName));
var map = Expressions.BuildSettingsMapPublic();
if (VtOptionMap.TryGetValue(vtName, out string? raName))
{

View file

@ -247,16 +247,12 @@ internal static class TinkerCatalog
};
/// <summary>
/// Trinkets (compass, goggles, scarab, watch, puzzle box, tops) are jewelry the Jewelry tab
/// leaves alone: they take the Trinkets tab's recipes instead (UB-IT IsLeaftideTrinketJewelry).
/// Trinkets are jewelry the Jewelry tab leaves alone: they take the Trinkets tab's recipes instead.
/// Which jewelry is a trinket is the server plugin's (its profile's "trinkets": Leaftide's compasses,
/// goggles, scarabs, ... come from RynthILT since 2026-10-20); without one, nothing is.
/// </summary>
public static bool IsTrinket(string name)
{
string n = (name ?? string.Empty).ToLowerInvariant();
if (n.Contains("compass") || n.Contains("goggles") || n.Contains("scarab") || n.Contains("watch") || n.Contains("puzzle box"))
return true;
return n.Contains("top") && !n.Contains("topaz");
}
public static bool IsTrinket(string name, RynthCore.Plugin.Shared.ServerTrinketRule? rule)
=> (rule ?? RynthCore.Plugin.Shared.ServerTrinketRule.None).IsTrinket(name);
public static string Label(TinkerBench bench) => bench switch
{

View file

@ -203,7 +203,7 @@ internal sealed class TinkerRunner
foreach (var wo in Inv.Items())
{
if (!TinkerCatalog.Targets(bench, wo.ObjectClass)) continue;
bool trinket = TinkerCatalog.IsTrinket(wo.Name);
bool trinket = TinkerCatalog.IsTrinket(wo.Name, _ctx.ServerTrinkets);
if (bench == TinkerBench.Jewelry && trinket) continue;
if (bench == TinkerBench.Trinkets && !trinket) continue;
if (done.Contains(wo.Id)) { hidden++; continue; }

View file

@ -1,203 +0,0 @@
// IltClient.cs - RynthAi's side of the "RynthILT.Hub" interface (Plugins/Shared/RynthIltHubApi.cs):
// the Infinite Leaftide tabs and sections the Mini Remote shows, the server's ILT feature bits
// (the Pets tab's refill / mastery charms, the Quests tab's /myquests bit), the ILT session rates
// and the ILT "/ra" verbs, all from the RynthILT plugin.
//
// Without RynthILT (not installed, too old, not loaded yet) every call answers "not ILT": no ILT
// tab, no ILT section, unknown feature bits, and the ILT verbs say RynthILT is needed. The table is
// looked up on the pump thread (Tick) at most every RecheckMs and kept in a volatile field for the
// render thread; RynthILT never frees it (Version goes to 0 on its shutdown), so reading a stale
// pointer is safe and a Version of 0 means "look again".
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.MiniRemote;
/// <summary>One ILT tab as RynthILT describes it (render thread copy).</summary>
internal readonly record struct IltTabInfo(string Id, string Label, float Width, float Height, bool Shown, bool Available);
internal sealed unsafe class IltClient
{
public const string NotLoaded = "That's an Infinite Leaftide feature: it comes with the RynthILT plugin, which isn't loaded.";
private const long RecheckMs = 3000;
private const int MaxTabs = 16;
private readonly RynthCoreHost _host;
private IntPtr _table; // volatile reads/writes: the render thread uses what the pump found
private long _checkedAt;
private bool _checkedOnce; // false: look now (a sentinel time would overflow "now - _checkedAt")
private readonly IltTabV1[] _tabBuf = new IltTabV1[MaxTabs];
private readonly List<IltTabInfo> _tabs = new();
public IltClient(RynthCoreHost host) => _host = host;
/// <summary>Pump thread: look the table up again when it's due, missing or shut down.</summary>
public void Tick()
{
long now = Environment.TickCount64;
var t = (RynthIltHubApiV1*)System.Threading.Volatile.Read(ref _table);
if (!LookupDue(_checkedOnce, _checkedAt, now, haveTable: t != null, tableLive: t != null && t->Version >= 1)) return;
_checkedOnce = true;
_checkedAt = now;
IntPtr found = IntPtr.Zero;
if (_host.HasGetPluginInterface)
{
var p = (RynthIltHubApiV1*)_host.GetPluginInterface(RynthIltHub.PluginName, RynthIltHubApiV1.InterfaceName, RynthIltHubApiV1.InterfaceVersion);
if (p != null && p->Version >= 1 && p->StructSize >= (uint)sizeof(RynthIltHubApiV1)) found = (IntPtr)p;
}
System.Threading.Volatile.Write(ref _table, found);
}
/// <summary>Forget the table (login, logout); the next Tick looks again.</summary>
public void Reset()
{
System.Threading.Volatile.Write(ref _table, IntPtr.Zero);
_checkedOnce = false;
}
/// <summary>
/// Whether Tick looks the table up again. Pure. Always on the first call (and after Reset), at
/// once when the table RynthILT gave is shut down (Version 0), else every <see cref="RecheckMs"/>.
/// </summary>
internal static bool LookupDue(bool checkedOnce, long checkedAt, long now, bool haveTable, bool tableLive)
{
if (!checkedOnce) return true;
if (haveTable && !tableLive) return true;
return now - checkedAt >= RecheckMs;
}
private RynthIltHubApiV1* T
{
get
{
var t = (RynthIltHubApiV1*)System.Threading.Volatile.Read(ref _table);
return t != null && t->Version >= 1 ? t : null;
}
}
/// <summary>RynthILT answers (any thread).</summary>
public bool Loaded => T != null;
/// <summary>This world is Infinite Leaftide / ACECustom (or forced), as RynthILT sees it. Any thread.</summary>
public bool IsIltWorld
{
get
{
var t = T;
return t != null && t->IsIltWorld != null && t->IsIltWorld() != 0;
}
}
/// <summary>The server's bit for a feature: -1 unknown (and always off ILT / without RynthILT), 0 off, 1 on. Any thread.</summary>
public int Feature(string key)
{
var t = T;
if (t == null || t->GetFeature == null) return -1;
using var k = new Utf8(key);
return t->GetFeature(k.P);
}
/// <summary>The server positively reported the feature off.</summary>
public bool IsOff(string key) => Feature(key) == 0;
/// <summary>The server positively reported the feature on.</summary>
public bool IsOn(string key) => Feature(key) == 1;
/// <summary>ILT coin / pyreal rates (false off ILT or without RynthILT). Any thread.</summary>
public bool TryGetRates(out double coinsPerHour, out double pyrealsPerHour)
{
coinsPerHour = pyrealsPerHour = 0;
var t = T;
if (t == null || t->GetRates == null) return false;
double c = 0, p = 0;
if (t->GetRates(&c, &p) == 0) return false;
coinsPerHour = c;
pyrealsPerHour = p;
return true;
}
/// <summary>This character's "Treat this world as ILT" (RynthILT's). Any thread.</summary>
public bool ForceIlt
{
get
{
var t = T;
return t != null && t->GetForceIlt != null && t->GetForceIlt() != 0;
}
set
{
var t = T;
if (t != null && t->SetForceIlt != null) t->SetForceIlt(value ? 1 : 0);
}
}
/// <summary>Render thread: RynthILT's tabs with their flags (empty without RynthILT). The list is reused.</summary>
public IReadOnlyList<IltTabInfo> Tabs()
{
_tabs.Clear();
var t = T;
if (t == null || t->GetTabs == null) return _tabs;
int n;
fixed (IltTabV1* buf = _tabBuf) n = t->GetTabs(buf, MaxTabs);
n = Math.Min(n, MaxTabs);
for (int i = 0; i < n; i++)
{
ref IltTabV1 tab = ref _tabBuf[i];
string id, label;
fixed (byte* pid = tab.Id) id = Marshal.PtrToStringUTF8((IntPtr)pid) ?? string.Empty;
fixed (byte* plabel = tab.Label) label = Marshal.PtrToStringUTF8((IntPtr)plabel) ?? string.Empty;
if (id.Length == 0) continue;
_tabs.Add(new IltTabInfo(id, label.Length > 0 ? label : id, tab.Width, tab.Height,
(tab.Flags & RynthIltHub.TabShown) != 0, (tab.Flags & RynthIltHub.TabAvailable) != 0));
}
return _tabs;
}
/// <summary>Render thread: one ILT tab's body into the current child window; false = nothing drawn.</summary>
public bool RenderTab(string id)
{
var t = T;
if (t == null || t->RenderTab == null) return false;
using var s = new Utf8(id);
return t->RenderTab(s.P) != 0;
}
/// <summary>Render thread: an ILT section (RynthIltHub.Section*); false = nothing drawn (not ILT, or no RynthILT).</summary>
public bool RenderSection(string id)
{
var t = T;
if (t == null || t->RenderSection == null) return false;
using var s = new Utf8(id);
return t->RenderSection(s.P) != 0;
}
/// <summary>An ILT "/ra" verb ("hub bank", "guardian handin", ...); false when RynthILT doesn't take it.</summary>
public bool Command(string text)
{
var t = T;
if (t == null || t->Command == null) return false;
using var s = new Utf8(text);
return t->Command(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

@ -1,7 +1,7 @@
// MiniRemoteContext.cs — Shared services for the Mini Remote's universal tabs (Quests, Pets) and
// the VTank .usd importer. The universal half of the ILT Hub's IltHubContext (SilentKelpie's ILT
// Hub; its Infinite Leaftide half went to the RynthILT plugin 2026-10-13, whose feature bits and
// sections come through Ilt).
// sections come through ServerHub).
//
// Threading contract (as before):
// * Tick / OnChat run on the plugin pump thread and may call the host freely.
@ -34,13 +34,13 @@ internal sealed class MiniRemoteContext
private readonly Func<LegacyUiSettings?> _settings;
public MiniRemoteContext(RynthCoreHost host, MiniRemoteState state, MiniRemoteStore store, MiniRemoteInventory inventory,
IltClient ilt, Func<LegacyUiSettings?> settings)
ServerHubClient serverHub, Func<LegacyUiSettings?> settings)
{
Host = host;
State = state;
Store = store;
Inventory = inventory;
Ilt = ilt;
ServerHub = serverHub;
_settings = settings;
}
@ -50,7 +50,7 @@ internal sealed class MiniRemoteContext
public MiniRemoteInventory Inventory { get; }
/// <summary>RynthILT's view (ILT world, feature bits, ILT sections); "not ILT" without RynthILT.</summary>
public IltClient Ilt { get; }
public ServerHubClient ServerHub { get; }
/// <summary>The live combat settings (rule lists the Pets tab / USD importer edit). Null before login.</summary>
public LegacyUiSettings? Settings => _settings();
@ -68,9 +68,9 @@ internal sealed class MiniRemoteContext
// ── Active server (RynthCore's verdict and its server plugin's profile) ─────────────────────
/// <summary>What the render thread reads about the active server: replaced whole, never edited.</summary>
private sealed record ServerView(string Name, IReadOnlyList<ServerSalvageView> Salvage)
private sealed record ServerView(string Name, IReadOnlyList<ServerSalvageView> Salvage, ServerTrinketRule Trinkets)
{
public static readonly ServerView None = new(string.Empty, Array.Empty<ServerSalvageView>());
public static readonly ServerView None = new(string.Empty, Array.Empty<ServerSalvageView>(), ServerTrinketRule.None);
}
private readonly ServerStateClient _server = new();
@ -83,6 +83,9 @@ internal sealed class MiniRemoteContext
/// <summary>The active server plugin's own tinkering salvage (empty when it defines none). Any thread.</summary>
public IReadOnlyList<ServerSalvageView> ServerSalvage => _serverView.Salvage;
/// <summary>Which jewelry the active server plugin calls a trinket (none without one). Any thread.</summary>
public ServerTrinketRule ServerTrinkets => _serverView.Trinkets;
/// <summary>Pump thread: polls RynthCore's server state (cheap until due) and rebuilds the view when it changed.</summary>
public void PollServer(long now)
{
@ -91,7 +94,7 @@ internal sealed class MiniRemoteContext
_serverRevision = _server.Revision;
EngineServerState? st = _server.State;
string name = st != null && st.HasActive ? st.ActiveName : string.Empty;
_serverView = new ServerView(name, ServerSalvageView.ParseList(_server.ProfileJson));
_serverView = new ServerView(name, ServerSalvageView.ParseList(_server.ProfileJson), ServerTrinketRule.Parse(_server.ProfileJson));
}
/// <summary>Logout: forget the server; the next login polls fresh.</summary>

View file

@ -9,12 +9,12 @@
// OnTick → Tick() (pump thread)
// OnChatWindowText → OnChat() (pump thread)
// OnRender → Render() (render thread: confirmations)
// /ra hub ..., /ra quests ..., /ra pets ..., /ra guardian ..., /ra bounty ... → HandleCommand()
// /ra hub ..., /ra quests ..., /ra pets ... → HandleCommand()
// OnLogout / teardown → OnLogout()
// The Mini Remote's tab bar (MiniRemoteHud) shows Remote, then Pets and Crafting (here, every
// world), then RynthILT's Infinite Leaftide tabs (IltClient). The ILT verbs ("/ra hub bank",
// "/ra hub attr ...", "/ra guardian ...", "/ra bounty", "/ra hub open banking", ...) are forwarded
// to RynthILT (RynthILT.Hub Command); without RynthILT they say so.
// world), then the active server plugin's tabs (ServerHubClient; RynthILT's on Infinite Leaftide). The
// "/ra hub" verbs RynthAi doesn't have ("/ra hub bank", "/ra hub open banking", ...) go to that
// plugin (RynthILT.Hub Command); without one they show the help, as on a retail world.
using System;
using System.Linq;
using System.Numerics;
@ -50,12 +50,12 @@ internal sealed class MiniRemoteController
public VTankUsdImporter Usd { get; }
public MiniRemoteController(RynthCoreHost host, string charFolder, Func<WorldObjectCache?> cache,
Func<LegacyUiSettings?> settings, Func<QuestTracker?> quests, Action saveCombatSettings, IltClient ilt)
Func<LegacyUiSettings?> settings, Func<QuestTracker?> quests, Action saveCombatSettings, ServerHubClient serverHub)
{
var store = new MiniRemoteStore(charFolder);
var state = store.Load();
var inventory = new MiniRemoteInventory(host, cache);
_ctx = new MiniRemoteContext(host, state, store, inventory, ilt, settings) { SaveCombatSettings = saveCombatSettings };
_ctx = new MiniRemoteContext(host, state, store, inventory, serverHub, settings) { SaveCombatSettings = saveCombatSettings };
_quests = quests;
Pets = new PetsTab(_ctx);
Crafting = new CraftingTab(_ctx);
@ -65,8 +65,8 @@ internal sealed class MiniRemoteController
public MiniRemoteState State => _ctx.State;
/// <summary>RynthILT's side (ILT world, tabs, sections, verbs).</summary>
public IltClient Ilt => _ctx.Ilt;
/// <summary>The server plugin's hub (its world check, tabs, sections, verbs; RynthILT on Infinite Leaftide).</summary>
public ServerHubClient ServerHub => _ctx.ServerHub;
/// <summary>Shows / hides / toggles the Mini Remote ("show", "hide", "toggle"). Set by RynthAiPlugin; returns the chat reply.</summary>
public Func<string, string>? MiniRemoteCommand { get; set; }
@ -77,8 +77,8 @@ internal sealed class MiniRemoteController
/// </summary>
public Func<string, string, string>? MiniRemoteTabCommand { get; set; }
/// <summary>True when the cached ILT options already say /myquests is off (skip the login refresh).</summary>
public bool SkipLoginQuestRefresh => _ctx.Ilt.IsIltWorld && _ctx.Ilt.IsOff(RynthIltHub.FeatureQuests);
/// <summary>True when the server plugin already says /myquests is off on its server (skip the login refresh).</summary>
public bool SkipLoginQuestRefresh => _ctx.ServerHub.ServerActive && _ctx.ServerHub.IsOff(RynthIltHub.FeatureQuests);
// ── Lifecycle ───────────────────────────────────────────────────────────
@ -144,7 +144,7 @@ internal sealed class MiniRemoteController
RynthLog.Trace(LogCat.Quests, "RefreshQuests()");
QuestTracker? t = _quests();
if (t == null) return "Quest tracker not ready.";
if (_ctx.Ilt.IsOff(RynthIltHub.FeatureQuests) || t.Disabled) return "/myquests is disabled on this server.";
if (_ctx.ServerHub.IsOff(RynthIltHub.FeatureQuests) || t.Disabled) return "/myquests is disabled on this server.";
long now = MiniRemoteContext.NowMs;
if (now - _lastQuestRefreshAt < QuestRefreshCooldownMs)
return $"Wait {(QuestRefreshCooldownMs - (now - _lastQuestRefreshAt)) / 1000}s (server allows one /myquests per minute).";
@ -220,12 +220,14 @@ internal sealed class MiniRemoteController
// ── Commands ────────────────────────────────────────────────────────────
/// <summary>
/// "/ra hub [show|hide|toggle|open pets|crafting [show|hide|toggle]|open breeding|tab pets|crafting|breeding|remote]",
/// "/ra quests [refresh]", "/ra pets [show|hide|toggle]"; every other "/ra hub ..." verb,
/// "/ra guardian ..." and "/ra bounty|bounties|bountys ..." go to RynthILT. The retired quest
/// verbs and tab names ("/ra quests window", "/ra hub open quests", ...) say where quests went,
/// and "/ra hub open|tab character" opens RynthOracle's Character tab (Huds/MovedTabs.cs).
/// Returns false if not handled.
/// "/ra hub [show|hide|toggle|open pets|crafting [show|hide|toggle]|open|tab &lt;a server plugin's Pets
/// sub-tab&gt;|tab pets|crafting|remote]", "/ra quests [refresh]", "/ra pets [show|hide|toggle]"; every
/// other "/ra hub ..." verb goes to the server plugin (RynthILT on Infinite Leaftide: "/ra hub bank",
/// "/ra hub open banking", ...), and without one it shows the help. The retired quest verbs and tab
/// names ("/ra quests window", "/ra hub open quests", ...) say where quests went, and "/ra hub
/// open|tab character" opens RynthOracle's Character tab (Huds/MovedTabs.cs). "/ra guardian",
/// "/ra bounty" and the like aren't the Mini Remote's (RynthAiPlugin passes them to the server
/// plugin). Returns false if not handled.
/// </summary>
public bool HandleCommand(string verb, string[] args)
{
@ -242,10 +244,8 @@ internal sealed class MiniRemoteController
OpenTab(MiniRemoteTabs.Pets, args.Length > 0 ? args[0] : "toggle");
return true;
}
bool ilt = verb.Equals("guardian", StringComparison.OrdinalIgnoreCase) || IsBountyVerb(verb);
if (!ilt && !verb.Equals("hub", StringComparison.OrdinalIgnoreCase)) return false;
if (!verb.Equals("hub", StringComparison.OrdinalIgnoreCase)) return false;
if (!ilt)
{
string cmd = args.Length > 0 ? args[0].ToLowerInvariant() : "toggle";
// "/ra hub open|tab quests": the tab is RynthOracle's window now.
@ -270,8 +270,8 @@ internal sealed class MiniRemoteController
// The Mini Remote is the Hub's main window.
_ctx.Chat(MiniRemoteCommand != null ? MiniRemoteCommand(cmd) : "[Mini Remote] The Mini Remote is not available yet.");
return true;
case "open" or "tab" when args.Length > 1 && IsBreedingTabName(args[1]):
OpenBreeding(cmd);
case "open" or "tab" when args.Length > 1 && Pets.FindSubTab(args[1]) is { } subTab:
OpenPetsSubTab(cmd, subTab);
return true;
case "open" when args.Length > 1 && MiniRemoteTabs.Parse(args[1]) is { } openTab:
OpenTab(openTab, args.Length > 2 ? args[2] : "toggle");
@ -283,52 +283,39 @@ internal sealed class MiniRemoteController
}
}
// Everything else is an Infinite Leaftide verb: RynthILT's.
// Everything else is the server plugin's (RynthILT's "/ra hub bank", "/ra hub open banking", ...).
string line = (verb + " " + string.Join(" ", args)).Trim();
if (_ctx.Ilt.Command(line)) return true;
if (verb.Equals("hub", StringComparison.OrdinalIgnoreCase) && args.Length > 0 && args[0].Equals("tab", StringComparison.OrdinalIgnoreCase))
if (_ctx.ServerHub.Command(line)) return true;
if (args.Length > 0 && args[0].Equals("tab", StringComparison.OrdinalIgnoreCase))
{
// A tab RynthILT doesn't offer (not loaded): back to the remote rather than nothing.
// A tab no plugin offers (the engine's dashboard): back to the remote rather than nothing.
MiniRemoteTabCommand?.Invoke(MiniRemoteTabs.Remote, "select");
return true;
}
if (verb.Equals("hub", StringComparison.OrdinalIgnoreCase)) PrintHelp();
_ctx.Chat("[Mini Remote] " + IltClient.NotLoaded);
PrintHelp();
return true;
}
private void PrintHelp()
{
_ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote) /ra hub open pets|crafting [show|hide|toggle] /ra hub open breeding (ILT)");
_ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote) /ra hub open pets|crafting [show|hide|toggle]");
_ctx.Chat("[Mini Remote] /ra quests refresh (quiet /myquests) /ra pets [show|hide] Quest list, timers and rewards: RynthOracle (/ro).");
_ctx.Chat("[Mini Remote] Banking, gear, charms, games, the Guardian, bounties, /ra hub attr ...: Infinite Leaftide, the RynthILT plugin.");
_ctx.Chat("[Mini Remote] A server plugin adds its own tabs and /ra hub verbs here once it is loaded for your world.");
_ctx.Chat("[Mini Remote] Character overview and session: RynthOracle (/ro character). Force a server: /rc diagnostics.");
}
/// <summary>"breeding" / "breed": the Pets tab's Breeding sub-tab (RynthILT's tracker, Infinite Leaftide).</summary>
private static bool IsBreedingTabName(string text) => text.Trim().ToLowerInvariant() is "breeding" or "breed";
/// <summary>
/// "/ra hub open|tab breeding": the Pets tab on its Breeding sub-tab when RynthILT offers it. "open"
/// shows the Mini Remote and says why when there is no Breeding sub-tab; "tab" (the engine's
/// dashboard) only switches tabs, to the Pets roster when there is none.
/// "/ra hub open|tab &lt;sub-tab&gt;": the Pets tab on a sub-tab the server plugin adds (RynthILT's
/// Breeding). "open" shows the Mini Remote; "tab" (the engine's dashboard) only switches tabs.
/// </summary>
private void OpenBreeding(string cmd)
private void OpenPetsSubTab(string cmd, string subTab)
{
bool offered = Pets.BreedingOffered;
if (offered) Pets.SelectBreeding();
Pets.SelectSubTab(subTab);
if (cmd == "tab")
{
MiniRemoteTabCommand?.Invoke(MiniRemoteTabs.Pets, "select");
return;
}
if (!offered)
{
_ctx.Chat("[Mini Remote] " + (!_ctx.Ilt.Loaded ? IltClient.NotLoaded
: !_ctx.Ilt.IsIltWorld ? "Pet breeding is an Infinite Leaftide feature; this world isn't Infinite Leaftide."
: "This server reports pet breeding off."));
return;
}
OpenTab(MiniRemoteTabs.Pets, "show");
}
@ -339,12 +326,6 @@ internal sealed class MiniRemoteController
private static bool IsQuestsName(string text)
=> text.Equals("quests", StringComparison.OrdinalIgnoreCase) || text.Equals("quest", StringComparison.OrdinalIgnoreCase);
/// <summary>"/ra bounty", "/ra bounties" and the "/ra bountys" spelling (RynthILT's Bounties window).</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 one of the Mini Remote's own tabs. Says what happened.</summary>
private void OpenTab(string tab, string mode)
{

View file

@ -3,9 +3,8 @@
// ILT Hub went to the RynthILT plugin 2026-10-13, which has its own copy for its ILT features).
//
// One place for: WCID lookups (cached), stack / use counts, "is it equipped", appraisal requests
// (throttled), the Summon Essence Refill / Universal Summoning Mastery charm status (ACECustom
// items the Pets tab's refill path reads; harmless anywhere else) and player int/bool reads.
// Pump-thread only.
// (throttled) and player int/bool reads. (The ACECustom pet charms' status went to RynthILT with
// the charms, 2026-10-20.) Pump-thread only.
using System;
using System.Collections.Generic;
using System.Linq;
@ -14,16 +13,12 @@ using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.MiniRemote;
/// <summary>Charm ON / OFF read from its appraisal text.</summary>
internal enum CharmState { Unknown = -1, Off = 0, On = 1 }
internal sealed class MiniRemoteInventory
{
// ── Well-known WCIDs (ACECustom content the Pets tab recognises) ─────────
// ── Well-known WCIDs ────────────────────────────────────────────────────
/// <summary>Encapsulated Spirit (pet essence refills; never a pet itself).</summary>
public const uint WcidEncapsulatedSpirit = 49485;
public const uint WcidSummonRefillCharm = 78780030;
public const uint WcidUniversalMasteryCharm = 78780031;
public static readonly uint[] WcidInfiniteCastingStone = { 777700019, 777700055 };
// ACECustom's pet charms and the Infinite Casting Stone moved to RynthILT (IltPetAutomation) 2026-10-20.
// ── Property ids ────────────────────────────────────────────────────────
public const uint IntStackSize = 12;
@ -32,9 +27,6 @@ internal sealed class MiniRemoteInventory
public const uint IntNumTimesTinkered = 171;
public const uint IntImbuedEffect = 179;
public const uint IntMaterialType = 131;
public const uint StrUse = 14;
public const uint BoolPyrealRefillActive = 9049;
public const uint BoolUniversalMasteryActive = 50038;
private readonly RynthCoreHost _host;
private readonly Func<WorldObjectCache?> _cache;
@ -125,31 +117,6 @@ internal sealed class MiniRemoteInventory
public IEnumerable<WorldObject> AllByWcid(params uint[] wcids)
=> Items().Where(wo => Array.IndexOf(wcids, Wcid(wo)) >= 0);
/// <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) != CharmState.Off)
|| Items().Any(wo => wo.ObjectClass == AcObjectClass.SpellComponent);
/// <summary>
/// ON/OFF/Unknown from the appraisal Use text ("... Status: ON"). Requests appraisal
/// (throttled) when the text isn't loaded yet.
/// </summary>
public CharmState CharmStatus(WorldObject charm)
{
string use = Str(charm, StrUse);
if (use.Length == 0)
{
RequestAppraisal(charm);
return CharmState.Unknown;
}
if (use.Contains("Status: ON", StringComparison.OrdinalIgnoreCase)) return CharmState.On;
if (use.Contains("Status: OFF", StringComparison.OrdinalIgnoreCase)) return CharmState.Off;
return CharmState.Unknown;
}
// ── Actions ─────────────────────────────────────────────────────────────
public bool Use(WorldObject wo) => _host.HasUseObject && _host.UseObject(unchecked((uint)wo.Id));

View file

@ -100,9 +100,9 @@ public sealed class PetTabState
public int PetTimeoutSeconds = 30;
/// <summary>
/// Allow a combat summon from an EMPTY essence when the Summon Essence Refill Charm is
/// active (ACECustom: the server refills from banked pyreals). Still requires the server
/// flag to be on (RynthILT reports it).
/// Obsolete since 2026-10-20 (unused here, kept so miniremote.json still loads): the "summon from
/// empty essences" opt-in of ACECustom's refill charm. It is RynthILT's now, which copied this
/// value once (IltMigration.ImportRynthAiSettings).
/// </summary>
public bool UsePyrealRefillPath;
@ -120,10 +120,11 @@ public sealed class PetTabState
/// <summary>Seconds to wait before re-summoning the cosmetic pet after it despawns.</summary>
public int CosmeticRespawnSeconds = 15;
// Auto siphon-lens capture (ACECustom MonsterCapture; Mini Remote > Pets).
/// <summary>When on, use the selected siphon lens on a nearby creature once it is weak enough.</summary>
// Obsolete since 2026-10-20, as UsePyrealRefillPath: ACECustom's siphon auto-capture moved to
// RynthILT (IltPetAutomation), which copied these once. Unused here; kept so old files load.
/// <summary>Obsolete: auto-capture's switch (RynthILT's now).</summary>
public bool AutoCaptureEnabled;
/// <summary>Index into <see cref="PetCaptureRules.Lenses"/> (Flawed to Asheron).</summary>
/// <summary>Obsolete: auto-capture's lens (RynthILT's now).</summary>
public int CaptureLensIndex;
}
@ -256,7 +257,6 @@ internal sealed class MiniRemoteStore
s.Pet.RosterKind = Math.Clamp(s.Pet.RosterKind, 0, 2);
s.Pet.RosterSort = Math.Clamp(s.Pet.RosterSort, 0, 6);
s.Pet.CosmeticRespawnSeconds = Math.Clamp(s.Pet.CosmeticRespawnSeconds, 5, 600);
s.Pet.CaptureLensIndex = Math.Clamp(s.Pet.CaptureLensIndex, 0, PetCaptureRules.Lenses.Length - 1);
s.Quests ??= new QuestsTabState();
s.Quests.QuestFilter ??= string.Empty;
s.Quests.QuestFavorites ??= new();

View file

@ -1,9 +1,11 @@
// PetsTab.cs — The Mini Remote's Pets tab.
// Originally SilentKelpie's IltPets (ILT Hub). Summoning is every server's, so the tab stayed in
// RynthAi when the ILT Hub went to the RynthILT plugin (2026-10-13). The ACECustom bits it reads
// (the refill / mastery charm server flags, whether this is an ILT world) come from RynthILT
// (RynthILT.Hub GetFeature / IsIltWorld; unknown without it, which never spends pyreals); the
// /pets and /shinies logs moved to RynthILT, which draws them at the bottom of this tab.
// RynthAi when the ILT Hub went to the RynthILT plugin (2026-10-13). What is a server's own lives
// in that server's plugin and is drawn here through its hub (ServerHubClient, RynthILT.Hub): RynthILT
// draws ACECustom's pet charms, siphon auto-capture and the /pets and /shinies logs under the
// roster, adds the Breeding sub-tab, and answers whether an empty essence may be summoned
// (2026-10-20: charms, capture and that gate moved out of this file). Without a server plugin the
// tab is the retail one.
//
// * Pet roster (UtilityBelt Pets-tab style): every carried pet essence with three stat
// lines (bond / level / craft · sex / mutations / potency / mastery · ratings / uses /
@ -18,18 +20,14 @@
// - Cosmetic: the tick picks a display pet; "Keep cosmetic pet out" summons it in
// peace mode and dismisses it when PetManager needs the slot for a fight.
// Summon / Despawn act on the highlighted row (or the type's chosen pet).
// * Pet charms: Summon Essence Refill (server refills an empty essence from banked
// pyreals) and Universal Summoning Mastery, read from the charm appraisal text and the
// player bools the server stamps. Feeds PetManager.AllowSummonOnEmpty.
// * Summon from an empty essence: PetManager.AllowSummonOnEmpty asks the server plugin
// (RynthILT.Hub AllowSummonOnEmpty: ACECustom's refill charm); no server plugin = never.
// * Healing pet (UB HealingBuddy subset): summons a heal pet when HP drops, dismisses it
// after the heal lands, holds PetManager's combat summons while it is out.
// * Auto siphon capture (ACECustom MonsterCapture): when enabled, uses the chosen lens on the
// nearest attackable creature within 5 m once it is <=20% health or under 20 HP (Asheron's
// Lens skips the health gate). Resonance still needs a prior failed capture on the server.
// * /pets and /shinies logs: RynthILT's (RynthILT.Hub section "pets-logs", ILT only).
// * Breeding sub-tab (Infinite Leaftide only): the tab becomes Roster | Breeding when RynthILT
// offers it (an ILT world whose server hasn't reported pet breeding off). Its whole body is
// RynthILT's pet breeding tracker (RynthILT.Hub section "pets-breeding"); this tab only hosts it.
// * The server plugin's sections under the roster (RynthILT: "pets-charms", "pets-capture",
// "pets-logs"); each draws nothing off its server.
// * Sub-tabs: the tab becomes Roster | ... when the server plugin offers sub-tabs for it
// (GetSubTabs "pets"; RynthILT's Breeding). Each sub-tab's whole body is the plugin's section.
using System;
using System.Collections.Generic;
using System.Linq;
@ -60,17 +58,6 @@ internal sealed class PetsTab
private long _lastHealThink;
private string _healStatus = "idle";
// Auto siphon-lens capture (ACECustom MonsterCapture).
private long _lastCaptureThink;
private long _captureCooldownUntil;
private volatile string _captureStatus = "off";
private const long CaptureThinkMs = 250;
private const long CaptureCooldownMs = 2500;
private const long CaptureFailBackoffMs = 8000;
// Hard cap on lens uses: the loop stops on reply strings we only guess at, so it is also bounded
// per creature and over all creatures (PetCaptureThrottle).
private readonly PetCaptureThrottle _captureThrottle = new();
// Roster snapshot (rebuilt on the pump thread, read by the render thread).
private volatile PetStats[] _pets = Array.Empty<PetStats>();
private long _lastPetScan;
@ -90,11 +77,6 @@ internal sealed class PetsTab
/// <summary>Mini Remote pet status: "Out", "Ready", "Empty" or "Healing" (empty when there is no pet).</summary>
public string HudPetStatus => _hudPetStatus;
// Charm / supply status cached for the render thread.
private volatile bool _uiRefillActive;
private volatile bool _uiMasteryActive;
private volatile bool _uiHasCasting = true;
// Render-thread only: highlighted row and the sorted view cache.
private int _highlightId;
private PetStats[]? _viewSource;
@ -227,38 +209,14 @@ internal sealed class PetsTab
return _ctx.Inventory.Items().FirstOrDefault(wo => ClassifyKind(wo, out _) == PetKind.Healing);
}
// ── Charms / gates ──────────────────────────────────────────────────────
/// <summary>Summon Essence Refill charm is carried and switched on (or the server stamped the player bool).</summary>
public bool RefillCharmActive()
{
if (_ctx.Inventory.PlayerBool(MiniRemoteInventory.BoolPyrealRefillActive)) return true;
var charm = _ctx.Inventory.FindByWcid(MiniRemoteInventory.WcidSummonRefillCharm);
return charm != null && _ctx.Inventory.CharmStatus(charm) == CharmState.On;
}
public bool MasteryCharmActive()
{
if (_ctx.Ilt.IsOff(RynthIltHub.FeatureUniversalMastery)) return false;
if (_ctx.Inventory.PlayerBool(MiniRemoteInventory.BoolUniversalMasteryActive)) return true;
var charm = _ctx.Inventory.FindByWcid(MiniRemoteInventory.WcidUniversalMasteryCharm);
return charm != null && _ctx.Inventory.CharmStatus(charm) == CharmState.On;
}
// ── Gates ───────────────────────────────────────────────────────────────
/// <summary>
/// PetManager hook: summon from an empty essence (spends banked pyreals) only when the
/// player opted in, the refill charm is active, and the server has positively confirmed
/// the feature: either /ilt features reported pet_refill on, or the server stamped the
/// player's refill bool. An unknown feature state never spends.
/// PetManager hook: summon from an empty essence only when the server plugin says the server
/// refills it (RynthILT: ACECustom's Summon Essence Refill charm, opted in and confirmed by the
/// server). Without a server plugin, or when it is unsure, never: an empty essence isn't used.
/// </summary>
public bool AllowSummonOnEmpty()
{
if (!S.UsePyrealRefillPath || !_ctx.Ilt.IsIltWorld || !RefillCharmActive()) return false;
bool confirmed = _ctx.Ilt.IsOn(RynthIltHub.FeaturePetRefill)
|| _ctx.Inventory.PlayerBool(MiniRemoteInventory.BoolPyrealRefillActive);
if (!confirmed) RynthLog.Trace(LogCat.Pets, "summon-on-empty refused: pet_refill not confirmed by the server");
return confirmed;
}
public bool AllowSummonOnEmpty() => _ctx.ServerHub.AllowSummonOnEmpty();
/// <summary>PetManager hook: hold combat summons while the heal pet cycle is running.</summary>
public bool HoldCombatSummons() => _heal != HealState.Idle;
@ -293,21 +251,12 @@ internal sealed class PetsTab
{
_lastPetScan = nowMs;
RebuildPetSnapshot(autoAppraise: true);
// Host reads (and appraisal requests) happen here, never on the render thread.
_uiRefillActive = RefillCharmActive();
_uiMasteryActive = MasteryCharmActive();
_uiHasCasting = _ctx.Inventory.HasCastingSupplies();
}
if (nowMs - _lastHealThink >= 250)
{
_lastHealThink = nowMs;
TickHealing(nowMs);
}
if (nowMs - _lastCaptureThink >= CaptureThinkMs)
{
_lastCaptureThink = nowMs;
TickCapture(nowMs);
}
if (nowMs - _lastPresenceThink >= 1000)
{
_lastPresenceThink = nowMs;
@ -354,50 +303,9 @@ internal sealed class PetsTab
}
}
// ACECustom MonsterCapture replies — back off after a refuse so we don't burn lenses.
if (S.AutoCaptureEnabled && text.Length > 0)
{
long now = MiniRemoteContext.NowMs;
if (PetCaptureLines.IsSuccess(text))
{
_captureStatus = "captured";
_captureThrottle.RecordSuccess();
_captureCooldownUntil = now + CaptureCooldownMs;
}
else if (ContainsAny(text,
"too strong",
"blind rage",
"cannot be siphoned",
"cannot be captured",
"No creatures nearby",
"already dead",
"already being captured",
"hasn't failed a capture",
"echo has faded",
"Failed to consume"))
{
_captureStatus = "refused: " + Truncate(text, 48);
_captureCooldownUntil = now + CaptureFailBackoffMs;
}
else if (ContainsAny(text, "siphon failed", "lens shatters", "resisted your capture", "resonance fades"))
{
_captureStatus = "failed (creature may enrage)";
_captureCooldownUntil = now + CaptureFailBackoffMs;
}
}
return false;
}
private static bool ContainsAny(string text, params string[] parts)
{
foreach (string p in parts)
if (text.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0) return true;
return false;
}
private static string Truncate(string s, int max)
=> s.Length <= max ? s : s[..(max - 3)] + "...";
public void OnLogout()
{
_heal = HealState.Idle;
@ -406,9 +314,6 @@ internal sealed class PetsTab
_lastSummonEssenceId = 0;
_cosmeticOutEssenceId = 0;
_cosmeticNextAt = 0;
_captureCooldownUntil = 0;
_captureStatus = "off";
_captureThrottle.Reset();
}
// ── Healing pet ─────────────────────────────────────────────────────────
@ -479,154 +384,6 @@ internal sealed class PetsTab
// ── Active pet ──────────────────────────────────────────────────────────
// ── Auto siphon capture (ACECustom MonsterCapture) ───────────────────────
/// <summary>
/// When Auto Capture is on, use the chosen siphon lens on the nearest attackable creature
/// within 5 m once ACECustom's health gate is met (≤20% or under 20 HP; Asheron's skips it).
/// The server picks the nearest creature itself — we only fire when that nearest candidate is
/// already weak enough, so a full-health neighbour closer than the wounded target won't waste a lens.
/// </summary>
private void TickCapture(long now)
{
if (!S.AutoCaptureEnabled)
{
_captureStatus = "off";
return;
}
if (_ctx.Ilt.Loaded && _ctx.Ilt.IsOff(RynthIltHub.FeatureMonsterCapture))
{
_captureStatus = "monster capture disabled on this server";
return;
}
if (now < _captureCooldownUntil)
{
long left = (_captureCooldownUntil - now + 999) / 1000;
if (!_captureStatus.StartsWith("waiting", StringComparison.Ordinal))
_captureStatus = $"waiting {left}s";
return;
}
if (_ctx.Inventory.IsBusy) { _captureStatus = "busy"; return; }
var lens = PetCaptureRules.LensAt(S.CaptureLensIndex);
var lensItem = _ctx.Inventory.FindByWcid(lens.Wcid);
if (lensItem == null)
{
_captureStatus = $"no {lens.Name} carried";
return;
}
if (!TryFindNearestCaptureTarget(out WorldObject? target, out double distM, out uint curHp, out uint maxHp))
{
_captureStatus = "no attackable creature within 5 m";
return;
}
if (!PetCaptureRules.InRange(distM))
{
_captureStatus = $"{target!.Name} at {distM:0.0} m (need <={PetCaptureRules.CaptureRangeM:0} m)";
return;
}
if (!PetCaptureRules.CanAttempt(lens, curHp, maxHp))
{
float pct = maxHp > 0 ? curHp * 100f / maxHp : -1f;
_captureStatus = pct >= 0
? $"{target!.Name} at {pct:0}% / {curHp} HP (need <={PetCaptureRules.CaptureMaxHealthFraction:P0} or <{PetCaptureRules.CaptureMaxHealthPoints} HP)"
: $"{target!.Name}: health unknown";
return;
}
if (!_captureThrottle.MayAttempt(target!.Id, now))
{
_captureStatus = $"{target.Name}: {PetCaptureThrottle.MaxTriesPerTarget} tries, no capture; left alone for {_captureThrottle.BlockedSecondsLeft(target.Id, now)}s";
return;
}
if (!_ctx.Inventory.Use(lensItem))
{
_captureStatus = "UseObject refused";
return;
}
_captureThrottle.RecordAttempt(target.Id, now);
if (_captureThrottle.Exhausted)
{
// Backstop: this many lenses with no recognized capture means something is off. Stop, don't keep burning them.
S.AutoCaptureEnabled = false;
RynthLog.Write(LogCat.Pets,
$"[Pets] auto-capture: {PetCaptureThrottle.MaxTriesWithoutSuccess} lens uses without a capture reply; auto-capture switched off");
}
float shown = maxHp > 0 ? curHp * 100f / maxHp : 0f;
_captureStatus = $"using {lens.Name} on {target!.Name} ({shown:0}% / {curHp} HP)";
_captureCooldownUntil = now + CaptureCooldownMs;
RynthLog.Write(LogCat.Pets,
$"[Pets] auto-capture: {lens.Name} -> 0x{target.Id:X8} '{target.Name}' d={distM:0.0}m hp={curHp}/{maxHp}");
}
/// <summary>
/// Nearest attackable landscape creature within capture range, with vitals from the host when
/// available else the cache health ratio (fraction-only gate).
/// </summary>
private bool TryFindNearestCaptureTarget(out WorldObject? best, out double bestDist, out uint curHp, out uint maxHp)
{
best = null;
bestDist = double.MaxValue;
curHp = maxHp = 0;
var cache = _ctx.Inventory.Cache;
if (cache == null) return false;
uint playerId = _ctx.Inventory.PlayerId;
if (playerId == 0) return false;
int pid = unchecked((int)playerId);
string ownPrefix = _ctx.CharName.Length > 0 ? _ctx.CharName + "'s " : string.Empty;
foreach (var wo in cache.GetLandscape())
{
if (wo == null || wo.Id == pid) continue;
if (wo.ObjectClass != AcObjectClass.Monster) continue;
if (ownPrefix.Length > 0 && wo.Name.StartsWith(ownPrefix, StringComparison.Ordinal)) continue;
// Skip corpses / non-attackable when the host can tell.
if (_ctx.Host.HasObjectIsAttackable && !_ctx.Host.ObjectIsAttackable(unchecked((uint)wo.Id)))
continue;
double d = cache.Distance(pid, wo.Id);
if (d < 0 || d > PetCaptureRules.CaptureRangeM || d >= bestDist) continue;
if (!TryReadCreatureVitals(wo.Id, cache, out uint c, out uint m))
continue;
if (c == 0) continue; // dead
best = wo;
bestDist = d;
curHp = c;
maxHp = m;
}
return best != null;
}
/// <summary>
/// Absolute vitals via TryGetTargetVitals when bound; else cache health ratio as a 0–1000 scale
/// so only the fraction half of ACECustom's gate can fire.
/// </summary>
private bool TryReadCreatureVitals(int id, WorldObjectCache cache, out uint cur, out uint max)
{
cur = max = 0;
if (_ctx.Host.HasGetTargetVitals
&& _ctx.Host.TryGetTargetVitals(unchecked((uint)id), out uint h, out uint mh, out _, out _, out _, out _)
&& mh > 0)
{
cur = h;
max = mh;
return true;
}
float ratio = cache.GetHealthRatio(id);
if (ratio < 0f) return false;
// Synthetic scale: ratio 0.20 → 200/1000 so IsWeakEnough's fraction half matches.
max = 1000;
cur = (uint)Math.Clamp((int)Math.Round(ratio * 1000f), 1, 1000);
return true;
}
/// <summary>The live "&lt;Me&gt;'s …" creature (server pet naming), or null.</summary>
private WorldObject? FindOwnPet()
{
@ -909,28 +666,54 @@ internal sealed class PetsTab
// ── UI (render thread) ──────────────────────────────────────────────────
/// <summary>Set from any thread: the next frame opens the Breeding sub-tab ("/ra hub open breeding").</summary>
private volatile bool _selectBreeding;
/// <summary>Set from any thread: the sub-tab the next frame opens ("/ra hub open breeding"); null = none.</summary>
private volatile string? _selectSubTab;
/// <summary>Shows the Breeding sub-tab on the next frame (any thread).</summary>
public void SelectBreeding() => _selectBreeding = true;
/// <summary>Shows sub-tab <paramref name="id"/> (a server plugin's section id) on the next frame (any thread).</summary>
public void SelectSubTab(string id) => _selectSubTab = id;
/// <summary>The sub-tab a command asked for and the next frame will open; null = none. For the tests.</summary>
internal string? PendingSubTab => _selectSubTab;
/// <summary>The sub-tabs the server plugin adds to this tab now (RynthILT's Breeding); empty without one.</summary>
public IReadOnlyList<ServerTabInfo> SubTabs() => _ctx.ServerHub.SubTabs(RynthIltHub.TabParentPets);
/// <summary>
/// RynthILT offers the Breeding sub-tab: it calls this world Infinite Leaftide and the server
/// hasn't reported pet breeding off. False without RynthILT. Any thread.
/// The shown sub-tab a "/ra hub open|tab &lt;name&gt;" names: its label ("Breeding"), its id, or its id
/// without the "pets-" prefix ("breeding"; at least four letters of it, "breed"), case-insensitive.
/// Null when the server plugin offers none such.
/// </summary>
public bool BreedingOffered => _ctx.Ilt.IsIltWorld && !_ctx.Ilt.IsOff(RynthIltHub.FeaturePetBreeding);
public string? FindSubTab(string name)
{
string n = (name ?? string.Empty).Trim();
if (n.Length == 0) return null;
foreach (ServerTabInfo t in SubTabs())
{
if (!t.Shown) continue;
string shortId = t.Id.StartsWith(SubTabPrefix, StringComparison.OrdinalIgnoreCase) ? t.Id[SubTabPrefix.Length..] : t.Id;
if (t.Label.Equals(n, StringComparison.OrdinalIgnoreCase) || t.Id.Equals(n, StringComparison.OrdinalIgnoreCase)
|| shortId.Equals(n, StringComparison.OrdinalIgnoreCase)
|| (n.Length >= 4 && shortId.StartsWith(n, StringComparison.OrdinalIgnoreCase)))
return t.Id;
}
return null;
}
private const string SubTabPrefix = RynthIltHub.TabParentPets + "-";
/// <summary>
/// The Pets tab: the universal roster, and on Infinite Leaftide the Roster | Breeding sub-tabs
/// (Breeding is drawn by RynthILT).
/// The Pets tab: the universal roster, and Roster | ... sub-tabs when the server plugin adds some
/// (each drawn by that plugin).
/// </summary>
public void Render()
{
var settings = _ctx.Settings;
if (settings == null) { ImGui.TextDisabled("Not logged in."); return; }
if (!BreedingOffered)
var subTabs = SubTabs();
bool any = false;
foreach (ServerTabInfo t in subTabs) any |= t.Shown;
if (!any)
{
RenderRoster(settings);
return;
@ -941,19 +724,34 @@ internal sealed class PetsTab
RenderRoster(settings);
ImGui.EndTabItem();
}
ImGuiTabItemFlags breedFlags = _selectBreeding ? ImGuiTabItemFlags.SetSelected : ImGuiTabItemFlags.None;
_selectBreeding = false;
if (BeginTab(BreedingTabLabel, breedFlags))
string? select = System.Threading.Interlocked.Exchange(ref _selectSubTab, null);
foreach (ServerTabInfo t in subTabs)
{
// RynthILT's tracker; an older RynthILT (before 0.3.1) has no such section and draws nothing.
if (!_ctx.Ilt.RenderSection(RynthIltHub.SectionPetBreeding))
ImGui.TextDisabled("This RynthILT has no pet breeding tracker; update RynthILT to 0.3.1 or later.");
if (!t.Shown) continue;
ImGuiTabItemFlags flags = select != null && select.Equals(t.Id, StringComparison.OrdinalIgnoreCase)
? ImGuiTabItemFlags.SetSelected : ImGuiTabItemFlags.None;
if (!BeginTab(SubTabLabel(t), flags)) continue;
if (!_ctx.ServerHub.RenderSection(t.Id))
SafeImGui.TextDisabled("Not ready (the server plugin isn't drawing it).");
ImGui.EndTabItem();
}
ImGui.EndTabBar();
}
private static readonly byte[] BreedingTabLabel = System.Text.Encoding.UTF8.GetBytes("Breeding##petbreeding\0");
// Sub-tab labels as NUL-terminated UTF-8, built once per label (the tab bar runs every frame).
private readonly Dictionary<string, byte[]> _subTabLabels = new(StringComparer.Ordinal);
private byte[] SubTabLabel(ServerTabInfo t)
{
string key = t.Label + "##petsub_" + t.Id;
if (!_subTabLabels.TryGetValue(key, out byte[]? label))
{
label = new byte[System.Text.Encoding.UTF8.GetByteCount(key) + 1];
System.Text.Encoding.UTF8.GetBytes(key, 0, key.Length, label, 0);
_subTabLabels[key] = label;
}
return label;
}
/// <summary>
/// BeginTabItem with flags but no close button (ImGui.NET pairs the flags overload with p_open,
@ -965,58 +763,18 @@ internal sealed class PetsTab
return ImGuiNative.igBeginTabItem(label, null, flags) != 0;
}
/// <summary>The universal roster: types, summons, ILT charms, healing pets and RynthILT's /pets logs.</summary>
/// <summary>The universal roster: types, summons, healing pets, and the server plugin's sections.</summary>
private void RenderRoster(LegacyUiSettings settings)
{
RenderRosterHeader(settings);
RenderRosterTable();
// The tab is universal; the charms and the /pets and /shinies logs are ILT's (the logs RynthILT's).
bool ilt = _ctx.Ilt.IsIltWorld;
if (ilt)
{
ImGui.Separator();
RenderCharms();
ImGui.Separator();
RenderCapture();
}
// The server plugin's own pet features (RynthILT: ACECustom's charms and siphon capture);
// each draws its own separator, and nothing off its server.
_ctx.ServerHub.RenderSection(RynthIltHub.SectionPetCharms);
_ctx.ServerHub.RenderSection(RynthIltHub.SectionPetCapture);
ImGui.Separator();
RenderHealing();
_ctx.Ilt.RenderSection(RynthIltHub.SectionPetLogs);
}
/// <summary>ACECustom siphon-lens auto-capture (ILT only): enable + which lens to use.</summary>
private void RenderCapture()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Monster capture");
bool captureOff = _ctx.Ilt.IsOff(RynthIltHub.FeatureMonsterCapture);
ImGui.BeginDisabled(captureOff);
bool en = S.AutoCaptureEnabled;
if (ImGui.Checkbox("Auto-capture when a creature is weak enough", ref en))
{
S.AutoCaptureEnabled = en;
_captureThrottle.Reset();
}
if (ImGui.IsItemHovered())
{
SafeImGui.SetTooltip(
"Uses the selected siphon lens on the nearest attackable creature within 5 m once it is\n" +
"at or below 20% health or under 20 HP (ACECustom MonsterCapture). Asheron's Lens skips\n" +
"the health gate. Resonance Lens still needs a prior failed capture on the server.\n" +
"Off by default. Stops on its own after 5 tries on one creature (it is left alone for 2 min)\n" +
"or 15 lens uses in a row with no capture.");
}
ImGui.SameLine();
ImGui.SetNextItemWidth(120);
int lens = Math.Clamp(S.CaptureLensIndex, 0, PetCaptureRules.LensNames.Length - 1);
if (ImGui.Combo("##petcapturelens", ref lens, PetCaptureRules.LensNames, PetCaptureRules.LensNames.Length))
S.CaptureLensIndex = lens;
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("Which siphon lens to use. Must be carried in your pack.");
ImGui.EndDisabled();
if (captureOff)
SafeImGui.TextDisabled("Monster capture is disabled on this server.");
else
SafeImGui.TextDisabled("Status: " + _captureStatus);
_ctx.ServerHub.RenderSection(RynthIltHub.SectionPetLogs);
}
/// <summary>Type / Sort combos, action buttons, the active-summon line and per-type options.</summary>
@ -1189,22 +947,6 @@ internal sealed class PetsTab
_ => new Vector4(0.95f, 0.95f, 0.95f, 1f),
};
private void RenderCharms()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Pet charms");
bool refillOff = _ctx.Ilt.IsOff(RynthIltHub.FeaturePetRefill);
ImGui.TextUnformatted("Summon Essence Refill: " + (refillOff ? "disabled on this server" : _uiRefillActive ? "ON" : "off / not carried"));
ImGui.BeginDisabled(refillOff);
bool usePath = S.UsePyrealRefillPath;
if (ImGui.Checkbox("Summon from empty essences while the refill charm is ON (spends banked pyreals)", ref usePath))
S.UsePyrealRefillPath = usePath;
ImGui.EndDisabled();
ImGui.TextUnformatted("Universal Summoning Mastery: "
+ (_ctx.Ilt.IsOff(RynthIltHub.FeatureUniversalMastery) ? "disabled on this server" : _uiMasteryActive ? "ON" : "off / not carried"));
if (!_ctx.Ilt.IsOff(RynthIltHub.FeatureRequireComps) && !_uiHasCasting)
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "No spell components or Infinite Casting Stone carried.");
}
private void RenderHealing()
{
if (!ImGui.CollapsingHeader("Healing pet settings")) return;

View file

@ -0,0 +1,303 @@
// ServerHubClient.cs - RynthAi's side of a server plugin's hub (the "RynthILT.Hub" table layout,
// Plugins/Shared/RynthIltHubApi.cs; was IltClient until 2026-10-20): the tabs, sub-tabs and sections
// the Mini Remote hosts for the server you're on, its feature bits (the Quests tab's /myquests bit),
// its texts and settings, its "/ra" verbs, and its pet gate. RynthAi knows no server's content: it
// shows what the plugin offers.
//
// The plugin is found by the engine's server list first (the active server's owner plugin, under the
// neutral name "RynthServer.Hub"), then RynthILT under "RynthILT.Hub" (every RynthILT answers that;
// older ones only that). Without one (not installed, too old, not loaded yet: any retail-like world)
// every call answers "nothing": no tab, no section, unknown feature bits, no verbs. The table is
// looked up on the pump thread (Tick) at most every RecheckMs and kept in a volatile field for the
// render thread; the plugin never frees it (Version goes to 0 on its shutdown), so reading a stale
// pointer is safe and a Version of 0 means "look again".
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.MiniRemote;
/// <summary>One tab as the server plugin describes it (a copy).</summary>
internal readonly record struct ServerTabInfo(string Id, string Label, float Width, float Height, bool Shown, bool Available);
internal sealed unsafe class ServerHubClient
{
private const long RecheckMs = 3000;
private const int MaxTabs = 16;
private readonly RynthCoreHost _host;
private IntPtr _table; // volatile reads/writes: the render thread uses what the pump found
private long _checkedAt;
private bool _checkedOnce; // false: look now (a sentinel time would overflow "now - _checkedAt")
private readonly IltTabV1[] _tabBuf = new IltTabV1[MaxTabs];
private readonly List<ServerTabInfo> _tabs = new();
private bool _pinned; // tests: a table handed in, never looked up
public ServerHubClient(RynthCoreHost host) => _host = host;
/// <summary>Tests only: use <paramref name="table"/> (a fake server plugin's table) and never look it up.</summary>
internal void UseTableForTests(IntPtr table)
{
_pinned = true;
_checkedOnce = true;
System.Threading.Volatile.Write(ref _table, table);
}
/// <summary>Pump thread: look the table up again when it's due, missing or shut down.</summary>
public void Tick()
{
if (_pinned) return;
long now = Environment.TickCount64;
var t = (RynthIltHubApiV1*)System.Threading.Volatile.Read(ref _table);
if (!LookupDue(_checkedOnce, _checkedAt, now, haveTable: t != null, tableLive: t != null && t->Version >= 1)) return;
_checkedOnce = true;
_checkedAt = now;
IntPtr found = IntPtr.Zero;
if (_host.HasGetPluginInterface)
{
// The active server's own plugin (the engine's server list), under the neutral name ...
string owner = ActiveServerPlugin();
if (owner.Length > 0) found = Look(owner, RynthIltHubApiV1.NeutralInterfaceName);
// ... else RynthILT under its own name (every RynthILT; it also follows its own world check).
if (found == IntPtr.Zero) found = Look(RynthIltHub.PluginName, RynthIltHubApiV1.InterfaceName);
}
System.Threading.Volatile.Write(ref _table, found);
}
/// <summary>A hub table <paramref name="plugin"/> serves as <paramref name="iface"/>, or 0.</summary>
private IntPtr Look(string plugin, string iface)
{
var p = (RynthIltHubApiV1*)_host.GetPluginInterface(plugin, iface, RynthIltHubApiV1.InterfaceVersion);
// Any table at least as big as the first release's: newer functions are checked with Has.
return p != null && p->Version >= 1 && p->StructSize >= RynthIltHubApiV1.BaseStructSize ? (IntPtr)p : IntPtr.Zero;
}
/// <summary>The plugin that owns the engine's active server ("" when none, or the engine is pre-v86). Pump thread.</summary>
private string ActiveServerPlugin()
{
try
{
if (!_host.HasGetServerStateJson || !_host.TryGetServerStateJson(out string json)) return string.Empty;
return EngineServerState.Parse(json)?.ActivePlugin ?? string.Empty;
}
catch { return string.Empty; }
}
/// <summary>Forget the table (login, logout); the next Tick looks again.</summary>
public void Reset()
{
_pinned = false;
System.Threading.Volatile.Write(ref _table, IntPtr.Zero);
_checkedOnce = false;
}
/// <summary>
/// Whether Tick looks the table up again. Pure. Always on the first call (and after Reset), at
/// once when the table RynthILT gave is shut down (Version 0), else every <see cref="RecheckMs"/>.
/// </summary>
internal static bool LookupDue(bool checkedOnce, long checkedAt, long now, bool haveTable, bool tableLive)
{
if (!checkedOnce) return true;
if (haveTable && !tableLive) return true;
return now - checkedAt >= RecheckMs;
}
private RynthIltHubApiV1* T
{
get
{
var t = (RynthIltHubApiV1*)System.Threading.Volatile.Read(ref _table);
return t != null && t->Version >= 1 ? t : null;
}
}
/// <summary>A server plugin answers (any thread).</summary>
public bool Loaded => T != null;
/// <summary>This world is the plugin's server (or forced there), as it sees it (RynthILT: Infinite Leaftide). Any thread.</summary>
public bool ServerActive
{
get
{
var t = T;
return t != null && t->IsIltWorld != null && t->IsIltWorld() != 0;
}
}
/// <summary>The server's bit for a feature: -1 unknown (and always off its server / without a plugin), 0 off, 1 on. Any thread.</summary>
public int Feature(string key)
{
var t = T;
if (t == null || t->GetFeature == null) return -1;
using var k = new Utf8(key);
return t->GetFeature(k.P);
}
/// <summary>The server positively reported the feature off.</summary>
public bool IsOff(string key) => Feature(key) == 0;
/// <summary>The server positively reported the feature on.</summary>
public bool IsOn(string key) => Feature(key) == 1;
/// <summary>
/// A short text from the server plugin (RynthIltHub.Text*: the session report's tail, its server id);
/// "" without one, from an older one, or for nothing. Any thread.
/// </summary>
public string Text(string id)
{
var t = T;
if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetTextOffset) || t->GetText == null) return string.Empty;
byte* buf = stackalloc byte[256];
buf[0] = 0;
int n;
using (var k = new Utf8(id)) n = t->GetText(k.P, buf, 256);
if (n <= 0) return string.Empty;
buf[255] = 0;
return Marshal.PtrToStringUTF8((IntPtr)buf) ?? string.Empty;
}
/// <summary>
/// This character forces the plugin's server (RynthILT: "Treat this world as ILT"; set there or in
/// RynthCore's Options > Diagnostics, never by RynthAi). Any thread.
/// </summary>
public bool ServerForced
{
get
{
var t = T;
return t != null && t->GetForceIlt != null && t->GetForceIlt() != 0;
}
}
/// <summary>Render thread: the plugin's tabs with their flags (empty without one). The list is reused.</summary>
public IReadOnlyList<ServerTabInfo> Tabs()
{
_tabs.Clear();
var t = T;
if (t == null || t->GetTabs == null) return _tabs;
int n;
fixed (IltTabV1* buf = _tabBuf) n = t->GetTabs(buf, MaxTabs);
n = Math.Min(n, MaxTabs);
for (int i = 0; i < n; i++)
{
ref IltTabV1 tab = ref _tabBuf[i];
string id, label;
fixed (byte* pid = tab.Id) id = Marshal.PtrToStringUTF8((IntPtr)pid) ?? string.Empty;
fixed (byte* plabel = tab.Label) label = Marshal.PtrToStringUTF8((IntPtr)plabel) ?? string.Empty;
if (id.Length == 0) continue;
_tabs.Add(new ServerTabInfo(id, label.Length > 0 ? label : id, tab.Width, tab.Height,
(tab.Flags & RynthIltHub.TabShown) != 0, (tab.Flags & RynthIltHub.TabAvailable) != 0));
}
return _tabs;
}
/// <summary>Render thread: one ILT tab's body into the current child window; false = nothing drawn.</summary>
public bool RenderTab(string id)
{
var t = T;
if (t == null || t->RenderTab == null) return false;
using var s = new Utf8(id);
return t->RenderTab(s.P) != 0;
}
/// <summary>Render thread: an ILT section (RynthIltHub.Section*); false = nothing drawn (not ILT, or no RynthILT).</summary>
public bool RenderSection(string id)
{
var t = T;
if (t == null || t->RenderSection == null) return false;
using var s = new Utf8(id);
return t->RenderSection(s.P) != 0;
}
/// <summary>An ILT "/ra" verb ("hub bank", "guardian handin", ...); false when RynthILT doesn't take it.</summary>
public bool Command(string text)
{
var t = T;
if (t == null || t->Command == null) return false;
using var s = new Utf8(text);
return t->Command(s.P) != 0;
}
/// <summary>
/// The server plugin's answer to "may an EMPTY pet essence be summoned?" (the server refills it;
/// RynthILT: ACECustom's Summon Essence Refill charm). False without one, or from an older one
/// that doesn't answer: an empty essence is then never used. Any thread.
/// </summary>
public bool AllowSummonOnEmpty()
{
var t = T;
return t != null && RynthIltHubApiV1.Has(t, RynthIltHubApiV1.AllowSummonOnEmptyOffset)
&& t->AllowSummonOnEmpty != null && t->AllowSummonOnEmpty() != 0;
}
/// <summary>One of the server plugin's mirrored settings (RynthIltHub.Setting*): its value, -1 when not offered. Any thread.</summary>
public int Setting(string key)
{
var t = T;
if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetSettingOffset) || t->GetSetting == null) return -1;
using var k = new Utf8(key);
return t->GetSetting(k.P);
}
/// <summary>Changes one of those settings; false when the plugin doesn't take it. Any thread.</summary>
public bool SetSetting(string key, int value)
{
var t = T;
if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.SetSettingOffset) || t->SetSetting == null) return false;
using var k = new Utf8(key);
return t->SetSetting(k.P, value) != 0;
}
private const int MaxSubTabs = 8;
/// <summary>
/// The sub-tabs the server plugin adds to one of the Mini Remote's tabs (<paramref name="parent"/>
/// "pets": RynthILT's Breeding). Each id is a RenderSection id. Empty without one. A new list each
/// call (the render thread draws them, a command looks one up). Any thread.
/// </summary>
public IReadOnlyList<ServerTabInfo> SubTabs(string parent)
{
var t = T;
if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetSubTabsOffset) || t->GetSubTabs == null)
return Array.Empty<ServerTabInfo>();
IltTabV1* buf = stackalloc IltTabV1[MaxSubTabs];
int n;
using (var p = new Utf8(parent)) n = t->GetSubTabs(p.P, buf, MaxSubTabs);
n = Math.Min(n, MaxSubTabs);
if (n <= 0) return Array.Empty<ServerTabInfo>();
var list = new List<ServerTabInfo>(n);
for (int i = 0; i < n; i++)
{
IltTabV1* tab = &buf[i];
tab->Id[23] = 0; // never read past a buffer the other side filled to the brim
tab->Label[31] = 0;
string id = Marshal.PtrToStringUTF8((IntPtr)tab->Id) ?? string.Empty;
string label = Marshal.PtrToStringUTF8((IntPtr)tab->Label) ?? string.Empty;
if (id.Length == 0) continue;
list.Add(new ServerTabInfo(id, label.Length > 0 ? label : id, tab->Width, tab->Height,
(tab->Flags & RynthIltHub.TabShown) != 0, (tab->Flags & RynthIltHub.TabAvailable) != 0));
}
return list;
}
/// <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

@ -2970,9 +2970,24 @@ internal sealed class NavigationEngine
}
}
// Already stopped, StopMovement sends a reminder at most this often (as StartForward re-asserts).
private const long StopReassertMs = 1000;
private long _lastStopSentMs;
private bool _stopSent;
private void StopMovement()
{
// The pause, chat, portal, settle and idle paths call this every tick. It sent autorun-off and
// both turn keys each time even with the character standing still: in portal space the game
// thread takes none of them, 137 piled up and ran 12.7 s late on the far side, against the next
// route leg (Dargoth Hera's report, 2026-10-19). Now it sends when something moves, and a
// reminder once a second while stopped (something else may have started the character).
bool moving = _isMovingForward || _isTurning || _tier1TurnDir != 0;
_isTurning = false;
long now = Now;
if (!moving && _stopSent && now - _lastStopSentMs < StopReassertMs) return;
_stopSent = true;
_lastStopSentMs = now;
StopForward();
ClearTurnMotions();
}

View file

@ -0,0 +1,23 @@
using System;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Your heading as a compass bearing (0 = North, clockwise), from the pose quaternion: the
/// basis of TurnToHeading, map bearings and every nav and combat steer. Host.TryGetPlayerHeading
/// is another basis (0 = East, counter-clockwise: the radar's; measured 2026-10-20, Freya's
/// quaternion 13.9 against its 76.1), so it is never compared with a bearing or turned to.
/// </summary>
internal static class PlayerCompass
{
public static bool TryGet(RynthCoreHost host, out float heading)
{
heading = 0;
if (!host.HasGetPlayerPose || !host.TryGetPlayerPose(out _, out _, out _, out _, out float qw, out _, out _, out float qz))
return false;
double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI);
heading = (float)((-yaw % 360.0 + 720.0) % 360.0);
return true;
}
}

View file

@ -754,34 +754,6 @@ public static unsafe class PluginExports
}
}
private static IntPtr _progressionPtr = IntPtr.Zero;
/// <summary>
/// The Skills panel's Progression tab for an engine that still asks RynthAi: the planners went
/// to RynthILT (2026-10-13), so this passes on RynthILT's RynthILTGetProgressionJson
/// ({"available":false} without RynthILT). Same contract as before: one static buffer, valid
/// until the next call; the engine polls it from its pump thread only. (The Charms Tracking
/// export, RynthPluginGetCharmsJson, for engines up to 2026.10.5.35 is gone with the charms.)
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetProgressionJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetProgressionJson()
{
try
{
var host = Runtime.Plugin?.HostForIlt;
string? json = host is { HasGetPluginExportJson: true } h ? h.GetPluginExportJson("RynthILT", "RynthILTGetProgressionJson") : null;
IntPtr newPtr = Marshal.StringToHGlobalAnsi(string.IsNullOrEmpty(json) ? "{\"available\":false}" : json);
IntPtr oldPtr = Interlocked.Exchange(ref _progressionPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
// ── Items bridge (engine-side Avalonia ItemsPanel) ──────────────────────
private static IntPtr _itemsPtr = IntPtr.Zero;

View file

@ -41,7 +41,6 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra attackable — check if target is attackable");
ChatLine("[RynthAi] /ra wielded — show wielded items");
ChatLine("[RynthAi] /ra dumpprops [0xId] — every property of the selection (else yourself)");
ChatLine("[RynthAi] /ra t11 [augs <n|auto>|refresh|item] — T11 loot: wield counters, aug override, parsed item");
ChatLine("[RynthAi] /ra iteminfo [name] — the selected (or named) item's details, Mag-Tools style");
ChatLine("[RynthAi] /ra mexec <expr> — evaluate meta expression");
ChatLine("[RynthAi] /ra listvars — show session variables");
@ -2497,6 +2496,12 @@ public sealed partial class RynthAiPlugin
private enum GiveItemMatch { Exact, Partial, Regex }
/// <summary>
/// The most stacks one give-all command (/ra givea*, /ub give) queues. A line that matches more
/// than this gives the first MaxGiveAllPerCommand and says so; run it again for the rest.
/// </summary>
internal const int MaxGiveAllPerCommand = 500;
/// <summary>
/// Hands <paramref name="amount"/> of an item to a player or NPC with AC's give action
/// (Event_GiveObjectRequest) when the engine has it; MoveItemExternal is move-to-container
@ -2597,9 +2602,41 @@ public sealed partial class RynthAiPlugin
if (allItems)
{
// Every match goes, except what must never be handed over: equipped gear, the items
// RynthAi uses (Weapons and Consumables lists, monster-rule weapons), attuned and retained
// items, and, for a line a running meta sends, whatever the loot profile keeps. One log
// line per stack queued or skipped, and a cap on how many one command queues.
bool fromMeta = MetaCommandActive;
var toGive = new List<WorldObject>();
int protectedCount = 0;
foreach (var item in matches)
{
string? why = ItemProtectionReason(item, includeLootKeep: fromMeta);
if (why != null)
{
protectedCount++;
Log($"[Give] skipped 0x{(uint)item.Id:X8} '{item.Name}': {why}");
continue;
}
toGive.Add(item);
}
bool capped = toGive.Count > MaxGiveAllPerCommand;
if (capped)
{
Log($"[Give] '{itemPart}' matched {toGive.Count} stacks; the cap is {MaxGiveAllPerCommand}, so only the first {MaxGiveAllPerCommand} are queued.");
toGive.RemoveRange(MaxGiveAllPerCommand, toGive.Count - MaxGiveAllPerCommand);
}
foreach (var item in toGive)
{
EnqueueGive((uint)item.Id, (uint)target.Id, 0); // 0 = the whole stack, whatever it reads at send time
ChatLine($"[RynthAi] Queued {matches.Count} stack(s) matching '{itemPart}' → {target.Name}");
Log($"[Give] queued 0x{(uint)item.Id:X8} '{item.Name}' x{Math.Max(1, item.Values(LongValueKey.StackCount, 1))} -> {target.Name}{(fromMeta ? " (from a running meta)" : "")}");
}
string skippedNote = protectedCount > 0 ? $", {protectedCount} protected stack(s) skipped" : "";
string capNote = capped ? $", capped at {MaxGiveAllPerCommand}: run it again for the rest" : "";
if (toGive.Count == 0)
ChatLine($"[RynthAi] Nothing to give: every item matching '{itemPart}' is protected ({protectedCount} skipped).");
else
ChatLine($"[RynthAi] Queued {toGive.Count} stack(s) matching '{itemPart}' → {target.Name}{skippedNote}{capNote}");
}
else if (countGiven)
{

View file

@ -1,6 +1,6 @@
// RynthAiPlugin.LocalFeatures.cs — the Mini Remote's universal tabs, floating HUDs, chat
// translation, item info, the nav overlay and the UB damage seed. (The ILT Hub moved to the RynthILT
// plugin 2026-10-13: its tabs come through RynthILT.Hub, MiniRemote/IltClient.cs, and RynthILT
// plugin 2026-10-13: its tabs come through RynthILT.Hub, MiniRemote/ServerHubClient.cs, and RynthILT
// borrows from RynthAi through RynthAi.Hub, HubInterface.cs.)
//
// The engine draws the main panels. These features draw their own ImGui windows from
@ -20,8 +20,8 @@ public sealed partial class RynthAiPlugin
private NavBreadcrumbTracker? _navBreadcrumbs;
private NavOverlayRenderer? _navOverlay;
private MiniRemote.MiniRemoteController? _miniRemote;
// RynthILT's side of the Mini Remote (its ILT tabs, sections, feature bits); lives for the plugin.
private MiniRemote.IltClient? _ilt;
// The server plugin's side of the Mini Remote (its tabs, sections, feature bits, verbs; RynthILT on ILT); lives for the plugin.
private MiniRemote.ServerHubClient? _serverHub;
private Huds.HudController? _huds;
private Huds.HudIconCache? _hudIcons;
private Translate.ChatTranslator? _translator;
@ -120,10 +120,14 @@ public sealed partial class RynthAiPlugin
return;
var dash = _dashboard;
_ilt ??= new MiniRemote.IltClient(Host);
_serverHub ??= new MiniRemote.ServerHubClient(Host);
// The engine's Settings window mirrors the server plugin's own settings (RynthILT's Vaulted Dungeons switch).
var ilt = _serverHub;
dash.ServerSettingGet = key => ilt.Setting(key);
dash.ServerSettingSet = (key, value) => ilt.SetSetting(key, value);
_miniRemote = new MiniRemote.MiniRemoteController(Host, dash.CharFolder,
() => _objectCache, () => dash.Settings, () => _questTracker,
() => dash.SaveSettings(), _ilt);
() => dash.SaveSettings(), _serverHub);
_hudIcons ??= new Huds.HudIconCache(Host, () => _raycast?.GeometryLoader?.PortalDat);
_huds = new Huds.HudController(Host, dash.CharFolder, () => _objectCache, dash, () => _miniRemote, _hudIcons,
() => _combatManager?.activeTargetId ?? 0)
@ -159,9 +163,20 @@ public sealed partial class RynthAiPlugin
internal MiniRemote.MiniRemoteController? MiniRemoteForIlt => _miniRemote;
internal WorldObjectCache? ObjectCacheForIlt => _objectCache;
internal RynthCore.Plugin.Shared.SessionStatsTracker? SessionStatsForIlt => _sessionStats;
/// <summary>The Vaulted Dungeons master switch (Settings > Navigation); false before login.</summary>
/// <summary>
/// RynthAi.Hub VaultedDungeonsEnabled (obsolete slot): the value the profile still carries, which
/// RynthILT copied once and owns since 2026-10-20 (an older RynthILT still reads it here); false before login.
/// </summary>
internal bool VaultedDungeonsEnabledForIlt => _dashboard?.Settings.EnableVaultedDungeons == true;
/// <summary>RynthAi.Hub BackAwayFrom: combat's back-away (CombatManager.BackAwayFrom); not now before login. Pump thread.</summary>
internal int BackAwayForServer(uint objectId, float radiusYards, int holdMs)
{
var combat = _combatManager;
if (combat == null || !_loginComplete) return RynthCore.Plugin.Shared.RynthAiHub.BackAwayNotNow;
return combat.BackAwayFrom(unchecked((int)objectId), radiusYards, holdMs, "server plugin");
}
/// <summary>Item Info window, created once settings exist.</summary>
private void EnsureItemInfoUi()
{
@ -177,8 +192,8 @@ public sealed partial class RynthAiPlugin
catch (Exception ex) { Host.Log($"[RynthAi] diagnostics pump: {ex.Message}"); }
try { _sessionStats?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats tick"); }
try { _ilt?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "RynthILT lookup"); }
try { _serverHub?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "server plugin hub lookup"); }
try { _miniRemote?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "Mini Remote Tick"); }
try { _huds?.Tick(); }
@ -191,7 +206,6 @@ public sealed partial class RynthAiPlugin
catch (Exception ex) { RynthLog.Exception(LogCat.General, ex, "spells window tick"); }
try { _navBreadcrumbs?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Navigation, ex, "nav breadcrumbs tick"); }
Loot.T11ItemSupport.SyncOverride(_dashboard?.Settings.T11ItemAugsOverride ?? -1);
}
/// <summary>Drop per-character feature objects. The translator is disposed only on plugin shutdown.</summary>
@ -205,7 +219,7 @@ public sealed partial class RynthAiPlugin
try { _miniRemote?.OnLogout(); }
catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "Mini Remote logout"); }
_miniRemote = null;
_ilt?.Reset();
_serverHub?.Reset();
try { _huds?.OnLogout(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "logout"); }
_huds = null;
@ -400,7 +414,8 @@ public sealed partial class RynthAiPlugin
/// Remote sections (Huds/SectionsManifest.cs lists them), drawn into the engine's current
/// window (and context, see <see cref="EmbedContext"/>) at <paramref name="size"/>.
/// <paramref name="want"/> is the size the view would like. False (nothing drawn) for an
/// unknown view, or until login and the view's owner exist (RynthILT for the ILT tabs). Render thread.
/// unknown view, or until login and the view's owner exist. (A server plugin's tab views are its own:
/// RynthILT draws its ILT tabs since 2026-10-20.) Render thread.
/// </summary>
public bool RenderEmbeddedSection(string surface, System.Numerics.Vector2 size, out System.Numerics.Vector2 want)
{
@ -427,14 +442,6 @@ public sealed partial class RynthAiPlugin
want = MiniRemoteTabs.Size(ownTab);
draw = () => remote.RenderTab(ownTab);
}
else if (Huds.SectionsManifest.TryIltTabOf(surface, out string iltTab))
{
if (remote == null || !remote.Ilt.Loaded) return false;
foreach (IltTabInfo t in remote.Ilt.Tabs())
if (string.Equals(t.Id, iltTab, StringComparison.OrdinalIgnoreCase) && t.Width > 0 && t.Height > 0)
want = new System.Numerics.Vector2(t.Width, t.Height);
draw = () => remote.Ilt.RenderTab(iltTab);
}
else if (surface == Huds.SectionsManifest.SpellsSurface)
{
EnsureSpellsUi();
@ -466,16 +473,14 @@ public sealed partial class RynthAiPlugin
}
/// <summary>
/// RynthPluginGetSectionsJson: what RynthAi adds to RynthCore's Mini Remote sections, from
/// what is available now (Huds/SectionsManifest.cs; RynthILT's tabs through RynthILT.Hub).
/// Null before login (RynthCore then shows none of RynthAi's views). Render thread.
/// RynthPluginGetSectionsJson: what RynthAi adds to RynthCore's Mini Remote sections (Huds/
/// SectionsManifest.cs; a server plugin lists its own). Null before login (RynthCore then shows
/// none of RynthAi's views). Render thread.
/// </summary>
public string? BuildSectionsJson()
{
if (!_initialized || !_loginComplete) return null;
var remote = _miniRemote;
IReadOnlyList<IltTabInfo> iltTabs = remote != null ? remote.Ilt.Tabs() : Array.Empty<IltTabInfo>();
return Huds.SectionsManifest.Build(Huds.SectionsManifest.Views(iltTabs), Huds.SectionsManifest.OwnSections);
return Huds.SectionsManifest.Build(Huds.SectionsManifest.Views(), Huds.SectionsManifest.OwnSections);
}
/// <summary>Chat Translate window in the dashboard colours (no-op while hidden).</summary>
private void RenderTranslateWindow()
@ -494,16 +499,6 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] " + _huds.HandleCommand(which, mode));
}
/// <summary>
/// "prog ..." from an older engine's Skills panel (newer engines send it to RynthILT, which owns
/// the progression planners since 2026-10-13): passed on to RynthILT. Pump thread.
/// </summary>
private void HandleProgressionRemote(string value)
{
if (!Host.HasSendPluginCommand || !Host.SendPluginCommand("RynthILT", "prog", value))
ChatLine("[RynthAi] Progression is an Infinite Leaftide feature: it comes with the RynthILT plugin.");
}
/// <summary>"/ra itemhud add &lt;name&gt;" and the inventory panel's "Add to item count HUD". Pump thread.</summary>
private void HandleItemHudAdd(string name)
{
@ -560,11 +555,6 @@ public sealed partial class RynthAiPlugin
bool? state = ParseOnOff(action);
bool isAll = target.Equals("all", StringComparison.OrdinalIgnoreCase);
if (target.Equals("ilt", StringComparison.OrdinalIgnoreCase))
{
ChatLine("[RynthAi] The ILT features trace in RynthILT now: /ilt trace all on|off.");
return;
}
if (isAll)
{
if (!state.HasValue) { foreach (string l in RynthLog.StatusLines()) ChatLine(l); return; }

View file

@ -282,6 +282,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
long t0 = Environment.TickCount64;
try { _dashboard?.SaveSettings(); } catch { }
try { _sessionStats?.Shutdown(); } catch { }
try { GameInput.Shutdown(); } catch { } // keys still held for /mt movement | jump | strafe
// Release the Monster Editor process handle (if the toggle button
// launched one) rather than leaking it on plugin unload/hot-reload.
try { _dashboard?.ReleaseMonsterEditorHandle(); } catch { }
@ -742,8 +743,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager.ManaReserveHold = spellId => _buffManager?.OffensiveCastHold(spellId); // the mana reserve
_combatManager.ManaCanEverAfford = spellId => _buffManager?.CanEverAfford(spellId) ?? true; // script hook: never-payable spells
_combatManager.SetStaleBusyCallback(OnCombatBusyStale);
// Empyrean Handler lethal-ring: face the Handler, run-back jump (Jumper "xs"), re-engage.
// Read _jumper at call time — it is constructed later in this session setup.
// A server plugin's back-away (RynthAi.Hub BackAwayFrom; RynthILT's Empyrean Handler ring): face
// the danger, run-back jump (Jumper "xs"), re-engage. Read _jumper at call time — it is
// constructed later in this session setup.
_combatManager.RequestBackJump = (faceHeading, ms) => _jumper != null && _jumper.Start("xs", faceHeading, ms);
_combatManager.JumpBusy = () => _jumper?.IsBusy == true;
_buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count
@ -778,7 +780,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_metaManager = new MetaManager(_dashboard.Settings, Host, _vitals);
_metaManager.SetPlayerId(_playerId);
_metaManager.SetMtCommandHandler(HandleMtCommand);
_metaManager.SetMtCommandHandler(HandleMetaChatCommand);
_metaManager.SetRaCommandHandler(HandleRaCommand);
if (_objectCache != null) _metaManager.SetObjectCache(_objectCache);
_metaManager.SetFellowshipTracker(_fellowshipTracker);
@ -786,6 +788,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (_buffManager != null) _metaManager.SetBuffManager(_buffManager);
_metaManager.SetCreatureStore(_creatureStore);
_metaManager.SetKillClock(_killClock);
_metaManager.SetCorpseOpenedCheck(id => _completedCorpses.ContainsKey(id));
if (_dashboard != null)
_dashboard.MetaSnapshotProvider = () => _metaManager?.GetStateSnapshot();
@ -801,7 +804,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
CreateMiniRemote();
if (_miniRemote?.SkipLoginQuestRefresh == true)
Log("RynthAi: RynthILT says /myquests is off on this server; login quest refresh already ran.");
Log("RynthAi: the server plugin says /myquests is off on this server; login quest refresh already ran.");
try
{
string hubChar = CurrentCharacterName();
@ -995,13 +998,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "hub":
case "quests":
case "pets":
case "guardian":
case "bounty":
case "bounties":
case "bountys":
// Dashboard Char launcher and its right-click menu (hub=tab <section> switches the
// Mini Remote's tab); value carries the "/ra hub|quests|pets|bounty" arguments. The
// Infinite Leaftide verbs go on to RynthILT (MiniRemoteController.HandleCommand).
// Mini Remote's tab); value carries the "/ra hub|quests|pets" arguments. A hub verb that
// isn't RynthAi's goes on to the server plugin (MiniRemoteController.HandleCommand), and so
// does any other action RynthAi doesn't have (default below: "guardian", "bounty", ...).
if (_miniRemote == null) { ChatLine("[RynthAi] The Mini Remote isn't ready (log in first)."); break; }
_miniRemote.HandleCommand(action.ToLowerInvariant(), value.Split(' ', StringSplitOptions.RemoveEmptyEntries));
break;
@ -1021,10 +1021,6 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (_huds == null) { ChatLine("[RynthAi] HUDs not ready (log in first)."); break; }
if (!_huds.HandleRemoteSlot(value)) Host.Log($"[RynthAi] bad remoteslot value: {value}");
break;
case "prog":
// Skills panel Progression tab (augmentations / enlightenment edits).
HandleProgressionRemote(value);
break;
case "trace":
case "logs":
case "iteminfo":
@ -1045,6 +1041,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// movestart/movestop are applied DIRECTLY by the RynthRemote plugin (pure Host.SetAutoRun/
// SetMotion + its own dead-man watchdog) and are never forwarded here.
default:
// The server plugin's verbs sent to RynthAi (an engine button for "/ra guardian", "/ra bounty", ...).
if (_serverHub != null && _serverHub.Command((action.ToLowerInvariant() + " " + value).Trim())) break;
Host.Log($"[RynthAi] ignored unknown remote command: {action}={value}");
return;
}
@ -1448,6 +1446,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (_loginComplete) PostDataWriteProblems(); // a save that failed / folder not writable: say so in chat
CombatHook.ObserveUseDone(); // ctx.last.err: the answer to the hook's last cast
TickDelayedCommands(); // /ub delay
GameInput.Pump(); // release keys held for /mt movement | jump | strafe
DrainEngineCommands(); // fellowship command buttons (RynthCore's Fellowship section)
TickPropertyDump(); // /ub propertydump: waits for the ID, chat in chunks
if (_loginComplete) _dashboard?.TickPackSetup(_objectCache, _playerId); // new/copied profile items
@ -1623,7 +1622,6 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (diag) Host.Log("[RynthAi] OnTick: after quest tracker");
DrainGiveQueue();
if (diag) Host.Log("[RynthAi] OnTick: after drain give queue");
Loot.T11ItemSupport.SyncOverride(_dashboard?.Settings.T11ItemAugsOverride ?? -1);
_jumper?.Tick();
if (diag) Host.Log("[RynthAi] OnTick: after jumper tick");
@ -2371,14 +2369,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager?.TraceCastChat(text, chatType);
_combatManager?.HandleChatForDebuffs(text);
_combatManager?.HandleChatForDamage(text, chatType);
_combatManager?.HandleChatForRingEvade(text, chatType);
_missileCraftingManager?.HandleChat(text);
_scrollLearner?.OnChat(text);
_metaManager?.HandleChat(text, chatType);
_questTracker?.OnChatLine(text);
// The "/aug" reply carries the T11 wield counters (RynthILT's login probe requests it on ILT).
try { Loot.T11ItemSupport.OnChat(text); }
catch (Exception ex) { RynthLog.Exception(LogCat.Looting, ex, "T11 /aug parse"); }
CheckChatForSafetyStops(text);
try { OnOwnCorpseChat(text); } catch { }
}
@ -3826,6 +3820,18 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
DispatchRaCommand(cmd, parts, ref eat);
}
/// <summary>
/// An unknown "/ra" verb offered to the active server plugin (RynthILT.Hub Command, the words after
/// "/ra"). True when it took it (it answers in chat itself). Main / pump thread.
/// </summary>
private bool TryForwardToServerPlugin(string[] parts)
{
var server = _serverHub;
if (server == null || parts.Length < 2) return false;
try { return server.Command(string.Join(" ", parts, 1, parts.Length - 1)); }
catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "server plugin command"); return false; }
}
private void DispatchRaCommand(string cmd, string[] parts, ref int eat)
{
// Need trimmed original for commands that use it
@ -3858,7 +3864,6 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "dumpprops": HandleDumpPropsCommand(parts); break;
case "version": HandleVersionCommand(); break;
case "server": HandleServerCommand(); break;
case "t11": HandleT11Command(parts); break;
case "wielded": HandleWieldedCommand(); break;
case "scan": HandleScanCommand(); break;
case "buildinfo": HandleBuildInfoCommand(); break;
@ -3873,10 +3878,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "hub":
case "quests":
case "pets":
case "guardian":
case "bounty":
case "bounties":
case "bountys":
// The Mini Remote's verbs; "/ra guardian", "/ra bounty" and the like are the server
// plugin's (default below), as is any "/ra hub ..." verb RynthAi doesn't have.
if (_miniRemote == null) { ChatLine("[RynthAi] The Mini Remote isn't ready (log in first)."); break; }
_miniRemote.HandleCommand(cmd, parts.Length > 2 ? parts[2..] : Array.Empty<string>());
break;
@ -3964,6 +3967,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
}
break;
case "settings": HandleSettingsCommand(parts); break;
// /ra equipfor <monster>: VTank's /vt equipitemsfor (MagToolsCommands.Extra.cs)
case "equipfor": HandleEquipForCommand(parts); break;
case "autotrade": HandleAutoTradeRaCommand(parts); break;
case "trade": HandleTradeCommand(parts); break;
case "busyinfo": HandleBusyInfoCommand(); break;
@ -4021,6 +4026,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
HandleJumpCommand(cmd, parts);
break;
}
// A verb RynthAi doesn't have may be the server plugin's ("/ra t11", "/ra guardian", "/ra bounty"
// are RynthILT's on Infinite Leaftide); without one it goes on to the server, as any unknown "/ra".
if (TryForwardToServerPlugin(parts)) break;
eat = 0;
break;
}

View file

@ -11,7 +11,7 @@ public sealed partial class RynthAiPlugin
/// <summary>
/// /ra server: which server RynthCore says this is and why, every server it knows with this
/// character's override, the plugin that owns the active server and what its settings say,
/// and whether the Mini Remote's ILT tabs (RynthILT.Hub) are connected. One check that every
/// and whether a server plugin's hub (the Mini Remote's server tabs) is connected. One check that every
/// plugin is reading the same server identity. Plain ASCII (the AC chat can't draw more).
/// </summary>
private void HandleServerCommand()
@ -45,8 +45,15 @@ public sealed partial class RynthAiPlugin
: $"[RynthAi] {st.ActivePlugin} sent no server settings ({RynthServerProfileApiV1.InterfaceName} not answered - an older plugin?).");
}
bool iltTabs = _ilt != null && _ilt.Loaded;
ChatLine($"[RynthAi] Mini Remote ILT tabs (RynthILT.Hub): {(iltTabs ? "connected" + (_ilt!.IsIltWorld ? ", ILT world" : ", not an ILT world") : "not connected")}.");
var hub = _serverHub;
if (hub == null || !hub.Loaded)
ChatLine("[RynthAi] Mini Remote server tabs: no server plugin hub connected (none loaded for this world).");
else
{
string id = hub.Text(RynthIltHub.TextServerId);
ChatLine($"[RynthAi] Mini Remote server tabs: connected{(id.Length > 0 ? " (server '" + id + "')" : string.Empty)}, "
+ (hub.ServerActive ? "its server is this world." : "its server is not this world (nothing shown)."));
}
ChatLine("[RynthAi] Change the server: RynthCore Options > Diagnostics > Server, or /rc server pick <id>|auto.");
}
}

View file

@ -1,133 +0,0 @@
using System;
using System.Globalization;
using System.Linq;
using RynthCore.Loot.T11;
using RynthCore.Plugin.RynthAi.Loot;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
/// <summary>
/// /ra t11 [augs &lt;n|auto&gt; | refresh | item [0xId]]: T11 loot support.
/// No argument shows the wield counters the loot rules use; "augs" sets or clears the
/// item-aug override; "refresh" asks the server for "/aug"; "item" shows how the selected
/// item's T11 text was read and the values its virtual loot keys return.
/// </summary>
private void HandleT11Command(string[] parts)
{
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty;
switch (sub)
{
case "":
case "status":
PrintT11Status();
break;
case "augs":
SetT11ItemAugOverride(parts.Length >= 4 ? parts[3] : string.Empty);
break;
case "refresh":
if (!Host.HasInvokeChatParser) { ChatLine("[RynthAi] This engine can't send chat commands."); break; }
Host.InvokeChatParser("/aug");
ChatLine("[RynthAi] T11: sent /aug - the counters update from its reply.");
break;
case "item":
PrintT11Item(parts.Length >= 4 ? parts[3] : null);
break;
default:
ChatLine("[RynthAi] Usage: /ra t11 [augs <n|auto> | refresh | item [0xId]]");
break;
}
}
/// <summary>The counters the "T11: Can Wield" loot key compares wield gates against.</summary>
private void PrintT11Status()
{
T11PlayerAugs p = T11ItemSupport.Player;
int saved = _dashboard?.Settings.T11ItemAugsOverride ?? -1;
string updated = p.UpdatedUtc is DateTime t ? t.ToLocalTime().ToString("t", CultureInfo.CurrentCulture) : "never";
ChatLine($"[RynthAi] === T11 loot (last /aug read: {updated}) ===");
foreach ((T11Counter counter, string name) in T11Catalog.CounterNames)
{
long? v = p.Get(counter);
string source = counter == T11Counter.ItemAugmentations && saved >= 0 ? " (override)" : string.Empty;
ChatLine($"[RynthAi] {name}: {(v.HasValue ? v.Value.ToString("N0", CultureInfo.CurrentCulture) : "unknown")}{source}");
}
if (p.UpdatedUtc == null && saved < 0)
ChatLine("[RynthAi] Unknown counters make \"T11: Can Wield\" -1. Use /ra t11 refresh, or /ra t11 augs <n>.");
}
/// <summary>/ra t11 augs &lt;n|auto&gt;: saves the item-aug override (-1 = read from /aug).</summary>
private void SetT11ItemAugOverride(string arg)
{
if (_dashboard == null) { ChatLine("[RynthAi] Settings aren't loaded yet."); return; }
int value;
if (arg.Equals("auto", StringComparison.OrdinalIgnoreCase) || arg == "-1")
value = -1;
else if (!int.TryParse(arg.Replace(",", string.Empty), NumberStyles.Integer, CultureInfo.InvariantCulture, out value) || value < 0)
{
ChatLine("[RynthAi] Usage: /ra t11 augs <n|auto> (n = your item augmentation count)");
return;
}
_dashboard.Settings.T11ItemAugsOverride = value;
_dashboard.SaveSettings();
T11ItemSupport.SyncOverride(value);
ChatLine(value < 0
? "[RynthAi] T11: item augmentations now come from /aug."
: $"[RynthAi] T11: item augmentations fixed at {value:N0} for loot rules.");
}
/// <summary>/ra t11 item [0xId]: the parsed T11 text of an item (selected item by default).</summary>
private void PrintT11Item(string? idArg)
{
uint id = 0;
if (!string.IsNullOrEmpty(idArg))
uint.TryParse(idArg.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? idArg[2..] : idArg,
NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id);
if (id == 0 && Host.HasGetSelectedItemId) id = Host.GetSelectedItemId();
if (id == 0) { ChatLine("[RynthAi] T11: select an item first (or pass 0xId)."); return; }
int iid = unchecked((int)id);
WorldObject item = _objectCache?[iid]
?? new WorldObject(iid, Host.TryGetObjectName(id, out string n) ? n : string.Empty) { Cache = _objectCache };
T11ItemInfo info = T11ItemSupport.Get(item);
if (!info.IsT11)
{
bool appraised = !Host.HasHasAppraisalData || Host.HasAppraisalData(id);
ChatLine(appraised
? $"[RynthAi] T11: {item.Name} is not a T11 item."
: $"[RynthAi] T11: {item.Name} isn't appraised yet - ID it and try again.");
return;
}
ChatLine($"[RynthAi] === T11: {item.Name} (0x{id:X8}) ===");
ChatLine($"[RynthAi] Tier {(info.TierIsExact ? info.Tier.ToString(CultureInfo.InvariantCulture) : "~" + info.Tier.ToString(CultureInfo.InvariantCulture))}"
+ (info.Grade != null ? $", grade {info.Grade} ({info.DamagePercent}% of max damage)" : string.Empty)
+ (info.WeaponQuality >= 0 ? $", quality {info.WeaponQuality}/1000" : string.Empty)
+ (info.GearGrade != null ? $", gear grade {info.GearGrade} ({info.GearGradeLines} lines)" : string.Empty)
+ (info.ZoneLocked ? ", zone locked" : string.Empty));
if (info.PropertySlots >= 0 || info.Tainted)
ChatLine("[RynthAi] Properties "
+ (info.PropertySlots < 0 ? "?" : info.PropertySlotCap > 0 ? $"{info.PropertySlots} of {info.PropertySlotCap}" : info.PropertySlots.ToString(CultureInfo.InvariantCulture))
+ (info.Tainted ? ", tainted (bags no longer work)" : string.Empty));
foreach (T11WieldGate g in info.WieldGates)
ChatLine($"[RynthAi] Wield requires {g.Amount:N0} {T11Catalog.CounterName(g.Counter)}");
foreach (T11Modifier m in info.Modifiers)
{
string band = m.Min.HasValue && m.Max.HasValue ? $" [{m.Min}-{m.Max}] roll {m.RollPercent}%" : string.Empty;
string marks = (m.Tinkered != 0 ? $" ({m.Tinkered:+#;-#} tinkered)" : string.Empty)
+ (m.BuiltIn ? " (built-in)" : string.Empty) + (m.Locked ? " (locked)" : string.Empty);
ChatLine($"[RynthAi] Mod {m.Name} {(m.IsSlotSpecial ? "(special)" : "+" + m.Value)}{band}{marks}");
}
foreach ((string name, double chance) in info.Procs)
ChatLine($"[RynthAi] Cast on strike: {name} ({chance.ToString("0.#", CultureInfo.CurrentCulture)}%)");
int canWield = item.Values(T11Keys.CanWield, -1);
ChatLine($"[RynthAi] Can wield: {(canWield == 1 ? "yes" : canWield == 0 ? "no" : "unknown (no /aug read, or not appraised)")}"
+ $", modifier ratings {info.ModifierRatingTotal}, average roll {info.AverageRollPercent}%");
string keys = string.Join(", ", T11Keys.Names()
.Where(k => k.Id < T11Keys.ModifierBase)
.Select(k => $"{k.Name.Replace("T11: ", string.Empty)}={item.Values(k.Id, 0)}"));
ChatLine($"[RynthAi] Loot keys: {keys}");
}
}

View file

@ -60,8 +60,6 @@
<Compile Include="..\Shared\ServerCommandPanel.cs" Link="Shared\ServerCommandPanel.cs" />
<!-- Mini Remote session stats: RynthTracker's code, so the two show the same numbers (2026-10-11). -->
<Compile Include="..\Shared\KillCounter.cs" Link="Shared\KillCounter.cs" />
<!-- The pet-capture success replies: the Pets tab's auto-capture and RynthILT's Vaulted Dungeons timer. -->
<Compile Include="..\Shared\PetCaptureLines.cs" Link="Shared\PetCaptureLines.cs" />
<Compile Include="..\Shared\TrackerSessionStore.cs" Link="Shared\TrackerSessionStore.cs" />
<Compile Include="..\Shared\SessionStats.cs" Link="Shared\SessionStats.cs" />
<Compile Include="..\Shared\SessionStatsTracker.cs" Link="Shared\SessionStatsTracker.cs" />

View file

@ -86,6 +86,14 @@ public sealed partial class RynthAiPlugin
string cmd = parts[1].ToLower();
// ub-Rythai's verbs: that plugin answers; handled here only in the sense of "not unknown".
if (IsUbRythaiCommand(cmd, SplitUbLine(fullCommand).Args))
return true;
// "/ub vtsetmetastate[State]" and the like: an expression, not a verb.
if (TryHandleUbExpression(fullCommand))
return true;
// /ub jump[swzxc] [heading] [holdtime] — see Jumper.cs
if (cmd.StartsWith("jump", StringComparison.Ordinal))
{
@ -176,6 +184,11 @@ public sealed partial class RynthAiPlugin
if (TryHandleUbExtra(cmd, fullCommand))
return true;
// The rest of ub-IT's verbs: aliases, features, and accepted no-ops (UtilityBeltCompatCommands.cs).
// Before the /mt translation, so "/ub fellow dismiss" doesn't land on /mt fellow's usage line.
if (TryHandleUbCompat(cmd, fullCommand))
return true;
// /ub closestportal: use the nearest portal (UtilityBelt's command).
if (cmd == "closestportal")
{

View file

@ -0,0 +1,362 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// The rest of ub-IT's /ub verbs (2026-10-18 meta-compatibility pass). Three kinds:
/// 1. Aliases and features with a RynthAi, RynthNav, RynthSort, engine or server equivalent
/// (wear, getxy, stfl/stfr, arrow, navgoto, frame limits, fellow dismiss/leader/status,
/// qblist, augs, window save, packsort*, miniremote, meta/combat/sloot on|off, debug, lps).
/// 2. ub-Rythai's verbs, which RynthAi leaves to that plugin without a reply.
/// 3. ub-IT features that mean nothing here (videopatch, chat max, playeroption, ...): accepted
/// without error, said once per session, so a meta that sends them keeps running.
/// </summary>
public sealed partial class RynthAiPlugin
{
/// <summary>Verbs the ub-Rythai plugin answers. Every plugin sees each /ub line, so RynthAi stays quiet for these.</summary>
private static readonly HashSet<string> UbRythaiVerbs = new(StringComparer.OrdinalIgnoreCase)
{
"autopercent", "autotradeaccept", "bank", "build", "guard", "guardian", "ilt", "leaftide",
"log", "loginq", "p2", "periodic", "xpmeter",
};
/// <summary>
/// ub-IT verbs with no RynthAi equivalent: diagnostics of ub-IT's own tools, Decal UI and
/// client patches, and features RynthCore does its own way. Accepted so metas keep running.
/// </summary>
private static readonly HashSet<string> UbNoEquivalentVerbs = new(StringComparer.OrdinalIgnoreCase)
{
"acobject", "autologin", "autoloot", "autosalvage", "autosalvagedebug", "autosalvagereload",
"bankparse", "breakallegiance", "bridge", "calcdamage", "chat", "chatfilter", "chunkaeth",
"chunkaetheria", "chunkdebug", "chunkreset", "chunkstatus", "clapstatus", "dispel", "dispeltool",
"egg", "element", "enlighten", "enlightenment", "getjob", "getui", "invcache", "joke", "keystore",
"login", "lsdclearcache", "lsdlb", "mtbridge", "nav", "navfollow", "navfollowarrival",
"onetouchheal", "pcap", "perf", "playeroption", "prepclick", "printcolors", "professor",
"questbonus", "queuestatus", "refreshqueues", "resolution", "revalidate", "setui", "shittalk",
"soak", "spell", "statushud", "storm", "surgingstrength", "swearallegiance", "testassessor",
"textures", "tinkcalc", "trace", "tracearmorbuffs", "ubhudrecover", "ucm", "unstack",
"vhudbridgestatus", "xp", "xpdebug",
};
// No-equivalent verbs already reported this session (one chat line each, not one per meta pulse).
private readonly HashSet<string> _ubNoEquivalentSaid = new(StringComparer.OrdinalIgnoreCase);
/// <summary>True when ub-Rythai owns this /ub verb. "/ub portal use|list" (portal gems) is
/// ub-Rythai's; "/ub portal &lt;name&gt;" (the nearest portal) is RynthAi's.</summary>
internal static bool IsUbRythaiCommand(string cmd, string args)
{
if (UbRythaiVerbs.Contains(cmd)) return true;
if (!cmd.Equals("portal", StringComparison.OrdinalIgnoreCase)) return false;
string first = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries) is { Length: > 0 } w ? w[0] : "";
return first.Length == 0 || first.Equals("use", StringComparison.OrdinalIgnoreCase)
|| first.Equals("list", StringComparison.OrdinalIgnoreCase);
}
/// <summary>The verb and its arguments from a "/ub verb args" line.</summary>
private static (string Cmd, string Args) SplitUbLine(string fullCommand)
{
string rest = fullCommand.Length > 3 ? fullCommand.Substring(3).Trim() : "";
int sp = rest.IndexOf(' ');
return sp > 0 ? (rest.Substring(0, sp).ToLowerInvariant(), rest.Substring(sp + 1).Trim())
: (rest.ToLowerInvariant(), "");
}
/// <summary>
/// A meta's chat-command line. /ub lines go to the /ub dispatcher (ub-IT meaning: "/ub give" gives
/// every match, where "/mt give" gives one). ub-Rythai's verbs return false, so the meta hands the
/// line to the chat parser, which every plugin's chat handler sees. Anything else is /mt.
/// The whole line runs as one a running meta executes (<see cref="MetaCommandActive"/>), which is
/// what lets /mt vendor buy|sell and /mt trade accept act, and what /ub give's stricter item
/// protection (the loot profile's Keep rules) is keyed on. MetaManager's chat-command and
/// chat-expression actions are the only callers.
/// </summary>
internal bool HandleMetaChatCommand(string cmd) => RunAsMeta(() =>
{
if (cmd.StartsWith("/ub ", StringComparison.OrdinalIgnoreCase))
{
var (verb, args) = SplitUbLine(cmd);
return !IsUbRythaiCommand(verb, args) && HandleUbCommand(cmd);
}
return HandleMtCommand(cmd);
});
/// <summary>The verbs above. Returns false for anything else.</summary>
internal bool TryHandleUbCompat(string cmd, string fullCommand)
{
string args = SplitUbLine(fullCommand).Args;
string[] w = args.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string sub = w.Length > 0 ? w[0].ToLowerInvariant() : "";
switch (cmd)
{
// ── Aliases of commands RynthAi already has ─────────────────────────
case "wear": UbWear(args, partial: false); return true;
case "wearp": UbWear(args, partial: true); return true;
case "getxy": return HandleMtCursor();
case "stfl": return HandleMtStrafe(new[] { "/mt", "strafe", "left", args });
case "stfr": return HandleMtStrafe(new[] { "/mt", "strafe", "right", args });
case "debug": HandleRaCommand(("/ra debug " + args).TrimEnd()); return true;
case "close": UbClose(sub); return true;
case "bgframelimit":
case "globalframelimit":
UbFrameLimit(background: cmd == "bgframelimit", args);
return true;
case "fellow" when sub is "dismiss" or "dismissp" or "leader" or "leaderp" or "status" or "recruitp":
UbFellow(sub, w.Length > 1 ? string.Join(" ", w, 1, w.Length - 1) : "");
return true;
// ── RynthNav: the arrow and travel to coordinates ───────────────────
case "arrow":
if (sub == "point" && args.Length > 6)
SendToPlugin("RynthNav", "rnav", "arrow " + args.Substring(6).Trim(), "/ub arrow needs the RynthNav plugin.");
else
UbNoEquivalent(cmd, "\"arrow face\" has no RynthNav equivalent");
return true;
case "navgoto":
UbNavGoto(w);
return true;
// ── RynthSort: pack sorting ─────────────────────────────────────────
case "packsort":
case "packsortscansort":
case "packsortscanforcesort":
SendToPlugin("RynthSort", "rsort", "now", "/ub packsort needs the RynthSort plugin.");
return true;
case "packsortshow":
case "packsortlist":
SendToPlugin("RynthSort", "rsort", "status", "/ub packsort needs the RynthSort plugin.");
return true;
case "packsortreload":
case "packsortscan":
case "packsortscanforce":
UbNoEquivalent(cmd, "RynthSort reads its rules itself");
return true;
// ── A server's own commands (ub-IT's ACECustom verbs): the server plugin's (RynthILT) ──
case "qblist":
case "augs":
if (!TryForwardToServerPlugin(new[] { "/ra", "ub", cmd }))
UbNoEquivalent(cmd, "it is a server plugin's command (Infinite Leaftide: RynthILT), and none is loaded");
return true;
// ── RynthCore's window placement ────────────────────────────────────
case "window":
if (sub == "save") InvokeServerCommand("/rc window save");
else UbNoEquivalent(cmd + " " + sub, "RynthCore restores the saved window at login (/rc window save|reset)");
return true;
// ── RynthAi's Mini Remote ───────────────────────────────────────────
case "miniremote":
if (sub is "show" or "hide" or "toggle") HandleHudCommand("miniremote", sub);
else UbNoEquivalent(cmd + " " + sub, "use /ub miniremote show|hide|toggle");
return true;
// ── Project Storm's switches onto RynthAi's macro features ──────────
case "meta": return UbStormSwitch(cmd, sub, "enablemeta", w);
case "combat": return UbStormSwitch(cmd, sub, "enablecombat", w);
case "sloot": return UbStormSwitch(cmd, sub, "enablelooting", w);
case "lps":
case "lootprofilestatus":
{
string path = _dashboard?.Settings?.CurrentLootPath ?? "";
ChatLine("[RynthAi] Loot profile: " + (path.Length > 0 ? Path.GetFileName(path) : "(none)"));
return true;
}
}
// ── ub-IT features with no RynthAi equivalent ───────────────────────────
if (UbNoEquivalentVerbs.Contains(cmd))
{
UbNoEquivalent(cmd, null);
return true;
}
return false;
}
/// <summary>
/// /ub close corpse|chest (ub-IT): closes the open container when it is that kind (a bare
/// "/ub close" closes whatever is open). Metas send it after looting a quest corpse.
/// </summary>
private void UbClose(string kind)
{
uint open = Host.HasGetGroundContainerId ? Host.GetGroundContainerId() : 0;
if (open == 0) { ChatLine("[RynthAi] No container is currently open."); return; }
WorldObject? wo = _objectCache?[unchecked((int)open)];
bool fits = kind switch
{
"corpse" => wo == null || wo.ObjectClass == AcObjectClass.Corpse,
"chest" => wo == null || wo.ObjectClass == AcObjectClass.Container,
_ => true,
};
if (!fits) return; // as ub-IT: the open container isn't that kind, nothing to do
bool closed = Host.HasCloseContainer ? Host.CloseContainer(open) : Host.UseFor(open, "Command", "/ub close", UseKind.Asked);
Log($"[RynthAi] /ub close {kind}: 0x{open:X8} {(closed ? "closed" : "close refused")}.");
}
/// <summary>
/// "/ub &lt;expression&gt;": a /ub line whose verb is an expression call (S_BulbOfMornings broadcasts
/// "/ub bc /ub vtsetmetastate[State]" so every client switches state). ub-IT has no such
/// command; RynthAi evaluates the expression, which is what the meta means. True when it was one.
/// </summary>
internal bool TryHandleUbExpression(string fullCommand)
{
string rest = fullCommand.Length > 3 ? fullCommand.Substring(3).Trim() : "";
int bracket = rest.IndexOf('[');
int space = rest.IndexOf(' ');
if (bracket <= 0 || (space >= 0 && space < bracket) || !rest.EndsWith("]", StringComparison.Ordinal)) return false;
string result = EvalExpr(rest);
Log($"[RynthAi] /ub {rest} evaluated as an expression -> '{result}'.");
return true;
}
/// <summary>Says once per session that a /ub verb is accepted and ignored; every use is logged.</summary>
private void UbNoEquivalent(string what, string? note)
{
Log($"[RynthAi] /ub {what}: no RynthAi equivalent; ignored.");
if (_ubNoEquivalentSaid.Add(what))
ChatLine($"[RynthAi] /ub {what} is a ub-IT feature with no RynthAi equivalent; it is accepted and ignored so metas keep running"
+ (note != null ? $" ({note})." : "."));
}
/// <summary>Sends a chat line to the chat parser (server commands, /rc).</summary>
private void InvokeServerCommand(string line)
{
if (Host.HasInvokeChatParser) Host.InvokeChatParser(line);
else ChatLine($"[RynthAi] Can't send {line}: the chat parser isn't available.");
}
/// <summary>A command for another plugin through the engine broker.</summary>
private void SendToPlugin(string plugin, string action, string value, string missing)
{
if (!(Host.HasSendPluginCommand && Host.SendPluginCommand(plugin, action, value)))
ChatLine("[RynthAi] " + missing);
}
/// <summary>/ub wear[p] &lt;name&gt;: wield a carried item by name, skipping copies already worn
/// (using a worn item would take it off).</summary>
private void UbWear(string name, bool partial)
{
if (string.IsNullOrWhiteSpace(name)) { ChatLine("[RynthAi] Usage: /ub wear <item name> (wearp: partial name)"); return; }
if (_objectCache == null || !Host.HasUseObject) { ChatLine("[RynthAi] /ub wear: not ready (log in first)."); return; }
bool sawWorn = false;
foreach (var wo in _objectCache.GetInventory())
{
bool match = partial
? wo.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0
: string.Equals(wo.Name, name, StringComparison.OrdinalIgnoreCase);
if (!match) continue;
if (wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0) { sawWorn = true; continue; }
Host.UseFor(unchecked((uint)wo.Id), "Command", "/ub wear", UseKind.Asked);
Log($"[RynthAi] /ub wear: {wo.Name} (0x{(uint)wo.Id:X8})");
return;
}
ChatLine(sawWorn ? $"[RynthAi] Already wearing '{name}'." : $"[RynthAi] Item not found: '{name}'");
}
/// <summary>/ub globalframelimit|bgframelimit &lt;fps&gt;: RynthAi's frame limit (Settings, Display).
/// 0 turns the limit off (global) or lifts the background cap to its maximum.</summary>
private void UbFrameLimit(bool background, string arg)
{
LegacyUiSettings? s = _dashboard?.Settings;
if (s == null) { ChatLine("[RynthAi] Settings aren't loaded yet."); return; }
if (!int.TryParse(arg.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int fps) || fps < 0)
{
ChatLine($"[RynthAi] Usage: /ub {(background ? "bgframelimit" : "globalframelimit")} <frames per second>");
return;
}
if (background)
{
s.TargetFPSBackground = fps == 0 ? 60 : Math.Clamp(fps, 5, 60);
s.EnableFPSLimit = true;
ChatLine($"[RynthAi] Background frame limit: {s.TargetFPSBackground} fps.");
}
else if (fps == 0)
{
s.EnableFPSLimit = false;
ChatLine("[RynthAi] Frame limit off.");
}
else
{
s.TargetFPSFocused = Math.Clamp(fps, 10, 240);
s.EnableFPSLimit = true;
ChatLine($"[RynthAi] Frame limit: {s.TargetFPSFocused} fps.");
}
try { _dashboard?.SaveSettings(); } catch { }
}
/// <summary>/ub fellow dismiss[p]|leader[p] &lt;name&gt;, status, recruitp &lt;name&gt; (the p forms match part of a name).</summary>
private void UbFellow(string sub, string name)
{
if (sub == "status") { HandleFellowshipCommand(new[] { "/ra", "fellow", "status" }); return; }
if (name.Length == 0) { ChatLine($"[RynthAi] Usage: /ub fellow {sub} <name>"); return; }
bool partial = sub.EndsWith('p');
string resolved = name;
if (partial && sub != "recruitp" && _fellowshipTracker != null)
{
foreach (string member in _fellowshipTracker.GetMemberNames())
if (member.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0) { resolved = member; break; }
}
else if (sub == "recruitp" && FindObject(name, inv: false, land: true, partial: true) is { } wo)
{
resolved = wo.Name;
}
string verb = sub.TrimEnd('p');
InvokeServerCommand($"/fellowship {verb} {resolved}");
}
/// <summary>/ub navgoto &lt;ns&gt; &lt;ew&gt; [walk|run]: ub-IT's signed coordinates (south and west
/// negative) to RynthNav's "/rnav go 42.1N, 33.6E". RynthNav picks its own pace.</summary>
private void UbNavGoto(string[] w)
{
if (w.Length < 2
|| !double.TryParse(w[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double ns)
|| !double.TryParse(w[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double ew))
{
ChatLine("[RynthAi] Usage: /ub navgoto <ns> <ew> [walk|run] (south and west are negative)");
return;
}
string coords = FormattableString.Invariant($"{Math.Abs(ns):0.0#}{(ns < 0 ? 'S' : 'N')}, {Math.Abs(ew):0.0#}{(ew < 0 ? 'W' : 'E')}");
SendToPlugin("RynthNav", "rnav", "go " + coords, "/ub navgoto needs the RynthNav plugin.");
}
/// <summary>
/// Project Storm's /ub meta|combat|sloot: on/off switch the matching RynthAi macro feature
/// (enablemeta, enablecombat, enablelooting); "meta load &lt;name&gt;" and "meta state &lt;name&gt;"
/// are VTank's meta load and setmetastate. The other Storm verbs have no equivalent.
/// </summary>
private bool UbStormSwitch(string cmd, string sub, string vtOption, string[] w)
{
string rest = w.Length > 1 ? string.Join(" ", w, 1, w.Length - 1) : "";
if (_metaManager == null) { ChatLine("[RynthAi] Not ready (log in first)."); return true; }
switch (sub)
{
case "on" or "off":
_metaManager.TryHandleVtCommand($"/vt opt set {vtOption} {(sub == "on" ? "true" : "false")}");
return true;
case "status" or "":
_metaManager.TryHandleVtCommand($"/vt opt get {vtOption}");
return true;
case "load" when cmd == "meta" && rest.Length > 0:
_metaManager.TryHandleVtCommand("/vt meta load " + rest);
return true;
case "state" when cmd == "meta" && rest.Length > 0:
_metaManager.TryHandleVtCommand("/vt setmetastate " + rest);
return true;
}
UbNoEquivalent(cmd + " " + sub, "Project Storm's own engine; RynthAi is the macro here");
return true;
}
}

View file

@ -22,7 +22,9 @@ namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
// ── /ub delay queue ─────────────────────────────────────────────────────
private readonly List<(long DueMs, string Command)> _delayedCommands = new();
// FromMeta: the line was queued by a running meta, so it runs as one when due (it may be
// /mt vendor sell or /mt trade accept, which only act for a meta).
private readonly List<(long DueMs, string Command, bool FromMeta)> _delayedCommands = new();
/// <summary>Runs /ub delay commands that are due. Called every tick.</summary>
private void TickDelayedCommands()
@ -35,8 +37,13 @@ public sealed partial class RynthAiPlugin
{
if (_delayedCommands[i].DueMs > now) continue;
string cmd = _delayedCommands[i].Command;
bool fromMeta = _delayedCommands[i].FromMeta;
_delayedCommands.RemoveAt(i--);
try { HandleRynthChatSubmit(cmd); }
try
{
if (fromMeta) RunAsMeta(() => { HandleRynthChatSubmit(cmd); return true; });
else HandleRynthChatSubmit(cmd);
}
catch (Exception ex) { Log($"[RynthAi] /ub delay: '{cmd}' threw {ex.Message}"); }
}
}
@ -109,7 +116,7 @@ public sealed partial class RynthAiPlugin
}
string command = args.Substring(sp + 1).Trim();
if (command.Length == 0) return;
_delayedCommands.Add((Environment.TickCount64 + ms, command));
_delayedCommands.Add((Environment.TickCount64 + ms, command, MetaCommandActive));
}
// /ub count {item <name> | profile <lootProfile> | player <range>} [debug] [think]

View file

@ -67,7 +67,7 @@ internal sealed class AutoVendorManager
private bool _needsUpdateSaid;
// ── Session ──
private enum Phase { Idle, Identifying, Ready, WaitTrade, WaitConfirm, WaitSplit }
private enum Phase { Idle, Identifying, Ready, WaitTrade, WaitConfirm, WaitSplit, WaitMerge }
private Phase _phase = Phase.Idle;
private VTankLootProfile? _profile;
private string _profilePath = string.Empty;
@ -94,6 +94,13 @@ internal sealed class AutoVendorManager
private int _splitAmount;
private HashSet<uint> _splitBefore = new();
private long _splitDeadline;
// A split or merge that never shows up (no new stack / nothing moved): MaxFailures in a row ends the
// session instead of retrying every 10 s forever.
private int _tidyFails;
private int _tidySteps; // splits/merges since the last trade
private const int MaxTidySteps = 8;
private uint _mergeSource, _mergeTarget;
private int _mergeSourceCount, _mergeTargetCount;
private int _pyrealStackSize;
@ -391,6 +398,7 @@ internal sealed class AutoVendorManager
case Phase.WaitTrade: TickWaitTrade(now); break;
case Phase.WaitConfirm: TickWaitConfirm(now); break;
case Phase.WaitSplit: TickWaitSplit(now); break;
case Phase.WaitMerge: TickWaitMerge(now); break;
}
UpdateStatus();
}
@ -472,6 +480,8 @@ internal sealed class AutoVendorManager
if (!silent)
ThinkOrWrite($"AutoVendor finished: {_vendorName}");
_phase = Phase.Idle;
_tidyFails = 0;
_tidySteps = 0;
_profile = null;
_requestId = 0;
_idQueue.Clear();
@ -600,6 +610,20 @@ internal sealed class AutoVendorManager
PackState pack = ReadPack(v, vi, inv);
VendorPlan plan = AutoVendorPlanner.PlanNext(v, wants, sells, pack);
// Splits and merges only get the stacks ready for a trade: a run of them with no trade between
// is going in circles (split-merge-split, 2026-10-19), so it ends the session.
if (plan.Kind is PlanKind.Split or PlanKind.Merge)
{
if (++_tidySteps > MaxTidySteps)
{
ThinkOrWrite($"AutoVendor Fatal - {MaxTidySteps} splits/merges of {plan.SplitItem?.Name} without a sale");
Stop(false);
return;
}
}
else
_tidySteps = 0;
switch (plan.Kind)
{
case PlanKind.Done:
@ -622,6 +646,10 @@ internal sealed class AutoVendorManager
case PlanKind.Split:
DoSplit(plan.SplitItem!, plan.SplitAmount, plan.Message, inv, now);
break;
case PlanKind.Merge:
DoMerge(plan.SplitItem!, plan.MergeTarget!, plan.Message, now);
break;
}
}
@ -819,8 +847,71 @@ internal sealed class AutoVendorManager
{
if (now < _nextPollAt) return;
_nextPollAt = now + PollMs;
if (FindNewStack(Inventory(), _splitBefore, _splitName, _splitAmount) != 0 || now > _splitDeadline)
if (FindNewStack(Inventory(), _splitBefore, _splitName, _splitAmount) != 0)
{
_tidyFails = 0;
_phase = Phase.Ready;
}
else if (now > _splitDeadline)
TidyFailed($"splitting {_splitAmount} off {_splitName} made no new stack");
}
private void DoMerge(SellItem source, SellItem target, string why, long now)
{
if (!_host.HasMergeStackInternal)
{
ThinkOrWrite("AutoVendor Fatal - this engine can't merge stacks");
Stop(false);
return;
}
_mergeSource = source.Id;
_mergeTarget = target.Id;
_mergeSourceCount = source.StackSize;
_mergeTargetCount = target.StackSize;
_splitName = source.Name;
_host.Log($"[RynthAi] AutoVendor merge {source.Name}:{source.Id:X8} ({source.StackSize}) onto {target.Id:X8} ({target.StackSize}) - {why}");
if (!_host.MergeStackInternal(source.Id, target.Id))
{
TidyFailed($"could not merge {source.Name}");
return;
}
Tool($"merging {source.Name} stacks ({why})");
_splitDeadline = now + SplitWaitMs;
_nextPollAt = now + PollMs;
_bailAt = now;
_phase = Phase.WaitMerge;
}
private void TickWaitMerge(long now)
{
if (now < _nextPollAt) return;
_nextPollAt = now + PollMs;
var inv = Inventory();
var src = inv.FirstOrDefault(w => unchecked((uint)w.Id) == _mergeSource);
var tgt = inv.FirstOrDefault(w => unchecked((uint)w.Id) == _mergeTarget);
// Done when the source is used up, or either count moved (past the max the target fills and
// the source survives smaller).
if (src == null || StackOf(src) != _mergeSourceCount || (tgt != null && StackOf(tgt) != _mergeTargetCount))
{
_tidyFails = 0;
_phase = Phase.Ready;
}
else if (now > _splitDeadline)
TidyFailed($"merging {_splitName} stacks moved nothing");
}
private void TidyFailed(string what)
{
_tidyFails++;
_host.Log($"[RynthAi] AutoVendor: {what} ({_tidyFails}/{MaxFailures})");
if (_tidyFails >= MaxFailures)
{
_tidyFails = 0;
ThinkOrWrite($"AutoVendor Fatal - {what}, {MaxFailures} times in a row");
Stop(false);
return;
}
_phase = Phase.Ready;
}
// ── Collect (UB GetBuyItems / GetSellItems) ──
@ -847,6 +938,7 @@ internal sealed class AutoVendorManager
uint player = PlayerId();
var packOrder = PackOrder(inv, player);
var unitValues = TrueUnitValues(inv);
foreach (var wo in inv)
{
uint id = unchecked((uint)wo.Id);
@ -871,6 +963,13 @@ internal sealed class AutoVendorManager
int stack = StackOf(wo);
bool isNote = wo.ObjectClass == AcObjectClass.TradeNote || (type & AutoVendorPlanner.ItemTypePromissoryNote) != 0;
int unitValue = stack > 1 ? safety.Value / stack : safety.Value;
// A stack keeps its old Value after a split (100 peas' worth on a stack of 2 read "1,250,000
// each", 2026-10-19), which hid it from the sell list and from the split planner. Use the
// per-unit value most of this item's units carry (TrueUnitValues).
bool stackable = InventoryManager.GetMaxStackSize(wo) > 1;
if (stackable && unitValues.TryGetValue(StackKey(wo), out int trueUnit) && trueUnit > 0)
unitValue = trueUnit;
int stackValue = stackable ? unitValue * Math.Max(1, stack) : safety.Value;
if (unsafeWhy == null && !AutoVendorPlanner.VendorWillBuy(v, type, isNote, unitValue))
{
// A Sell rule wanted it and the vendor won't take it: say why, once per name a
@ -915,10 +1014,12 @@ internal sealed class AutoVendorManager
Class = wo.ObjectClass,
ItemType = type,
StackSize = stack,
Value = safety.Value,
Value = stackValue,
RuleName = sd.RuleName,
Location = main ? "Main Pack" : $"{packName} #{packIdx}",
SortSlot = main ? Math.Max(0, wo.DirectSlot) : 1000 + 100 * packIdx + Math.Max(0, wo.DirectSlot),
MaxStack = InventoryManager.GetMaxStackSize(wo),
Wcid = _host.HasGetObjectWcid && _host.TryGetObjectWcid(id, out uint wcid) ? wcid : 0,
});
}
return result;
@ -984,7 +1085,7 @@ internal sealed class AutoVendorManager
/// <summary>UB cancels a pending use by facing one degree away.</summary>
private void CancelUse()
{
if (_host.HasTurnToHeading && _host.TryGetPlayerHeading(out float h))
if (_host.HasTurnToHeading && PlayerCompass.TryGet(_host, out float h))
_host.TurnToHeadingBy("Vendor", (h + 359f) % 360f);
else if (_host.HasStopCompletely)
_host.StopCompletelyBy("Vendor");
@ -1330,6 +1431,34 @@ internal sealed class AutoVendorManager
return count;
}
/// <summary>
/// Per item (weenie, else name): the Value / StackSize that the most units carry. A stack's Value goes
/// stale after a split (too high) or a merge (too low); the untouched stacks outnumber them.
/// </summary>
private Dictionary<string, int> TrueUnitValues(List<WorldObject> inv)
{
var votes = new Dictionary<string, Dictionary<int, long>>(StringComparer.Ordinal);
foreach (var wo in inv)
{
int stack = StackOf(wo);
int value = wo.Values(19 /* Value */, 0);
if (stack < 1 || value <= 0 || InventoryManager.GetMaxStackSize(wo) < 2) continue;
string key = StackKey(wo);
if (!votes.TryGetValue(key, out var byUnit)) votes[key] = byUnit = new Dictionary<int, long>();
int unit = value / stack;
byUnit[unit] = byUnit.GetValueOrDefault(unit) + stack;
}
var result = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var (key, byUnit) in votes)
result[key] = AutoVendorPlanner.MostCarriedUnit(byUnit);
return result;
}
private string StackKey(WorldObject wo) =>
_host.HasGetObjectWcid && _host.TryGetObjectWcid(unchecked((uint)wo.Id), out uint wcid) && wcid != 0
? "w:" + wcid
: "n:" + wo.Name;
private uint FindNewStack(List<WorldObject> inv, HashSet<uint> before, string name, int amount)
{
foreach (var wo in inv)
@ -1487,6 +1616,7 @@ internal sealed class AutoVendorManager
Phase.WaitTrade => $"Waiting for the server - {_vendorName}",
Phase.WaitConfirm => $"Confirming trade - {_vendorName}",
Phase.WaitSplit => $"Splitting {_splitName} - {_vendorName}",
Phase.WaitMerge => $"Merging {_splitName} - {_vendorName}",
_ => $"Vendoring {_vendorName} ({Path.GetFileName(_profilePath)})",
};
if (_settings.AutoVendorTestMode && _phase != Phase.Idle) s += " [test mode]";

View file

@ -73,6 +73,10 @@ internal sealed class SellItem
public string RuleName { get; init; } = string.Empty;
public string Location { get; init; } = string.Empty;
public int SortSlot { get; init; }
/// <summary>The item's max stack size (0 = unknown); a stack below it is a partial.</summary>
public int MaxStack { get; init; }
/// <summary>Weenie class id (0 = unknown): only the same weenie merges.</summary>
public uint Wcid { get; init; }
public bool IsNote => Class == AcObjectClass.TradeNote || (ItemType & AutoVendorPlanner.ItemTypePromissoryNote) != 0;
public int UnitValue => StackSize > 1 ? Value / StackSize : Value;
@ -96,6 +100,7 @@ internal enum PlanKind : byte
Sell = 2,
Split = 3,
Fatal = 4,
Merge = 5,
}
internal readonly record struct BuyLine(Listing Item, int Amount);
@ -109,12 +114,16 @@ internal sealed class VendorPlan
public long Total { get; init; }
public SellItem? SplitItem { get; init; }
public int SplitAmount { get; init; }
/// <summary>Merge: SplitItem goes onto MergeTarget.</summary>
public SellItem? MergeTarget { get; init; }
public string Message { get; init; } = string.Empty;
public static VendorPlan Done() => new() { Kind = PlanKind.Done };
public static VendorPlan Fatal(string msg) => new() { Kind = PlanKind.Fatal, Message = msg };
public static VendorPlan Split(SellItem item, int amount, string why) =>
new() { Kind = PlanKind.Split, SplitItem = item, SplitAmount = amount, Message = why };
public static VendorPlan Merge(SellItem source, SellItem target, string why) =>
new() { Kind = PlanKind.Merge, SplitItem = source, MergeTarget = target, Message = why };
}
/// <summary>What the manager read about an inventory item for UB's "safe to get rid of" checks.</summary>
@ -430,7 +439,7 @@ internal static class AutoVendorPlanner
if (single != null)
return new VendorPlan { Kind = PlanKind.Sell, Sells = new List<SellItem> { single }, Total = VendorPays(v, true, single.Value) };
return VendorPlan.Split(item, 1, $"one {item.Name} to afford {nextBuy.Name}");
return SplitClean(v, sells, item, 1, $"one {item.Name} to afford {nextBuy.Name}");
}
// Can't sell the whole stack? Split off what the pyreals will fit.
@ -441,7 +450,7 @@ internal static class AutoVendorPlanner
int newStack = unit > 0 ? (int)Math.Floor((p.FreeMainSlots - 2) * (double)Math.Max(1, p.PyrealStackSize) / unit) : 0;
newStack = Math.Min(newStack, stack - 1);
if (newStack > 0)
return VendorPlan.Split(item, newStack, "the pyreals for the whole stack won't fit");
return SplitClean(v, sells, item, newStack, "the pyreals for the whole stack won't fit");
return VendorPlan.Fatal($"AutoVendor Fatal - No inventory room to sell {item.Name}");
}
break;
@ -457,6 +466,57 @@ internal static class AutoVendorPlanner
return VendorPlan.Done();
}
/// <summary>
/// A split lands on another partial stack of the same item when there is one, instead of making
/// a new stack (the stack split from doesn't count), so the split-off amount never shows up to be
/// sold. Drakkon's Gold Peas looped split-wait-split for good once two partial stacks existed
/// (2026-10-19). So: first merge partials down to one; with one partial left, sell it whole if it
/// fits, else split from it (nothing else partial for the new stack to join); with none, split as
/// asked. An unknown max stack size keeps the old plain split.
/// </summary>
internal static VendorPlan SplitClean(VendorView v, IReadOnlyList<SellItem> sells, SellItem item, int amount, string why)
{
if (item.MaxStack <= 1)
return VendorPlan.Split(item, amount, why);
var partials = sells
.Where(s => SameItem(s, item) && s.StackSize > 0 && s.StackSize < item.MaxStack)
.OrderByDescending(s => s.StackSize)
.ToList();
// A partial that fits is sold whole first: the stack a split just made, or any leftover. (Merging
// it back instead looped split-merge-split three times a second, 2026-10-19.)
SellItem? fits = partials.FirstOrDefault(s => s.StackSize <= amount);
if (fits != null)
return new VendorPlan { Kind = PlanKind.Sell, Sells = new List<SellItem> { fits }, Total = VendorPays(v, fits.IsNote, fits.Value) };
// Every partial is too big to sell whole: merge them down to one before splitting.
if (partials.Count >= 2)
return VendorPlan.Merge(partials[^1], partials[0], $"one partial {item.Name} stack, so the split makes a new stack");
if (partials.Count == 1 && partials[0].Id != item.Id)
return VendorPlan.Split(partials[0], amount, why);
return VendorPlan.Split(item, amount, why);
}
/// <summary>The unit value carrying the most units (ties: the higher value, the safe side for a vendor's max).</summary>
internal static int MostCarriedUnit(IReadOnlyDictionary<int, long> unitsByValue)
{
int best = 0;
long bestUnits = -1;
foreach (var (unit, units) in unitsByValue)
if (units > bestUnits || (units == bestUnits && unit > best))
{
best = unit;
bestUnits = units;
}
return best;
}
private static bool SameItem(SellItem a, SellItem b) =>
a.Wcid != 0 && b.Wcid != 0 ? a.Wcid == b.Wcid : string.Equals(a.Name, b.Name, StringComparison.Ordinal);
// ── /ub vendor addsell (UB AddItemToSellList) ────────────────────────────
/// <summary>

View file

@ -1,11 +1,13 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
// Moved here from RynthOracle (Data/Conquest.cs) on 2026-10-20: Conquest-only features live in RynthConquest.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using RynthCore.Plugin.ServerPack;
namespace RynthCore.Plugin.RynthOracle.Data;
namespace RynthCore.Plugin.RynthConquest;
/// <summary>A labelled value from a server reply ("Pyreals" = "1,039,678,533 (4,158 MMDs)").</summary>
internal sealed class NamedValue
@ -110,11 +112,11 @@ internal sealed class ConquestBoard
}
/// <summary>
/// Everything ConquestAC-only (tag Conquest): bank balances and bank commands ("/b", "/bank"),
/// Everything Conquest-only: bank balances and bank commands ("/b", "/bank"),
/// advanced augmentations ("/augs"), enlightenment augmentations ("/enl augs"), the XP bonus
/// breakdown ("/bonus"), fellowships looking for members ("/fship list"), the /top boards, and
/// the void damage-over-time duration scaling. The plugin only feeds it chat and only shows it
/// while the server is ConquestAC; every reply regex is anchored at the start of the line (after
/// the void damage-over-time duration scaling. RynthConquest only feeds it chat while the server is
/// Conquest (and only loads there); every reply regex is anchored at the start of the line (after
/// an optional chat timestamp), as upstream does, so a pasted copy in a chat channel can't
/// overwrite your values.
/// </summary>
@ -185,7 +187,7 @@ internal sealed class ConquestData
BonusUtc = DateTime.MinValue, FshipUtc = DateTime.MinValue;
public int Revision { get; private set; }
private readonly ChatRequest _bankReq = new(), _augReq = new(), _enlReq = new(), _bonusReq = new(), _fshipReq = new(),
private readonly ServerChatRequest _bankReq = new(), _augReq = new(), _enlReq = new(), _bonusReq = new(), _fshipReq = new(),
_topReq = new(), _depositReq = new();
private ConquestBoard? _collecting;
private long _collectingMs;
@ -230,7 +232,7 @@ internal sealed class ConquestData
/// <summary>
/// A chat line: true when it was a reply this module reads; <paramref name="ours"/> = it
/// answers a request RynthOracle sent (eligible to be hidden).
/// answers a request RynthConquest sent (eligible to be hidden).
/// </summary>
public bool OnChatLine(string text, long now, out bool ours)
{
@ -337,7 +339,7 @@ internal sealed class ConquestData
return false;
}
private bool Done(ChatRequest req, long now, out bool ours)
private bool Done(ServerChatRequest req, long now, out bool ours)
{
ours = req.Awaiting(now);
req.Extend(now);

View file

@ -0,0 +1,143 @@
// ConquestFeature.cs - What RynthConquest does on Conquest, without the host (ConquestPlugin.cs wires it
// to the engine, ConquestPages.cs draws it). Moved out of RynthOracle on 2026-10-20 so that only players
// who installed RynthConquest get Conquest's features, and the automatic /bank deposit with them:
// * reads the replies of Conquest's own commands (ConquestData: /b, /augs, /enl augs, /bonus,
// /fship list, /top) and the quest flags (/myquests, for the custom quest worklist), and hides
// the replies to its own requests when HideOwnReplies is on;
// * reads the advanced augmentations once after login (the Void DoT rule needs the Duration augs);
// * deposits everything at each ten-minute mark when AutoDeposit is on (off unless the player
// turned it on, in RynthOracle before or here);
// * works out the Void DoT duration rule for this character, which RynthOracle's Void timers read
// from the server profile ("voidDotDurationScale") instead of knowing about Conquest.
// Settings: rynthconquest.json (ServerPackSettings), taken over once from rynthoracle.json.
// Threads: everything here runs under Gate. Chat and tick come from the pump, the pages draw on the
// render thread holding it too; nothing in here calls the host.
// Pure: RynthServerPack.Tests covers it.
using System;
using RynthCore.Plugin.RynthOracle.Data;
using RynthCore.Plugin.ServerPack;
namespace RynthCore.Plugin.RynthConquest;
internal sealed class ConquestFeature
{
public const string SettingAutoDeposit = "autoDeposit";
public const string SettingHideOwnReplies = "hideOwnReplies";
/// <summary>Set once rynthoracle.json's Conquest settings were taken over (they're never read again).</summary>
public const string MigrationMarker = "migratedFromRynthOracle";
/// <summary>The profile value RynthOracle's Void timers apply ("RynthServer.Profile" values).</summary>
public const string VoidScaleKey = "voidDotDurationScale";
/// <summary>After login, before the hidden /augs (RynthOracle's old timing: its quest read plus 4 s).</summary>
public const long AugsReadDelayMs = 10_000;
/// <summary>The character's level, XP and augmentation are read this often.</summary>
public const long CharacterReadMs = 1000;
/// <summary>RynthConquest's pages (ConquestPages draws them): id, label, tooltip.</summary>
public static readonly (string Id, string Label, string Tooltip)[] PageList =
{
("main", "Conquest", "Conquest: bank and auto-deposit, augmentations, levels past 275, fellowships and custom quests (RynthConquest)."),
("boards", "Leaderboards", "Conquest's /top boards (RynthConquest)."),
};
/// <summary>Held for everything below (pump and render thread).</summary>
public readonly object Gate = new();
public readonly ConquestData Data = new();
public readonly QuestFlagStore Flags = new();
/// <summary>"/bank deposit" at every ten-minute mark (upstream's auto-deposit). Off by default.</summary>
public bool AutoDeposit;
/// <summary>Hide the replies to RynthConquest's own requests (a command typed by hand always shows).</summary>
public bool HideOwnReplies = true;
// The character (ConquestPlugin reads them every CharacterReadMs).
public bool CharacterKnown;
public int Level, Enlightenment, ArchmagesEndurance;
public long TotalXp;
private long _loginMs;
private bool _augsAsked;
private long _lastDepositBlock = -1;
/// <summary>
/// Takes over the settings RynthOracle had for Conquest (rynthoracle.json at <paramref name="oraclePath"/>),
/// once per settings file; a value that isn't there keeps this plugin's default (auto-deposit off,
/// hiding on, as they were in RynthOracle). True when it ran now.
/// </summary>
public static bool Migrate(ServerPackSettings settings, string oraclePath) => settings.MigrateOnce(MigrationMarker, s =>
{
if (ServerPackSettings.ReadBoolFrom(oraclePath, "conquestAutoDeposit") is bool deposit) s.SetBool(SettingAutoDeposit, deposit);
if (ServerPackSettings.ReadBoolFrom(oraclePath, "hideOwnQuestReplies") is bool hide) s.SetBool(SettingHideOwnReplies, hide);
});
public void LoadSettings(ServerPackSettings s)
{
AutoDeposit = s.GetBool(SettingAutoDeposit, false);
HideOwnReplies = s.GetBool(SettingHideOwnReplies, true);
}
public void SaveSettings(ServerPackSettings s)
{
bool changed = s.SetBool(SettingAutoDeposit, AutoDeposit);
changed |= s.SetBool(SettingHideOwnReplies, HideOwnReplies);
if (changed) s.Save();
}
/// <summary>A character logged in (or the plugin loaded in game): everything is read fresh.</summary>
public void Login(long nowMs)
{
_loginMs = nowMs;
_augsAsked = false;
Data.Clear();
Flags.Clear();
CharacterKnown = false;
Level = Enlightenment = ArchmagesEndurance = 0;
TotalXp = 0;
}
public void Logout()
{
Data.Clear();
Flags.Clear();
CharacterKnown = false;
}
/// <summary>
/// An incoming chat line on Conquest. True when it should be hidden: a reply to one of
/// RynthConquest's own requests, with HideOwnReplies on.
/// </summary>
public bool OnChatLine(string text, long nowMs)
{
string line = text.TrimEnd('\r', '\n');
MyQuestsLine kind = Flags.OnChatLine(line, nowMs);
if (kind != MyQuestsLine.None)
return Flags.AwaitingOurs && HideOwnReplies && kind is MyQuestsLine.Quest or MyQuestsLine.Empty;
return Data.OnChatLine(line, nowMs, out bool ours) && ours && HideOwnReplies;
}
/// <summary>The once-after-login /augs: the command to send now, or null.</summary>
public string? LoginAugsDue(long nowMs)
{
if (_augsAsked || nowMs - _loginMs <= AugsReadDelayMs) return null;
_augsAsked = true;
return Data.RequestAugs(nowMs);
}
/// <summary>The automatic deposit: "/bank deposit" when one is due now, else null.</summary>
public string? AutoDepositDue(DateTime local, long nowMs)
=> AutoDeposit && DepositDue(local, ref _lastDepositBlock) ? Data.AutoDeposit(nowMs) : null;
/// <summary>
/// True once in each ten-minute block, at its first minute (:00, :10, :20 ... local time), as
/// upstream does; <paramref name="lastBlock"/> remembers the block already done.
/// </summary>
public static bool DepositDue(DateTime local, ref long lastBlock)
{
long block = local.Ticks / TimeSpan.TicksPerMinute / 10;
if (local.Minute % 10 != 0 || block == lastBlock) return false;
lastBlock = block;
return true;
}
/// <summary>This character's Void DoT duration multiplier on Conquest (Archmage's Endurance and the Duration augs).</summary>
public double VoidScale => Data.VoidDurationMultiplier(ArchmagesEndurance);
}

View file

@ -0,0 +1,417 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
// RynthOracle's Conquest tab (Views/ConquestTab.cs) and the Conquest half of its Leaderboards tab
// (Views/BoardsTab.cs), moved here on 2026-10-20 and redrawn with ImGui as RynthConquest's pages:
// sub-tabs of the Mini Remote's Server section while on Conquest, and tabs of the /rserver window.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthOracle.Data;
using RynthCore.Plugin.ServerPack;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthConquest;
/// <summary>
/// The Conquest page (bank balances and bank commands, advanced and enlightenment augmentations,
/// levels past 275 and the XP bonus breakdown, fellowships looking for members, the custom quest
/// worklist: upstream's Bank, Conquest Augs, Conquest XP, Fship and Custom tabs) and the
/// Leaderboards page (Conquest's /top boards: upstream's Top Players tab).
/// Render thread: each page draws holding the feature's lock, and queues what it sends for the tick.
/// </summary>
internal sealed class ConquestPages
{
private static readonly Vector4 Gold = new(1.00f, 0.84f, 0.30f, 1f);
private static readonly Vector4 Green = new(0.45f, 0.85f, 0.45f, 1f);
private static readonly Vector4 Grey = new(0.55f, 0.57f, 0.60f, 1f);
private static readonly Vector4 Selected = new(0.26f, 0.45f, 0.70f, 1f);
private static readonly string[] Views = { "Bank", "Augs", "Enlightenment", "Experience", "Fellowships", "Custom quests" };
private static readonly string[] FshipSorts = { "Name", "Leader", "Most members", "Location" };
private readonly ConquestFeature _f;
private readonly Func<bool> _active;
private readonly Action<Action> _runOnTick;
private readonly Func<string, bool> _send;
private readonly Action<string> _print;
private readonly Action _saveSettings;
private readonly ServerRefreshRow _refresh = new();
private int _view;
private int _withdrawIndex = ConquestData.DefaultWithdraw, _transferIndex = ConquestData.DefaultTransfer;
private string _withdrawAmount = "", _transferAmount = "", _transferTarget = "";
private int _fshipSort;
private int _board;
/// <param name="active">RynthConquest's server is this world.</param>
/// <param name="runOnTick">Queues work for the plugin tick (ServerPackPlugin.RunOnTick).</param>
/// <param name="send">Sends a chat command as if typed (pump thread).</param>
/// <param name="print">A line in the chat window (pump thread).</param>
/// <param name="saveSettings">Writes the feature's settings (pump thread).</param>
public ConquestPages(ConquestFeature feature, Func<bool> active, Action<Action> runOnTick, Func<string, bool> send,
Action<string> print, Action saveSettings)
{
_f = feature;
_active = active;
_runOnTick = runOnTick;
_send = send;
_print = print;
_saveSettings = saveSettings;
}
public ServerPage[] Pages()
{
var list = ConquestFeature.PageList;
return new[]
{
new ServerPage(list[0].Id, list[0].Label, list[0].Tooltip, DrawConquest),
new ServerPage(list[1].Id, list[1].Label, list[1].Tooltip, DrawBoards),
};
}
/// <summary>Logout: the next character's status lines start empty.</summary>
public void Reset() => _refresh.Reset();
// ── Conquest page ───────────────────────────────────────────────────
private void DrawConquest()
{
if (!Ready()) return;
lock (_f.Gate)
{
for (int i = 0; i < Views.Length; i++)
{
if (i > 0) ImGui.SameLine();
if (Toggle(Views[i] + "##cq_v" + i, i == _view)) _view = i;
}
_refresh.Draw("cq" + _view, ConquestHelp(), RefreshConquest);
ImGui.Separator();
switch (_view)
{
case 0: DrawBank(); break;
case 1: DrawAugs(); break;
case 2: DrawEnl(); break;
case 3: DrawXp(); break;
case 4: DrawFships(); break;
default: DrawCustom(); break;
}
ImGui.Spacing();
bool hide = _f.HideOwnReplies;
if (ImGui.Checkbox("Hide the replies to RynthConquest's own requests##cq_hide", ref hide))
{
_f.HideOwnReplies = hide;
_runOnTick(_saveSettings);
}
Tooltip("/b, /augs, /top, /myquests and the like when RynthConquest sends them. A command you type yourself always shows its reply.");
}
}
/// <summary>True when the page has something to show; otherwise says why.</summary>
private bool Ready()
{
if (_active()) return true;
SafeImGui.TextWrapped("These pages are for Conquest. RynthCore doesn't see this world as Conquest "
+ "(check RynthCore Options > Diagnostics, or /rserver info).");
return false;
}
private static string ReadAt(DateTime utc) => utc == DateTime.MinValue ? "not read yet" : $"read at {utc.ToLocalTime():HH:mm}";
private void DrawBank()
{
ConquestData cq = _f.Data;
SafeImGui.TextDisabled(ReadAt(cq.BankUtc));
foreach (NamedValue b in cq.Bank.OrderBy(b => b.Name, StringComparer.OrdinalIgnoreCase))
{
SafeImGui.TextDisabled(Cut(b.Name, 34));
ImGui.SameLine(260f);
SafeImGui.Text(b.Value);
}
if (cq.Bank.Count == 0) SafeImGui.TextDisabled("No balances read yet.");
ImGui.SeparatorText("Deposit");
if (ImGui.Button("Deposit everything##cq_dep")) Queue("/bank deposit");
Tooltip("Sends /bank deposit.");
bool auto = _f.AutoDeposit;
if (ImGui.Checkbox("Deposit by itself every ten minutes##cq_auto", ref auto))
{
_f.AutoDeposit = auto;
_runOnTick(_saveSettings);
}
Tooltip("At :00, :10, :20 ... while you're logged in on Conquest. Its reply is hidden.");
ImGui.SeparatorText("Withdraw");
string[] wl = ConquestData.Withdrawable.Select(c => c.Label).ToArray();
ImGui.SetNextItemWidth(200f);
if (ImGui.Combo("Currency##cq_wcur", ref _withdrawIndex, wl, wl.Length)) _withdrawIndex = Math.Clamp(_withdrawIndex, 0, wl.Length - 1);
ImGui.SetNextItemWidth(200f);
ImGui.InputText("Amount##cq_wamt", ref _withdrawAmount, 16);
if (ImGui.Button("Withdraw##cq_withdraw"))
{
string? cmd = ConquestData.WithdrawCommand(ConquestData.Withdrawable[_withdrawIndex], _withdrawAmount);
if (cmd == null) Print("Withdraw: type a whole number above 0.");
else Queue(cmd);
}
ImGui.SeparatorText("Transfer to a character");
string[] tl = ConquestData.Transferable.Select(c => c.Label).ToArray();
ImGui.SetNextItemWidth(200f);
if (ImGui.Combo("Currency##cq_tcur", ref _transferIndex, tl, tl.Length)) _transferIndex = Math.Clamp(_transferIndex, 0, tl.Length - 1);
ImGui.SetNextItemWidth(200f);
ImGui.InputText("Amount##cq_tamt", ref _transferAmount, 16);
ImGui.SetNextItemWidth(200f);
ImGui.InputText("Character##cq_tgt", ref _transferTarget, 40);
if (ImGui.Button("Transfer##cq_transfer"))
{
string? cmd = ConquestData.TransferCommand(ConquestData.Transferable[_transferIndex], _transferAmount, _transferTarget);
if (cmd == null) Print("Transfer: type a whole number above 0 (MMD notes: at most 1,000) and a character name.");
else Queue(cmd);
}
}
private void DrawAugs()
{
ConquestData cq = _f.Data;
SafeImGui.TextDisabled($"{ReadAt(cq.AugsUtc)}, {cq.AugTotal} in total");
ImGui.TextDisabled("Aug"); ImGui.SameLine(120f); ImGui.TextDisabled("Have"); ImGui.SameLine(170f);
ImGui.TextDisabled("Next costs"); ImGui.SameLine(330f); ImGui.TextDisabled("Effect now");
foreach (ConquestAug a in cq.Augs)
{
SafeImGui.Text(a.Name);
ImGui.SameLine(120f);
SafeImGui.Text(a.Count.ToString());
ImGui.SameLine(170f);
SafeImGui.Text(a.NextCostText());
ImGui.SameLine(330f);
SafeImGui.TextDisabled(Cut(a.Effect(), 48));
Tooltip(a.Effect());
}
}
private void DrawEnl()
{
ConquestData cq = _f.Data;
SafeImGui.TextDisabled(ReadAt(cq.EnlUtc));
foreach (NamedValue a in cq.EnlAugs)
{
SafeImGui.Text(Cut(a.Name, 26));
ImGui.SameLine(200f);
SafeImGui.Text(a.Value);
ImGui.SameLine(360f);
SafeImGui.TextDisabled(ConquestData.EnlCost(a.Name));
}
if (cq.EnlAugs.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh.");
}
private void DrawXp()
{
ConquestData cq = _f.Data;
int level = _f.Level;
if (!_f.CharacterKnown) ImGui.TextDisabled("Reading your character...");
ImGui.SeparatorText($"Level {level}");
if (level >= ConquestData.MaxLevel) ImGui.TextUnformatted("Maximum level.");
else if (level < 275)
{
// Retail levels: RynthOracle's Character tab has the progress to the next one.
SafeImGui.TextDisabled($"Conquest's own levels start at 276. {Number(Math.Max(0, ConquestData.XpForLevel(276) - _f.TotalXp))} XP to level 276.");
}
else
{
long start = level >= 276 ? ConquestData.XpForLevel(level) : 0;
long next = ConquestData.XpForLevel(level + 1);
long toNext = Math.Max(0, next - _f.TotalXp);
long begin = level == 275 ? 191_226_310_247 : start;
float frac = next > begin ? (float)Math.Clamp((double)(_f.TotalXp - begin) / (next - begin), 0, 1) : 1f;
ImGui.ProgressBar(frac, new Vector2(-1f, 0f), $"{Number(toNext)} to level {level + 1}");
long toMax = Math.Max(0, ConquestData.XpForLevel(ConquestData.MaxLevel) - _f.TotalXp);
SafeImGui.TextDisabled($"{Number(toMax)} to level {ConquestData.MaxLevel}");
}
int target = _f.Enlightenment + 1;
ImGui.SeparatorText($"Enlightenment {_f.Enlightenment}");
SafeImGui.Text($"Next costs {Number(ConquestData.EnlCoinCost(target))} coins and {(ConquestData.EnlLuminanceCost(target) / 1_000_000.0):0.##}M luminance");
ImGui.SeparatorText("Experience bonuses");
SafeImGui.TextDisabled(ReadAt(cq.BonusUtc));
foreach (NamedValue b in cq.Bonuses)
{
SafeImGui.TextDisabled(b.Name);
ImGui.SameLine(200f);
SafeImGui.Text(b.Value.Length > 0 ? b.Value : "-");
}
}
private void DrawFships()
{
ConquestData cq = _f.Data;
SafeImGui.TextDisabled($"{ReadAt(cq.FshipUtc)}, {cq.Fellowships.Count} looking for members");
ImGui.SetNextItemWidth(160f);
ImGui.Combo("Sort##cq_fsort", ref _fshipSort, FshipSorts, FshipSorts.Length);
IEnumerable<ConquestFellowship> list = _fshipSort switch
{
1 => cq.Fellowships.OrderBy(f => f.Leader, StringComparer.OrdinalIgnoreCase),
2 => cq.Fellowships.OrderByDescending(f => f.MemberCount),
3 => cq.Fellowships.OrderBy(f => f.Location, StringComparer.OrdinalIgnoreCase),
_ => cq.Fellowships.OrderBy(f => f.Name, StringComparer.OrdinalIgnoreCase),
};
if (ImGui.BeginChild("##cq_fships", new Vector2(0f, 220f), ImGuiChildFlags.Borders))
{
foreach (ConquestFellowship f in list)
{
SafeImGui.Text(Cut(f.Name, 26));
ImGui.SameLine(200f);
SafeImGui.Text(Cut(f.Leader, 20));
ImGui.SameLine(350f);
SafeImGui.Text(f.Members);
if (f.Location.Length > 0) { ImGui.SameLine(410f); SafeImGui.TextDisabled(Cut(f.Location, 26)); }
}
if (cq.Fellowships.Count == 0) ImGui.TextDisabled("None read yet. Press Refresh.");
}
ImGui.EndChild();
}
private void DrawCustom()
{
DateTime now = DateTime.UtcNow;
int i = 0;
foreach (CustomQuest q in CustomQuestList.All)
{
bool done = q.IsComplete(_f.Flags, now);
SafeImGui.TextColored(done ? Green : Grey, done ? "done" : "--");
ImGui.SameLine(50f);
string status = q.Status(_f.Flags, now);
CustomQuest row = q;
if (ImGui.Selectable(Cut(q.Name, 34) + "##cq_cust" + i++, false, ImGuiSelectableFlags.None, new Vector2(280f, 0f)))
PrintEntry(row.Name, row.Flag, status, row.Hint, row.Url);
Tooltip("Click: the quest's hint in chat.");
ImGui.SameLine(340f);
SafeImGui.Text(status);
}
if (CustomQuestList.All.Count == 0) ImGui.TextDisabled("No custom quests listed.");
if (_f.Flags.LastReadUtc == DateTime.MinValue) ImGui.TextDisabled("Press Refresh to read your quest flags (/myquests) for their status.");
}
/// <summary>An entry's name, status, hint and link in chat (upstream "thinks" them).</summary>
private void PrintEntry(string name, string flag, string status, string details, string url)
{
Print(flag.Length > 0 ? $"{name} ({flag}){(status.Length > 0 ? " - " + status : "")}" : name);
if (details.Length > 0) Print(details);
if (url.Length > 0) Print(url);
}
// ── Leaderboards page ───────────────────────────────────────────────
private void DrawBoards()
{
if (!Ready()) return;
lock (_f.Gate)
{
ConquestData cq = _f.Data;
_board = Math.Clamp(_board, 0, cq.Boards.Count - 1);
for (int i = 0; i < cq.Boards.Count; i++)
{
if (i > 0) ImGui.SameLine();
if (Toggle(cq.Boards[i].Label + "##cb_tab" + i, i == _board)) _board = i;
}
ConquestBoard b = cq.Boards[_board];
_refresh.Draw("board" + b.Key, $"Sends {b.Command} and reads the reply.", () => Ask("board" + b.Key, () => b.UpdatedUtc.Ticks, b.Command,
now => cq.RequestBoard(b, now)));
ImGui.Separator();
SafeImGui.TextDisabled(b.UpdatedUtc == DateTime.MinValue ? "not read yet" : $"read at {b.UpdatedUtc.ToLocalTime():HH:mm}");
if (b.You != null) SafeImGui.Text($"You: #{b.You.Rank} with {b.You.Value}");
if (ImGui.BeginChild("##cb_rows", Vector2.Zero, ImGuiChildFlags.Borders))
{
ImGui.TextDisabled("Rank"); ImGui.SameLine(60f); ImGui.TextDisabled("Name"); ImGui.SameLine(280f); ImGui.TextDisabled("Value");
foreach (BoardRow r in b.Rows)
{
SafeImGui.Text(r.Rank.ToString());
ImGui.SameLine(60f);
if (r.IsYou) SafeImGui.TextColored(Gold, Cut(r.Name, 30));
else SafeImGui.Text(Cut(r.Name, 30));
ImGui.SameLine(280f);
SafeImGui.Text(r.Value);
if (r.Extra.Length > 0) { ImGui.SameLine(420f); SafeImGui.TextDisabled(Cut(r.Extra, 40)); }
}
if (b.Rows.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh.");
}
ImGui.EndChild();
}
}
// ── Refresh (RynthOracle's RefreshBar, Conquest's part) ──────────────
private ServerRefreshResult RefreshConquest()
{
ConquestData cq = _f.Data;
switch (_view)
{
case 0: return Ask("bank", () => cq.BankUtc.Ticks, "/b", now => cq.RequestBank(now));
case 1: return Ask("augs", () => cq.AugsUtc.Ticks, "/augs", now => cq.RequestAugs(now));
case 2: return Ask("enl", () => cq.EnlUtc.Ticks, "/enl augs", now => cq.RequestEnl(now));
case 3: return Ask("bonus", () => cq.BonusUtc.Ticks, "/bonus", now => cq.RequestBonus(now));
case 4: return Ask("fship", () => cq.FshipUtc.Ticks, "/fship list", now => cq.RequestFships(now));
default:
if (_refresh.CoolingDown("quests", Environment.TickCount64)) return new ServerRefreshResult(ServerRefreshRow.TooSoon);
QuestFlagStore flags = _f.Flags;
int rev = flags.Revision;
int wait = flags.ThrottleSecondsLeft(Environment.TickCount64);
if (wait > 0) return new ServerRefreshResult($"The server answers one /myquests a minute; try again in {wait}s (the flags shown are kept).");
_runOnTick(() =>
{
lock (_f.Gate) flags.Request(_send, Environment.TickCount64);
});
return new ServerRefreshResult("Asked the server for your quest flags (/myquests).", () => flags.Revision != rev);
}
}
private string ConquestHelp() => _view switch
{
0 => "Sends /b and reads your balances.",
1 => "Sends /augs and reads your advanced augmentations.",
2 => "Sends /enl augs and reads your enlightenment augmentations.",
3 => "Sends /bonus for the experience bonuses (your level is read from the game).",
4 => "Sends /fship list and reads the fellowships looking for members.",
_ => "Sends /myquests: the custom quests' status comes from your quest flags.",
};
/// <summary>
/// Sends one of the page's own commands on the next tick (marking it as RynthConquest's, so its
/// reply can be hidden) and waits for <paramref name="state"/> to change.
/// </summary>
private ServerRefreshResult Ask(string key, Func<long> state, string command, Action<long> markSent)
{
if (_refresh.CoolingDown(key, Environment.TickCount64)) return new ServerRefreshResult(ServerRefreshRow.TooSoon);
long before = state();
_runOnTick(() =>
{
lock (_f.Gate) markSent(Environment.TickCount64);
if (!_send(command)) _print($"Couldn't send {command} (not in the world).");
});
return new ServerRefreshResult($"Sent {command}.", () => state() != before);
}
// ── Helpers ─────────────────────────────────────────────────────────
/// <summary>A command from a button, sent on the next tick.</summary>
private void Queue(string command) => _runOnTick(() => _send(command));
/// <summary>A line in chat, written on the next tick.</summary>
private void Print(string text) => _runOnTick(() => _print(text));
private static bool Toggle(string label, bool selected)
{
if (selected) ImGui.PushStyleColor(ImGuiCol.Button, Selected);
bool clicked = ImGui.SmallButton(label);
if (selected) ImGui.PopStyleColor();
return clicked;
}
private static void Tooltip(string text)
{
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(text);
}
private static string Cut(string s, int max) => s.Length <= max ? s : s.Substring(0, Math.Max(0, max - 3)) + "...";
private static string Number(long n) => TimeText.Number(n);
}

View file

@ -1,14 +1,19 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
// Moved here from RynthOracle (Data/CustomQuests.cs) on 2026-10-20, with Resources\customquests.csv.
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using RynthCore.Plugin.RynthOracle.Data;
namespace RynthCore.Plugin.RynthOracle.Data;
namespace RynthCore.Plugin.RynthConquest;
/// <summary>
/// A server's custom quest worklist (customquests.csv: Server, Name, QuestFlag, Url, Hint). Each
/// row carries its server tag, so only the current server's rows show (today: ConquestAC's).
/// A repeatable counts as done only while on cooldown (upstream's rule).
/// Conquest's custom quest worklist (customquests.csv: Server, Name, QuestFlag, Url, Hint; every row
/// is Conquest's), upstream's Custom tab. The status comes from the character's quest flags
/// (/myquests, read with RynthOracle's parser, linked source). A repeatable counts as done only
/// while on cooldown (upstream's rule).
/// </summary>
internal sealed class CustomQuest
{
@ -31,18 +36,17 @@ internal sealed class CustomQuest
internal static class CustomQuestList
{
public static List<CustomQuest> All { get; } = Load();
/// <summary>The embedded list's logical name (RynthCore.Plugin.RynthConquest.csproj).</summary>
public const string ResourceName = "RynthConquest.customquests.csv";
public static IEnumerable<CustomQuest> For(ServerIdentity server)
{
foreach (CustomQuest q in All)
if (server.Is(q.Server)) yield return q;
}
public static List<CustomQuest> All { get; } = Load();
private static List<CustomQuest> Load()
{
var list = new List<CustomQuest>();
using StreamReader r = Csv.OpenEmbedded("customquests.csv");
Stream? stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(ResourceName);
if (stream == null) return list;
using var r = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
r.ReadLine(); // Server,Name,QuestFlag,Url,Hint
while (r.ReadLine() is string line)
{

View file

@ -0,0 +1,118 @@
// ConquestPlugin.cs - RynthConquest's own features, through the shared server plugin's hooks
// (Plugins/Shared/ServerPack/ServerPackPlugin.cs). Everything Conquest-specific that RynthOracle used to
// carry lives here since 2026-10-20 (Conquest/ConquestFeature.cs says what), so a player without
// RynthConquest gets none of it, the automatic /bank deposit included.
using System;
using System.IO;
using RynthCore.Plugin.RynthConquest;
namespace RynthCore.Plugin.ServerPack;
public sealed partial class ServerPackPlugin
{
private readonly ConquestFeature _conquest = new();
private ConquestPages? _conquestPages;
private long _nextConquestCharacterMs;
/// <summary>Where RynthOracle kept the Conquest settings before they moved here (read once).</summary>
internal static string OracleSettingsPath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthoracle.json");
partial void ServerPages(System.Collections.Generic.List<ServerPage> pages)
{
_conquestPages = new ConquestPages(_conquest, () => Active, RunOnTick, Send,
text => ChatLine($"[{RynthPluginInfo.Name}] {text}"), SaveConquestSettings);
pages.AddRange(_conquestPages.Pages());
}
partial void ServerInitialize()
{
if (ConquestFeature.Migrate(Settings, OracleSettingsPath))
LogTagged("Took over RynthOracle's Conquest settings (auto-deposit, hiding own replies) from rynthoracle.json.");
lock (_conquest.Gate) _conquest.LoadSettings(Settings);
}
private void SaveConquestSettings()
{
lock (_conquest.Gate) _conquest.SaveSettings(Settings);
}
partial void ServerLoginComplete()
{
lock (_conquest.Gate) _conquest.Login(Environment.TickCount64);
_nextConquestCharacterMs = 0;
_conquestPages?.Reset();
}
partial void ServerLogout()
{
lock (_conquest.Gate) _conquest.Logout();
_conquestPages?.Reset();
}
partial void ServerShutdown() => SaveConquestSettings();
partial void ServerChatText(string text, int chatType, ref bool eat)
{
if (!Active) return;
bool hide;
lock (_conquest.Gate) hide = _conquest.OnChatLine(text, Environment.TickCount64);
if (hide) eat = true;
}
partial void ServerChatBar(string text)
{
// The player's own /myquests: its reply shows (QuestFlagStore tells it from RynthConquest's).
if (text.Equals("/myquests", StringComparison.OrdinalIgnoreCase)) _conquest.Flags.NoteTypedCommand();
}
partial void ServerTick(bool active)
{
if (!active) return;
long now = Environment.TickCount64;
string? augs, deposit;
lock (_conquest.Gate)
{
_conquest.Flags.Tick(now);
augs = _conquest.LoginAugsDue(now);
deposit = _conquest.AutoDepositDue(DateTime.Now, now);
}
if (augs != null) Send(augs);
if (deposit != null && Send(deposit)) ChatLine($"[{RynthPluginInfo.Name}] Auto-deposited to the bank.");
if (now < _nextConquestCharacterMs) return;
_nextConquestCharacterMs = now + ConquestFeature.CharacterReadMs;
ReadConquestCharacter();
}
/// <summary>Level, XP, enlightenment and Archmage's Endurance (the Void DoT rule), then the rule for RynthOracle.</summary>
private void ReadConquestCharacter()
{
uint player = Host.HasGetPlayerId ? Host.GetPlayerId() : 0;
if (player == 0) return;
int level = Host.TryGetObjectIntProperty(player, 25, out int l) ? l : 0; // PropertyInt Level
int enl = Host.TryGetObjectIntProperty(player, 390, out int e) ? e : 0; // Enlightenment
int archmage = Host.TryGetObjectIntProperty(player, 238, out int a) ? a : 0; // AugmentationIncreasedSpellDuration
long xp = Host.HasGetObjectQuadProperty && Host.TryGetObjectQuadProperty(player, 1, out long x) ? x : 0; // TotalExperience
double scale;
lock (_conquest.Gate)
{
_conquest.Level = level;
_conquest.Enlightenment = enl;
_conquest.ArchmagesEndurance = archmage;
_conquest.TotalXp = xp;
_conquest.CharacterKnown = level > 0;
scale = _conquest.VoidScale;
}
SetProfileValue(ConquestFeature.VoidScaleKey, scale);
}
partial void ServerInfoLines(Action<string> line)
{
lock (_conquest.Gate)
{
line($"Auto-deposit {(_conquest.AutoDeposit ? "on" : "off")}; own replies {(_conquest.HideOwnReplies ? "hidden" : "shown")}"
+ $"; Void DoT duration x{_conquest.VoidScale:0.##} ({_conquest.Data.DurationAugs} Duration augs).");
}
}
}

View file

@ -1,17 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- RynthConquest: the Conquest (ConquestAC) server plugin. The build is shared
(..\Shared\ServerPack\ServerPlugin.props); ServerData.cs holds what is known about the server. -->
(..\Shared\ServerPack\ServerPlugin.props); ServerData.cs holds what is known about the server.
Conquest's own features (ConquestPlugin.cs, Conquest\) came from RynthOracle on 2026-10-20: the
bank and its auto-deposit, augmentations, levels past 275, fellowships, custom quests and the
/top boards, as pages of the Mini Remote's Server section. -->
<PropertyGroup>
<AssemblyName>RynthCore.Plugin.RynthConquest</AssemblyName>
<Version>0.1.0</Version>
<Version>0.2.0</Version>
<RynthPluginServerId>conquest</RynthPluginServerId>
<RynthPluginServerName>Conquest</RynthPluginServerName>
<RynthPluginServerHosts>acconquest.ddns.net</RynthPluginServerHosts>
<RynthPluginServerWorldNames>Conquest|ConquestAC</RynthPluginServerWorldNames>
<RynthPluginDescription>Conquest only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote.</RynthPluginDescription>
<RynthPluginDescription>Conquest only: the server card, and Conquest's bank (with auto-deposit), augmentations, levels past 275, fellowships, custom quests and leaderboards in the Mini Remote.</RynthPluginDescription>
</PropertyGroup>
<Import Project="..\Shared\ServerPack\ServerPlugin.props" />
<ItemGroup>
<!-- RynthOracle's /myquests parser and its helpers (linked source, so both read the flags alike):
the custom quest worklist's status. -->
<Compile Include="..\RynthCore.Plugin.RynthOracle\Data\QuestFlags.cs" Link="Shared\QuestFlags.cs" />
<Compile Include="..\RynthCore.Plugin.RynthOracle\Data\TimeText.cs" Link="Shared\TimeText.cs" />
<Compile Include="..\RynthCore.Plugin.RynthOracle\Data\Csv.cs" Link="Shared\Csv.cs" />
</ItemGroup>
<ItemGroup>
<!-- Oracle of Dereth's Conquest custom quest list (MIT, by Advis Eveldan / advis61). -->
<EmbeddedResource Include="Resources\customquests.csv" LogicalName="RynthConquest.customquests.csv" />
</ItemGroup>
<ItemGroup>
<None Include="THIRD_PARTY_NOTICES.md" CopyToPublishDirectory="PreserveNewest" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>

View file

@ -16,6 +16,7 @@ internal static class ServerData
"Live events and deep crafting.",
"Has a PK system on a PvE server.",
"RynthOracle has a Conquest quest pack (quests.conquest.csv).",
"RynthConquest's pages (Server section, or /rserver): bank and auto-deposit, augmentations, levels past 275, fellowships, custom quests, leaderboards.",
},
Discord = "https://discord.gg/Gsadhhv72S",
Website = "https://dsc.gg/conquerac",

View file

@ -0,0 +1,42 @@
# Third-party notices: RynthConquest
RynthConquest's Conquest features (the bank, advanced and enlightenment augmentations, XP bonuses
and levels past 275, the fellowship list, the /top boards, the custom quest worklist, the
auto-deposit and the Void damage-over-time duration rule) are ported from **Oracle of Dereth**, a
Decal plugin for Asheron's Call by **Advis Eveldan** (GitHub:
[advis61](https://github.com/advis61/OracleOfDereth)). They were part of RynthOracle until
2026-10-20 and moved here so that only Conquest players carry them. Thank you, Advis!
- Upstream: https://github.com/advis61/OracleOfDereth
- Ported from commit `ee618c6847b98b656a47ca87cc347441d206c547` (2026-10-01, version 2.3.0).
- Licence: MIT. The upstream README states "License: MIT". The repository has no separate
LICENSE file and names no copyright line, so the standard MIT text is reproduced below
with the author and the years of the repository's history.
What came from upstream: `Resources\customquests.csv` (copied unchanged), and the logic of the
features above, rewritten for RynthCore. Ported files say so in their header. RynthOracle's quest
flag parser (`QuestFlags.cs`, also ported from upstream) is compiled in as shared source.
---
MIT License
Copyright (c) 2024-2026 Advis Eveldan (GitHub: advis61) and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,7 +1,8 @@
// DataInterface.cs - RynthILT's side of the "RynthILT.Data" interface (Plugins/Shared/RynthIltDataApi.cs):
// the charms list and the bank balances (every character RynthILT has seen on this server) the
// Mini Remote's Charms and Banking tabs show, for other plugins to draw, with the charm Toggle and
// the bank verbs they send back; since version 2 also the pet breeding tracker's JSON and verbs.
// the bank verbs they send back; since version 2 also the pet breeding tracker's JSON and verbs;
// since version 3 the Temple guardians' JSON and verbs (RynthOracle's Quests tab).
//
// The table is allocated once per loaded copy of RynthILT and never freed (a plugin DLL is never
// unloaded); after Release() it reports Version 0 and every function answers 0. Before login there
@ -37,6 +38,8 @@ internal static unsafe class DataInterface
t->BankCommand = &BankCommand;
t->GetPetBreedingJson = &GetPetBreedingJson;
t->PetBreedingCommand = &PetBreedingCommand;
t->GetGuardianJson = &GetGuardianJson;
t->GuardianCommand = &GuardianCommand;
t->Version = RynthIltDataApiV1.InterfaceVersion;
_table = t;
}
@ -128,6 +131,32 @@ internal static unsafe class DataInterface
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetGuardianJson(byte* buffer, int capacity)
{
try
{
string? json = Hub?.GuardianJson;
return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity);
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GuardianCommand(byte* utf8)
{
try
{
IltHubController? hub = Hub;
if (hub == null) return 0;
string? line = ReadVerb(utf8);
if (line == null) return 0;
hub.RequestGuardianVerb(line);
return 1;
}
catch { return 0; }
}
/// <summary>A reader's verb line, or null when it is empty, too long or not plain ASCII (no control characters reach a chat command).</summary>
private static string? ReadVerb(byte* utf8)
{

View file

@ -20,6 +20,8 @@
// Fellowship.cs), Zone Share (ZoneShareManager) and the fellowship luminance share.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace RynthCore.Plugin.RynthILT.Hub;
@ -45,6 +47,16 @@ internal enum IltKnown
ProfileOff,
}
/// <summary>The quest bonus list as the profile JSON carries it ("questBonus"), for RynthOracle's Quests tab.</summary>
/// <param name="Disabled">The server has /qb turned off.</param>
/// <param name="Generation">Bumped per parsed "/qb list"; 0 = not loaded this session.</param>
/// <param name="Count">The server's quest bonus count; -1 = unknown.</param>
/// <param name="Status">One line on the last request ("loading...", "12 completed, 3 incomplete", ...).</param>
/// <param name="Completed">Completed bonus flags, sorted.</param>
/// <param name="Incomplete">Incomplete bonus flags, sorted.</param>
internal sealed record IltQuestBonusInfo(bool Disabled, int Generation, long Count, string Status,
IReadOnlyList<string> Completed, IReadOnlyList<string> Incomplete);
internal static class IltFeatureCatalog
{
public const string GroupCharacter = "Character";
@ -257,6 +269,83 @@ internal static class IltFeatureCatalog
/// <summary>The fellowship member limit: ACECustom's 29 on an ILT world, retail's 9 elsewhere.</summary>
public static int FellowshipMax(bool iltWorld) => iltWorld ? IltFellowshipMax : RetailFellowshipMax;
/// <summary>
/// The "RynthILT.Server" profile JSON (schema in Plugins/Shared/RynthIltServerApi.cs). Pure:
/// everything comes in as arguments, so the tests build it without a client. Plain ASCII.
/// </summary>
public static string BuildProfileJson(bool iltWorld, string world, bool forced, string source, DateTime checkedUtc,
Func<string, IltTri> bit, IltQuestBonusInfo? questBonus = null)
{
var sb = new StringBuilder(4096);
sb.Append("{\"ilt\":").Append(iltWorld ? "true" : "false");
sb.Append(",\"world\":\"").Append(Escape(world)).Append('"');
sb.Append(",\"forced\":").Append(forced ? "true" : "false");
sb.Append(",\"source\":\"").Append(Escape(source)).Append('"');
sb.Append(",\"checked\":\"")
.Append(checkedUtc == DateTime.MinValue ? "" : checkedUtc.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture))
.Append('"');
sb.Append(",\"features\":[");
for (int i = 0; i < All.Length; i++)
{
IltFeatureInfo f = All[i];
if (i > 0) sb.Append(',');
sb.Append("{\"key\":\"").Append(Escape(f.Key))
.Append("\",\"label\":\"").Append(Escape(f.Label))
.Append("\",\"group\":\"").Append(Escape(f.Group))
.Append("\",\"state\":").Append(((int)StateOf(f, iltWorld, bit)).ToString(CultureInfo.InvariantCulture))
.Append(",\"where\":\"").Append(Escape(f.Where)).Append("\"}");
}
sb.Append(']');
int State(string key) => (int)StateOf(Find(key)!, iltWorld, bit);
sb.Append(",\"fellowship\":{\"maxMembers\":").Append(FellowshipMax(iltWorld).ToString(CultureInfo.InvariantCulture))
.Append(",\"zoneShare\":").Append(State("zone_share").ToString(CultureInfo.InvariantCulture))
.Append(",\"blackjack\":").Append(State("fellowship_blackjack").ToString(CultureInfo.InvariantCulture))
.Append(",\"luminanceShare\":").Append(State("fellowship_luminance").ToString(CultureInfo.InvariantCulture))
.Append('}');
// The /qb list (ILT worlds only): RynthOracle's Quests tab draws it.
if (questBonus != null && iltWorld)
{
sb.Append(",\"questBonus\":{\"disabled\":").Append(questBonus.Disabled ? "true" : "false")
.Append(",\"generation\":").Append(questBonus.Generation.ToString(CultureInfo.InvariantCulture))
.Append(",\"count\":").Append(questBonus.Count.ToString(CultureInfo.InvariantCulture))
.Append(",\"status\":\"").Append(Escape(questBonus.Status)).Append('"');
AppendList(sb, "completed", questBonus.Completed);
AppendList(sb, "incomplete", questBonus.Incomplete);
sb.Append('}');
}
sb.Append('}');
return sb.ToString();
static void AppendList(StringBuilder b, string name, IReadOnlyList<string> items)
{
b.Append(",\"").Append(name).Append("\":[");
for (int i = 0; i < items.Count; i++)
{
if (i > 0) b.Append(',');
b.Append('"').Append(Escape(items[i])).Append('"');
}
b.Append(']');
}
}
/// <summary>JSON string body: quotes, backslashes and control characters escaped, anything non-ASCII as \uXXXX.</summary>
private static string Escape(string? s)
{
if (string.IsNullOrEmpty(s)) return string.Empty;
var sb = new StringBuilder(s.Length + 8);
foreach (char c in s)
{
if (c == '"') sb.Append("\\\"");
else if (c == '\\') sb.Append("\\\\");
else if (c < 0x20 || c > 0x7E) sb.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
else sb.Append(c);
}
return sb.ToString();
}
/// <summary>The chat listing for "/ra hub features": one line per feature, ASCII only.</summary>
public static List<string> BuildChatLines(bool iltWorld, Func<string, IltTri> bit)
{

View file

@ -9,6 +9,8 @@
// nearest vendor (VendorBuy). Runs as a small pump-thread state machine with timeouts; the
// client busy state is respected between steps.
// * Attribute tracker: IltTempleAttributes.
// * Reader: the same state as JSON with verbs back ("RynthILT.Data" version 3), for RynthOracle's
// Quests tab. The automation (auto hand-in, buy if missing) stays here either way.
//
// Threading: OnChat / Tick / commands run on the pump thread; Render only reads volatile fields
// and posts actions through IltHubContext.Post.
@ -426,6 +428,90 @@ internal sealed class IltGuardian : IIltFeature
}
}
// ── Reader ("RynthILT.Data" GetGuardianJson / GuardianCommand; RynthOracle's Quests tab) ──
/// <summary>
/// The reader JSON (Plugins/Shared/RynthIltDataApi.cs header has the shape): the switches, the
/// last answer and hand-in status, and the attribute turn-in rows. Built on demand: everything it
/// reads is volatile or an immutable snapshot. Any thread.
/// </summary>
public string ReaderJson(string world)
{
TimeSpan age = LastAnswerAge;
return BuildJson(world, S.AutoDetectFromChat, S.AutoHandIn, S.BuyMissingFromVendor, S.CooldownHoursAssumed,
_lastAnswer, _lastNpc, age == TimeSpan.MaxValue ? -1 : (long)age.TotalSeconds,
IltGuardianPhrasebook.MessageOf(_lastLine), HandInRunning, _handInStatus, Attributes.SyncedUtc, Attributes.Snapshot);
}
/// <summary>The reader JSON from its parts. Pure: the tests drive it.</summary>
internal static string BuildJson(string world, bool chat, bool auto, bool buy, int cooldownHours,
string answer, string npc, long answerAgeSec, string heard, bool running, string status,
DateTime syncedUtc, System.Collections.Generic.IReadOnlyList<IltTempleAttrStatus> rows)
{
var sb = new System.Text.StringBuilder(1024);
sb.Append("{\"available\":true");
Str(sb, "world", world);
sb.Append(",\"chat\":").Append(chat ? "true" : "false");
sb.Append(",\"auto\":").Append(auto ? "true" : "false");
sb.Append(",\"buy\":").Append(buy ? "true" : "false");
sb.Append(",\"cooldownHours\":").Append(cooldownHours);
Str(sb, "answer", answer);
Str(sb, "npc", npc);
sb.Append(",\"answerAgeSec\":").Append(answerAgeSec);
Str(sb, "heard", heard);
sb.Append(",\"running\":").Append(running ? "true" : "false");
Str(sb, "status", status);
Str(sb, "synced", syncedUtc == DateTime.MinValue ? "" : syncedUtc.ToString("yyyy-MM-ddTHH:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture));
sb.Append(",\"rows\":[");
for (int i = 0; i < rows.Count; i++)
{
IltTempleAttrStatus r = rows[i];
if (i > 0) sb.Append(',');
sb.Append('{');
Str(sb, "attribute", r.Attribute, first: true);
Str(sb, "npc", r.Npc);
sb.Append(",\"count\":").Append(r.Count);
Str(sb, "status", r.Status);
Str(sb, "eta", r.Eta);
sb.Append(",\"ready\":").Append(r.Ready ? "true" : "false");
sb.Append(",\"exact\":").Append(r.FromMyQuests ? "true" : "false");
sb.Append('}');
}
sb.Append("]}");
return sb.ToString();
}
private static void Str(System.Text.StringBuilder sb, string name, string? value, bool first = false)
{
if (!first) sb.Append(',');
sb.Append('"').Append(name).Append("\":\"").Append(IltStyle.JsonEscape(value ?? string.Empty)).Append('"');
}
/// <summary>
/// A reader's verb line (header of Plugins/Shared/RynthIltDataApi.cs): handin | stop | refresh |
/// chat on|off | auto on|off | buy on|off. The reader shows the new state, so the switches don't
/// echo in chat; hand-in and refresh report as the Guardian window's buttons do. Pump thread.
/// </summary>
public void RunVerb(string line)
{
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0) return;
string arg = parts.Length > 1 ? parts[1] : "";
switch (parts[0].ToLowerInvariant())
{
case "handin": StartHandIn(_lastAnswer, _lastNpc, asked: true); break;
case "stop": StopHandIn(); break;
case "refresh": _ctx.Chat("[ILT Guardian] " + Attributes.Refresh()); break;
case "chat": S.AutoDetectFromChat = Toggle(arg, S.AutoDetectFromChat); break;
case "auto": S.AutoHandIn = Toggle(arg, S.AutoHandIn); break;
case "buy": S.BuyMissingFromVendor = Toggle(arg, S.BuyMissingFromVendor); break;
default:
RynthLog.Trace(LogCat.IltHub, $"[IltGuardian] reader verb ignored: {line}");
return;
}
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] reader verb: {line}");
}
private static bool Toggle(string mode, bool current) => mode.Trim().ToLowerInvariant() switch
{
"on" or "true" or "1" or "show" => true,

View file

@ -34,6 +34,8 @@ internal sealed class IltHubController
private int _questGeneration; // RynthAi's /myquests refreshes seen (NoteQuestTrackerOutcome)
private bool _availabilityAnnounced; // "open the Mini Remote" hint printed this session
private volatile int _forceRequest = -1; // SetForceIlt from another thread, applied on the next tick
private long _tabDrawnAt = long.MinValue / 2; // a tab drawn as RynthCore's section view (render thread)
private const long TabDrawnMs = 2000;
// "RynthILT.Data" (Plugins/Shared/RynthIltDataApi.cs): the charms and bank snapshots, rebuilt on
// the pump every DataRebuildMs only while a reader has asked within DataWatchMs.
@ -45,6 +47,11 @@ internal sealed class IltHubController
private long _charmsBuiltAt, _bankBuiltAt, _siblingsReadAt;
private volatile string _charmsJson = string.Empty;
private volatile string _bankJson = string.Empty;
// "RynthILT.Server" profile JSON (RynthOracle: feature states, fellowship rules, the /qb list). Rebuilt ~1 s.
private const long ProfileRebuildMs = 1000;
private long _profileBuiltAt;
private volatile string _profileJson = string.Empty;
private List<IltBankExport.Row> _siblings = new();
public IltBanking Banking { get; }
@ -55,6 +62,8 @@ internal sealed class IltHubController
public IltPetLogs PetLogs { get; }
/// <summary>The pet breeding tracker (the Pets tab's Breeding sub-tab, and the "RynthILT.Data" breeding JSON).</summary>
public IltPetBreeding Breeding { get; }
/// <summary>The Pets tab's ACECustom sections: pet charms, the summon-from-empty refill path, siphon auto-capture.</summary>
public IltPetAutomation PetAutomation { get; }
public IltProgression Progression { get; }
public IltGear Gear { get; }
public IltGames Games { get; }
@ -64,8 +73,12 @@ internal sealed class IltHubController
public IltCharms CharmsTab { get; }
/// <summary>Temple guardians: riddle translator, hand-in, attribute turn-in tracker.</summary>
public IltGuardian Guardian { get; }
/// <summary>Vaulted Dungeons keeper (Mini Remote tab). ILT-only and behind RynthAi's master switch, off by default.</summary>
/// <summary>Vaulted Dungeons keeper (Mini Remote tab). ILT-only and behind its master switch (State.VaultedDungeonsEnabled), off by default.</summary>
public IltVaultedDungeons VaultedDungeons { get; }
/// <summary>The Empyrean Handler's lethal ring: asks RynthAi to back away (RynthAi.Hub BackAwayFrom).</summary>
public IltRingEvade RingEvade { get; }
/// <summary>T11 gear: the "/aug" wield counters for RynthAi's loot rules, "/ilt t11".</summary>
public IltT11 T11 { get; }
/// <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>
@ -86,6 +99,7 @@ internal sealed class IltHubController
Banking = new IltBanking(_ctx);
PetLogs = new IltPetLogs(_ctx);
Breeding = new IltPetBreeding(_ctx);
PetAutomation = new IltPetAutomation(_ctx);
Rates = new IltSessionRates(_ctx);
QuestBonus = new IltQuestBonus(_ctx);
Progression = new IltProgression(_ctx);
@ -95,13 +109,33 @@ internal sealed class IltHubController
CharmsTab = new IltCharms(_ctx, Charms);
Guardian = new IltGuardian(_ctx, QuestBonus);
VaultedDungeons = new IltVaultedDungeons(_ctx);
_features.AddRange(new IIltFeature[] { Banking, PetLogs, Breeding, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, VaultedDungeons, Guardian });
RingEvade = new IltRingEvade(_ctx);
T11 = new IltT11(_ctx);
_features.AddRange(new IIltFeature[] { Banking, PetLogs, Breeding, PetAutomation, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, VaultedDungeons, Guardian, RingEvade, T11 });
Banking.BalanceChanged += Rates.OnBankBalanceChanged;
Rates.MovingMoney = () => Banking.MovingMoney;
options.ProbeReplyTap = OnProbeReply;
_ui = new IltHubUi(this, _ctx);
_ctx.ShowTab = section => _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), "show");
RebuildProfile();
}
/// <summary>
/// The latest "RynthILT.Server" profile JSON: Leaftide features, fellowship rules and the /qb
/// list (Plugins/Shared/RynthIltServerApi.cs). Rebuilt on the pump about once a second so any
/// thread (ServerInterface) may read it.
/// </summary>
public string ProfileJson => _profileJson;
/// <summary>Rebuilds <see cref="ProfileJson"/> from the current server options. Pump thread.</summary>
private void RebuildProfile()
{
IltServerOptions o = _ctx.Options;
_profileJson = IltFeatureCatalog.BuildProfileJson(
o.IsIltLikeWorld, o.WorldName, _ctx.State.ForceLeaftideFeatures,
o.Source ?? string.Empty, o.LastRefreshUtc, o.Get,
QuestBonus.Snapshot());
}
/// <summary>
@ -144,6 +178,20 @@ internal sealed class IltHubController
Breeding.RunVerb(line);
});
/// <summary>
/// The Temple guardian JSON ("RynthILT.Data" GetGuardianJson): switches, last answer, hand-in
/// status and attribute turn-ins. "" off an ILT world. Any thread.
/// </summary>
public string GuardianJson => _ctx.Options.IsIltLikeWorld ? Guardian.ReaderJson(_ctx.Options.WorldName) : string.Empty;
/// <summary>A reader's guardian verb line, posted to the pump (IltGuardian.RunVerb). Any thread.</summary>
public void RequestGuardianVerb(string line)
=> _ctx.Post(() =>
{
if (!_ctx.Options.IsIltLikeWorld) return;
Guardian.RunVerb(line);
});
/// <summary>A reader's bank verb line, posted to the pump (IltBanking.RunVerb). Any thread.</summary>
public void RequestBankVerb(string line)
=> _ctx.Post(() =>
@ -195,7 +243,7 @@ internal sealed class IltHubController
IltSection.Character => true,
IltSection.Banking => Available && !_ctx.Options.IsOff(IltFeature.Bank),
IltSection.Games => Available && Games.AnyGameAvailable,
// Content, not a server feature bit: an ILT world and the master switch (RynthAi's setting).
// Content, not a server feature bit: an ILT world and the master switch.
IltSection.VaultedDungeons => _ctx.Options.IsIltLikeWorld && VaultedDungeons.MasterEnabled(),
_ => Available,
};
@ -212,6 +260,9 @@ internal sealed class IltHubController
/// <summary>Render thread: one Mini Remote ILT tab's body (RynthAi's MiniRemoteHud draws the tab bar).</summary>
public void RenderTab(IltSection section) => _ui.RenderTab(section);
/// <summary>Render thread: a tab was just drawn as RynthCore's section view (it counts as the Mini Remote on screen).</summary>
public void NoteTabDrawn() => System.Threading.Interlocked.Exchange(ref _tabDrawnAt, IltHubContext.NowMs);
/// <summary>
/// Render thread: the ILT session extras (coins, pyreals, item conversions) in RynthCore's Mini
/// Remote "Session Stats" section, below RynthAi's session stats (surface "section:ilt-rates").
@ -288,8 +339,18 @@ internal sealed class IltHubController
try { RebuildReaderData(now); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "RebuildReaderData"); }
// "Mini Remote on screen" gates bank auto-refresh and the gear / split-arrow scans.
_ctx.State.WindowVisible = _ctx.Ai.MiniRemoteVisible;
// The profile other plugins read ("RynthILT.Server"): world, feature states, fellowship, /qb.
if (now - _profileBuiltAt >= ProfileRebuildMs)
{
_profileBuiltAt = now;
try { RebuildProfile(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "RebuildProfile"); }
}
// "Mini Remote on screen" gates bank auto-refresh and the gear / split-arrow scans: RynthAi's Mini
// Remote, or one of the tabs drawn as RynthCore's section view in the last couple of seconds.
_ctx.State.WindowVisible = _ctx.Ai.MiniRemoteVisible
|| now - System.Threading.Interlocked.Read(ref _tabDrawnAt) < TabDrawnMs;
// One hint per session once the server confirms ILT features. The Mini Remote is separate
// from the main RynthAi panel, so say how to open it.
@ -325,6 +386,59 @@ internal sealed class IltHubController
}
}
/// <summary>A creature's health update from the server (RynthPluginOnUpdateHealth): auto-capture's fallback health read.</summary>
public void OnUpdateHealth(uint objectId, float healthRatio)
{
if (!_ctx.Options.IsIltLikeWorld) return;
PetAutomation.NoteHealth(objectId, healthRatio);
}
/// <summary>
/// The sub-tabs RynthILT adds to one of RynthAi's tabs (RynthILT.Hub GetSubTabs): the Pets tab's
/// Breeding on an ILT world whose server hasn't reported pet breeding off. (Id, label) pairs; the
/// id is a RenderSection id. Any thread.
/// </summary>
public (string Id, string Label)[] SubTabs(string parent)
{
if (!string.Equals(parent, RynthCore.Plugin.Shared.RynthIltHub.TabParentPets, StringComparison.OrdinalIgnoreCase)
|| !_ctx.Options.IsIltLikeWorld || _ctx.Options.IsOff(RynthCore.Plugin.Shared.RynthIltHub.FeaturePetBreeding))
return Array.Empty<(string, string)>();
return new[] { (RynthCore.Plugin.Shared.RynthIltHub.SectionPetBreeding, "Breeding") };
}
/// <summary>
/// RynthILT.Hub GetSetting: a setting another plugin mirrors (RynthIltHub.Setting*), -1 when not offered
/// (unknown key, or off an ILT world: the engine row then hides). Any thread.
/// </summary>
public int GetSetting(string key) => key switch
{
RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons when _ctx.Options.IsIltLikeWorld
=> _ctx.State.VaultedDungeonsEnabled ? 1 : 0,
_ => -1,
};
/// <summary>
/// RynthILT.Hub GetText: a short text RynthAi shows (RynthIltHub.Text*); "" for an unknown id, and
/// the session tail off ILT. Any thread.
/// </summary>
public string GetText(string id) => id switch
{
RynthCore.Plugin.Shared.RynthIltHub.TextServerId => IltSectionsManifest.Server,
RynthCore.Plugin.Shared.RynthIltHub.TextSessionReport when _ctx.Options.IsIltLikeWorld => _ui.SessionReportTail(),
_ => string.Empty,
};
/// <summary>RynthILT.Hub SetSetting: false for an unknown key. Saved with the state (next periodic save). Any thread.</summary>
public bool SetSetting(string key, int value)
{
if (key != RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons) return false;
bool on = value != 0;
if (_ctx.State.VaultedDungeonsEnabled != on)
RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons master switch {(on ? "on" : "off")} (Settings window)");
_ctx.State.VaultedDungeonsEnabled = on;
return true;
}
/// <summary>The server's killer notification (pump thread): restarts the Vaulted Dungeons no-kill timer, on ILT only.</summary>
public void OnKillNotification()
{
@ -334,13 +448,16 @@ internal sealed class IltHubController
}
/// <summary>Pump-thread chat line. Returns true when the line should be hidden.</summary>
public bool OnChat(string text)
public bool OnChat(string text, int chatType = -1)
{
if (string.IsNullOrEmpty(text)) return false;
string line = text.TrimEnd('\r', '\n');
_ctx.Options.OnChatLine(line);
bool eat = _ctx.Capture.OnChatLine(line);
if (!_ctx.Options.IsIltLikeWorld) return eat;
// The ring line needs its chat type (a player repeating it is ignored).
try { RingEvade.OnChatLine(line, chatType); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "IltRingEvade.OnChatLine"); }
foreach (var f in _features)
{
try { eat |= f.OnChat(line); }
@ -353,7 +470,7 @@ internal sealed class IltHubController
private static LogCat CategoryOf(IIltFeature f) => f switch
{
IltBanking => LogCat.IltBanking,
IltPetLogs or IltPetBreeding => LogCat.IltPets,
IltPetLogs or IltPetBreeding or IltPetAutomation => LogCat.IltPets,
IltSessionRates => LogCat.IltRates,
IltQuestBonus => LogCat.IltQuests,
IltProgression => LogCat.IltProgression,
@ -513,7 +630,7 @@ internal sealed class IltHubController
default:
_ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote)|refresh|bank|status|features|force on|off|servers [list]|clap|confirm|cancel");
_ctx.Chat("[Mini Remote] /ra hub open pets|banking|gear|charms|games|vaulted [show|hide|toggle] (Mini Remote tabs; character: /ro character, quests: /ro)");
_ctx.Chat("[Mini Remote] /ilt vaulted [on|off|toggle|status] (Vaulted Dungeons; master switch: Settings > Navigation > Vaulted Dungeons)");
_ctx.Chat("[Mini Remote] /ilt vaulted [on|off|toggle|status] (Vaulted Dungeons; master switch: /ilt settings or Settings > Navigation > Vaulted Dungeons)");
_ctx.Chat("[Mini Remote] /ra hub profile list|save <name> [shared]|load <name> /ra hub suit list|test|load [name]");
_ctx.Chat("[Mini Remote] /ra hub attr run|stop|costs|status|auto on|off|every <min>|raise <stat> <n> (Skills panel > Progression)");
_ctx.Chat("[Mini Remote] /ra quests refresh (quiet /myquests) /ra pets [show|hide] /ilt qb (the quest bonus list)");
@ -602,7 +719,7 @@ internal sealed class IltHubController
if (section == IltSection.VaultedDungeons && !SectionAvailable(section))
{
_ctx.Chat(_ctx.Options.IsIltLikeWorld
? "[Mini Remote] The Vaulted Dungeons tab is off: turn on \"Vaulted Dungeons\" in Settings > Navigation (the master switch, off by default)."
? "[Mini Remote] The Vaulted Dungeons tab is off: turn on \"Vaulted Dungeons\" in the ILT settings (/ilt settings; also Settings > Navigation) (the master switch, off by default)."
: "[Mini Remote] Vaulted Dungeons is not available on this server (Infinite Leaftide / ACECustom only).");
return;
}

View file

@ -38,6 +38,12 @@ public sealed class IltHubState
/// <summary>True once the one-time UtilityBelt sidecar import has run for this character.</summary>
public bool UbSidecarsImported;
/// <summary>
/// True once the RynthAi settings that moved to RynthILT on 2026-10-20 (the Pets tab's ACECustom
/// options, ...) were copied from this character's RynthAi files (IltMigration.ImportRynthAiSettings).
/// </summary>
public bool RynthAiSettingsImported;
/// <summary>Last-seen server feature bits. Cache only — overwritten by every login refresh.</summary>
public IltServerOptionsSnapshot ServerOptions = new();
@ -47,6 +53,56 @@ public sealed class IltHubState
public IltGearState Gear = new();
public IltGamesState Games = new();
public IltGuardianState Guardian = new();
/// <summary>Infinite Leaftide combat helpers (moved from RynthAi's profile 2026-10-20).</summary>
public IltCombatState Combat = new();
/// <summary>
/// The Vaulted Dungeons keeper's master switch (off by default): while off it does nothing (no
/// recalls, no /rc quit, no tab). RynthAi's "Vaulted Dungeons" setting until 2026-10-20 (copied once);
/// set in the ILT settings ("/ilt settings") or the engine's Settings > Navigation row (RynthAi
/// mirrors it through RynthILT.Hub GetSetting / SetSetting).
/// </summary>
public bool VaultedDungeonsEnabled;
/// <summary>ACECustom T11 gear (IltT11): the item-aug override (moved from RynthAi's profile 2026-10-20).</summary>
public IltT11State T11 = new();
/// <summary>The ILT sections of RynthAi's Remote tab (moved from RynthAi's huds.json 2026-10-20).</summary>
public IltRemoteState Remote = new();
}
// ── RynthAi's Remote tab ────────────────────────────────────────────────────
public sealed class IltRemoteState
{
/// <summary>The Remote tab's Bank section (ILT bank balances). Was RynthAi's MiniShowBank.</summary>
public bool ShowBank = true;
/// <summary>The Remote tab's Guardian line (the last Temple guardian answer). Was RynthAi's MiniShowGuardian.</summary>
public bool ShowGuardian = true;
}
// ── T11 ─────────────────────────────────────────────────────────────────────
public sealed class IltT11State
{
/// <summary>
/// The item augmentation count T11 wield gates use ("T11: Can Wield" in RynthAi's loot rules) instead
/// of the "/aug" reply's; -1 = automatic (read from /aug). "/ilt t11 augs &lt;n|auto&gt;". Was RynthAi's
/// T11ItemAugsOverride.
/// </summary>
public int ItemAugsOverride = -1;
}
// ── Combat ──────────────────────────────────────────────────────────────────
public sealed class IltCombatState
{
/// <summary>
/// When the Empyrean Handler channels its lethal ring and the character is inside it, have RynthAi
/// back-jump away and re-engage (IltRingEvade; RynthAi acts only while its macro runs with combat
/// on). On by default because it is gated that way. Was RynthAi's HandlerRingEvade.
/// </summary>
public bool HandlerRingEvade = true;
}
/// <summary>Cached result of the server-options check (see IltServerOptions).</summary>
@ -110,8 +166,22 @@ public sealed class IltPetState
public List<string> ShinyLog = new();
/// <summary>The breeding tracker: rules this server showed, growth stage names, recent events (IltPetBreeding).</summary>
public IltBreedingState Breeding = 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.
// ACECustom's parts of the Pets tab (IltPetAutomation, moved from RynthAi 2026-10-20; copied once
// from RynthAi's miniremote.json by IltMigration.ImportRynthAiSettings). New names on purpose: an
// old ilt-hub.json copy still carries RynthAi's UsePyrealRefillPath / AutoCaptureEnabled /
// CaptureLensIndex from before 2026-10-13, and those stale values must not be read back.
/// <summary>
/// Summon from an EMPTY essence while the Summon Essence Refill charm is on (the server refills it
/// from banked pyreals). Still needs the server to confirm the feature (RynthAi.Hub's PetManager
/// asks AllowSummonOnEmpty).
/// </summary>
public bool RefillFromEmpty;
/// <summary>Use the chosen siphon lens on the nearest creature once it is weak enough (off by default).</summary>
public bool AutoCapture;
/// <summary>Index into PetCaptureRules.Lenses (Flawed to Asheron's).</summary>
public int CaptureLens;
// The Pets tab's own settings (roster, healing / cosmetic pets) are RynthAi's (its miniremote.json).
}
// ── Character ───────────────────────────────────────────────────────────────

View file

@ -150,6 +150,7 @@ internal sealed class IltHubStore
s.Pet.Breeding.StageNames ??= new();
s.Pet.Breeding.Log ??= new();
s.Pet.Breeding.LastDebug ??= new();
s.Pet.CaptureLens = Math.Clamp(s.Pet.CaptureLens, 0, PetCaptureRules.Lenses.Length - 1);
s.Pet.Breeding.Rules.RemoveAll(r => r == null || string.IsNullOrEmpty(r.Key));
s.Pet.Breeding.Log.RemoveAll(e => e == null);
for (int i = 0; i < s.Pet.Breeding.StageNames.Count; i++) s.Pet.Breeding.StageNames[i] ??= string.Empty;
@ -169,6 +170,10 @@ internal sealed class IltHubStore
s.Gear.DispelExclusions ??= new();
s.Gear.RingRuns = new Dictionary<string, int>(s.Gear.RingRuns ?? new(), StringComparer.OrdinalIgnoreCase);
s.Games ??= new IltGamesState();
s.Combat ??= new IltCombatState();
s.T11 ??= new IltT11State();
s.Remote ??= new IltRemoteState();
if (s.T11.ItemAugsOverride < -1) s.T11.ItemAugsOverride = -1;
s.Guardian ??= new IltGuardianState();
s.Guardian.TurnInCounts = new Dictionary<string, int>(s.Guardian.TurnInCounts ?? new(), StringComparer.OrdinalIgnoreCase);
s.Guardian.CooldownUntilUtc = new Dictionary<string, DateTime>(s.Guardian.CooldownUntilUtc ?? new(), StringComparer.OrdinalIgnoreCase);

View file

@ -121,13 +121,21 @@ internal sealed class IltHubUi
switch (id)
{
case RynthIltHub.SectionRemoteBank:
if (!o.IsIltLikeWorld || o.IsOff(IltFeature.Bank)) return false;
if (!o.IsIltLikeWorld || o.IsOff(IltFeature.Bank) || !_ctx.State.Remote.ShowBank) return false;
RenderRemoteBank();
return true;
case RynthIltHub.SectionRemoteGuardian:
if (!o.IsIltLikeWorld) return false;
if (!o.IsIltLikeWorld || !_ctx.State.Remote.ShowGuardian) return false;
_hub.Guardian.RenderRemoteLine();
return true;
case RynthIltHub.SectionRemoteStats:
if (!o.IsIltLikeWorld) return false;
RenderRemoteStats();
return true;
case RynthIltHub.SectionRemoteOptions:
if (!o.IsIltLikeWorld) return false;
RenderRemoteOptions();
return true;
case RynthIltHub.SectionQuestBonus:
if (!o.IsIltLikeWorld) return false;
_hub.QuestBonus.RenderSection();
@ -140,6 +148,14 @@ internal sealed class IltHubUi
if (!o.IsIltLikeWorld) return false;
_hub.Breeding.RenderSection();
return true;
case RynthIltHub.SectionPetCharms:
if (!o.IsIltLikeWorld) return false;
_hub.PetAutomation.RenderCharms();
return true;
case RynthIltHub.SectionPetCapture:
if (!o.IsIltLikeWorld) return false;
_hub.PetAutomation.RenderCapture();
return true;
case RynthIltHub.SectionIltStatus:
return RenderIltStatus();
case RynthIltHub.SectionServerMenu:
@ -206,6 +222,34 @@ internal sealed class IltHubUi
}
}
// ── RynthAi's Mini Remote: the Remote tab's Stats lines and Options switches ──
/// <summary>Coins and pyreals per hour under RynthAi's per-hour lines (the Remote tab's Stats).</summary>
private void RenderRemoteStats()
{
var r = _hub.Rates.Summary;
Stat("Coins:", Compact(r.CoinsPerHour) + "/h");
Stat("Pyr:", Compact(r.PyrealsPerHour) + "/h");
}
/// <summary>The Remote tab's ILT sections' switches, in RynthAi's Options popup.</summary>
private void RenderRemoteOptions()
{
var st = _ctx.State.Remote;
bool bank = st.ShowBank, guardian = st.ShowGuardian;
if (ImGui.Checkbox("Bank##iltmrbank", ref bank)) st.ShowBank = bank;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Infinite Leaftide bank balances (RynthILT).");
if (ImGui.Checkbox("Guardian answer##iltmrguardian", ref guardian)) st.ShowGuardian = guardian;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("The last Temple guardian answer with a Give button (RynthILT).");
}
/// <summary>The tail of RynthAi's one-line session report: the coin / pyreal rates (RynthIltHub.TextSessionReport).</summary>
public string SessionReportTail()
{
var r = _hub.Rates.Summary;
return $", Coins {Compact(r.CoinsPerHour)}/h, Pyr {Compact(r.PyrealsPerHour)}/h";
}
// ── RynthAi's Mini Remote: the Remote tab's Bank section ────────────────
private void RenderRemoteBank()

View file

@ -23,11 +23,41 @@ 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>
/// <summary>
/// The fields of a RynthAi profile RynthILT reads (the rest of the file is ignored): the two Server
/// Features fields, and the settings that moved to RynthILT on 2026-10-20 (null when the profile
/// predates them: the default applies).
/// </summary>
public sealed class IltLegacyProfileFlags
{
public List<string>? FeatureServerNames;
public bool ForceServerFeatures;
/// <summary>RynthAi's Empyrean Handler ring evade (on by default there too).</summary>
public bool? HandlerRingEvade;
/// <summary>RynthAi's Vaulted Dungeons master switch (off by default).</summary>
public bool? EnableVaultedDungeons;
/// <summary>RynthAi's T11 item-aug override (-1 = automatic).</summary>
public int? T11ItemAugsOverride;
}
/// <summary>The Remote tab switches of RynthAi's huds.json that moved to RynthILT (2026-10-20).</summary>
public sealed class IltLegacyHuds
{
public bool? MiniShowBank;
public bool? MiniShowGuardian;
}
/// <summary>The Pets tab fields of RynthAi's miniremote.json that moved to RynthILT (2026-10-20).</summary>
public sealed class IltLegacyMiniRemote
{
public IltLegacyPetTab? Pet;
}
public sealed class IltLegacyPetTab
{
public bool? UsePyrealRefillPath;
public bool? AutoCaptureEnabled;
public int? CaptureLensIndex;
}
internal static class IltMigration
@ -67,6 +97,7 @@ internal static class IltMigration
|| File.Exists(Path.Combine(dir, "ilt-hub-transactions.json"))
|| Directory.Exists(Path.Combine(dir, "ilt-hub-profiles"))
|| File.Exists(Path.Combine(dir, "active_profile.txt"))
|| File.Exists(Path.Combine(dir, LegacyMiniRemoteFile))
|| File.Exists(Path.Combine(dir, "Default.json"))))
return dir;
return null;
@ -163,6 +194,70 @@ internal static class IltMigration
return done;
}
/// <summary>RynthAi's per-character Mini Remote file (the Pets tab's settings).</summary>
public const string LegacyMiniRemoteFile = "miniremote.json";
/// <summary>RynthAi's per-character HUD file (the Remote tab's section switches).</summary>
public const string LegacyHudsFile = "huds.json";
/// <summary>
/// Once per character (IltHubState.RynthAiSettingsImported): the RynthAi settings that moved to
/// RynthILT on 2026-10-20 are copied from the character's RynthAi files into <paramref name="state"/>:
/// from miniremote.json the Pets tab's ACECustom options (summon from empty with the refill
/// charm, siphon auto-capture and its lens); from the active profile (as ReadProfileFlags) the
/// Empyrean Handler ring evade, the Vaulted Dungeons master switch and the T11 item-aug override;
/// from huds.json the Remote tab's Bank / Guardian switches. The RynthAi files are only read (RynthAi keeps the
/// old fields readable and no longer uses them). A character with no RynthAi files keeps
/// RynthILT's defaults. Returns what was copied (for the log); empty when nothing was done.
/// </summary>
public static List<string> ImportRynthAiSettings(IltHubState state, string world, string charName)
{
var done = new List<string>();
if (state.RynthAiSettingsImported || string.IsNullOrWhiteSpace(charName)) return done;
string? legacy = FindLegacyCharFolder(world, charName);
if (legacy != null)
{
if (ReadJson(Path.Combine(legacy, LegacyMiniRemoteFile), IltHubJsonContext.Default.IltLegacyMiniRemote) is { Pet: { } pet })
{
if (pet.UsePyrealRefillPath is bool refill) { state.Pet.RefillFromEmpty = refill; done.Add($"summon from empty essences {(refill ? "on" : "off")}"); }
if (pet.AutoCaptureEnabled is bool capture) { state.Pet.AutoCapture = capture; done.Add($"auto-capture {(capture ? "on" : "off")}"); }
if (pet.CaptureLensIndex is int lens)
{
state.Pet.CaptureLens = Math.Clamp(lens, 0, PetCaptureRules.Lenses.Length - 1);
done.Add("capture lens " + PetCaptureRules.LensAt(state.Pet.CaptureLens).Name);
}
}
if (ReadJson(Path.Combine(legacy, LegacyHudsFile), IltHubJsonContext.Default.IltLegacyHuds) is { } huds)
{
if (huds.MiniShowBank is bool bank) { state.Remote.ShowBank = bank; if (!bank) done.Add("the Remote tab's Bank hidden"); }
if (huds.MiniShowGuardian is bool g) { state.Remote.ShowGuardian = g; if (!g) done.Add("the Remote tab's Guardian line hidden"); }
}
if (ReadProfileFlags(legacy, out IltLegacyProfileFlags flags))
{
if (flags.HandlerRingEvade is bool ring) { state.Combat.HandlerRingEvade = ring; done.Add($"Empyrean Handler ring evade {(ring ? "on" : "off")}"); }
if (flags.EnableVaultedDungeons is bool vaulted) { state.VaultedDungeonsEnabled = vaulted; done.Add($"Vaulted Dungeons master switch {(vaulted ? "on" : "off")}"); }
if (flags.T11ItemAugsOverride is int augs && augs >= 0) { state.T11.ItemAugsOverride = augs; done.Add($"T11 item augmentations fixed at {augs:N0}"); }
}
}
state.RynthAiSettingsImported = true;
if (done.Count == 0) done.Add(legacy == null ? "no RynthAi settings for this character (defaults kept)" : "nothing set in RynthAi (defaults kept)");
return done;
}
/// <summary>A JSON file read with <paramref name="info"/>, or null (missing or unreadable: logged).</summary>
private static T? ReadJson<T>(string path, System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> info) where T : class
{
try
{
return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllText(path), info) : null;
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.IltStore, ex, $"migration: read {path}");
return null;
}
}
/// <summary>The character's active RynthAi profile's Server Features fields.</summary>
internal static bool ReadProfileFlags(string legacyCharFolder, out IltLegacyProfileFlags flags)
{

View file

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

View file

@ -1,4 +1,6 @@
// PetCaptureRules.cs — ACECustom MonsterCapture thresholds for siphon lenses (pure; no host).
// IltPetCaptureRules.cs — ACECustom MonsterCapture thresholds for siphon lenses (pure; no host).
// Moved from RynthAi's Pets tab (MiniRemote/PetCaptureRules.cs) 2026-10-20 with the auto-capture
// itself (IltPetAutomation): monster capture is ACECustom's, so it is RynthILT's.
//
// Copied from ACECustom Source/ACE.Server/Entity/MonsterCapture.cs so the client can tell when
// a creature is weak enough to siphon before using a lens. Keep these numbers in lockstep with
@ -7,10 +9,10 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.MiniRemote;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One siphon lens the Pets tab can auto-use (name, WCID, whether health is gated).</summary>
public readonly struct PetCaptureLens
internal readonly struct PetCaptureLens
{
public PetCaptureLens(string name, uint wcid, bool bypassesHealthGate)
{
@ -30,7 +32,7 @@ public readonly struct PetCaptureLens
/// A creature is weak enough when its health fraction is ≤ 20% OR its current HP is under 20
/// (whichever comes first). Asheron's Lens skips that check.
/// </summary>
public static class PetCaptureRules
internal static class PetCaptureRules
{
/// <summary>A lens targets the nearest attackable creature within this many meters.</summary>
public const float CaptureRangeM = 5.0f;
@ -100,12 +102,12 @@ public static class PetCaptureRules
}
/// <summary>
/// A brake on the auto-capture loop. The Pets tab fires a lens every couple of seconds and only stops
/// A brake on the auto-capture loop. Auto-capture fires a lens every couple of seconds and only stops
/// on reply strings it guesses at, so an unrecognized reply (or a creature the server never lets go of)
/// would burn lenses without end. This caps consecutive tries per target and, as a backstop, consecutive
/// tries over all targets; both reset on a recognized success. Pure: the tests drive it.
/// </summary>
public sealed class PetCaptureThrottle
internal sealed class PetCaptureThrottle
{
/// <summary>Lens uses on one creature, with no success in between, before it is left alone.</summary>
public const int MaxTriesPerTarget = 5;

View file

@ -2,8 +2,9 @@
// (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.
// pets) stayed in RynthAi (MiniRemote/PetsTab.cs): summoning is every server's, these two commands
// are ACECustom's (as are the pet charms, the refill path and siphon capture: IltPetAutomation,
// moved 2026-10-20).
using System;
using System.Collections.Generic;
using ImGuiNET;

View file

@ -125,6 +125,12 @@ internal sealed class IltQuestBonus : IIltFeature
/// <summary>Increments each time a "/qb list" reply is parsed (0 = not loaded this session).</summary>
public int QbGeneration => _qbGeneration;
/// <summary>
/// Snapshot for the "RynthILT.Server" profile JSON (Oracle Quests / Fellowship). Pump thread.
/// </summary>
public IltQuestBonusInfo Snapshot() =>
new(_ctx.Options.IsOff(IltFeature.Qb), _qbGeneration, _qbCount, _qbStatus, _qbCompleted, _qbIncomplete);
/// <summary>True when the last "/qb list" (completed or incomplete) contains the flag.</summary>
public bool QbHasFlag(string flag)
{

View file

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

View file

@ -15,6 +15,15 @@ namespace RynthCore.Plugin.RynthILT.Hub;
internal static class IltSalvage
{
/// <summary>
/// Leaftide trinkets (compass, goggles, scarab, watch, puzzle box, tops): jewelry that takes the
/// Trinkets bench's recipes (UB-IT's IsLeaftideTrinketJewelry; RynthAi's TinkerCatalog.IsTrinket until
/// 2026-10-20). Sent in the profile's "trinkets" (RynthServer.Profile).
/// </summary>
internal static readonly string[] TrinketNames = { "compass", "goggles", "scarab", "watch", "puzzle box", "top" };
/// <summary>"top" but not "topaz".</summary>
internal static readonly string[] TrinketExcept = { "topaz" };
// MaterialType (131) ids.
private const int Wool = 8, BlackGarnet = 15, Diamond = 20, GreenJade = 24, Ruby = 38, TigerEye = 42, Tourmaline = 43,
Turquoise = 44, WhiteQuartz = 46, YellowGarnet = 48, Leather = 52, GromnieHide = 54, Copper = 59, Pyreal = 62,

View file

@ -31,7 +31,7 @@ internal enum IltSection
Games,
/// <summary>
/// Vaulted Dungeons keeper (portal-recall gem + kill-client). A Mini Remote tab on ILT worlds only,
/// and only while RynthAi's "Vaulted Dungeons" master switch (Settings > Navigation) is on.
/// and only while its "Vaulted Dungeons" master switch (/ilt settings, Settings > Navigation) is on.
/// </summary>
VaultedDungeons,
/// <summary>Registry charms (acquired / status / tier / server) and the Guardian Hand.</summary>

View file

@ -105,6 +105,7 @@ internal sealed class IltSessionRates : IIltFeature
public void Tick(long nowMs)
{
FollowSharedSession();
// The shared stats move every 0.5 s; their rows refresh each second, coins every 5 s.
if (nowMs - _lastSampleAt < SampleIntervalMs)
{
@ -138,6 +139,23 @@ internal sealed class IltSessionRates : IIltFeature
BuildRows();
}
private long _sharedStartTicks; // RynthAi's session start as last seen (0 = not yet)
/// <summary>
/// The coins / pyreals start over with RynthAi's shared session (its Reset XP, or a session that
/// restarted): one clock for both, without RynthAi telling RynthILT. Pump thread.
/// </summary>
private void FollowSharedSession()
{
if (!_ctx.Ai.TryGetSessionStats(out SessionStatsV1 s) || s.StartUtcTicks == 0) return;
if (_sharedStartTicks != 0 && s.StartUtcTicks > _sharedStartTicks)
{
RynthLog.Trace(LogCat.IltRates, "RynthAi's session restarted: coins and pyreals start over too");
Reset();
}
_sharedStartTicks = s.StartUtcTicks;
}
/// <summary>Positive change since the last sample; the first sample only sets the baseline.</summary>
private static long Gain(ref long last, long current)
{

View file

@ -86,6 +86,8 @@ internal static class IltSettingsStore
[JsonSerializable(typeof(List<IltBankTransaction>), TypeInfoPropertyName = "IltBankTransactionList")]
[JsonSerializable(typeof(IltAugCostFile))]
[JsonSerializable(typeof(IltLegacyProfileFlags))]
[JsonSerializable(typeof(IltLegacyMiniRemote))]
[JsonSerializable(typeof(IltLegacyHuds))]
[JsonSourceGenerationOptions(
WriteIndented = true,
IncludeFields = true,

View file

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

View file

@ -7,8 +7,9 @@
// * ILT only. The module does nothing (no tick work, no recall, no quit, no tab) unless
// IltServerOptions.IsIltLikeWorld says this is an Infinite Leaftide / ACECustom world, the same
// verdict every other ILT feature follows. A command answers "not available on this server".
// * Master switch, off by default: RynthAi's "Vaulted Dungeons" setting (Settings > Navigation),
// read through RynthAi.Hub VaultedDungeonsEnabled. It is the only copy. While it is off the module
// * Master switch, off by default: IltHubState.VaultedDungeonsEnabled (the ILT settings, and the
// engine's Settings > Navigation row RynthAi mirrors; RynthAi's profile setting until 2026-10-20,
// copied once). It is the only copy. While it is off the module
// ignores AutoStart, never ticks, sends no recall and no /rc quit, and the tab is hidden. Turning
// it off while running stops the keeper at once and says so once.
// * Active is never resumed from the saved settings. It starts when the player turns it on, or on
@ -122,7 +123,7 @@ internal sealed class IltVaultedDungeons : IIltFeature
public IltVaultedDungeons(IltHubContext ctx)
{
_ctx = ctx;
MasterEnabled = () => _ctx.Ai.VaultedDungeonsEnabled;
MasterEnabled = () => _ctx.State.VaultedDungeonsEnabled;
Activity = () => _ctx.Ai.Activity();
UseGem = gemName =>
{
@ -152,7 +153,7 @@ internal sealed class IltVaultedDungeons : IIltFeature
private static string? GateReply(string gate) => gate switch
{
GateWorld => "Not available on this server (Infinite Leaftide / ACECustom only).",
GateMaster => "Off: turn on \"Vaulted Dungeons\" in Settings > Navigation first (the master switch, off by default).",
GateMaster => "Off: turn on \"Vaulted Dungeons\" in the ILT settings (/ilt settings; also Settings > Navigation) first (the master switch, off by default).",
_ => null,
};
@ -431,7 +432,7 @@ internal sealed class IltVaultedDungeons : IIltFeature
_state = "paused";
_ctx.Chat("[Vaulted Dungeons] Stopped: " + (gate == GateWorld
? "this is not an Infinite Leaftide / ACECustom world."
: "\"Vaulted Dungeons\" was turned off in Settings > Navigation."));
: "\"Vaulted Dungeons\" (the master switch) was turned off."));
SaveIfDirty();
}
@ -552,7 +553,7 @@ internal sealed class IltVaultedDungeons : IIltFeature
? GemNames[_cfg.Gem - 1] : "(none)";
_ctx.Chat($"[Vaulted Dungeons] {(_cfg.Active ? "On" : "Off")} — dungeon={d}, gem={g}, "
+ $"kill-client={(_cfg.Quit ? $"{_cfg.QuitMinutes}m" : "off")}, state={_state}.");
_ctx.Chat("[Vaulted Dungeons] /ilt vaulted [on|off|toggle|status] (Mini Remote tab; master switch: Settings > Navigation > Vaulted Dungeons)");
_ctx.Chat("[Vaulted Dungeons] /ilt vaulted [on|off|toggle|status] (Mini Remote tab; master switch: /ilt settings or Settings > Navigation > Vaulted Dungeons)");
return true;
}
}

View file

@ -51,11 +51,23 @@ internal sealed unsafe class RynthAiClient
private bool _checked;
private long _checkedAt;
private bool _pinned; // tests: a table handed in, never looked up
public RynthAiClient(RynthCoreHost host) => _host = host;
/// <summary>Tests only: use <paramref name="table"/> (a fake RynthAi's table) and never look it up.</summary>
internal void UseTableForTests(IntPtr table)
{
_pinned = true;
_t = (RynthAiHubApiV1*)table;
_checked = true;
System.Threading.Volatile.Write(ref _renderTable, table);
}
/// <summary>Forget the table; the next call looks it up again (login, logout, RynthAi reload).</summary>
public void Reset()
{
if (_pinned) return;
_t = null;
_checked = false;
System.Threading.Volatile.Write(ref _renderTable, IntPtr.Zero);
@ -66,6 +78,7 @@ internal sealed unsafe class RynthAiClient
{
get
{
if (_pinned) return _t;
long now = Environment.TickCount64;
if (_checked && now - _checkedAt < RecheckMs && (_t == null || _t->Version >= 1)) return _t;
_checked = true;
@ -123,22 +136,9 @@ internal sealed unsafe class RynthAiClient
}
}
// ── Vaulted Dungeons (master switch, activity) ──────────────────────────
/// <summary>
/// RynthAi's "Vaulted Dungeons" setting (Settings > Navigation): the master switch of the Vaulted
/// Dungeons keeper, and the only place it is stored. False when RynthAi isn't loaded, is older than
/// the call, hasn't logged in, or has it off (the default): the keeper then does nothing. Any thread.
/// </summary>
public bool VaultedDungeonsEnabled
{
get
{
var t = AnyThreadTable;
return t != null && RynthAiHubApiV1.Has(t, RynthAiHubApiV1.VaultedDungeonsEnabledOffset)
&& t->VaultedDungeonsEnabled != null && t->VaultedDungeonsEnabled() != 0;
}
}
// ── Vaulted Dungeons (activity) ─────────────────────────────────────────
// The master switch is RynthILT's own since 2026-10-20 (IltHubState.VaultedDungeonsEnabled);
// RynthAi.Hub VaultedDungeonsEnabled is no longer read.
/// <summary>
/// What RynthAi is doing now (its "RynthAi.Activity" interface: combat, buffing, loot, a use or cast
@ -161,6 +161,31 @@ internal sealed unsafe class RynthAiClient
}
}
// ── Combat ──────────────────────────────────────────────────────────────
/// <summary>
/// Asks RynthAi to back away from <paramref name="objectId"/> (RynthAi.Hub BackAwayFrom): a
/// RynthAiHub.BackAway* result, or int.MinValue when RynthAi isn't loaded or is older than the
/// call. Pump thread.
/// </summary>
public int BackAwayFrom(uint objectId, float radiusYards, int holdMs)
{
var t = Table;
if (t == null || !RynthAiHubApiV1.Has(t, RynthAiHubApiV1.BackAwayFromOffset) || t->BackAwayFrom == null) return int.MinValue;
return t->BackAwayFrom(objectId, radiusYards, holdMs);
}
/// <summary>
/// Reports one player wield counter to RynthAi's loot rules (RynthAi.Hub SetPlayerCounter; the T11
/// "Can Wield" key): <paramref name="value"/> &lt; 0 = unknown. False without RynthAi (or an older one). Pump thread.
/// </summary>
public bool SetPlayerCounter(uint propertyId, long value)
{
var t = Table;
return t != null && RynthAiHubApiV1.Has(t, RynthAiHubApiV1.SetPlayerCounterOffset)
&& t->SetPlayerCounter != null && t->SetPlayerCounter(propertyId, value) != 0;
}
// ── Quests (/myquests) ──────────────────────────────────────────────────
/// <summary>A /myquests flag from RynthAi's tracker (pump thread).</summary>

View file

@ -27,7 +27,9 @@ internal static unsafe class HubInterface
/// <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)
// Its own name, and the neutral one RynthAi asks the active server's owner for (the same table).
if ((iface != RynthIltHubApiV1.InterfaceName && iface != RynthIltHubApiV1.NeutralInterfaceName)
|| version < 1 || version > RynthIltHubApiV1.InterfaceVersion || _released)
return IntPtr.Zero;
if (_table == null)
{
@ -42,6 +44,11 @@ internal static unsafe class HubInterface
t->RenderTab = &RenderTab;
t->RenderSection = &RenderSection;
t->Command = &Command;
t->AllowSummonOnEmpty = &AllowSummonOnEmpty;
t->GetSubTabs = &GetSubTabs;
t->GetSetting = &GetSetting;
t->SetSetting = &SetSetting;
t->GetText = &GetText;
t->Version = RynthIltHubApiV1.InterfaceVersion;
_table = t;
}
@ -186,6 +193,82 @@ internal static unsafe class HubInterface
catch { return 0; }
}
/// <summary>The Pets tab's summon-from-empty gate (IltPetAutomation's last tick; 0 off ILT).</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int AllowSummonOnEmpty()
{
try { return Hub?.PetAutomation.AllowSummonOnEmpty == true ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetSubTabs(byte* parent, IltTabV1* tabs, int capacity)
{
try
{
var hub = Hub;
string? p = Utf8(parent);
if (hub == null || p == null) return 0;
var all = hub.SubTabs(p);
if (tabs != null)
{
for (int i = 0; i < all.Length && i < capacity; i++)
{
IltTabV1* t = &tabs[i];
WriteUtf8(all[i].Id, t->Id, 24);
WriteUtf8(all[i].Label, t->Label, 32);
t->Width = 0;
t->Height = 0;
t->Flags = RynthIltHub.TabShown | RynthIltHub.TabAvailable;
}
}
return all.Length;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetSetting(byte* key)
{
try
{
var hub = Hub;
string? k = Utf8(key);
return hub == null || k == null ? -1 : hub.GetSetting(k);
}
catch { return -1; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetSetting(byte* key, int value)
{
try
{
var hub = Hub;
string? k = Utf8(key);
return hub != null && k != null && hub.SetSetting(k, value) ? 1 : 0;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetText(byte* id, byte* buffer, int capacity)
{
try
{
var hub = Hub;
string? k = Utf8(id);
if (hub == null || k == null || buffer == null || capacity <= 0) return 0;
string text = hub.GetText(k);
if (text.Length == 0) { buffer[0] = 0; return 0; }
WriteUtf8(text, buffer, capacity);
int n = 0;
while (n < capacity && buffer[n] != 0) n++;
return n;
}
catch { return 0; }
}
/// <summary>Writes <paramref name="s"/> as NUL-terminated UTF-8 into a fixed buffer, truncated to fit.</summary>
private static void WriteUtf8(string s, byte* dest, int capacity)
{

View file

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

View file

@ -1,8 +1,10 @@
// IltSettingsUi.cs - The "ILT settings" view: RynthILT's copy of the Infinite Leaftide settings.
//
// Drawn in its own window ("/ilt settings"). Shows RynthCore's verdict and reason, this character's
// Auto / On / Off override, the ILT world names (edited through RynthCore), and every ILT feature
// with the state RynthILT's Hub read from the server (IltSettingsModel has where each comes from).
// Auto / On / Off override, the ILT world names (edited through RynthCore), this character's ILT
// options (the settings that moved here from RynthAi on 2026-10-20: the Empyrean Handler ring
// evade, ...; saved in the Hub's state), and every ILT feature with the state RynthILT's Hub read
// from the server (IltSettingsModel has where each comes from).
// Edits are RynthCore commands, queued for the plugin tick; the next server-list poll shows the
// result. Render thread only.
using System;
@ -25,6 +27,7 @@ internal sealed class IltSettingsUi
private readonly IltSettingsModel _model;
private readonly Action<string> _runCommand;
private readonly Func<bool> _refreshFeatures;
private readonly Func<IltHubController?> _hub;
private string _newName = string.Empty;
private string _status = string.Empty;
@ -33,11 +36,13 @@ internal sealed class IltSettingsUi
/// <param name="runCommand">Queues a RynthCore command (run on the plugin tick).</param>
/// <param name="refreshFeatures">Asks the Hub to read the server's features again; false before it exists.</param>
public IltSettingsUi(IltSettingsModel model, Action<string> runCommand, Func<bool> refreshFeatures)
/// <param name="hub">This character's Hub (its options live in the Hub's state); null before login.</param>
public IltSettingsUi(IltSettingsModel model, Action<string> runCommand, Func<bool> refreshFeatures, Func<IltHubController?>? hub = null)
{
_model = model;
_runCommand = runCommand;
_refreshFeatures = refreshFeatures;
_hub = hub ?? (() => null);
}
/// <summary>The standalone window, while open.</summary>
@ -56,6 +61,8 @@ internal sealed class IltSettingsUi
{
RenderVerdict();
ImGui.Separator();
RenderCharacterOptions();
ImGui.Separator();
RenderFeatures();
if (_status.Length > 0)
{
@ -123,6 +130,38 @@ internal sealed class IltSettingsUi
}
}
/// <summary>
/// This character's Infinite Leaftide options: the ones that were RynthAi settings until
/// 2026-10-20 (copied over once). Saved with the Hub's state.
/// </summary>
private void RenderCharacterOptions()
{
ImGui.TextUnformatted("This character");
IltHubController? hub = _hub();
if (hub == null)
{
ImGui.TextDisabled("Shown once this character is logged in.");
return;
}
IltHubState st = hub.State;
bool vaulted = st.VaultedDungeonsEnabled;
if (ImGui.Checkbox("Vaulted Dungeons (the keeper's master switch)##iltvaulted", ref vaulted)) st.VaultedDungeonsEnabled = vaulted;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Off by default. While off the Vaulted Dungeons keeper does nothing: no recalls, no /rc quit, no Mini\n"
+ "Remote tab. On: the \"Vaulted Dungeons\" tab shows, where you pick a dungeon and a tied Portal Recall\n"
+ "Gem and start it (/ilt vaulted on). Also in RynthCore's Settings > Navigation (it was a RynthAi setting).");
bool ring = st.Combat.HandlerRingEvade;
if (ImGui.Checkbox("Evade the Empyrean Handler's lethal ring##iltring", ref ring)) st.Combat.HandlerRingEvade = ring;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When an Empyrean Handler channels its lethal ring and you are within 12 yards (or RynthAi's\n"
+ "Ring Range if larger), RynthAi back-jumps away and re-engages. Only while RynthAi's macro\n"
+ "is running with combat on. On by default (it was RynthAi's \"Evade Handler Ring\").");
int augs = st.T11.ItemAugsOverride;
SafeImGui.TextDisabled(augs >= 0
? $"T11 item augmentations: fixed at {augs:N0} for RynthAi's loot rules (/ilt t11 augs auto to read /aug)"
: "T11 item augmentations: read from /aug (/ilt t11 augs <n> fixes them; /ilt t11 shows the counters)");
}
/// <summary>
/// The server's ILT features, one collapsible section per group (Character, Items, Pets,
/// Fellowship, Combat, Activities, then the charms and any other bit chat or a probe set), with

View file

@ -15,8 +15,10 @@ public static unsafe class PluginExports
// sections RynthAi's Mini Remote hosts (Plugins/Shared/RynthIltHubApi.cs, HubInterface.cs), and
// "RynthServer.Profile" v1, ILT's settings and tinkering salvage for any reader, as every server
// plugin serves its own (Plugins/Shared/RynthServerProfileApi.cs, ProfileInterface.cs), and
// "RynthILT.Data" v1, the charms list and bank balances with their actions
// (Plugins/Shared/RynthIltDataApi.cs, DataInterface.cs).
// "RynthILT.Data" v1..v3, the charms list and bank balances with their actions, the pet breeding
// tracker and the Temple guardians (Plugins/Shared/RynthIltDataApi.cs, DataInterface.cs), and
// "RynthILT.Server" v1, the Leaftide feature / fellowship / quest bonus profile RynthOracle reads
// (Plugins/Shared/RynthIltServerApi.cs, ServerInterface.cs).
// Fixed signature: void* (const char* iface, uint version).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version)
@ -26,6 +28,8 @@ public static unsafe class PluginExports
string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? "";
IntPtr table = HubInterface.Query(iface, version);
if (table != IntPtr.Zero) return table;
table = ServerInterface.Query(iface, version);
if (table != IntPtr.Zero) return table;
table = ProfileInterface.Query(iface, version);
return table != IntPtr.Zero ? table : DataInterface.Query(iface, version);
}
@ -44,6 +48,7 @@ public static unsafe class PluginExports
// An exception escaping an UnmanagedCallersOnly export fail-fasts the client under NativeAOT.
try { Runtime.Shutdown(); } catch { }
try { HubInterface.Release(); } catch { }
try { ServerInterface.Release(); } catch { }
try { ProfileInterface.Release(); } catch { }
try { DataInterface.Release(); } catch { }
foreach (IntPtr p in new[] { Interlocked.Exchange(ref _bountiesPtr, IntPtr.Zero), Interlocked.Exchange(ref _progressionPtr, IntPtr.Zero),
@ -92,7 +97,9 @@ public static unsafe class PluginExports
/// still asks) are RynthCore's Mini Remote sections. ":popout" is added when one is popped out
/// into a window of its own, and RynthILT draws in the engine's current context either way. The
/// Guardian panel is user-sized (want echoes the size given); a section reports the height it
/// used. 1 = drawn, 0 = not ready / unknown surface.
/// used. "section:gear|charms|banking|games|vaulted" are the Mini Remote ILT tabs as RynthCore's
/// section views (RynthILT lists them since 2026-10-20; RynthAi did before), sized to the tab.
/// 1 = drawn, 0 = not ready / unknown surface.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })]
public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight)
@ -116,7 +123,16 @@ public static unsafe class PluginExports
: name.SequenceEqual("section:ilt-rates"u8) ? RynthILTPlugin.RatesSurface
: name.SequenceEqual("section:ilt-questbonus"u8) ? RynthILTPlugin.QuestBonusSurface
: null;
if (view == null || !plugin.RenderEmbedded(view, out float wantH)) return 0;
if (view == null)
{
// "section:gear", "section:banking", ...: the Mini Remote ILT tabs RynthILT lists (IltSectionsManifest).
if (name.Length > 64 || !name.StartsWith("section:"u8)) return 0;
if (!plugin.RenderEmbeddedTab(System.Text.Encoding.UTF8.GetString(name), out float tabW, out float tabH)) return 0;
if (wantWidth != null) *wantWidth = tabW > 0 ? tabW : width;
if (wantHeight != null) *wantHeight = tabH > 0 ? tabH : height;
return 1;
}
if (!plugin.RenderEmbedded(view, out float wantH)) return 0;
if (wantWidth != null) *wantWidth = width;
if (wantHeight != null) *wantHeight = wantH;
return 1;
@ -132,6 +148,11 @@ public static unsafe class PluginExports
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag)
=> Runtime.OnChatBarEnter(textUtf16, eatFlag);
// Creatures' health from the server (siphon auto-capture's fallback health read, IltPetAutomation).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
=> Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
// This character's kills re-read the bounty list (while the Bounties window is open).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnKillNotification", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnKillNotification(IntPtr textUtf16) => Runtime.OnKillNotification(textUtf16);

View file

@ -29,6 +29,9 @@ internal static unsafe class ProfileInterface
{
Emulator = "ACE",
Salvage = IltSalvage.Rows,
// Leaftide trinkets (UB-IT's IsLeaftideTrinketJewelry): the Crafting tab's Trinkets bench, not Jewelry.
TrinketNames = IltSalvage.TrinketNames,
TrinketExcept = IltSalvage.TrinketExcept,
Source = "RynthILT; salvage from UB-IT's LeaftideImbueHelper (via SilentKelpie)",
};

View file

@ -13,7 +13,15 @@
RynthILT borrows from RynthAi through RynthAi.Hub (Plugins/Shared/RynthIltHubApi.cs,
RynthAiHubApi.cs).
IltSettingsView/ a copy of the ILT settings (RynthCore's verdict, this character's override, the
ILT world names, the Hub's feature read) in its own window ("/ilt settings").
ILT world names, the Hub's feature read) in its own window ("/ilt settings"),
with this character's ILT options (Vaulted Dungeons master switch, Handler
ring evade, T11 item augs).
Moved out of RynthAi 2026-10-20 (Hub/): the Pets tab's ACECustom parts (IltPetAutomation:
pet charms, summon from empty, siphon capture), the Empyrean Handler ring
detection (IltRingEvade; RynthAi does the back-away), the T11 /aug counters
and "/ilt t11" (IltT11; RynthAi keeps the loot keys), the Vaulted Dungeons
switch, the Remote tab's ILT parts, the Mini Remote tab views on the rail
(IltSectionsManifest.cs) and the Leaftide trinket list (the profile).
IltFellowship/ ILT's /fship commands as buttons ("/ilt fellow").
-->
<PropertyGroup>
@ -43,7 +51,7 @@
<RynthPluginServerName>Infinite Leaftide</RynthPluginServerName>
<RynthPluginServerHosts>infiniteleaftide.online</RynthPluginServerHosts>
<RynthPluginServerWorldNames>InfiniteLeaftide|*Leaftide*</RynthPluginServerWorldNames>
<RynthPluginDescription>Infinite Leaftide (ACECustom) features: the ILT Hub (the Mini Remote's ILT tabs: banking, gear, charms, games), the Guardian, bounties, progression, the attribute raiser, the ring inscription chain, the ILT settings and the /fship fellowship commands.</RynthPluginDescription>
<RynthPluginDescription>Infinite Leaftide (ACECustom) features: the ILT Hub (the Mini Remote's ILT tabs: banking, gear, charms, games, Vaulted Dungeons; the Pets tab's charms, siphon capture and breeding), the Guardian, bounties, progression, the attribute raiser, the ring inscription chain, the Empyrean Handler ring evade, the T11 loot counters, the ILT settings and the /fship fellowship commands.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>
@ -56,12 +64,16 @@
<!-- 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" />
<!-- Chat types and the line-start marker (the Empyrean Handler's ring line, Hub/IltRingEvade.cs). -->
<Compile Include="..\Shared\ChatSource.cs" Link="Shared\ChatSource.cs" />
<!-- "RynthAi.Activity": what the bot is doing (the Vaulted Dungeons keeper waits out combat and buffing). -->
<Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<!-- The pet-capture success lines (shared with RynthAi's Pets tab): they count as a kill for Vaulted Dungeons' timer. -->
<Compile Include="..\Shared\PetCaptureLines.cs" Link="Shared\PetCaptureLines.cs" />
<!-- "RynthILT.Data": the charms list and bank balances for other plugins (DataInterface.cs). -->
<Compile Include="..\Shared\RynthIltDataApi.cs" Link="Shared\RynthIltDataApi.cs" />
<!-- "RynthILT.Server": the feature / fellowship / quest bonus profile for other plugins (ServerInterface.cs). -->
<Compile Include="..\Shared\RynthIltServerApi.cs" Link="Shared\RynthIltServerApi.cs" />
<!-- RynthCore's server list (API v86): the ILT verdict the Hub follows (IltSettingsView/). -->
<Compile Include="..\Shared\EngineServerState.cs" Link="Shared\EngineServerState.cs" />
<!-- "RynthServer.Profile": ILT's settings and tinkering salvage (Hub/IltSalvage.cs) for other
@ -80,6 +92,12 @@
<!-- 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" />
<!-- T11 (ACECustom tier 11+ gear): the "/aug" reader, the counters and the item text parser (Hub/IltT11.cs,
"/ilt t11"). RynthAi keeps the loot keys and evaluator; RynthILT reports the counters to it. -->
<Compile Include="..\..\Shared\RynthCore.LootSdk\T11\T11Catalog.cs" Link="Shared\T11\T11Catalog.cs" />
<Compile Include="..\..\Shared\RynthCore.LootSdk\T11\T11ItemInfo.cs" Link="Shared\T11\T11ItemInfo.cs" />
<Compile Include="..\..\Shared\RynthCore.LootSdk\T11\T11Keys.cs" Link="Shared\T11\T11Keys.cs" />
<Compile Include="..\..\Shared\RynthCore.LootSdk\T11\T11PlayerAugs.cs" Link="Shared\T11\T11PlayerAugs.cs" />
<!-- AcObjectClass (the item classes the gear tools check). -->
<Compile Include="..\..\Shared\RynthCore.LootSdk\AcGameEnums.cs" Link="Shared\AcGameEnums.cs" />
<!-- ILT's /fship commands (IltFellowship/): the shared command list format and its button panel. -->

View file

@ -22,6 +22,13 @@
// comes from RynthCore's server list (plugin API v86, polled every 2 s), and the Hub follows it
// once one arrives (IltEngineVerdict).
//
// Moved from RynthAi on 2026-10-20 (Hub/): the Pets tab's ACECustom parts (IltPetAutomation), the
// Empyrean Handler ring detection (IltRingEvade; RynthAi.Hub BackAwayFrom does the jump), the T11
// "/aug" counters and "/ilt t11" (IltT11; RynthAi.Hub SetPlayerCounter), the Vaulted Dungeons
// master switch, the Remote tab's ILT parts, and the Mini Remote ILT tab views on RynthCore's rail
// (IltSectionsManifest.cs, RenderEmbeddedTab). Their settings were copied once from the
// character's RynthAi files (IltMigration.ImportRynthAiSettings, at the Hub's start).
//
// Third: ILT's fellowship commands (IltFellowship/, ACECustom /fship) as buttons in RynthCore's
// Fellowship section and their own window ("/ilt fellow"). While ILT is active the list is also
// sent to RynthAi ("servercommands"), whose Fellowship view draws them; an empty list clears it.
@ -50,8 +57,8 @@ namespace RynthCore.Plugin.RynthILT;
public sealed class RynthILTPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthILT");
// Previous release: 0.3.1.
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.2");
// Previous release: 0.3.2.
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.3");
/// <summary>
/// The settings view's surface. Not in the sections manifest (the force-server override lives
@ -83,7 +90,7 @@ public sealed class RynthILTPlugin : RynthPluginBase
public RynthILTPlugin()
{
_settingsUi = new IltSettingsUi(_settingsModel, cmd => QueueChatCommand(cmd), RefreshFeatures);
_settingsUi = new IltSettingsUi(_settingsModel, cmd => QueueChatCommand(cmd), RefreshFeatures, () => _hub);
_fellowshipUi = new IltFellowshipUi(QueueChatCommand);
IltEngineVerdict.Attach(_settingsModel);
}
@ -353,27 +360,50 @@ public sealed class RynthILTPlugin : RynthPluginBase
/// <summary>
/// RynthPluginGetSectionsJson (schema 1, UI/Sections/SectionManifest.cs in RynthCore): the ILT
/// session extras in Session Stats ("char"), the fellowship commands in Fellowship and the /qb
/// list in a Quests section of RynthILT's own, all Infinite Leaftide areas (shown while RynthCore
/// treats this world as ILT). The Mini Remote ILT tabs (Banking, Gear, Charms, Games) are listed
/// by RynthAi, which hosts them. Null before login.
/// session extras in Session Stats ("char"), the fellowship commands in Fellowship, the /qb list in
/// a Quests section of RynthILT's own, and the Mini Remote ILT tabs the Hub shows (Gear, Charms,
/// Banking in Inventory, Games in a section of RynthILT's own, Vaulted Dungeons in Nav), all
/// Infinite Leaftide areas (shown while RynthCore treats this world as ILT). IltSectionsManifest.cs.
/// The tabs were listed by RynthAi, which hosted them, until 2026-10-20. Null before login.
/// </summary>
internal string? BuildSectionsJson() => _loginComplete ? SectionsJson : null;
internal string? BuildSectionsJson() => _loginComplete ? IltSectionsManifest.Build(IltSectionsManifest.TabsOf(_hub)) : null;
internal const string SectionsJson =
"{\"version\":1,\"sections\":[{\"id\":\"quests\",\"label\":\"Quests\",\"order\":1160}],\"contributions\":[" +
"{\"section\":\"char\",\"server\":\"ilt\"," +
"\"label\":\"ILT session rates (RynthILT)\",\"surface\":\"" + RatesSurface + "\",\"primary\":false," +
"\"height\":220,\"enabled\":true,\"tooltip\":\"Enlightened Coins, pyreals and item conversions this session, " +
"on the same clock as RynthAi's session stats (RynthILT).\",\"order\":120}," +
"{\"section\":\"fellowship\",\"server\":\"ilt\"," +
"\"label\":\"ILT fellowship (RynthILT)\",\"surface\":\"" + FellowshipSurface + "\",\"primary\":false," +
"\"height\":110,\"enabled\":true,\"tooltip\":\"Infinite Leaftide's /fship commands: create, invite, dismiss, " +
"invite your landblock, list nearby, leave, disband (RynthILT; also /ilt fellow).\",\"order\":120}," +
"{\"section\":\"quests\",\"server\":\"ilt\"," +
"\"label\":\"Quest bonus (/qb)\",\"surface\":\"" + QuestBonusSurface + "\",\"primary\":true," +
"\"width\":520,\"height\":440,\"enabled\":true,\"tooltip\":\"Infinite Leaftide's quest bonus list: completed and " +
"incomplete /qb flags (RynthILT; the quest list, timers and rewards are RynthOracle's, /ro).\",\"order\":100}]}";
/// <summary>
/// RynthPluginRenderEmbed "section:&lt;tab&gt;": one Mini Remote ILT tab as RynthCore's section view
/// (IltSectionsManifest lists them), drawn into the engine's current window and context in the
/// dashboard colours. <paramref name="wantWidth"/> / <paramref name="wantHeight"/> are the tab's
/// size. False until the Hub exists, or for a surface that is no ILT tab. Render thread.
/// </summary>
internal bool RenderEmbeddedTab(string surface, out float wantWidth, out float wantHeight)
{
wantWidth = wantHeight = 0;
IltHubController? hub = _hub;
if (!_loginComplete || hub == null || !IltSectionsManifest.TryTabOf(surface, out IltSection section)) return false;
IntPtr previous = ImGui.GetCurrentContext();
IntPtr context = previous != IntPtr.Zero ? previous : Host.ImGuiContext;
if (context == IntPtr.Zero) return false;
ImGui.SetCurrentContext(context);
int pushed = IltStyle.PushDashboardStyle();
try
{
var size = IltSections.TabSize(section);
wantWidth = size.X;
wantHeight = size.Y;
hub.NoteTabDrawn();
hub.RenderTab(section);
return true;
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.IltHub, ex, "RenderEmbeddedTab " + surface);
return false;
}
finally
{
ImGui.PopStyleColor(pushed);
ImGui.SetCurrentContext(previous);
}
}
/// <summary>Plugin tick: runs the settings and fellowship views' chat commands through the engine.</summary>
private void DrainChatCommands()
@ -486,7 +516,7 @@ public sealed class RynthILTPlugin : RynthPluginBase
try
{
// The Hub eats its own probe / capture replies (IltChatCapture).
if (_hub?.OnChat(text) == true) eat = 1;
if (_hub?.OnChat(text, chatType) == true) eat = 1;
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnChat"); }
if (_bounties == null) return;
@ -519,6 +549,13 @@ public sealed class RynthILTPlugin : RynthPluginBase
_commands.Enqueue(trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries));
}
// A creature's health from the server: siphon auto-capture's fallback health read (ILT only).
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
{
try { _hub?.OnUpdateHealth(targetId, healthRatio); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnUpdateHealth"); }
}
// The server's killer notification: this character landed the killing blow.
public override void OnKillNotification(string? deathMessage)
{
@ -624,15 +661,18 @@ public sealed class RynthILTPlugin : RynthPluginBase
/// <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".
/// Remote tab), "/ra guardian", "/ra bounty|bounties|bountys", "rates" and "t11".
/// </summary>
internal static bool IsIltVerb(string[] words)
{
string verb = words[0].ToLowerInvariant();
switch (verb)
{
case "guardian": case "bounty": case "bounties": case "bountys": case "rates":
case "guardian": case "bounty": case "bounties": case "bountys": case "rates": case "t11":
return true;
case "ub":
// ub-IT's ACECustom verbs RynthAi passes on ("/ub qblist", "/ub augs").
return words.Length >= 2 && words[1].ToLowerInvariant() is "qblist" or "augs";
case "hub":
if (words.Length < 2) return false; // "/ra hub" alone toggles RynthAi's Mini Remote
string sub = words[1].ToLowerInvariant();
@ -678,6 +718,23 @@ public sealed class RynthILTPlugin : RynthPluginBase
case "hub":
case "rates":
break;
case "ub":
{
// ub-IT's "/ub qblist" and "/ub augs" (RynthAi passes them on): ACECustom's own commands.
string sub = args.Length > 0 ? args[0].ToLowerInvariant() : string.Empty;
string? server = sub == "qblist" ? "/qb list" : sub == "augs" ? "/aug" : null;
if (server == null) { ChatLine("[RynthILT] /ub qblist or /ub augs"); return; }
if (_hub?.Options.IsIltLikeWorld != true) { ChatLine($"[RynthILT] /ub {sub}: not an Infinite Leaftide world."); return; }
if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(server)) ChatLine("[RynthILT] RynthCore didn't take: " + server);
return;
}
case "t11":
{
// "/ilt t11 ..." and RynthAi's "/ra t11 ..." (T11 loot counters; IltT11).
if (_hub == null) { ChatLine("[RynthILT] ILT features not ready (log in first)."); return; }
_hub.T11.HandleCommand(args);
return;
}
case "vaulted":
case "vaulteddungeons":
{
@ -707,7 +764,8 @@ public sealed class RynthILTPlugin : RynthPluginBase
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 vaulted [on|off|toggle|status] - Vaulted Dungeons keeper (ILT only; master switch: RynthAi Settings > Navigation > Vaulted Dungeons, off by default),");
ChatLine("[RynthILT] /ilt vaulted [on|off|toggle|status] - Vaulted Dungeons keeper (ILT only; master switch: /ilt settings or Settings > Navigation > Vaulted Dungeons, off by default),");
ChatLine("[RynthILT] /ilt t11 [augs <n|auto>|refresh|item [0xId]] - T11 loot: the /aug wield counters RynthAi's loot rules use, the item-aug override, an item's T11 text (also /ra t11),");
ChatLine("[RynthILT] /ilt settings [show|hide|toggle] - the ILT settings: the world verdict, the ILT world names and the server's features (force a server: RynthCore Options > Diagnostics),");
ChatLine("[RynthILT] /ilt fellow [show|hide|toggle] - ILT's /fship commands as buttons (also in the Mini Remote's Fellowship section),");
ChatLine("[RynthILT] /ilt trace <category|all|list> [on|off], /ilt debug [on|off].");
@ -835,6 +893,10 @@ public sealed class RynthILTPlugin : RynthPluginBase
{
_hub = new IltHubController(Host, folder, _settings, _ai, () => _hubWritesBlocked,
pending ? IltMigration.FindLegacyCharFolder(world, charName) : null);
// Once per character: the RynthAi settings that moved here on 2026-10-20.
var imported = IltMigration.ImportRynthAiSettings(_hub.State, world, charName);
if (imported.Count > 0)
RynthLog.Write(LogCat.IltStore, $"Carried {charName}'s RynthAi settings that moved to RynthILT over: {string.Join(", ", imported)}.");
_hub.OnLoginComplete(charName, force);
}
catch (Exception ex)

View file

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

View file

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthInventory.Data;
/// <summary>One character on the Banking tab: its saved balances (null = never read) and account.</summary>
internal sealed record BankRosterEntry(string Name, string Account, bool Current, IltBankRow? Bank);
/// <summary>
/// The Banking tab's character list (2026-10-13; the Mini Remote's Banking tab moved here). Every
/// character RynthILT has bank balances for on this server (its saved per-character state, so every
/// account played on this PC), plus every character Global Inventory has recorded on the same
/// server without a balance yet, so the list covers the same characters as the inventory does.
/// Pure: the tests feed it a parsed bank view and an index.
/// </summary>
internal static class BankRoster
{
/// <summary>
/// The merged list: the logged-in character first, then by name. A name in both lists keeps
/// RynthILT's balances and the inventory's account.
/// </summary>
public static List<BankRosterEntry> Build(IltBankView bank, InventoryIndex? index)
{
var byName = new Dictionary<string, BankRosterEntry>(StringComparer.OrdinalIgnoreCase);
foreach (IltBankRow r in bank.Characters)
byName[r.Name] = new BankRosterEntry(r.Name, string.Empty, r.Current, r);
if (index != null)
{
foreach (CharacterInfo ci in index.Characters)
{
// Same server only: a bank belongs to one world.
if (!SameServer(ci, bank)) continue;
string account = !string.IsNullOrEmpty(ci.Account) && ci.Account != "unknown" ? ci.Account : string.Empty;
if (byName.TryGetValue(ci.Name, out BankRosterEntry? have))
byName[ci.Name] = have with { Account = account, Current = have.Current || ci.IsCurrentCharacter };
else
byName[ci.Name] = new BankRosterEntry(ci.Name, account, ci.IsCurrentCharacter, null);
}
}
var list = new List<BankRosterEntry>(byName.Values);
list.Sort((a, b) => a.Current != b.Current ? (a.Current ? -1 : 1) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
return list;
}
/// <summary>
/// A recorded character is on the bank's server: the world RynthILT names when it gave one,
/// otherwise the server Global Inventory says you are on now.
/// </summary>
private static bool SameServer(CharacterInfo ci, IltBankView bank) =>
bank.World.Length > 0 ? InventoryIndex.SameName(ci.Server, bank.World) : ci.IsCurrentServer;
/// <summary>The sums over every character with a balance (one row of the same shape).</summary>
public static IltBankRow Totals(IReadOnlyList<BankRosterEntry> roster)
{
long py = 0, lum = 0, lk = 0, mk = 0, ec = 0, wec = 0, pc = 0;
foreach (BankRosterEntry e in roster)
{
if (e.Bank is not { } b) continue;
py += b.Pyreals; lum += b.Luminance; lk += b.LegendaryKeys; mk += b.MythicalKeys;
ec += b.EnlightenedCoins; wec += b.WeaklyEnlightenedCoins; pc += b.PrestigeCoins;
}
return new IltBankRow("Total", false, py, lum, lk, mk, ec, wec, pc, DateTime.MinValue);
}
/// <summary>
/// The withdraw / transfer amount typed in the form: a positive whole number (commas and spaces
/// allowed), or 0 when it isn't one.
/// </summary>
public static long ParseAmount(string? text)
{
if (string.IsNullOrWhiteSpace(text)) return 0;
string digits = text.Replace(",", string.Empty).Replace(" ", string.Empty).Trim();
return long.TryParse(digits, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out long n) && n > 0 ? n : 0;
}
}

View file

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthInventory.Data;
/// <summary>
/// Storage another plugin read for us (Plugins/Shared/StorageFeed.cs): a server-side store the client
/// is never shown, e.g. Aelrynth's account vault from RynthAelrynth. Filed with the character's storage
/// like a container that was opened; RynthInventory itself knows nothing about any server's store.
/// Pure: RynthInventory.Tests covers it.
/// </summary>
internal static class ExternalStorage
{
/// <summary>The feed's record as a storage record, seen now (<paramref name="seenUtc"/>).</summary>
public static StorageRecord ToRecord(StorageFeedRecord feed, DateTime seenUtc)
{
var items = new List<ItemRecord>(feed.Items.Count);
foreach (StorageFeedItem f in feed.Items)
{
var it = new ItemRecord
{
Id = f.Id,
Wcid = f.Wcid,
Name = f.Name,
Icon = f.Icon,
Underlay = f.Underlay,
Overlay = f.Overlay,
Stack = Math.Max(1, f.Stack),
MaxStack = f.MaxStack,
ItemType = f.ItemType,
Place = ItemPlace.Storage,
};
it.Category = ItemCategory.FromItemType(it.ItemType);
items.Add(it);
}
return new StorageRecord { Id = feed.Id, Name = feed.Name, Label = feed.Label, Cell = 0, SeenUtc = seenUtc, Items = items };
}
/// <summary>A copy of <paramref name="storage"/> with <paramref name="record"/> in it (replacing the one with its id).</summary>
public static List<StorageRecord> FileInto(IReadOnlyList<StorageRecord> storage, StorageRecord record)
{
var list = new List<StorageRecord>(storage);
int i = list.FindIndex(s => s.Id == record.Id);
if (i >= 0) list[i] = record; else list.Add(record);
return list;
}
}

View file

@ -35,6 +35,13 @@ internal sealed class InventoryContext
public bool IconsAvailable;
public DateTime UtcNow;
/// <summary>RynthILT's "RynthILT.Data" (the Banking tab's balances and bank commands).</summary>
public readonly RynthCore.Plugin.Shared.RynthIltDataClient IltData = new();
/// <summary>The bank RynthILT last reported (None without RynthILT); read while the window shows.</summary>
public RynthCore.Plugin.Shared.IltBankView Bank = RynthCore.Plugin.Shared.IltBankView.None;
/// <summary>Set by the plugin: queues a bank verb with RynthILT (IltBankView.*Verb); false when refused.</summary>
public Func<string, bool> BankCommand = _ => false;
public Action RequestRescan = () => { };
public Action RequestReload = () => { };
/// <summary>Forgets a character (moves its file aside). Returns a message for the player.</summary>

View file

@ -37,7 +37,7 @@ public static unsafe class PluginExports
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion()
{
try { return LiteralPointer("0.1.0"u8); }
try { return LiteralPointer("0.1.1"u8); }
catch { return IntPtr.Zero; }
}
@ -59,8 +59,23 @@ public static unsafe class PluginExports
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
/// <summary>
/// The engine's plugin-command broker: "storage" from another plugin (StorageFeed.cs, e.g. Aelrynth's
/// account vault from RynthAelrynth). The ANSI strings are copied before returning; the payload is
/// only queued, so any thread is fine.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi)
{
try
{
string action = actionAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(actionAnsi) ?? string.Empty) : string.Empty;
if (action.Length == 0 || action.Length > 32) return;
string value = valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty;
Runtime.Plugin?.ApplyRemoteCommand(action, value);
}
catch { /* never let a managed exception cross the native boundary */ }
}
// Inventory change triggers (the scan's poll catches the rest, e.g. moves from a corpse).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]

View file

@ -39,8 +39,10 @@
</ItemGroup>
<ItemGroup>
<!-- Server signal vs a player's copy of it (VaultFeed). Also linked by RynthInventory.Tests. -->
<Compile Include="..\Shared\ChatSource.cs" Link="Shared\ChatSource.cs" />
<!-- Storage another plugin reads for us ("storage" commands: Aelrynth's vault from RynthAelrynth). Also linked by RynthInventory.Tests. -->
<Compile Include="..\Shared\StorageFeed.cs" Link="Shared\StorageFeed.cs" />
<!-- RynthILT's "RynthILT.Data" interface: the Banking tab's balances for every character on the server. -->
<Compile Include="..\Shared\RynthIltDataApi.cs" Link="Shared\RynthIltDataApi.cs" />
</ItemGroup>
</Project>

View file

@ -7,6 +7,7 @@ using RynthCore.Plugin.RynthInventory.Data;
using RynthCore.Plugin.RynthInventory.Scanning;
using RynthCore.Plugin.RynthInventory.Ui;
using RynthCore.Plugin.RynthInventory.Views;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
@ -17,7 +18,9 @@ namespace RynthCore.Plugin.RynthInventory;
/// (like Virindi Global Inventory). Each client scans the character it is logged into (a full
/// scan after login, then whenever the inventory changes, debounced) and writes one file per
/// character per server; storage the character opens (house storage, banks, vaults) is
/// recorded when it is opened. /ginv opens a window that merges every file.
/// recorded when it is opened, and storage another plugin reads for it (a server plugin's
/// server-side store, through Plugins/Shared/StorageFeed.cs) when that arrives. /ginv opens a
/// window that merges every file.
///
/// Everything runs on the plugin pump (OnTick and the events the engine drains into it)
/// except OnChatBarEnter, which the engine may call on AC's thread: it only queues the
@ -26,7 +29,14 @@ namespace RynthCore.Plugin.RynthInventory;
/// </summary>
public sealed class RynthInventoryPlugin : RynthPluginBase
{
public const string Version = "0.1.0";
// Previous release: 0.1.0. Keep in step with PluginExports.GetVersion.
public const string Version = "0.1.1";
// RynthILT's bank JSON: every BankTabReadMs on the Banking tab, every BankIdleReadMs with the
// window on another tab (so the Banking button appears on ILT worlds), never with it closed.
private const long BankTabReadMs = 2000, BankIdleReadMs = 10_000;
private long _nextBankReadMs;
private string _bankJson = string.Empty;
private const long IdentityRetryMs = 1000;
private const long AccountWaitMs = 15_000;
@ -47,10 +57,12 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
private InventoryView? _view;
private readonly ConcurrentQueue<string> _commands = new();
// The Aelrynth account vault (/mule-data), read a few seconds after login and every VaultRefreshMs.
private const long VaultFirstAskMs = 8_000, VaultRefreshMs = 10 * 60_000;
private VaultFeed? _vault;
private long _nextVaultAskMs;
// Storage other plugins read for us ("storage" plugin commands, StorageFeed.cs): queued by
// ApplyRemoteCommand (any thread), filed on the tick once the character is known. Aelrynth's
// account vault comes this way from RynthAelrynth (it was read here until 2026-10-20).
private readonly ConcurrentQueue<string> _storagePushes = new();
private const int MaxQueuedPushes = 8;
private string _lastPush = string.Empty;
private bool _identityKnown;
private long _loginMs;
@ -86,8 +98,8 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
_c.RequestRescan = () => { _scheduler.RequestFullScan(); _forceWrite = true; };
_c.RequestReload = () => { _reloadWanted = true; _files.Clear(); };
_c.Forget = ForgetCharacter;
_c.BankCommand = SendBankVerb;
_ui.Log = msg => Host.Log(msg);
_vault = new VaultFeed(text => Host.InvokeChatParser(text));
_view = new InventoryView(_c);
// No bar button of its own: opened from the engine Inventory window's GInv button, the
@ -115,17 +127,50 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
_c.LastSavedUtc = default;
_c.LastSaveError = string.Empty;
_scanner.Reset();
_vault?.Reset();
_nextVaultAskMs = 0;
CloseStorage();
_lastViewed = 0;
_lastWriteMs = 0;
_carriedIds.Clear();
_carriedPacks.Clear();
RefreshIconSupport();
ClearBank();
if (_window != null) { _window.Visible = _c.Settings.MainWindowOpen; _window.NeedsPass = true; }
}
/// <summary>Forgets the last bank read (login, logout): the next character's comes fresh.</summary>
private void ClearBank()
{
_c.Bank = Shared.IltBankView.None;
_bankJson = string.Empty;
_nextBankReadMs = 0;
}
/// <summary>The Banking tab's actions: a verb line for RynthILT, then a quick re-read for its reply.</summary>
private bool SendBankVerb(string verb)
{
long now = Environment.TickCount64;
bool ok = _c.InWorld && _c.IltData.BankCommand(Host, now, verb);
_nextBankReadMs = now + 500;
if (_window != null) _window.NeedsPass = true;
return ok;
}
/// <summary>
/// Reads RynthILT's bank JSON while the window is open (more often on the Banking tab) and
/// redraws when it changed. Reading is what tells RynthILT someone is looking.
/// </summary>
private void TickBank(long now)
{
if (!_c.InWorld || _window == null || _view == null || !_window.Visible) return;
if (now < _nextBankReadMs) return;
_nextBankReadMs = now + (_view.Tab == InventoryView.TabBanking ? BankTabReadMs : BankIdleReadMs);
string json = _c.IltData.ReadBank(Host, now);
if (string.Equals(json, _bankJson, StringComparison.Ordinal)) return;
_bankJson = json;
_c.Bank = Shared.IltBankView.Parse(json);
_window.NeedsPass = true;
}
public override void OnLogout()
{
// Last word for this character: write what it has now (also refreshes its "scanned" time).
@ -138,6 +183,9 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
_ui.SubmitEmpty(Host);
_c.Live = null;
_indexDirty = true;
ClearBank();
while (_storagePushes.TryDequeue(out _)) { } // the next character's come fresh
_lastPush = string.Empty;
}
public override void Shutdown()
@ -226,11 +274,6 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
case "keep":
KeepOpenContainer();
break;
case "vault":
if (_vault == null || !Host.HasInvokeChatParser) { _c.Print("This engine can't send commands for the plugin, so the vault can't be read."); break; }
_nextVaultAskMs = Environment.TickCount64 + VaultRefreshMs;
_c.Print(_vault.Ask(Environment.TickCount64, force: true) ? "Reading the vault (/mule-data)..." : "The vault is already being read: " + _vault.Describe());
break;
case "reload":
_reloadWanted = true;
_files.Clear();
@ -239,9 +282,16 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
case "status":
PrintStatus();
break;
case "bank":
case "banking":
// The Banking tab: every character's Infinite Leaftide bank (RynthILT's data). Shows, never toggles off.
_view?.ShowBanking();
_nextBankReadMs = 0;
if (_window != null) { _window.Visible = true; _window.NeedsPass = true; }
break;
case "help":
case "?":
_c.Print("/ginv (window), /ginv <text> (search), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv vault (read the Aelrynth account vault now), /ginv reload, /ginv status");
_c.Print("/ginv (window), /ginv <text> (search), /ginv bank (every character's Infinite Leaftide bank), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv reload, /ginv status");
break;
default:
_view?.SetSearch(arg);
@ -261,7 +311,7 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
int items = _c.Live?.Items.Count ?? 0, storage = _c.Live?.Storage.Count ?? 0;
string saved = _c.LastSavedUtc == default ? "not saved yet" : "saved " + InventoryIndex.Age(_c.LastSavedUtc, DateTime.UtcNow);
_c.Print($"{who}: {items} items carried, {storage} storage container(s), {saved}. {_c.Index?.Characters.Count ?? 0} characters in {_c.Store.Root}.");
if (_vault != null) _c.Print("Aelrynth vault: " + _vault.Describe() + ".");
if (_lastPush.Length > 0) _c.Print("From other plugins: " + _lastPush + ".");
if (_c.LastSaveError.Length > 0) _c.Print("Last save failed: " + _c.LastSaveError);
}
@ -309,6 +359,7 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
}
TickWrite(now);
TickIndex(now);
TickBank(now);
if (!Host.HasUi || _window == null || _view == null) return;
Record(_window, now, 2000, _view.Draw);
@ -345,48 +396,42 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
if (_openStorage != 0 && now >= _nextStorageScanMs)
ScanStorage(now, final: false);
TickVault(now);
TickStoragePushes(now);
}
// ── The account vault ───────────────────────────────────────────────────
// ── Storage from other plugins ──────────────────────────────────────────
/// <summary>
/// Asks the server for the vault after login and now and then, and files what comes back with the
/// character's storage (one record, the same id on every character of the account).
/// RynthPluginApplyRemoteCommand: "storage" (StorageFeed.Action) carries a whole store another
/// plugin read. Any thread: the payload is only queued (the newest few).
/// </summary>
private void TickVault(long now)
internal void ApplyRemoteCommand(string action, string value)
{
VaultFeed? v = _vault;
if (v == null || _c.Live == null || !Host.HasInvokeChatParser) return;
if (_nextVaultAskMs == 0) _nextVaultAskMs = now + VaultFirstAskMs;
else if (now >= _nextVaultAskMs && v.Status != VaultFeed.State.Unsupported)
{
_nextVaultAskMs = now + VaultRefreshMs;
v.Ask(now);
}
v.Tick(now, _c.Account);
if (v.TakeChanged() && v.Record != null) FileVault(v.Record, now);
if (!action.Equals(StorageFeed.Action, StringComparison.OrdinalIgnoreCase) || value.Length == 0 || value.Length > StorageFeed.MaxJsonLength) return;
_storagePushes.Enqueue(value);
while (_storagePushes.Count > MaxQueuedPushes && _storagePushes.TryDequeue(out _)) { }
}
private void FileVault(StorageRecord vault, long now)
/// <summary>Files what other plugins sent, once the character (and so its storage) is known. Plugin tick.</summary>
private void TickStoragePushes(long now)
{
if (_c.Live == null) return;
var storage = new List<StorageRecord>(_c.Live.Storage);
int i = storage.FindIndex(s => s.Id == vault.Id);
if (i >= 0) storage[i] = vault; else storage.Add(vault);
CharacterSnapshot snap = NewSnapshot(_c.Live.Items, storage);
snap.ScannedUtc = _c.Live.ScannedUtc;
_c.Live = snap;
_indexDirty = true;
_scheduler.ContentChanged(now, snap.ContentHash());
}
// May run on AC's thread: the feed only queues.
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
if (eat == 0 && _vault != null && _vault.ShouldEat(text, chatType)) eat = 1;
while (_storagePushes.TryDequeue(out string? json))
{
StorageFeedRecord? feed = StorageFeed.Parse(json, out string error);
if (feed == null)
{
Host.Log("[RynthInventory] storage from another plugin refused: " + error);
continue;
}
StorageRecord record = ExternalStorage.ToRecord(feed, DateTime.UtcNow);
CharacterSnapshot snap = NewSnapshot(_c.Live.Items, ExternalStorage.FileInto(_c.Live.Storage, record));
snap.ScannedUtc = _c.Live.ScannedUtc;
_c.Live = snap;
_indexDirty = true;
_scheduler.ContentChanged(now, snap.ContentHash());
_lastPush = $"{record.Label} ({record.Items.Count} item(s)) at {DateTime.Now:HH:mm}";
}
}
private void StartCharacter(long now, uint player, string server, string account, string character)

View file

@ -0,0 +1,237 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using RynthCore.Plugin.RynthInventory.Data;
using RynthCore.Plugin.RynthInventory.Ui;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthInventory.Views;
/// <summary>
/// Banking: the Infinite Leaftide bank of every character on this server (the Mini Remote's Banking
/// tab moved here 2026-10-13). Balances, form choices and the last reply come from RynthILT's
/// "RynthILT.Data" bank JSON; the character list adds the inventory's characters on the same server
/// (BankRoster). Deposits, withdrawals, transfers and balance reads go back to RynthILT as verb lines;
/// a transfer is confirmed here first (RynthILT doesn't ask again).
/// </summary>
internal sealed partial class InventoryView
{
private const int MaxTransactionsShown = 20;
private const float ColPyreals = 150f, ColLum = 270f, ColKeys = 380f, ColCoins = 450f, ColUpdated = 560f;
private int _depositIndex, _withdrawIndex, _withdrawNote, _transferIndex, _transferNote;
private string _withdrawAmount = string.Empty, _transferAmount = string.Empty, _transferTo = string.Empty;
/// <summary>The transfer waiting for "Yes, send": its verb line and the sentence shown.</summary>
private (string Verb, string Text)? _confirmTransfer;
private string _bankMessage = string.Empty;
/// <summary>
/// The Banking tab button shows when RynthILT answered on an ILT world, or when the tab was asked
/// for (/ginv bank) so it can say what is missing.
/// </summary>
private bool BankingShown => Tab == TabBanking || (_c.Bank.Loaded && _c.Bank.Available);
/// <summary>Opens on the Banking tab ("/ginv bank", RynthAi's and RynthILT's bank links).</summary>
public void ShowBanking()
{
Tab = TabBanking;
_confirmTransfer = null;
}
private void DrawBanking(UiWindow w)
{
IltBankView b = _c.Bank;
if (!b.Loaded)
{
w.TextDisabled("The bank comes from RynthILT (Infinite Leaftide). Load RynthILT to see every character's bank here.");
return;
}
if (!b.Available)
{
w.TextDisabled("This isn't an Infinite Leaftide world, so there is no bank to show.");
return;
}
w.Text($"Bank on {(b.World.Length > 0 ? b.World : "this server")}");
w.SameLine();
w.SmallButton("Refresh", "b.refresh", () => SendBank(IltBankView.RefreshVerb(), "Reading the balance..."));
w.Tooltip("A quiet /bank balance read for the character you're on (other characters update when they log in).");
if (b.Enabled == 0) w.TextColored(UiColors.Red, "This server has no /bank command.");
else if (b.Enabled < 0) w.TextDisabled("Whether this server has /bank isn't known yet.");
if (b.Result.Length > 0) w.TextColored(UiColors.Gold, b.Result);
if (_bankMessage.Length > 0) w.TextColored(UiColors.Yellow, _bankMessage);
List<BankRosterEntry> roster = BankRoster.Build(b, _c.Index);
DrawBankTable(w, roster);
if (b.Enabled != 0)
{
DrawDeposit(w, b);
DrawWithdraw(w, b);
DrawTransfer(w, b, roster);
}
DrawTransactions(w, b);
}
private void DrawBankTable(UiWindow w, List<BankRosterEntry> roster)
{
w.SeparatorText($"Characters ({roster.Count})");
w.TextDisabled("Character");
w.SameLine(ColPyreals); w.TextDisabled("Pyreals");
w.SameLine(ColLum); w.TextDisabled("Luminance");
w.SameLine(ColKeys); w.TextDisabled("Keys L/M");
w.SameLine(ColCoins); w.TextDisabled("Coins E/W/P");
w.SameLine(ColUpdated); w.TextDisabled("Updated");
foreach (BankRosterEntry e in roster)
{
string name = e.Current ? e.Name + " (you)" : e.Name;
if (e.Bank is { } r)
{
w.Text(name);
if (e.Account.Length > 0) w.Tooltip("Account: " + e.Account);
BankCells(w, r);
w.SameLine(ColUpdated);
w.TextDisabled(r.UpdatedUtc == DateTime.MinValue ? "-" : InventoryIndex.Age(r.UpdatedUtc, _c.UtcNow));
}
else
{
w.TextDisabled(name);
if (e.Account.Length > 0) w.Tooltip("Account: " + e.Account);
w.SameLine(ColPyreals);
w.TextDisabled("not read yet: log in with RynthILT loaded");
}
}
if (roster.Count == 0) w.TextDisabled("No characters on this server yet.");
else
{
w.TextColored(UiColors.Gold, "Total");
BankCells(w, BankRoster.Totals(roster));
}
}
/// <summary>The balance columns of one row (Pyreals .. Coins).</summary>
private static void BankCells(UiWindow w, IltBankRow r)
{
w.SameLine(ColPyreals); w.Text(N(r.Pyreals));
w.SameLine(ColLum); w.Text(N(r.Luminance));
w.SameLine(ColKeys); w.Text($"{N(r.LegendaryKeys)}/{N(r.MythicalKeys)}");
w.SameLine(ColCoins); w.Text($"{N(r.EnlightenedCoins)}/{N(r.WeaklyEnlightenedCoins)}/{N(r.PrestigeCoins)}");
}
private void DrawDeposit(UiWindow w, IltBankView b)
{
if (b.Deposits.Count == 0) return;
w.SeparatorText("Deposit");
_depositIndex = Math.Clamp(_depositIndex, 0, b.Deposits.Count - 1);
w.Combo("What", "b.dep.what", _depositIndex, b.Deposits, i => _depositIndex = i);
w.SameLine();
int di = _depositIndex;
string label = b.Deposits[di];
w.SmallButton("Deposit", "b.dep.go", () => SendBank(IltBankView.DepositVerb(di), "Depositing " + label + "..."));
}
private void DrawWithdraw(UiWindow w, IltBankView b)
{
if (b.Withdrawals.Count == 0) return;
w.SeparatorText("Withdraw");
_withdrawIndex = Math.Clamp(_withdrawIndex, 0, b.Withdrawals.Count - 1);
w.Combo("Currency", "b.wd.what", _withdrawIndex, Labels(b.Withdrawals), i => _withdrawIndex = i);
IltBankChoice choice = b.Withdrawals[_withdrawIndex];
w.InputText(choice.Notes ? "Notes" : "Amount", "b.wd.amt", _withdrawAmount, 20, v => _withdrawAmount = v);
int note = NoteCombo(w, b, choice, "b.wd.note", _withdrawNote, i => _withdrawNote = i);
w.SameLine();
int wi = _withdrawIndex;
w.SmallButton("Withdraw", "b.wd.go", () =>
{
long amount = BankRoster.ParseAmount(_withdrawAmount);
if (amount <= 0) { _bankMessage = "Type a whole number to withdraw."; return; }
SendBank(IltBankView.WithdrawVerb(wi, amount, note), $"Withdrawing {N(amount)} {choice.Label}...");
});
}
private void DrawTransfer(UiWindow w, IltBankView b, List<BankRosterEntry> roster)
{
if (b.Transfers.Count == 0) return;
w.SeparatorText("Transfer");
_transferIndex = Math.Clamp(_transferIndex, 0, b.Transfers.Count - 1);
w.Combo("Currency", "b.tx.what", _transferIndex, Labels(b.Transfers), i => { _transferIndex = i; _confirmTransfer = null; });
IltBankChoice choice = b.Transfers[_transferIndex];
w.InputText(choice.Notes ? "Notes" : "Amount", "b.tx.amt", _transferAmount, 20, v => { _transferAmount = v; _confirmTransfer = null; });
int note = NoteCombo(w, b, choice, "b.tx.note", _transferNote, i => { _transferNote = i; _confirmTransfer = null; });
w.InputText("To", "b.tx.to", _transferTo, 40, v => { _transferTo = v; _confirmTransfer = null; });
// The other characters on this server, to fill "To" with one click.
var others = new List<string> { "Pick a character..." };
foreach (BankRosterEntry e in roster) if (!e.Current) others.Add(e.Name);
if (others.Count > 1)
{
w.SameLine();
w.Combo("##pick", "b.tx.pick", 0, others, i => { if (i > 0 && i < others.Count) { _transferTo = others[i]; _confirmTransfer = null; } });
}
if (_confirmTransfer is { } pending)
{
w.TextColored(UiColors.Red, pending.Text);
w.SmallButton("Yes, send", "b.tx.yes", () =>
{
_confirmTransfer = null;
SendBank(pending.Verb, "Transfer sent...");
});
w.SameLine();
w.SmallButton("Cancel", "b.tx.no", () => _confirmTransfer = null);
return;
}
int ti = _transferIndex;
w.SmallButton("Transfer...", "b.tx.go", () =>
{
long amount = BankRoster.ParseAmount(_transferAmount);
string to = (_transferTo ?? string.Empty).Trim();
if (amount <= 0) { _bankMessage = "Type a whole number to transfer."; return; }
if (to.Length == 0) { _bankMessage = "Type (or pick) who gets the transfer."; return; }
string what = choice.Notes && note < b.Notes.Count ? $"{N(amount)} x {b.Notes[note].Label}" : $"{N(amount)} {choice.Label}";
_confirmTransfer = (IltBankView.TransferVerb(ti, amount, note, to), $"Send {what} to {to}? This can't be undone.");
_bankMessage = string.Empty;
});
}
/// <summary>
/// The trade-note combo for a choice that counts notes; returns the note index in use (0 when
/// the choice isn't notes). A pick arrives as an event and lands in <paramref name="set"/>.
/// </summary>
private static int NoteCombo(UiWindow w, IltBankView b, IltBankChoice choice, string id, int index, Action<int> set)
{
if (!choice.Notes || b.Notes.Count == 0) return 0;
var labels = new List<string>(b.Notes.Count);
foreach (IltBankNote n in b.Notes) labels.Add($"{n.Label} ({N(n.Value)} pyreals)");
index = Math.Clamp(index, 0, b.Notes.Count - 1);
w.Combo("Note", id, index, labels, set);
return index;
}
private void DrawTransactions(UiWindow w, IltBankView b)
{
if (b.Transactions.Count == 0) return;
if (!w.CollapsingHeader($"Recent transfers ({b.Transactions.Count})", "b.txlog")) return;
int shown = 0;
foreach (IltBankTx t in b.Transactions)
{
if (shown++ >= MaxTransactionsShown) { w.TextDisabled($"...and {b.Transactions.Count - MaxTransactionsShown} more."); break; }
string dir = t.Type.Length > 0 ? t.Type : "?";
w.Text($"{t.When} {dir} {N(t.Amount)} {t.Currency}{(t.Player.Length > 0 ? " - " + t.Player : "")}");
}
}
/// <summary>Hands a verb to RynthILT; says so when it was refused.</summary>
private void SendBank(string verb, string sending)
{
_bankMessage = _c.BankCommand(verb) ? sending : "RynthILT didn't take that (is it loaded, and are you logged in?).";
}
private static List<string> Labels(IReadOnlyList<IltBankChoice> choices)
{
var list = new List<string>(choices.Count);
foreach (IltBankChoice c in choices) list.Add(c.Label);
return list;
}
private static string N(long n) => n.ToString("N0", CultureInfo.InvariantCulture);
}

View file

@ -8,12 +8,12 @@ namespace RynthCore.Plugin.RynthInventory.Views;
/// <summary>
/// The Global Inventory window: a search page (every character on every server, filters,
/// totals, results, details) and a characters page (snapshot ages, forget). Recorded on the
/// pump thread, replayed by the engine.
/// totals, results, details), a characters page (snapshot ages, forget) and, with RynthILT, a
/// Banking page (Views\BankingTab.cs). Recorded on the pump thread, replayed by the engine.
/// </summary>
internal sealed class InventoryView
internal sealed partial class InventoryView
{
public const int TabSearch = 0, TabCharacters = 1;
public const int TabSearch = 0, TabCharacters = 1, TabBanking = 2;
private const int PageSize = 100;
private const float RowIcon = 18f, DetailIcon = 32f, DetailsHeight = 190f;
@ -58,10 +58,21 @@ internal sealed class InventoryView
w.SameLine();
int chars = _c.Index?.Characters.Count ?? 0;
w.ToggleButton($"Characters ({chars})", "tab.chars", Tab == TabCharacters, () => Tab = TabCharacters, small: true);
if (BankingShown)
{
w.SameLine();
w.ToggleButton("Banking", "tab.bank", Tab == TabBanking, () => Tab = TabBanking, small: true);
}
w.SameLine();
w.TextDisabled(StatusLine());
w.Separator();
// The bank comes from RynthILT, not the inventory files: it draws before they are read.
if (Tab == TabBanking)
{
DrawBanking(w);
return;
}
if (_c.Index == null)
{
w.TextDisabled(_c.Loading ? "Reading the inventory files..." : "No inventory read yet.");
@ -222,6 +233,17 @@ internal sealed class InventoryView
private void Select(string key) => _selectedKey = _selectedKey == key ? null : key;
/// <summary>
/// Clicking one of the logged-in character's own items also selects it in the game (the bag and
/// the selection panel), as clicking it in the pack would. Another character's item can't be.
/// A problem report asked for this (R-20261016-213300-1737).
/// </summary>
private void SelectInGame(InventoryRow? r)
{
if (r == null || !r.Owner.IsCurrentCharacter || r.Item.Id == 0 || !_c.Host.HasSelectItem) return;
_c.Host.SelectItem(r.Item.Id);
}
private void DrawRow(UiWindow w, InventoryRow r)
{
ItemRecord it = r.Item;
@ -234,7 +256,7 @@ internal sealed class InventoryView
string key = RowKey(r);
uint? color = !r.Owner.IsCurrentServer ? UiColors.OtherServer : IsStale(r.SeenUtc) ? UiColors.Stale : null;
if (color != null) w.PushStyleColor(UiFormat.ColText, color.Value);
w.Selectable(label, "r." + key, _selectedKey == key, () => Select(key), 0f, icons ? RowIcon : 0f);
w.Selectable(label, "r." + key, _selectedKey == key, () => { Select(key); SelectInGame(r); }, 0f, icons ? RowIcon : 0f);
if (color != null) w.PopStyleColor();
}
@ -245,7 +267,9 @@ internal sealed class InventoryView
string label = $"{t.Name} x{t.Count.ToString("N0", CultureInfo.InvariantCulture)} - {t.Characters} character{(t.Characters == 1 ? "" : "s")}";
if (t.Servers > 1) label += $", {t.Servers} servers";
string key = GroupKey(t);
w.Selectable(label, "g." + key, _selectedKey == key, () => Select(key), 0f, icons ? RowIcon : 0f);
// A total across characters: select the logged-in character's own stack, if it has one.
w.Selectable(label, "g." + key, _selectedKey == key,
() => { Select(key); SelectInGame(t.Holders.Find(h => h.Owner.IsCurrentCharacter)); }, 0f, icons ? RowIcon : 0f);
}
/// <summary>

Some files were not shown because too many files have changed in this diff Show more