RynthSuite as of 2026-11-12 (internal b899791): release 2026.11.12.1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-11-12 19:56:37 -05:00
commit b48c49f76e
110 changed files with 12476 additions and 340 deletions

View file

@ -0,0 +1,252 @@
// ============================================================================
// RynthAi - ActiveGear/ActiveGearWindow.cs
// The Active Gear window: one row per worn item with spells (slot, whether its
// magic is on, its mana, the time its mana lasts, its spells on hover), the
// summary line, and Check items (identify the worn items again). RynthCore
// hosts the window (the sections manifest's "activegear" window, plugin API
// v89: header, pop-out, resize, remembered place; no bar button) and calls
// Draw through RynthPluginRenderEmbed.
//
// AC's render thread: it reads the view the tick published (RynthAiPlugin.
// ActiveGear.cs) and queues Check items for the tick. Looks: Shared/RynthUi.
// ============================================================================
using System;
using System.Globalization;
using System.Numerics;
using System.Text;
using ImGuiNET;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthAi.ActiveGear;
/// <summary>One worn item in the view.</summary>
internal sealed record ActiveGearRow(int Id, GearFacts Facts, GearVerdict Verdict, string SlotName, string[] SpellNames);
/// <summary>What the window shows (immutable; the tick publishes a new one about every second while it shows).</summary>
internal sealed record ActiveGearView(ActiveGearRow[] Rows, string Summary, bool InWorld, bool EnchantmentsReadable,
int CheckDone, int CheckTotal, bool CanCheck)
{
public static readonly ActiveGearView Empty = new(Array.Empty<ActiveGearRow>(), string.Empty, false, false, -1, 0, false);
/// <summary>Check items is still sending.</summary>
public bool Checking => CheckDone >= 0;
}
/// <summary>The words for a row: the window's cells and /ra gear list's lines. Pure.</summary>
internal static class ActiveGearText
{
public static string Mana(ActiveGearRow r) =>
!r.Facts.Identified ? "?"
: r.Facts.MaxMana is int max && max > 0
? $"{(r.Facts.CurMana is int c ? c.ToString("N0", CultureInfo.InvariantCulture) : "?")} / {max.ToString("N0", CultureInfo.InvariantCulture)}"
: "-";
public static string TimeLeft(ActiveGearRow r) =>
!r.Facts.Identified ? "?" : GearActivation.TimeText(r.Verdict.SecondsLeft);
public static string Spells(ActiveGearRow r) =>
!r.Facts.Identified ? "?"
: r.SpellNames.Length == 0 ? "-"
: $"{r.Verdict.SpellsOn}/{r.SpellNames.Length} on";
/// <summary>The hover list: each spell, on or not.</summary>
public static string SpellList(ActiveGearRow r)
{
if (r.SpellNames.Length == 0) return r.Facts.Identified ? "No spells read." : "Not identified yet: Check items reads its spells.";
var sb = new StringBuilder();
for (int i = 0; i < r.SpellNames.Length; i++)
{
bool on = i < r.Verdict.SpellOn.Count && r.Verdict.SpellOn[i];
if (i > 0) sb.Append('\n');
sb.Append(on ? "on " : "-- ").Append(r.SpellNames[i]);
}
return sb.ToString();
}
/// <summary>"Left Ring, Ring of X: Yes, mana 1,234 / 4,000, 3 h 5 min left, 2/2 spells on" (/ra gear list).</summary>
public static string ListLine(ActiveGearRow r)
{
var sb = new StringBuilder();
sb.Append(r.SlotName).Append(", ").Append(r.Facts.Name.Length > 0 ? r.Facts.Name : "(no name)").Append(": ")
.Append(GearActivation.ActiveText(r.Verdict.Active));
if (r.Verdict.Reason.Length > 0) sb.Append(" (").Append(r.Verdict.Reason).Append(')');
if (r.Facts.Identified)
{
string mana = Mana(r);
if (mana != "-") sb.Append(", mana ").Append(mana);
if (r.Verdict.SecondsLeft is double) sb.Append(", ").Append(TimeLeft(r)).Append(" left");
if (r.SpellNames.Length > 0) sb.Append(", ").Append(r.Verdict.SpellsOn).Append('/').Append(r.SpellNames.Length).Append(" spells on");
}
return sb.ToString();
}
}
internal sealed class ActiveGearWindow
{
private readonly Action _check;
private float _k = 1f;
private float Px(float v) => v * _k;
private const string HelpText =
"Your worn items that have spells, like MagTools' mana tracker.\n\n" +
"Active: Yes when one of its spells is on you (an item's spell on its wearer never runs out) or on the item " +
"itself (its appraisal lists that). No when it is out of mana, you lack the Arcane Lore or the skill it needs, " +
"or a recent appraisal shows none of its spells on. ? when that can't be told yet: not identified, or identified " +
"before you put it on.\n\n" +
"Mana and time left come from the item's last appraisal (the server doesn't send mana as it burns): the time " +
"left is its mana over its mana rate, less the time since it was identified. An estimate.\n\n" +
"Check items identifies each worn item again, one every 1.5 s, so the reads are fresh.\n\n" +
"/ra gear prints the summary in chat and opens this window; /ra gear list prints each item.";
public ActiveGearWindow(Action check) => _check = check;
/// <summary>Draws the window body into the current ImGui window and returns the size it would like. Render thread.</summary>
public Vector2 Draw(ActiveGearView view)
{
_k = Math.Max(0.5f, Font(RynthUiFont.Ui11).FontSize / 11f);
Vector2 origin = ImGui.GetCursorScreenPos();
Vector2 size = ImGui.GetContentRegionAvail();
var want = new Vector2(Px(640), Px(320));
if (size.X < 60 || size.Y < 40) return want;
ImDrawListPtr frame = ImGui.GetWindowDrawList();
frame.AddRectFilled(origin, origin + size, Background, 4);
using (PushFont(RynthUiFont.Ui11))
{
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4));
ImGui.SetCursorScreenPos(origin + new Vector2(6, 6));
ImGui.Indent(6);
float w = size.X - 12;
DrawTop(view, w);
// The host's resize grip sits over the bottom-right corner: the rows end above it.
float bodyH = Math.Max(Px(30), origin.Y + size.Y - 6 - ImGui.GetCursorScreenPos().Y - Px(10));
DrawTable(view, new Vector2(w, bodyH));
ImGui.Unindent(6);
ImGui.PopStyleVar();
}
frame.AddRect(origin, origin + size, Border, 4);
return want;
}
private void DrawTop(ActiveGearView view, float w)
{
Vector2 start = ImGui.GetCursorScreenPos();
float h = Px(20), iconW = Px(22);
const string checkLabel = "Check items";
float checkW = ButtonWidth(checkLabel);
float textW = Math.Max(10, w - checkW - iconW - Px(10));
string status = !view.InWorld ? "Active gear shows once you are in the world."
: view.Summary.Length > 0 ? view.Summary : "Reading your gear...";
ImGui.PushTextWrapPos(start.X + textW);
Label(status, view.Rows.Length > 0 ? Text : Mute);
ImGui.PopTextWrapPos();
float textBottom = ImGui.GetCursorScreenPos().Y;
float x = start.X + w - iconW - checkW - Px(4);
if (Button("##ag_check", checkLabel, new Vector2(x, start.Y), new Vector2(checkW, h), Text, ButtonFill,
enabled: view.InWorld && view.CanCheck && !view.Checking))
_check();
ImGui.SetItemTooltip(view.Checking
? $"Identifying: {view.CheckDone} of {view.CheckTotal} asked so far."
: "Identify each worn item again (one every 1.5 s) so its mana and spells are fresh (/ra gear check).");
x += checkW + Px(4);
IconButton("##ag_help", RynthIcons.Info, new Vector2(x, start.Y), new Vector2(iconW, h), Mute, ButtonFill, font: RynthUiFont.Ui11);
if (ImGui.IsItemHovered())
{
ImGui.BeginTooltip();
ImGui.PushTextWrapPos(ImGui.GetFontSize() * 32);
ImGui.TextUnformatted(HelpText);
ImGui.PopTextWrapPos();
ImGui.EndTooltip();
}
ImGui.SetCursorScreenPos(new Vector2(start.X, Math.Max(textBottom, start.Y + h + Px(4))));
if (view.Checking)
Label($"Identifying worn items: {view.CheckDone} of {view.CheckTotal} asked...", Mute);
else if (view.InWorld && !view.EnchantmentsReadable)
Label("Your enchantments can't be read yet, so only mana and requirements are judged.", Highlight);
ImGui.Dummy(Vector2.Zero);
}
private static readonly (string Head, string Tip)[] Columns =
{
("Item", "The item's name."),
("Slot", "Where it is worn."),
("Active", "Yes, No, or ? (hover a cell for the reason)."),
("Mana", "Its mana and its most, from its last appraisal."),
("Time left", "How long its mana lasts at its rate: an estimate from the last appraisal."),
("Spells", "Its spells that are on, of all it has (hover for the list)."),
};
private void DrawTable(ActiveGearView view, Vector2 size)
{
if (view.InWorld && view.Rows.Length == 0)
{
Label("No worn items with spells.", Mute);
return;
}
var flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.ScrollY;
ImGui.PushStyleColor(ImGuiCol.TableRowBgAlt, RowAlt);
ImGui.PushStyleVar(ImGuiStyleVar.CellPadding, new Vector2(Px(5), Px(2)));
if (ImGui.BeginTable("##ag_rows", Columns.Length, flags, size))
{
ImGui.TableSetupScrollFreeze(0, 1);
ImGui.TableSetupColumn(Columns[0].Head, ImGuiTableColumnFlags.WidthStretch, 2.4f);
ImGui.TableSetupColumn(Columns[1].Head, ImGuiTableColumnFlags.WidthStretch, 1.0f);
ImGui.TableSetupColumn(Columns[2].Head, ImGuiTableColumnFlags.WidthStretch, 0.6f);
ImGui.TableSetupColumn(Columns[3].Head, ImGuiTableColumnFlags.WidthStretch, 1.1f);
ImGui.TableSetupColumn(Columns[4].Head, ImGuiTableColumnFlags.WidthStretch, 0.9f);
ImGui.TableSetupColumn(Columns[5].Head, ImGuiTableColumnFlags.WidthStretch, 0.7f);
ImGui.TableNextRow(ImGuiTableRowFlags.Headers);
for (int c = 0; c < Columns.Length; c++)
{
ImGui.TableSetColumnIndex(c);
Label(Columns[c].Head, Mute);
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(Columns[c].Tip);
}
foreach (ActiveGearRow r in view.Rows)
{
ImGui.PushID(r.Id);
ImGui.TableNextRow();
ImGui.TableNextColumn();
Label(r.Facts.Name.Length > 0 ? r.Facts.Name : "(no name)", Text);
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(RowTip(r));
ImGui.TableNextColumn();
Label(r.SlotName, Mute);
ImGui.TableNextColumn();
Label(GearActivation.ActiveText(r.Verdict.Active), r.Verdict.Active switch
{
GearActive.Yes => Green,
GearActive.No => Red,
_ => Highlight,
});
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(RowTip(r));
ImGui.TableNextColumn();
Label(ActiveGearText.Mana(r), r.Verdict.ManaPercent is int p && p < 25 ? Highlight : Text);
ImGui.TableNextColumn();
string left = ActiveGearText.TimeLeft(r);
Label(left, left is "-" or "?" ? Faded(Mute) : r.Verdict.SecondsLeft is double s && s < 30 * 60 ? Highlight : Text);
ImGui.TableNextColumn();
Label(ActiveGearText.Spells(r), Text);
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(ActiveGearText.SpellList(r));
ImGui.PopID();
}
ImGui.EndTable();
}
ImGui.PopStyleVar();
ImGui.PopStyleColor();
}
/// <summary>The hover on a row's name and Active cell: the verdict and why, then its spells.</summary>
private static string RowTip(ActiveGearRow r)
{
string head = r.Verdict.Active switch
{
GearActive.Yes => "Active",
GearActive.No => "Not active",
_ => "Can't tell yet",
};
if (r.Verdict.Reason.Length > 0) head += ": " + r.Verdict.Reason;
return head + "\n\n" + ActiveGearText.SpellList(r);
}
}

View file

@ -0,0 +1,314 @@
// ============================================================================
// RynthAi - ActiveGear/GearActivation.cs
// Is a worn item's magic on, and how long its mana lasts: the logic behind the
// Active Gear window and /ra gear (RynthAiPlugin.ActiveGear.cs), MagTools'
// mana tracker in RynthAi.
//
// An item's spells turn on once it is wielded and the wearer meets its
// requirements (Arcane Lore for its difficulty, an activation skill), while it
// has mana. Two places show that they are on:
// * the player's enchantments: a spell an item casts on its wearer is an
// enchantment with no end time (the engine reads it as double.MaxValue);
// a buff the player cast has an end time;
// * the item's appraisal: its spell book lists the enchantments on the item
// itself with bit 31 set (the client's "Enchantments:" list), which is
// where the item's own spells go (armor's Impenetrability, a weapon's
// Blood Drinker). That list is as old as the last appraisal.
// The engine doesn't say which item cast an enchantment (its caster field is
// not read), so a wearer spell is matched by spell id.
//
// Mana: CurrentMana and MaxMana come from the last appraisal too, and the
// server sends no change while gear burns mana, so the time left is worked out
// from the read's age: current / |ManaRate| seconds (ManaRate, float 5, is the
// mana per second, negative), less the seconds since the appraisal.
//
// Pure (System only): linked into Tools/RynthCore.RynthAiTests.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace RynthCore.Plugin.RynthAi.ActiveGear;
/// <summary>Whether an item's magic is on.</summary>
internal enum GearActive { Unknown, Yes, No }
/// <summary>What is known about one worn item (read from the engine by RynthAiPlugin.ActiveGear.cs).</summary>
internal sealed record GearFacts
{
public string Name { get; init; } = string.Empty;
/// <summary>Where it is worn (EquipMask bits).</summary>
public int Slot { get; init; }
/// <summary>The item has appraisal data (it was identified at some point).</summary>
public bool Identified { get; init; }
/// <summary>The appraisal's spell book as read: bit 31 set = an enchantment on the item itself.</summary>
public IReadOnlyList<uint> RawSpellIds { get; init; } = Array.Empty<uint>();
public int? CurMana { get; init; }
public int? MaxMana { get; init; }
/// <summary>ManaRate (float 5): mana per second, negative while it burns; null = not read.</summary>
public double? ManaRate { get; init; }
/// <summary>Seconds since the appraisal the reads come from; null = unknown.</summary>
public double? ReadAgeSeconds { get; init; }
/// <summary>Seconds since the item was first seen worn this session; null = unknown.</summary>
public double? WornForSeconds { get; init; }
/// <summary>The player's enchantments could be read (the list below is real, even if empty).</summary>
public bool EnchantmentsReadable { get; init; }
/// <summary>Spell ids on the player with no end time (cast by worn items).</summary>
public IReadOnlyCollection<int> PlayerItemSpells { get; init; } = Array.Empty<int>();
/// <summary>ItemDifficulty (int 109): the Arcane Lore it needs; 0 = none.</summary>
public int ArcaneLoreNeeded { get; init; }
/// <summary>The player's Arcane Lore (buffed); null = not read.</summary>
public int? ArcaneLore { get; init; }
/// <summary>The activation skill's name ("Heavy Weapons"), its level (int 115; 0 = none) and the player's level of it.</summary>
public string ActivationSkillName { get; init; } = string.Empty;
public int ActivationLevel { get; init; }
public int? ActivationSkill { get; init; }
/// <summary>ProcSpell (data id 55): the spell it casts when it triggers; 0 = none or not read.</summary>
public int ProcSpellId { get; init; }
}
/// <summary>The answer for one item.</summary>
internal sealed record GearVerdict(
GearActive Active,
string Reason,
IReadOnlyList<int> SpellIds,
IReadOnlyList<bool> SpellOn,
double? SecondsLeft,
int? ManaPercent)
{
public int SpellsOn
{
get { int n = 0; foreach (bool b in SpellOn) if (b) n++; return n; }
}
}
internal static class GearActivation
{
/// <summary>Bit 31 of an appraisal spell id: an enchantment on the item itself.</summary>
public const uint ActiveOnItemBit = 0x80000000u;
/// <summary>An enchantment ending this late has no end (the engine reads "no end" as double.MaxValue).</summary>
public static bool IsEndless(double expiry) => double.IsInfinity(expiry) || expiry >= double.MaxValue / 2;
/// <summary>The ammunition slot: arrows and bolts carry no spells.</summary>
public const int AmmoSlot = 0x00800000;
/// <summary>
/// True when the item belongs in the list: not identified yet (it may have spells), or it has spells
/// or mana. Never ammunition.
/// </summary>
public static bool Listed(GearFacts f) =>
f.Slot != AmmoSlot && (!f.Identified || BaseSpells(f.RawSpellIds).Count > 0 || f.MaxMana is > 0);
/// <summary>The item's own spells (bit 31 stripped, each once, in order) and which carry the on-the-item bit.</summary>
public static List<int> BaseSpells(IReadOnlyList<uint> raw) => BaseSpells(raw, out _);
private static List<int> BaseSpells(IReadOnlyList<uint> raw, out HashSet<int> onItem)
{
onItem = new HashSet<int>();
var own = new List<int>();
var seen = new HashSet<int>();
foreach (uint r in raw)
{
int id = unchecked((int)(r & ~ActiveOnItemBit));
if (id == 0) continue;
if ((r & ActiveOnItemBit) != 0) onItem.Add(id);
else if (seen.Add(id)) own.Add(id);
}
// An enchantment someone cast on the item (not one of its own spells) isn't listed;
// only when the book has nothing but marked ids do those stand for its spells.
if (own.Count == 0)
foreach (int id in onItem)
if (seen.Add(id)) own.Add(id);
return own;
}
/// <summary>
/// Seconds of mana left: current / |rate|, less the read's age, never below 0. Null without a
/// current mana or a burning rate.
/// </summary>
public static double? SecondsLeft(int? curMana, double? manaRate, double? readAgeSeconds)
{
if (curMana is not int cur || manaRate is not double rate) return null;
if (double.IsNaN(rate) || rate == 0) return null;
double left = cur / Math.Abs(rate) - Math.Max(0, readAgeSeconds ?? 0);
return Math.Max(0, left);
}
/// <summary>The cloak slot and the three aetheria slots: their one spell is a proc.</summary>
public const int ProcSlots = 0x08000000 | 0x10000000 | 0x20000000 | 0x40000000;
/// <summary>
/// The item's proc spell: ProcSpell when read, else a cloak's or aetheria's only spell (the server
/// puts ProcSpell in the appraisal's spell book). 0 for none.
/// </summary>
public static int ProcSpellOf(GearFacts f, List<int> spells)
{
if (f.ProcSpellId != 0) return spells.Contains(f.ProcSpellId) ? f.ProcSpellId : 0;
return (f.Slot & ProcSlots) != 0 && spells.Count == 1 ? spells[0] : 0;
}
/// <summary>Decides one item (see the file note).</summary>
public static GearVerdict Judge(GearFacts f)
{
List<int> spells = BaseSpells(f.RawSpellIds, out HashSet<int> onItem);
var on = new bool[spells.Count];
// A proc (a cloak's or aetheria's surge, a weapon's cast on strike) is cast when the item
// triggers: never a lasting enchantment on the wearer or the item, so it isn't looked for.
// It shows as on whenever the item is (2026-11-12: cloak and aetheria read "No").
int proc = ProcSpellOf(f, spells);
int procAt = proc != 0 ? spells.IndexOf(proc) : -1;
int needed = spells.Count - (procAt >= 0 ? 1 : 0);
int seenOnPlayer = 0, seenOnItem = 0;
for (int i = 0; i < spells.Count; i++)
{
if (i == procAt) continue;
bool p = f.EnchantmentsReadable && Contains(f.PlayerItemSpells, spells[i]);
bool it = onItem.Contains(spells[i]);
on[i] = p || it;
if (p) seenOnPlayer++;
else if (it) seenOnItem++;
}
double? left = f.Identified ? SecondsLeft(f.CurMana, f.ManaRate, f.ReadAgeSeconds) : null;
int? pct = f.Identified && f.CurMana is int c && f.MaxMana is int m && m > 0
? (int)Math.Clamp(c * 100L / m, 0, 100) : null;
GearVerdict V(GearActive a, string why) => new(a, why, spells, on, left, pct);
if (!f.Identified)
return V(GearActive.Unknown, "not identified yet");
int seen = seenOnPlayer + seenOnItem;
if (seen > 0)
{
// Seen only in the appraisal's list: as old as the read, so a read that has since run dry can't say yes.
if (seenOnPlayer == 0 && left is double l && l <= 0 && f.ManaRate is double)
return V(GearActive.Unknown, "its mana may have run out since it was identified");
string why = seen == needed ? string.Empty : $"{seen} of {needed} spells seen";
if (f.MaxMana is > 0 && f.CurMana == 0)
why = Join(why, "the mana read is older than its spells");
if (procAt >= 0) on[procAt] = true;
return V(GearActive.Yes, why);
}
if (f.MaxMana is > 0 && f.CurMana == 0)
return V(GearActive.No, "out of mana");
if (f.ArcaneLoreNeeded > 0 && f.ArcaneLore is int lore && lore < f.ArcaneLoreNeeded)
return V(GearActive.No, $"needs Arcane Lore {f.ArcaneLoreNeeded}, you have {lore}");
if (f.ActivationLevel > 0 && f.ActivationSkill is int skill && skill < f.ActivationLevel)
return V(GearActive.No, $"needs {(f.ActivationSkillName.Length > 0 ? f.ActivationSkillName : "its skill")} {f.ActivationLevel}, you have {skill}");
// Only a proc: worn, with its mana and requirements met, it is on (it casts when it triggers).
if (procAt >= 0 && needed == 0)
{
on[procAt] = true;
return V(GearActive.Yes, "casts its spell when it triggers");
}
if (spells.Count == 0)
return V(GearActive.Unknown, "no spells read");
if (!f.EnchantmentsReadable)
return V(GearActive.Unknown, "your enchantments can't be read yet");
// An appraisal from while it was worn would list its own spells on it: none on it or on you is off.
// An older one (from before it was put on) can't tell.
if (f.ReadAgeSeconds is double age && f.WornForSeconds is double worn && age < worn)
return V(GearActive.No, "none of its spells is on you or on it");
return V(GearActive.Unknown, "its spells aren't seen (Check items reads it again)");
}
private static bool Contains(IReadOnlyCollection<int> set, int id)
{
if (set is ISet<int> s) return s.Contains(id);
foreach (int x in set) if (x == id) return true;
return false;
}
private static string Join(string a, string b) => a.Length == 0 ? b : a + "; " + b;
// ── Words ────────────────────────────────────────────────────────────
/// <summary>"12 min", "3 h 5 min", "2 d 4 h", "&lt;1 min"; "-" for none.</summary>
public static string TimeText(double? seconds)
{
if (seconds is not double s || double.IsNaN(s)) return "-";
if (s < 60) return s <= 0 ? "0 min" : "<1 min";
long min = (long)(s / 60);
if (min < 60) return min.ToString(CultureInfo.InvariantCulture) + " min";
long h = min / 60, mm = min % 60;
if (h < 48) return mm == 0 ? $"{h} h" : $"{h} h {mm} min";
long d = h / 24, hh = h % 24;
return hh == 0 ? $"{d} d" : $"{d} d {hh} h";
}
/// <summary>"Yes", "No" or "?".</summary>
public static string ActiveText(GearActive a) => a switch { GearActive.Yes => "Yes", GearActive.No => "No", _ => "?" };
// The slot a bit names, armor first (a coat covers chest and arms: "Chest"), then the rest.
private static readonly (int Bit, string Name)[] Slots =
{
(0x00000200, "Chest"), (0x00000400, "Abdomen"), (0x00000800, "Upper Arms"), (0x00001000, "Lower Arms"),
(0x00002000, "Upper Legs"), (0x00004000, "Lower Legs"),
(0x00000001, "Head"), (0x00000020, "Hands"), (0x00000100, "Feet"),
(0x00000002, "Shirt"), (0x00000004, "Shirt"), (0x00000008, "Shirt"), (0x00000010, "Shirt"),
(0x00000040, "Pants"), (0x00000080, "Pants"),
(0x00008000, "Neck"), (0x00010000, "Left Wrist"), (0x00020000, "Right Wrist"),
(0x00040000, "Left Ring"), (0x00080000, "Right Ring"),
(0x00100000, "Melee"), (0x00200000, "Shield"), (0x00400000, "Missile"), (0x00800000, "Ammo"),
(0x01000000, "Held"), (0x02000000, "Two-handed"), (0x04000000, "Trinket"), (0x08000000, "Cloak"),
(0x10000000, "Blue Aetheria"), (0x20000000, "Yellow Aetheria"), (0x40000000, "Red Aetheria"),
};
/// <summary>The slot's name ("Left Ring"); "Worn" for none known.</summary>
public static string SlotName(int mask)
{
foreach (var (bit, name) in Slots)
if ((mask & bit) != 0) return name;
return "Worn";
}
/// <summary>The order the window lists slots in (the slot table's order; unknown last).</summary>
public static int SlotOrder(int mask)
{
for (int i = 0; i < Slots.Length; i++)
if ((mask & Slots[i].Bit) != 0) return i;
return Slots.Length;
}
/// <summary>
/// The summary line: "9 of 10 items active, lowest: Left Ring 12 min", with the unknown count and
/// the items that are off ("off: Neck (out of mana)", two at most) when there are any.
/// </summary>
public static string Summary(IReadOnlyList<(GearFacts Facts, GearVerdict Verdict)> items)
{
if (items.Count == 0) return "No worn items with spells.";
int yes = 0, unknown = 0;
var off = new List<string>();
string lowest = string.Empty;
double lowestLeft = double.MaxValue;
string lowestPct = string.Empty;
int lowestPctValue = int.MaxValue;
foreach (var (f, v) in items)
{
string slot = SlotName(f.Slot);
switch (v.Active)
{
case GearActive.Yes: yes++; break;
case GearActive.No: off.Add(v.Reason.Length > 0 ? $"{slot} ({v.Reason})" : slot); break;
default: unknown++; break;
}
if (v.Active != GearActive.Yes) continue;
if (v.SecondsLeft is double s && s < lowestLeft) { lowestLeft = s; lowest = $"{slot} {TimeText(s)}"; }
if (v.ManaPercent is int p && p < lowestPctValue) { lowestPctValue = p; lowestPct = $"{slot} {p}% mana"; }
}
var sb = new StringBuilder();
sb.Append(yes).Append(" of ").Append(items.Count).Append(items.Count == 1 ? " item active" : " items active");
if (unknown > 0) sb.Append(", ").Append(unknown).Append(" unknown");
if (off.Count > 0)
{
sb.Append(", off: ").Append(string.Join(", ", off.GetRange(0, Math.Min(2, off.Count))));
if (off.Count > 2) sb.Append(" and ").Append(off.Count - 2).Append(" more");
}
if (lowest.Length > 0) sb.Append(", lowest: ").Append(lowest);
else if (lowestPct.Length > 0) sb.Append(", lowest: ").Append(lowestPct);
return sb.ToString();
}
}

View file

@ -0,0 +1,388 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi;
// Buff items (Use Buff Items, 2026-11-11): the items RynthAi uses for their buff when it isn't on.
// Three are built in (Asheron's Benediction, Asheron's Lesser Benediction, Blackmoor's Favor); the
// player can block any of them and add their own (a server's custom gems, potions). This file is the
// pure part: the lists as saved in the profile, the edits made to them, and which item to use now.
// BuffManager.BuffItems.cs reads the pack and the enchantments and sends the use. No game calls here.
/// <summary>
/// A buff item the player added (LegacyUiSettings.CustomBuffItems). Saved in the character's profile.
/// </summary>
public sealed class CustomBuffItem
{
/// <summary>The item's name, matched against the pack without case.</summary>
public string Name { get; set; } = string.Empty;
/// <summary>Ticked in the Buff Items list: RynthAi may use it.</summary>
public bool Allowed { get; set; } = true;
/// <summary>
/// The spells its use casts, read from the item: its spell (data id 28 in the object's
/// CreateObject header), else the spell book its appraisal lists. Buffs only: a spell the
/// catalog lists with no duration is left out. Its buff counts as on when any of them is on
/// the player.
/// </summary>
public List<uint> SpellIds
{
get => _spellIds;
set => _spellIds = value ?? new List<uint>();
}
private List<uint> _spellIds = new();
/// <summary>
/// The spells were read. With none found the item is used on <see cref="RepeatMinutes"/>
/// instead. False: not read yet (added by name and not in the pack since), so it waits.
/// </summary>
public bool SpellsRead { get; set; }
/// <summary>For an item with no spell to check: use it again this many minutes after the last use.</summary>
public int RepeatMinutes { get; set; } = BuffItemRules.DefaultRepeatMinutes;
/// <summary>When RynthAi last used it (UTC); the repeat timer counts from here, across reloads.</summary>
public DateTime? LastUsedUtc { get; set; }
public CustomBuffItem Copy() => new()
{
Name = Name,
Allowed = Allowed,
SpellIds = new List<uint>(SpellIds),
SpellsRead = SpellsRead,
RepeatMinutes = RepeatMinutes,
LastUsedUtc = LastUsedUtc,
};
}
/// <summary>The built-in items, the limits, and the edits the window and /ra buffitems make.</summary>
internal static class BuffItemRules
{
/// <summary>The same item is not used again this soon, so its buff has time to land.</summary>
public const int RetryAfterUseSec = 15;
/// <summary>Uses in a row whose buff never showed before the item is rested.</summary>
public const int UsesBeforeRest = 2;
/// <summary>How long an item whose buff didn't show is left alone.</summary>
public const int RestMinutes = 10;
public const int DefaultRepeatMinutes = 60;
public const int MinRepeatMinutes = 1;
public const int MaxRepeatMinutes = 7 * 24 * 60;
public const int MaxNameLength = 80;
/// <summary>
/// The built-in items: name, and the spell ids that mean its buff is already on (the
/// Benediction and the Lesser one give the same +10% max health, so either counts for both).
/// </summary>
public static readonly (string Name, uint[] Spells)[] BuiltIns =
{
("Asheron's Benediction", new uint[] { 3810, 4024 }),
("Asheron's Lesser Benediction", new uint[] { 3810, 4024 }),
("Blackmoor's Favor", new uint[] { 3811 }),
};
/// <summary>The built-in item of that name (its own spelling), or null.</summary>
public static string? BuiltInName(string? name)
{
string n = (name ?? "").Trim();
foreach (var (b, _) in BuiltIns)
if (b.Equals(n, StringComparison.OrdinalIgnoreCase)) return b;
return null;
}
public static int ClampRepeatMinutes(int minutes) => Math.Clamp(minutes, MinRepeatMinutes, MaxRepeatMinutes);
/// <summary>A name as typed: trimmed, at most <see cref="MaxNameLength"/> characters.</summary>
public static string CleanName(string? name)
{
string n = (name ?? "").Trim();
return n.Length > MaxNameLength ? n.Substring(0, MaxNameLength).TrimEnd() : n;
}
public static CustomBuffItem? FindCustom(IReadOnlyList<CustomBuffItem>? customs, string? name)
{
if (customs == null) return null;
string n = (name ?? "").Trim();
foreach (var c in customs)
if (c != null && c.Name.Equals(n, StringComparison.OrdinalIgnoreCase)) return c;
return null;
}
public static bool IsBlocked(IReadOnlyList<string>? blocked, string name)
{
if (blocked == null) return false;
foreach (string b in blocked)
if (string.Equals(b, name, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
public enum EditResult { Changed, Unchanged, NotFound, Added, AlreadyListed, BuiltIn, EmptyName, Updated, Removed }
/// <summary>
/// Allows or blocks a built-in or custom item by name. Built-ins are blocked through the
/// blocked list (a new list when it changes); a custom item's Allowed is set on a copy in a
/// new list, so a reader holding the old lists never sees them change.
/// </summary>
public static EditResult SetAllowed(IReadOnlyList<string> blocked, IReadOnlyList<CustomBuffItem> customs, string name, bool allowed,
out List<string> newBlocked, out List<CustomBuffItem> newCustoms, out string shownName)
{
newBlocked = new List<string>(blocked);
newCustoms = new List<CustomBuffItem>(customs);
shownName = CleanName(name);
string? builtIn = BuiltInName(name);
if (builtIn != null)
{
shownName = builtIn;
bool isBlocked = IsBlocked(blocked, builtIn);
if (isBlocked != allowed) return EditResult.Unchanged;
if (allowed) newBlocked.RemoveAll(b => string.Equals(b, builtIn, StringComparison.OrdinalIgnoreCase));
else newBlocked.Add(builtIn);
return EditResult.Changed;
}
for (int i = 0; i < newCustoms.Count; i++)
{
var c = newCustoms[i];
if (c == null || !c.Name.Equals(shownName, StringComparison.OrdinalIgnoreCase)) continue;
shownName = c.Name;
if (c.Allowed == allowed) return EditResult.Unchanged;
var copy = c.Copy();
copy.Allowed = allowed;
newCustoms[i] = copy;
return EditResult.Changed;
}
return EditResult.NotFound;
}
/// <summary>
/// Adds a custom item (a new list). <paramref name="spells"/> null: its spells aren't known yet
/// (added by name). Adding one already listed with spells read from the item refreshes them
/// (<see cref="EditResult.Updated"/>); a built-in name is refused.
/// </summary>
public static EditResult Add(IReadOnlyList<CustomBuffItem> customs, string? name, IReadOnlyList<uint>? spells,
out List<CustomBuffItem> newCustoms, out CustomBuffItem? item)
{
newCustoms = new List<CustomBuffItem>(customs);
item = null;
string n = CleanName(name);
if (n.Length == 0) return EditResult.EmptyName;
if (BuiltInName(n) != null) return EditResult.BuiltIn;
for (int i = 0; i < newCustoms.Count; i++)
{
var c = newCustoms[i];
if (c == null || !c.Name.Equals(n, StringComparison.OrdinalIgnoreCase)) continue;
if (spells == null) { item = c; return EditResult.AlreadyListed; }
var copy = c.Copy();
copy.SpellIds = new List<uint>(spells);
copy.SpellsRead = true;
newCustoms[i] = copy;
item = copy;
return EditResult.Updated;
}
item = new CustomBuffItem
{
Name = n,
SpellIds = spells != null ? new List<uint>(spells) : new List<uint>(),
SpellsRead = spells != null,
};
newCustoms.Add(item);
return EditResult.Added;
}
/// <summary>Removes a custom item (a new list). Built-ins can't be removed, only blocked.</summary>
public static EditResult Remove(IReadOnlyList<CustomBuffItem> customs, string? name, out List<CustomBuffItem> newCustoms, out string shownName)
{
newCustoms = new List<CustomBuffItem>(customs);
shownName = CleanName(name);
string? builtIn = BuiltInName(name);
if (builtIn != null) { shownName = builtIn; return EditResult.BuiltIn; }
for (int i = 0; i < newCustoms.Count; i++)
{
if (newCustoms[i] == null || !newCustoms[i].Name.Equals(shownName, StringComparison.OrdinalIgnoreCase)) continue;
shownName = newCustoms[i].Name;
newCustoms.RemoveAt(i);
return EditResult.Removed;
}
return EditResult.NotFound;
}
}
/// <summary>One line of the buff item list as the picker sees it: a built-in or a custom item.</summary>
internal sealed class BuffItemEntry
{
public string Name = string.Empty;
public bool BuiltIn;
public bool Allowed = true;
/// <summary>The spell ids that mean its buff is on (empty: none known).</summary>
public uint[] Spells = Array.Empty<uint>();
/// <summary>The spells are known (always for a built-in): with none, the repeat timer is used.</summary>
public bool SpellsKnown = true;
public int RepeatMinutes = BuffItemRules.DefaultRepeatMinutes;
/// <summary>The custom item behind this line (its LastUsedUtc is set on a use); null for a built-in.</summary>
public CustomBuffItem? Custom;
public bool UsesTimer => SpellsKnown && Spells.Length == 0;
/// <summary>The built-ins (a blocked one is listed, not allowed), then the custom items.</summary>
public static List<BuffItemEntry> Build(IReadOnlyList<string>? blocked, IReadOnlyList<CustomBuffItem>? customs)
{
var list = new List<BuffItemEntry>();
foreach (var (name, spells) in BuffItemRules.BuiltIns)
list.Add(new BuffItemEntry { Name = name, BuiltIn = true, Allowed = !BuffItemRules.IsBlocked(blocked, name), Spells = spells });
if (customs != null)
{
foreach (var c in customs)
{
if (c == null || string.IsNullOrWhiteSpace(c.Name) || BuffItemRules.BuiltInName(c.Name) != null) continue;
list.Add(new BuffItemEntry
{
Name = c.Name.Trim(),
Allowed = c.Allowed,
Spells = c.SpellIds.ToArray(),
SpellsKnown = c.SpellsRead || c.SpellIds.Count > 0,
RepeatMinutes = BuffItemRules.ClampRepeatMinutes(c.RepeatMinutes),
Custom = c,
});
}
}
return list;
}
public static BuffItemEntry? Find(IReadOnlyList<BuffItemEntry> entries, string? name)
{
if (string.IsNullOrEmpty(name)) return null;
foreach (var e in entries)
if (e.Name.Equals(name.Trim(), StringComparison.OrdinalIgnoreCase)) return e;
return null;
}
}
/// <summary>An item in the pack: its object id and name.</summary>
internal readonly record struct BuffItemInPack(int Id, string Name);
/// <summary>The item to use now, the line it matched, and why.</summary>
internal readonly record struct BuffItemChoice(int ItemId, BuffItemEntry Entry, string Why);
/// <summary>
/// Which buff item to use now. One item per call, the first in pack order whose line is allowed and
/// whose buff is due: with spells, none of them on the player; with no spell to check, its repeat
/// time gone by since the last use. Never the same item within <see cref="BuffItemRules.RetryAfterUseSec"/>
/// of a use (an item that shares a spell with it counts as used too), and an item used
/// <see cref="BuffItemRules.UsesBeforeRest"/> times in a row without its buff showing rests
/// <see cref="BuffItemRules.RestMinutes"/> minutes (a potion is not drunk every 15 s for nothing).
/// Only items in the pack are ever picked. Times are passed in.
/// </summary>
internal sealed class BuffItemPicker
{
private sealed class State
{
public DateTime UsedAt = DateTime.MinValue;
public int UsesWithoutBuff;
public DateTime RestUntil = DateTime.MinValue;
}
private readonly Dictionary<string, State> _state = new(StringComparer.OrdinalIgnoreCase);
private readonly List<string> _notes = new();
/// <summary>Lines for the player (an item rested); taken by <see cref="TakeNotes"/>.</summary>
public List<string> TakeNotes()
{
var n = new List<string>(_notes);
_notes.Clear();
return n;
}
private State StateOf(string name)
{
if (!_state.TryGetValue(name, out var s)) _state[name] = s = new State();
return s;
}
private static bool AnyOn(uint[] spells, IReadOnlyCollection<uint> active)
{
foreach (uint s in spells)
if (Contains(active, s)) return true;
return false;
}
private static bool Contains(IReadOnlyCollection<uint> set, uint v)
{
if (set is ISet<uint> hs) return hs.Contains(v);
foreach (uint x in set) if (x == v) return true;
return false;
}
public BuffItemChoice? Choose(IReadOnlyList<BuffItemEntry> entries, IReadOnlyList<BuffItemInPack> pack,
IReadOnlyCollection<uint> active, DateTime now, DateTime utcNow)
{
foreach (var p in pack)
{
var e = BuffItemEntry.Find(entries, p.Name);
if (e == null || !e.Allowed) continue;
var st = StateOf(e.Name);
if (e.Spells.Length > 0 && AnyOn(e.Spells, active))
{
st.UsesWithoutBuff = 0;
continue;
}
if (now < st.RestUntil) continue;
if ((now - st.UsedAt).TotalSeconds < BuffItemRules.RetryAfterUseSec) continue;
if (e.Spells.Length > 0)
{
if (st.UsesWithoutBuff >= BuffItemRules.UsesBeforeRest)
{
st.UsesWithoutBuff = 0;
st.RestUntil = now.AddMinutes(BuffItemRules.RestMinutes);
_notes.Add($"[RynthAi] Buff item: {e.Name} was used {BuffItemRules.UsesBeforeRest} times and its buff didn't show. Trying it again in {BuffItemRules.RestMinutes} minutes.");
continue;
}
return new BuffItemChoice(p.Id, e, "its buff isn't on");
}
if (!e.SpellsKnown) continue; // a custom item whose spells haven't been read yet
DateTime? last = e.Custom?.LastUsedUtc;
if (last is DateTime l && (utcNow - l).TotalMinutes < e.RepeatMinutes) continue;
return new BuffItemChoice(p.Id, e, $"no spell to check, used every {e.RepeatMinutes} min");
}
return null;
}
/// <summary>
/// The choice went out (or was tried): no use of it, or of an item sharing a spell with it,
/// for <see cref="BuffItemRules.RetryAfterUseSec"/>. <paramref name="sent"/>: the use was sent,
/// so it counts towards the rest and starts a custom item's repeat time.
/// </summary>
public void NoteUsed(BuffItemChoice c, IReadOnlyList<BuffItemEntry> entries, DateTime now, DateTime utcNow, bool sent = true)
{
var st = StateOf(c.Entry.Name);
st.UsedAt = now;
if (c.Entry.Spells.Length > 0)
{
foreach (var other in entries)
{
if (ReferenceEquals(other, c.Entry) || other.Spells.Length == 0) continue;
foreach (uint s in other.Spells)
if (Array.IndexOf(c.Entry.Spells, s) >= 0) { StateOf(other.Name).UsedAt = now; break; }
}
}
if (!sent) return;
if (c.Entry.Spells.Length > 0) st.UsesWithoutBuff++;
if (c.Entry.Custom != null) c.Entry.Custom.LastUsedUtc = utcNow;
}
/// <summary>What the line is doing now, for the Buff Items list and /ra buffitems list.</summary>
public string Describe(BuffItemEntry e, int inPack, IReadOnlyCollection<uint>? active, DateTime now, DateTime utcNow)
{
if (!e.Allowed) return "blocked";
if (inPack <= 0) return "not in your pack";
_state.TryGetValue(e.Name, out var st);
if (e.Spells.Length > 0)
{
if (active != null && AnyOn(e.Spells, active)) return "buff on";
if (st != null && now < st.RestUntil)
return $"its buff didn't show, trying again in {Math.Max(1, (int)Math.Ceiling((st.RestUntil - now).TotalMinutes))} min";
if (st != null && (now - st.UsedAt).TotalSeconds < BuffItemRules.RetryAfterUseSec) return "used, waiting for its buff";
return active == null ? "in your pack" : "buff off: used at the next check";
}
if (!e.SpellsKnown) return "reading its spell";
DateTime? last = e.Custom?.LastUsedUtc;
if (last is not DateTime l) return $"no spell to check: used now, then every {e.RepeatMinutes} min";
double left = e.RepeatMinutes - (utcNow - l).TotalMinutes;
return left <= 0
? $"no spell to check: due (every {e.RepeatMinutes} min)"
: $"no spell to check: next in {Math.Max(1, (int)Math.Ceiling(left))} min (every {e.RepeatMinutes} min)";
}
}

View file

@ -0,0 +1,258 @@
using System;
using System.Collections.Generic;
using System.Text;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>One line of the Buff Items list for the window and /ra buffitems list (pump thread makes it).</summary>
public sealed class BuffItemRow
{
public string Name = string.Empty;
public bool BuiltIn;
public bool Allowed;
/// <summary>How many are in the pack (stacks counted).</summary>
public int InPack;
/// <summary>What it is doing now ("buff on", "not in your pack", ...).</summary>
public string Status = string.Empty;
/// <summary>The spells that mean its buff is on, by name; empty when it has none to check.</summary>
public string Spells = string.Empty;
/// <summary>No spell to check: used every <see cref="RepeatMinutes"/> minutes instead.</summary>
public bool UsesTimer;
public int RepeatMinutes;
}
// Buff items (Use Buff Items): BuffItemPicker.cs decides, this part reads the game and sends the use.
public partial class BuffManager
{
private readonly BuffItemPicker _buffItemPicker = new();
private DateTime _lastBuffItemCheck = DateTime.MinValue;
/// <summary>Items whose appraisal was asked for to read their spells (object id -> when).</summary>
private readonly Dictionary<int, DateTime> _buffItemIdAsked = new();
/// <summary>How long an asked-for appraisal may take before the item counts as casting nothing we can read.</summary>
private const double BuffItemAppraiseWaitSec = 10;
/// <summary>PropertyDataId.Spell: the spell an item casts when used (CreateObject header).</summary>
private const uint STypeDidSpell = 28;
/// <summary>
/// Uses a buff item whose buff isn't on the player: the built-ins (Asheron's Benediction, Asheron's
/// Lesser Benediction, Blackmoor's Favor) unless blocked, and the player's own allowed items. One
/// item per check, 3 s apart; the rest is BuffItemPicker's (15 s before the same item again, a rest
/// after two uses whose buff didn't show, a repeat time for an item with no spell to check). Only
/// items in the pack are used. Off with UseBuffItems.
/// </summary>
private void TryUseBuffItems()
{
if (!_settings.UseBuffItems || _worldObjectCache == null || !_host.HasReadPlayerEnchantments) return;
if ((RynthClock.Now - _lastBuffItemCheck).TotalMilliseconds < 3000) return;
_lastBuffItemCheck = RynthClock.Now;
if (!_host.CanCastNow) return;
var inventory = _worldObjectCache.GetDirectInventory(forceRefresh: false);
ReadCustomBuffItemSpells(inventory);
var entries = BuffItemEntry.Build(_settings.BlockedBuffItems, _settings.CustomBuffItems);
var pack = PackForBuffItems(inventory);
var active = ReadActiveSpellIds();
BuffItemChoice? pick = _buffItemPicker.Choose(entries, pack, active, RynthClock.Now, DateTime.UtcNow);
foreach (string note in _buffItemPicker.TakeNotes()) { _host.Log(note); _host.WriteToChat(note, 2); }
if (pick is not BuffItemChoice c) return;
_host.Log($"[RynthAi] Buff item: using {c.Entry.Name} ({c.Why}).");
bool sent = _host.UseFor(unchecked((uint)c.ItemId), "Buff", $"buff item: {c.Entry.Name}, {c.Why}");
_buffItemPicker.NoteUsed(c, entries, RynthClock.Now, DateTime.UtcNow, sent);
_lastCastAttempt = RynthClock.Now;
}
private static List<BuffItemInPack> PackForBuffItems(IReadOnlyList<WorldObject> inventory)
{
var pack = new List<BuffItemInPack>(inventory.Count);
foreach (var wo in inventory)
if (!string.IsNullOrEmpty(wo.Name)) pack.Add(new BuffItemInPack(wo.Id, wo.Name));
return pack;
}
private HashSet<uint> ReadActiveSpellIds()
{
var active = new HashSet<uint>();
if (!_host.HasReadPlayerEnchantments) return active;
var sids = new uint[256];
var exp = new double[256];
int n = _host.ReadPlayerEnchantments(sids, exp, sids.Length);
for (int i = 0; i < n && i < sids.Length; i++) active.Add(sids[i]);
return active;
}
/// <summary>
/// A custom item added by name has no spells read yet: read them from the first one in the pack
/// (once; the profile keeps them). An item still waiting for its appraisal stays unread and isn't used.
/// </summary>
private void ReadCustomBuffItemSpells(IReadOnlyList<WorldObject> inventory)
{
foreach (var c in _settings.CustomBuffItems)
{
if (c == null || c.SpellsRead) continue;
WorldObject? wo = null;
foreach (var w in inventory)
if (w.Name != null && w.Name.Equals(c.Name, StringComparison.OrdinalIgnoreCase)) { wo = w; break; }
if (wo == null) continue;
if (!TryReadItemUseSpells(wo.Id, out var spells)) continue;
// In place: one item's own fields, read by this thread only (the window shows the next snapshot).
c.SpellIds = spells;
c.SpellsRead = true;
_host.Log($"[RynthAi] Buff item: {c.Name} " + (spells.Count > 0
? $"casts {SpellNames(spells)}; its buff counts as on while that is on you."
: $"casts no spell RynthAi can check; it is used every {BuffItemRules.ClampRepeatMinutes(c.RepeatMinutes)} min."));
}
}
/// <summary>
/// The buff spells an item casts when used: its spell (data id 28 from its CreateObject header, no
/// appraisal needed), plus the spell book an appraisal lists. A spell the catalog lists with no
/// duration (a heal) is left out: it never shows as an enchantment. False when that can't be told
/// yet: no spell in the header and no appraisal (one is asked for; after
/// <see cref="BuffItemAppraiseWaitSec"/> without one, the item counts as casting nothing).
/// </summary>
internal bool TryReadItemUseSpells(int objectId, out List<uint> spells)
{
spells = new List<uint>();
uint uid = unchecked((uint)objectId);
bool appraised = false;
try
{
if (_host.TryGetObjectDataIdProperty(uid, STypeDidSpell, out uint did) && did != 0 && did < 0x10000)
spells.Add(did);
}
catch { }
try
{
if (_host.HasGetObjectSpellIds)
{
var buf = new uint[32];
int n = _host.GetObjectSpellIds(uid, buf, buf.Length);
if (n >= 0) appraised = true;
for (int i = 0; i < n && i < buf.Length; i++)
if (buf[i] != 0 && !spells.Contains(buf[i])) spells.Add(buf[i]);
}
}
catch { }
if (spells.Count == 0 && !appraised && _host.HasGetObjectSpellIds)
{
if (!_buffItemIdAsked.TryGetValue(objectId, out DateTime asked))
{
_buffItemIdAsked[objectId] = RynthClock.Now;
if (_host.HasRequestId) { try { _host.RequestId(uid); } catch { } }
return false;
}
if ((RynthClock.Now - asked).TotalSeconds < BuffItemAppraiseWaitSec) return false;
}
if (SpellCatalog.IsLoaded)
spells.RemoveAll(id => SpellCatalog.Get((int)id) is { } e && e.DurationSec <= 0);
return true;
}
private static string SpellNames(IReadOnlyList<uint> spells)
{
var sb = new StringBuilder();
foreach (uint id in spells)
{
if (sb.Length > 0) sb.Append(", ");
sb.Append(SpellCatalog.Get((int)id)?.Name is { Length: > 0 } n ? n : $"spell {id}");
}
return sb.ToString();
}
private static string HowItIsUsed(CustomBuffItem item) => !item.SpellsRead
? "its spell is read from the item when it is in your pack, before the first use"
: item.SpellIds.Count > 0
? $"its buff counts as on while {SpellNames(item.SpellIds)} is on you"
: $"it casts no spell RynthAi can check, so it is used every {BuffItemRules.ClampRepeatMinutes(item.RepeatMinutes)} min (change it in the list or with /ra buffitems repeat)";
/// <summary>"Add selected item" and /ra buffitems addselected: the selected item as a custom buff item. Pump thread.</summary>
public bool AddSelectedBuffItem(out string reply)
{
uint sel = _host.GetSelectedItemId();
if (sel == 0) { reply = "[RynthAi] Buff items: nothing selected. Click the item in your inventory first."; return false; }
var wo = _worldObjectCache?[unchecked((int)sel)];
if (wo == null || string.IsNullOrEmpty(wo.Name)) { reply = $"[RynthAi] Buff items: item 0x{sel:X8} isn't known yet. Try again in a moment."; return false; }
return AddBuffItem(wo.Name, wo.Id, out reply);
}
/// <summary>
/// /ra buffitems add &lt;name&gt; and the window's name box: adds an item by name. When one is in the
/// pack its spells are read now, else before its first use. Pump thread.
/// </summary>
public bool AddBuffItemByName(string name, out string reply)
{
string n = BuffItemRules.CleanName(name);
int id = 0;
if (_worldObjectCache != null)
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: false))
if (wo.Name != null && wo.Name.Equals(n, StringComparison.OrdinalIgnoreCase)) { id = wo.Id; n = wo.Name; break; }
return AddBuffItem(n, id, out reply);
}
private bool AddBuffItem(string name, int objectId, out string reply)
{
List<uint>? spells = null;
if (objectId != 0 && TryReadItemUseSpells(objectId, out var read)) spells = read;
var r = _settings.AddCustomBuffItem(name, spells, out var item);
switch (r)
{
case BuffItemRules.EditResult.EmptyName:
reply = "[RynthAi] Buff items: no name given. Usage: /ra buffitems add <item name>";
return false;
case BuffItemRules.EditResult.BuiltIn:
string b = BuffItemRules.BuiltInName(name) ?? name;
reply = $"[RynthAi] Buff items: {b} is built in and {(BuffItemRules.IsBlocked(_settings.BlockedBuffItems, b) ? "blocked" : "allowed")}. Tick or untick it in the list (/ra buffitems allow|block {b}).";
return false;
case BuffItemRules.EditResult.AlreadyListed:
reply = $"[RynthAi] Buff items: {item!.Name} is already in the list ({(item.Allowed ? "allowed" : "blocked")}); {HowItIsUsed(item)}.";
return true;
case BuffItemRules.EditResult.Updated:
reply = $"[RynthAi] Buff items: {item!.Name} read again from the item; {HowItIsUsed(item)}.";
return true;
default:
reply = $"[RynthAi] Buff items: added {item!.Name} (allowed); {HowItIsUsed(item)}."
+ (_settings.UseBuffItems ? "" : " Use Buff Items is off, so nothing is used until it is on.");
return true;
}
}
/// <summary>The list as the window and /ra buffitems list show it: every line, its pack count and what it is doing. Pump thread.</summary>
public List<BuffItemRow> DescribeBuffItems()
{
var entries = BuffItemEntry.Build(_settings.BlockedBuffItems, _settings.CustomBuffItems);
var counts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
if (_worldObjectCache != null)
{
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: false))
{
if (string.IsNullOrEmpty(wo.Name) || BuffItemEntry.Find(entries, wo.Name) == null) continue;
counts.TryGetValue(wo.Name, out int had);
counts[wo.Name] = had + Math.Max(1, wo.Values(LongValueKey.StackCount, 1));
}
}
HashSet<uint>? active = _host.HasReadPlayerEnchantments ? ReadActiveSpellIds() : null;
var rows = new List<BuffItemRow>(entries.Count);
foreach (var e in entries)
{
counts.TryGetValue(e.Name, out int inPack);
rows.Add(new BuffItemRow
{
Name = e.Name,
BuiltIn = e.BuiltIn,
Allowed = e.Allowed,
InPack = inPack,
Status = _buffItemPicker.Describe(e, inPack, active, RynthClock.Now, DateTime.UtcNow),
Spells = e.Spells.Length > 0 ? SpellNames(e.Spells) : string.Empty,
UsesTimer = e.UsesTimer,
RepeatMinutes = e.RepeatMinutes,
});
}
return rows;
}
}

View file

@ -2664,55 +2664,7 @@ public partial class BuffManager : IDisposable
return VitalNo("none in the Items list or the pack");
}
// ── Buff items: unlimited gems that cast a buff when used ─────────────
// name -> the spell ids that mean its buff is already on (Benediction and the
// Lesser one give the same +10% max health, so either counts for both).
private static readonly (string Name, uint[] Spells)[] BuffItems =
{
("Asheron's Benediction", new uint[] { 3810, 4024 }),
("Asheron's Lesser Benediction", new uint[] { 3810, 4024 }),
("Blackmoor's Favor", new uint[] { 3811 }),
};
private readonly Dictionary<string, DateTime> _buffItemUsedAt = new(StringComparer.OrdinalIgnoreCase);
private DateTime _lastBuffItemCheck = DateTime.MinValue;
/// <summary>
/// Uses a buff item whose buff isn't on the player (Asheron's Benediction, Blackmoor's
/// Favor). They were never used. One item per check, 3 s apart; 15 s before the same
/// item again so its buff can land. Off with UseBuffItems.
/// </summary>
private void TryUseBuffItems()
{
if (!_settings.UseBuffItems || _worldObjectCache == null || !_host.HasReadPlayerEnchantments) return;
if ((RynthClock.Now - _lastBuffItemCheck).TotalMilliseconds < 3000) return;
_lastBuffItemCheck = RynthClock.Now;
if (!_host.CanCastNow) return;
var active = new HashSet<uint>();
var sids = new uint[256];
var exp = new double[256];
int n = _host.ReadPlayerEnchantments(sids, exp, sids.Length);
for (int i = 0; i < n && i < sids.Length; i++) active.Add(sids[i]);
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: false))
{
foreach (var (name, spells) in BuffItems)
{
if (!wo.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) continue;
bool on = false;
foreach (uint s in spells) if (active.Contains(s)) { on = true; break; }
if (on) break;
if (_buffItemUsedAt.TryGetValue(name, out DateTime at) && (RynthClock.Now - at).TotalSeconds < 15) break;
_buffItemUsedAt[name] = RynthClock.Now;
// The same buff from the other Benediction counts as done too.
foreach (var (other, os) in BuffItems) if (os == spells || os[0] == spells[0]) _buffItemUsedAt[other] = RynthClock.Now;
_host.Log($"[RynthAi] Buff item: using {wo.Name} (its buff isn't on).");
_host.UseFor(unchecked((uint)wo.Id), "Buff", $"buff item: the buff of {wo.Name} is not on");
_lastCastAttempt = RynthClock.Now;
return;
}
}
}
// Buff items (Asheron's Benediction, Blackmoor's Favor and the player's own): BuffManager.BuffItems.cs.
// ── Field rations: Cooking Pot on (Infinite) Dried Rations, 25 at a time ──
private DateTime _lastRationAttempt = DateTime.MinValue, _rationRestUntil = DateTime.MinValue;

View file

@ -103,16 +103,12 @@ internal static class BuffProfileStore
File.Move(tmp, path, overwrite: true);
}
public static bool Delete(string path)
{
try
{
if (!File.Exists(path)) return false;
File.Delete(path);
return true;
}
catch { return false; }
}
/// <summary>
/// The Spells window's Delete: the profile is moved to BuffProfiles\Deleted (never deleted;
/// LegacyUi/ProfileFileOps.cs), so it leaves the list and can be moved back.
/// </summary>
public static bool Delete(string path) =>
RynthCore.Plugin.RynthAi.LegacyUi.ProfileFileOps.MoveToDeleted(path, RynthClock.Now, out _, out _);
/// <summary>An entry for a catalog spell, with its buffing key worked out.</summary>
public static BuffProfileEntry EntryFor(SpellCatalogEntry e) => new()

View file

@ -0,0 +1,145 @@
// ============================================================================
// RynthSuite - Combat/CombatManager.DirtyFighting.cs
// Dirty Fighting rotation (2026-11-11): melee and missile attacks aim at the
// height whose Dirty Fighting effect the target is missing, in the player's
// order (High, Medium, Low by default), then at a chosen default height once
// all three are on, and back again when one is about to run out.
//
// What is on a target comes from this character's own landing lines in
// combat chat ("Dirty Fighting! <me> delivers a <spell> to <target>!"), the
// only signal the server sends the attacker; the line names the target, so it
// is matched to the target being fought by name. Durations are the server's
// 20 s. The height choice itself is DirtyFightingHeights.Choose (pure, tested).
// Off, or with Dirty Fighting untrained, the fixed Attack Height applies.
// ============================================================================
using System;
namespace RynthCore.Plugin.RynthAi;
public partial class CombatManager
{
private readonly DirtyFightingTracker _dfTracker = new();
private string _dfOwnName = string.Empty;
private uint _dfOwnNameFor;
// The last height the rotation picked, per target, so a change is logged once.
private int _dfLoggedTarget;
private int _dfLoggedHeight = -1;
/// <summary>Dirty Fighting trained or specialized (an unread skill table counts as not).</summary>
internal bool DirtyFightingTrained =>
_charSkills != null && _charSkills[AcSkillType.DirtyFighting].Training >= 2;
private string OwnNameForDf()
{
if (_playerId == 0) return string.Empty;
if (_dfOwnNameFor == _playerId && _dfOwnName.Length > 0) return _dfOwnName;
string name = string.Empty;
try
{
if (_host.HasGetObjectName && _host.TryGetObjectName(_playerId, out string n)) name = n ?? string.Empty;
}
catch { }
if (name.Length == 0) name = _worldFilter[unchecked((int)_playerId)]?.Name ?? string.Empty;
_dfOwnName = name;
_dfOwnNameFor = _playerId;
return name;
}
/// <summary>
/// Every chat line (RynthAiPlugin.OnChatWindowText): a landing line of ours records the effect
/// on the target it names, when that is the target being fought (or the one the server's
/// attack is bound to). Recorded whether or not the rotation is on, so the status shows it.
/// </summary>
public void NoteDirtyFightingChat(string? text)
{
if (string.IsNullOrEmpty(text) || !text.StartsWith("Dirty Fighting! ", StringComparison.Ordinal)) return;
if (!DirtyFightingHeights.TryParseLanding(text, OwnNameForDf(), out int height, out string targetName)) return;
int id = 0;
foreach (int candidate in new[] { activeTargetId, _serverAttackTargetId })
{
if (candidate == 0) continue;
if (string.Equals(_worldFilter[candidate]?.Name, targetName, StringComparison.Ordinal)) { id = candidate; break; }
}
if (id == 0)
{
_host.Log($"[DFHeight] {DirtyFightingHeights.HeightName(height)} landed on '{targetName}', not the target being fought: not tracked");
return;
}
_dfTracker.Landed(id, height, RynthClock.Now);
_host.Log($"[DFHeight] {DirtyFightingHeights.HeightName(height)} landed on 0x{unchecked((uint)id):X8} '{targetName}' " +
$"({_dfTracker.Get(id)?.Describe(_settings.DfHeightOrder, RynthClock.Now)})");
}
/// <summary>The height (0 Low, 1 Medium, 2 High) this attack at the active target aims at.</summary>
private int AttackHeightForTarget(bool isMissile)
{
int fixedHeight = isMissile ? _settings.MissileAttackHeight : _settings.MeleeAttackHeight;
if (!_settings.DfHeightRotation) return Math.Clamp(fixedHeight, 0, 2);
int target = activeTargetId;
DateTime now = RynthClock.Now;
int h = DirtyFightingHeights.Choose(true, DirtyFightingTrained, fixedHeight, _settings.DfHeightOrder,
_settings.DfDefaultHeight, _dfTracker.Get(target), now);
if (target != _dfLoggedTarget || h != _dfLoggedHeight)
{
_dfLoggedTarget = target;
_dfLoggedHeight = h;
_host.Log($"[DFHeight] 0x{unchecked((uint)target):X8} '{_worldFilter[target]?.Name}': attacking {DirtyFightingHeights.HeightName(h)}" +
(DirtyFightingTrained ? $" ({_dfTracker.Get(target)?.Describe(_settings.DfHeightOrder, now) ?? "nothing on it yet"})"
: " (Dirty Fighting not trained: the fixed height)"));
}
return h;
}
/// <summary>
/// The server's chance per damaging hit for this character: 25%, less when Dirty Fighting is
/// below the best weapon skill for the current stance (an estimate: the server uses the
/// wielded weapon's skill).
/// </summary>
private double DirtyFightingChance()
{
if (_charSkills == null || !DirtyFightingTrained) return 0;
int df = _charSkills[AcSkillType.DirtyFighting].Buffed;
bool missile = CurrentCombatMode == CombatMode.Missile;
int best = 0;
foreach (AcSkillType s in missile
? new[] { AcSkillType.MissileWeapons }
: new[] { AcSkillType.HeavyWeapons, AcSkillType.LightWeapons, AcSkillType.FinesseWeapons, AcSkillType.TwoHandedCombat })
{
var info = _charSkills[s];
if (info.Training >= 2 && info.Buffed > best) best = info.Buffed;
}
return DirtyFightingHeights.ChancePerHit(true, df, best);
}
/// <summary>One line for the settings page and /ra dfheight status.</summary>
public string DirtyFightingStatus()
{
if (!DirtyFightingTrained)
return "Dirty Fighting is not trained: attacks use the fixed Attack Height.";
string head = (_settings.DfHeightRotation ? "On" : "Off") +
$", order {DirtyFightingHeights.OrderLabel(_settings.DfHeightOrder)}, then " +
(_settings.DfDefaultHeight >= 0 ? DirtyFightingHeights.HeightName(_settings.DfDefaultHeight) : "the Attack Height setting") +
$"; about {DirtyFightingChance() * 100:0}% per hit.";
int target = activeTargetId;
if (target == 0) return head + " No target.";
DateTime now = RynthClock.Now;
DfTargetEffects? fx = _dfTracker.Get(target);
string on = fx?.Describe(_settings.DfHeightOrder, now) ?? "nothing landed yet";
string next = _settings.DfHeightRotation
? $"; next attack {DirtyFightingHeights.HeightName(AttackHeightPreview())}"
: string.Empty;
return $"{head} Target '{_worldFilter[target]?.Name}': {on}{next}.";
}
/// <summary>The height the rotation would pick now, without logging (the status line).</summary>
private int AttackHeightPreview()
{
bool isMissile = CurrentCombatMode == CombatMode.Missile;
int fixedHeight = isMissile ? _settings.MissileAttackHeight : _settings.MeleeAttackHeight;
return DirtyFightingHeights.Choose(_settings.DfHeightRotation, DirtyFightingTrained, fixedHeight,
_settings.DfHeightOrder, _settings.DfDefaultHeight, _dfTracker.Get(activeTargetId), RynthClock.Now);
}
}

View file

@ -18,6 +18,10 @@ namespace RynthCore.Plugin.RynthAi;
/// A weapons-back swap under way when the target comes goes on, pointed at the fight's weapons when they
/// differ; a fight with the wand ends it. A failed fight swap leaves that weapon to the client's own swap
/// for <see cref="FightSwapFallbackSec"/>. Setting off: none of this runs.
///
/// Caster to caster (2026-11-11, WandSwapRules): a fight that wants another caster than the one in hand
/// swaps the same way (peace, the old caster out, the new one into the Held slot, then Magic) instead of
/// the client's own use, which went Magic, peace, bare hands, peace, Magic.
/// </summary>
public partial class CombatManager
{
@ -34,6 +38,39 @@ public partial class CombatManager
private string HandsSwapLabel => _handsSwapForFight ? "weapons for the fight" : "weapons back";
// A fight's hands swap away from one caster to another (2026-11-11, WandSwapRules): the caster it
// started from, so the swap tracker records the swap (its no-flip-flop and window cap) as it
// does for the client's own use. 0 for every other hands swap (as before).
private int _handsSwapFrom;
// The first cast after a wield waits for the stance (WandSwapRules.EquipCastHoldMs).
private bool _equipGateHeld; // AttackWithMagic held its cast for it this tick
private DateTime _equipGateLoggedFor = DateTime.MinValue; // the wield its line was logged for
/// <summary>
/// AttackWithMagic: true (and the cast held this tick, not counted as an attack) while the wield
/// before it is still settling. One log line per wield.
/// </summary>
private bool EquipCastHoldsNow()
{
if (_lastEquipTime == DateTime.MinValue) return false;
DateTime now = RynthClock.Now;
DateTime changed = _cmModeChangedAt;
try { if (LastModeChangeAt?.Invoke() is DateTime b && b > changed) changed = b; } catch { }
static double Since(DateTime now, DateTime at) => at == DateTime.MinValue ? -1 : (now - at).TotalMilliseconds;
double sinceEquip = Since(now, _lastEquipTime);
double hold = WandSwapRules.EquipCastHoldMs(sinceEquip, Since(now, changed), Since(now, lastStanceAttempt));
if (hold <= 0) return false;
_equipGateHeld = true;
LastCombatSkipReason = "equip-gate"; // D4 record-only
if (_equipGateLoggedFor != _lastEquipTime)
{
_equipGateLoggedFor = _lastEquipTime;
_host.Log($"[CombatCast] equip-gate: the first cast waits {hold:0} ms more for the stance to settle ({sinceEquip:0} ms after the wield)");
}
return true;
}
/// <summary>
/// The fight's main weapon and the off hand to go with it: the planned one, else what is in the off
/// hand already when it may stay (a hands swap takes off everything it doesn't want).
@ -79,7 +116,11 @@ public partial class CombatManager
}
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("combat-hands-swap")) return true;
StartHandsSwapForFight(now, FightWants(target, rule, mainId), desiredMode, target);
// A caster goes in alone: a Held-slot caster needs both hands empty (the off hand comes off too).
var wants = desiredMode == CombatMode.Magic
? new List<(int Id, int Slot)> { (mainId, HandSwapSequence.HeldSlot) }
: FightWants(target, rule, mainId);
StartHandsSwapForFight(now, wants, desiredMode, target);
RearmSwapAdvance(now);
return true;
}
@ -88,6 +129,10 @@ public partial class CombatManager
{
int mode = CurrentCombatMode;
_rearmWants = wants;
// A caster for a caster: record where it came from (the swap tracker). The wield step reads the
// hands after the old one went into the pack, so it would see empty hands.
int from = InHandWeaponId();
_handsSwapFrom = desiredMode == CombatMode.Magic && from != 0 && WeaponKind(from) == CombatMode.Magic ? from : 0;
_rearmSwap.Start("weapons for the fight", now, wants, peaceFirst: mode != CombatMode.NonCombat);
_handsSwapForFight = true;
_handsSwapFightMode = desiredMode;
@ -112,6 +157,17 @@ public partial class CombatManager
bool wasFight = _handsSwapForFight;
if (IsWandObject(mainObj))
{
// The fight's own swap to a caster (from another one, WandSwapRules): it goes on for that
// caster, and a step on its way lands before anything else is decided. Once combat's own
// read has the caster in hand (the swap's read of the hands can lag), the swap is over and
// the wielded branch asks for Magic.
if (wasFight && _handsSwapFightMode == CombatMode.Magic && _rearmSwap.Wants.Count > 0 && _rearmSwap.Wants[0].Id == mainId)
{
if (InHandWeaponId(fresh: true) != mainId) return true;
FinishRearmSwap(now, done: true);
return false;
}
if (wasFight && _handsSwapFightMode == CombatMode.Magic && _rearmSwap.InFlight) return true;
FinishRearmSwap(now, done: false, why: $"'{target.Name}' is fought with the wand");
if (!wasFight) _rearmedFor = _rearmVital;
return false;
@ -150,7 +206,8 @@ public partial class CombatManager
_offSlotReadAt = DateTime.MinValue;
// A launcher: only with fitting ammo on; otherwise the wielded branch puts it on, then asks.
bool ammoReady = mode != CombatMode.Missile || (HasWieldedAmmo() && !LauncherSwapHoldsStance(main));
_rearmStanceWanted = mode != 0 && mode != CombatMode.Magic && CurrentCombatMode != mode && ammoReady ? mode : 0;
// A caster (another caster's swap through peace): Magic at once, as for a melee weapon.
_rearmStanceWanted = mode != 0 && CurrentCombatMode != mode && ammoReady ? mode : 0;
_rearmStanceSince = now;
_rearmStanceForFight = true;
FinishRearmSwap(now, done: true);

View file

@ -1,6 +1,6 @@
// ============================================================================
// RynthSuite - Combat/CombatManager.SelectedTarget.cs
// "Fight the monster I select" (Settings > Ranges > Combat Targeting, off by default;
// "Fight the monster I select" (Settings > Combat > Targeting, off by default;
// /ra fightselected [on|off]; the FightSelectedTarget setting key): the automatic form of
// the target lock (CombatManager.TargetLock.cs). When the PLAYER selects an attackable monster
// in game, it becomes the forced target: fought ahead of the Targeting setting and the

View file

@ -4048,6 +4048,13 @@ public partial class CombatManager : IDisposable
_tickWait = CombatLatencyTracker.Wait.Cast;
return true;
}
// The first cast after a wield waits for the stance to settle (WandSwapRules): nothing
// was sent, so the attack interval doesn't start; the next tick asks again.
if (_equipGateHeld)
{
_tickWait = CombatLatencyTracker.Wait.Cast;
return true;
}
// Waiting on a script's choice of spell (RynthAi.Combat): nothing was sent. The same
// as the wall hold: the attack interval doesn't start, the target and scan stay as they
@ -5739,7 +5746,7 @@ public partial class CombatManager : IDisposable
private void NoteRearmWield(int id, bool off, DateTime now)
{
if (off) { _offhandSentId = id; _lastEquipTime = now; EquippedState.Invalidate(); }
else MarkWieldSent(id, InHandWeaponId());
else MarkWieldSent(id, _handsSwapForFight && _handsSwapFrom != 0 ? _handsSwapFrom : InHandWeaponId());
}
/// <summary>
@ -5758,7 +5765,7 @@ public partial class CombatManager : IDisposable
bool onlyOurPeace = a == null || (a.Kind == PacedKind.CombatMode && a.ModeTarget == CombatMode.NonCombat && a.Who == "Combat");
if (!_host.ChangeCombatModeFor(_rearmStanceWanted, "Combat", "weapons back: the fight's stance", force: onlyOurPeace))
return false;
_host.Log($"[EquipDiag] {(_rearmStanceForFight ? "weapons for the fight" : "weapons back after heals")}: {(_rearmStanceWanted == CombatMode.Missile ? "Missile" : "Melee")} mode");
_host.Log($"[EquipDiag] {(_rearmStanceForFight ? "weapons for the fight" : "weapons back after heals")}: {CombatModeName(_rearmStanceWanted)} mode");
if (_rearmStanceForFight)
{
// Combat's own stance request (the wielded branch) waits its retry delay behind this one.
@ -5871,6 +5878,7 @@ public partial class CombatManager : IDisposable
string what = HandsSwapLabel;
_rearmSwap.Cancel();
_handsSwapForFight = false;
_handsSwapFrom = 0;
_weaponSwapGate?.Release(_handsGateBy, _rearmLastMoved);
LastRearmSwapMs = ms;
_host.Log(done
@ -6492,8 +6500,10 @@ public partial class CombatManager : IDisposable
// Fast Weapon Swap: a caster in hand and a melee weapon or launcher wanted (a monster came while
// healing): peace, the wand out, the weapons on (one frame when the server is quiet), then the
// fight's stance. The client's own use took 1.4-1.7 s and paid a forced stance change.
if (_settings.FastWeaponSwap && allowWield && desiredMode != CombatMode.Magic && inHand != 0 && inHand != targetWeaponId
&& WeaponKind(inHand) == CombatMode.Magic && TryStartFightHandsSwap(target, rule, targetWeaponId, desiredMode))
// Another caster wanted (2026-11-11, WandSwapRules): the same, then Magic. The client's own use
// went Magic, peace, bare hands, peace, Magic.
if (WandSwapRules.UseHandsSwap(_settings.FastWeaponSwap, allowWield, inHand, targetWeaponId, WeaponKind(inHand))
&& TryStartFightHandsSwap(target, rule, targetWeaponId, desiredMode))
{
LastCombatSkipReason = "hand-swap";
return false;
@ -7454,7 +7464,8 @@ public partial class CombatManager : IDisposable
(recklessTrained ? "" : " (Recklessness untrained: no reckless band)") + $", first attack at {power * 100:0}%");
}
int uiHeight = isMissile ? _settings.MissileAttackHeight : _settings.MeleeAttackHeight;
// The fixed Attack Height, or the Dirty Fighting rotation's pick (CombatManager.DirtyFighting.cs).
int uiHeight = AttackHeightForTarget(isMissile);
int acHeight = uiHeight switch { 0 => 3, 2 => 1, _ => 2 }; // Low=3, Med=2, High=1
// Native attack: select target, Start fills power bar, End fires the attack.
@ -7624,6 +7635,7 @@ public partial class CombatManager : IDisposable
_wallFaceHeld = false;
_manaCastHeld = false;
_scriptHeld = false;
_equipGateHeld = false;
if (_spellManager == null || target == null) return;
// Hard safety veto: never cast offensive magic at something AC's combat
@ -7648,14 +7660,13 @@ public partial class CombatManager : IDisposable
// didn't execute, which is what collapsed war to Force Bolt I and
// re-poisoned bufftimers.txt every few seconds.
// Don't cast while a weapon equip is in progress — the wand may not be registered
// as wielded yet. _lastEquipTime is set whenever UseObject is called for a wand swap.
if ((RynthClock.Now - _lastEquipTime).TotalMilliseconds < 3000)
{
_host.Log($"[CombatCast] equip-gate: wand equip in progress ({(RynthClock.Now - _lastEquipTime).TotalMilliseconds:0}ms < 3000ms), skipping cast");
LastCombatSkipReason = "equip-gate"; // D4 record-only
// Don't cast while a weapon equip is still settling. _lastEquipTime is set by every wield.
// This was a flat 3 s, and each held tick counted as an attack (the next try a whole attack
// interval later); now the cast goes once the stance has settled after the wield, at most
// the old 3 s (WandSwapRules.EquipCastHoldMs). Combat only gets here with the chosen wand in
// hand and the client reading Magic.
if (EquipCastHoldsNow())
return;
}
// Cadence is set in Think before this is called: the previous cast must have resolved
// (UseDone, IsAwaitingCastResolution), its gesture must be over (CanCastNow), and the
// Attack Spell Delay must have passed since the last cast at this same target (the first

View file

@ -0,0 +1,272 @@
// ============================================================================
// RynthSuite - Combat/DirtyFightingHeights.cs
// Dirty Fighting rotation: which attack height the next melee swing or missile
// shot uses, so all three Dirty Fighting effects get onto the target.
//
// How the server does it (ACE, read for behaviour only): with Dirty Fighting
// at least trained, every melee or missile hit that does damage has a 25%
// chance (scaled down by Dirty Fighting / weapon skill when Dirty Fighting is
// the lower one) to land the effect of the height it was aimed at:
// High attack skills down, and heals on the target down (two spells)
// Medium a bleed (damage over time)
// Low defense skills down
// Each lasts 20 seconds. The same effect from the same attacker refreshes to a
// full 20 s rather than stacking; the three heights stack with each other.
// Each landing is announced to the attacker in combat chat:
// "Dirty Fighting! <attacker> delivers a <spell> to <target>!"
// with the spell names in SpellNames below (Blow = trained, Assault =
// specialized). That line is the only signal the attacker gets, so the
// tracker keys on it and the target's name.
//
// Pure logic (System only, time passed in), so the tests can run it.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthAi;
internal static class DirtyFightingHeights
{
// Heights in the settings' numbering (MeleeAttackHeight / MissileAttackHeight).
public const int Low = 0;
public const int Medium = 1;
public const int High = 2;
/// <summary>DfDefaultHeight: the regular Melee/Missile Attack Height setting.</summary>
public const int DefaultIsFixedHeight = -1;
/// <summary>How long each effect lasts on the server (every Dirty Fighting spell is 20 s).</summary>
public const double EffectSeconds = 20.0;
/// <summary>
/// An effect this close to running out counts as missing, so the rotation goes back to
/// its height while it is still on (a landing refreshes it to the full 20 s).
/// </summary>
public const double RenewLeadSeconds = 5.0;
/// <summary>The server's best chance per damaging hit (Dirty Fighting at or above the weapon skill).</summary>
public const double BaseChance = 0.25;
public const string DefaultOrder = "HML";
/// <summary>Every order the setting can hold, in the order the UI lists them.</summary>
public static readonly string[] OrderChoices = { "HML", "HLM", "MHL", "MLH", "LHM", "LMH" };
public static readonly string[] HeightNames = { "Low", "Medium", "High" };
/// <summary>The spell words after "delivers a" and the height each comes from.</summary>
private static readonly (string Name, int Height)[] SpellNames =
{
("Blinding Blow", High), ("Blinding Assault", High),
("Traumatic Blow", High), ("Traumatic Assault", High),
("Bleeding Blow", Medium), ("Bleeding Assault", Medium),
("Unbalancing Blow", Low), ("Unbalancing Assault", Low),
};
private const string Prefix = "Dirty Fighting! ";
public static string HeightName(int height) =>
height >= 0 && height < HeightNames.Length ? HeightNames[height] : "?";
/// <summary>A valid order ("HML" and the like: H, M and L once each), else <see cref="DefaultOrder"/>.</summary>
public static string NormalizeOrder(string? order)
{
if (string.IsNullOrWhiteSpace(order)) return DefaultOrder;
string o = order.Trim().ToUpperInvariant();
foreach (string c in OrderChoices)
if (c == o) return c;
return DefaultOrder;
}
/// <summary>The order as heights, first to last.</summary>
public static int[] ParseOrder(string? order)
{
string o = NormalizeOrder(order);
var heights = new int[3];
for (int i = 0; i < 3; i++)
heights[i] = o[i] switch { 'H' => High, 'M' => Medium, _ => Low };
return heights;
}
/// <summary>"High, Medium, Low".</summary>
public static string OrderLabel(string? order)
{
int[] h = ParseOrder(order);
return $"{HeightName(h[0])}, {HeightName(h[1])}, {HeightName(h[2])}";
}
/// <summary>
/// A Dirty Fighting landing line from <paramref name="attackerName"/>: the height whose
/// effect landed and the target's name. False for anything else, a landing by someone else
/// (a monster's on this character included) and the same words said in a chat channel.
/// </summary>
public static bool TryParseLanding(string? text, string? attackerName, out int height, out string targetName)
{
height = -1;
targetName = string.Empty;
if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(attackerName)) return false;
string t = text.Trim();
if (!t.StartsWith(Prefix, StringComparison.Ordinal)) return false;
string who = Prefix + attackerName + " delivers ";
if (!t.StartsWith(who, StringComparison.Ordinal)) return false;
string rest = t.Substring(who.Length);
if (rest.StartsWith("a ", StringComparison.Ordinal)) rest = rest.Substring(2);
else if (rest.StartsWith("an ", StringComparison.Ordinal)) rest = rest.Substring(3);
else return false;
foreach (var (name, h) in SpellNames)
{
string lead = name + " to ";
if (!rest.StartsWith(lead, StringComparison.Ordinal)) continue;
string target = rest.Substring(lead.Length);
if (target.EndsWith('!')) target = target.Substring(0, target.Length - 1);
target = target.Trim();
if (target.Length == 0) return false;
height = h;
targetName = target;
return true;
}
return false;
}
/// <summary>
/// The server's chance per damaging hit: 25%, scaled by Dirty Fighting / weapon skill when
/// Dirty Fighting is the lower one. 0 when Dirty Fighting is not trained.
/// </summary>
public static double ChancePerHit(bool dfTrained, int dfSkill, int weaponSkill)
{
if (!dfTrained) return 0;
if (weaponSkill <= 0 || dfSkill >= weaponSkill) return BaseChance;
return BaseChance * Math.Max(0, dfSkill) / weaponSkill;
}
/// <summary>
/// The height for the next attack. The fixed height (the Melee/Missile Attack Height setting)
/// when the rotation is off or Dirty Fighting isn't trained. Otherwise the first height in
/// <paramref name="order"/> whose effect is missing or due to run out within
/// <see cref="RenewLeadSeconds"/>; with all three on, <paramref name="defaultHeight"/>
/// (<see cref="DefaultIsFixedHeight"/> = the fixed height).
/// <paramref name="effects"/> may be null (nothing known about this target: a fresh one).
/// </summary>
public static int Choose(bool rotationOn, bool dfTrained, int fixedHeight, string? order, int defaultHeight,
DfTargetEffects? effects, DateTime now)
{
int fixedH = Math.Clamp(fixedHeight, Low, High);
if (!rotationOn || !dfTrained) return fixedH;
foreach (int h in ParseOrder(order))
if (effects == null || !effects.IsOn(h, now, RenewLeadSeconds))
return h;
return defaultHeight >= Low && defaultHeight <= High ? defaultHeight : fixedH;
}
}
/// <summary>When each of one target's three effects runs out (MinValue = never landed).</summary>
internal sealed class DfTargetEffects
{
private readonly DateTime[] _until = { DateTime.MinValue, DateTime.MinValue, DateTime.MinValue };
public DateTime Until(int height) => _until[height];
public void Landed(int height, DateTime now) =>
_until[height] = now.AddSeconds(DirtyFightingHeights.EffectSeconds);
public void SetUntil(int height, DateTime until) => _until[height] = until;
/// <summary>On, with more than <paramref name="leadSeconds"/> left.</summary>
public bool IsOn(int height, DateTime now, double leadSeconds = 0) =>
(_until[height] - now).TotalSeconds > leadSeconds;
public bool AnyOn(DateTime now) => IsOn(0, now) || IsOn(1, now) || IsOn(2, now);
/// <summary>"High 14 s, Medium off, Low 3 s", in the given order.</summary>
public string Describe(string? order, DateTime now)
{
var sb = new StringBuilder();
foreach (int h in DirtyFightingHeights.ParseOrder(order))
{
if (sb.Length > 0) sb.Append(", ");
sb.Append(DirtyFightingHeights.HeightName(h)).Append(' ');
double left = (_until[h] - now).TotalSeconds;
sb.Append(left > 0 ? $"{Math.Ceiling(left):0} s" : "off");
}
return sb.ToString();
}
}
/// <summary>
/// The effects this character's landing lines put on each target, by object id. Entries go when
/// every effect on them has run out. Locked: chat, the combat tick and the UI read it.
/// </summary>
internal sealed class DirtyFightingTracker
{
private const int MaxTargets = 64;
private readonly Dictionary<int, DfTargetEffects> _targets = new();
private readonly object _lock = new();
public void Landed(int targetId, int height, DateTime now)
{
if (targetId == 0 || height < DirtyFightingHeights.Low || height > DirtyFightingHeights.High) return;
lock (_lock)
{
if (!_targets.TryGetValue(targetId, out var fx))
{
if (_targets.Count >= MaxTargets) PruneLocked(now);
fx = new DfTargetEffects();
_targets[targetId] = fx;
}
fx.Landed(height, now);
}
}
/// <summary>A copy of the target's effects, or null when none are known.</summary>
public DfTargetEffects? Get(int targetId)
{
lock (_lock)
{
if (!_targets.TryGetValue(targetId, out var fx)) return null;
var copy = new DfTargetEffects();
for (int h = 0; h < 3; h++) copy.SetUntil(h, fx.Until(h));
return copy;
}
}
public void Forget(int targetId)
{
lock (_lock) _targets.Remove(targetId);
}
public void Clear()
{
lock (_lock) _targets.Clear();
}
public int Count
{
get { lock (_lock) return _targets.Count; }
}
private void PruneLocked(DateTime now)
{
var gone = new List<int>();
foreach (var kv in _targets)
if (!kv.Value.AnyOn(now)) gone.Add(kv.Key);
foreach (int id in gone) _targets.Remove(id);
// Still full (64 targets all carrying effects): drop the one that runs out first.
while (_targets.Count >= MaxTargets)
{
int oldest = 0;
DateTime best = DateTime.MaxValue;
foreach (var kv in _targets)
{
DateTime last = Max(kv.Value.Until(0), Max(kv.Value.Until(1), kv.Value.Until(2)));
if (last < best) { best = last; oldest = kv.Key; }
}
_targets.Remove(oldest);
}
}
private static DateTime Max(DateTime a, DateTime b) => a > b ? a : b;
}

View file

@ -0,0 +1,75 @@
using System;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Combat's wand swaps and the first cast after one (2026-11-11). Pure: the caller passes what is in
/// hand, the kinds (CombatMode values) and the times.
///
/// The report (Outdoor Hunt, a wand user): "wand swapping can't make up its mind to do in combat or
/// peacemode then there is a long pause between picking up the next target". Two causes in combat's
/// own equip, both for a new target that wants another wand than the one in hand:
///
/// * The swap. Only a swap away from a caster to a melee weapon or a launcher went through peace
/// (HandSwapSequence, 2026-10-23). A swap from one caster to another was the client's own use of
/// the new one. On ACE the old caster leaves the Held slot first (a Held caster needs both hands
/// empty), and a wielded item put into a pack in a combat mode first plays a forced change to bare
/// hands; the new caster then puts the character back into Magic. Every stance change goes through
/// peace, so the character went Magic, peace, bare hands, peace, Magic. From peace (Peace Mode When
/// Idle between hunt targets) combat also asked for Magic beside the use, which added a leg in front.
/// Now, with Fast Weapon Swap on, a swap away from a caster goes through peace whatever it is for:
/// peace (when not in it), the old caster into a pack (answered at once in peace), the new one into
/// the Held slot, then Magic, one leg each (<see cref="UseHandsSwap"/>).
///
/// * The first cast. AttackWithMagic held every cast for a flat 3 s after any wield, and each held
/// tick counted as an attack, so the next try came one attack interval later: the first spell at a
/// new target went 3-4.5 s after the wield although the wand was in hand and the stance up in about
/// 1 s (07:38:08.540 wield, Magic asked 07:38:08.924, casts skipped 09.814 and 11.314, cast 12.840,
/// "lock->attack 4734 ms ... interval 2954"). Now the cast goes once the client has read Magic for
/// <see cref="StanceSettleMs"/> since a change after the wield, and <see cref="StanceMinAfterRequestMs"/>
/// after the wield or after our own Magic request that followed it (BuffManager's stance settle,
/// 2026-10-05), never later than the old 3 s (<see cref="EquipCastHoldMs"/>), and a held tick is not
/// an attack.
/// </summary>
internal static class WandSwapRules
{
/// <summary>The old flat wait after a wield, still the longest the first cast waits.</summary>
public const double EquipGateMaxMs = 3000;
/// <summary>The client reads Magic this long before the first cast (BuffManager.StanceSettleMs).</summary>
public const double StanceSettleMs = 300;
/// <summary>The wield, or our own Magic request after it, this long before the first cast (BuffManager.StanceMinAfterRequestMs).</summary>
public const double StanceMinAfterRequestMs = 1000;
/// <summary>CombatMode.Magic (the kind a caster puts the character in).</summary>
private const int Magic = 8;
/// <summary>
/// True: combat's swap from <paramref name="inHand"/> to <paramref name="chosen"/> is the hands swap
/// through peace. Fast Weapon Swap on, a wield allowed (the swap tracker said swap), a caster in hand
/// (<paramref name="inHandKind"/> Magic) and another weapon chosen: a melee weapon, a launcher, or
/// (since 2026-11-11) another caster.
/// </summary>
public static bool UseHandsSwap(bool fastWeaponSwap, bool allowWield, int inHand, int chosen, int inHandKind)
=> fastWeaponSwap && allowWield && inHand != 0 && chosen != 0 && inHand != chosen && inHandKind == Magic;
/// <summary>
/// How long the first cast after a wield still waits (0 = cast now). Called only with the chosen
/// wand in hand and the client reading Magic. <paramref name="sinceEquipMs"/>: since the last wield
/// (negative or at least <see cref="EquipGateMaxMs"/>: no wait). <paramref name="sinceModeChangeMs"/>:
/// since the client's combat mode last changed (negative: never seen). <paramref name="sinceMagicRequestMs"/>:
/// since combat last asked for a stance (negative: never).
/// No mode change seen since the wield: the client may not have caught up with the server's stance
/// change yet, so the old wait stands.
/// </summary>
public static double EquipCastHoldMs(double sinceEquipMs, double sinceModeChangeMs, double sinceMagicRequestMs)
{
if (sinceEquipMs < 0 || sinceEquipMs >= EquipGateMaxMs) return 0;
double cap = EquipGateMaxMs - sinceEquipMs;
if (sinceModeChangeMs < 0 || sinceModeChangeMs >= sinceEquipMs) return cap;
// The client's mode field can flip before the server's stance animation has run (2026-10-05):
// the floor runs from the wield, or from our own request when one followed it.
double floorFrom = sinceMagicRequestMs >= 0 && sinceMagicRequestMs < sinceEquipMs ? sinceMagicRequestMs : sinceEquipMs;
double hold = Math.Max(StanceSettleMs - sinceModeChangeMs, StanceMinAfterRequestMs - floorFrom);
return Math.Clamp(hold, 0, cap);
}
}

View file

@ -1704,18 +1704,37 @@ public class WorldObjectCache
}
/// <summary>
/// Where a looted item goes: the main pack while it has a free slot, else the side pack
/// with the most room, 0 when nothing has room. The pickup used to be a UseObject, which
/// let the client pick the spot, but a use on a wearable item lying in a corpse is a
/// get-and-wield: jewellery for an empty slot went straight onto the character
/// (2026-10-02). A move needs an explicit target, and the engine refuses a move into a
/// full pack of ours, so this finds one with room.
/// Where a looted item goes: the main pack (the player) or 0. The pickup used to be a
/// UseObject, which let the client pick the spot, but a use on a wearable item lying in a
/// corpse is a get-and-wield: jewellery for an empty slot went straight onto the character
/// (2026-10-02). So it is a move, and a move from a corpse or chest can only go to the main
/// pack: the client refuses one straight into a side pack ("You must first pick up the X",
/// and nothing is sent), so the side-pack fallback this used to return when the main pack
/// was full never worked (2026-11-12: 75 such pickups in a week of logs, none landed; the
/// looter waited out 3 + 3 tries on each and left them).
/// <list type="bullet">
/// <item>The main pack has a free slot: the main pack.</item>
/// <item>It is full, and <paramref name="item"/> joins a stack you carry: the main pack anyway.
/// The client puts a stack onto a same-name stack with room wherever that is (the pea stacks
/// live in a side pack), so no slot is needed.</item>
/// <item>Otherwise 0: nothing can take it from the corpse (<see cref="SidePackHasRoom"/> tells
/// a full main pack from no room at all).</item>
/// </list>
/// </summary>
/// <remarks><paramref name="skip"/>: packs (or the player id, for the main pack) the server refused lately.</remarks>
/// <remarks><paramref name="skip"/>: packs (or the player id, for the main pack) the server refused lately;
/// a stack join needs no slot, so it goes whatever the main pack's mark.</remarks>
public static int FindLootDestination(IReadOnlyList<WorldObject> inv, int playerId, RynthCoreHost? host = null,
Func<int, bool>? skip = null)
Func<int, bool>? skip = null, WorldObject? item = null)
{
if (inv == null || playerId == 0) return 0;
if (item != null && JoinsCarriedStack(inv, playerId, item)) return playerId;
if (MainPackFreeSlots(inv, playerId, host) > 0 && !(skip != null && skip(playerId))) return playerId;
return 0;
}
/// <summary>The main pack's free item slots (102 less the loose items in it; packs, foci and worn items don't count).</summary>
public static int MainPackFreeSlots(IReadOnlyList<WorldObject> inv, int playerId, RynthCoreHost? host = null)
{
int mainUsed = 0; // same tally as FindPackFor
foreach (var p in inv)
{
@ -1725,8 +1744,35 @@ public class WorldObjectCache
if (host.HasValue && IsWieldable(p) && IsWieldedByPlayer(host.Value, p)) continue;
mainUsed++;
}
if (102 - mainUsed > 0 && !(skip != null && skip(playerId))) return playerId;
return FindPackFor(inv, playerId, includeMainPack: false, requireFree: 1, host, skip);
return 102 - mainUsed;
}
/// <summary>A side pack has a free slot (so a loot pickup that found no destination met a full main pack, not full packs).</summary>
public static bool SidePackHasRoom(IReadOnlyList<WorldObject> inv, int playerId, RynthCoreHost? host = null)
=> inv != null && playerId != 0 && FindPackFor(inv, playerId, includeMainPack: false, requireFree: 1, host) != 0;
/// <summary>
/// <paramref name="item"/> stacks and a stack of the same kind you carry (main pack or a side
/// pack) still has room for one more: a pickup aimed at the main pack joins it.
/// </summary>
internal static bool JoinsCarriedStack(IReadOnlyList<WorldObject> inv, int playerId, WorldObject item)
{
int max = RynthCore.Plugin.RynthAi.Loot.InventoryManager.GetMaxStackSize(item);
if (max <= 1 || string.IsNullOrEmpty(item.Name)) return false;
int wcid = item.Values(unchecked((int)DecalTypeKey), 0);
var packs = new HashSet<int>();
foreach (var p in inv)
if (p.Container == playerId && p.ObjectClass == AcObjectClass.Container) packs.Add(p.Id);
foreach (var s in inv)
{
if (s.Id == item.Id || s.ObjectClass == AcObjectClass.Container) continue;
if (s.Container != playerId && !packs.Contains(s.Container)) continue;
int sw = s.Values(unchecked((int)DecalTypeKey), 0);
bool same = wcid != 0 && sw != 0 ? sw == wcid : string.Equals(s.Name, item.Name, StringComparison.Ordinal);
if (!same) continue;
if (Math.Max(1, s.Values(LongValueKey.StackCount, 1)) < max) return true;
}
return false;
}
/// <summary>

View file

@ -854,6 +854,11 @@ public sealed partial class RynthAiPlugin
if (_targetCorpseId == 0 && _chestCandidateId != 0 && TryTakeOpenChest(settings, CorpseNowMs))
return;
// A chest that closed before the looter was done is opened again, before any corpse is
// claimed (opening a corpse would close it once more; RynthAiPlugin.ChestLoot.cs).
if (_targetCorpseId == 0 && _chestReopenId != 0 && TryReopenChest(settings, CorpseNowMs))
return;
// A named object (Loot by name) when no corpse is claimed and nothing is open.
if (_targetCorpseId == 0 && _lootNameTargetId != 0 && TryLootByName(settings, CorpseNowMs))
return;
@ -1936,7 +1941,7 @@ public sealed partial class RynthAiPlugin
LootDiag($"[RynthAi] {LootTag}: queuing 0x{(uint)firstMatchId:X8} '{matchItemName}' behind 0x{(uint)_settlingLootItemId:X8}'s Return.");
}
LootPickupResult pickup = SendLootPickup(firstMatchId, matchItemName, corpseId);
if (pickup == LootPickupResult.NoRoom || pickup == LootPickupResult.Refused)
if (pickup is LootPickupResult.NoRoom or LootPickupResult.Refused or LootPickupResult.MainPackFull)
return;
bool moved = pickup == LootPickupResult.Moved || pickup == LootPickupResult.Used;
@ -2354,13 +2359,19 @@ public sealed partial class RynthAiPlugin
private string LootPackName(int packId) =>
packId == unchecked((int)_playerId) ? "the main pack" : $"pack 0x{(uint)packId:X8}";
/// <summary>A pack other than the ones left out could take the item (the client's own counts).</summary>
/// <summary>
/// Somewhere other than the pack just tried could take the item (the client's own counts).
/// The only loot destination is the main pack (FindLootDestination), so after it this is a
/// stack join, and one already tried is not a new place to try.
/// </summary>
private bool HasOtherLootDestination()
{
if (_objectCache == null || _playerId == 0) return false;
long now = CorpseNowMs;
return WorldObjectCache.FindLootDestination(_objectCache.GetDirectInventory(forceRefresh: false),
unchecked((int)_playerId), Host, id => _packRefusals.IsRefused(id, now)) != 0;
int dest = WorldObjectCache.FindLootDestination(_objectCache.GetDirectInventory(forceRefresh: false),
unchecked((int)_playerId), Host, id => _packRefusals.IsRefused(id, now),
_objectCache[_currentLootItemId]);
return dest != 0 && dest != _currentLootItemDest;
}
/// <summary>The current item is done without its landing seen: watch for one that comes late.</summary>
@ -2469,9 +2480,13 @@ public sealed partial class RynthAiPlugin
internal const long PickupHoldMaxGapMs = 500;
/// <summary>Jump-loot for this pickup: the setting, the keyboard jump and the move call, stamina for
/// the jump, and no fight or heal it could delay (<see cref="JumpLootWouldDelayFight"/>).</summary>
/// the jump, and no fight or heal it could delay (<see cref="JumpLootWouldDelayFight"/>).
/// Never from a chest: the client closes a container once the character is outside its use
/// radius at its once-a-second check, and a hop (with the server's walk back for the next item)
/// can be that. A corpse is opened again for nothing; a chest costs a reopen, or its loot.</summary>
private bool ShouldJumpLoot(LegacyUiSettings settings) =>
settings.LootJumpEnabled
&& !IsChestLoot(_openedContainerId)
&& Host.HasTapJump
&& Host.HasMoveItemExternal
&& _vitals.CurrentStamina > 5
@ -2802,11 +2817,17 @@ public sealed partial class RynthAiPlugin
{
_packRefusals.Refuse(dest, now, confirmed, _currentLootItemId);
if (confirmed && !_currentLootItemFullPacks.Contains(dest)) _currentLootItemFullPacks.Add(dest);
if (!_currentLootItemPackRetried && (confirmed || HasOtherLootDestination()))
// Another round only where there is somewhere else to go. Loot goes only to the main
// pack (FindLootDestination), so after it there is at most a stack join: an item
// refused there for room is given up below, not sent round again into nothing.
bool another = !_currentLootItemPackRetried && HasOtherLootDestination();
LootDiag(confirmed
? $"[RynthAi] {LootTag}: {LootPackName(dest)} took none of {_currentLootItemMoveAttempts} tries for 0x{(uint)_currentLootItemId:X8} (the server refused {_currentLootItemDestRefusals} after the pickup ran); treating it as full for {RynthCore.Plugin.RynthAi.Loot.PackRefusals.HoldMs / 60_000} min" +
(another ? " and trying another pack." : "; there is nowhere else to put it.")
: $"[RynthAi] {LootTag}: {LootPackName(dest)} took none of {_currentLootItemMoveAttempts} tries for 0x{(uint)_currentLootItemId:X8} ({_currentLootItemDestTimeouts} unanswered in {answerWaitMs} ms, {_currentLootItemDestRefusals} refused)" +
(another ? "; trying another pack for this item only (not known to be full)." : "; there is nowhere else to try it."));
if (another)
{
LootDiag(confirmed
? $"[RynthAi] {LootTag}: {LootPackName(dest)} took none of {_currentLootItemMoveAttempts} tries for 0x{(uint)_currentLootItemId:X8} (the server refused {_currentLootItemDestRefusals} after the pickup ran); treating it as full for {RynthCore.Plugin.RynthAi.Loot.PackRefusals.HoldMs / 60_000} min and trying another pack."
: $"[RynthAi] {LootTag}: {LootPackName(dest)} took none of {_currentLootItemMoveAttempts} tries for 0x{(uint)_currentLootItemId:X8} ({_currentLootItemDestTimeouts} unanswered in {answerWaitMs} ms, {_currentLootItemDestRefusals} refused); trying another pack for this item only (not known to be full).");
_currentLootItemPackRetried = true;
_currentLootItemMoveAttempts = 0;
_currentLootItemDestRefusals = 0;
@ -2818,16 +2839,21 @@ public sealed partial class RynthAiPlugin
}
LootDiag($"[RynthAi] {LootTag}: pickup failed for 0x{(uint)_currentLootItemId:X8}; container remained 0x{(uint)_openedContainerId:X8} after {_currentLootItemMoveAttempts} attempt(s)" +
(lastTry.Length > 0 ? $" (last: {lastTry})." : "."));
// Refused for room in every pack it tried (two or more), and in none of them for
// another item: the server is refusing this item, not the packs (a pickup timer that
// says no more than a full pack does, 2026-11-01). Its marks go with it, or the next
// item finds no pack and is selected and never picked up.
if (_currentLootItemFullPacks.Count >= 2)
// Refused for room in every place it could go, and in none of them for another item:
// the server is refusing this item, not the packs (a pickup timer that says no more
// than a full pack does, 2026-11-01). Its marks go with it, or the next item finds
// nowhere to go and is left, corpse after corpse. Loot goes only to the main pack now
// (FindLootDestination), so that is the one place: a second item refused there as
// well keeps the mark (PackRefusals), and then it is the pack.
if (_currentLootItemFullPacks.Count >= 2 || (_currentLootItemFullPacks.Count == 1 && !HasOtherLootDestination()))
{
List<int> back = _packRefusals.Withdraw(_currentLootItemId, now);
if (back.Count > 0)
LootDiag($"[RynthAi] {LootTag}: the server refused 0x{(uint)_currentLootItemId:X8} in {_currentLootItemFullPacks.Count} packs the client counts room in: it is refusing the item, not the packs; " +
$"{string.Join(" and ", back.Select(LootPackName))} {(back.Count == 1 ? "is" : "are")} no longer treated as full.");
LootDiag(_currentLootItemFullPacks.Count >= 2
? $"[RynthAi] {LootTag}: the server refused 0x{(uint)_currentLootItemId:X8} in {_currentLootItemFullPacks.Count} packs the client counts room in: it is refusing the item, not the packs; " +
$"{string.Join(" and ", back.Select(LootPackName))} {(back.Count == 1 ? "is" : "are")} no longer treated as full."
: $"[RynthAi] {LootTag}: the server refused 0x{(uint)_currentLootItemId:X8} for room in {LootPackName(back[0])}, the only place loot can go, though the client counts room there: " +
$"taken as refusing the item, not the pack, so {LootPackName(back[0])} is no longer treated as full (unless another item is refused there too).");
}
_processedCorpseItems.Add(_currentLootItemId);
ResetCurrentLootItem();
@ -2851,7 +2877,7 @@ public sealed partial class RynthAiPlugin
long refusedAfter = refused ? _currentLootItemRefusedAt - _currentLootItemMoveRequestedAt : 0;
uint refusal = _currentLootItemRefusalError;
LootPickupResult retry = SendLootPickup(_currentLootItemId, _currentLootItemName, _openedContainerId);
if (retry == LootPickupResult.NoRoom || retry == LootPickupResult.Refused)
if (retry is LootPickupResult.NoRoom or LootPickupResult.Refused or LootPickupResult.MainPackFull)
return; // SendLootPickup finished the item / corpse
bool retried = retry == LootPickupResult.Moved || retry == LootPickupResult.Used;
if (freeRetry)
@ -2929,7 +2955,7 @@ public sealed partial class RynthAiPlugin
_currentLootItemDest = to;
if (!_currentLootItemDestsTried.Contains(to)) _currentLootItemDestsTried.Add(to);
}
if (ownCorpse && r == LootPickupResult.NoRoom)
if (ownCorpse && r is LootPickupResult.NoRoom or LootPickupResult.MainPackFull)
{
PauseOwnCorpseNoRoom(corpseId, itemName);
return r;
@ -2950,10 +2976,29 @@ public sealed partial class RynthAiPlugin
_processedCorpseItems.Add(itemId);
ResetCurrentLootItem();
break;
case LootPickupResult.MainPackFull:
// This item only: a stack the next item joins still goes, and so does everything
// once the main pack has a slot again (RynthSort or cram moving things out of it).
LootDiag($"[RynthAi] {LootTag}: leaving '{itemName}' 0x{(uint)itemId:X8} on 0x{(uint)corpseId:X8} — the main pack is full, it joins no stack you carry, and the client takes nothing from a corpse or chest straight into a side pack.");
WarnMainPackFull(itemName);
_processedCorpseItems.Add(itemId);
ResetCurrentLootItem();
break;
}
return r;
}
private DateTime _mainPackFullWarnedAt = DateTime.MinValue;
/// <summary>Once per 5 minutes in chat: the main pack is full, so loot is being left (looting goes on).</summary>
private void WarnMainPackFull(string itemName)
{
if ((RynthClock.Now - _mainPackFullWarnedAt).TotalMinutes < 5) return;
_mainPackFullWarnedAt = RynthClock.Now;
ChatLine($"[RynthAi] Main pack full: '{itemName}' is left. AC loots only into the main pack (or onto a stack you already carry), " +
"not straight into a side pack. Move items out of the main pack (RynthSort, cram) and looting takes everything again.");
}
/// <summary>
/// The current pickup is done as far as the item goes (<paramref name="answered"/>: the
/// server's answer was seen; false: it left the corpse and the wait for it ran out). The
@ -3162,6 +3207,13 @@ public sealed partial class RynthAiPlugin
return true;
}
// A chest that closed before the looter was done, to be opened again.
if (HasChestReopenWork())
{
_lootWorkWhy = "a chest to open again";
return true;
}
// A named object in range (Loot by name, RynthAiPlugin.LootByName.cs): used so the client walks there.
if (HasLootNameWork(settings, CorpseNowMs))
{

View file

@ -0,0 +1,93 @@
// ============================================================================
// RynthAi - Dashboard/BuffHalo.cs
// The Buffing key's icon, "Halo" (picked 2026-11-10 over Ascend, Aura and
// Crystal; the mock-ups are the artifact "Buffing Key Icons"). A four-point
// star in a sigil ring, drawn with the draw list rather than a font glyph so
// the icon itself says what buffing is doing, not only the key's LED:
// Off a hollow star in a dotted ring: buffing is off.
// On a solid star in a faint ring with four ticks, over a faint
// violet glow: buffing is on, nothing to cast.
// Casting On, and a light runs round the ring while the star breathes:
// RynthAi is casting buffs right now (the activity reads Buffing).
// Drawn on a 15 px em (IconKit) and scaled to the em asked for.
// Render thread; allocates nothing.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using static RynthCore.Plugin.RynthAi.Dashboard.IconKit;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthAi.Dashboard;
internal static class BuffHalo
{
internal enum Look { Off, On, Casting }
// The buffing colour (the activity line's violet), the running light's paler violet, white.
private static readonly uint Violet = Argb(0xFFC5ABF4), Light = Argb(0xFFE9DFFF), White = Argb(0xFFFFFFFF);
// The design, in pixels at a 15 px em.
private const float RingR = 6.8f, TickIn = 6.0f, TickOut = 7.6f;
private const float StarR = 5.4f, OffStarR = 4.8f, Waist = 0.6f; // Waist: the curves' control point, from the centre
private const float GlowR = 6.0f, DotR = 0.5f;
private const int RingDots = 12;
// While casting: the light goes round 0.8 times a second, its tail a third of the ring; the
// star swells and shrinks 8% at 1.4 Hz.
private const float TurnsPerSecond = 0.8f, TailSpan = MathF.Tau * 0.34f, BreathHz = 1.4f, Breath = 0.08f;
private const int TailSegments = 16;
private const float HeadR = 1.9f, HeadWaist = 0.2f;
/// <summary>
/// Draws the halo centred on <paramref name="centre"/>, <paramref name="em"/> pixels across, in
/// <paramref name="color"/> (the key's icon colour). <paramref name="glow"/> adds the violet glow
/// under the star (the key has it; the activity line, already violet, doesn't).
/// </summary>
public static void Draw(ImDrawListPtr dl, Vector2 centre, float em, uint color, Look look, bool glow = true)
{
float s = em / DesignEm;
float line = MathF.Max(1f, s);
Span<Vector2> pts = stackalloc Vector2[StarPoints];
if (look == Look.Off)
{
int n = Star(pts, centre, OffStarR * s, Waist * s);
dl.AddPolyline(ref pts[0], n, color, ImDrawFlags.Closed, line);
uint dot = Alpha(color, 0.5f);
float dotR = MathF.Max(0.55f, DotR * s);
for (int i = 0; i < RingDots; i++)
{
float a = (i + 0.5f) * MathF.Tau / RingDots;
dl.AddCircleFilled(centre + Dir(a) * (RingR * s), dotR, dot, 6);
}
return;
}
bool casting = look == Look.Casting;
float t = Clock();
float swell = casting ? 1f + Breath * MathF.Sin(t * MathF.Tau * BreathHz) : 1f;
if (glow) Glow(dl, centre, GlowR * s, Violet, casting ? 0.09f : 0.05f);
dl.AddCircle(centre, RingR * s, Alpha(color, 0.4f), 32, line);
for (int k = 0; k < 4; k++)
{
Vector2 d = Dir(MathF.PI / 4 + k * MathF.PI / 2);
dl.AddLine(centre + d * (TickIn * s), centre + d * (TickOut * s), color, 1.2f * line);
}
int count = Star(pts, centre, StarR * s * swell, Waist * s * swell);
dl.AddConcavePolyFilled(ref pts[0], count, color);
if (!casting) return;
// The running light: a head and a tail that fades behind it, then a small white star on the head.
float head = (t * TurnsPerSecond % 1f) * MathF.Tau;
float step = TailSpan / TailSegments;
for (int j = 0; j < TailSegments; j++)
{
float a1 = head - j * step;
dl.PathArcTo(centre, RingR * s, a1 - step - 0.03f, a1, 3);
dl.PathStroke(Alpha(Light, MathF.Pow(1f - j / (float)TailSegments, 1.6f)), ImDrawFlags.None, 1.6f * line);
}
FillStar(dl, centre + Dir(head) * (RingR * s), HeadR * s, HeadWaist * s, White);
}
}

View file

@ -0,0 +1,189 @@
// ============================================================================
// RynthAi - Dashboard/CombatCrossed.cs
// The Combat key's icon, "Crossed" (picked 2026-11-11 over Sigil, Lock-on and
// Swing; the mock-ups are the artifact "Combat Key Icons"). Two crossed
// weapons for the stance the character is in:
// melee crossed swords; fighting, they knock together and throw sparks.
// missile crossed arrows; fighting, they loose outward with speed lines.
// magic crossed wands; fighting, the orbs flare blue and a spark jumps
// between them.
// Off is hollow (blades, heads, orbs drawn in outline); On is solid over a
// faint glow; Fighting (the activity reads Combat) moves, about 1.3 times a
// second. Drawn on a 15 px em (IconKit) and scaled to the em asked for.
// Render thread; allocates nothing.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using static RynthCore.Plugin.RynthAi.Dashboard.IconKit;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthAi.Dashboard;
internal static class CombatCrossed
{
internal enum Look { Off, On, Fighting }
// The combat red (the activity line's) and its light, the mana blue and its light, white.
private static readonly uint Red = Argb(0xFFF98075), RedLight = Argb(0xFFFFD6CF), SparkCore = Argb(0xFFFFEBE7),
Blue = Argb(0xFF7FB9F9), BlueLight = Argb(0xFFDCEBFF), White = Argb(0xFFFFFFFF);
private const float ClashHz = 1.3f, ClashShare = 0.32f; // a knock 1.3 times a second, lasting 32% of the cycle
private const float MinStarK = 0.08f; // the knock's star starts here: smaller, it would be a degenerate polygon to fill
private const float Up = -MathF.PI / 2, Right = -MathF.PI / 4, Left = -3 * MathF.PI / 4; // up-right and up-left
/// <summary>
/// Draws the crossed weapons for <paramref name="stance"/> (the client's combat mode: Melee,
/// Missile or Magic; anything else draws swords) centred on <paramref name="centre"/>,
/// <paramref name="em"/> pixels across, in <paramref name="color"/>. <paramref name="glow"/> adds the
/// faint glow under them (the key has it; the activity line doesn't).
/// </summary>
public static void Draw(ImDrawListPtr dl, Vector2 centre, float em, uint color, Look look, int stance, bool glow = true)
{
float s = em / DesignEm;
float line = MathF.Max(1f, s);
float t = Clock();
// The knock: 0 most of the cycle, rising to 1 and back over its first third.
float k = 0f;
if (look == Look.Fighting)
{
float ph = t * ClashHz % 1f;
if (ph < ClashShare) k = MathF.Sin(ph / ClashShare * MathF.PI);
}
switch (stance)
{
case CombatMode.Missile: Arrows(dl, centre, s, line, color, look, k, glow); break;
case CombatMode.Magic: Wands(dl, centre, s, line, color, look, k, glow, t); break;
default: Swords(dl, centre, s, line, color, look, k, glow); break;
}
}
// ── Melee: crossed swords ──────────────────────────────────────────
private static void Swords(ImDrawListPtr dl, Vector2 c, float s, float line, uint color, Look look, float k, bool glow)
{
bool solid = look != Look.Off;
if (solid && glow) Glow(dl, c + new Vector2(0, -1.5f) * s, 5.5f * s, Red, look == Look.Fighting ? 0.04f + 0.12f * k : 0.035f);
float kick = 0.08f * k; // the blades knock apart a little
Vector2 o = c + new Vector2(0, 0.6f) * s;
Sword(dl, o, Right - kick, s, line, color, solid);
Sword(dl, o, Left + kick, s, line, color, solid);
if (k <= 0f) return;
// Sparks where the blades meet: five rays thrown upward and a star.
Vector2 at = c + new Vector2(0, -2.3f) * s;
uint ray = Alpha(RedLight, k);
ReadOnlySpan<float> rays = stackalloc float[] { 0f, -0.75f, 0.75f, -1.45f, 1.45f };
foreach (float da in rays)
{
Vector2 d = Dir(Up + da);
dl.AddLine(at + d * ((1.8f + 1.6f * k) * s), at + d * ((2.6f + 2.4f * k) * s), ray, 1.1f * line);
}
if (k > MinStarK) FillStar(dl, at, 2.4f * k * s, 0.3f * s, SparkCore);
}
/// <summary>A sword from <paramref name="o"/> along angle <paramref name="a"/>: blade (solid or outlined), guard, grip and pommel.</summary>
private static void Sword(ImDrawListPtr dl, Vector2 o, float a, float s, float line, uint color, bool solid)
{
// Slim, with the guards well below the crossing: at 15 px wider blades and guards near the
// middle drew a second X under the first (seen on the test client, 2026-11-11).
const float Tip = 7.4f, Guard = -3.6f, Pommel = -6.7f, GuardW = 1.9f, W = 0.85f;
Span<Vector2> blade = stackalloc Vector2[5];
blade[0] = o + Turn(Guard, -W, a) * s;
blade[1] = o + Turn(Tip - 2.3f * W, -W, a) * s;
blade[2] = o + Turn(Tip, 0, a) * s;
blade[3] = o + Turn(Tip - 2.3f * W, W, a) * s;
blade[4] = o + Turn(Guard, W, a) * s;
if (solid) dl.AddConvexPolyFilled(ref blade[0], 5, color);
else dl.AddPolyline(ref blade[0], 5, color, ImDrawFlags.Closed, line);
dl.AddLine(o + Turn(Guard, -GuardW, a) * s, o + Turn(Guard, GuardW, a) * s, color, 1.25f * line);
dl.AddLine(o + Turn(Guard, 0, a) * s, o + Turn(Pommel + 0.9f, 0, a) * s, color, 1.15f * line);
Vector2 pommel = o + Turn(Pommel, 0, a) * s;
if (solid) dl.AddCircleFilled(pommel, 0.95f * s, color, 10);
else dl.AddCircle(pommel, 0.85f * s, color, 10, line);
}
// ── Missile: crossed arrows ────────────────────────────────────────
private static void Arrows(ImDrawListPtr dl, Vector2 c, float s, float line, uint color, Look look, float k, bool glow)
{
bool solid = look != Look.Off;
if (solid && glow) Glow(dl, c + new Vector2(0, -1f) * s, 5.5f * s, Red, look == Look.Fighting ? 0.04f + 0.12f * k : 0.035f);
float push = 1.6f * k; // loosed: each arrow slides out along its shaft
uint streak = Alpha(RedLight, k);
Span<float> angles = stackalloc float[] { Right, Left };
foreach (float a in angles)
{
Vector2 o = c + (new Vector2(0, 0.5f) + Dir(a) * push) * s;
Arrow(dl, o, a, s, line, color, solid);
if (k <= 0f) continue;
for (int side = -1; side <= 1; side += 2)
dl.AddLine(o + Turn(1.2f, 1.5f * side, a) * s, o + Turn(3.6f, 1.5f * side, a) * s, streak, line);
}
}
/// <summary>An arrow from <paramref name="o"/> along angle <paramref name="a"/>: shaft, barbed head (solid or outlined), two pairs of fletching.</summary>
private static void Arrow(ImDrawListPtr dl, Vector2 o, float a, float s, float line, uint color, bool solid)
{
const float Tip = 7.0f, Tail = -7.0f;
dl.AddLine(o + Turn(Tail, 0, a) * s, o + Turn(Tip - 2.4f, 0, a) * s, color, 1.15f * line);
Span<Vector2> head = stackalloc Vector2[4];
head[0] = o + Turn(Tip, 0, a) * s;
head[1] = o + Turn(Tip - 3.1f, -1.8f, a) * s;
head[2] = o + Turn(Tip - 2.3f, 0, a) * s;
head[3] = o + Turn(Tip - 3.1f, 1.8f, a) * s;
if (solid) dl.AddConcavePolyFilled(ref head[0], 4, color);
else dl.AddPolyline(ref head[0], 4, color, ImDrawFlags.Closed, line);
for (int f = 0; f < 2; f++)
{
float u = Tail + 1.6f * f;
Vector2 root = o + Turn(u, 0, a) * s;
dl.AddLine(root, o + Turn(u - 1.5f, -1.5f, a) * s, color, 1.05f * line);
dl.AddLine(root, o + Turn(u - 1.5f, 1.5f, a) * s, color, 1.05f * line);
}
}
// ── Magic: crossed wands ───────────────────────────────────────────
private static void Wands(ImDrawListPtr dl, Vector2 c, float s, float line, uint color, Look look, float k, bool glow, float t)
{
const float Tip = 6.1f, Pommel = -7.0f;
bool solid = look != Look.Off;
Vector2 o = c + new Vector2(0, 0.6f) * s;
Vector2 orbR = o + Dir(Right) * (Tip * s), orbL = o + Dir(Left) * (Tip * s);
if (solid && glow) Glow(dl, c + new Vector2(0, -1f) * s, 5.5f * s, Blue, look == Look.Fighting ? 0.04f + 0.1f * k : 0.035f);
if (k > 0f)
{
Glow(dl, orbR, 3.2f * s, Blue, 0.16f * k);
Glow(dl, orbL, 3.2f * s, Blue, 0.16f * k);
}
float orb = 1.75f * (1f + 0.3f * k) * s;
Wand(dl, o, Right, Tip, Pommel, orb, s, line, color, solid);
Wand(dl, o, Left, Tip, Pommel, orb, s, line, color, solid);
if (k <= 0f) return;
// The spark: a jagged line from orb to orb, its kinks new each knock, and a star above.
Span<Vector2> bolt = stackalloc Vector2[5];
int knock = (int)(t * ClashHz);
bolt[0] = orbL;
for (int i = 1; i < 4; i++)
{
double r = Math.Abs(Math.Sin(knock * 12.9898 + i * 78.233) * 43758.5453 % 1.0);
Vector2 p = Vector2.Lerp(orbL, orbR, i / 4f);
bolt[i] = p + new Vector2(0, (-2.0f + 2.4f * (float)r) * s);
}
bolt[4] = orbR;
dl.AddPolyline(ref bolt[0], 5, Alpha(BlueLight, k), ImDrawFlags.None, 1.1f * line);
FillStar(dl, new Vector2(c.X, orbL.Y - 2.3f * s), (1.6f * k + 0.4f) * s, 0.2f * s, Alpha(White, k));
}
/// <summary>A wand from <paramref name="o"/> along angle <paramref name="a"/>: shaft, collar, orb (solid or ringed) and a pommel bead.</summary>
private static void Wand(ImDrawListPtr dl, Vector2 o, float a, float tip, float pommel, float orb, float s, float line, uint color, bool solid)
{
dl.AddLine(o + Turn(pommel, 0, a) * s, o + Turn(tip - 2.0f, 0, a) * s, color, 1.35f * line);
dl.AddLine(o + Turn(tip - 2.5f, -1.2f, a) * s, o + Turn(tip - 2.5f, 1.2f, a) * s, color, 1.1f * line);
Vector2 c = o + Turn(tip, 0, a) * s;
if (solid) dl.AddCircleFilled(c, orb, color, 12);
else dl.AddCircle(c, orb, color, 12, line);
dl.AddCircleFilled(o + Turn(pommel, 0, a) * s, 0.8f * s, color, 8);
}
}

View file

@ -36,6 +36,8 @@ internal sealed class DashboardPrefs
private static string EngineStatePath => Path.Combine(Folder, "rynthai_avalonia.cache");
private volatile bool _minimized, _showTarget = true, _showVitals = true;
// The activity line, the FPS + timers footer and the Report key: shown unless turned off (options menu).
private volatile bool _showActivity = true, _showFooter = true, _showReport = true;
private volatile string _left = string.Empty, _right = string.Empty;
private volatile string[] _moved = Array.Empty<string>();
private volatile bool _dirty;
@ -48,6 +50,13 @@ internal sealed class DashboardPrefs
public void SetShowTarget(bool v) { _showTarget = v; _dirty = true; }
public void SetShowVitals(bool v) { _showVitals = v; _dirty = true; }
public bool ShowActivity => _showActivity;
public bool ShowFooter => _showFooter;
public bool ShowReport => _showReport;
public void SetShowActivity(bool v) { _showActivity = v; _dirty = true; }
public void SetShowFooter(bool v) { _showFooter = v; _dirty = true; }
public void SetShowReport(bool v) { _showReport = v; _dirty = true; }
/// <summary>The drawer is on the right edge now (its start side, or the other one when moved).</summary>
public bool OnRight(string key) => StartsRight(key) != (Array.IndexOf(_moved, key) >= 0);
@ -105,6 +114,9 @@ internal sealed class DashboardPrefs
case "minimized": p._minimized = on; break;
case "target": p._showTarget = on; break;
case "vitals": p._showVitals = on; break;
case "activity": p._showActivity = on; break;
case "footer": p._showFooter = on; break;
case "report": p._showReport = on; break;
case "left": p._left = IsDrawer(value) ? value : string.Empty; break;
case "right": p._right = IsDrawer(value) ? value : string.Empty; break;
case "drawer": legacyDrawer = value; break; // before 2026-10-21's two sides
@ -152,6 +164,9 @@ internal sealed class DashboardPrefs
"minimized=" + (_minimized ? 1 : 0) + "\n" +
"target=" + (_showTarget ? 1 : 0) + "\n" +
"vitals=" + (_showVitals ? 1 : 0) + "\n" +
"activity=" + (_showActivity ? 1 : 0) + "\n" +
"footer=" + (_showFooter ? 1 : 0) + "\n" +
"report=" + (_showReport ? 1 : 0) + "\n" +
"left=" + _left + "\n" +
"right=" + _right + "\n" +
"moved=" + string.Join(",", _moved) + "\n");

View file

@ -0,0 +1,85 @@
// ============================================================================
// RynthAi - Dashboard/IconKit.cs
// What the dashboard's drawn key icons share (BuffHalo, CombatCrossed,
// NavTrail): the clock they animate by, directions, alpha and mix, the soft
// glow and the four-point star. Render thread; allocates nothing.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthAi.Dashboard;
internal static class IconKit
{
/// <summary>The icons are drawn on a 15 px em (the keys' icon size) and scaled to the em asked for.</summary>
internal const float DesignEm = 15f;
private const int CurveSteps = 6;
/// <summary>The points <see cref="Star"/> writes (4 sides).</summary>
internal const int StarPoints = 4 * CurveSteps;
/// <summary>ImGui's clock in seconds, wrapped so the float keeps its precision in a long session.</summary>
internal static float Clock() => (float)(ImGui.GetTime() % 3600.0);
internal static Vector2 Dir(float a) => new(MathF.Cos(a), MathF.Sin(a));
/// <summary>(u, v) turned to angle <paramref name="a"/>: u runs along the angle, v across it.</summary>
internal static Vector2 Turn(float u, float v, float a)
{
float c = MathF.Cos(a), s = MathF.Sin(a);
return new Vector2(u * c - v * s, u * s + v * c);
}
internal static uint Alpha(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
/// <summary>ABGR mix: <paramref name="t"/> of the way from <paramref name="a"/> to <paramref name="b"/>, <paramref name="a"/>'s alpha.</summary>
internal static uint Mix(uint a, uint b, float t)
{
static uint Ch(uint c, int s) => (c >> s) & 0xFF;
uint r = (uint)MathF.Round(Ch(a, 0) + (Ch(b, 0) - (float)Ch(a, 0)) * t);
uint g = (uint)MathF.Round(Ch(a, 8) + (Ch(b, 8) - (float)Ch(a, 8)) * t);
uint bl = (uint)MathF.Round(Ch(a, 16) + (Ch(b, 16) - (float)Ch(a, 16)) * t);
return (a & 0xFF000000) | (bl << 16) | (g << 8) | r;
}
/// <summary>A soft glow: four discs of <paramref name="color"/> at <paramref name="alpha"/>, each a fifth smaller.</summary>
internal static void Glow(ImDrawListPtr dl, Vector2 c, float r, uint color, float alpha)
{
uint g = Alpha(color, alpha);
for (int i = 0; i < 4; i++) dl.AddCircleFilled(c, r * (1f - i * 0.2f), g, 24);
}
/// <summary>
/// A four-point star, tip up, with concave sides (one quadratic curve each, its control point
/// <paramref name="waist"/> from the centre). Writes <see cref="StarPoints"/> points; returns the count.
/// </summary>
internal static int Star(Span<Vector2> pts, Vector2 c, float r, float waist)
{
int n = 0;
for (int i = 0; i < 4; i++)
{
float a = -MathF.PI / 2 + i * (MathF.PI / 2);
Vector2 p0 = c + Dir(a) * r;
Vector2 cp = c + Dir(a + MathF.PI / 4) * waist;
Vector2 p1 = c + Dir(a + MathF.PI / 2) * r;
// p0 and the curve up to p1; p1 is the next side's first point.
for (int k = 0; k < CurveSteps; k++)
{
float u = k / (float)CurveSteps, v = 1f - u;
pts[n++] = v * v * p0 + 2f * v * u * cp + u * u * p1;
}
}
return n;
}
/// <summary>A filled star (see <see cref="Star"/>).</summary>
internal static void FillStar(ImDrawListPtr dl, Vector2 c, float r, float waist, uint color)
{
Span<Vector2> pts = stackalloc Vector2[StarPoints];
int n = Star(pts, c, r, waist);
dl.AddConcavePolyFilled(ref pts[0], n, color);
}
}

View file

@ -18,9 +18,22 @@
// the meta's state.
// controls RUN / STOP, the five subsystem keys (lit LED = on; right-click:
// their settings), then RynthSort's auto-sort key (when it's loaded;
// right-click: its window) and Force rebuff.
// right-click: its window) and Force rebuff. The Buffing key's icon
// is the Halo (BuffHalo.cs): off, on, or running while it casts. The
// Combat key's is Crossed (CombatCrossed.cs): swords, arrows or wands
// for the stance, off, on, or moving while it fights. The Navigation
// key's is Trail (NavTrail.cs): a shape for the route type, follow,
// dungeon patrol or Outdoor Hunt, its marker running while it walks;
// green over a green lane with Boost Nav Priority.
// The Looting key's is the Chest (LootChest.cs): off, on, gold with
// Boost Loot Priority, its lid popping while it loots. The Meta key's is
// States (MetaStates.cs): the current state ringed, a token hopping
// while the macro runs, the ring moving on with a burst when the
// state changes. The auto-sort key's is the Grid (SortGrid.cs): a
// pack's slots, an item arcing to its place while RynthSort moves items.
// launchers a tray of window buttons (lit while open), labels when wide.
// footer FPS (coloured by rate), RynthAi's version, bot and client uptime.
// report a full-width "Report a problem" key: RynthCore's panel (/rc report).
// bars the vitals and the target (15 segments, coloured by health).
// Minimized keeps the header, the activity line, the controls and the bars.
// Drawers on the edges, docked or popped out: Ranges, Loaded files, Patrol and the Mini
@ -73,6 +86,8 @@ internal interface IDashboardHost
void SetLootMode(int mode);
/// <summary>RynthSort's auto-sort: -1 RynthSort not loaded (or not logged in, or too old to say), 0 off, 1 on.</summary>
int AutoSort { get; }
/// <summary>RynthSort is moving items right now (the auto-sort key's sorting look).</summary>
bool AutoSortMoving { get; }
/// <summary>Fight the monster I select (combat setting), for the options menu's toggle.</summary>
bool FightSelectedTarget { get; }
void SetAutoSort(bool on);
@ -84,11 +99,22 @@ internal interface IDashboardHost
bool HuntActive { get; }
/// <summary>The small Outdoor Hunt window (its two distances) open or closed.</summary>
void ToggleHuntPanel();
/// <summary>The Dirty Fighting window (the rotation's settings) open or closed, and whether the rotation is on.</summary>
void ToggleDfHeightPanel();
bool DfHeightRotation { get; }
void ToggleSpells();
/// <summary>The Active Gear window (worn items' magic, mana and time left) open or closed.</summary>
void ToggleActiveGear();
/// <summary>The Timed Commands window (commands sent every N seconds) open or closed.</summary>
void ToggleTimedCommands();
/// <summary>The Classic (retail) look: RynthCore's own face comes back for it.</summary>
void UseClassicLook();
/// <summary>The Mini Remote, drawn into the current window; the size it wants.</summary>
bool DrawMiniRemote(out Vector2 want);
/// <summary>A Loaded files row's file (kind: SelectProfile's numbers): its name, path and unsaved changes. Any thread.</summary>
ProfileFileInfo ProfileInfo(int kind);
/// <summary>A profile button (Save, Save As, New, ...), run on the tick; its line goes to chat and to <paramref name="done"/>.</summary>
void ProfileAction(int kind, ProfileVerb verb, string name, bool replace, Action<ProfileResult> done);
}
internal sealed unsafe class InstrumentDashboard
@ -110,7 +136,7 @@ internal sealed unsafe class InstrumentDashboard
private const float TrayH = 24, FootH = 12;
private const float Chip = 18, ChipGap = 1;
private const float VitalH = 12, VitalGap = 3, VitalLabelW = 16, VitalNumW = 62, VitalColGap = 7, BarH = 6;
private const float TabW = 19, TabH = 22, TabGap = 2, TabsTop = 30, DrawerW = 216;
private const float TabW = 19, TabH = 22, TabGap = 2, TabsTop = 30, DrawerW = 216, FilesDrawerW = 240;
// ── Colours (ABGR), read once a frame ────────────────────────────────
@ -159,6 +185,7 @@ internal sealed unsafe class InstrumentDashboard
_popped = popped;
_k = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f);
_r = _d.Read();
NoteMetaState();
ReadColors();
DashboardPrefs prefs = _d.Prefs;
@ -179,15 +206,26 @@ internal sealed unsafe class InstrumentDashboard
float y = origin.Y + Px(PadTop);
y = Header(dl, prefs, x0, y, w);
y += Px(Gap);
y = Readout(dl, x0, y, w);
y += Px(Gap);
if (prefs.ShowActivity)
{
y = Readout(dl, x0, y, w);
y += Px(Gap);
}
y = Controls(dl, x0, y, w);
if (!prefs.Minimized)
{
y += Px(Gap);
y = Launchers(dl, prefs, x0, y, w);
y += Px(Gap);
y = Footer(dl, x0, y, w);
if (prefs.ShowFooter)
{
y += Px(Gap);
y = Footer(dl, x0, y, w);
}
if (prefs.ShowReport)
{
y += Px(Gap);
y = ReportKey(dl, x0, y, w);
}
}
if (prefs.ShowVitals || prefs.ShowTarget)
y = Bars(dl, prefs, origin.X, width, x0, y, w);
@ -355,7 +393,18 @@ internal sealed unsafe class InstrumentDashboard
dl.PushClipRect(min + new Vector2(Px(3), 0), max - new Vector2(Px(3), 0), true);
if (icon.Length > 0)
{
DrawIcon(dl, icon, new Vector2(tx, y), new Vector2(Px(11), h), Px(11), color);
// Buffing, Combat, Navigating and Looting: their keys' drawn icons, moving, in the line's colour.
Vector2 ic = new(tx + Px(11) * 0.5f, y + h * 0.5f);
if (activity == BuffManager.LabelBuffing)
BuffHalo.Draw(dl, ic, Px(11), color, BuffHalo.Look.Casting, glow: false);
else if (activity == CombatActivity)
CombatCrossed.Draw(dl, ic, Px(11), color, CombatCrossed.Look.Fighting, _r.CombatStance, glow: false);
else if (activity == NavActivity)
NavTrail.Draw(dl, ic, Px(11), color, NavTrail.Look.Moving, _r.NavKind, _r.NavPriority, glow: false);
else if (activity == LootActivity)
LootChest.Draw(dl, ic, Px(11), color, LootChest.Look.Looting, _r.BoostLoot, _inset, glow: false);
else
DrawIcon(dl, icon, new Vector2(tx, y), new Vector2(Px(11), h), Px(11), color);
tx += Px(11) + Px(5);
}
Tracked(dl, mono, mono.FontSize, new Vector2(tx, ty), color, _actCaps, 0.06f * mono.FontSize);
@ -402,6 +451,39 @@ internal sealed unsafe class InstrumentDashboard
// ── Controls: RUN / STOP, the subsystem keys, Force rebuff ──────────
// The subsystem keys draw their own icons (CombatCrossed, BuffHalo, NavTrail, LootChest,
// MetaStates), not their glyphs.
private const int CombatKey = 0, BuffingKey = 1, NavKey = 2, LootKey = 3, MetaKey = 4;
private const string CombatActivity = "Combat", NavActivity = "Navigating", LootActivity = "Looting"; // the activities (ActivityStyle)
private enum KeyArt { Glyph, Halo, Crossed, Trail, Chest, States, Grid }
// The Meta key's ring goes one state round each time the meta's state changes, with a burst
// this long. The first state seen (the dashboard opening) moves nothing.
private const float MetaFlashSeconds = 0.8f;
private string? _metaStateSeen;
private int _metaNode;
private float _metaFlashAt = -100f;
/// <summary>Moves the Meta key's ring on when the META readout's state changes. Render thread, each frame.</summary>
private void NoteMetaState()
{
string state = _r.MetaState;
if (string.Equals(state, _metaStateSeen, StringComparison.Ordinal)) return;
if (_metaStateSeen != null)
{
_metaNode = (_metaNode + 1) % MetaStates.Nodes;
_metaFlashAt = IconKit.Clock();
}
_metaStateSeen = state;
}
/// <summary>How far the Meta key's burst has gone (0..1), or -1 when there's none.</summary>
private float MetaFlash()
{
float f = (IconKit.Clock() - _metaFlashAt) / MetaFlashSeconds;
return f is >= 0f and < 1f ? f : -1f;
}
private static readonly (string Icon, string Name, string Right)[] Subsystems =
{
(RynthIcons.Sword, "Combat", "the Monsters panel (weapons, spells and rules per monster)"),
@ -502,10 +584,15 @@ internal sealed unsafe class InstrumentDashboard
&& ImGui.IsMouseReleased(ImGuiMouseButton.Left);
bool right = ImGui.IsItemClicked(ImGuiMouseButton.Right);
bool hot = ImGui.IsItemHovered();
string mode = i == 3 && Loot.LootModes.IsRares(_r.LootMode)
string mode = i == LootKey && Loot.LootModes.IsRares(_r.LootMode)
? "\nLoot Mode: rares and needed mana stones only (the loot profile is not used)." : "";
if (i == LootKey && _r.BoostLoot) mode += "\nBoost Loot Priority (the gold chest): RynthAi loots each kill before it starts the next fight.";
if (i == NavKey && _r.NavPriority && NavTrail.IsRoute(_r.NavKind))
mode += "\nBoost Nav Priority (the green trail): while the route runs, RynthAi only follows it (no hunting, no looting).";
if (i == MetaKey) mode += _r.MetaLoaded ? "\nMeta state: " + _r.MetaState + " (the ringed state moves on, with a flash, when it changes)." : "\nNo meta is loaded.";
SafeImGui.SetItemTooltip((on ? s.Name + " on. Click to turn it off." : s.Name + " off. Click to turn it on.") + mode + "\nRight-click: " + s.Right + ".");
KeyFace(dl, s.Icon, on, hot, pos, size);
KeyArt art = i switch { BuffingKey => KeyArt.Halo, CombatKey => KeyArt.Crossed, NavKey => KeyArt.Trail, LootKey => KeyArt.Chest, MetaKey => KeyArt.States, _ => KeyArt.Glyph };
KeyFace(dl, s.Icon, on, hot, pos, size, art);
if (clicked) _d.SetSubsystem(i, !on);
if (right) SubsystemSettings(i);
}
@ -518,15 +605,18 @@ internal sealed unsafe class InstrumentDashboard
&& ImGui.IsMouseReleased(ImGuiMouseButton.Left);
bool right = ImGui.IsItemClicked(ImGuiMouseButton.Right);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(on ? "Auto-sort (RynthSort) on. Click to turn it off.\nRight-click: RynthSort's window."
: "Auto-sort (RynthSort) off. Click to turn it on.\nRight-click: RynthSort's window.");
KeyFace(dl, RynthIcons.SortAscending, on, hot, pos, size);
SafeImGui.SetItemTooltip((on ? "Auto-sort (RynthSort) on. Click to turn it off." : "Auto-sort (RynthSort) off. Click to turn it on.")
+ (_d.AutoSortMoving ? "\nMoving items now." : "") + "\nRight-click: RynthSort's window.");
KeyFace(dl, RynthIcons.SortAscending, on, hot, pos, size, KeyArt.Grid);
if (clicked) _d.SetAutoSort(!on);
if (right) _d.ToggleSortWindow();
}
/// <summary>A key's face: raised with its LED lit when on, flat and dim when off.</summary>
private void KeyFace(ImDrawListPtr dl, string icon, bool on, bool hot, Vector2 pos, Vector2 size)
/// <summary>
/// A key's face: raised with its LED lit when on, flat and dim when off. <paramref name="art"/>
/// Halo, Crossed, Trail, Chest, States or Grid draws that icon (off, on, or moving with the activity) instead of the glyph.
/// </summary>
private void KeyFace(ImDrawListPtr dl, string icon, bool on, bool hot, Vector2 pos, Vector2 size, KeyArt art = KeyArt.Glyph)
{
float r = Px(3);
if (on)
@ -539,7 +629,38 @@ internal sealed unsafe class InstrumentDashboard
{
dl.AddRect(pos, pos + size, Mix(_bg, _line, 0.55f), r);
}
DrawIcon(dl, icon, pos, size, Px(15), on || hot ? _text : _faint);
uint fg = on || hot ? _text : _faint;
Vector2 centre = pos + size * 0.5f;
switch (art)
{
case KeyArt.Halo:
BuffHalo.Draw(dl, centre, Px(15), fg, !on ? BuffHalo.Look.Off
: _r.Activity == BuffManager.LabelBuffing ? BuffHalo.Look.Casting : BuffHalo.Look.On);
break;
case KeyArt.Crossed:
CombatCrossed.Draw(dl, centre, Px(15), fg, !on ? CombatCrossed.Look.Off
: _r.Activity == CombatActivity ? CombatCrossed.Look.Fighting : CombatCrossed.Look.On, _r.CombatStance);
break;
case KeyArt.Trail:
NavTrail.Draw(dl, centre, Px(15), fg, !on ? NavTrail.Look.Off
: _r.Activity == NavActivity ? NavTrail.Look.Moving : NavTrail.Look.On, _r.NavKind, _r.NavPriority);
break;
case KeyArt.Chest:
LootChest.Draw(dl, centre, Px(15), fg, !on ? LootChest.Look.Off
: _r.Activity == LootActivity ? LootChest.Look.Looting : LootChest.Look.On, _r.BoostLoot, _key);
break;
case KeyArt.States:
MetaStates.Draw(dl, centre, Px(15), fg, !on ? MetaStates.Look.Off : !_r.MetaLoaded ? MetaStates.Look.Empty
: _r.MacroRunning ? MetaStates.Look.Running : MetaStates.Look.On, _metaNode, MetaFlash(), _key);
break;
case KeyArt.Grid:
// Sorting plays while RynthSort moves items, auto-sort or a job asked for (the key may be off).
SortGrid.Draw(dl, centre, Px(15), fg, _d.AutoSortMoving ? SortGrid.Look.Sorting : on ? SortGrid.Look.On : SortGrid.Look.Off);
break;
default:
DrawIcon(dl, icon, pos, size, Px(15), fg);
break;
}
// The LED, top right: lit in the accent with a glow, or dark.
Vector2 led = new(pos.X + size.X - Px(6), pos.Y + Px(6));
if (on)
@ -750,6 +871,49 @@ internal sealed unsafe class InstrumentDashboard
return y + Px(FootH);
}
// ── Report a problem: one labelled key under the footer ─────────────
/// <summary>RynthCore's "Report a problem" panel (Report/ProblemReport.cs): alone, the command opens it.</summary>
internal const string ReportCommand = "/rc report";
/// <summary>The engine panel's title (ProblemReport.PanelTitle), for the key's lit state.</summary>
private const string ReportPanel = "Report a problem";
private const string ReportTip =
"Something went wrong, or an idea for a feature? Tell the staff.\n" +
"Opens RynthCore's Report a problem panel (/rc report): say what happened or what you'd\n" +
"like, and your recent RynthCore log can go with it (View shows exactly what is sent).";
private const float ReportH = 20;
private float ReportKey(ImDrawListPtr dl, float x0, float y, float w)
{
Vector2 p = new(x0, y), s = new(w, Px(ReportH));
float r = Px(3);
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton("##dash_report", s);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(ReportTip);
bool lit = _d.Host.SetPanelOpen(ReportPanel, RynthPanelOpen.Ask) == 1;
dl.AddRectFilled(p, p + s, hot || lit ? _key : A(_key, 0.55f), r);
dl.AddRect(p, p + s, hot ? A(Gold, 0.8f) : _line, r);
ImFontPtr f = Font(RynthUiFont.Narrow10);
// The short label only when the full one wouldn't fit a narrow dashboard.
string label = "REPORT A PROBLEM OR FEATURE";
float track = 0.14f * f.FontSize, iconBox = Px(14), gap = Px(5);
float lw = TrackedWidth(f, f.FontSize, label, track);
if (iconBox + gap + lw > w - Px(8))
{
label = "PROBLEM OR FEATURE";
lw = TrackedWidth(f, f.FontSize, label, track);
}
float cx = MathF.Round(x0 + (w - (iconBox + gap + lw)) * 0.5f);
DrawIcon(dl, RynthIcons.Warning, new Vector2(cx, y), new Vector2(iconBox, s.Y), Px(12), Gold);
Tracked(dl, f, f.FontSize, new Vector2(cx + iconBox + gap, MathF.Round(y + (s.Y - f.FontSize) * 0.5f)),
hot || lit ? _text : _dim, label, track);
if (clicked) _d.Command(ReportCommand);
return y + s.Y;
}
// ── Bars: the vitals, then the target ───────────────────────────────
private readonly NumberText _hpText = new(), _stText = new(), _mnText = new(), _tStText = new(), _tMnText = new();
@ -958,7 +1122,7 @@ internal sealed unsafe class InstrumentDashboard
ImGui.CloseCurrentPopup();
_d.Command("/ra why");
}
// Fight the monster I select (also Settings > Ranges > Combat Targeting): a toggle, the
// Fight the monster I select (also Settings > Combat > Targeting): a toggle, the
// command's reply says the new state.
bool fightSelected = _d.FightSelectedTarget;
if (MenuItem(dl, ref p, w, "##m_fightsel", RynthIcons.Crosshair,
@ -969,12 +1133,60 @@ internal sealed unsafe class InstrumentDashboard
ImGui.CloseCurrentPopup();
_d.Command("/ra fightselected");
}
// Which worn items have their magic on (RynthAiPlugin.ActiveGear.cs): its own window, no bar button.
if (MenuItem(dl, ref p, w, "##m_gear", RynthIcons.BatteryCharging, "Active gear", "/ra gear",
"Which worn items have their magic on, their mana and how long it lasts (the Active Gear window)."))
{
ImGui.CloseCurrentPopup();
_d.ToggleActiveGear();
}
// Commands sent every N seconds (RynthAiPlugin.TimedCommands.cs): its own window, no bar button.
if (MenuItem(dl, ref p, w, "##m_timed", RynthIcons.HourglassMedium, "Timed commands", "/ra timed",
"Chat commands sent every so many seconds, per character, server or all characters,\n" +
"like MagTools' periodic commands (the Timed Commands window)."))
{
ImGui.CloseCurrentPopup();
_d.ToggleTimedCommands();
}
// Dirty Fighting rotation: opens its window (the checkbox, order and default height are there).
if (MenuItem(dl, ref p, w, "##m_dfheight", RynthIcons.Knife,
"Dirty Fighting heights", _d.DfHeightRotation ? "ON" : "OFF",
"Opens the Dirty Fighting window: attack at the height of the next Dirty Fighting\n" +
"effect the target is missing (High, Medium, Low), then a height of your choice\n" +
"(/ra dfheight). Needs Dirty Fighting trained."))
{
ImGui.CloseCurrentPopup();
_d.ToggleDfHeightPanel();
}
if (MenuItem(dl, ref p, w, "##m_busy", RynthIcons.Hourglass, "Clear busy", "/ra clearbusy",
"The game thinks the character is still busy (the hourglass stays, nothing can be used): clear it."))
{
ImGui.CloseCurrentPopup();
_d.Command("/ra clearbusy");
}
if (MenuItem(dl, ref p, w, "##m_report", RynthIcons.Warning, "Report a Problem or Feature", ReportCommand,
"Something went wrong, or an idea for a feature? Tell the staff: RynthCore's Report a problem panel.\n" +
"Your recent RynthCore log can go with it (View shows exactly what is sent)."))
{
ImGui.CloseCurrentPopup();
_d.Command(ReportCommand);
}
// What the dashboard shows: each a switch, the menu stays open to flip several.
p.Y += Px(4);
dl.AddLine(new Vector2(p.X, p.Y + 0.5f), new Vector2(p.X + w, p.Y + 0.5f), _line);
p.Y += Px(5);
if (MenuItem(dl, ref p, w, "##m_showact", RynthIcons.Info, "Show bot activity", prefs.ShowActivity ? "ON" : "OFF",
"The line under the header with what the bot is doing and the meta's state. Click to " +
(prefs.ShowActivity ? "hide it." : "show it.")))
prefs.SetShowActivity(!prefs.ShowActivity);
if (MenuItem(dl, ref p, w, "##m_showfoot", RynthIcons.Hourglass, "Show FPS and timers", prefs.ShowFooter ? "ON" : "OFF",
"The footer with the frame rate and the bot's timers. Click to " +
(prefs.ShowFooter ? "hide it." : "show it.")))
prefs.SetShowFooter(!prefs.ShowFooter);
if (MenuItem(dl, ref p, w, "##m_showrep", RynthIcons.Warning, "Show Report button", prefs.ShowReport ? "ON" : "OFF",
"The Report a Problem or Feature button under the footer. Hidden, the entry above still opens it.\nClick to " +
(prefs.ShowReport ? "hide it." : "show it.")))
prefs.SetShowReport(!prefs.ShowReport);
if (_popped)
{
// Popped out the pickers are here as well (an older RynthCore's pop-out lets clicks
@ -1334,6 +1546,7 @@ internal sealed unsafe class InstrumentDashboard
DashboardPrefs.PatrolDrawer => Px(290),
DashboardPrefs.RangesDrawer => Px(250),
DashboardPrefs.PinnedDrawer => Px(300),
DashboardPrefs.FilesDrawer => Px(FilesDrawerW),
_ => Px(DrawerW),
};
@ -1468,10 +1681,18 @@ internal sealed unsafe class InstrumentDashboard
return y + h;
}
// The Loaded files drawer: label, picker, and the Loot Editor and Spells buttons.
// The Loaded files drawer: label, picker, the Loot Editor and Spells buttons, and each row's
// "..." key: that file's buttons (Save, Save As, New, Rename, Move to Deleted, Open folder).
private float FilesHeight() => 5 * Px(22) + 4 * Px(4);
private float FilesBody(ImDrawListPtr dl, float x0, float y, float w)
{
y = FilesRows(dl, x0, y, w);
FilesMenu();
return y;
}
private float FilesRows(ImDrawListPtr dl, float x0, float y, float w)
{
DashboardFiles f = _d.ReadFiles();
y = PickerRow(dl, x0, y, w, "PROFILE", f.ProfileName, f.Profiles, f.ProfileIdx, 3, null, null, null) + Px(4);
@ -1491,7 +1712,8 @@ internal sealed unsafe class InstrumentDashboard
ImFontPtr lf = Font(RynthUiFont.Narrow9);
Tracked(dl, lf, lf.FontSize, new Vector2(x0, MathF.Round(y + (h - lf.FontSize) * 0.5f)), _faint, label, 0.14f * lf.FontSize);
// The LOOT row also has a one-click Loot Mode key (a star, lit in rares mode) left of its button.
float fx = x0 + labelW, fw = w - labelW - (button != null ? h + Px(4) : 0) - (lootMode >= 0 ? h + Px(4) : 0);
// Every row ends with its file menu key ("...").
float fx = x0 + labelW, fw = w - labelW - (button != null ? h + Px(4) : 0) - (lootMode >= 0 ? h + Px(4) : 0) - (h + Px(4));
Vector2 p = new(fx, y), s = new(fw, h);
string popup = Id("##pick", kind);
ImGui.SetCursorScreenPos(p);
@ -1540,11 +1762,303 @@ internal sealed unsafe class InstrumentDashboard
dl.AddRectFilled(bp, bp + bs, _key, r);
dl.AddRect(bp, bp + bs, _line, r);
DrawIcon(dl, buttonIcon, bp, bs, Px(12), bhot ? _text : _dim);
bx += h + Px(4);
}
{
Vector2 mp = new(bx, y), ms = new(h, h);
bool open = _filesKind == kind && ImGui.IsPopupOpen(FilesMenuId);
ImGui.SetCursorScreenPos(mp);
if (ImGui.InvisibleButton(Id("##fmenu", kind), ms)) OpenFilesMenu(kind, new Vector2(x0, y + h + Px(2)));
bool mhot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(FilesMenuTip(kind));
dl.AddRectFilled(mp, mp + ms, open ? Mix(_bg, _accent, 0.16f) : _key, r);
dl.AddRect(mp, mp + ms, open ? _accent : _line, r);
DrawIcon(dl, RynthIcons.DotsThree, mp, ms, Px(12), open ? _accent : mhot ? _text : _dim);
}
PickerPopup(popup, items, selected, kind, lootMode);
return y + h;
}
// ── A row's file menu (the "..." key): Save, Save As, New, Rename, Move to Deleted, Open folder ──
//
// The buttons run on the plugin tick (RynthAiPlugin.ProfileFiles.cs, the same as the /ra verbs)
// and say what they did in chat and on the menu's last line. Save As onto another file asks
// first (its old copy is kept in Deleted); Move to Deleted asks first too. Nothing is deleted.
private const string FilesMenuId = "##files_menu";
private int _filesKind = -1;
private Vector2 _filesAnchor;
private string _filesName = string.Empty;
private enum FilesAsk { None, Replace, Delete }
private FilesAsk _filesAsk;
private string _filesAskName = string.Empty; // the name Replace was asked for
private string _filesStatus = string.Empty;
private bool _filesStatusOk = true;
private bool _filesBusy; // a button's action is queued
/// <summary>The last result from the tick (a new object each time), applied on the next frame.</summary>
private sealed record FilesOutcome(int Kind, ProfileVerb Verb, string Name, ProfileResult Result);
private volatile FilesOutcome? _filesOutcome;
private static string FilesMenuTip(int kind) => kind switch
{
3 => "Settings profile: Save, Save As, Rename, Move to Deleted, Open folder.",
0 => "Nav: Save, Save As, New, Rename, Move to Deleted, Open folder.",
2 => "Meta: Save, Save As, New, Rename, Move to Deleted, Open folder.",
1 => "Loot profile: Loot Editor, Save As (a copy), New, Rename, Move to Deleted, Open folder.",
_ => "Buff profiles: the Spells window, Open folder.",
};
private static string KindTitle(int kind) => kind switch
{
3 => "SETTINGS PROFILE", 0 => "NAV", 2 => "META", 1 => "LOOT PROFILE", _ => "BUFF PROFILE",
};
private void OpenFilesMenu(int kind, Vector2 anchor)
{
if (_filesKind != kind)
{
_filesName = string.Empty;
_filesStatus = string.Empty;
_filesStatusOk = true;
}
_filesKind = kind;
_filesAnchor = anchor;
_filesAsk = FilesAsk.None;
_filesBusy = false; // an action whose answer never came (a full queue) doesn't hold the buttons
ImGui.OpenPopup(FilesMenuId);
}
private void RunFiles(ProfileVerb verb, string name, bool replace = false)
{
int kind = _filesKind;
_filesBusy = true;
_filesAsk = FilesAsk.None;
_d.ProfileAction(kind, verb, name, replace, r => _filesOutcome = new FilesOutcome(kind, verb, name, r));
}
/// <summary>A result from the tick: the status line, the Replace question, the name box cleared after a success.</summary>
private void TakeFilesOutcome()
{
FilesOutcome? o = _filesOutcome;
if (o == null) return;
_filesOutcome = null;
_filesBusy = false;
if (o.Kind != _filesKind) return;
string text = o.Result.Text.StartsWith("[RynthAi] ", StringComparison.Ordinal) ? o.Result.Text[10..] : o.Result.Text;
_filesStatus = text;
_filesStatusOk = o.Result.Ok;
if (o.Result.NeedsReplace)
{
_filesAsk = FilesAsk.Replace;
_filesAskName = o.Name;
}
else if (o.Result.Ok && o.Verb is ProfileVerb.SaveAs or ProfileVerb.New or ProfileVerb.Rename)
{
_filesName = string.Empty;
}
}
private void FilesMenu()
{
TakeFilesOutcome();
if (_filesKind < 0 || !ImGui.IsPopupOpen(FilesMenuId)) return;
ImGui.SetNextWindowPos(_filesAnchor, ImGuiCond.Appearing);
PushPopupStyle();
bool open = ImGui.BeginPopup(FilesMenuId);
PopPopupStyle();
if (!open) return;
try
{
KeepPopupOnScreen();
int kind = _filesKind;
ProfileFileInfo info = _d.ProfileInfo(kind);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
Vector2 p = ImGui.GetCursorScreenPos();
float w = Px(250), h = Px(22), gap = Px(4);
// Title and the file in use ("*": changes not saved yet).
ImFontPtr tf = Font(RynthUiFont.Narrow9), nf = Font(RynthUiFont.Narrow11);
Tracked(dl, tf, tf.FontSize, new Vector2(p.X + Px(2), p.Y), _faint, KindTitle(kind), 0.14f * tf.FontSize);
p.Y += tf.FontSize + Px(3);
string shown = info.Name + (info.Unsaved ? " *" : string.Empty);
ImGui.SetCursorScreenPos(p);
ImGui.InvisibleButton("##files_cur", new Vector2(w, nf.FontSize + Px(2)));
SafeImGui.SetItemTooltip(info.Path.Length > 0 ? info.Path : info.Folder);
dl.PushClipRect(p, p + new Vector2(w, nf.FontSize + Px(2)), true);
dl.AddText(nf, nf.FontSize, new Vector2(p.X + Px(2), p.Y), info.Unsaved ? _accent : _text, shown);
dl.PopClipRect();
p.Y += nf.FontSize + Px(2);
string note = FilesNote(kind, info);
if (note.Length > 0)
{
dl.AddText(tf, tf.FontSize, new Vector2(p.X + Px(2), p.Y), _faint, note);
p.Y += tf.FontSize + Px(2);
}
p.Y += Px(4);
bool settings = kind == 3, nav = kind == 0, loot = kind == 1, buffs = kind == 4;
bool isDefault = settings && string.Equals(info.Name, "Default", StringComparison.OrdinalIgnoreCase);
bool idle = !_filesBusy;
// First row: what acts on the file in use.
float x = p.X;
if (buffs)
{
if (FilesKey(dl, ref x, p.Y, h, "Spells window", "##f_spells", true,
"Buff profiles are made, saved, copied and removed in the Spells window."))
{
ImGui.CloseCurrentPopup();
_d.ToggleSpells();
}
}
else if (loot)
{
if (FilesKey(dl, ref x, p.Y, h, "Loot Editor", "##f_edit", true,
"Edit the loot profile in use (rules are saved with the editor's Save)."))
{
ImGui.CloseCurrentPopup();
_d.Host.SetPanelOpen("Loot Editor", RynthPanelOpen.Open);
}
}
else
{
bool canSave = idle && (settings || (nav ? info.Name != "None" : info.HasFile)); // a nav: a file, a meta's nav or an unsaved route
string saveTip = settings ? "Save the settings profile now (it also saves every change on its own)."
: nav ? (info.HasFile ? "Save the route to its file now." : "Save the route (an unsaved route gets a new file, Route N).")
: info.HasFile ? "Save the meta to its file now." : "This meta has no file yet: type a name below and use Save As.";
if (FilesKey(dl, ref x, p.Y, h, "Save", "##f_save", canSave, saveTip)) RunFiles(ProfileVerb.Save, string.Empty);
}
if (!buffs)
{
bool canDelete = idle && info.HasFile && !isDefault;
string delTip = isDefault ? "The Default profile stays (every character falls back to it)."
: info.HasFile ? $"Move {System.IO.Path.GetFileName(info.Path)} to the Deleted folder beside it. Nothing is deleted; move it back to restore it."
: "No file in use.";
if (FilesKey(dl, ref x, p.Y, h, "Delete...", "##f_del", canDelete, delTip))
_filesAsk = FilesAsk.Delete;
}
if (FilesKey(dl, ref x, p.Y, h, "Open folder", "##f_folder", idle, "Open " + info.Folder + " in Explorer."))
RunFiles(ProfileVerb.Folder, string.Empty);
p.Y += h + gap;
if (buffs)
{
p = FilesText(p, w, "Buff profiles are made, saved and removed in the Spells window.", _faint);
}
else
{
// The name box, and what can be done with the name.
ImGui.SetCursorScreenPos(p);
ImGui.PushStyleColor(ImGuiCol.FrameBg, _inset);
ImGui.PushStyleColor(ImGuiCol.Border, _line);
ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, Px(3));
ImGui.SetNextItemWidth(w);
bool enter = ImGui.InputTextWithHint("##files_name", NameHint(kind), ref _filesName, 120, ImGuiInputTextFlags.EnterReturnsTrue);
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(2);
p.Y += ImGui.GetItemRectSize().Y + gap;
string name = _filesName.Trim();
bool named = idle && name.Length > 0;
x = p.X;
string asTip = loot ? "Copy the loot profile in use to this name; RynthAi loots with the copy."
: settings ? "Save these settings as a profile with this name; it becomes the one in use."
: $"Save the {(nav ? "route" : "meta")} under this name; it becomes the one in use.";
bool saveAs = FilesKey(dl, ref x, p.Y, h, "Save As", "##f_saveas", named && (!loot || info.HasFile), asTip);
if (saveAs || (enter && named && (!loot || info.HasFile))) RunFiles(ProfileVerb.SaveAs, name);
if (!settings)
{
string newTip = loot ? "A new, empty loot profile with this name, opened in the Loot Editor (its Save creates the file)."
: nav ? "A new, empty route with this name (Circular), loaded." : "A new meta with this name (one state, Default), loaded.";
if (FilesKey(dl, ref x, p.Y, h, "New", "##f_new", named, newTip)) RunFiles(ProfileVerb.New, name);
}
if (FilesKey(dl, ref x, p.Y, h, "Rename", "##f_rename", named && info.HasFile && !isDefault,
isDefault ? "The Default profile keeps its name." : "Rename the file in use to this name."))
RunFiles(ProfileVerb.Rename, name);
p.Y += h + gap;
}
// A question, when one is open.
if (_filesAsk == FilesAsk.Replace)
{
p = FilesText(p, w, $"Replace '{_filesAskName}'? Its old copy is kept in the Deleted folder.", _accent);
x = p.X;
if (FilesKey(dl, ref x, p.Y, h, "Replace", "##f_yes", idle, "Save over it (its old copy goes to Deleted first).")) RunFiles(ProfileVerb.SaveAs, _filesAskName, replace: true);
if (FilesKey(dl, ref x, p.Y, h, "Cancel", "##f_no", true, "Leave it as it is.")) { _filesAsk = FilesAsk.None; _filesStatus = "Not saved."; _filesStatusOk = true; }
p.Y += h + gap;
}
else if (_filesAsk == FilesAsk.Delete)
{
string file = info.Path.Length > 0 ? System.IO.Path.GetFileName(info.Path) : info.Name;
p = FilesText(p, w, $"Move {file} to the Deleted folder? It stops being used{(settings ? " (the settings go back to Default)" : string.Empty)}.", _accent);
x = p.X;
if (FilesKey(dl, ref x, p.Y, h, "Move", "##f_yes", idle, "Move it to Deleted (nothing is deleted).")) RunFiles(ProfileVerb.Delete, string.Empty);
if (FilesKey(dl, ref x, p.Y, h, "Cancel", "##f_no", true, "Keep it.")) _filesAsk = FilesAsk.None;
p.Y += h + gap;
}
if (_filesBusy) p = FilesText(p, w, "Working...", _dim);
else if (_filesStatus.Length > 0) p = FilesText(p, w, _filesStatus, _filesStatusOk ? _dim : HpText);
ImGui.SetCursorScreenPos(p);
ImGui.Dummy(new Vector2(w, 0));
}
finally
{
ImGui.EndPopup();
}
}
private static string NameHint(int kind) => kind switch
{
3 => "Profile name...", 0 => "Nav name...", 2 => "Meta name...", _ => "Loot profile name...",
};
/// <summary>The faint line under the name: where it lives, and how it is saved.</summary>
private static string FilesNote(int kind, ProfileFileInfo info) => kind switch
{
3 => "This character's profile; every change saves on its own.",
0 => info.Unsaved ? "Not saved to a file yet." : info.HasFile ? "NavProfiles; edits save on their own." : string.Empty,
2 => info.Unsaved ? "Not saved to a file yet (Save As names one)." : info.HasFile ? "MetaFiles; every change saves on its own." : string.Empty,
1 => info.Unsaved ? "The Loot Editor has changes not saved yet." : info.HasFile ? "LootProfiles" : string.Empty,
_ => info.Unsaved ? "The Spells window has changes not saved yet." : string.Empty,
};
/// <summary>Wrapped text at <paramref name="p"/>; returns the position under it.</summary>
private static Vector2 FilesText(Vector2 p, float w, string text, uint color)
{
ImGui.SetCursorScreenPos(p);
ImGui.PushStyleColor(ImGuiCol.Text, color);
ImGui.PushTextWrapPos(p.X + w);
ImGui.TextUnformatted(text);
ImGui.PopTextWrapPos();
ImGui.PopStyleColor();
Vector2 next = ImGui.GetCursorScreenPos();
return new Vector2(p.X, next.Y + 2);
}
/// <summary>A text key in the file menu at (<paramref name="x"/>, <paramref name="y"/>), x moved past it. True when clicked (and enabled).</summary>
private bool FilesKey(ImDrawListPtr dl, ref float x, float y, float h, string label, string id, bool enabled, string tip)
{
ImFontPtr f = Font(RynthUiFont.Narrow11);
float tw = f.CalcTextSizeA(f.FontSize, float.MaxValue, 0f, label).X;
Vector2 pos = new(x, y), size = new(MathF.Ceiling(tw + Px(14)), h);
ImGui.SetCursorScreenPos(pos);
bool clicked = ImGui.InvisibleButton(id, size);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(tip);
float r = Px(3);
dl.AddRectFilled(pos, pos + size, hot && enabled ? Mix(_key, _accent, 0.12f) : _key, r);
dl.AddRect(pos, pos + size, hot && enabled ? Mix(_line, _accent, 0.45f) : _line, r);
dl.AddText(f, f.FontSize, new Vector2(MathF.Round(pos.X + Px(7)), MathF.Round(pos.Y + (h - f.FontSize) * 0.5f)),
enabled ? _text : _faint, label);
x += size.X + Px(4);
return clicked && enabled;
}
private Vector2 _pickAnchor;
private float _pickWidth;

View file

@ -0,0 +1,152 @@
// ============================================================================
// RynthAi - Dashboard/LootChest.cs
// The Looting key's icon, "Chest" (picked 2026-11-11 over Pouch and Gem, with
// the Gilded priority mark; the mock-ups are the artifact "Looting Key
// Icons"). A domed treasure chest with two bands and a lock:
// Off the chest in outline: looting is off.
// On a solid chest over a faint gold glow: looting is on.
// Looting On, and the lid pops up, the inside glows and three sparks fly
// out: RynthAi is looting right now (the activity reads Looting).
// Priority (Boost Loot Priority, where it applies) gilds the chest: RynthAi
// loots each kill before it starts the next fight.
// Drawn on a 15 px em (IconKit) and scaled to the em asked for.
// Render thread; allocates nothing.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using static RynthCore.Plugin.RynthAi.Dashboard.IconKit;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthAi.Dashboard;
internal static class LootChest
{
internal enum Look { Off, On, Looting }
// The looting colour (the activity line's gold) and the light inside the chest and the sparks.
private static readonly uint Gold = Argb(0xFFEFC054), Light = Argb(0xFFFFE9AE);
// The design, in pixels at a 15 px em. The body is a box under a domed lid; a gap of 0.8
// between them. The lid turns on its back-left corner (the hinge).
private const float Half = 6f, BodyTop = -0.4f, BodyBottom = 5.4f, BodyRound = 0.9f;
private const float LidBottom = -1.2f, LidShoulder = -2.7f, DomeCtrl = -5.0f, LidBandTop = -4.0f;
private const float BandX = 3.7f, BandW = 0.8f, GapInset = 0.4f;
private const float LockL = -1.25f, LockR = 1.25f, LockTop = -2.1f, LockBottom = 0.6f, KeyholeY = -0.9f, KeyholeR = 0.5f;
private const float Cut = 1.5f, LockCut = 1.1f; // the knockouts: a ground-coloured edge that sets a part off what's behind it
private const float GlowR = 6.8f, GlowY = 0.4f, OpenGlowR = 6.2f, OpenGlowY = -2f;
private static readonly Vector2 Hinge = new(-Half, LidBottom);
// While looting: a cycle every 1/0.72 s. The lid rises 2.3 and tips back 0.1 rad, holds with a
// small shake, drops, and bounces once. The sparks leave the gap one after another.
private const float CyclesPerSecond = 0.72f, Rise = 2.3f, Tip = 0.1f;
private const float SparkR = 1.5f, SparkWaist = 0.24f, SparkStart = 0.08f, SparkStagger = 0.07f, SparkLife = 0.5f;
// Each spark: from (x0, y0) to (x1, y1): out to the left, straight up, out to the right (low,
// to keep clear of the key's LED).
private static readonly Vector4[] Sparks =
{
new(-5.4f, -1.6f, -9.2f, -5.8f),
new(0f, -6.4f, 0f, -11.2f),
new(5.4f, -1.4f, 9.4f, -2.8f),
};
/// <summary>
/// Draws the chest centred on <paramref name="centre"/>, <paramref name="em"/> pixels across, in
/// <paramref name="color"/> (the key's icon colour), or gold with <paramref name="priority"/>.
/// <paramref name="ground"/> is the colour behind it (the key face, or the activity line's
/// inset): the bands, the keyhole and the edges that set the lid and lock apart are cut in it.
/// <paramref name="glow"/> adds the gold glow (the key has it; the activity line, already gold, doesn't).
/// </summary>
public static void Draw(ImDrawListPtr dl, Vector2 centre, float em, uint color, Look look, bool priority, uint ground, bool glow = true)
{
float s = em / DesignEm;
float line = MathF.Max(1f, s);
if (look == Look.Off)
{
LidPath(dl, centre, s, 0f, 0f);
dl.PathStroke(color, ImDrawFlags.Closed, 1.1f * line);
dl.AddRect(centre + new Vector2(-Half, BodyTop) * s, centre + new Vector2(Half, BodyBottom) * s, color, BodyRound * s, ImDrawFlags.None, 1.1f * line);
dl.AddRect(centre + new Vector2(LockL, LockTop) * s, centre + new Vector2(LockR, LockBottom) * s, color, 0.5f * s, ImDrawFlags.None, 1.1f * line);
return;
}
uint ink = priority ? Gold : color;
bool looting = look == Look.Looting;
float ph = Clock() * CyclesPerSecond % 1f;
float lift = looting ? MathF.Max(0f, Lift(ph)) : 0f;
float a = -Tip * lift, dy = -Rise * lift;
if (glow)
{
Glow(dl, centre + new Vector2(0, GlowY) * s, GlowR * s, Gold, priority ? 0.075f : 0.045f);
if (lift > 0f) Glow(dl, centre + new Vector2(0, OpenGlowY) * s, OpenGlowR * s, Gold, 0.09f * lift);
}
// The body, its edge cut, and its two bands.
Vector2 bMin = centre + new Vector2(-Half, BodyTop) * s, bMax = centre + new Vector2(Half, BodyBottom) * s;
dl.AddRect(bMin, bMax, ground, BodyRound * s, ImDrawFlags.None, Cut * s);
dl.AddRectFilled(bMin, bMax, ink, BodyRound * s);
for (int k = -1; k <= 1; k += 2)
dl.AddLine(centre + new Vector2(k * BandX, BodyTop) * s, centre + new Vector2(k * BandX, BodyBottom) * s, ground, BandW * s);
// The light inside, while the lid is up (clockwise for ImGui's anti-aliased fill).
if (lift > 0.02f)
dl.AddQuadFilled(centre + new Vector2(-Half + GapInset, BodyTop) * s, Lid(centre, s, a, dy, -Half + GapInset, LidBottom),
Lid(centre, s, a, dy, Half - GapInset, LidBottom), centre + new Vector2(Half - GapInset, BodyTop) * s,
Alpha(Light, MathF.Min(1f, lift * 1.6f)));
// The lid, its edge cut, its bands, then the lock on its front edge.
LidPath(dl, centre, s, a, dy);
dl.PathStroke(ground, ImDrawFlags.Closed, Cut * s);
LidPath(dl, centre, s, a, dy);
dl.PathFillConvex(ink);
for (int k = -1; k <= 1; k += 2)
dl.AddLine(Lid(centre, s, a, dy, k * BandX, LidBottom), Lid(centre, s, a, dy, k * BandX, LidBandTop), ground, BandW * s);
Vector2 l0 = Lid(centre, s, a, dy, LockL, LockTop), l1 = Lid(centre, s, a, dy, LockR, LockTop);
Vector2 l2 = Lid(centre, s, a, dy, LockR, LockBottom), l3 = Lid(centre, s, a, dy, LockL, LockBottom);
dl.AddQuad(l0, l1, l2, l3, ground, LockCut * s);
dl.AddQuadFilled(l0, l1, l2, l3, ink);
dl.AddCircleFilled(Lid(centre, s, a, dy, 0f, KeyholeY), KeyholeR * s, ground, 8);
if (!looting) return;
// The sparks: each eases out along its path, swelling in and fading.
for (int k = 0; k < Sparks.Length; k++)
{
float u = (ph - SparkStart - k * SparkStagger) / SparkLife;
if (u <= 0f || u >= 1f) continue;
float e = 1f - (1f - u) * (1f - u);
Vector4 p = Sparks[k];
float r = SparkR * (1f - 0.4f * u) * s;
float alpha = MathF.Min(1f, MathF.Sin(u * MathF.PI) * 1.2f);
if (r < 0.3f || alpha <= 0.01f) continue;
Vector2 at = centre + new Vector2(p.X + (p.Z - p.X) * e, p.Y + (p.W - p.Y) * e) * s;
FillStar(dl, at, r, r * SparkWaist, Alpha(Light, alpha));
}
}
/// <summary>How far the lid is up (0 shut, 1 open) at phase <paramref name="ph"/> of the cycle.</summary>
private static float Lift(float ph)
{
if (ph < 0.14f) { float u = ph / 0.14f; return 1f - (1f - u) * (1f - u); } // pops up
if (ph < 0.62f) return 1f + 0.05f * MathF.Sin((ph - 0.14f) * 30f); // holds, with a shake
if (ph < 0.76f) { float u = (ph - 0.62f) / 0.14f; return 1f - u * u; } // drops
float v = (ph - 0.76f) / 0.24f; // one small bounce
return 0.16f * MathF.Sin(MathF.Min(1f, v * 2.2f) * MathF.PI) * (1f - v);
}
/// <summary>A point (x, y) of the lid, raised by <paramref name="dy"/> and turned <paramref name="a"/> on the hinge, on screen.</summary>
private static Vector2 Lid(Vector2 centre, float s, float a, float dy, float x, float y)
=> centre + (Hinge + Turn(x - Hinge.X, y - Hinge.Y, a) + new Vector2(0f, dy)) * s;
/// <summary>The lid's outline as the draw list's path: up the left side, over the dome, down the right (clockwise).</summary>
private static void LidPath(ImDrawListPtr dl, Vector2 centre, float s, float a, float dy)
{
dl.PathLineTo(Lid(centre, s, a, dy, -Half, LidBottom));
dl.PathLineTo(Lid(centre, s, a, dy, -Half, LidShoulder));
dl.PathBezierCubicCurveTo(Lid(centre, s, a, dy, -Half, DomeCtrl), Lid(centre, s, a, dy, Half, DomeCtrl),
Lid(centre, s, a, dy, Half, LidShoulder), 12);
dl.PathLineTo(Lid(centre, s, a, dy, Half, LidBottom));
}
}

View file

@ -0,0 +1,126 @@
// ============================================================================
// RynthAi - Dashboard/MetaStates.cs
// The Meta key's icon, "States" (picked 2026-11-11 over Gears and Rule; the
// mock-ups are the artifact "Meta Key Icons"). Three states joined in a
// cycle, the current one ringed: what a meta is, states and the jumps
// between them.
// Off hollow states, dotted links: Meta is off.
// Empty the same in the key's lit colour: Meta is on, no meta loaded.
// On solid states, arrowed links, the current state ringed.
// Running On, and a token hops from state to state: the macro runs, so
// the meta is checking its rules.
// A state change (the META readout's state changes) moves the ring to the
// next state with a blue burst; the dashboard passes how far that flash is.
// Drawn on a 15 px em (IconKit) and scaled to the em asked for. The top
// right stays clear for the key's LED. Render thread; allocates nothing.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using static RynthCore.Plugin.RynthAi.Dashboard.IconKit;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthAi.Dashboard;
internal static class MetaStates
{
internal enum Look { Off, Empty, On, Running }
/// <summary>The states drawn (the ring moves round them, one step per state change).</summary>
internal const int Nodes = 3;
// The meta colour (the mana blue) and its light, for the token and the burst.
private static readonly uint Blue = Argb(0xFF7FB9F9), Light = Argb(0xFFD6E8FF);
// The design, in pixels at a 15 px em: three states in a triangle, top left, right, bottom.
private static readonly Vector2[] Node = { new(-5.0f, -3.4f), new(5.0f, -0.6f), new(-1.5f, 5.3f) };
private const float NodeR = 2.0f, NodeCut = 0.6f, HollowR = 1.75f, RingR = 3.1f;
private const float LinkFrom = 0.6f, LinkTo = 0.8f, LinkW = 1.05f, ArrowSize = 1.0f, DotGap = 1.6f, DotR = 0.55f;
// Running: the token takes 1/1.1 s per link, easing in and out of each state. A blue bead
// with a light core, so it shows against the white links at the key's size.
private const float HopsPerSecond = 1.1f, TokenR = 1.35f, TokenCoreR = 0.6f, TokenGlowR = 3.2f, TokenGlow = 0.22f;
// The burst on a state change: the ring swells 3.4 and fades, the state lights up.
private const float BurstGrow = 3.4f, BurstW = 1.4f, BurstGlowR = 5f;
/// <summary>
/// Draws the states centred on <paramref name="centre"/>, <paramref name="em"/> pixels across, in
/// <paramref name="color"/> (the key's icon colour). <paramref name="current"/> is the ringed state
/// (0..2); <paramref name="flash"/> is how far the burst of a state change has gone (0..1), or
/// outside that range for none. <paramref name="ground"/> is the key face, cut round the states
/// so the links end clear of them. <paramref name="glow"/> adds the blue glows.
/// </summary>
public static void Draw(ImDrawListPtr dl, Vector2 centre, float em, uint color, Look look, int current, float flash, uint ground, bool glow = true)
{
float s = em / DesignEm;
float line = MathF.Max(1f, s);
bool hollow = look is Look.Off or Look.Empty;
bool lit = look != Look.Off;
// The links: state to state round the cycle.
for (int i = 0; i < Nodes; i++)
{
Vector2 a = Node[i], b = Node[(i + 1) % Nodes];
Vector2 u = Vector2.Normalize(b - a);
Vector2 from = a + u * (NodeR + LinkFrom), to = b - u * (NodeR + LinkTo);
if (hollow)
{
uint dot = Alpha(color, lit ? 0.7f : 0.5f);
int n = Math.Max(2, (int)MathF.Round(Vector2.Distance(from, to) / DotGap));
float r = MathF.Max(0.55f, DotR * s);
for (int k = 0; k <= n; k++) dl.AddCircleFilled(centre + Vector2.Lerp(from, to, k / (float)n) * s, r, dot, 6);
}
else
{
dl.AddLine(centre + from * s, centre + to * s, Alpha(color, 0.6f), LinkW * line);
Arrow(dl, centre, s, to, MathF.Atan2(u.Y, u.X), Alpha(color, 0.85f), LinkW * line);
}
}
// Running: the token, under the states so it slips behind them at each end.
if (look == Look.Running)
{
float hop = Clock() * HopsPerSecond % Nodes;
int k = (int)hop;
float f = hop - k;
f = f * f * (3f - 2f * f);
Vector2 at = centre + Vector2.Lerp(Node[k], Node[(k + 1) % Nodes], f) * s;
if (glow) Glow(dl, at, TokenGlowR * s, Blue, TokenGlow);
dl.AddCircleFilled(at, TokenR * s, Blue, 10);
dl.AddCircleFilled(at, TokenCoreR * s, Light, 8);
}
// The states.
for (int i = 0; i < Nodes; i++)
{
Vector2 c = centre + Node[i] * s;
if (hollow) dl.AddCircle(c, HollowR * s, Alpha(color, lit ? 0.9f : 0.6f), 14, line);
else
{
dl.AddCircleFilled(c, (NodeR + NodeCut) * s, ground, 14);
dl.AddCircleFilled(c, NodeR * s, color, 14);
}
}
if (hollow) return;
// The current state's ring, and the burst when it has just changed.
Vector2 cur = centre + Node[Math.Clamp(current, 0, Nodes - 1)] * s;
dl.AddCircle(cur, RingR * s, Alpha(color, 0.85f), 20, line);
if (flash is >= 0f and < 1f)
{
if (glow) Glow(dl, cur, BurstGlowR * s, Blue, 0.2f * (1f - flash));
dl.AddCircle(cur, (RingR + BurstGrow * MathF.Sqrt(flash)) * s, Alpha(Blue, 0.95f * (1f - flash)), 24, BurstW * line);
dl.AddCircleFilled(cur, NodeR * s, Mix(color, Light, 0.6f * (1f - flash)), 14);
}
}
/// <summary>An open arrowhead with its tip at <paramref name="tip"/> (design pixels), pointing along <paramref name="angle"/>.</summary>
private static void Arrow(ImDrawListPtr dl, Vector2 centre, float s, Vector2 tip, float angle, uint color, float width)
{
Span<Vector2> pts = stackalloc Vector2[3];
pts[0] = centre + (tip + Turn(-ArrowSize, -ArrowSize, angle)) * s;
pts[1] = centre + tip * s;
pts[2] = centre + (tip + Turn(-ArrowSize, ArrowSize, angle)) * s;
dl.AddPolyline(ref pts[0], 3, color, ImDrawFlags.None, width);
}
}

View file

@ -0,0 +1,401 @@
// ============================================================================
// RynthAi - Dashboard/NavTrail.cs
// The Navigation key's icon, "Trail" (2026-11-11; the mock-ups are the
// artifact "Navigation Key Icons"). A shape for the way RynthAi navigates:
// Circular a loop with its direction arrow
// Linear a trail with an arrow at each end
// Once a trail to a flag
// Follow footsteps after a leader arrow
// Patrol a sweep back and forth across the rooms (dungeon patrol)
// Hunt a radar (Outdoor Hunt)
// None an empty dotted trail: navigation on, nothing loaded
// Off is a dotted outline; On is the trail with its marker at rest;
// Moving (the activity reads Navigating) sends the marker along it with a
// green trail behind (the radar sweeps, the footsteps march).
// Priority (Boost Nav Priority, on a route, follow or patrol: picked
// 2026-11-11, "green and lane", artifact "Nav Priority Mark") draws the
// trail in green over a green lane, the way the Looting key's chest turns
// gold. Drawn on a 15 px em (IconKit) and scaled to the em asked for. The
// top right stays clear for the key's LED. Render thread; allocates nothing
// per frame.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using static RynthCore.Plugin.RynthAi.Dashboard.IconKit;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthAi.Dashboard;
internal static class NavTrail
{
internal enum Look { Off, On, Moving }
/// <summary>What the Navigation key shows (RynthAiPlugin.ReadNavKind picks it on the tick).</summary>
internal enum Kind { None, Circular, Linear, Once, Follow, Patrol, Hunt }
// The stamina green (go) and its light.
private static readonly uint Green = Argb(0xFF73D885), GreenLight = Argb(0xFFD2F5DA);
private const float Q = MathF.PI / 2;
/// <summary>A path in design pixels: its points, the running length at each, closed or not.</summary>
private sealed class Path
{
public readonly Vector2[] Pts;
public readonly float[] Len; // Len[i]: length up to point i; closed paths have one more, back to Pts[0]
public readonly bool Closed;
public float Total => Len[^1];
public Path(Vector2[] pts, bool closed)
{
Pts = pts;
Closed = closed;
int segs = closed ? pts.Length : pts.Length - 1;
Len = new float[segs + 1];
for (int i = 1; i <= segs; i++) Len[i] = Len[i - 1] + Vector2.Distance(pts[i - 1], pts[i % pts.Length]);
}
/// <summary>The point a fraction <paramref name="u"/> of the way along (wrapped when closed, clamped when not).</summary>
public Vector2 At(float u)
{
u = Closed ? u - MathF.Floor(u) : Math.Clamp(u, 0f, 1f);
float d = u * Total;
int i = 1;
while (i < Len.Length - 1 && Len[i] < d) i++;
float span = MathF.Max(1e-6f, Len[i] - Len[i - 1]);
return Vector2.Lerp(Pts[i - 1], Pts[i % Pts.Length], (d - Len[i - 1]) / span);
}
public float AngleAt(float u)
{
Vector2 d = At(u + 0.01f) - At(u - 0.01f);
return MathF.Atan2(d.Y, d.X);
}
}
// ── The shapes, in pixels at a 15 px em, built once ────────────────
private static readonly Path Loop = BuildLoop();
private static readonly Path S = new(Cubic(new(5.4f, 5.4f), new(6.4f, -1.0f), new(-6.4f, 1.4f), new(-5.4f, -4.6f), 36), false);
private static readonly Path Once = new(Cubic(new(5.4f, 5.6f), new(6.0f, 0f), new(-5.6f, 2.2f), new(-4.2f, -1.2f), 32), false);
private static readonly Path Fol = new(Cubic(new(4.6f, 5.2f), new(4.2f, 0.2f), new(-1.0f, 1.2f), new(-3.6f, -3.6f), 30), false);
private static readonly Path Serp = BuildSerpentine();
private const int MaxPoints = 64;
/// <summary>An ellipse 12.2 by 9.8 starting at the top, clockwise.</summary>
private static Path BuildLoop()
{
var pts = new Vector2[48];
for (int i = 0; i < pts.Length; i++)
{
float a = -Q + MathF.Tau * i / pts.Length;
pts[i] = new Vector2(MathF.Cos(a) * 6.1f, MathF.Sin(a) * 6.1f * 0.8f + 0.6f);
}
return new Path(pts, true);
}
/// <summary>Four runs across, joined by U-turns at alternate ends (the runs are the gaps between the arcs).</summary>
private static Path BuildSerpentine()
{
var pts = new System.Collections.Generic.List<Vector2> { new(-5.2f, -4.6f) };
AddArc(pts, new(3.6f, -3.05f), 1.55f, -Q, Q, 8);
AddArc(pts, new(-3.6f, 0.05f), 1.55f, -Q, -3 * Q, 8);
AddArc(pts, new(3.6f, 3.15f), 1.55f, -Q, Q, 8);
pts.Add(new(-5.2f, 4.7f));
return new Path(pts.ToArray(), false);
}
private static void AddArc(System.Collections.Generic.List<Vector2> pts, Vector2 c, float r, float a0, float a1, int n)
{
for (int i = 0; i <= n; i++) pts.Add(c + Dir(a0 + (a1 - a0) * i / n) * r);
}
private static Vector2[] Cubic(Vector2 p0, Vector2 c1, Vector2 c2, Vector2 p3, int n)
{
var o = new Vector2[n + 1];
for (int i = 0; i <= n; i++)
{
float t = i / (float)n, u = 1f - t;
o[i] = u * u * u * p0 + 3f * u * u * t * c1 + 3f * u * t * t * c2 + t * t * t * p3;
}
return o;
}
// ── Drawing ─────────────────────────────────────────────────────────
/// <summary>One frame's placement: the icon's centre and scale, the line width and the colour.</summary>
private readonly struct Pen
{
public readonly ImDrawListPtr Dl;
public readonly Vector2 C;
public readonly float S, Line;
public readonly uint Fg;
public readonly bool Glow;
public Pen(ImDrawListPtr dl, Vector2 c, float s, uint fg, bool glow)
{
Dl = dl; C = c; S = s; Line = MathF.Max(1f, s); Fg = fg; Glow = glow;
}
public Vector2 P(Vector2 design) => C + design * S;
}
// The priority lane: a green band under the trail, an inner one and a wider, fainter one;
// it breathes while the marker runs.
private const float LaneW = 4.6f, LaneOuterW = 6.4f, LaneAlpha = 0.22f, LaneOuter = 0.6f, LanePulse = 0.07f, LaneHz = 0.8f;
private const float PriGlowR = 6.6f, PriGlowY = 0.4f, PriGlow = 0.05f;
/// <summary>The kinds Boost Nav Priority applies to: a route, a follow or a patrol (not the hunt, not nothing).</summary>
internal static bool IsRoute(Kind kind) => kind is Kind.Circular or Kind.Linear or Kind.Once or Kind.Follow or Kind.Patrol;
/// <summary>
/// Draws the Navigation icon for <paramref name="kind"/> centred on <paramref name="centre"/>,
/// <paramref name="em"/> pixels across, in <paramref name="color"/>. <paramref name="priority"/>
/// (Boost Nav Priority) draws a route in green over a green lane; the hunt and no route ignore it.
/// <paramref name="glow"/> adds the green glows (the key has them; the activity line doesn't).
/// </summary>
public static void Draw(ImDrawListPtr dl, Vector2 centre, float em, uint color, Look look, Kind kind, bool priority = false, bool glow = true)
{
float t = Clock();
bool pri = priority && look != Look.Off && IsRoute(kind);
var pen = new Pen(dl, centre, em / DesignEm, pri ? Green : color, glow);
if (pri)
{
if (glow) Glow(dl, pen.P(new Vector2(0f, PriGlowY)), PriGlowR * pen.S, Green, PriGlow);
Lane(pen, PathOf(kind), look == Look.Moving, t);
}
switch (kind)
{
case Kind.Circular: DrawLoop(pen, look, t); break;
case Kind.Linear: DrawLinear(pen, look, t); break;
case Kind.Once: DrawOnce(pen, look, t); break;
case Kind.Follow: DrawFollow(pen, look, t); break;
case Kind.Patrol: DrawPatrol(pen, look, t); break;
case Kind.Hunt: DrawHunt(pen, look, t); break;
default: DrawNone(pen, look); break;
}
}
private static void DrawLoop(Pen p, Look look, float t)
{
bool moving = look == Look.Moving;
float u = moving ? t * 0.45f % 1f : 0.75f;
PathLook(p, Loop, look);
if (look != Look.Off)
{
// Waypoints at the quarters; the resting marker covers the left one.
for (int k = 0; k < 4; k++)
if (k != 3 || moving) p.Dl.AddCircleFilled(p.P(Loop.At(k * 0.25f)), 0.7f * p.S, Alpha(p.Fg, 0.75f), 8);
}
Chevron(p, new Vector2(1.3f, Loop.At(0).Y), 0f, 1.3f, look != Look.Off ? p.Fg : Alpha(p.Fg, 0.6f), 1.15f);
if (moving) Tail(p, Loop, u, 0.32f, forward: true);
Marker(p, Loop.At(u), look);
}
private static void DrawLinear(Pen p, Look look, float t)
{
bool moving = look == Look.Moving;
float u = 0.5f, ph = t * 0.42f % 1f;
if (moving)
{
u = ph < 0.5f ? ph * 2f : 2f - ph * 2f;
u = u * u * (3f - 2f * u); // eases at each end
}
PathLook(p, S, look);
uint ends = look != Look.Off ? p.Fg : Alpha(p.Fg, 0.6f);
Chevron(p, S.At(1f) + new Vector2(0, -0.4f), S.AngleAt(0.99f), 1.4f, ends, 1.2f);
Chevron(p, S.At(0f) + new Vector2(0, 0.4f), S.AngleAt(0.01f) + MathF.PI, 1.4f, ends, 1.2f);
if (moving) Tail(p, S, u, 0.22f, forward: ph < 0.5f);
Marker(p, S.At(u), look);
}
private static void DrawOnce(Pen p, Look look, float t)
{
bool moving = look == Look.Moving;
float ph = t * 0.4f % 1f;
float u = moving ? MathF.Min(1f, ph / 0.8f) : 0f;
bool arrived = moving && u >= 1f;
PathLook(p, Once, look);
// The flag at the trail's end: a pole and a pennant, lit while the marker is there.
Vector2 pole = Once.At(1f) + new Vector2(-0.2f, 0);
uint fc = look != Look.Off ? p.Fg : Alpha(p.Fg, 0.6f);
p.Dl.AddLine(p.P(pole), p.P(pole + new Vector2(0, -6f)), fc, 1.15f * p.Line);
Span<Vector2> flag = stackalloc Vector2[3];
flag[0] = p.P(pole + new Vector2(0, -6f));
flag[1] = p.P(pole + new Vector2(3.8f, -4.9f));
flag[2] = p.P(pole + new Vector2(0, -3.6f));
if (look != Look.Off) p.Dl.AddConvexPolyFilled(ref flag[0], 3, arrived ? Mix(p.Fg, GreenLight, 0.5f) : p.Fg);
else p.Dl.AddPolyline(ref flag[0], 3, fc, ImDrawFlags.Closed, p.Line);
if (arrived && p.Glow) Glow(p.Dl, p.P(pole + new Vector2(1.6f, -4.8f)), 3.6f * p.S, Green, 0.16f * (1f - (ph - 0.8f) / 0.2f));
if (moving && !arrived) Tail(p, Once, u, 0.25f, forward: true);
if (!arrived) Marker(p, Once.At(u), look);
}
private static void DrawFollow(Pen p, Look look, float t)
{
bool on = look != Look.Off, moving = look == Look.Moving;
// Six footsteps toward the leader, marching while moving.
float off = moving ? t * 1.2f % 1f : 0f;
for (int i = 0; i < 6; i++)
{
float u = MathF.Min(0.86f, (i + off) / 6f * 0.86f + 0.06f);
float a = !on ? 0.55f : moving ? 0.35f + 0.65f * MathF.Sin(MathF.Min(1f, u / 0.86f) * MathF.PI) : 0.7f;
p.Dl.AddCircleFilled(p.P(Fol.At(u)), (on ? 0.75f : 0.55f) * p.S, Alpha(p.Fg, a), 8);
}
// The leader: an arrowhead at the end, pointing the way.
Vector2 lead = Fol.At(1f);
float la = Fol.AngleAt(0.97f);
Span<Vector2> kite = stackalloc Vector2[4];
kite[0] = p.P(lead + Turn(2.7f, 0f, la));
kite[1] = p.P(lead + Turn(-1.9f, 1.9f, la));
kite[2] = p.P(lead + Turn(-0.9f, 0f, la));
kite[3] = p.P(lead + Turn(-1.9f, -1.9f, la));
if (on)
{
if (moving && p.Glow) Glow(p.Dl, p.P(lead), 3.4f * p.S, Green, 0.12f);
p.Dl.AddConcavePolyFilled(ref kite[0], 4, p.Fg);
}
else p.Dl.AddPolyline(ref kite[0], 4, p.Fg, ImDrawFlags.Closed, p.Line);
// The follower, at the start, never moves: the steps do.
Marker(p, Fol.At(0f), look == Look.Off ? Look.Off : Look.On);
}
private static void DrawPatrol(Pen p, Look look, float t)
{
bool moving = look == Look.Moving;
float u = moving ? t * 0.3f % 1f : 0f;
PathLook(p, Serp, look);
if (moving) Tail(p, Serp, u, 0.18f, forward: true);
Marker(p, Serp.At(u), look);
}
private static void DrawHunt(Pen p, Look look, float t)
{
const float R = 6.1f;
if (look == Look.Off)
{
uint dot = Alpha(p.Fg, 0.55f);
for (int i = 0; i < 16; i++) p.Dl.AddCircleFilled(p.P(Dir(i * MathF.Tau / 16f) * R), MathF.Max(0.55f, 0.5f * p.S), dot, 6);
p.Dl.AddCircle(p.C, 1.1f * p.S, p.Fg, 10, p.Line);
return;
}
bool moving = look == Look.Moving;
p.Dl.AddCircle(p.C, R * p.S, Alpha(p.Fg, moving ? 0.45f : 0.6f), 32, p.Line);
for (int k = 0; k < 4; k++)
{
Vector2 d = Dir(k * Q);
p.Dl.AddLine(p.P(d * (R - 1.4f)), p.P(d * (R + 0.9f)), p.Fg, 1.15f * p.Line);
}
float sweep = moving ? (t * 0.7f % 1f) * MathF.Tau - Q : -MathF.PI * 0.8f;
if (moving)
{
// The sweep: a fading wedge behind the needle, and two blips that light as it passes.
const int n = 12;
const float span = 1.4f;
for (int j = 0; j < n; j++)
{
float a1 = sweep - span * j / n, a0 = sweep - span * (j + 1) / n;
p.Dl.PathLineTo(p.C);
p.Dl.PathArcTo(p.C, (R - 0.6f) * p.S, a0, a1, 3);
p.Dl.PathFillConvex(Alpha(Green, 0.28f * MathF.Pow(1f - j / (float)n, 1.3f)));
}
Blip(p, sweep, -MathF.PI * 0.15f, 3.6f);
Blip(p, sweep, MathF.PI * 0.62f, 4.4f);
}
p.Dl.AddLine(p.C, p.P(Dir(sweep) * (R - 1f)), moving ? GreenLight : p.Fg, 1.3f * p.Line);
p.Dl.AddCircleFilled(p.C, 1.2f * p.S, p.Fg, 10);
}
private static void Blip(Pen p, float sweep, float angle, float radius)
{
float d = ((sweep - angle) % MathF.Tau + MathF.Tau) % MathF.Tau; // how far the needle has gone past it
if (d >= 2.2f) return;
p.Dl.AddCircleFilled(p.P(Dir(angle) * radius), 1.1f * p.S, Alpha(GreenLight, 1f - d / 2.2f), 8);
}
private static void DrawNone(Pen p, Look look)
{
bool on = look != Look.Off;
Dotted(p, S, Alpha(p.Fg, on ? 0.75f : 0.5f));
uint ends = Alpha(p.Fg, on ? 0.9f : 0.6f);
p.Dl.AddCircle(p.P(S.At(0f)), 1.35f * p.S, ends, 10, p.Line);
p.Dl.AddCircle(p.P(S.At(1f)), 1.35f * p.S, ends, 10, p.Line);
}
// ── Pieces ──────────────────────────────────────────────────────────
/// <summary>The path a route kind draws (the footsteps' path for a follow).</summary>
private static Path PathOf(Kind kind) => kind switch
{
Kind.Circular => Loop,
Kind.Linear => S,
Kind.Once => Once,
Kind.Follow => Fol,
_ => Serp,
};
/// <summary>The priority lane under <paramref name="path"/>: a wide faint green band, then a narrower one.</summary>
private static void Lane(Pen p, Path path, bool moving, float t)
{
float a = LaneAlpha + (moving ? LanePulse * MathF.Sin(t * MathF.Tau * LaneHz) : 0f);
int n = Math.Min(path.Pts.Length, MaxPoints);
Span<Vector2> pts = stackalloc Vector2[MaxPoints];
for (int i = 0; i < n; i++) pts[i] = p.P(path.Pts[i]);
ImDrawFlags flags = path.Closed ? ImDrawFlags.Closed : ImDrawFlags.None;
p.Dl.AddPolyline(ref pts[0], n, Alpha(Green, a * LaneOuter), flags, LaneOuterW * p.S);
p.Dl.AddPolyline(ref pts[0], n, Alpha(Green, a), flags, LaneW * p.S);
}
/// <summary>The path: dotted when off, solid (fainter while the marker runs) when on.</summary>
private static void PathLook(Pen p, Path path, Look look)
{
if (look == Look.Off) { Dotted(p, path, Alpha(p.Fg, 0.6f)); return; }
int n = Math.Min(path.Pts.Length, MaxPoints);
Span<Vector2> pts = stackalloc Vector2[MaxPoints];
for (int i = 0; i < n; i++) pts[i] = p.P(path.Pts[i]);
p.Dl.AddPolyline(ref pts[0], n, Alpha(p.Fg, look == Look.Moving ? 0.45f : 0.75f),
path.Closed ? ImDrawFlags.Closed : ImDrawFlags.None, 1.35f * p.Line);
}
private static void Dotted(Pen p, Path path, uint color)
{
const float Gap = 1.6f;
int n = Math.Max(2, (int)MathF.Round(path.Total / Gap));
int last = path.Closed ? n - 1 : n;
float r = MathF.Max(0.55f, 0.55f * p.S);
for (int i = 0; i <= last; i++) p.Dl.AddCircleFilled(p.P(path.At(i / (float)n)), r, color, 6);
}
/// <summary>The green tail behind the marker at <paramref name="u"/>, <paramref name="span"/> of the path long.</summary>
private static void Tail(Pen p, Path path, float u, float span, bool forward)
{
const int n = 14;
for (int j = 0; j < n; j++)
{
float a = forward ? u - span * (j + 1) / n : u + span * (j + 1) / n;
float b = forward ? u - span * j / n : u + span * j / n;
if (!path.Closed && (forward ? b <= 0f : b >= 1f)) break;
p.Dl.AddLine(p.P(path.At(a)), p.P(path.At(b)), Alpha(GreenLight, MathF.Pow(1f - j / (float)n, 1.4f)), 1.6f * p.Line);
}
}
/// <summary>The marker: a ring when off, a dot when on, a greener dot with a glow while moving.</summary>
private static void Marker(Pen p, Vector2 at, Look look)
{
Vector2 c = p.P(at);
if (look == Look.Off) { p.Dl.AddCircle(c, 1.5f * p.S, p.Fg, 12, p.Line); return; }
bool moving = look == Look.Moving;
if (moving && p.Glow) Glow(p.Dl, c, 3.6f * p.S, Green, 0.15f);
p.Dl.AddCircleFilled(c, 1.95f * p.S, moving ? Mix(p.Fg, GreenLight, 0.35f) : p.Fg, 12);
}
/// <summary>An open arrowhead with its tip at <paramref name="tip"/>, pointing along <paramref name="angle"/>.</summary>
private static void Chevron(Pen p, Vector2 tip, float angle, float size, uint color, float width)
{
Span<Vector2> pts = stackalloc Vector2[3];
pts[0] = p.P(tip + Turn(-size, -size, angle));
pts[1] = p.P(tip);
pts[2] = p.P(tip + Turn(-size, size, angle));
p.Dl.AddPolyline(ref pts[0], 3, color, ImDrawFlags.None, width * p.Line);
}
}

View file

@ -0,0 +1,140 @@
// ============================================================================
// RynthAi - Dashboard/SortGrid.cs
// RynthSort's auto-sort key's icon, "Grid" (picked 2026-11-11 over Packs and
// List; the mock-ups are the artifact "Auto-sort Key Icons"). A pack's slots,
// 3 by 3, with its items in order:
// Off the items in outline, the empty slots as dots: auto-sort off.
// On the items solid in faint slots: auto-sort on.
// Sorting an item lifts out of its slot, arcs to its place with a teal
// trail and lands with a ring, then the next; the two then fade
// back and it plays again. Shown while RynthSort is moving items
// (its "moving" flag), whether auto-sort or a job asked for moves them.
// Drawn on a 15 px em (IconKit) and scaled to the em asked for. The top
// right stays clear for the key's LED. Render thread; allocates nothing.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using static RynthCore.Plugin.RynthAi.Dashboard.IconKit;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthAi.Dashboard;
internal static class SortGrid
{
internal enum Look { Off, On, Sorting }
// The sort colour (a teal of its own) and its light, for the moving item and its ring.
private static readonly uint Teal = Argb(0xFF62D5C8), Light = Argb(0xFFD4F6F1);
// The design, in pixels at a 15 px em: 3 by 3 cells, set a little low to clear the LED.
private const float Cell = 3.3f, Gap = 0.85f, X0 = -5.8f, Y0 = -5.2f, Round = 0.8f;
private const float SlotInset = 0.3f, SlotRound = 0.6f, SlotW = 0.8f, SlotAlpha = 0.3f, DotR = 0.55f;
private const int Slots = 9, Items = 6; // sorted: the first six cells hold items
// Sorting: the items start in cells 0 1 3 4 7 8; 7 goes to 2, then 8 to 5 (a second each),
// then a pause sorted, then the two fade back to 7 and 8.
private const int Unsorted = (1 << 0) | (1 << 1) | (1 << 3) | (1 << 4) | (1 << 7) | (1 << 8);
private static readonly (int From, int To)[] Moves = { (7, 2), (8, 5) };
private const float MoveSeconds = 1f, Cycle = 2.8f, ResetAt = 2.45f, ResetSeconds = 0.35f;
// Within a move: lift (to 0.12), travel on an arc (to 0.72), land with a ring (to 1).
private const float LiftEnd = 0.12f, TravelEnd = 0.72f, Arc = 2.6f, Swell = 0.18f;
private const int TrailDots = 5;
private const float TrailStep = 0.06f, TrailR = 0.9f, TrailAlpha = 0.5f;
private const float GlowR = 3.2f, RingGrow = 2f, RingW = 1.1f;
/// <summary>
/// Draws the grid centred on <paramref name="centre"/>, <paramref name="em"/> pixels across, in
/// <paramref name="color"/> (the key's icon colour). <paramref name="glow"/> adds the teal glow
/// round the moving item.
/// </summary>
public static void Draw(ImDrawListPtr dl, Vector2 centre, float em, uint color, Look look, bool glow = true)
{
float s = em / DesignEm;
float line = MathF.Max(1f, s);
if (look == Look.Off)
{
for (int i = 0; i < Slots; i++)
{
Vector2 p = CellAt(i);
if (i < Items) dl.AddRect(At(centre, s, p), At(centre, s, p + new Vector2(Cell)), color, Round * s, ImDrawFlags.None, line);
else dl.AddCircleFilled(At(centre, s, p + new Vector2(Cell / 2)), MathF.Max(DotR, DotR * s), Alpha(color, 0.55f), 6);
}
return;
}
uint slot = Alpha(color, SlotAlpha);
for (int i = 0; i < Slots; i++)
{
Vector2 p = CellAt(i);
dl.AddRect(At(centre, s, p + new Vector2(SlotInset)), At(centre, s, p + new Vector2(Cell - SlotInset)), slot, SlotRound * s, ImDrawFlags.None, SlotW * line);
}
if (look == Look.On)
{
for (int i = 0; i < Items; i++) Item(dl, centre, s, CellAt(i) + new Vector2(Cell / 2), 1f, color);
return;
}
float ph = Clock() % Cycle;
int done = Math.Min(Moves.Length, (int)(ph / MoveSeconds));
int held = Unsorted;
for (int j = 0; j < done; j++) held = (held & ~(1 << Moves[j].From)) | (1 << Moves[j].To);
bool moving = done < Moves.Length;
float f = ph - done * MoveSeconds;
float reset = ph > ResetAt ? Ease((ph - ResetAt) / ResetSeconds) : 0f;
// The items at rest; once both moves are done the moved two fade out as they fade back in below.
for (int i = 0; i < Slots; i++)
{
if ((held & (1 << i)) == 0 || (moving && i == Moves[done].From)) continue;
bool moved = !moving && (i == Moves[0].To || i == Moves[1].To);
Item(dl, centre, s, CellAt(i) + new Vector2(Cell / 2), 1f, moved ? Alpha(color, 1f - reset) : color);
}
if (reset > 0f)
foreach (var m in Moves) Item(dl, centre, s, CellAt(m.From) + new Vector2(Cell / 2), 1f, Alpha(color, reset));
if (!moving) return;
// The moving item: lifts, arcs over with a fading trail, lands with a ring.
Vector2 a = CellAt(Moves[done].From) + new Vector2(Cell / 2), b = CellAt(Moves[done].To) + new Vector2(Cell / 2);
float u = Ease((f - LiftEnd) / (TravelEnd - LiftEnd));
float lift = f < LiftEnd ? f / LiftEnd : f > TravelEnd ? MathF.Max(0f, 1f - (f - TravelEnd) / LiftEnd) : 1f;
if (f > LiftEnd && f < TravelEnd)
{
for (int k = 1; k <= TrailDots; k++)
{
float fade = 1f - k / (TrailDots + 1f);
dl.AddCircleFilled(At(centre, s, OnArc(a, b, MathF.Max(0f, u - k * TrailStep))), TrailR * fade * s, Alpha(Teal, TrailAlpha * fade), 8);
}
}
Vector2 c = OnArc(a, b, u);
if (glow) Glow(dl, At(centre, s, c), GlowR * s, Teal, 0.16f * lift + 0.04f);
Item(dl, centre, s, c, 1f + Swell * lift, Mix(color, Light, 0.55f * lift));
if (f > TravelEnd)
{
float k = 1f - (f - TravelEnd) / (1f - TravelEnd);
dl.AddCircle(At(centre, s, b), (Cell * 0.55f + RingGrow * (1f - k)) * s, Alpha(Teal, k), 16, RingW * line);
}
}
private static Vector2 CellAt(int i) => new(X0 + (i % 3) * (Cell + Gap), Y0 + (i / 3) * (Cell + Gap));
private static Vector2 At(Vector2 centre, float s, Vector2 design) => centre + design * s;
/// <summary>A point a fraction <paramref name="u"/> along the arc from <paramref name="a"/> to <paramref name="b"/>.</summary>
private static Vector2 OnArc(Vector2 a, Vector2 b, float u) => Vector2.Lerp(a, b, u) + new Vector2(0f, -Arc * MathF.Sin(u * MathF.PI));
/// <summary>An item: a filled rounded cell centred on <paramref name="c"/>, <paramref name="scale"/> times a cell.</summary>
private static void Item(ImDrawListPtr dl, Vector2 centre, float s, Vector2 c, float scale, uint color)
{
Vector2 half = new(Cell * scale / 2);
dl.AddRectFilled(At(centre, s, c - half), At(centre, s, c + half), color, Round * s);
}
private static float Ease(float u)
{
u = Math.Clamp(u, 0f, 1f);
return u * u * (3f - 2f * u);
}
}

View file

@ -28,6 +28,7 @@ internal enum TickStep
RouteJobs,
GiveQueue,
ItemTool,
TimedCommands,
Jumper,
Dashboard,
// In world.
@ -118,6 +119,7 @@ internal sealed class TickGuard
Add(TickStep.RouteJobs, "dungeon route jobs", LogCat.Navigation);
Add(TickStep.GiveQueue, "give queue", LogCat.Inventory);
Add(TickStep.ItemTool, "item tool", LogCat.Inventory);
Add(TickStep.TimedCommands, "timed commands", LogCat.Commands);
Add(TickStep.Jumper, "jumper", LogCat.Jumper, essential: true);
Add(TickStep.Dashboard, "dashboard window", LogCat.UI);

View file

@ -9,7 +9,7 @@
// 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,
// which RynthCore sends (ServerMenuModel), or a link to RynthCore's Options > Diagnostics (where a
// which RynthCore sends (ServerMenuModel), or a link to RynthCore's Settings > Game Client (where a
// server is forced) when none matches. The Options button opens RynthAi Settings (/rc ui open
// Settings); the small gear next to it, or a right-click on Options, holds the Mini Remote's own
// settings (sections, layout, slot size), and so does a click on Options when there is no chat parser.
@ -985,11 +985,11 @@ internal sealed class MiniRemoteHud
ImGui.Separator();
ImGui.TextDisabled("Server: no installed server plugin matches this world");
// Forcing a server lives in one place since 2026-10-13: RynthCore's Options > Diagnostics.
if (_hud.Host.HasInvokeChatParser && ImGui.MenuItem("Force a server... (Options > Diagnostics)##mrforce", MovedTabs.Diagnostics))
// Forcing a server lives in one place since 2026-10-13: RynthCore's Settings > Game Client (Diagnostics until 2026-11-11).
if (_hud.Host.HasInvokeChatParser && ImGui.MenuItem("Force a server... (Settings > Game Client)##mrforce", MovedTabs.Diagnostics))
_hud.RunEngineCommand(MovedTabs.Diagnostics);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("RynthCore's server selection (Options > Diagnostics) shows a server's windows here anyway.\n"
SafeImGui.SetTooltip("RynthCore's server selection (Settings > Game Client) shows a server's windows here anyway.\n"
+ "It only says which world this is: the server still decides which features exist.");
}

View file

@ -3,7 +3,7 @@
// RynthILT's Character tab left the Mini Remote: its character overview and session went to
// 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
// RynthCore Settings > Game Client ("/rc diagnostics", the server picker). Infinite Leaftide's own screens stay
// 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.
@ -18,7 +18,7 @@ internal static class MovedTabs
/// <summary>RynthOracle's Character tab (the character overview and this session).</summary>
public const string OracleCharacter = "/ro character";
/// <summary>RynthCore Options > Diagnostics (the server picker; RynthCore 2026.10.5.54+).</summary>
/// <summary>The server picker: RynthCore Settings > Game Client (on Diagnostics until 2026-11-11, hence the name; RynthCore 2026.10.5.54+).</summary>
public const string Diagnostics = "/rc diagnostics";
/// <summary>
@ -41,7 +41,7 @@ internal static class MovedTabs
public static string HomeOf(string command) => command switch
{
OracleCharacter => "RynthOracle's Character tab",
Diagnostics => "RynthCore Options > Diagnostics",
Diagnostics => "RynthCore Settings > Game Client",
Settings => "RynthAi Settings (Advanced Settings)",
_ => command,
};

View file

@ -85,17 +85,35 @@ internal static class SectionsManifest
public const string MonsterStatsTitle = RynthAiPlugin.MonsterStatsTitle, MonsterStatsSurface = RynthAiPlugin.MonsterStatsSurface;
/// <summary>
/// The manifest JSON for <paramref name="views"/> (UTF-8 text, schema version 1), with the dashboard
/// window when <paramref name="dashboard"/> and the Monster Stats window when <paramref name="monsterStats"/>.
/// The Timed Commands window (RynthAiPlugin.TimedCommands.cs, 2026-11-03): commands sent every N
/// seconds, per character, server and for all, drawn by RynthAi (plugin API v89). No bar button
/// and no bar menu: the dashboard's options menu (Timed commands) and /ra timed show open it.
/// </summary>
public static string Build(IReadOnlyList<View> views, IReadOnlyList<Section> sections, bool dashboard = false, bool monsterStats = false)
public const string TimedCommandsTitle = RynthAiPlugin.TimedCommandsTitle, TimedCommandsSurface = RynthAiPlugin.TimedCommandsSurface;
/// <summary>
/// The Active Gear window (RynthAiPlugin.ActiveGear.cs, 2026-11-11): which worn items have their magic
/// on, their mana and time left, drawn by RynthAi in the engine's frame (plugin API v89). No bar button
/// and no bar menu: the dashboard's options menu (Active gear) and /ra gear open it.
/// </summary>
public const string ActiveGearTitle = RynthAiPlugin.ActiveGearTitle, ActiveGearSurface = RynthAiPlugin.ActiveGearSurface;
/// <summary>
/// The manifest JSON for <paramref name="views"/> (UTF-8 text, schema version 1), with the dashboard
/// window when <paramref name="dashboard"/>, the Monster Stats window when <paramref name="monsterStats"/>,
/// the Timed Commands window when <paramref name="timedCommands"/> and the Active Gear window when
/// <paramref name="activeGear"/>.
/// </summary>
public static string Build(IReadOnlyList<View> views, IReadOnlyList<Section> sections, bool dashboard = false, bool monsterStats = false,
bool timedCommands = false, bool activeGear = false)
{
using var stream = new MemoryStream(4096);
using (var w = new Utf8JsonWriter(stream))
{
w.WriteStartObject();
w.WriteNumber("version", 1);
if (dashboard || monsterStats)
bool windows = dashboard || monsterStats || timedCommands || activeGear;
if (windows)
w.WriteStartArray("windows");
if (dashboard)
{
@ -130,7 +148,37 @@ internal static class SectionsManifest
w.WriteBoolean("edgeToEdge", true);
w.WriteEndObject();
}
if (dashboard || monsterStats)
if (timedCommands)
{
w.WriteStartObject();
w.WriteString("id", "timedcommands");
w.WriteString("title", TimedCommandsTitle);
w.WriteString("surface", TimedCommandsSurface);
w.WriteString("icon", RynthCore.Plugin.Shared.RynthUi.RynthIcons.Hourglass);
w.WriteNumber("width", 640);
w.WriteNumber("height", 300);
w.WriteNumber("minWidth", 480);
w.WriteNumber("minHeight", 160);
w.WriteBoolean("bar", false);
w.WriteBoolean("edgeToEdge", true);
w.WriteEndObject();
}
if (activeGear)
{
w.WriteStartObject();
w.WriteString("id", "activegear");
w.WriteString("title", ActiveGearTitle);
w.WriteString("surface", ActiveGearSurface);
w.WriteString("icon", RynthCore.Plugin.Shared.RynthUi.RynthIcons.BatteryCharging);
w.WriteNumber("width", 640);
w.WriteNumber("height", 320);
w.WriteNumber("minWidth", 420);
w.WriteNumber("minHeight", 140);
w.WriteBoolean("bar", false);
w.WriteBoolean("edgeToEdge", true);
w.WriteEndObject();
}
if (windows)
w.WriteEndArray();
w.WriteStartArray("sections");
foreach (Section s in sections)

View file

@ -0,0 +1,180 @@
// ItemInfoPartColors.cs — a colour per part of the one-line item info (2026-11-11).
//
// A player asked for the Mag-style one-liner with its name, armour / damage, spells, set,
// value / burden, workmanship ... each in a colour of its own, instead of one colour for the line.
// MagItemDescription.ToOneLineParts gives the line as (part, text) pieces; this file turns them
// into character ranges and the payload RynthCore's chat takes:
//
// SendPluginCommand("RynthCore.Chat", "nextspans", "start:length:RRGGBB;start:length:RRGGBB")
//
// (engine UI/Data/ChatOwnColors.cs). Text outside every range (the prefix, the ", " between parts,
// the "not identified" and loot verdict tails) keeps the line's colour: the Info text colour, else
// the chat type's own. No dependencies besides System, so Tools/RynthCore.RynthAiTests compiles it in.
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthAi.ItemInfo;
/// <summary>What a piece of the one-line item info is, for its colour. None = the line's own colour.</summary>
internal enum ItemInfoPart
{
None,
/// <summary>"[Material ]Name[ (DamageType Mastery)]".</summary>
Name,
/// <summary>Equipment set.</summary>
Set,
/// <summary>T11 tier, quality, gear grade, property slots, tainted, weapon grade.</summary>
Tier,
/// <summary>Armour level, damage, variance, elemental / damage bonuses, base protections.</summary>
Stats,
/// <summary>Imbues, procs, armour cleaving, crushing / biting, cleaving / multi-strike, splits, range, slayer.</summary>
Special,
/// <summary>Attack, defence and mana conversion percents.</summary>
Bonus,
/// <summary>Spell names.</summary>
Spells,
/// <summary>The "[D 3, CD 2]" ratings cluster and T11 modifiers.</summary>
Ratings,
/// <summary>Wield / activation / use requirements and arcane lore difficulty.</summary>
Requirements,
/// <summary>Workmanship ("Craft 8", salvage "Work"), tinks and applied materials.</summary>
Craft,
/// <summary>Value and burden.</summary>
ValueBurden,
}
internal static class ItemInfoPartColors
{
/// <summary>The engine takes at most this many ranges for one line (ChatOwnColors.MaxSpans).</summary>
public const int MaxSpans = 32;
/// <summary>The SendPluginCommand action ("RynthCore.Chat" target) that arms the ranges for the next line.</summary>
public const string NextSpansAction = "nextspans";
/// <summary>
/// Each part's colour ("#RRGGBB"), close to how AC's appraisal panel and chat colour such things:
/// the name amber, sets green, spells magic blue, ratings cyan, requirements rose, value grey.
/// <c>Label</c> is what the Item Info window's legend and the sample line call the part.
/// </summary>
public static readonly (ItemInfoPart Part, string Label, string Color)[] Defaults =
{
(ItemInfoPart.Name, "Name", "#E6B450"),
(ItemInfoPart.Set, "Set", "#80FF7F"),
(ItemInfoPart.Tier, "Tier / grade", "#D2D264"),
(ItemInfoPart.Stats, "Armour / damage", "#FFFFFF"),
(ItemInfoPart.Special, "Imbues / slayer", "#FF7FFF"),
(ItemInfoPart.Bonus, "Attack / defence %", "#9FD8C8"),
(ItemInfoPart.Spells, "Spells", "#3FBFFF"),
(ItemInfoPart.Ratings, "Ratings", "#3FDCDC"),
(ItemInfoPart.Requirements, "Requirements", "#FF9696"),
(ItemInfoPart.Craft, "Workmanship / tinks", "#EE921E"),
(ItemInfoPart.ValueBurden, "Value / burden", "#A8A8A8"),
};
/// <summary>A part's colour ("#RRGGBB"), or "" for <see cref="ItemInfoPart.None"/> (the line's own).</summary>
public static string ColorOf(ItemInfoPart part)
{
foreach (var d in Defaults)
if (d.Part == part) return d.Color;
return string.Empty;
}
/// <summary>
/// The coloured ranges of a line whose text is <paramref name="offset"/> characters of something
/// else (the prefix) followed by the pieces in order. Pieces of one part next to each other, and
/// what lies between them (", " between two spells), become one range; empty and uncoloured
/// pieces make none. At most <see cref="MaxSpans"/>: later parts keep the line's colour.
/// </summary>
public static List<(int Start, int Length, string Color)> Ranges(IReadOnlyList<(ItemInfoPart Part, string Text)> pieces, int offset = 0)
{
var ranges = new List<(int Start, int Length, string Color)>();
int pos = Math.Max(0, offset);
// The open range: its part, start, and end (exclusive) of its last coloured piece.
ItemInfoPart openPart = ItemInfoPart.None;
int openStart = 0, openEnd = 0;
// Uncoloured text since the open range's last piece: only separators may join two pieces.
bool gapIsSeparator = true;
void Close()
{
if (openPart != ItemInfoPart.None && openEnd > openStart && ranges.Count < MaxSpans)
ranges.Add((openStart, openEnd - openStart, ColorOf(openPart)));
openPart = ItemInfoPart.None;
}
foreach (var (part, text) in pieces)
{
string t = text ?? string.Empty;
if (t.Length == 0) continue;
string color = ColorOf(part);
if (color.Length == 0)
{
if (!IsSeparator(t)) gapIsSeparator = false;
pos += t.Length;
continue;
}
if (part == openPart && gapIsSeparator) openEnd = pos + t.Length; // the same part again: one range
else
{
Close();
openPart = part;
openStart = pos;
openEnd = pos + t.Length;
}
gapIsSeparator = true;
pos += t.Length;
}
Close();
return ranges;
}
/// <summary>", " and the like: what may sit inside one range between two pieces of a part.</summary>
private static bool IsSeparator(string t)
{
foreach (char c in t)
if (c != ',' && c != ' ' && c != ';') return false;
return true;
}
/// <summary>
/// The ranges as the engine's "nextspans" payload: "start:length:RRGGBB" joined by ';'
/// ("" when there are none, or when a range doesn't fit a line <paramref name="lineLength"/> long).
/// </summary>
public static string Payload(IReadOnlyList<(int Start, int Length, string Color)> ranges, int lineLength)
{
var sb = new StringBuilder(ranges.Count * 14);
int prevEnd = 0;
foreach (var (start, length, color) in ranges)
{
string hex = color.StartsWith('#') ? color[1..] : color;
if (start < prevEnd || length < 1 || start + length > lineLength || hex.Length != 6) return string.Empty;
if (sb.Length > 0) sb.Append(';');
sb.Append(start).Append(':').Append(length).Append(':').Append(hex);
prevEnd = start + length;
}
return sb.ToString();
}
/// <summary>
/// A sample line for the window's Test button: every part's label, comma-separated, as pieces
/// (so it is coloured exactly like a real line).
/// </summary>
public static List<(ItemInfoPart Part, string Text)> SamplePieces()
{
var pieces = new List<(ItemInfoPart Part, string Text)>(Defaults.Length * 2);
foreach (var d in Defaults)
{
if (pieces.Count > 0) pieces.Add((ItemInfoPart.None, ", "));
pieces.Add((d.Part, d.Label));
}
return pieces;
}
/// <summary>The pieces' text, joined.</summary>
public static string Join(IReadOnlyList<(ItemInfoPart Part, string Text)> pieces)
{
var sb = new StringBuilder(256);
foreach (var (_, text) in pieces) sb.Append(text);
return sb.ToString();
}
}

View file

@ -92,10 +92,16 @@ internal sealed class MagItemDescription
/// <summary>The title's "(DamageType Mastery)" text without the brackets, or "".</summary>
public string TypeMastery = string.Empty;
public readonly List<(MagItemSection Section, string Text)> Segments = new();
/// <summary>What each of <see cref="Segments"/> is, for its colour (same index; 2026-11-11 per-part colours).</summary>
public readonly List<ItemInfoPart> SegmentParts = new();
public void Add(MagItemSection section, string text)
public void Add(MagItemSection section, string text) => Add(section, ItemInfoPart.None, text);
public void Add(MagItemSection section, ItemInfoPart part, string text)
{
if (!string.IsNullOrEmpty(text)) Segments.Add((section, text));
if (string.IsNullOrEmpty(text)) return;
Segments.Add((section, text));
SegmentParts.Add(part);
}
/// <summary>Classic Mag one-liner: title, then every field comma-separated.</summary>
@ -106,6 +112,21 @@ internal sealed class MagItemDescription
return sb.ToString();
}
/// <summary>
/// <see cref="ToOneLine"/> as (part, text) pieces, the ", " between fields uncoloured: joined
/// they are exactly that line (<see cref="ItemInfoPartColors"/> colours them).
/// </summary>
public List<(ItemInfoPart Part, string Text)> ToOneLineParts()
{
var pieces = new List<(ItemInfoPart Part, string Text)>(Segments.Count * 2 + 1) { (ItemInfoPart.Name, Title) };
for (int i = 0; i < Segments.Count; i++)
{
pieces.Add((ItemInfoPart.None, ", "));
pieces.Add((i < SegmentParts.Count ? SegmentParts[i] : ItemInfoPart.None, Segments[i].Text));
}
return pieces;
}
/// <summary>
/// Pet-roster layout: line 1 is always present; empty stat / requirement / spell lines are
/// dropped so plain armor stays short.
@ -304,58 +325,58 @@ internal static class MagItemDescriber
// ── Set ─────────────────────────────────────────────────────────────────
int set = Int(IntEquipmentSet);
if (set > 0 && Show(MagItemInfoField.Set))
d.Add(Id, MagItemInfoTables.EquipmentSets.TryGetValue(set, out string? setName) ? setName : $"Unknown set {set}");
d.Add(Id, ItemInfoPart.Set, MagItemInfoTables.EquipmentSets.TryGetValue(set, out string? setName) ? setName : $"Unknown set {set}");
// ── T11 state: "T16, Gear B+ (4 lines), Props 3/5, Tainted" ───────────
if (t11.IsT11 && Show(MagItemInfoField.T11))
{
// "~" marks a tier estimated from the wield gates (older server, or not yet IDed).
d.Add(Id, t11.TierIsExact ? "T" + I(t11.Tier) : "~T" + I(t11.Tier));
if (t11.WeaponQuality >= 0) d.Add(Id, "Quality " + I(t11.WeaponQuality));
d.Add(Id, ItemInfoPart.Tier, t11.TierIsExact ? "T" + I(t11.Tier) : "~T" + I(t11.Tier));
if (t11.WeaponQuality >= 0) d.Add(Id, ItemInfoPart.Tier, "Quality " + I(t11.WeaponQuality));
if (t11.GearGradeRank > 0)
d.Add(Id, t11.GearGradeLines > 0 ? $"Gear {t11.GearGrade} ({I(t11.GearGradeLines)} lines)" : $"Gear {t11.GearGrade}");
d.Add(Id, ItemInfoPart.Tier, t11.GearGradeLines > 0 ? $"Gear {t11.GearGrade} ({I(t11.GearGradeLines)} lines)" : $"Gear {t11.GearGrade}");
if (t11.PropertySlots >= 0)
d.Add(Id, t11.PropertySlotCap > 0 ? $"Props {I(t11.PropertySlots)}/{I(t11.PropertySlotCap)}" : $"Props {I(t11.PropertySlots)}");
if (t11.Tainted) d.Add(Id, "Tainted");
d.Add(Id, ItemInfoPart.Tier, t11.PropertySlotCap > 0 ? $"Props {I(t11.PropertySlots)}/{I(t11.PropertySlotCap)}" : $"Props {I(t11.PropertySlots)}");
if (t11.Tainted) d.Add(Id, ItemInfoPart.Tier, "Tainted");
}
// ── Armor level ─────────────────────────────────────────────────────────
int al = Int(IntArmorLevel);
if (al > 0 && Show(MagItemInfoField.ArmorLevel)) d.Add(Id, "AL " + I(al));
if (al > 0 && Show(MagItemInfoField.ArmorLevel)) d.Add(Id, ItemInfoPart.Stats, "AL " + I(al));
// ── Imbues (ImbuedEffect 179 plus ImbuedEffect2..5 = 303..306) ─────────
if (Show(MagItemInfoField.Imbues))
d.Add(Cbt, ImbueLabels(Int(IntImbued) | Int(303) | Int(304) | Int(305) | Int(306), ImbueStrengths(longDesc)));
d.Add(Cbt, ItemInfoPart.Special, ImbueLabels(Int(IntImbued) | Int(303) | Int(304) | Int(305) | Int(306), ImbueStrengths(longDesc)));
if (Has(Field.ArmorCleave) && Show(MagItemInfoField.ArmorCleave) && Dbl(FloatIgnoreArmor, 0) != 0)
d.Add(Cbt, "AC");
d.Add(Cbt, ItemInfoPart.Special, "AC");
if (Has(Field.CritStats) && Show(MagItemInfoField.CritStats))
{
// A crit deals 1 + CriticalMultiplier; a stored 1.0 is a normal 2x crit, so ACE only
// calls it Crushing Blow above 1.0.
double critMult = Dbl(FloatCritMultiplier, 0);
if (critMult > 1) d.Add(Cbt, $"Crushing Blow {Fmt(critMult + 1)}x");
if (critMult > 1) d.Add(Cbt, ItemInfoPart.Special, $"Crushing Blow {Fmt(critMult + 1)}x");
// Biting Strike replaces the base crit chance with this fraction.
double critFreq = Dbl(FloatCritFrequency, 0);
if (critFreq > 0) d.Add(Cbt, $"Biting Strike {Math.Round(critFreq * 100).ToString(CultureInfo.InvariantCulture)}%");
if (critFreq > 0) d.Add(Cbt, ItemInfoPart.Special, $"Biting Strike {Math.Round(critFreq * 100).ToString(CultureInfo.InvariantCulture)}%");
}
// T11 Cast on Strike procs: "Proc Force Arc 13%".
if (Show(MagItemInfoField.Imbues))
foreach (var (procName, chance) in t11.Procs)
d.Add(Cbt, $"Proc {procName} {Fmt(chance)}%");
d.Add(Cbt, ItemInfoPart.Special, $"Proc {procName} {Fmt(chance)}%");
if (Has(Field.Splits) && Show(MagItemInfoField.Splits))
{
int splits = Int(IntSplitArrows);
if (splits > 0) d.Add(Cbt, $"Splits ({I(splits)})");
if (splits > 0) d.Add(Cbt, ItemInfoPart.Special, $"Splits ({I(splits)})");
}
if (Has(Field.Range) && Show(MagItemInfoField.Range))
{
int yards = MissileRangeYards(Dbl(FloatMaxVelocity, 0));
if (yards > 0) d.Add(Cbt, $"Range {I(yards)}yd");
if (yards > 0) d.Add(Cbt, ItemInfoPart.Special, $"Range {I(yards)}yd");
}
if (Has(Field.Cleaves) && Show(MagItemInfoField.CleaveMultiStrike))
@ -363,31 +384,31 @@ internal static class MagItemDescriber
int attackType = Int(IntAttackType);
int mastery = Int(IntWeaponType);
bool cleaving = (attackType == 4 && mastery == 11) || (attackType == 1 && mastery != 11 && mastery != 0);
if (cleaving) d.Add(Cbt, "Cleaving");
else if (attackType is 160 or 166) d.Add(Cbt, "Multi-Strike");
else if (attackType == 486) d.Add(Cbt, "Multi-Strike (3)");
if (cleaving) d.Add(Cbt, ItemInfoPart.Special, "Cleaving");
else if (attackType is 160 or 166) d.Add(Cbt, ItemInfoPart.Special, "Multi-Strike");
else if (attackType == 486) d.Add(Cbt, ItemInfoPart.Special, "Multi-Strike (3)");
}
// ── Slayer ──────────────────────────────────────────────────────────────
if (Has(Field.Slayer) && Show(MagItemInfoField.Slayer))
{
string? slayer = MagItemInfoTables.CreatureTypeName(Int(IntSlayerCreature));
if (slayer != null) d.Add(Cbt, slayer + " Slayer");
if (slayer != null) d.Add(Cbt, ItemInfoPart.Special, slayer + " Slayer");
}
// ── Tinks + applied materials (TinkerLog) ──────────────────────────────
int tinks = Int(IntTinks);
if (tinks > 0 && Show(MagItemInfoField.Tinks)) d.Add(Id, "Tinks " + I(tinks));
if (tinks > 0 && Show(MagItemInfoField.Tinks)) d.Add(Id, ItemInfoPart.Craft, "Tinks " + I(tinks));
if (Show(MagItemInfoField.Applied))
{
string applied = FormatTinkerLog(item.GetString(StringTinkerLog));
if (applied.Length > 0) d.Add(Id, "Applied: " + applied);
if (applied.Length > 0) d.Add(Id, ItemInfoPart.Craft, "Applied: " + applied);
}
// ── Damage ──────────────────────────────────────────────────────────────
// T11 weapon grade sits with the identity fields: "Grade S (100%)".
if (Has(Field.Damage) && Show(MagItemInfoField.Damage) && t11.GradeRank > 0)
d.Add(Id, t11.DamagePercent >= 0 ? $"Grade {t11.Grade} ({I(t11.DamagePercent)}%)" : $"Grade {t11.Grade}");
d.Add(Id, ItemInfoPart.Tier, t11.DamagePercent >= 0 ? $"Grade {t11.Grade} ({I(t11.DamagePercent)}%)" : $"Grade {t11.Grade}");
if (Has(Field.Damage) && Show(MagItemInfoField.Damage))
AddDamage(d, cls, Int(IntMaxDamage), Dbl(FloatVariance, 0), Int(IntElementalBonus),
@ -402,7 +423,7 @@ internal static class MagItemDescriber
if (Has(Field.ManaConversion) && Show(MagItemInfoField.ManaConversion))
{
double mc = Dbl(FloatManaConversion, 0);
if (mc != 0) d.Add(Cbt, Math.Round(mc * 100).ToString(CultureInfo.InvariantCulture) + "%mc");
if (mc != 0) d.Add(Cbt, ItemInfoPart.Bonus, Math.Round(mc * 100).ToString(CultureInfo.InvariantCulture) + "%mc");
}
// ── Spells ──────────────────────────────────────────────────────────────
@ -417,27 +438,27 @@ internal static class MagItemDescriber
AddWieldRequirement(d, Int(IntWieldReq2), Int(IntWieldSkill2), Int(IntWieldValue2));
// T11 gates (item augs, Triune Weave, charms) only exist as "Wield requires:" text.
foreach (T11WieldGate gate in t11.WieldGates)
d.Add(Req, $"Wield {gate.Amount.ToString("N0", CultureInfo.InvariantCulture)} {GateName(gate.Counter)}");
d.Add(Req, ItemInfoPart.Requirements, $"Wield {gate.Amount.ToString("N0", CultureInfo.InvariantCulture)} {GateName(gate.Counter)}");
}
if (Show(MagItemInfoField.Activation))
{
int useLevel = Int(IntUseRequiresLevel);
if (useLevel > 0) d.Add(Req, "Lvl " + I(useLevel));
if (useLevel > 0) d.Add(Req, ItemInfoPart.Requirements, "Lvl " + I(useLevel));
// "Melee Defense 300 to Activate" — hidden when the wield requirement already covers it.
int actSkill = Int(IntActivationSkill), actLevel = Int(IntActivationLevel);
if (actLevel > 0 && (Int(IntWieldSkill) != actSkill || Int(IntWieldValue) < actLevel))
d.Add(Req, $"{SkillName(actSkill)} {I(actLevel)} to Activate");
d.Add(Req, ItemInfoPart.Requirements, $"{SkillName(actSkill)} {I(actLevel)} to Activate");
// Summoning essences / gems.
int useSkill = Int(IntUseRequiresSkill), useSkillLvl = Int(IntUseRequiresSkillLvl), useSpec = Int(IntUseRequiresSpec);
if (useSkill > 0 && useSkillLvl > 0) d.Add(Req, $"{SkillName(useSkill)} {I(useSkillLvl)}");
if (useSpec > 0 && useSkillLvl > 0) d.Add(Req, $"Spec {SkillName(useSpec)} {I(useSkillLvl)}");
if (useSkill > 0 && useSkillLvl > 0) d.Add(Req, ItemInfoPart.Requirements, $"{SkillName(useSkill)} {I(useSkillLvl)}");
if (useSpec > 0 && useSkillLvl > 0) d.Add(Req, ItemInfoPart.Requirements, $"Spec {SkillName(useSpec)} {I(useSkillLvl)}");
}
int diff = Int(IntItemDifficulty);
if (diff > 0 && Show(MagItemInfoField.Difficulty)) d.Add(Req, "Diff " + I(diff));
if (diff > 0 && Show(MagItemInfoField.Difficulty)) d.Add(Req, ItemInfoPart.Requirements, "Diff " + I(diff));
// ── Workmanship ─────────────────────────────────────────────────────────
int work = Show(MagItemInfoField.Craft) ? Int(IntWorkmanship) : 0;
@ -447,12 +468,12 @@ internal static class MagItemDescriber
if (work > 0)
{
double avg = items > 0 ? (double)work / items : work;
d.Add(Id, "Work " + avg.ToString("N2", CultureInfo.InvariantCulture));
d.Add(Id, ItemInfoPart.Craft, "Work " + avg.ToString("N2", CultureInfo.InvariantCulture));
}
}
else if (work > 0 && tinks != 10) // Mag: hide craft once fully tinked
{
d.Add(Id, "Craft " + I(work));
d.Add(Id, ItemInfoPart.Craft, "Craft " + I(work));
}
// ── Unenchantable armor: base protections [S/P/B/C/F/A/L] ─────────────
@ -464,21 +485,21 @@ internal static class MagItemDescriber
if (i > 0) prot.Append('/');
prot.Append(Dbl(FloatArmorVsSlash + i, 0).ToString("N1", CultureInfo.InvariantCulture));
}
d.Add(Cbt, prot.Append(']').ToString());
d.Add(Cbt, ItemInfoPart.Stats, prot.Append(']').ToString());
}
if (options.ShowValueAndBurden)
{
int value = Int(IntValue);
if (value > 0) d.Add(Req, "Value " + value.ToString("N0", CultureInfo.InvariantCulture));
if (value > 0) d.Add(Req, ItemInfoPart.ValueBurden, "Value " + value.ToString("N0", CultureInfo.InvariantCulture));
int burden = Int(IntBurden);
if (burden > 0) d.Add(Req, "BU " + I(burden));
if (burden > 0) d.Add(Req, ItemInfoPart.ValueBurden, "BU " + I(burden));
}
// ── Ratings ─────────────────────────────────────────────────────────────
if (Show(MagItemInfoField.Ratings))
{
d.Add(MagItemSection.Ratings, RatingsCluster(item, options.HiddenRatings));
d.Add(MagItemSection.Ratings, ItemInfoPart.Ratings, RatingsCluster(item, options.HiddenRatings));
// T11 zone modifiers: the server drops a modifier's Gear* rating from the ratings it
// sends, so the modifier lines are the only place those values appear.
if (t11.Modifiers.Count > 0)
@ -491,7 +512,7 @@ internal static class MagItemDescriber
if (m.Locked) mod += " (Locked)";
mods.Add(mod);
}
d.Add(MagItemSection.Ratings, "Mods: " + string.Join(", ", mods));
d.Add(MagItemSection.Ratings, ItemInfoPart.Ratings, "Mods: " + string.Join(", ", mods));
}
}
@ -595,18 +616,18 @@ internal static class MagItemDescriber
string max = maxDmg.ToString(CultureInfo.InvariantCulture);
// The appraisal panel rounds the low end to a whole number (2069 * 0.865 → 1790).
long min = (long)Math.Round(maxDmg * (1 - variance), MidpointRounding.AwayFromZero);
d.Add(Cbt, variance > 0 ? min.ToString(CultureInfo.InvariantCulture) + "-" + max : max);
d.Add(Cbt, ItemInfoPart.Stats, variance > 0 ? min.ToString(CultureInfo.InvariantCulture) + "-" + max : max);
}
// Three places: loot variances are often x.xx5 and two places would misreport them.
if (variance > 0)
d.Add(Cbt, Math.Round(variance, 3).ToString("0.###", CultureInfo.InvariantCulture) + "v");
d.Add(Cbt, ItemInfoPart.Stats, Math.Round(variance, 3).ToString("0.###", CultureInfo.InvariantCulture) + "v");
if (elemBonus != 0)
d.Add(Cbt, "+" + elemBonus.ToString(CultureInfo.InvariantCulture));
d.Add(Cbt, ItemInfoPart.Stats, "+" + elemBonus.ToString(CultureInfo.InvariantCulture));
// A missing/zero multiplier means "no bonus" (0 would print as -100%).
if (dmgMod > 0 && dmgMod != 1)
d.Add(Cbt, "+" + Math.Round((dmgMod - 1) * 100).ToString(CultureInfo.InvariantCulture) + "%");
d.Add(Cbt, ItemInfoPart.Stats, "+" + Math.Round((dmgMod - 1) * 100).ToString(CultureInfo.InvariantCulture) + "%");
if (vsMonsters > 0 && vsMonsters != 1)
d.Add(Cbt, "+" + Math.Round((vsMonsters - 1) * 100).ToString(CultureInfo.InvariantCulture) + "% vs. Monsters");
d.Add(Cbt, ItemInfoPart.Stats, "+" + Math.Round((vsMonsters - 1) * 100).ToString(CultureInfo.InvariantCulture) + "% vs. Monsters");
}
/// <summary>Mag "+18%a" from a 1.0-based multiplier; skips missing (≤0) and neutral 1.0.</summary>
@ -616,7 +637,7 @@ internal static class MagItemDescriber
double pct = Math.Round((multiplier - 1) * 100, decimals);
if (pct == 0) return; // rounds to nothing at this precision
// Signed like the appraisal panel ("Bonus to Attack Skill +20%"); penalties keep their '-'.
d.Add(MagItemSection.Combat, (pct > 0 ? "+" : "") + pct.ToString(CultureInfo.InvariantCulture) + suffix);
d.Add(MagItemSection.Combat, ItemInfoPart.Bonus, (pct > 0 ? "+" : "") + pct.ToString(CultureInfo.InvariantCulture) + suffix);
}
/// <summary>"Wield Lvl 180" for a level requirement, else "Heavy Weapons 375".</summary>
@ -625,7 +646,7 @@ internal static class MagItemDescriber
// Int64 gates name a counter, not a skill; the T11 text supplies those.
if (value <= 0 || reqType == WieldReqInt64Stat) return;
string v = value.ToString(CultureInfo.InvariantCulture);
d.Add(MagItemSection.Requirements, reqType == 7 // WieldRequirement.Level
d.Add(MagItemSection.Requirements, ItemInfoPart.Requirements, reqType == 7 // WieldRequirement.Level
? "Wield Lvl " + v
: SkillName(skillOrAttr) + " " + v);
}
@ -667,11 +688,11 @@ internal static class MagItemDescriber
string name = SpellDatabase.GetSpellName(id);
SpellDatabase.TryGetSpellMeta(id, out int family, out int difficulty);
if (ShouldShowSpell(name, family, difficulty, unenchantable))
d.Add(MagItemSection.Spells, name);
d.Add(MagItemSection.Spells, ItemInfoPart.Spells, name);
}
if (verboseList == null || verboseList.Length == 0) return;
if (skippedVerbose > 0) verboseList.Append("; (+").Append(skippedVerbose).Append(" more spells)");
d.Add(MagItemSection.Spells, verboseList.ToString());
d.Add(MagItemSection.Spells, ItemInfoPart.Spells, verboseList.ToString());
}
private static bool ShouldShowSpell(string name, int family, int difficulty, bool unenchantable)

View file

@ -106,6 +106,13 @@ public sealed class MagItemInfoSettings
/// </summary>
public string TextColor = string.Empty;
/// <summary>
/// "Colour each part" (2026-11-11): the one-line layout's name, set, armour / damage, spells,
/// ratings, requirements, workmanship, value / burden ... each in its own colour in RynthCore's
/// chat (ItemInfoPartColors); the rest of the line keeps <see cref="TextColor"/>, else the chat
/// type's colour. Off by default and in every profile before it: one colour, as before.
/// </summary>
public bool PartColors;
/// <summary>
/// Text put in front of every line. RynthChat files lines starting "[RynthAi Item] " under
/// its Items tab (ChatClassifier.IsItemInfo).
/// </summary>
@ -156,7 +163,7 @@ public sealed class MagItemInfoSettings
HiddenFields = d.HiddenFields; HiddenRatings = d.HiddenRatings;
ShowValueAndBurden = d.ShowValueAndBurden;
SpellMode = d.SpellMode; MaxListedSpells = d.MaxListedSpells;
ChatType = d.ChatType; Prefix = d.Prefix; TextColor = d.TextColor;
ChatType = d.ChatType; Prefix = d.Prefix; TextColor = d.TextColor; PartColors = d.PartColors;
}
}

View file

@ -360,9 +360,14 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Checkbox("Start Macro On Login", ref _settings.StartMacroOnLogin);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Automatically starts the macro when RynthAi loads.");
ImGui.Checkbox("Patrol On Login", ref _settings.PatrolOnLogin);
if (ImGui.Checkbox("Patrol On Login", ref _settings.PatrolOnLogin) && _settings.PatrolOnLogin)
_settings.HuntOnLogin = false; // one or the other (LoginAutoStart)
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Automatically starts dungeon patrol when RynthAi loads.");
if (ImGui.Checkbox("Hunt On Login", ref _settings.HuntOnLogin) && _settings.HuntOnLogin)
_settings.PatrolOnLogin = false;
if (ImGui.IsItemHovered())
ImGui.SetTooltip(LoginAutoStart.HuntOnLoginTip);
ImGui.Checkbox("Resume Meta After Reload", ref _settings.ResumeMetaOnReload);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("After a hot reload the meta carries on in the same state, with its variables,\nfired rules and route. A real login still starts in Default.");

View file

@ -3,13 +3,20 @@
// read directly, plus the vitals refresh that the engine's snapshot poll used to drive.
using System;
using System.IO;
using RynthCore.Plugin.RynthAi.Dashboard;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// <summary>
/// One frame of the dashboard: the macro, the subsystems, the bot's activity, the target and the vitals.
/// The target is the selection, or the monster RynthAi is fighting (TargetIsFight: combat doesn't
/// select it). TargetHealth is 0..1, or -1 while the server hasn't said.
/// select it). TargetHealth is 0..1, or -1 while the server hasn't said. CombatStance is the
/// client's combat mode for the Combat key's icon (Melee, Missile or Magic; in peace, the last one).
/// NavKind is what the Navigation key's icon shows (the route's type, follow, patrol or hunt).
/// BoostLoot: Boost Loot Priority is on where it applies (the Looting key's chest turns gold).
/// NavPriority: Boost Nav Priority is on and the route isn't a finished Once route (the
/// Navigation key's trail turns green over a lane, for a route, follow or patrol).
/// MetaLoaded: a meta with rules is loaded (the Meta key's states are hollow otherwise).
/// </summary>
internal readonly record struct DashboardReadout(
bool MacroRunning,
@ -23,7 +30,12 @@ internal readonly record struct DashboardReadout(
string LootPath,
bool TargetIsFight = false,
int LootMode = 0,
bool BoostNav = false);
bool BoostNav = false,
int CombatStance = CombatMode.Melee,
NavTrail.Kind NavKind = NavTrail.Kind.None,
bool BoostLoot = false,
bool NavPriority = false,
bool MetaLoaded = false);
/// <summary>The loaded-files pickers: each list, and the entry in use.</summary>
internal sealed record DashboardFiles(
@ -52,7 +64,13 @@ internal sealed partial class LegacyDashboardRenderer
_isLocked, _bgOpacity,
!string.IsNullOrEmpty(_vendorProfilePath?.Invoke()) ? _vendorProfilePath!.Invoke() : _settings.CurrentLootPath ?? string.Empty,
LootMode: Loot.LootModes.Clamp(_settings.LootMode),
BoostNav: BoostNavRule.Active(_settings)); // the flag counts only while a nav route runs
BoostNav: BoostNavRule.Active(_settings), // the flag counts only while a nav route runs
// Boost Loot Priority waits for no corpse when only rares are looted (the looter's own rule,
// CorpseOpenController.BoostLootCanRun), so the chest isn't gilded then.
BoostLoot: _settings.BoostLootPriority && !_settings.LootOnlyRareCorpses && !Loot.LootModes.IsRares(_settings.LootMode),
// Shown before RUN too (BoostNav above is only while the route runs); a Once route that
// has walked off its end hunts instead (BoostNavRule), so it isn't shown then.
NavPriority: _settings.BoostNavPriority && !_settings.NavRouteFinished());
}
/// <summary>The five pickers' lists (copied under the lists' lock) and the entry in use. Any thread.</summary>

View file

@ -0,0 +1,435 @@
using System;
using System.Collections.Generic;
using System.IO;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// <summary>The kinds of profile the Loaded files drawer lists (the numbers of <see cref="LegacyDashboardRenderer.SelectProfileAtIndex"/>).</summary>
internal enum ProfileKind { Nav = 0, Loot = 1, Meta = 2, Settings = 3, Buffs = 4 }
/// <summary>What a profile button or its /ra verb does.</summary>
internal enum ProfileVerb { Save, SaveAs, New, Rename, Delete, Folder, Edit }
/// <summary>
/// The result of a profile button or verb: the chat line ("[RynthAi] ..."), whether it worked, and
/// for Save As onto another file, that it needs the player's yes first (nothing was written).
/// </summary>
internal readonly record struct ProfileResult(bool Ok, string Text, bool NeedsReplace = false)
{
public static ProfileResult Done(string text) => new(true, "[RynthAi] " + text);
public static ProfileResult Failed(string text) => new(false, "[RynthAi] " + text);
}
/// <summary>What the profile row shows: the name in use, its file, unsaved changes, the folder.</summary>
internal sealed record ProfileFileInfo(string Name, string Path, bool HasFile, bool Unsaved, string Folder);
// The Loaded files drawer's profile buttons (2026-11-11): Save, Save As, New, Rename, Move to
// Deleted and Open folder for the settings profile, the nav, the meta and the loot profile, and
// the /ra verbs that do the same. The loads and saves are the ones the pickers and the commands
// already use (SaveRoute, LoadNavByName, LoadMetaByName, SaveAsProfile, the meta's Save As);
// ProfileFileOps does the renames and the moves into Deleted. Plugin tick, except ProfileInfo.
internal sealed partial class LegacyDashboardRenderer
{
internal static readonly string[] NavExtensions = NewProfileFiles.NavExtensions;
internal static readonly string[] MetaExtensions = NewProfileFiles.MetaExtensions;
internal static readonly string[] LootExtensions = { ".utl", ".json" };
internal static readonly string[] SettingsExtensions = { ".json" };
/// <summary>The settings profile everyone has: it can't be renamed or moved to Deleted.</summary>
internal const string DefaultProfileName = "Default";
/// <summary>
/// Files in the character's folder that aren't settings profiles (RefreshProfilesList skips
/// them): a settings profile can't take one of these names.
/// </summary>
internal static bool IsReservedSettingsName(string name) =>
name.Equals("settings", StringComparison.OrdinalIgnoreCase)
|| name.Equals("monsters", StringComparison.OrdinalIgnoreCase)
|| name.Equals("metamanager", StringComparison.OrdinalIgnoreCase);
internal static string KindWord(ProfileKind k) => k switch
{
ProfileKind.Nav => "nav",
ProfileKind.Loot => "loot profile",
ProfileKind.Meta => "meta",
ProfileKind.Settings => "settings profile",
_ => "buff profile",
};
internal static IReadOnlyList<string> ExtensionsOf(ProfileKind k) => k switch
{
ProfileKind.Nav => NavExtensions,
ProfileKind.Loot => LootExtensions,
ProfileKind.Meta => MetaExtensions,
_ => SettingsExtensions,
};
/// <summary>The folder the kind's picker lists (settings: this character's folder; empty before login).</summary>
internal string ProfileFolder(ProfileKind k) => k switch
{
ProfileKind.Nav => _navFolder,
ProfileKind.Loot => _lootFolder,
ProfileKind.Meta => _metaFolder,
ProfileKind.Settings => _charFolder ?? string.Empty,
_ => BuffProfileStore.Folder,
};
/// <summary>A route from a file (not a meta's embedded nav, not /ra navheading's, not none).</summary>
private static bool IsNavFile(string? path) => !string.IsNullOrEmpty(path) && path[0] != '<';
/// <summary>The file the kind uses now; empty when there is none.</summary>
internal string ProfilePath(ProfileKind k) => k switch
{
ProfileKind.Nav => IsNavFile(_settings.CurrentNavPath) ? _settings.CurrentNavPath : string.Empty,
ProfileKind.Loot => _settings.CurrentLootPath ?? string.Empty,
ProfileKind.Meta => _settings.CurrentMetaPath ?? string.Empty,
ProfileKind.Settings => _settingsFilePath ?? string.Empty,
_ => _settings.CurrentBuffProfilePath ?? string.Empty,
};
/// <summary>
/// The row's header: the name in use and whether it has unsaved changes. Any thread (plain
/// field reads, as ReadDashboardFiles). Settings profiles, navs with a file and metas with a file
/// save every change on their own, so they are unsaved only when there is no file to save to
/// (or the meta's last save failed). The Loot Editor's and the Spells window's edits are added by
/// the plugin.
/// </summary>
internal ProfileFileInfo ProfileInfo(ProfileKind k)
{
string path = ProfilePath(k);
bool hasFile = path.Length > 0; // no disk look: the menu reads this every frame (a missing file is said by the button)
string name = path.Length > 0 ? Path.GetFileNameWithoutExtension(path) : "None";
bool unsaved = false;
switch (k)
{
case ProfileKind.Settings:
name = _settings.SelectedProfile ?? DefaultProfileName;
break;
case ProfileKind.Nav:
{
string nav = _settings.CurrentNavPath ?? string.Empty;
int points = _settings.CurrentRoute?.Points.Count ?? 0;
if (nav.StartsWith("<embedded:", StringComparison.Ordinal) && nav.EndsWith('>'))
name = nav[10..^1] + " (in the meta)";
else if (nav.Length > 0 && nav[0] == '<')
name = nav.Trim('<', '>') + " route";
else if (nav.Length == 0 && points > 0)
name = "Unsaved route";
unsaved = nav.Length == 0 && points > 0;
break;
}
case ProfileKind.Meta:
if (path.Length == 0 && _settings.MetaRules.Count > 0) name = "Unsaved meta";
unsaved = _settings.MetaUnsaved || (path.Length == 0 && _settings.MetaRules.Count > 0);
break;
case ProfileKind.Buffs:
if (path.Length == 0) name = BuiltInBuffProfileLabel;
break;
}
return new ProfileFileInfo(name, path, hasFile, unsaved, ProfileFolder(k));
}
// ── Save ─────────────────────────────────────────────────────────────
/// <summary>The Save button and /ra &lt;kind&gt; save: writes the profile in use to its file now.</summary>
internal ProfileResult SaveProfileNow(ProfileKind k)
{
switch (k)
{
case ProfileKind.Settings:
{
if (string.IsNullOrEmpty(_settingsFilePath)) return ProfileResult.Failed("Not logged in: no settings profile to save.");
string name = _settings.SelectedProfile ?? DefaultProfileName;
return SaveSettingsNow(out string reason, callerShows: true)
? ProfileResult.Done($"Saved settings profile '{name}' ({Path.GetFileName(_settingsFilePath)}). It also saves every change on its own.")
: ProfileResult.Failed($"Couldn't save settings profile '{name}': {reason}");
}
case ProfileKind.Nav:
{
string msg = SaveRoute(null);
return new ProfileResult(!RynthAiPlugin.ResultFailed(msg), msg);
}
case ProfileKind.Meta:
{
if (string.IsNullOrEmpty(_settings.CurrentMetaPath))
return ProfileResult.Failed("This meta has no file yet: type a name and use Save As (or /ra meta saveas <name>).");
bool ok = _metaSaver.SaveCurrent("Save button");
if (ok) { RefreshMetaFiles(); SaveSettings(); } // a .met is saved as the .af beside it
return ok ? ProfileResult.Done(_metaSaver.LastText + ".") : ProfileResult.Failed("Meta " + _metaSaver.LastText);
}
case ProfileKind.Loot:
return ProfileResult.Failed("Loot profiles are saved in the Loot Editor (its Save button).");
default:
return ProfileResult.Failed("Buff profiles are saved in the Spells window (its Save button).");
}
}
// ── Save As ──────────────────────────────────────────────────────────
/// <summary>
/// The Save As button and /ra &lt;kind&gt; saveas &lt;name&gt;: the profile in use saved under a
/// new name, which is then the one in use (a loot profile: a copy of its file). Onto another
/// file only with <paramref name="replace"/> (the button's confirm); that file's old copy is
/// kept in Deleted first. Without it the result asks (<see cref="ProfileResult.NeedsReplace"/>).
/// </summary>
internal ProfileResult SaveProfileAs(ProfileKind k, string? raw, bool replace)
{
if (k == ProfileKind.Buffs) return ProfileResult.Failed("Buff profiles: change the name in the Spells window and Save to make a copy.");
string? why = ProfileFileOps.CleanName(raw, ExtensionsOf(k), out string name);
if (why != null) return ProfileResult.Failed($"Can't use '{name}' as a {KindWord(k)} name: {why}.");
if (k == ProfileKind.Settings && IsReservedSettingsName(name))
return ProfileResult.Failed($"Can't use '{name}' as a settings profile name: RynthAi keeps its own {name}.json there.");
string current = ProfilePath(k), target, folder = ProfileFolder(k);
switch (k)
{
case ProfileKind.Settings:
if (string.IsNullOrEmpty(_charFolder)) return ProfileResult.Failed("Not logged in: settings profiles are per character.");
target = GetProfileFilePath(name);
break;
case ProfileKind.Nav:
target = Path.Combine(folder, name + ".nav");
break;
case ProfileKind.Meta:
target = Path.Combine(folder, name + ".af"); // new metas are .af (a .met is never written)
break;
default: // Loot: a copy of the file in use
if (current.Length == 0 || !File.Exists(current))
return ProfileResult.Failed("No loot profile in use to copy. New makes a blank one in the Loot Editor.");
string ext = Path.GetExtension(current);
target = Path.Combine(folder, name + (ext.Length > 0 ? ext : ".utl"));
if (ProfileFileOps.SamePath(target, current))
return ProfileResult.Failed($"{Path.GetFileName(target)} is the loot profile in use already; pick another name.");
break;
}
if (ProfileFileOps.WouldReplace(target, current))
{
if (!replace)
return new ProfileResult(false,
$"[RynthAi] {Path.GetFileName(target)} already exists. Replace it? (its old copy is kept in {ProfileFileOps.DeletedFolderName})",
NeedsReplace: true);
if (!ProfileFileOps.CopyToDeleted(target, RynthClock.Now, out _, out string keepError))
return ProfileResult.Failed($"Not saved: couldn't keep a copy of {Path.GetFileName(target)} first ({keepError}).");
}
switch (k)
{
case ProfileKind.Settings:
{
string r = SaveAsProfile(name);
return r.StartsWith("Saved profile", StringComparison.Ordinal)
? ProfileResult.Done($"Saved these settings as profile '{name}'; it is the profile in use now.")
: ProfileResult.Failed(r);
}
case ProfileKind.Nav:
{
string msg = SaveRoute(name);
return new ProfileResult(!RynthAiPlugin.ResultFailed(msg), msg);
}
case ProfileKind.Meta:
return SaveMetaAs(target)
? ProfileResult.Done($"Saved the meta as {Path.GetFileName(target)}; every change now saves to it.")
: ProfileResult.Failed("Meta " + _metaSaver.LastText);
default:
{
string from = current;
if (!DataWriteGuard.TrySave("the loot profile", target, () => File.Copy(from, target, overwrite: true), out string copyWhy, callerShows: true))
return ProfileResult.Failed($"Couldn't copy {Path.GetFileName(from)} to {Path.GetFileName(target)}: {copyWhy}");
_settings.CurrentLootPath = target;
RefreshLootFiles();
SaveSettings();
return ProfileResult.Done($"Copied {Path.GetFileName(from)} to {Path.GetFileName(target)}; RynthAi loots with {Path.GetFileName(target)} now.");
}
}
}
/// <summary>The meta's Save As (the Meta panel's save_file and the drawer's button): written to <paramref name="path"/>, which is then its file.</summary>
private bool SaveMetaAs(string path)
{
if (!_metaSaver.SaveTo(path, "Save As", callerShows: true)) return false;
_settings.CurrentMetaPath = path;
RefreshMetaFiles(); // the picker lists (and selects) the new file
SaveSettings();
return true;
}
// ── New ──────────────────────────────────────────────────────────────
/// <summary>
/// The New button and /ra nav|meta new &lt;name&gt;: a blank nav (Circular, no points) or meta (one
/// state "Default", no rules), loaded. Never over an existing one (that is picked in the list).
/// Loot profiles: <see cref="NewLootProfilePath"/>, opened in the Loot Editor by the plugin.
/// </summary>
internal ProfileResult NewProfile(ProfileKind k, string? raw)
{
switch (k)
{
case ProfileKind.Nav:
{
string? why = ProfileFileOps.CleanName(raw, NavExtensions, out string name);
if (why != null) return ProfileResult.Failed($"Can't use '{name}' as a nav name: {why}.");
if (File.Exists(Path.Combine(_navFolder, name + ".nav")))
return ProfileResult.Failed($"Nav '{name}' already exists. Pick it in the NAV list to load it, or use another name.");
string msg = LoadNavByName(name);
return new ProfileResult(msg.Contains("Created new nav", StringComparison.Ordinal), msg);
}
case ProfileKind.Meta:
{
string msg = LoadMetaByName(raw ?? string.Empty, createOnly: true);
return new ProfileResult(msg.Contains("Created new meta", StringComparison.Ordinal), msg);
}
case ProfileKind.Settings:
return ProfileResult.Failed("Save As makes a new settings profile (a copy of these settings).");
case ProfileKind.Buffs:
return ProfileResult.Failed("New buff profiles are made in the Spells window (its New button).");
default:
return ProfileResult.Failed("New loot profiles are made in the Loot Editor.");
}
}
/// <summary>
/// LootProfiles\&lt;name&gt;.utl for a new loot profile: null when it can be made (nothing is
/// written: the Loot Editor's Save creates it), else why not.
/// </summary>
internal string? NewLootProfilePath(string? raw, out string path)
{
path = string.Empty;
string? why = ProfileFileOps.CleanName(raw, LootExtensions, out string name);
if (why != null) return $"Can't use '{name}' as a loot profile name: {why}.";
string utl = Path.Combine(_lootFolder, name + ".utl");
if (File.Exists(utl) || File.Exists(Path.Combine(_lootFolder, name + ".json")))
return $"Loot profile '{name}' already exists. Pick it in the LOOT list, or use another name.";
path = utl;
return null;
}
// ── Rename ───────────────────────────────────────────────────────────
/// <summary>The Rename button and /ra &lt;kind&gt; rename &lt;name&gt;: the file in use gets the new name and stays in use.</summary>
internal ProfileResult RenameProfile(ProfileKind k, string? raw)
{
if (k == ProfileKind.Buffs) return ProfileResult.Failed("Buff profiles are renamed in the Spells window.");
string current = ProfilePath(k);
if (current.Length == 0 || !File.Exists(current))
return ProfileResult.Failed($"No {KindWord(k)} file in use to rename.");
if (k == ProfileKind.Settings && string.Equals(_settings.SelectedProfile, DefaultProfileName, StringComparison.OrdinalIgnoreCase))
return ProfileResult.Failed("The Default settings profile keeps its name; Save As makes a copy under another name.");
string? why = ProfileFileOps.CleanName(raw, ExtensionsOf(k), out string name);
if (why != null) return ProfileResult.Failed($"Can't use '{name}' as a {KindWord(k)} name: {why}.");
if (k == ProfileKind.Settings && (IsReservedSettingsName(name) || name.Equals(DefaultProfileName, StringComparison.OrdinalIgnoreCase)))
return ProfileResult.Failed($"Can't rename a settings profile to '{name}': that name is taken by RynthAi.");
string target = Path.Combine(Path.GetDirectoryName(current) ?? ProfileFolder(k), name + Path.GetExtension(current));
string oldName = Path.GetFileName(current);
if (!ProfileFileOps.Rename(current, target, out string error))
return ProfileResult.Failed($"Couldn't rename {oldName} to {Path.GetFileName(target)}: {error}.");
switch (k)
{
case ProfileKind.Settings:
_settings.SelectedProfile = name;
_settingsFilePath = target;
WriteActiveProfile(name);
RefreshProfilesList();
break;
case ProfileKind.Nav:
_settings.CurrentNavPath = target;
RefreshNavFiles();
SaveSettings();
break;
case ProfileKind.Meta:
_settings.CurrentMetaPath = target;
RefreshMetaFiles();
SaveSettings();
break;
default:
_settings.CurrentLootPath = target;
RefreshLootFiles();
SaveSettings();
break;
}
string note = k is ProfileKind.Nav or ProfileKind.Loot or ProfileKind.Meta
? " Metas that load it by its old name need the new one." : string.Empty;
return ProfileResult.Done($"Renamed {oldName} to {Path.GetFileName(target)}; it is still the {KindWord(k)} in use.{note}");
}
// ── Move to Deleted ──────────────────────────────────────────────────
/// <summary>
/// The Delete button and /ra &lt;kind&gt; delete: the file in use is moved to the Deleted folder
/// beside it (never deleted) and is no longer used: the nav, meta and loot profile become None,
/// the settings switch to Default first.
/// </summary>
internal ProfileResult DeleteProfile(ProfileKind k)
{
if (k == ProfileKind.Buffs) return ProfileResult.Failed("Buff profiles are removed in the Spells window (its Delete button).");
string current = ProfilePath(k);
if (current.Length == 0 || !File.Exists(current))
return ProfileResult.Failed($"No {KindWord(k)} file in use to move to {ProfileFileOps.DeletedFolderName}.");
string file = Path.GetFileName(current);
string folderName = Path.GetFileName(Path.GetDirectoryName(current) ?? string.Empty);
string after;
if (k == ProfileKind.Settings)
{
if (string.Equals(_settings.SelectedProfile, DefaultProfileName, StringComparison.OrdinalIgnoreCase))
return ProfileResult.Failed("The Default settings profile can't be moved to Deleted; it is the one every character falls back to.");
SwitchProfile(DefaultProfileName); // saves this profile's last changes first
after = "the settings are the Default profile now";
}
else after = $"no {KindWord(k)} is in use now";
if (!ProfileFileOps.MoveToDeleted(current, RynthClock.Now, out string moved, out string error))
return ProfileResult.Failed($"Couldn't move {file} to {ProfileFileOps.DeletedFolderName}: {error}."
+ (k == ProfileKind.Settings ? " The settings are the Default profile now." : string.Empty));
switch (k)
{
case ProfileKind.Settings:
RefreshProfilesList();
break;
case ProfileKind.Nav:
RefreshNavFiles();
_selectedNavIdx = 0; // "None": the route is cleared, as picking None does
LoadSelectedNav();
break;
case ProfileKind.Meta:
_metaUi.LoadMacroFile(string.Empty); // as picking None
RefreshMetaFiles();
SaveSettings();
break;
default:
_settings.CurrentLootPath = string.Empty;
RefreshLootFiles();
_settings.LootProfileIdx = 0;
SaveSettings();
break;
}
return ProfileResult.Done($"Moved {file} to {folderName}\\{ProfileFileOps.DeletedFolderName}\\{Path.GetFileName(moved)}; {after}. Move it back out of {ProfileFileOps.DeletedFolderName} to restore it.");
}
// ── Open folder ──────────────────────────────────────────────────────
/// <summary>The Open folder button and /ra &lt;kind&gt; folder: Explorer on the kind's folder, the file in use selected.</summary>
internal ProfileResult OpenProfileFolder(ProfileKind k)
{
string folder = ProfileFolder(k);
if (string.IsNullOrEmpty(folder)) return ProfileResult.Failed("Not logged in: settings profiles are per character.");
string current = ProfilePath(k);
try
{
Directory.CreateDirectory(folder);
string args = current.Length > 0 && File.Exists(current) ? $"/select,\"{current}\"" : $"\"{folder}\"";
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("explorer.exe", args) { UseShellExecute = true });
return ProfileResult.Done($"Opened the {KindWord(k)} folder: {folder}");
}
catch (Exception ex)
{
return ProfileResult.Failed($"Couldn't open {folder}: {ex.Message}");
}
}
}

View file

@ -265,7 +265,7 @@ internal sealed partial class LegacyDashboardRenderer
_navigationUi = new LegacyNavigationUi(_settings, host);
_weaponsUi = new LegacyWeaponsUi(_settings, host);
_metaSaver = new MetaSaver(_settings, line => _host.Log(line));
_metaUi = new LegacyMetaUi(_settings, _navFiles) { Saver = _metaSaver };
_metaUi = new LegacyMetaUi(_settings, _navFiles) { Saver = _metaSaver, Log = line => _host.Log(line) };
_dungeonMapUi = new DungeonMapUi();
_rynthRadarUi = new RynthRadarUi(host, _settings);
_rynthRadarUi.SetMapData(_dungeonMapUi);
@ -586,6 +586,7 @@ internal sealed partial class LegacyDashboardRenderer
_settings.MetaRulesStructuralVersion++;
_host.Log($"[RynthAi] Meta ({when}): {path} differs from the copy kept with these settings ({mine} rules); running the file's {loaded.Rules.Count} rules.");
}
_metaUi.NoteCallStates(path, loaded.Rules); // CallState rules that call nothing: say so
}
catch (Exception ex)
{
@ -593,21 +594,27 @@ internal sealed partial class LegacyDashboardRenderer
}
}
public void SaveSettings()
public void SaveSettings() => SaveSettingsNow(out _);
/// <summary>
/// <see cref="SaveSettings"/>, saying whether it was written and why not (the Loaded files
/// drawer's Save, /ra settings save). <paramref name="callerShows"/>: the caller reports a failure.
/// </summary>
internal bool SaveSettingsNow(out string reason, bool callerShows = false)
{
if (string.IsNullOrEmpty(_settingsFilePath)) return;
reason = string.Empty;
if (string.IsNullOrEmpty(_settingsFilePath)) { reason = "not logged in"; return false; }
string json;
try
{
CaptureTransientUiState();
json = JsonSerializer.Serialize(_settings, RynthAiJsonContext.Default.LegacyUiSettings);
}
catch { return; }
if (WriteSettingsFile(_settingsFilePath, json))
{
_lastSavedJson = json;
WriteActiveProfile(_settings.SelectedProfile);
}
catch (Exception ex) { reason = ex.Message; return false; }
if (!WriteSettingsFile(_settingsFilePath, json, out reason, callerShows)) return false;
_lastSavedJson = json;
WriteActiveProfile(_settings.SelectedProfile);
return true;
}
/// <summary>
@ -1279,6 +1286,7 @@ internal sealed partial class LegacyDashboardRenderer
RearmAfterVitals = s.RearmAfterVitals,
StartMacroOnLogin = s.StartMacroOnLogin,
PatrolOnLogin = s.PatrolOnLogin,
HuntOnLogin = s.HuntOnLogin,
ResumeMetaOnReload = s.ResumeMetaOnReload,
YieldToVTank = s.YieldToVTank,
EnableRaycasting = s.EnableRaycasting,
@ -1336,6 +1344,9 @@ internal sealed partial class LegacyDashboardRenderer
PetMinMonsters = s.PetMinMonsters,
VariablePowerMin = s.VariablePowerMin,
VariablePowerMax = s.VariablePowerMax,
DfHeightRotation = s.DfHeightRotation,
DfHeightOrder = s.DfHeightOrder,
DfDefaultHeight = s.DfDefaultHeight,
MissileEnvironmentResponse = s.MissileEnvironmentResponse,
MagicEnvironmentResponse = s.MagicEnvironmentResponse,
EnvironmentImpactLimit = s.EnvironmentImpactLimit,
@ -1432,6 +1443,8 @@ internal sealed partial class LegacyDashboardRenderer
CastBuffsOverItemBuffs = s.CastBuffsOverItemBuffs,
SkipUnusableBuffs = s.SkipUnusableBuffs,
DisabledBuffs = new List<string>(s.DisabledBuffs),
BlockedBuffItems = new List<string>(s.BlockedBuffItems),
CustomBuffItems = s.CustomBuffItems.ConvertAll(c => c.Copy()),
BuffMinSkillLevelTier1 = s.BuffMinSkillLevelTier1,
BuffMinSkillLevelTier2 = s.BuffMinSkillLevelTier2,
BuffMinSkillLevelTier3 = s.BuffMinSkillLevelTier3,
@ -1463,6 +1476,8 @@ internal sealed partial class LegacyDashboardRenderer
EnableAutostack = s.EnableAutostack,
ReadUnknownScrolls = s.ReadUnknownScrolls,
UnboxAetheriaWhenIdle = s.UnboxAetheriaWhenIdle,
AutoConfirmCraft = s.AutoConfirmCraft,
AutoConfirmCraftPercent = s.AutoConfirmCraftPercent,
EnableCombineSalvage = s.EnableCombineSalvage,
CombineBagsDuringSalvage = s.CombineBagsDuringSalvage,
SalvageWithoutPanel = s.SalvageWithoutPanel,
@ -1555,7 +1570,10 @@ internal sealed partial class LegacyDashboardRenderer
s.PeaceModeWhenIdle = p.PeaceModeWhenIdle;
if (p.RearmAfterVitals is bool rav) s.RearmAfterVitals = rav;
s.StartMacroOnLogin = p.StartMacroOnLogin;
s.PatrolOnLogin = p.PatrolOnLogin;
// Patrol On Login and Hunt On Login are one choice: the one just turned on clears the other
// (an engine without Hunt On Login sends no HuntOnLogin: unchanged, unless Patrol was turned on).
(s.PatrolOnLogin, s.HuntOnLogin) = LoginAutoStart.Exclusive(s.PatrolOnLogin, s.HuntOnLogin,
p.PatrolOnLogin, p.HuntOnLogin ?? s.HuntOnLogin);
if (p.ResumeMetaOnReload is bool resumeMeta) s.ResumeMetaOnReload = resumeMeta; // absent = unchanged
s.YieldToVTank = p.YieldToVTank;
s.EnableRaycasting = p.EnableRaycasting;
@ -1617,6 +1635,9 @@ internal sealed partial class LegacyDashboardRenderer
// Absent (an engine without these controls) = unchanged.
if (p.VariablePowerMin is int vpMin) s.VariablePowerMin = vpMin;
if (p.VariablePowerMax is int vpMax) s.VariablePowerMax = vpMax;
if (p.DfHeightRotation is bool dfRot) s.DfHeightRotation = dfRot;
if (p.DfHeightOrder is string dfOrder) s.DfHeightOrder = DirtyFightingHeights.NormalizeOrder(dfOrder);
if (p.DfDefaultHeight is int dfDef) s.DfDefaultHeight = Math.Clamp(dfDef, -1, 2);
if (p.MissileEnvironmentResponse is int envMis) s.MissileEnvironmentResponse = envMis;
if (p.MagicEnvironmentResponse is int envMag) s.MagicEnvironmentResponse = envMag;
if (p.EnvironmentImpactLimit is int envLimit) s.EnvironmentImpactLimit = envLimit;
@ -1717,6 +1738,8 @@ internal sealed partial class LegacyDashboardRenderer
if (p.CastBuffsOverItemBuffs is bool castOverItems) s.CastBuffsOverItemBuffs = castOverItems; // absent = unchanged
if (p.SkipUnusableBuffs is bool skipUnusable) s.SkipUnusableBuffs = skipUnusable; // absent = unchanged
if (p.DisabledBuffs is { } disabledBuffs) s.DisabledBuffs = new List<string>(disabledBuffs); // absent = unchanged
if (p.BlockedBuffItems is { } blockedItems) s.BlockedBuffItems = new List<string>(blockedItems); // absent = unchanged
if (p.CustomBuffItems is { } customItems) s.CustomBuffItems = customItems.FindAll(c => c != null); // absent = unchanged
s.BuffMinSkillLevelTier1 = p.BuffMinSkillLevelTier1;
s.BuffMinSkillLevelTier2 = p.BuffMinSkillLevelTier2;
s.BuffMinSkillLevelTier3 = p.BuffMinSkillLevelTier3;
@ -1745,6 +1768,9 @@ internal sealed partial class LegacyDashboardRenderer
s.EnableAutostack = p.EnableAutostack;
s.ReadUnknownScrolls = p.ReadUnknownScrolls;
if (p.UnboxAetheriaWhenIdle is bool unboxAetheria) s.UnboxAetheriaWhenIdle = unboxAetheria; // absent = unchanged
if (p.AutoConfirmCraft is bool autoConfirm) s.AutoConfirmCraft = autoConfirm; // absent = unchanged
if (p.AutoConfirmCraftPercent is int autoConfirmPct) // absent = unchanged
s.AutoConfirmCraftPercent = MiniRemote.Crafting.CraftAutoConfirm.ClampPercent(autoConfirmPct);
s.EnableCombineSalvage = p.EnableCombineSalvage;
s.CombineBagsDuringSalvage = p.CombineBagsDuringSalvage;
if (p.SalvageWithoutPanel is bool salvNoPanel) s.SalvageWithoutPanel = salvNoPanel; // absent = unchanged
@ -2105,6 +2131,8 @@ internal sealed partial class LegacyDashboardRenderer
dst.EnableAutocram = tmp.EnableAutocram;
dst.ReadUnknownScrolls = tmp.ReadUnknownScrolls;
dst.UnboxAetheriaWhenIdle = tmp.UnboxAetheriaWhenIdle;
dst.AutoConfirmCraft = tmp.AutoConfirmCraft;
dst.AutoConfirmCraftPercent = tmp.AutoConfirmCraftPercent;
dst.EnableCombineSalvage = tmp.EnableCombineSalvage;
dst.CombineBagsDuringSalvage = tmp.CombineBagsDuringSalvage;
dst.SalvageWithoutPanel = tmp.SalvageWithoutPanel;
@ -2227,6 +2255,8 @@ internal sealed partial class LegacyDashboardRenderer
dst.FastBuffChain = tmp.FastBuffChain;
dst.SkipUnusableBuffs = tmp.SkipUnusableBuffs;
dst.DisabledBuffs = tmp.DisabledBuffs;
dst.BlockedBuffItems = tmp.BlockedBuffItems;
dst.CustomBuffItems = tmp.CustomBuffItems.FindAll(c => c != null && !string.IsNullOrWhiteSpace(c.Name));
dst.BuffShield = tmp.BuffShield;
dst.BlacklistAttempts = tmp.BlacklistAttempts;
dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec;
@ -2257,6 +2287,9 @@ internal sealed partial class LegacyDashboardRenderer
dst.PreferDualWield = tmp.PreferDualWield;
dst.MeleeAttackHeight = tmp.MeleeAttackHeight;
dst.MissileAttackHeight = tmp.MissileAttackHeight;
dst.DfHeightRotation = tmp.DfHeightRotation;
dst.DfHeightOrder = DirtyFightingHeights.NormalizeOrder(tmp.DfHeightOrder);
dst.DfDefaultHeight = Math.Clamp(tmp.DfDefaultHeight, -1, 2);
dst.UseArcs = tmp.UseArcs;
dst.BowArcVelocity = tmp.BowArcVelocity;
dst.CrossbowArcVelocity = tmp.CrossbowArcVelocity;
@ -2339,6 +2372,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.AllowMetaKeystrokes = tmp.AllowMetaKeystrokes;
dst.StartMacroOnLogin = tmp.StartMacroOnLogin;
dst.PatrolOnLogin = tmp.PatrolOnLogin;
dst.HuntOnLogin = tmp.HuntOnLogin;
dst.ResumeMetaOnReload = tmp.ResumeMetaOnReload;
dst.YieldToVTank = tmp.YieldToVTank;
dst.FeatureServerNames = tmp.FeatureServerNames;
@ -2827,6 +2861,25 @@ internal sealed partial class LegacyDashboardRenderer
+ (warnings.Count > 0 ? $" — {warnings.Count} warning(s): {warnings[0]}" : "");
}
/// <summary>
/// /ra meta repair (and the Macro Rules window's Repair from .met): fills the loaded .af's CallState
/// rules that lost their target from the .met of the same name (CallStateRepair). Returns the chat line.
/// </summary>
public string RepairMetaFromMet()
{
bool ok = _metaUi.RepairFromMet(out string reply);
if (ok)
{
_metaUi.RefreshFileListIfShown();
RefreshMetaFiles(); // MetaProfileIdx follows the loaded file
SaveSettings();
}
return reply;
}
/// <summary>Posts the meta load warnings waiting for chat (plugin tick, in game).</summary>
public void DrainMetaNotices(Func<string, bool> write) => _metaUi.DrainNotices(write);
/// <summary>/ra meta list: the metas in MetaFiles (file names, with extension).</summary>
public List<string> MetaFileNames()
{
@ -3751,19 +3804,8 @@ internal sealed partial class LegacyDashboardRenderer
_metaSaver.Refuse("Not saved: no file name was given.", "save_file");
break;
}
{
string savePath = cmd.Path;
if (_metaSaver.SaveTo(savePath, "Save As", callerShows: true))
{
_settings.CurrentMetaPath = savePath;
RefreshMetaFiles(); // the picker lists (and selects) the new file
SaveSettings();
}
else
{
ReportMetaApply(false, "Meta " + _metaSaver.LastText);
}
}
if (!SaveMetaAs(cmd.Path))
ReportMetaApply(false, "Meta " + _metaSaver.LastText);
break;
case "set_source":

View file

@ -20,6 +20,7 @@ internal sealed class LegacyItemInfoUi
private Func<string?>? _describeSelected; // selected item's line (no prefix) or null when nothing is selected
private Action? _printSelected; // same path as /ra iteminfo (requests an ID when needed)
private Action<int>? _testChatType; // prints a sample line with the given chat type
private Action? _testPartColors; // prints a sample one-line with every part in its colour
// Preview is rebuilt on a timer or when an output option changes, not every frame.
private const long PreviewRefreshMs = 500;
@ -31,11 +32,12 @@ internal sealed class LegacyItemInfoUi
public LegacyItemInfoUi(LegacyUiSettings settings) => _settings = settings;
public void SetHooks(Func<string?> describeSelected, Action printSelected, Action<int> testChatType)
public void SetHooks(Func<string?> describeSelected, Action printSelected, Action<int> testChatType, Action? testPartColors = null)
{
_describeSelected = describeSelected;
_printSelected = printSelected;
_testChatType = testChatType;
_testPartColors = testPartColors;
}
public void Render()
@ -312,6 +314,7 @@ internal sealed class LegacyItemInfoUi
ImGui.SetTooltip("Chat type of a described \"Looted\" line\n(\"Same as name line\": the chat type above).");
RenderTextColor(s);
RenderPartColors(s);
ImGui.SetNextItemWidth(220);
ImGui.InputText("Line prefix##iiPrefix", ref s.Prefix, 32);
@ -319,6 +322,52 @@ internal sealed class LegacyItemInfoUi
ImGui.SetTooltip("Text put in front of every item info line (may be empty).");
}
private const string PartColorsTip =
"One-line layout: the name, set, armour / damage, spells, ratings, requirements,\n" +
"workmanship, value / burden ... each in its own colour in RynthCore's chat\n" +
"(the colours are listed below). The rest of the line (the prefix, the commas)\n" +
"keeps the Info text colour, else the chat type's. A RynthCore from before this\n" +
"shows the line in that one colour. AC's own chat window shows the chat type's colour.\n" +
"Also: /ra iteminfo parts on|off.";
/// <summary>
/// "Colour each part": the one-line layout's parts in their own colours (ItemInfoPartColors),
/// a Test line that shows every part, and the colours as a legend while it is on.
/// </summary>
private void RenderPartColors(MagItemInfoSettings s)
{
bool oneLine = s.Layout == MagItemInfoSettings.LayoutOneLine;
ImGui.BeginDisabled(!oneLine);
ImGui.Checkbox("Colour each part (one-line layout)##iiPartColors", ref s.PartColors);
ImGui.EndDisabled();
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
ImGui.SetTooltip(oneLine ? PartColorsTip : PartColorsTip + "\nSwitch the layout to the one-line Mag style to use it.");
ImGui.SameLine();
ImGui.BeginDisabled(!oneLine || !s.PartColors);
if (ImGui.Button("Test##iiPartColorsTest")) _testPartColors?.Invoke();
ImGui.EndDisabled();
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
ImGui.SetTooltip("Print a sample line with every part in its colour.");
if (!oneLine || !s.PartColors) return;
// The legend: each part's name in its colour, wrapped to the window.
ImGui.Indent();
float right = ImGui.GetCursorPosX() + ImGui.GetContentRegionAvail().X;
bool firstItem = true;
foreach (var (_, label, color) in ItemInfoPartColors.Defaults)
{
float w = ImGui.CalcTextSize(label).X;
if (!firstItem)
{
ImGui.SameLine(0, 12);
if (ImGui.GetCursorPosX() + w > right) ImGui.NewLine();
}
firstItem = false;
SafeImGui.TextColored(new Vector4(MagItemInfoCatalog.TextColorRgb(color), 1f), label);
}
ImGui.Unindent();
}
private const string TextColorTip =
"The colour of every item info line in RynthCore's chat: the name line, the\n" +
"detail lines, a described \"Looted\" line and your own ratings. The lines keep\n" +

View file

@ -69,6 +69,20 @@ internal sealed class LegacyMetaUi
/// <summary>Writes the meta file and keeps the result (the dashboard passes its own, which logs).</summary>
internal MetaSaver Saver { get; set; }
/// <summary>The plugin log (the dashboard sets it). Null: nothing is logged.</summary>
internal Action<string>? Log { get; set; }
// ── CallState rules without a target (CallStateRepair) ───────────────
// Chat lines wait here and go out on the plugin tick (DrainNotices), after the reply of the
// command that loaded the meta: two lines in a row off the main thread lose the second.
private readonly System.Collections.Concurrent.ConcurrentQueue<string> _pendingChat = new();
private int _pendingTries;
private const int MaxPendingChat = 8, MaxChatTries = 90;
// The .met found for the loaded .af (looked up on load, not every frame).
private string _callCheckPath = string.Empty;
private string? _callCheckMet;
private string? _repairFailText; // the status line of a refused repair (shown in red)
public void Render()
{
if (!DashWindows.ShowMacroRules) return;
@ -1048,6 +1062,11 @@ internal sealed class LegacyMetaUi
if (_macroFiles.Count == 0)
RefreshMacroFileList();
// CallState rules that call nothing (an .af saved by an older RynthAi): a Repair button
// when the .met it came from is there, and a line saying so either way.
int emptyCalls = EmptyCallStatesNow(out string? repairMet);
bool showRepair = emptyCalls > 0 && repairMet != null;
// Combo label: show selected file, or the currently loaded file if selection is stale
string comboLabel = (_selectedFileIdx >= 0 && _selectedFileIdx < _macroFiles.Count)
? _macroFiles[_selectedFileIdx].Display
@ -1055,7 +1074,7 @@ internal sealed class LegacyMetaUi
? Path.GetFileName(_settings.CurrentMetaPath)
: "-- None --");
ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X - 210);
ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X - (showRepair ? 345 : 210));
if (ImGui.BeginCombo("##MacroFileCombo", comboLabel))
{
for (int i = 0; i < _macroFiles.Count; i++)
@ -1081,9 +1100,31 @@ internal sealed class LegacyMetaUi
if (ImGui.Button("Save", new Vector2(55, 0)))
_openSavePopup = true;
if (showRepair)
{
ImGui.SameLine();
ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.55f, 0.35f, 0.05f, 1f));
if (ImGui.Button("Repair from .met", new Vector2(127, 0)))
{
bool repaired = RepairFromMet(out string reply);
_statusMessage = reply;
_repairFailText = repaired ? null : reply;
_statusTime = RynthClock.Now;
}
ImGui.PopStyleColor();
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip($"Fills the {emptyCalls} CallState target(s) from {Path.GetFileName(repairMet)}, in order, state by state.\n" +
"A backup copy of the .af is kept next to it first. Refused if the two files don't match.");
}
if (emptyCalls > 0)
SafeImGui.TextColored(new Vector4(1f, 0.55f, 0.2f, 1f), repairMet != null
? $"{emptyCalls} CallState rule(s) call no state (saved by an older RynthAi). Repair from .met fills them."
: $"{emptyCalls} CallState rule(s) call no state (saved by an older RynthAi). No .met of the same name to repair from.");
// Status message
// A save that failed (or an edit that wasn't written) stays up, in red, until the next result.
bool unsaved = !Saver.LastOk && Saver.Seq > 0 && ReferenceEquals(_statusMessage, Saver.LastText);
bool unsaved = (!Saver.LastOk && Saver.Seq > 0 && ReferenceEquals(_statusMessage, Saver.LastText))
|| (_repairFailText != null && ReferenceEquals(_statusMessage, _repairFailText)); // a refused repair stays up too
if (unsaved)
SafeImGui.TextColored(new Vector4(1, 0.35f, 0.35f, 1), _statusMessage);
else if (!string.IsNullOrEmpty(_statusMessage) && (RynthClock.Now - _statusTime).TotalSeconds < 5)
@ -1220,6 +1261,7 @@ internal sealed class LegacyMetaUi
? $"Loaded {loaded.Rules.Count} rules / {stateCount} states / {loaded.EmbeddedNavs.Count} navs from {name}"
: $"Loaded {loaded.Rules.Count} rules / {stateCount} states from {name} — {loaded.Warnings.Count} warning(s): {loaded.Warnings[0]}";
_statusTime = RynthClock.Now;
NoteCallStates(filePath, loaded.Rules);
return true;
}
catch (Exception ex)
@ -1242,6 +1284,154 @@ internal sealed class LegacyMetaUi
if (_macroFiles.Count > 0) RefreshMacroFileList();
}
// ── CallState rules without a target ─────────────────────────────────
/// <summary>
/// A meta just loaded (or read again at login): when it is an .af with CallState rules that
/// call nothing, one chat line says so (queued, see <see cref="DrainNotices"/>) and the log names
/// each state. Remembers the .met to repair from, for the Repair button.
/// </summary>
internal void NoteCallStates(string path, IReadOnlyList<MetaRule> rules)
{
_callCheckPath = path ?? string.Empty;
_callCheckMet = null;
if (!Path.GetExtension(_callCheckPath).Equals(".af", StringComparison.OrdinalIgnoreCase)) return;
var empty = CallStateRepair.EmptyTargets(rules);
if (empty.Count == 0) return;
_callCheckMet = CallStateRepair.FindSourceMet(_callCheckPath);
int count = 0;
foreach (var (_, n) in empty) count += n;
string name = Path.GetFileName(_callCheckPath);
string line = CallStateRepair.WarningLine(name, count, _callCheckMet);
if (_pendingChat.Count < MaxPendingChat) _pendingChat.Enqueue(line);
WriteLog(line);
foreach (var (state, n) in empty)
WriteLog($"[RynthAi] {name}: state '{state}' has {n} CallState rule{(n == 1 ? "" : "s")} with no state to call.");
}
/// <summary>
/// Posts the queued chat lines (plugin tick). <paramref name="write"/> is Host.WriteToChat: a line
/// it refuses waits for the next tick (about 1.5 s at most, then it is only in the log).
/// </summary>
internal void DrainNotices(Func<string, bool> write)
{
while (_pendingChat.TryPeek(out string? line))
{
bool ok;
try { ok = write(line); } catch { ok = false; }
if (!ok && ++_pendingTries < MaxChatTries) return;
_pendingChat.TryDequeue(out _);
_pendingTries = 0;
}
}
/// <summary>Chat lines waiting to be posted (tests).</summary>
internal int PendingNotices => _pendingChat.Count;
/// <summary>
/// The loaded meta's CallState rules without a target, now (edits included), and the .met to
/// repair from (null: none). 0 for a .met or no meta.
/// </summary>
internal int EmptyCallStatesNow(out string? repairMet)
{
repairMet = null;
string path = _settings.CurrentMetaPath ?? string.Empty;
if (!Path.GetExtension(path).Equals(".af", StringComparison.OrdinalIgnoreCase)) return 0;
int n;
lock (_settings.MetaRulesLock) n = CallStateRepair.CountEmpty(_settings.MetaRules);
if (n == 0) return 0;
if (!path.Equals(_callCheckPath, StringComparison.OrdinalIgnoreCase))
{
// The meta's file changed without a load here (a .met saved as its .af, a login): look once.
_callCheckPath = path;
_callCheckMet = CallStateRepair.FindSourceMet(path);
}
repairMet = _callCheckMet;
return n;
}
/// <summary>
/// Repair from .met (the Macro Rules button, /ra meta repair): fills the loaded .af's empty
/// CallState targets and return states from the .met of the same name, in order, state by state;
/// keeps a backup copy ("&lt;name&gt;.af.bak-yyyyMMdd-HHmmss"), writes the .af and loads it again.
/// Refused, with nothing changed, when the two files don't match. <paramref name="reply"/> is the
/// chat line either way.
/// </summary>
internal bool RepairFromMet(out string reply)
{
(bool ok, string text) = RepairFromMetCore();
reply = text;
return ok;
}
private (bool Ok, string Reply) RepairFromMetCore()
{
string path = _settings.CurrentMetaPath ?? string.Empty;
string name = Path.GetFileName(path);
(bool, string) Refuse(string why)
{
WriteLog($"[RynthAi] Meta repair of {(path.Length > 0 ? path : "(no meta)")} refused: {why}");
return (false, $"[RynthAi] Can't repair {(name.Length > 0 ? name : "the meta")}: {why}");
}
if (path.Length == 0) return Refuse("no meta is loaded. Load the .af first.");
if (!Path.GetExtension(path).Equals(".af", StringComparison.OrdinalIgnoreCase))
return Refuse("only an .af can be repaired (a .met already has its CallState targets).");
if (!File.Exists(path)) return Refuse("the file isn't there any more.");
if (_settings.MetaUnsaved)
return Refuse("your last change to it isn't saved to the file yet. Save it first, then repair.");
string? met = CallStateRepair.FindSourceMet(path);
if (met == null)
return Refuse($"there is no {Path.GetFileNameWithoutExtension(path)}.met next to it. Load the original .met if you have it, or set each CallState's target in the editor.");
string metName = Path.GetFileName(met);
LoadedMeta af;
LoadedMeta source;
try
{
af = AfFileParser.Load(path);
source = MetFileParser.Load(met);
}
catch (Exception ex) { return Refuse($"reading the files failed ({ex.Message})."); }
if (af.Rules.Count == 0)
return Refuse($"it didn't read ({(af.Warnings.Count > 0 ? af.Warnings[0] : "no rules")}).");
if (CallStateRepair.CountEmpty(af.Rules) == 0)
{
string none = $"[RynthAi] No CallState rule in {name} is missing its target; nothing to repair.";
WriteLog(none);
return (false, none);
}
if (source.Rules.Count == 0)
return Refuse($"{metName} didn't read ({(source.Warnings.Count > 0 ? source.Warnings[0] : "no rules")}).");
CallStateRepair.Result r = CallStateRepair.Repair(af.Rules, source.Rules);
if (!r.Ok) return Refuse($"{r.Why}.");
string backup = CallStateRepair.BackupPath(path, RynthClock.Now);
try { File.Copy(path, backup, overwrite: false); }
catch (Exception ex) { return Refuse($"couldn't keep a backup copy ({ex.Message}); nothing was changed."); }
if (!DataWriteGuard.TrySave("the meta", path,
() => AfFileWriter.Save(path, af.Rules, af.EmbeddedNavs), out string why, callerShows: true))
return Refuse($"couldn't write it: {why} The backup {Path.GetFileName(backup)} is kept.");
WriteLog($"[RynthAi] Meta repaired: {path} from {met}: {r.Filled} CallState rule(s) in {r.States} state(s); backup {backup}");
foreach (string d in r.Details) WriteLog($"[RynthAi] {d}");
if (!LoadMacroFile(path))
return (false, $"[RynthAi] Couldn't load {name} again after repairing it ({LastLoadStatus}). The repaired file is written; the backup is {Path.GetFileName(backup)}.");
string done = $"[RynthAi] Repaired {name}: {r.Filled} CallState rule{(r.Filled == 1 ? "" : "s")} in {r.States} state{(r.States == 1 ? "" : "s")} filled from {metName}, and loaded it again (it starts over in {_settings.CurrentState}). Backup: {Path.GetFileName(backup)}.";
_statusMessage = done;
_statusTime = RynthClock.Now;
return (true, done);
}
private void WriteLog(string line)
{
try { Log?.Invoke(line); } catch { }
}
/// <summary>Writes the meta file after an edit here (MetaSaver: logged); the status line says
/// whether it was saved, or why not (used to say nothing either way).</summary>

View file

@ -0,0 +1,223 @@
// LegacySpellsUi.BuffItems.cs - the Spells window's right pane as two tabs: Buff Profile (the
// profile editor) and Buff Items: which items buffing may use for their buff (Use Buff Items).
//
// Render thread. The list is the settings' (BlockedBuffItems + CustomBuffItems, replaced, never
// edited in place, so the buff tick never sees a list change under it); the pump thread hands in
// each line's pack count and status every 2 s. Adding an item needs the game (the selection, the
// item's spell), so the two Add buttons send /ra buffitems to the plugin tick.
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed unsafe partial class LegacySpellsUi
{
private static readonly byte[] ProfileTabLabel = Utf8Z("Buff Profile##sptabprofile");
private static readonly byte[] BuffItemsTabLabel = Utf8Z("Buff Items##sptabitems");
private Action<string>? _buffItemsCommand; // queues "/ra buffitems <args>" for the plugin tick
private List<BuffItemRow>? _buffItemRows; // pump thread writes (Volatile)
private int _selectBuffItemsTab;
private string _newBuffItemName = "";
private sealed record BuffItemsStatus(string Text, bool Warning);
private BuffItemsStatus? _buffItemsStatus; // pump thread or render thread writes (Volatile)
private static byte[] Utf8Z(string s)
{
var b = new byte[System.Text.Encoding.UTF8.GetByteCount(s) + 1];
System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, b, 0);
return b;
}
/// <summary>The Add buttons' way to the plugin tick (arguments of /ra buffitems).</summary>
public void SetBuffItemsCommand(Action<string> command) => _buffItemsCommand = command;
/// <summary>Pump thread: each line's pack count and status.</summary>
public void SetBuffItemRows(List<BuffItemRow> rows) => Volatile.Write(ref _buffItemRows, rows);
/// <summary>Any thread: the line under the Add buttons (what the last add did).</summary>
public void SetBuffItemsStatus(string text, bool warning) => Volatile.Write(ref _buffItemsStatus, new BuffItemsStatus(text, warning));
/// <summary>Any thread: the next frame shows the Buff Items tab (/ra buffitems open).</summary>
public void ShowBuffItemsTab() => Interlocked.Exchange(ref _selectBuffItemsTab, 1);
/// <summary>BeginTabItem with flags and no close button (ImGui.NET pairs flags with p_open, which draws an X).</summary>
private static bool BeginTab(byte[] labelUtf8Z, ImGuiTabItemFlags flags)
{
fixed (byte* label = labelUtf8Z)
return ImGuiNative.igBeginTabItem(label, null, flags) != 0;
}
private void RenderRightTabs()
{
if (!ImGui.BeginTabBar("##spright")) return;
if (BeginTab(ProfileTabLabel, ImGuiTabItemFlags.None))
{
RenderProfileEditor();
ImGui.EndTabItem();
}
var select = Interlocked.Exchange(ref _selectBuffItemsTab, 0) == 1 ? ImGuiTabItemFlags.SetSelected : ImGuiTabItemFlags.None;
if (BeginTab(BuffItemsTabLabel, select))
{
RenderBuffItems();
ImGui.EndTabItem();
}
ImGui.EndTabBar();
}
private static BuffItemRow? RowFor(List<BuffItemRow>? rows, string name)
{
if (rows == null) return null;
foreach (var r in rows)
if (r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) return r;
return null;
}
private void RenderBuffItems()
{
ImGui.Checkbox("Use Buff Items##spusebuffitems", ref _settings.UseBuffItems);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("Use the ticked items below from your pack whenever their buff isn't on you.\n" +
"The same switch as Settings > Buffing > Use Buff Items.");
ImGui.PushTextWrapPos(0);
ImGui.TextDisabled("One item at a time, when its buff isn't on you. Untick an item to keep RynthAi from using it. " +
"Items used up on use (potions) are used only from your pack.");
ImGui.PopTextWrapPos();
var entries = BuffItemEntry.Build(_settings.BlockedBuffItems, _settings.CustomBuffItems);
var rows = Volatile.Read(ref _buffItemRows);
string? remove = null;
float listH = MathF.Max(90f, ImGui.GetContentRegionAvail().Y - ImGui.GetFrameHeightWithSpacing() * 4.6f);
const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.BordersInnerV
| ImGuiTableFlags.Resizable | ImGuiTableFlags.SizingFixedFit;
if (ImGui.BeginTable("##spbuffitems", 6, flags, new Vector2(0, listH)))
{
ImGui.TableSetupScrollFreeze(0, 1);
ImGui.TableSetupColumn("Allowed", ImGuiTableColumnFlags.WidthFixed, 52);
ImGui.TableSetupColumn("Item", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Pack", ImGuiTableColumnFlags.WidthFixed, 36);
ImGui.TableSetupColumn("Status", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Every (min)", ImGuiTableColumnFlags.WidthFixed, 78);
ImGui.TableSetupColumn("##remove", ImGuiTableColumnFlags.WidthFixed, 56);
ImGui.TableHeadersRow();
for (int i = 0; i < entries.Count; i++)
{
var e = entries[i];
var row = RowFor(rows, e.Name);
ImGui.TableNextRow();
ImGui.PushID("bi" + i);
ImGui.TableSetColumnIndex(0);
bool allowed = e.Allowed;
if (ImGui.Checkbox("##allowed", ref allowed))
{
_settings.SetBuffItemAllowed(e.Name, allowed, out _);
e.Allowed = allowed;
}
if (ImGui.IsItemHovered()) ImGui.SetTooltip(allowed ? "Allowed: RynthAi may use it." : "Blocked: RynthAi never uses it.");
ImGui.TableSetColumnIndex(1);
ImGui.BeginGroup();
if (e.Allowed) ImGui.TextUnformatted(e.Name);
else SafeImGui.TextDisabled(e.Name);
if (e.BuiltIn) { ImGui.SameLine(); ImGui.TextDisabled("(built in)"); }
ImGui.EndGroup();
if (ImGui.IsItemHovered()) BuffItemTooltip(e, row);
ImGui.TableSetColumnIndex(2);
if (row == null) ImGui.TextDisabled("?");
else if (row.InPack > 0) ImGui.TextUnformatted(row.InPack.ToString());
else ImGui.TextDisabled("0");
ImGui.TableSetColumnIndex(3);
string status = row?.Status ?? (e.Allowed ? "" : "blocked");
if (status.StartsWith("buff on", StringComparison.Ordinal)) SafeImGui.TextColored(GoodColor, status);
else if (status.StartsWith("its buff didn't show", StringComparison.Ordinal)) SafeImGui.TextColored(WarnColor, status);
else SafeImGui.TextDisabled(status);
ImGui.TableSetColumnIndex(4);
if (e.Custom != null && !(e.SpellsKnown && e.Spells.Length > 0))
{
int minutes = e.RepeatMinutes;
ImGui.SetNextItemWidth(-1);
if (ImGui.InputInt("##repeat", ref minutes, 0, 0))
e.Custom.RepeatMinutes = BuffItemRules.ClampRepeatMinutes(minutes);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip(e.SpellsKnown
? "This item casts no spell RynthAi can check, so it is used\nagain this many minutes after its last use."
: "Used only if the item turns out to cast no spell RynthAi can check:\nthen it is used again this many minutes after its last use.");
}
else ImGui.TextDisabled("-");
ImGui.TableSetColumnIndex(5);
if (e.Custom != null && ImGui.SmallButton("Remove")) remove = e.Name;
ImGui.PopID();
}
ImGui.EndTable();
}
if (remove != null)
{
string name = remove;
Confirm($"Remove {name} from the buff items?", () =>
{
_settings.RemoveCustomBuffItem(name, out string shown);
SetBuffItemsStatus($"Removed {shown}.", false);
});
}
ImGui.Separator();
ImGui.TextUnformatted("Add your own item");
if (ImGui.Button("Add selected item##spbiaddsel"))
{
_buffItemsCommand?.Invoke("addselected");
SetBuffItemsStatus("Adding the selected item...", false);
}
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("Select the item in your inventory, then click. RynthAi reads the spell it casts,\n" +
"so it knows when its buff is on. One with no spell it can read is used on a timer.");
ImGui.SetNextItemWidth(MathF.Max(120f, ImGui.GetContentRegionAvail().X - 70f));
bool enter = ImGui.InputTextWithHint("##spbiname", "Item name, exactly as in your pack", ref _newBuffItemName, BuffItemRules.MaxNameLength,
ImGuiInputTextFlags.EnterReturnsTrue);
ImGui.SameLine();
bool add = ImGui.Button("Add##spbiadd");
if ((enter || add) && _newBuffItemName.Trim().Length > 0)
{
_buffItemsCommand?.Invoke("add " + BuffItemRules.CleanName(_newBuffItemName));
SetBuffItemsStatus($"Adding {BuffItemRules.CleanName(_newBuffItemName)}...", false);
_newBuffItemName = "";
}
var st = Volatile.Read(ref _buffItemsStatus);
if (st != null && st.Text.Length > 0)
{
ImGui.PushTextWrapPos(0);
if (st.Warning) SafeImGui.TextColored(WarnColor, st.Text);
else SafeImGui.TextDisabled(st.Text);
ImGui.PopTextWrapPos();
}
}
private static void BuffItemTooltip(BuffItemEntry e, BuffItemRow? row)
{
ImGui.BeginTooltip();
ImGui.PushTextWrapPos(ImGui.GetFontSize() * 30f);
ImGui.TextUnformatted(e.Name + (e.BuiltIn ? " (built in)" : ""));
if (e.Spells.Length > 0)
ImGui.TextUnformatted("Its buff counts as on while this is on you: " + (row != null && row.Spells.Length > 0 ? row.Spells : string.Join(", ", e.Spells)));
else if (e.SpellsKnown)
ImGui.TextUnformatted($"It casts no spell RynthAi can check: used every {e.RepeatMinutes} min.");
else
ImGui.TextUnformatted("Its spell is read from the item when it is in your pack, before the first use.");
if (e.BuiltIn) ImGui.TextUnformatted("Built-in items can be blocked but not removed.");
ImGui.PopTextWrapPos();
ImGui.EndTooltip();
}
}

View file

@ -4,6 +4,7 @@
// sortable columns (click a header; Shift+click adds a second sort key).
// Right: the buff profile editor. A saved profile chosen here ("Use for buffing") or under
// Loaded Files → Buffs replaces buffing's built-in list.
// Right, second tab: Buff Items (LegacySpellsUi.BuffItems.cs), the items buffing may use.
//
// Render thread only. The plugin hands in pump-thread data: the known-spell copy, the built-in
// buff list, and applies the chosen profile path.
@ -17,7 +18,7 @@ using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed unsafe class LegacySpellsUi
internal sealed unsafe partial class LegacySpellsUi
{
private const string WindowTitle = "RynthAi Spells##RynthAiSpells";
private const string ConfirmPopupId = "Confirm##rynthaispells";
@ -168,7 +169,7 @@ internal sealed unsafe class LegacySpellsUi
ImGui.SameLine();
if (ImGui.BeginChild("##spprofile", Vector2.Zero, ImGuiChildFlags.Borders))
RenderProfileEditor();
RenderRightTabs();
ImGui.EndChild();
}
@ -445,6 +446,9 @@ internal sealed unsafe class LegacySpellsUi
// ── Profile editor ──────────────────────────────────────────────────────
/// <summary>The profile open here has edits not saved yet (the Loaded files drawer's BUFFS row shows a *).</summary>
internal bool Dirty => _dirty;
private void RenderProfileEditor()
{
string active = _settings.CurrentBuffProfilePath ?? "";
@ -483,9 +487,13 @@ internal sealed unsafe class LegacySpellsUi
ImGui.SameLine();
ImGui.BeginDisabled(_editPath == null);
if (ImGui.Button("Delete##spdel")) ConfirmDelete();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Moves the profile to BuffProfiles\\Deleted (nothing is deleted; move it back to restore it).");
ImGui.EndDisabled();
ImGui.SameLine();
if (ImGui.Button("Refresh##sprefresh")) RefreshFiles();
ImGui.SameLine();
if (ImGui.Button("Open folder##spfolder")) OpenFolder();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Opens RynthAi\\BuffProfiles in Explorer.");
string name = _edit.Name;
ImGui.SetNextItemWidth(-1);
@ -761,11 +769,11 @@ internal sealed unsafe class LegacySpellsUi
{
string? path = _editPath;
if (path == null) return;
Confirm($"Delete the profile '{Path.GetFileNameWithoutExtension(path)}'?", () =>
Confirm($"Move the profile '{Path.GetFileNameWithoutExtension(path)}' to BuffProfiles\\{ProfileFileOps.DeletedFolderName}?", () =>
{
if (!BuffProfileStore.Delete(path))
{
SetStatus("Delete failed (file missing or in use).", warning: true);
SetStatus("Not moved (file missing or in use).", warning: true);
return;
}
if ((_settings.CurrentBuffProfilePath ?? "").Equals(path, StringComparison.OrdinalIgnoreCase))
@ -773,10 +781,27 @@ internal sealed unsafe class LegacySpellsUi
RefreshFiles();
_refreshProfileList?.Invoke();
StartNewProfile();
SetStatus($"Deleted {Path.GetFileNameWithoutExtension(path)}.");
SetStatus($"Moved {Path.GetFileNameWithoutExtension(path)} to BuffProfiles\\{ProfileFileOps.DeletedFolderName}.");
});
}
/// <summary>Explorer on RynthAi\BuffProfiles, the open profile selected.</summary>
private void OpenFolder()
{
try
{
string folder = BuffProfileStore.Folder;
Directory.CreateDirectory(folder);
string args = _editPath != null && File.Exists(_editPath) ? $"/select,\"{_editPath}\"" : $"\"{folder}\"";
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("explorer.exe", args) { UseShellExecute = true });
SetStatus("Opened " + folder);
}
catch (Exception ex)
{
SetStatus("Couldn't open the folder: " + ex.Message, warning: true);
}
}
private void RefreshFiles() => _files = BuffProfileStore.ListFileNames();
private void RebuildEditKeys()

View file

@ -128,6 +128,12 @@ public sealed class LegacyUiSettings
// nothing to do, an Aetheria Mana Stone is used on each Coalesced Aetheria in the pack, one at a
// time, to reveal its sigil (Loot/AetheriaUnboxer.cs). The stone isn't used up on ACE.
public bool UnboxAetheriaWhenIdle = false;
// Auto-confirm crafting (a players' request, 2026-11-11; default off): when the server asks
// "You determine that you have a N percent chance to succeed." for a craft or tinker the player
// starts by hand, say Yes when N is at least AutoConfirmCraftPercent; anything lower shows AC's
// own dialog as usual, never a No (engine API v97; MiniRemote/Crafting/CraftAutoConfirm.cs).
public bool AutoConfirmCraft = false;
public int AutoConfirmCraftPercent = 100;
public bool EnableCombineSalvage = true;
public bool CombineBagsDuringSalvage = true;
// Salvage (and combine bags) by sending the 0x027D salvage request straight to the server, no
@ -203,6 +209,57 @@ public sealed class LegacyUiSettings
public bool UsePotions = true;
// Unlimited buff gems (Asheron's Benediction, Blackmoor's Favor) and field rations (2026-09-29).
public bool UseBuffItems = true;
/// <summary>
/// Built-in buff items the player blocked in the Buff Items list (Spells window > Buff Items,
/// /ra buffitems block): never used. Empty = all three allowed, which is also what a profile
/// saved before this setting loads as. Replaced, not edited in place (BuffItemRules.SetAllowed),
/// so the buff tick holding the old list never sees it change under it.
/// </summary>
public List<string> BlockedBuffItems
{
get => _blockedBuffItems;
set => _blockedBuffItems = value ?? new List<string>();
}
private List<string> _blockedBuffItems = new();
/// <summary>
/// Buff items the player added (a server's own gems or potions), each with its Allowed tick and
/// the spells that mean its buff is on (or a repeat time when it casts none we can check).
/// Replaced, not edited in place, like <see cref="BlockedBuffItems"/>.
/// </summary>
public List<CustomBuffItem> CustomBuffItems
{
get => _customBuffItems;
set => _customBuffItems = value ?? new List<CustomBuffItem>();
}
private List<CustomBuffItem> _customBuffItems = new();
/// <summary>Allows or blocks a built-in or custom buff item by name; see BuffItemRules.SetAllowed.</summary>
internal BuffItemRules.EditResult SetBuffItemAllowed(string name, bool allowed, out string shownName)
{
var r = BuffItemRules.SetAllowed(_blockedBuffItems, _customBuffItems, name, allowed, out var blocked, out var customs, out shownName);
if (r == BuffItemRules.EditResult.Changed)
{
_blockedBuffItems = blocked;
_customBuffItems = customs;
}
return r;
}
/// <summary>Adds (or, with spells read from the item, refreshes) a custom buff item; see BuffItemRules.Add.</summary>
internal BuffItemRules.EditResult AddCustomBuffItem(string name, IReadOnlyList<uint>? spells, out CustomBuffItem? item)
{
var r = BuffItemRules.Add(_customBuffItems, name, spells, out var customs, out item);
if (r is BuffItemRules.EditResult.Added or BuffItemRules.EditResult.Updated) _customBuffItems = customs;
return r;
}
/// <summary>Removes a custom buff item; see BuffItemRules.Remove.</summary>
internal BuffItemRules.EditResult RemoveCustomBuffItem(string name, out string shownName)
{
var r = BuffItemRules.Remove(_customBuffItems, name, out var customs, out shownName);
if (r == BuffItemRules.EditResult.Removed) _customBuffItems = customs;
return r;
}
public int MakeRationsBelow = 5; // 0 = don't cook field rations
public bool UseKitsInMagicMode = true;
public bool PeaceModeForKits = false;
@ -332,7 +389,7 @@ public sealed class LegacyUiSettings
/// <summary>
/// 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)
/// mirrors RynthILT's value into the engine's Settings > General row (ServerSettingGet / Set)
/// and answers this old value through RynthAi.Hub VaultedDungeonsEnabled for an older RynthILT.
/// </summary>
public bool EnableVaultedDungeons;
@ -485,6 +542,11 @@ public sealed class LegacyUiSettings
public bool StartMacroOnLogin;
public bool PatrolOnLogin;
/// <summary>
/// Hunt On Login (2026-11-11): starts the Outdoor Hunt once the character is in the world, as Patrol
/// On Login starts the Dungeon Patrol. One or the other: ticking one clears the other (LoginAutoStart).
/// </summary>
public bool HuntOnLogin;
/// <summary>
/// Resume Meta After Reload (2026-11-07, Tom: "remembers which meta state you're in and restarts in
/// that state so Drakkon doesn't recall back every time"). A hot reload carries the meta's whole
/// runtime over (Meta/MetaResume.cs): state, variables, fired rules, call stack, watchdog, route.
@ -671,6 +733,17 @@ public sealed class LegacyUiSettings
public int WeaponSwapMinGainPct = 20;
public int MeleeAttackHeight = 1;
public int MissileAttackHeight = 1;
/// <summary>
/// Dirty Fighting rotation (Combat/DirtyFightingHeights.cs): with Dirty Fighting trained,
/// melee and missile attacks aim at the height of the next effect missing from the target
/// (in DfHeightOrder), then at DfDefaultHeight once all three are on. Off by default; off
/// or untrained, the Melee/Missile Attack Height above is used as before.
/// </summary>
public bool DfHeightRotation;
/// <summary>The order the effects are put on: "HML" (High, Medium, Low) and the like.</summary>
public string DfHeightOrder = DirtyFightingHeights.DefaultOrder;
/// <summary>The height once all three are on: 0 Low, 1 Medium, 2 High, -1 the Attack Height setting.</summary>
public int DfDefaultHeight = DirtyFightingHeights.DefaultIsFixedHeight;
// Projectile arc velocities for missile-weapon LoS checks.
// Lower velocity = higher arc. Must approximate the AC client trajectory
@ -1238,6 +1311,8 @@ public sealed class SettingsBridgePayload
public bool? RearmAfterVitals { get; set; }
public bool StartMacroOnLogin { get; set; }
public bool PatrolOnLogin { get; set; }
// Hunt On Login. Nullable: an engine without the row doesn't send it (unchanged).
public bool? HuntOnLogin { get; set; }
// Resume Meta After Reload. Nullable: an engine without the row doesn't send it (unchanged).
public bool? ResumeMetaOnReload { get; set; }
// Dungeon patrol. Nullable: an engine that predates them doesn't send them, and its save
@ -1320,6 +1395,10 @@ public sealed class SettingsBridgePayload
// engine without these controls, which leaves the plugin's own values alone.
public int? VariablePowerMin { get; set; }
public int? VariablePowerMax { get; set; }
// Dirty Fighting rotation (2026-11-11). Null = a sender without these controls: unchanged.
public bool? DfHeightRotation { get; set; }
public string? DfHeightOrder { get; set; }
public int? DfDefaultHeight { get; set; }
public int? MissileEnvironmentResponse { get; set; }
public int? MagicEnvironmentResponse { get; set; }
public int? EnvironmentImpactLimit { get; set; }
@ -1431,6 +1510,10 @@ public sealed class SettingsBridgePayload
public bool? SkipUnusableBuffs { get; set; }
// Null (absent) likewise leaves the unticked prots/banes alone; an empty list ticks them all.
public List<string>? DisabledBuffs { get; set; }
// The Buff Items lists (RynthAi's Spells window draws them; the engine's face has no rows for
// them). Null (absent) leaves them alone, as DisabledBuffs.
public List<string>? BlockedBuffItems { get; set; }
public List<CustomBuffItem>? CustomBuffItems { get; set; }
public int BuffMinSkillLevelTier1 { get; set; }
public int BuffMinSkillLevelTier2 { get; set; }
public int BuffMinSkillLevelTier3 { get; set; }
@ -1467,6 +1550,8 @@ public sealed class SettingsBridgePayload
public bool EnableAutostack { get; set; }
public bool ReadUnknownScrolls { get; set; } = true; // absent from an older engine: keep the default
public bool? UnboxAetheriaWhenIdle { get; set; } // absent from an older engine: unchanged
public bool? AutoConfirmCraft { get; set; } // absent from an older engine: unchanged
public int? AutoConfirmCraftPercent { get; set; } // absent from an older engine: unchanged
public bool EnableCombineSalvage { get; set; }
public bool CombineBagsDuringSalvage { get; set; }
public bool? SalvageWithoutPanel { get; set; } // absent from an older engine: unchanged

View file

@ -0,0 +1,162 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// <summary>
/// The file side of the Loaded files drawer's profile buttons (Save As, Rename, Move to Deleted) and
/// their /ra verbs, for settings profiles, navs, metas and loot profiles (2026-11-11): the name
/// typed checked as a file name (<see cref="NewProfileFiles"/>' rules), whether it would replace
/// another file, and the Deleted folder. Nothing is ever deleted: a profile removed from its picker
/// is moved into a "Deleted" folder beside it, and a file replaced by Save As has its old copy
/// kept there first. The pickers list only their own folder, so nothing in Deleted shows in them;
/// moving a file back out of Deleted (and dropping the time from its name) brings it back.
/// Pure file work, so the offline tests cover it.
/// </summary>
internal static class ProfileFileOps
{
/// <summary>The folder, inside each profile folder, that removed and replaced profiles go to.</summary>
public const string DeletedFolderName = "Deleted";
/// <summary>
/// The name typed, tidied (whitespace, quotes and one of <paramref name="extensions"/> dropped)
/// into <paramref name="name"/>. Null when it is safe as a file name, else why not.
/// </summary>
public static string? CleanName(string? raw, IReadOnlyList<string> extensions, out string name)
{
name = NewProfileFiles.Tidy(raw, extensions, out _);
return NewProfileFiles.Validate(name);
}
/// <summary>The same file (full paths, case ignored)? False when either is empty or not a path.</summary>
public static bool SamePath(string? a, string? b)
{
if (string.IsNullOrWhiteSpace(a) || string.IsNullOrWhiteSpace(b)) return false;
try { return string.Equals(Path.GetFullPath(a.Trim()), Path.GetFullPath(b.Trim()), StringComparison.OrdinalIgnoreCase); }
catch { return false; }
}
/// <summary>
/// Saving to <paramref name="target"/> would replace another file: it exists and it isn't
/// <paramref name="current"/> (saving a profile onto its own file is a plain save).
/// </summary>
public static bool WouldReplace(string target, string? current) =>
File.Exists(target) && !SamePath(target, current);
/// <summary>&lt;folder of path&gt;\Deleted.</summary>
public static string DeletedFolderFor(string path) =>
Path.Combine(Path.GetDirectoryName(Path.GetFullPath(path)) ?? ".", DeletedFolderName);
/// <summary>
/// Where <paramref name="path"/> goes in the Deleted folder: its name with the time before the
/// extension ("farm.nav" -> Deleted\farm.2026-11-11_153012.nav), and " (2)", " (3)" ... when
/// that is taken, so an earlier copy is never replaced.
/// </summary>
public static string DeletedPathFor(string path, DateTime now)
{
string folder = DeletedFolderFor(path);
string ext = Path.GetExtension(path);
string stem = Path.GetFileNameWithoutExtension(path);
string stamp = now.ToString("yyyy-MM-dd_HHmmss", CultureInfo.InvariantCulture);
string candidate = Path.Combine(folder, $"{stem}.{stamp}{ext}");
for (int n = 2; File.Exists(candidate) || Directory.Exists(candidate); n++)
candidate = Path.Combine(folder, $"{stem}.{stamp} ({n}){ext}");
return candidate;
}
/// <summary>
/// Moves <paramref name="path"/> into its Deleted folder (made when missing). Never deletes:
/// on any failure the file stays where it was. <paramref name="moved"/> is where it went.
/// </summary>
public static bool MoveToDeleted(string path, DateTime now, out string moved, out string error)
{
moved = string.Empty;
error = string.Empty;
try
{
if (!File.Exists(path)) { error = $"{Path.GetFileName(path)} isn't there any more"; return false; }
string target = DeletedPathFor(path, now);
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
File.Move(path, target, overwrite: false);
moved = target;
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
/// <summary>
/// Keeps a copy of <paramref name="path"/> in its Deleted folder before it is replaced (Save As
/// over another profile). Nothing to keep (no such file) is a success with an empty
/// <paramref name="copy"/>.
/// </summary>
public static bool CopyToDeleted(string path, DateTime now, out string copy, out string error)
{
copy = string.Empty;
error = string.Empty;
try
{
if (!File.Exists(path)) return true;
string target = DeletedPathFor(path, now);
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
File.Copy(path, target, overwrite: false);
copy = target;
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
/// <summary>
/// Renames <paramref name="from"/> to <paramref name="to"/> (same folder). Refused when
/// <paramref name="to"/> is another file that exists (a change of case only is allowed).
/// </summary>
public static bool Rename(string from, string to, out string error)
{
error = string.Empty;
try
{
if (!File.Exists(from)) { error = $"{Path.GetFileName(from)} isn't there any more"; return false; }
if (string.Equals(Path.GetFullPath(from), Path.GetFullPath(to), StringComparison.Ordinal))
{
error = "that is already its name";
return false;
}
if (File.Exists(to) && !SamePath(from, to))
{
error = $"{Path.GetFileName(to)} already exists";
return false;
}
if (SamePath(from, to))
{
// Only the case changes: Windows sees one file, so go through a temporary name.
string tmp = from + "." + Environment.ProcessId + ".rename";
File.Move(from, tmp);
try { File.Move(tmp, to); }
catch
{
try { File.Move(tmp, from); } catch { }
throw;
}
}
else
{
File.Move(from, to, overwrite: false);
}
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
}

View file

@ -0,0 +1,40 @@
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Patrol On Login and Hunt On Login (2026-11-11): what starts once the character is in the world.
/// The two are one choice: ticking one clears the other (<see cref="Exclusive"/>). A profile that has
/// both on anyway (edited by hand, or from a sender that only knows one of them) gets the one that
/// fits where the character is: the Dungeon Patrol in a dungeon, the Outdoor Hunt outdoors
/// (<see cref="Choose"/>). Both turn the macro on themselves, so Start Macro On Login isn't needed.
/// Pure, for the tests.
/// </summary>
internal static class LoginAutoStart
{
internal enum Start { None, Patrol, Hunt }
internal const string HuntOnLoginTip =
"Starts the Outdoor Hunt from where you are once you're in the world (and the macro with it).\n" +
"In a dungeon, or without RynthNav: it doesn't start, and says why in chat.\n" +
"One or the other: ticking it clears Patrol On Login.";
/// <summary>What runs at login. <paramref name="inDungeon"/> only matters with both on.</summary>
internal static Start Choose(bool patrolOnLogin, bool huntOnLogin, bool inDungeon) =>
patrolOnLogin && huntOnLogin ? (inDungeon ? Start.Patrol : Start.Hunt)
: patrolOnLogin ? Start.Patrol
: huntOnLogin ? Start.Hunt
: Start.None;
/// <summary>
/// The two boxes after a change: the one just turned on wins and the other goes off. Both turned
/// on in one change (no way to tell which was meant): the patrol, as before Hunt On Login existed.
/// Turning one off leaves the other as it was.
/// </summary>
internal static (bool Patrol, bool Hunt) Exclusive(bool wasPatrol, bool wasHunt, bool patrol, bool hunt)
{
bool patrolTurnedOn = patrol && !wasPatrol;
bool huntTurnedOn = hunt && !wasHunt;
if (patrolTurnedOn) return (true, false);
if (huntTurnedOn) return (false, true);
return (patrol, hunt);
}
}

View file

@ -139,6 +139,30 @@ internal sealed class LootEditorBridge
if (saved != null) _onSaved(saved);
}
/// <summary>
/// The Loaded files drawer's New (2026-11-11): the editor on <paramref name="path"/>, the same
/// open as its own file picker (a .utl that isn't there yet opens empty, and its Save creates
/// it). False, with the editor's reason, when it has unsaved edits in another profile.
/// </summary>
public bool OpenFile(string path, out string message)
{
lock (_sync)
{
var cmd = new LootEditCommand { Op = "open", Path = path };
bool opened = _session.Apply(cmd) == LootEditSession.Outcome.Opened;
if (opened) _followInUse = LootEditSession.SamePath(path, InUse);
message = _session.Message;
return opened;
}
}
/// <summary>The editor has unsaved edits in <paramref name="path"/> (the drawer's * and its rename/move guard).</summary>
public bool IsDirtyFor(string path)
{
lock (_sync)
return _session.IsDirty && path.Length > 0 && LootEditSession.SamePath(path, _session.Path);
}
// =====================================================================
// Add to loot profile (a clicked item)
// =====================================================================

View file

@ -12,6 +12,9 @@ internal enum LootPickupResult
Used,
/// <summary>No pack of ours has a free slot.</summary>
NoRoom,
/// <summary>The main pack is full and the item joins no stack you carry. Side packs may have room, but the
/// client takes nothing from a corpse straight into one, so this item can't be looted now; others still can.</summary>
MainPackFull,
/// <summary>No move call, and a use could put the item on the character, so nothing was sent.</summary>
Refused,
/// <summary>The engine turned the call down.</summary>
@ -38,10 +41,14 @@ internal static class LootPickup
{
if (playerId == 0) return LootPickupResult.Failed;
int pid = unchecked((int)playerId);
int dest = cache == null
? pid
: WorldObjectCache.FindLootDestination(cache.GetDirectInventory(forceRefresh: false), pid, host, skip);
if (dest == 0) return LootPickupResult.NoRoom;
int dest = pid;
if (cache != null)
{
var inv = cache.GetDirectInventory(forceRefresh: false);
dest = WorldObjectCache.FindLootDestination(inv, pid, host, skip, cache[unchecked((int)itemId)]);
if (dest == 0)
return WorldObjectCache.SidePackHasRoom(inv, pid, host) ? LootPickupResult.MainPackFull : LootPickupResult.NoRoom;
}
destination = unchecked((uint)dest);
return host.MoveItemExternal(itemId, destination, 0) ? LootPickupResult.Moved : LootPickupResult.Failed;
}

View file

@ -502,7 +502,7 @@ public sealed partial class RynthAiPlugin
return true;
}
/// <summary>/mt client minimize|restore (ub-IT's frame apply|restore points to Settings > Display).</summary>
/// <summary>/mt client minimize|restore (ub-IT's frame apply|restore points to Settings > Game Client).</summary>
private bool HandleMtClient(string[] parts)
{
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : "";
@ -511,7 +511,7 @@ public sealed partial class RynthAiPlugin
case "minimize": if (KeystrokesAllowed("/mt client")) { GameInput.Minimize(); ReplyOk("[RynthAi] Game window minimized."); } return true;
case "restore": if (KeystrokesAllowed("/mt client")) { GameInput.Restore(); ReplyOk("[RynthAi] Game window restored."); } return true;
case "frame":
ChatLine("[RynthAi] The window frame is RynthCore's: Settings > Display, Borderless Windowed (there is no chat command for it).");
ChatLine("[RynthAi] The window frame is RynthCore's: Settings > Game Client, Borderless Windowed (there is no chat command for it).");
return true;
default:
ReplyFail("[RynthAi] Usage: /mt client minimize | restore");

View file

@ -0,0 +1,234 @@
using System;
using System.Collections.Generic;
using System.IO;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.Meta;
/// <summary>
/// CallState rules that lost their target (2026-11-11).
///
/// Before 34b7d45e (2026-09-30) the .met parser read a CallState's data (a TABLE {st, ret}) as a
/// string and left the target empty. The .af writer then saved such a rule as
/// "CallState {} {&lt;the rule's own state&gt;}" ("{Default}" for one inside a DoAll), so every .af
/// saved from a .met through RynthAi's meta editor before then has every CallState broken: the
/// rule fires, calls nothing (MetaManager skips an empty target), latches, and the meta stays in
/// that state for good. The return state written then is wrong as well (VTank's "ret" is often the
/// next state, not the caller).
///
/// This finds those rules (nested DoAll ones included) and, when the original .met is still
/// there, puts its CallState targets and return states back, matched by order: per state, the
/// .met's CallState actions depth-first and the .af's in the same walk. The .af writer keeps each
/// state's rules in file order, so the Nth CallState of a state is the same rule in both files.
/// A state whose counts differ is refused rather than guessed.
/// </summary>
internal static class CallStateRepair
{
/// <summary>A CallState rule with no state to call.</summary>
public static bool IsEmptyTarget(MetaRule rule)
=> rule.Action == MetaActionType.CallMetaState && string.IsNullOrWhiteSpace(rule.ActionData);
/// <summary>
/// The CallState actions of one rule, depth first: the rule itself, or the children of a DoAll
/// (the same lists MetaManager runs: ActionChildren, else Children).
/// </summary>
public static IEnumerable<MetaRule> CallStatesInOrder(MetaRule rule)
{
if (rule.Action == MetaActionType.CallMetaState)
{
yield return rule;
yield break;
}
if (rule.Action != MetaActionType.All) yield break;
List<MetaRule>? children = rule.ActionChildren is { Count: > 0 } ? rule.ActionChildren : rule.Children;
if (children == null) yield break;
foreach (MetaRule child in children)
foreach (MetaRule c in CallStatesInOrder(child))
yield return c;
}
/// <summary>Each state's CallState actions in order (states in first-seen order; names ignore case).</summary>
public static List<(string State, List<MetaRule> Calls)> CallStatesByState(IEnumerable<MetaRule> rules)
{
var order = new List<(string State, List<MetaRule> Calls)>();
var index = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (MetaRule rule in rules)
{
string state = rule.State ?? string.Empty;
if (!index.TryGetValue(state, out int i))
{
i = order.Count;
index[state] = i;
order.Add((state, new List<MetaRule>()));
}
order[i].Calls.AddRange(CallStatesInOrder(rule));
}
return order;
}
/// <summary>The states that have CallState rules without a target, and how many each (file order).</summary>
public static List<(string State, int Count)> EmptyTargets(IEnumerable<MetaRule> rules)
{
var result = new List<(string State, int Count)>();
foreach (var (state, calls) in CallStatesByState(rules))
{
int n = 0;
foreach (MetaRule c in calls)
if (IsEmptyTarget(c)) n++;
if (n > 0) result.Add((state, n));
}
return result;
}
/// <summary>How many CallState rules have no target.</summary>
public static int CountEmpty(IEnumerable<MetaRule> rules)
{
int n = 0;
foreach (var (_, count) in EmptyTargets(rules)) n += count;
return n;
}
/// <summary>
/// The .met the .af came from: the same name next to it, else in a folder above it up to the
/// MetaFiles folder (metas live flat in MetaFiles; this also covers a subfolder of it). Null
/// when there is none.
/// </summary>
public static string? FindSourceMet(string afPath)
{
try
{
if (string.IsNullOrEmpty(afPath)) return null;
string full = Path.GetFullPath(afPath);
string metName = Path.GetFileNameWithoutExtension(full) + ".met";
string? dir = Path.GetDirectoryName(full);
if (string.IsNullOrEmpty(dir)) return null;
string own = Path.Combine(dir, metName);
if (File.Exists(own)) return own;
// In a subfolder of MetaFiles: the folders above it, up to MetaFiles itself.
if (IsMetaFiles(dir) || !UnderMetaFiles(dir)) return null;
for (string? d = Path.GetDirectoryName(dir); !string.IsNullOrEmpty(d); d = Path.GetDirectoryName(d))
{
string candidate = Path.Combine(d, metName);
if (File.Exists(candidate)) return candidate;
if (IsMetaFiles(d)) break;
}
}
catch { }
return null;
}
private static bool IsMetaFiles(string dir)
=> Path.GetFileName(dir).Equals("MetaFiles", StringComparison.OrdinalIgnoreCase);
private static bool UnderMetaFiles(string dir)
{
for (string? d = Path.GetDirectoryName(dir); !string.IsNullOrEmpty(d); d = Path.GetDirectoryName(d))
if (IsMetaFiles(d)) return true;
return false;
}
/// <summary>The chat line for a meta that loaded with CallState rules that call nothing.</summary>
public static string WarningLine(string afFileName, int count, string? metPath)
{
string rules = count == 1 ? "1 CallState rule has" : $"{count} CallState rules have";
string head = $"[RynthAi] {afFileName}: {rules} no state to call. The file was saved by an older RynthAi and the targets are lost.";
return metPath != null
? $"{head} Load the original .met instead, or use Repair from .met (Macro Rules window, or /ra meta repair) to fill them from {Path.GetFileName(metPath)}."
: $"{head} No {Path.GetFileNameWithoutExtension(afFileName)}.met is next to it to repair from: load the original .met if you have it, or set each CallState's target in the editor.";
}
/// <summary>What <see cref="Repair"/> did.</summary>
internal sealed class Result
{
public bool Ok;
/// <summary>CallState rules given a target.</summary>
public int Filled;
/// <summary>States with a rule filled.</summary>
public int States;
/// <summary>Why it was refused (empty when it worked).</summary>
public string Why = string.Empty;
/// <summary>Each state the repair touched, with the targets it put back ("20_UPPER_S: 90_DO_STONE").</summary>
public List<string> Details = new();
}
/// <summary>
/// Fills the empty CallState targets (and their return states) in <paramref name="afRules"/>
/// from <paramref name="metRules"/>, by order within each state. Nothing is changed unless every
/// state with an empty target matches: the state is in the .met, it has as many CallState
/// actions there, and the .met's matching rule has a target. A CallState that already has a
/// target is left as it is.
/// </summary>
public static Result Repair(List<MetaRule> afRules, List<MetaRule> metRules)
{
var result = new Result();
var af = CallStatesByState(afRules);
var met = new Dictionary<string, List<MetaRule>>(StringComparer.OrdinalIgnoreCase);
foreach (var (state, calls) in CallStatesByState(metRules))
met[state] = calls;
var problems = new List<string>();
var work = new List<(string State, List<MetaRule> Af, List<MetaRule> Met)>();
foreach (var (state, calls) in af)
{
bool needs = false;
foreach (MetaRule c in calls)
if (IsEmptyTarget(c)) { needs = true; break; }
if (!needs) continue;
if (!met.TryGetValue(state, out var metCalls))
{
problems.Add($"state '{state}' isn't in the .met");
continue;
}
if (metCalls.Count != calls.Count)
{
problems.Add($"state '{state}' has {calls.Count} CallState rule{(calls.Count == 1 ? "" : "s")} in the .af and {metCalls.Count} in the .met");
continue;
}
for (int i = 0; i < calls.Count; i++)
if (IsEmptyTarget(calls[i]) && string.IsNullOrWhiteSpace(metCalls[i].ActionData))
problems.Add($"state '{state}': CallState {i + 1} has no target in the .met either");
work.Add((state, calls, metCalls));
}
if (work.Count == 0 && problems.Count == 0)
{
result.Why = "no CallState rule is missing its target";
return result;
}
if (problems.Count > 0)
{
const int Shown = 3;
string list = string.Join("; ", problems.GetRange(0, Math.Min(Shown, problems.Count)));
if (problems.Count > Shown) list += $"; and {problems.Count - Shown} more";
result.Why = $"the .met doesn't match the .af ({list}). The .af may have been edited since; nothing was changed";
return result;
}
foreach (var (state, afCalls, metCalls) in work)
{
var filled = new List<string>();
for (int i = 0; i < afCalls.Count; i++)
{
if (!IsEmptyTarget(afCalls[i])) continue;
MetaRule from = metCalls[i];
afCalls[i].ActionData = from.ActionData;
// VTank's "ret": what Return goes back to. Empty there means the calling state.
afCalls[i].CallReturnState = string.IsNullOrWhiteSpace(from.CallReturnState) ? state : from.CallReturnState;
filled.Add(from.ActionData + " (return " + afCalls[i].CallReturnState + ")");
result.Filled++;
}
if (filled.Count > 0)
{
result.States++;
result.Details.Add($"{state}: {string.Join(", ", filled)}");
}
}
result.Ok = true;
return result;
}
/// <summary>The backup copy's path: "&lt;name&gt;.af.bak-yyyyMMdd-HHmmss" next to it.</summary>
public static string BackupPath(string afPath, DateTime now)
=> afPath + ".bak-" + now.ToString("yyyyMMdd-HHmmss", System.Globalization.CultureInfo.InvariantCulture);
}

View file

@ -3672,6 +3672,8 @@ internal sealed partial class ExpressionEngine
["ItemInfoLootChatType"] = (() => I(s.ItemInfoSettings.LootChatType), v => { if (int.TryParse(v, out int i)) s.ItemInfoSettings.LootChatType = Math.Clamp(i, -1, 31); }),
// Info text colour: "#RRGGBB" or a name ("allegiance"); "" / "default" = the chat type's own colour.
["ItemInfoTextColor"] = (() => s.ItemInfoSettings.TextColor, v => { if (RynthCore.Plugin.RynthAi.ItemInfo.MagItemInfoCatalog.ParseTextColor(v ?? string.Empty) is { } c) s.ItemInfoSettings.TextColor = c; }),
// One-line layout: each part in its own colour.
["ItemInfoPartColors"] = (() => B(s.ItemInfoSettings.PartColors), v => s.ItemInfoSettings.PartColors = ToDouble(v) != 0),
["StopMacroWhenPackFull"] = (() => B(s.StopMacroWhenPackFull), v => s.StopMacroWhenPackFull = ToDouble(v) != 0),
["SummonPets"] = (() => B(s.SummonPets), v => s.SummonPets = ToDouble(v) != 0),
["MineOnly"] = (() => B(s.MineOnly), v => s.MineOnly = ToDouble(v) != 0),
@ -3680,6 +3682,8 @@ internal sealed partial class ExpressionEngine
["AutoFellowMgmt"] = (() => B(s.AutoFellowMgmt), v => s.AutoFellowMgmt = ToDouble(v) != 0),
["OpenFellowOnCreate"] = (() => B(s.OpenFellowOnCreate), v => s.OpenFellowOnCreate = ToDouble(v) != 0),
["UseRecklessness"] = (() => B(s.UseRecklessness), v => s.UseRecklessness = ToDouble(v) != 0),
// Dirty Fighting rotation (attack heights by the effects on the target).
["DfHeightRotation"] = (() => B(s.DfHeightRotation), v => s.DfHeightRotation = ToDouble(v) != 0),
// The range a monster rule's Variable attack power picks from (percent of the bar).
["VariablePowerMin"] = (() => I(s.VariablePowerMin), v => { if (int.TryParse(v, out int i)) s.VariablePowerMin = Math.Clamp(i, 0, 100); }),
["VariablePowerMax"] = (() => I(s.VariablePowerMax), v => { if (int.TryParse(v, out int i)) s.VariablePowerMax = Math.Clamp(i, 0, 100); }),

View file

@ -0,0 +1,151 @@
// CraftAutoConfirm.cs - "Auto-confirm crafting": say Yes to the server's craft-chance prompt when
// the chance is high enough, for crafts and tinkers the player starts by hand.
//
// When a player combines two items (salvage on an item, a crafting recipe) the server asks first:
// "You determine that you have a N percent chance to succeed." with Yes / No. With the setting on
// (LegacyUiSettings.AutoConfirmCraft, off by default) RynthAi keeps the engine's sticky
// CraftInteraction answer armed (plugin API v97, RynthCoreHost.ArmConfirmationLeaveBelow): a prompt
// at or above the threshold (AutoConfirmCraftPercent, 50-100, default 100) is answered Yes without
// the dialog opening; a lower one shows AC's own dialog as usual. It never says No.
//
// The engine's arm lasts ArmTimeoutMs; it is re-armed every RearmAfterMs, so it stays up while the
// setting is on and goes away by itself at most a minute after RynthAi stops ticking.
//
// The tinker runner (TinkerRunner) arms the engine's ONE-SHOT answer for each of its own steps (Yes
// at the tab's Min chance %, else No). The engine keeps the two in separate slots and asks the
// one-shot first, and a one-shot's arm or disarm never touches the sticky arm, so the runner's
// steps keep its own rule and the sticky arm is still there when the run ends: the two never fight.
// A Yes from the sticky arm is outcome AcceptedSticky, so only those get the chat line.
//
// Pump thread (CraftingTab.Tick, OnLogout). The UI reads Status / Supported only.
using System;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
internal sealed class CraftAutoConfirm
{
public const int MinThreshold = 50;
public const int MaxThreshold = 100;
public const int DefaultThreshold = 100;
/// <summary>The engine arm's life (the engine caps it at 120 s).</summary>
public const int ArmTimeoutMs = 60_000;
/// <summary>Re-arm this often while on (well inside <see cref="ArmTimeoutMs"/>); also the retry gap after a refusal.</summary>
public const long RearmAfterMs = 20_000;
/// <summary>Why the setting can't work on this engine (the checkbox's tooltip and the command's reply).</summary>
public const string NeedsEngineText = "needs a newer RynthCore (core update with plugin API 97)";
private readonly Func<RynthCoreHost> _host;
private readonly Func<LegacyUiSettings?> _settings;
private readonly Action<string> _chat;
// Pump thread.
private bool _armed;
private int _armedPercent;
private long _armedAt;
private long _lastTryAt = long.MinValue / 2;
private int _seenSeq = -1;
private volatile string _status = "off";
private volatile int _accepted;
public CraftAutoConfirm(Func<RynthCoreHost> host, Func<LegacyUiSettings?> settings, Action<string> chat)
{
_host = host;
_settings = settings;
_chat = chat;
}
/// <summary>The engine can keep a sticky answer (plugin API v97). Any thread.</summary>
public bool Supported => _host().HasConfirmationLeaveBelow;
/// <summary>RynthAi's sticky arm is up (pump thread's view).</summary>
public bool Armed => _armed;
/// <summary>What it is doing, for the tab and /ra autoconfirm status.</summary>
public string Status => _status;
/// <summary>Prompts answered Yes by the sticky arm this session.</summary>
public int AcceptedCount => _accepted;
public static int ClampPercent(int percent) => Math.Clamp(percent, MinThreshold, MaxThreshold);
/// <summary>The chat line after an auto-accepted prompt.</summary>
public static string AcceptedLine(int percent) => $"[RynthAi] Auto-confirmed: {(percent >= 0 ? percent + "%" : "the")} chance";
/// <summary>One pump tick: report what the arm answered, then keep it armed while the setting is on.</summary>
public void Tick(long nowMs)
{
RynthCoreHost host = _host();
ReportAnswers(host);
LegacyUiSettings? s = _settings();
if (s == null || !s.AutoConfirmCraft)
{
Release(host, "off");
return;
}
if (!host.HasConfirmationLeaveBelow)
{
_armed = false;
_status = "off: " + NeedsEngineText;
return;
}
int percent = ClampPercent(s.AutoConfirmCraftPercent);
if (_armed && percent == _armedPercent && nowMs - _armedAt < RearmAfterMs)
return;
if (!_armed && nowMs - _lastTryAt < RearmAfterMs && percent == _armedPercent)
return; // refused a moment ago: try again later, not every tick
_lastTryAt = nowMs;
_armedPercent = percent;
int r = host.ArmConfirmationLeaveBelow(RynthCoreHost.ConfirmationKind.CraftInteraction, percent, ArmTimeoutMs);
if (r == 1)
{
_armed = true;
_armedAt = nowMs;
_status = $"on: Yes at {percent}% or better";
return;
}
_armed = false;
_status = r == 0
? "waiting: this client can't answer prompts yet (the engine's sender or hook is missing)"
: "off: the engine refused the arm (" + NeedsEngineText + ")";
}
/// <summary>Drops RynthAi's sticky arm (setting off, logout, teardown). Pump thread.</summary>
public void Release(string status = "off")
{
Release(_host(), status);
_seenSeq = -1;
}
private void Release(RynthCoreHost host, string status)
{
if (_armed && host.HasConfirmationLeaveBelow)
host.DisarmConfirmationLeaveBelow(RynthCoreHost.ConfirmationKind.CraftInteraction);
_armed = false;
_armedPercent = 0;
_status = status;
}
/// <summary>One chat line for each prompt the sticky arm said Yes to since the last look.</summary>
private void ReportAnswers(RynthCoreHost host)
{
if (!host.HasConfirmationAnswers
|| !host.TryGetLastConfirmation(out int seq, out uint type, out int percent, out int outcome, out _))
return;
if (_seenSeq < 0)
{
_seenSeq = seq; // what came before RynthAi was looking is not reported
return;
}
if (seq == _seenSeq) return;
_seenSeq = seq;
if (type != RynthCoreHost.ConfirmationKind.CraftInteraction || outcome != RynthCoreHost.ConfirmationOutcome.AcceptedSticky)
return;
_accepted++;
_chat(AcceptedLine(percent));
}
}

View file

@ -10,6 +10,8 @@
// Infinite Leaftide), then the player's own rows for this world (CraftingTabState.CustomByWorld).
// With none defined it says so.
// One TinkerRunner works one tab's scan at a time.
// Above the benches: "Auto-confirm crafting" (CraftAutoConfirm), Yes to the server's chance prompt
// at the chosen percent for crafts the player starts by hand.
using System;
using System.Collections.Generic;
using System.Linq;
@ -26,6 +28,9 @@ internal sealed class CraftingTab
public TinkerRunner Runner { get; }
/// <summary>Auto-confirm crafting (the sticky engine answer for hand-made crafts).</summary>
public CraftAutoConfirm AutoConfirm { get; }
// Custom-row editor (render thread only)
private int _newMaterial = TinkerCatalog.Steel;
private int _newKind;
@ -39,6 +44,7 @@ internal sealed class CraftingTab
{
_ctx = ctx;
Runner = new TinkerRunner(ctx, RowsFor, SettingsFor);
AutoConfirm = new CraftAutoConfirm(() => ctx.Host, () => ctx.Settings, ctx.Chat);
}
private CraftingTabState C => _ctx.State.Crafting;
@ -78,16 +84,25 @@ internal sealed class CraftingTab
// ── Lifecycle (MiniRemoteController) ─────────────────────────────────────────────────────────
public void Tick(long nowMs) => Runner.Tick(nowMs);
public void Tick(long nowMs)
{
Runner.Tick(nowMs);
AutoConfirm.Tick(nowMs);
}
public void OnChat(string text) => Runner.OnChat(text);
public void OnLogout() => Runner.OnLogout();
public void OnLogout()
{
Runner.OnLogout();
AutoConfirm.Release();
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
RenderAutoConfirm();
if (!ImGui.BeginTabBar("##crafting")) return;
if (ImGui.BeginTabItem("Armor")) { RenderBench(TinkerBench.Armor); ImGui.EndTabItem(); }
if (ImGui.BeginTabItem("Weapons"))
@ -107,6 +122,48 @@ internal sealed class CraftingTab
ImGui.EndTabBar();
}
/// <summary>Auto-confirm crafting: the checkbox, the percent and what it has done.</summary>
private void RenderAutoConfirm()
{
var settings = _ctx.Settings;
if (settings == null) return;
bool supported = AutoConfirm.Supported;
bool on = settings.AutoConfirmCraft && supported;
ImGui.BeginDisabled(!supported);
if (ImGui.Checkbox("Auto-confirm crafting##autoconfirm", ref on))
{
bool value = on;
_ctx.Post(() => { settings.AutoConfirmCraft = value; _ctx.SaveCombatSettings?.Invoke(); });
}
ImGui.EndDisabled();
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
SafeImGui.SetTooltip(supported
? "When you combine items yourself (salvage on an item, a crafting recipe), click Yes on the\n"
+ "server's \"N percent chance to succeed\" prompt when the chance is at least the percent here.\n"
+ "A lower chance shows AC's dialog as usual. It never says No. Also /ra autoconfirm."
: "Auto-confirm crafting " + CraftAutoConfirm.NeedsEngineText + ".");
ImGui.SameLine();
ImGui.BeginDisabled(!supported || !settings.AutoConfirmCraft);
int percent = CraftAutoConfirm.ClampPercent(settings.AutoConfirmCraftPercent);
ImGui.SetNextItemWidth(90);
if (ImGui.InputInt("% or better##autoconfirmpct", ref percent, 5))
{
int value = CraftAutoConfirm.ClampPercent(percent);
_ctx.Post(() => { settings.AutoConfirmCraftPercent = value; _ctx.SaveCombatSettings?.Invoke(); });
}
ImGui.EndDisabled();
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
ImGui.SetTooltip($"The lowest chance to say Yes to ({CraftAutoConfirm.MinThreshold}-{CraftAutoConfirm.MaxThreshold}). Below it AC's dialog shows.");
ImGui.SameLine();
if (!supported)
SafeImGui.TextDisabled("needs a RynthCore update");
else if (settings.AutoConfirmCraft && AutoConfirm.AcceptedCount > 0)
SafeImGui.TextDisabled($"{AutoConfirm.AcceptedCount} confirmed this session");
else
SafeImGui.TextDisabled(settings.AutoConfirmCraft ? AutoConfirm.Status : "");
ImGui.Separator();
}
private void RenderBench(TinkerBench bench)
{
var s = SettingsFor(bench);

View file

@ -193,7 +193,7 @@ internal sealed unsafe class ServerHubClient
/// <summary>
/// This character forces the plugin's server (its own override; set there or in
/// RynthCore's Options > Diagnostics, never by RynthAi). Any thread.
/// RynthCore's Settings > Game Client, never by RynthAi). Any thread.
/// </summary>
public bool ServerForced
{

View file

@ -30,6 +30,36 @@ internal sealed class OutdoorHunt
{
internal enum PathStatus { Ok, Partial, NoPath, NoMesh, Unavailable }
/// <summary>Why the hunt can't start here (None: it can). The Hunt button and Hunt On Login ask the same.</summary>
internal enum StartBlock { None, NoSettings, NoPosition, InDungeon, UnknownBuilding, NoRynthNav }
/// <summary>
/// The checks before a start, in order, each asked only when the ones before it passed (the later
/// ones read cell.dat and RynthNav): settings, a position, not in a dungeon, not in a building whose
/// doors it doesn't know, RynthNav's map there.
/// </summary>
internal static StartBlock WhyNoStart(bool hasSettings, bool hasPosition,
Func<bool> inDungeon, Func<bool> unknownBuilding, Func<bool> noRynthNav)
{
if (!hasSettings) return StartBlock.NoSettings;
if (!hasPosition) return StartBlock.NoPosition;
if (inDungeon()) return StartBlock.InDungeon;
if (unknownBuilding()) return StartBlock.UnknownBuilding;
if (noRynthNav()) return StartBlock.NoRynthNav;
return StartBlock.None;
}
/// <summary>What chat says for a <see cref="StartBlock"/> (after "[RynthAi] ").</summary>
internal static string StartBlockText(StartBlock b) => b switch
{
StartBlock.NoSettings => "Settings not ready.",
StartBlock.NoPosition => "Outdoor hunt: no position yet.",
StartBlock.InDungeon => "Outdoor hunt is for outdoors; in a dungeon the Dungeon Patrol hunts (Patrol).",
StartBlock.UnknownBuilding => "Outdoor hunt: start it outdoors (it doesn't know this building's doors; it finds its own way out of a building it went into).",
StartBlock.NoRynthNav => "Outdoor hunt needs RynthNav 2026.10.23 or newer (its map shows the way round obstacles).",
_ => "",
};
/// <summary>A planned walk: the corners after the start (the last is the goal), its length, and for a
/// partial path how far its end is from the goal.</summary>
internal readonly record struct PathResult(PathStatus Status, IReadOnlyList<Vec> Corners, double Length, double Gap);

View file

@ -166,12 +166,24 @@ public static unsafe class PluginExports
int drawn = plugin.RenderDashboard(popped, out want);
if (drawn != 1) return drawn;
}
else if (name.SequenceEqual("window:timedcommands"u8))
{
// The Timed Commands window (RynthAiPlugin.TimedCommands.cs): 1 drawn, 0 not ready, -2 failed.
int drawn = plugin.RenderTimedCommands(popped, out want);
if (drawn != 1) return drawn;
}
else if (name.SequenceEqual("window:monsterstats"u8))
{
// The Monster Stats window (RynthAiPlugin.MonsterStats.cs): 1 drawn, 0 not ready, -2 failed.
int drawn = plugin.RenderMonsterStats(popped, out want);
if (drawn != 1) return drawn;
}
else if (name.SequenceEqual("window:activegear"u8))
{
// The Active Gear window (RynthAiPlugin.ActiveGear.cs): 1 drawn, 0 not ready, -2 failed.
int drawn = plugin.RenderActiveGear(popped, out want);
if (drawn != 1) return drawn;
}
else if (name.StartsWith("section:"u8))
{
// Section names are short ASCII ids (Huds/SectionsManifest.cs); anything longer isn't ours.

View file

@ -71,8 +71,10 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra version — RynthAi version and build date, and the engine it runs on");
ChatLine("[RynthAi] /ra server - which server RynthCore says this is, its overrides, and the server plugin's settings");
ChatLine("[RynthAi] /ra power <0-100|auto> — set attack power (auto = recklessness-aware)");
ChatLine("[RynthAi] /ra dfheight [on|off|status|window] — Dirty Fighting rotation: attack heights by the effects on the target");
ChatLine("[RynthAi] /ra cast <spellId> — cast spell on current target");
ChatLine("[RynthAi] /ra buffs — show active buff timers");
ChatLine("[RynthAi] /ra buffitems [list|allow|block|add|addselected|remove|repeat|open] — the buff items RynthAi may use");
ChatLine("[RynthAi] /ra scan — show nearby monsters");
ChatLine("[RynthAi] /ra cache — show object cache summary");
ChatLine("[RynthAi] /ra cache2 — show raw object cache IDs");
@ -108,9 +110,11 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra meta load <name> — load a meta from MetaFiles (none by that name: a new blank one)");
ChatLine("[RynthAi] /ra meta new <name> — create a blank meta and load it");
ChatLine("[RynthAi] /ra meta list — list the metas in MetaFiles");
ChatLine("[RynthAi] /ra meta repair — fill the loaded .af's CallState rules that call no state from the .met of the same name");
ChatLine("[RynthAi] /ra lua run <name> — run a RynthLua script (same as /lua run; also stop, list, exec <code>)");
ChatLine("[RynthAi] /ra items fill — add weapons, healing kits, lockpicks and pet essences from your pack");
ChatLine("[RynthAi] /ra aetheria [status|unbox|on|off] — unbox Coalesced Aetheria with an Aetheria Mana Stone (Unbox Aetheria When Idle)");
ChatLine("[RynthAi] /ra autoconfirm [status|on|off|<50-100>] — Yes to the craft-chance prompt at that % or better (Mini Remote > Crafting)");
ChatLine("[RynthAi] /ra offhand [auto|shield|weapon|none] [rule] — the off hand (shield / dual wield), global or for a Monsters rule; dual on|off");
ChatLine("[RynthAi] /ra dunnav <NS> <EW> — navigate to NS/EW coords through dungeon (no nav file needed)");
ChatLine("[RynthAi] /ra dunnav-patrol — circular hunt patrol through the whole dungeon (no nav file needed)");
@ -135,6 +139,8 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra dumpinv — dump all inventory items (cache + direct)");
ChatLine("[RynthAi] /ra combat — dump combat state machine snapshot");
ChatLine("[RynthAi] /ra mstats [monster] — its evades, resists, hits, spells and kills this session (list | reset | show | hide)");
ChatLine("[RynthAi] /ra timed [server|all] list | add <seconds> <command> | remove|on|off|run <n> | show — commands sent every N seconds (window: the RynthAi options menu > Timed commands)");
ChatLine("[RynthAi] /ra gear — which worn items have their magic on, mana and time left (check | list | hide; the Active Gear window)");
ChatLine("[RynthAi] /ra why — one-glance diagnosis of why the bot is idle/attacking");
ChatLine("[RynthAi] /ra start | stop — start/stop the macro from chat");
ChatLine("[RynthAi] /ra pause [sec] — stop the macro, auto-resume after sec (default 60)");
@ -1290,6 +1296,14 @@ public sealed partial class RynthAiPlugin
var names = _dashboard.NavFileNames();
ChatLine(names.Count == 0 ? "[RynthAi] No navs in NavProfiles." : $"[RynthAi] Navs ({names.Count}): {string.Join(", ", names)}");
break;
case "new":
case "saveas":
case "rename":
case "delete":
case "folder":
// The Loaded files drawer's NAV buttons (RynthAiPlugin.ProfileFiles.cs).
TryProfileVerb(ProfileKind.Nav, sub, rest, NavUsage);
break;
case "restart":
{
// Stopping and starting the macro keeps the route where it was (a finished Once
@ -1308,13 +1322,21 @@ public sealed partial class RynthAiPlugin
}
default:
// Bare "/ra nav" asks what it takes; anything else is a wrong form.
const string navUsage = "[RynthAi] /ra nav save [name] | /ra nav load <name> | /ra nav list | /ra nav restart";
if (sub.Length == 0) ChatLine(navUsage);
else ReplyFail($"[RynthAi] Unknown /ra nav verb '{sub}'. Usage: /ra nav save [name] | load <name> | list | restart");
if (sub.Length == 0) ChatLine("[RynthAi] " + NavUsage);
else ReplyFail($"[RynthAi] Unknown /ra nav verb '{sub}'. Usage: {NavUsage}");
break;
}
}
private const string NavUsage =
"/ra nav save [name] | /ra nav load <name> | /ra nav new <name> | /ra nav saveas <name> | /ra nav rename <name> | /ra nav delete | /ra nav folder | /ra nav list | /ra nav restart";
private const string MetaUsage =
"/ra meta load <name> | new <name> | save | saveas <name> | rename <name> | delete | folder | list | repair";
private const string SettingsUsage =
"/ra settings loadchar <name> | savechar <name> | save | saveas <name> | rename <name> | delete | folder | list";
private const string LootFileUsage =
"/ra loot new <name> | saveas <name> | rename <name> | delete | folder | edit";
private void HandleMetaCommand(string[] parts)
{
if (_dashboard == null) { ReplyFail("[RynthAi] Settings not ready."); return; }
@ -1331,9 +1353,21 @@ public sealed partial class RynthAiPlugin
var names = _dashboard.MetaFileNames();
ChatLine(names.Count == 0 ? "[RynthAi] No metas in MetaFiles." : $"[RynthAi] Metas ({names.Count}): {string.Join(", ", names)}");
break;
case "repair":
if (rest.Length > 0) { ReplyFail("[RynthAi] Usage: /ra meta repair (repairs the loaded .af from the .met of the same name)"); break; }
ReplyResult(_dashboard.RepairMetaFromMet());
break;
case "save":
case "saveas":
case "rename":
case "delete":
case "folder":
// The Loaded files drawer's META buttons (RynthAiPlugin.ProfileFiles.cs).
TryProfileVerb(ProfileKind.Meta, sub, rest, MetaUsage);
break;
default:
if (sub.Length == 0) ChatLine("[RynthAi] /ra meta load <name> | /ra meta new <name> | /ra meta list");
else ReplyFail($"[RynthAi] Unknown /ra meta verb '{sub}'. Usage: /ra meta load <name> | new <name> | list");
if (sub.Length == 0) ChatLine("[RynthAi] " + MetaUsage);
else ReplyFail($"[RynthAi] Unknown /ra meta verb '{sub}'. Usage: {MetaUsage}");
break;
}
}
@ -1818,11 +1852,15 @@ public sealed partial class RynthAiPlugin
HandleLootModeCommand(parts);
return;
}
// The Loaded files drawer's LOOT buttons (RynthAiPlugin.ProfileFiles.cs).
if (TryProfileVerb(ProfileKind.Loot, sub, parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3) : string.Empty, LootFileUsage))
return;
if (sub != "add")
{
ChatLine("[RynthAi] /ra loot mode [profile|rares] — what is looted: the loot profile, or rares and needed mana stones only");
ChatLine("[RynthAi] /ra loot why [window] — which loot rule takes the selected item, and why the rules above it didn't (window: in the Loot why window)");
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [t11] [preview] — add a loot rule for the selected item to the loot profile in use");
ChatLine("[RynthAi] " + LootFileUsage + " — the loot profile's file: a new one in the Loot Editor, a copy, rename, move to Deleted, its folder, the editor");
ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. t11 = also require its T11 tier, grade and modifiers (at least this good). preview = show it, add nothing.");
ChatLine("[RynthAi] Also: right-click an item in the Inventory panel, or 'Add selected item' in the Loot Editor; 'Why this loot rule?' there and on the Selection window's right-click.");
return;
@ -2120,7 +2158,7 @@ public sealed partial class RynthAiPlugin
!s.EnableCombat ? "combat is disabled in settings." :
s.BusyCount > 0 ? "AC busy>0 — waiting on a server action (cast/use/move); try /ra clearbusy if stuck." :
forced != 0 && forced == s.ActiveTargetId && bySelection
? "fighting the monster you selected (Fight the monster I select: Settings > Ranges)." :
? "fighting the monster you selected (Fight the monster I select: Settings > Combat > Targeting)." :
forced != 0 && forced == s.ActiveTargetId
? "fighting the target-locked monster (/ra targetlock; /ra targetlock off releases it)." :
total < 0 ? "no combat scan has run yet (cold start / just logged in)." :
@ -2498,16 +2536,30 @@ public sealed partial class RynthAiPlugin
private void HandleSettingsCommand(string[] parts)
{
string sub = parts.Length > 2 ? parts[2].ToLowerInvariant() : string.Empty;
string rest = parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3).Trim() : string.Empty;
if (sub is "save" or "saveas" or "rename" or "delete" or "folder")
{
// The Loaded files drawer's PROFILE buttons (RynthAiPlugin.ProfileFiles.cs).
TryProfileVerb(ProfileKind.Settings, sub, rest, SettingsUsage);
return;
}
if (sub == "list")
{
if (_dashboard == null) { ReplyFail("[RynthAi] Dashboard not ready."); return; }
DashboardFiles files = _dashboard.ReadDashboardFiles();
ChatLine($"[RynthAi] Settings profiles ({files.Profiles.Length}): {string.Join(", ", files.Profiles)}; in use: {files.ProfileName}.");
return;
}
if (parts.Length < 4)
{
ReplyFail("[RynthAi] Usage: /ra settings loadchar <name> | /ra settings savechar <name>");
ReplyFail("[RynthAi] Usage: " + SettingsUsage);
return;
}
string sub = parts[2].ToLower();
if (sub != "loadchar" && sub != "savechar")
{
ReplyFail("[RynthAi] Usage: /ra settings loadchar <name> | /ra settings savechar <name>");
ReplyFail("[RynthAi] Usage: " + SettingsUsage);
return;
}

View file

@ -29,7 +29,8 @@ namespace RynthCore.Plugin.RynthAi;
/// /ra iteminfo loot on|off describe what the looter takes in its "Looted" line
/// /ra iteminfo loot salvage on|off salvage too (material and workmanship only)
/// /ra iteminfo color &lt;name&gt;|#RRGGBB the lines' colour in RynthCore's chat, whatever their chat type ("default": the type's)
/// /ra iteminfo reset restore defaults
/// /ra iteminfo parts on|off one-line layout: each part (name, set, spells, ...) in its own colour
/// /ra iteminfo reset restore defaults
/// Every option is also editable in the "RynthAi Item Info" window (LegacyItemInfoUi).
/// </summary>
public sealed partial class RynthAiPlugin
@ -183,6 +184,15 @@ public sealed partial class RynthAiPlugin
: $"[RynthAi] Item info text colour: {MagItemInfoCatalog.TextColorLabel(s.TextColor)} in RynthCore's chat (same tab; AC's chat window shows the chat type's colour)");
return;
case "parts":
case "partcolors":
case "partcolours":
if (ParseOnOff(arg3) is bool partsOn) s.PartColors = partsOn;
else if (arg3.Length > 0) { ReplyFail("[RynthAi] Usage: /ra iteminfo parts on|off"); return; }
ReplyOk($"[RynthAi] Item info colour per part: {OnOff(s.PartColors)}"
+ (s.PartColors && s.Layout != MagItemInfoSettings.LayoutOneLine ? " (the one-line layout only: /ra iteminfo layout line)" : ""));
return;
case "reset":
s.ResetToDefaults();
ReplyOk("[RynthAi] Item info settings reset to defaults.");
@ -203,7 +213,7 @@ public sealed partial class RynthAiPlugin
if (found != 0) { QueueItemInfo(unchecked((int)found), requestId: true); return; }
ReplyFail($"[RynthAi] Item info: no \"{name}\" in your inventory.");
}
ReplyFail("[RynthAi] Usage: /ra iteminfo [<item name>|me|on|off|settings|fields|field <name> on|off|rating <tag> on|off|value on|off|verbose on|off|click left|right|off|layout pet|line|loot on|off|color <name>|#RRGGBB|reset]");
ReplyFail("[RynthAi] Usage: /ra iteminfo [<item name>|me|on|off|settings|fields|field <name> on|off|rating <tag> on|off|value on|off|verbose on|off|click left|right|off|layout pet|line|loot on|off|color <name>|#RRGGBB|parts on|off|reset]");
}
/// <summary>"default|allegiance|...|#RRGGBB": what /ra iteminfo color takes.</summary>
@ -443,18 +453,26 @@ public sealed partial class RynthAiPlugin
/// Builds the output lines (no prefix / indent) in the configured layout, or returns null
/// with <paramref name="error"/> set. The one-line layout returns a single line.
/// </summary>
private List<string>? BuildItemInfoLines(int itemId, out string? error)
private List<string>? BuildItemInfoLines(int itemId, out string? error) => BuildItemInfoLines(itemId, out error, out _);
/// <summary>
/// As above; for the one-line layout <paramref name="oneLineParts"/> is that line as (part, text)
/// pieces (joined, exactly the line) for the per-part colours; null for the pet-style layout.
/// </summary>
private List<string>? BuildItemInfoLines(int itemId, out string? error, out List<(ItemInfoPart Part, string Text)>? oneLineParts)
{
error = null;
oneLineParts = null;
WorldObject? wo = _objectCache?[itemId];
if (wo == null) { error = $"Item 0x{(uint)itemId:X8} is not in the object cache."; return null; }
try
{
var s = ItemInfoSettings;
MagItemDescription d = MagItemDescriber.Build(new CacheItemPropertySource(Host, wo), MagItemInfoOptions.From(s));
return (s?.Layout ?? MagItemInfoSettings.LayoutPetLines) == MagItemInfoSettings.LayoutOneLine
? new List<string> { d.ToOneLine() }
: d.ToPetLines();
if ((s?.Layout ?? MagItemInfoSettings.LayoutPetLines) != MagItemInfoSettings.LayoutOneLine)
return d.ToPetLines();
oneLineParts = d.ToOneLineParts();
return new List<string> { d.ToOneLine() };
}
catch (Exception ex)
{
@ -470,7 +488,7 @@ public sealed partial class RynthAiPlugin
/// </summary>
private void PrintItemInfo(int itemId, bool identified)
{
List<string>? lines = BuildItemInfoLines(itemId, out string? error);
List<string>? lines = BuildItemInfoLines(itemId, out string? error, out var oneLineParts);
if (lines == null || lines.Count == 0)
{
ItemInfoLog($"0x{(uint)itemId:X8}: not printed: {error}");
@ -486,7 +504,13 @@ public sealed partial class RynthAiPlugin
int headerType = s?.ChatType ?? 1;
int detailType = s == null || s.DetailChatType == MagItemInfoSettings.SameAsHeader ? headerType : s.DetailChatType;
WriteItemInfoLine(prefix + lines[0], headerType);
// One-line layout, colour per part: the parts' ranges, after the prefix (the tails added
// above come after every part and keep the line's colour).
string first = prefix + lines[0];
string? spans = s is { PartColors: true } && oneLineParts != null
? ItemInfoPartColors.Payload(ItemInfoPartColors.Ranges(oneLineParts, prefix.Length), first.Length)
: null;
WriteItemInfoLine(first, headerType, spans);
for (int i = 1; i < lines.Count; i++)
WriteItemInfoLine(prefix + " " + lines[i], detailType);
}
@ -504,7 +528,18 @@ public sealed partial class RynthAiPlugin
/// is asked to draw the next line in that colour just before it is written: RynthCore's chat
/// shows it so, in the same tab. Unset, or an older engine: the plain WriteToChat, as before.
/// </summary>
internal void WriteItemInfoLine(string text, int chatType)
internal void WriteItemInfoLine(string text, int chatType) => WriteItemInfoLine(text, chatType, null);
// An engine from before 2026-11-11 has line colours but no colour runs: it refuses "nextspans"
// and its "none" alike. The lines then keep one colour, without asking again.
private bool _partColorsUnsupported;
/// <summary>
/// As above; <paramref name="spans"/> (ItemInfoPartColors.Payload, "start:length:RRGGBB;...")
/// asks for those characters in their own colours too (engine ChatOwnColors "nextspans"). The
/// whole-line colour goes first, so an engine without colour runs still draws the line in it.
/// </summary>
internal void WriteItemInfoLine(string text, int chatType, string? spans)
{
string color = ItemInfoSettings?.TextColor ?? string.Empty;
if (color.Length > 0 && text.Length > 0 && !_infoColorUnsupported && Host.HasWriteToChat && Host.HasSendPluginCommand
@ -513,6 +548,19 @@ public sealed partial class RynthAiPlugin
_infoColorUnsupported = true;
ItemInfoLog("the engine has no line colours (before 2026-11-05): item info keeps its chat type's colour");
}
if (!string.IsNullOrEmpty(spans) && text.Length > 0 && !_partColorsUnsupported && !_infoColorUnsupported
&& Host.HasWriteToChat && Host.HasSendPluginCommand
&& !Host.SendPluginCommand(ChatColorTarget, ItemInfoPartColors.NextSpansAction, spans))
{
// "none" tells a refused payload (logged, kept on) from an engine without runs.
if (Host.SendPluginCommand(ChatColorTarget, ItemInfoPartColors.NextSpansAction, "none"))
ItemInfoLog($"the engine refused the part colours '{spans}' for '{text}': this line keeps one colour");
else
{
_partColorsUnsupported = true;
ItemInfoLog("the engine has no part colours (before 2026-11-11): item info lines keep one colour");
}
}
Host.WriteToChat(text, chatType);
}
@ -572,4 +620,17 @@ public sealed partial class RynthAiPlugin
string color = ItemInfoSettings?.TextColor ?? string.Empty;
WriteItemInfoLine($"{prefix}Item info chat test (type {chatType}{(color.Length > 0 ? ", colour " + color : "")})", chatType);
}
/// <summary>
/// Item Info window "Colour each part" Test: a one-line sample naming every part, each in its
/// colour, in the Item Info chat type (as a real one-line item info line is written).
/// </summary>
private void TestItemInfoPartColors()
{
string prefix = ItemInfoSettings?.Prefix ?? "[RynthAi Item] ";
var pieces = ItemInfoPartColors.SamplePieces();
string text = prefix + ItemInfoPartColors.Join(pieces);
WriteItemInfoLine(text, ItemInfoSettings?.ChatType ?? 1,
ItemInfoPartColors.Payload(ItemInfoPartColors.Ranges(pieces, prefix.Length), text.Length));
}
}

View file

@ -0,0 +1,356 @@
// RynthAiPlugin.ActiveGear.cs — the Active Gear window and /ra gear (2026-11-11, a player's request:
// "is there any place that shows you what gear is activated and what is not? Like MagTools does?").
//
// One row per worn item with spells: its slot, whether its magic is on (and why not, when that can
// be told), its mana, the time its mana lasts at its rate, and its spells (on hover). The logic is
// ActiveGear/GearActivation.cs (pure, tested); this file reads the engine for it:
// * what is worn: EquippedState (the engine's EquipmentTracker, API v87; the client's fields before it);
// * the item's appraisal: HasAppraisalData, GetObjectSpellIds (bit 31 = on the item itself),
// CurrentMana 107 / MaxMana 108 / ItemDifficulty 109 / activation level 115 and skill 176 (ints),
// ManaRate 5 (float), and GetLastIdTime (when it was appraised, Unix seconds);
// * the player's enchantments: ReadPlayerEnchantments (an item's spell on its wearer has no end time);
// * the player's Arcane Lore and activation skill: TryGetObjectSkill.
// "Check items" (and /ra gear check) identifies the worn items again, one every 1.5 s, so the mana
// reads and the on-the-item spells are fresh.
//
// The window is a plugin window (API v89) declared in the sections manifest without a bar button;
// the dashboard's options menu (⋯ > Active gear) and /ra gear open it. Pump thread throughout,
// except the window (render thread: it reads the published view and queues Check items for the tick).
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.ActiveGear;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
/// <summary>The window's title (its panel key) and surface (Huds/SectionsManifest.cs).</summary>
internal const string ActiveGearTitle = "Active Gear", ActiveGearSurface = "window:activegear";
internal const string ActiveGearUsage = "Usage: /ra gear [show | hide | check | list]";
private const uint GearCurManaKey = 107, GearMaxManaKey = 108, GearDifficultyKey = 109,
GearActivationLevelKey = 115, GearActivationSkillKey = 176;
private const uint GearManaRateKey = 5; // PropertyFloat ManaRate
private const uint GearProcSpellKey = 55; // PropertyDataId ProcSpell (a cloak's, aetheria's or weapon's proc)
private const uint ArcaneLoreSkill = 14;
private const long GearViewEveryMs = 1000, GearWornTrackEveryMs = 2000, GearCheckSpacingMs = 1500;
private volatile ActiveGearView _gearView = ActiveGearView.Empty; // tick writes, render reads
private long _gearViewAtMs = long.MinValue / 2;
private long _gearDrawnMs = long.MinValue / 2; // render writes, tick reads
private long _gearWornAtMs = long.MinValue / 2;
// When each worn item was first seen worn this login (ms): an appraisal newer than that lists its
// on-the-item spells. Dropped when the item comes off.
private readonly Dictionary<int, long> _gearWornSince = new();
// Check items: the ids still to identify, the next send, and how many were asked for in all.
private readonly Queue<int> _gearCheckQueue = new();
private long _gearNextCheckMs;
private int _gearCheckTotal;
private volatile bool _gearCheckWanted; // the window's button (render thread)
private ActiveGearWindow? _gearWindow; // render thread
private int _gearFailures; // render thread
private readonly uint[] _gearSpellBuf = new uint[128];
private readonly uint[] _gearEnchIds = new uint[512];
private readonly double[] _gearEnchExp = new double[512];
/// <summary>The window goes in the manifest on an engine with plugin windows (v89).</summary>
private bool ActiveGearWindowWanted => Host.HasUiTheme && Host.HasSetPanelOpen;
/// <summary>The last view (tests).</summary>
internal ActiveGearView ActiveGearViewForTests => _gearView;
// ── Tick ─────────────────────────────────────────────────────────────
/// <summary>Pump thread: worn-since tracking, Check items' sends, and the view while the window shows.</summary>
private void TickActiveGear()
{
if (!_loginComplete || _objectCache == null || _playerId == 0) return;
long now = Environment.TickCount64;
if (now - _gearWornAtMs >= GearWornTrackEveryMs) TrackWorn(now, ReadWorn());
if (_gearCheckWanted)
{
_gearCheckWanted = false;
StartGearCheck();
}
TickGearCheck(now);
bool shown = now - Volatile.Read(ref _gearDrawnMs) < 2000;
if (shown && now - _gearViewAtMs >= GearViewEveryMs) PublishGearView(now);
}
/// <summary>What is worn (item id -> EquipMask): the engine's tracker, or the client's fields before it.</summary>
private Dictionary<int, int> ReadWorn()
{
if (EquippedState.TryGet(Host, out Dictionary<int, int> map)) return new Dictionary<int, int>(map);
return EquippedState.ReadFresh(Host, _objectCache);
}
private void TrackWorn(long now, Dictionary<int, int> worn)
{
_gearWornAtMs = now;
foreach (int id in worn.Keys) _gearWornSince.TryAdd(id, now);
if (_gearWornSince.Count == worn.Count) return;
var gone = new List<int>();
foreach (int id in _gearWornSince.Keys) if (!worn.ContainsKey(id)) gone.Add(id);
foreach (int id in gone) _gearWornSince.Remove(id);
}
/// <summary>Queues every listed worn item for an identify (the unidentified first). Returns how many.</summary>
private int StartGearCheck()
{
if (!Host.HasRequestId) return 0;
ActiveGearView view = BuildGearView(Environment.TickCount64);
_gearCheckQueue.Clear();
foreach (ActiveGearRow r in view.Rows) if (!r.Facts.Identified) _gearCheckQueue.Enqueue(r.Id);
foreach (ActiveGearRow r in view.Rows) if (r.Facts.Identified) _gearCheckQueue.Enqueue(r.Id);
_gearCheckTotal = _gearCheckQueue.Count;
_gearNextCheckMs = 0;
Host.Log($"[RynthAi] Active gear: identifying {_gearCheckTotal} worn item(s), one every {GearCheckSpacingMs / 1000.0:0.#} s.");
return _gearCheckTotal;
}
/// <summary>One identify every 1.5 s while Check items has some left; a refused one is asked again next time.</summary>
private void TickGearCheck(long now)
{
if (_gearCheckQueue.Count == 0 || now < _gearNextCheckMs) return;
_gearNextCheckMs = now + GearCheckSpacingMs;
int id = _gearCheckQueue.Peek();
if (!_gearWornSince.ContainsKey(id)) { _gearCheckQueue.Dequeue(); return; } // taken off meanwhile
if (Host.RequestId(unchecked((uint)id))) _gearCheckQueue.Dequeue();
if (_gearCheckQueue.Count == 0) _gearViewAtMs = long.MinValue / 2; // the last reply shows soon
}
private void PublishGearView(long now)
{
_gearViewAtMs = now;
_gearView = BuildGearView(now);
}
/// <summary>Reads every worn item and judges it (GearActivation). Pump thread.</summary>
private ActiveGearView BuildGearView(long now)
{
if (!_loginComplete || _objectCache == null || _playerId == 0) return ActiveGearView.Empty;
Dictionary<int, int> worn = ReadWorn();
TrackWorn(now, worn);
// The player's enchantments with no end time: what worn items cast on their wearer.
bool enchReadable = false;
var playerItemSpells = new HashSet<int>();
if (Host.HasReadPlayerEnchantments)
{
int n = Host.ReadPlayerEnchantments(_gearEnchIds, _gearEnchExp, _gearEnchIds.Length);
if (n >= 0)
{
enchReadable = true;
for (int i = 0; i < n && i < _gearEnchIds.Length; i++)
if (GearActivation.IsEndless(_gearEnchExp[i])) playerItemSpells.Add(unchecked((int)_gearEnchIds[i]));
}
}
int? lore = null;
if (Host.HasGetObjectSkill && Host.TryGetObjectSkill(_playerId, ArcaneLoreSkill, out int loreBuffed, out _)) lore = loreBuffed;
long unixNow = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var rows = new List<ActiveGearRow>();
foreach (var (id, slot) in worn)
{
uint uid = unchecked((uint)id);
string name = _objectCache[id]?.Name ?? string.Empty;
if (name.Length == 0 && Host.HasGetObjectName && Host.TryGetObjectName(uid, out string n0)) name = n0 ?? string.Empty;
bool identified = Host.HasHasAppraisalData ? Host.HasAppraisalData(uid) : IntProp(uid, GearMaxManaKey).HasValue;
uint[] raw = Array.Empty<uint>();
if (identified && Host.HasGetObjectSpellIds)
{
int n = Host.GetObjectSpellIds(uid, _gearSpellBuf, _gearSpellBuf.Length);
if (n > 0)
{
raw = new uint[Math.Min(n, _gearSpellBuf.Length)];
Array.Copy(_gearSpellBuf, raw, raw.Length);
}
}
double? age = null;
if (Host.HasGetLastIdTime)
{
long at = Host.GetLastIdTime(uid);
if (at > 0) age = Math.Max(0, unixNow - at);
}
double? wornFor = _gearWornSince.TryGetValue(id, out long since) ? (now - since) / 1000.0 : null;
int actSkillId = identified ? IntProp(uid, GearActivationSkillKey) ?? 0 : 0;
int actLevel = identified ? IntProp(uid, GearActivationLevelKey) ?? 0 : 0;
int? actSkill = null;
if (actLevel > 0 && actSkillId > 0 && Host.HasGetObjectSkill
&& Host.TryGetObjectSkill(_playerId, unchecked((uint)actSkillId), out int b, out _)) actSkill = b;
double? rate = null;
if (identified && Host.HasGetObjectDoubleProperty && Host.TryGetObjectDoubleProperty(uid, GearManaRateKey, out double r)) rate = r;
uint procSpell = 0;
if (identified && Host.HasGetObjectDataIdProperty) Host.TryGetObjectDataIdProperty(uid, GearProcSpellKey, out procSpell);
var facts = new GearFacts
{
Name = name,
Slot = slot,
Identified = identified,
RawSpellIds = raw,
CurMana = identified ? IntProp(uid, GearCurManaKey) : null,
MaxMana = identified ? IntProp(uid, GearMaxManaKey) : null,
ManaRate = rate,
ReadAgeSeconds = age,
WornForSeconds = wornFor,
EnchantmentsReadable = enchReadable,
PlayerItemSpells = playerItemSpells,
ArcaneLoreNeeded = identified ? IntProp(uid, GearDifficultyKey) ?? 0 : 0,
ArcaneLore = lore,
ActivationSkillName = actSkillId > 0 && ItemInfo.MagItemInfoTables.Skills.TryGetValue(actSkillId, out string? sn) ? sn : string.Empty,
ActivationLevel = actLevel,
ActivationSkill = actSkill,
ProcSpellId = unchecked((int)procSpell),
};
if (!GearActivation.Listed(facts)) continue;
GearVerdict v = GearActivation.Judge(facts);
var spellNames = new string[v.SpellIds.Count];
for (int i = 0; i < spellNames.Length; i++) spellNames[i] = SpellDatabase.GetSpellNameOrId(v.SpellIds[i]);
rows.Add(new ActiveGearRow(id, facts, v, GearActivation.SlotName(slot), spellNames));
}
rows.Sort((a, b) =>
{
int c = GearActivation.SlotOrder(a.Facts.Slot).CompareTo(GearActivation.SlotOrder(b.Facts.Slot));
return c != 0 ? c : string.Compare(a.Facts.Name, b.Facts.Name, StringComparison.OrdinalIgnoreCase);
});
var pairs = new List<(GearFacts, GearVerdict)>(rows.Count);
foreach (ActiveGearRow row in rows) pairs.Add((row.Facts, row.Verdict));
int left = _gearCheckQueue.Count;
return new ActiveGearView(rows.ToArray(), GearActivation.Summary(pairs), true, enchReadable,
left > 0 ? _gearCheckTotal - left : -1, _gearCheckTotal, Host.HasRequestId);
}
private int? IntProp(uint id, uint key) =>
Host.HasGetObjectIntProperty && Host.TryGetObjectIntProperty(id, key, out int v) ? v : null;
/// <summary>Logout: the view and the per-login records go.</summary>
private void ResetActiveGear()
{
_gearView = ActiveGearView.Empty;
_gearWornSince.Clear();
_gearCheckQueue.Clear();
_gearCheckTotal = 0;
_gearWornAtMs = long.MinValue / 2;
_gearViewAtMs = long.MinValue / 2;
}
// ── /ra gear ─────────────────────────────────────────────────────────
/// <summary>
/// "/ra gear" opens the window and says the summary; "show" / "hide" open or close it; "check"
/// identifies the worn items again; "list" prints a line per item. Every form replies. Pump thread.
/// </summary>
private void HandleGearCommand(string[] parts)
{
string arg = parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2).Trim().ToLowerInvariant() : string.Empty;
if (!_loginComplete || _objectCache == null || _playerId == 0)
{
ReplyFail("[RynthAi] Active gear: not in the world yet. " + ActiveGearUsage);
return;
}
switch (arg)
{
case "":
case "show":
case "open":
{
PublishGearView(Environment.TickCount64);
ReplyOk("[RynthAi] Active gear: " + _gearView.Summary + GearWindowNote(RynthPanelOpen.Open));
return;
}
case "hide":
case "close":
{
if (!Host.HasSetPanelOpen) { ReplyFail("[RynthAi] Active gear: this RynthCore has no plugin windows (plugin API 89+). " + ActiveGearUsage); return; }
int open = Host.SetPanelOpen(ActiveGearTitle, RynthPanelOpen.Close);
if (open < 0) ReplyFail("[RynthAi] The Active Gear window isn't there yet (RynthCore adds it a few seconds after login).");
else ReplyOk("[RynthAi] Active Gear window closed.");
return;
}
case "check":
case "id":
{
if (!Host.HasRequestId) { ReplyFail("[RynthAi] Active gear: this RynthCore can't identify items. " + ActiveGearUsage); return; }
int n = StartGearCheck();
ReplyOk(n == 0
? "[RynthAi] Active gear: no worn items with spells to identify."
: $"[RynthAi] Active gear: identifying {n} worn {(n == 1 ? "item" : "items")}, one every {GearCheckSpacingMs / 1000.0:0.#} s.");
return;
}
case "list":
{
PublishGearView(Environment.TickCount64);
ActiveGearView view = _gearView;
ChatLine("[RynthAi] Active gear: " + view.Summary);
foreach (ActiveGearRow r in view.Rows) ChatLine("[RynthAi] " + ActiveGearText.ListLine(r));
return;
}
case "help":
case "?":
ChatLine("[RynthAi] /ra gear — which worn items have their magic on, their mana and how long it lasts (opens the Active Gear window)");
ChatLine("[RynthAi] /ra gear check | list | hide — identify the worn items again, a line per item in chat, close the window");
return;
default:
ReplyFail($"[RynthAi] Active gear: unknown option '{arg}'. {ActiveGearUsage}");
return;
}
}
/// <summary>" (window open)" after the summary, or why it can't open.</summary>
private string GearWindowNote(RynthPanelOpen mode)
{
if (!Host.HasSetPanelOpen) return " (/ra gear list for each item; the window needs RynthCore with plugin windows)";
int open = Host.SetPanelOpen(ActiveGearTitle, mode);
return open < 0 ? " (the window isn't there yet: RynthCore adds it a few seconds after login)"
: open == 1 ? " (Active Gear window open)" : " (Active Gear window closed)";
}
/// <summary>The dashboard's ⋯ > Active gear: the window open or closed. Any thread.</summary>
internal void ToggleActiveGearWindow()
{
if (Host.HasSetPanelOpen) Host.SetPanelOpen(ActiveGearTitle, RynthPanelOpen.Toggle);
}
// ── Window (render thread) ───────────────────────────────────────────
/// <summary>
/// RynthPluginRenderEmbed "window:activegear": the Active Gear window body, docked or popped out.
/// 1 drawn, 0 not ready, -2 failed (three draws in a row threw).
/// </summary>
internal int RenderActiveGear(bool popped, out Vector2 want)
{
want = default;
if (!_initialized || Host.ImGuiContext == IntPtr.Zero) return 0;
Volatile.Write(ref _gearDrawnMs, Environment.TickCount64);
IntPtr previous = ImGui.GetCurrentContext();
ImGui.SetCurrentContext(EmbedContext());
try
{
_gearWindow ??= new ActiveGearWindow(() => _gearCheckWanted = true);
want = _gearWindow.Draw(_gearView);
_gearFailures = 0;
return 1;
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.UI, ex, "RenderActiveGear");
return ++_gearFailures >= 3 ? -2 : 0;
}
finally
{
ImGui.SetCurrentContext(previous);
}
}
}

View file

@ -0,0 +1,71 @@
using System;
using System.Globalization;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
namespace RynthCore.Plugin.RynthAi;
// Auto-confirm crafting (a players' request, 2026-11-11): /ra autoconfirm [on|off|<percent>|status].
// The work is MiniRemote/Crafting/CraftAutoConfirm.cs (ticked by the Crafting tab); the main path is
// the Mini Remote's Crafting tab, "Auto-confirm crafting" and its percent.
public sealed partial class RynthAiPlugin
{
internal const string AutoConfirmUsage = "Usage: /ra autoconfirm [on | off | <percent 50-100> | status]";
/// <summary>/ra autoconfirm: status (the default), on, off, or a percent (sets it and turns it on).</summary>
private void HandleAutoConfirmCommand(string[] parts)
{
var settings = _dashboard?.Settings;
if (settings == null) { ReplyFail("[RynthAi] Auto-confirm crafting: not ready yet (log in first)."); return; }
bool supported = Host.HasConfirmationLeaveBelow;
string verb = parts.Length > 2 ? parts[2].Trim().TrimEnd('%').ToLowerInvariant() : "status";
switch (verb)
{
case "status":
ChatLine(AutoConfirmStatusLine(settings, supported));
break;
case "on":
if (!supported) { ReplyFail($"[RynthAi] Auto-confirm crafting {CraftAutoConfirm.NeedsEngineText}; it stays off."); break; }
settings.AutoConfirmCraft = true;
_dashboard?.SaveSettings();
ReplyOk($"[RynthAi] Auto-confirm crafting: on, Yes at {CraftAutoConfirm.ClampPercent(settings.AutoConfirmCraftPercent)}% or better (lower chances show AC's dialog).");
break;
case "off":
settings.AutoConfirmCraft = false;
_dashboard?.SaveSettings();
ReplyOk("[RynthAi] Auto-confirm crafting: off (AC asks you every time).");
break;
default:
if (!int.TryParse(verb, NumberStyles.Integer, CultureInfo.InvariantCulture, out int percent))
{
ReplyFail($"[RynthAi] Auto-confirm crafting: unknown option '{parts[2]}'. {AutoConfirmUsage}");
break;
}
if (percent < CraftAutoConfirm.MinThreshold || percent > CraftAutoConfirm.MaxThreshold)
{
ReplyFail($"[RynthAi] Auto-confirm crafting: the percent must be {CraftAutoConfirm.MinThreshold}-{CraftAutoConfirm.MaxThreshold} (got {percent}). {AutoConfirmUsage}");
break;
}
if (!supported) { ReplyFail($"[RynthAi] Auto-confirm crafting {CraftAutoConfirm.NeedsEngineText}; nothing changed."); break; }
settings.AutoConfirmCraftPercent = percent;
settings.AutoConfirmCraft = true;
_dashboard?.SaveSettings();
ReplyOk($"[RynthAi] Auto-confirm crafting: on, Yes at {percent}% or better (lower chances show AC's dialog).");
break;
}
}
private string AutoConfirmStatusLine(LegacyUiSettings settings, bool supported)
{
int percent = CraftAutoConfirm.ClampPercent(settings.AutoConfirmCraftPercent);
if (!supported)
return $"[RynthAi] Auto-confirm crafting: {(settings.AutoConfirmCraft ? "on" : "off")}, but it {CraftAutoConfirm.NeedsEngineText}.";
if (!settings.AutoConfirmCraft)
return $"[RynthAi] Auto-confirm crafting: off (the percent is {percent}%). /ra autoconfirm on, or the Mini Remote's Crafting tab.";
var ac = _miniRemote?.Crafting.AutoConfirm;
string detail = ac == null ? "starts once you are in the world"
: (ac.Armed ? "armed" : ac.Status) + $"; {ac.AcceptedCount} confirmed this session";
return $"[RynthAi] Auto-confirm crafting: on, Yes at {percent}% or better ({detail}).";
}
}

View file

@ -0,0 +1,170 @@
// RynthAiPlugin.BuffItems.cs - /ra buffitems and the Spells window's Buff Items tab (pump side).
// The tab draws on the render thread (LegacySpellsUi); its two Add buttons come here through the
// remote command queue, and the open tab gets a fresh copy of the list every 2 s.
using System;
using System.Collections.Generic;
using System.Text;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
internal const string BuffItemsUsage =
"/ra buffitems [list] | on | off | open | allow <name> | block <name> | add <name> | addselected | remove <name> | repeat <minutes> <name>";
private long _buffItemRowsPushedAt;
/// <summary>/ra buffitems ... (also the Buff Items tab's Add buttons, through the remote command queue). Always answers.</summary>
private void HandleBuffItemsCommand(string[] parts)
{
var s = _dashboard?.Settings;
if (s == null) { ReplyFail("[RynthAi] Buff items: settings not ready (log in first)."); return; }
string verb = parts.Length > 2 ? parts[2].ToLowerInvariant() : "list";
string rest = parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3).Trim() : string.Empty;
switch (verb)
{
case "list":
case "status":
ListBuffItems(s);
break;
case "on":
case "off":
s.UseBuffItems = verb == "on";
ReplyOk($"[RynthAi] Use Buff Items is {(s.UseBuffItems ? "on" : "off")}.");
break;
case "open":
case "panel":
case "window":
EnsureSpellsUi();
s.ShowSpellsWindow = true;
_spellsUi?.ShowBuffItemsTab();
PushBuffItemRows(force: true);
ReplyOk("[RynthAi] Spells window opened on Buff Items.");
break;
case "allow":
case "block":
{
if (rest.Length == 0) { ReplyFail($"[RynthAi] Buff items: which item? Usage: {BuffItemsUsage}"); break; }
bool allow = verb == "allow";
var r = s.SetBuffItemAllowed(rest, allow, out string shown);
if (r == BuffItemRules.EditResult.NotFound)
ReplyFail($"[RynthAi] Buff items: '{rest}' isn't in the list ({ListedNames(s)}). /ra buffitems add <name> adds one.");
else
ReplyOk($"[RynthAi] Buff items: {shown} is {(allow ? "allowed" : "blocked")}{(r == BuffItemRules.EditResult.Unchanged ? " (it already was)" : "")}."
+ (allow && !s.UseBuffItems ? " Use Buff Items is off, so nothing is used until it is on." : ""));
PushBuffItemRows(force: true);
break;
}
case "add":
{
if (rest.Length == 0) { ReplyFail($"[RynthAi] Buff items: no name given (or select the item and use addselected). Usage: {BuffItemsUsage}"); break; }
if (_buffManager == null) { ReplyFail("[RynthAi] Buff items: buffing isn't ready yet (log in first)."); break; }
bool ok = _buffManager.AddBuffItemByName(rest, out string reply);
SayBuffItems(ok, reply);
break;
}
case "addselected":
{
if (_buffManager == null) { ReplyFail("[RynthAi] Buff items: buffing isn't ready yet (log in first)."); break; }
bool ok = _buffManager.AddSelectedBuffItem(out string reply);
SayBuffItems(ok, reply);
break;
}
case "remove":
case "delete":
{
if (rest.Length == 0) { ReplyFail($"[RynthAi] Buff items: which item? Usage: {BuffItemsUsage}"); break; }
var r = s.RemoveCustomBuffItem(rest, out string shown);
if (r == BuffItemRules.EditResult.Removed)
ReplyOk($"[RynthAi] Buff items: removed {shown}.");
else if (r == BuffItemRules.EditResult.BuiltIn)
ReplyFail($"[RynthAi] Buff items: {shown} is built in and can't be removed; /ra buffitems block {shown} stops its use.");
else
ReplyFail($"[RynthAi] Buff items: '{rest}' isn't one of your items ({ListedNames(s)}).");
PushBuffItemRows(force: true);
break;
}
case "repeat":
{
int sp = rest.IndexOf(' ');
if (sp < 0 || !int.TryParse(rest.Substring(0, sp), out int minutes))
{
ReplyFail($"[RynthAi] Buff items: /ra buffitems repeat <minutes> <name> sets how often an item with no spell to check is used. Usage: {BuffItemsUsage}");
break;
}
var item = BuffItemRules.FindCustom(s.CustomBuffItems, rest.Substring(sp + 1));
if (item == null) { ReplyFail($"[RynthAi] Buff items: '{rest.Substring(sp + 1).Trim()}' isn't one of your items ({ListedNames(s)})."); break; }
int set = BuffItemRules.ClampRepeatMinutes(minutes);
item.RepeatMinutes = set;
ReplyOk($"[RynthAi] Buff items: {item.Name} is used every {set} min when it casts no spell RynthAi can check"
+ (set != minutes ? $" ({minutes} is outside {BuffItemRules.MinRepeatMinutes}-{BuffItemRules.MaxRepeatMinutes})" : "")
+ (item.SpellsRead && item.SpellIds.Count > 0 ? "; it does cast one, so its buff is what counts." : "."));
PushBuffItemRows(force: true);
break;
}
default:
ReplyFail($"[RynthAi] Buff items: unknown '{parts[2]}'. Usage: {BuffItemsUsage}");
break;
}
}
/// <summary>A reply for the player and, when the window is open, its status line.</summary>
private void SayBuffItems(bool ok, string reply)
{
if (ok) ReplyOk(reply); else ReplyFail(reply);
_spellsUi?.SetBuffItemsStatus(reply.StartsWith("[RynthAi] ", StringComparison.Ordinal) ? reply.Substring(10) : reply, !ok);
PushBuffItemRows(force: true);
}
private static string ListedNames(LegacyUiSettings s)
{
var names = new List<string>();
foreach (var e in BuffItemEntry.Build(s.BlockedBuffItems, s.CustomBuffItems)) names.Add(e.Name);
return string.Join(", ", names);
}
private void ListBuffItems(LegacyUiSettings s)
{
ChatLine($"[RynthAi] Use Buff Items: {(s.UseBuffItems ? "on" : "off")}. Buff items (one used at a time when its buff isn't on):");
List<BuffItemRow> rows = _buffManager?.DescribeBuffItems() ?? RowsWithoutBuffing(s);
foreach (var r in rows)
{
var sb = new StringBuilder(" ");
sb.Append(r.Allowed ? "[x] " : "[ ] ").Append(r.Name).Append(r.BuiltIn ? " (built in)" : "");
if (r.InPack > 0) sb.Append(", ").Append(r.InPack).Append(" in pack");
sb.Append(": ").Append(r.Status);
if (r.Spells.Length > 0) sb.Append(". Checks: ").Append(r.Spells);
ChatLine(sb.ToString());
}
ChatLine($"[RynthAi] {BuffItemsUsage}. The list is in the Spells window, Buff Items tab (/ra buffitems open).");
}
private static List<BuffItemRow> RowsWithoutBuffing(LegacyUiSettings s)
{
var rows = new List<BuffItemRow>();
foreach (var e in BuffItemEntry.Build(s.BlockedBuffItems, s.CustomBuffItems))
rows.Add(new BuffItemRow { Name = e.Name, BuiltIn = e.BuiltIn, Allowed = e.Allowed, Status = e.Allowed ? "allowed" : "blocked", UsesTimer = e.UsesTimer, RepeatMinutes = e.RepeatMinutes });
return rows;
}
/// <summary>Pump thread: the open Spells window's Buff Items tab gets the list every 2 s (at once after a change).</summary>
private void PushBuffItemRows(bool force = false)
{
var ui = _spellsUi;
if (ui == null || !ui.Visible || _buffManager == null) return;
long now = Environment.TickCount64;
if (!force && now - _buffItemRowsPushedAt < SpellsKnownPushMs) return;
_buffItemRowsPushedAt = now;
ui.SetBuffItemRows(_buffManager.DescribeBuffItems());
}
}

View file

@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
@ -103,6 +105,8 @@ public sealed partial class RynthAiPlugin
/// <summary>OnViewObjectContents for a non-corpse container: remember it as a chest to look at.</summary>
private void NoteContainerOpened(int id)
{
if (id != 0 && id == _chestReopenId)
ClearChestReopen(); // it is open again (the looter's use, a meta's or the player's)
if (id == 0 || unchecked((uint)id) == _playerId || IsChestLoot(id))
return;
_chestCandidateId = id;
@ -302,21 +306,178 @@ public sealed partial class RynthAiPlugin
/// <summary>OnStopViewingObjectContents / DeleteObject for a chest. True when it was the chest being looted.</summary>
private bool OnChestGone(int id, string how)
{
if (_chestCandidateId == id)
bool wasCandidate = _chestCandidateId == id;
if (wasCandidate)
_chestCandidateId = 0;
if (!IsChestLoot(id))
{
// Open and eligible, but closed before the looter took it (it was on a corpse, or in a fight).
if (wasCandidate && how == ChestClosedHow)
ConsiderChestReopen(id, taken: false);
return false;
}
bool active = _openedContainerId == id || _targetCorpseId == id;
if (!active)
{
_lootChestId = 0;
return true;
}
LootDiag($"[RynthAi] Chest loot: chest 0x{(uint)id:X8} {how} before looting finished; not reopening it (open it again to loot the rest).");
// Not a chest the player opened with the macro off: that one is the player's to close.
bool reopens = how == ChestClosedHow && id != _manualChestLootId && ConsiderChestReopen(id, taken: true);
if (!reopens)
LootDiag($"[RynthAi] Chest loot: chest 0x{(uint)id:X8} {how} before looting finished; not reopening it (open it again to loot the rest).");
FinishChestLoot(id, how, close: false, sayNothingMatched: false);
return true;
}
// ── A chest that closes before the looter is done is opened again (2026-11-12) ──────────────
// 8 of 134 chest loots in a week of logs ended "was closed before looting finished", with
// items still to take. What closes it is the client: while its loot window shows a container it
// checks once a second that the character stands within that container's use radius, and when
// it doesn't it hides the window, which uses the container - and a use of a container you are
// viewing closes it on the server (read from acclient.exe; RynthCore's LootWindowProbe logs
// each one). A jump-loot hop, the server's walk back for the next pickup, a step toward a
// monster or an open that needed a walk-up is enough. Opening a corpse closes an open chest
// too (the server shows one container at a time).
//
// A corpse the looter was on is opened again (OnStopViewingObjectContents); a chest was not,
// so the rest stayed in it until someone opened it again. Now the looter uses the chest again,
// at most ChestReopenMax times a minute per chest: a chest that keeps closing (locked again,
// a player closing it on purpose) is left after that. Only with the macro and Looting on, and
// never for a chest the player opened with the macro off.
/// <summary>OnChestGone's "how" for the server's close (the other is "left range": the object is gone).</summary>
internal const string ChestClosedHow = "was closed";
internal const int ChestReopenMax = 2;
internal const long ChestReopenWindowMs = 60_000;
/// <summary>After the close, before the use: the close settles (the client's window, the server's viewer).</summary>
internal const long ChestReopenDelayMs = 600;
/// <summary>The use is answered within this (a walk back included) or the chest is left.</summary>
internal const long ChestReopenAnswerMs = 5_000;
/// <summary>A reopen that got no turn in this long (a fight, the macro off) is dropped.</summary>
internal const long ChestReopenStaleMs = 30_000;
/// <summary>The chest to open again (0 = none).</summary>
private int _chestReopenId;
private long _chestReopenDueAt;
/// <summary>When the use went out (0 = not yet).</summary>
private long _chestReopenSentAt;
private readonly Dictionary<int, (long FirstAt, int Count)> _chestReopens = new();
private void ClearChestReopen()
{
_chestReopenId = 0;
_chestReopenDueAt = 0;
_chestReopenSentAt = 0;
}
/// <summary>
/// Chest <paramref name="id"/> was closed with loot work left: books a reopen and logs it. False
/// (nothing booked) with the macro or Looting off, for a container that isn't a chest to loot,
/// or once it has been reopened ChestReopenMax times in the last minute (logged).
/// <paramref name="taken"/>: the looter was on it; false: it was open but not taken yet.
/// </summary>
private bool ConsiderChestReopen(int id, bool taken)
{
var settings = _dashboard?.Settings;
if (settings == null || !settings.IsMacroRunning || !settings.EnableLooting)
return false;
if (_objectCache?[id] == null)
return false;
if (!taken && JudgeChest(id, out _) != ChestVerdict.Loot)
return false;
long now = CorpseNowMs;
int count = 0;
long firstAt = now;
if (_chestReopens.TryGetValue(id, out var seen) && now - seen.FirstAt < ChestReopenWindowMs)
{
count = seen.Count;
firstAt = seen.FirstAt;
}
string before = taken ? "before looting finished" : "before the looter got to it";
if (count >= ChestReopenMax)
{
LootDiag($"[RynthAi] Chest loot: chest 0x{(uint)id:X8} {ChestClosedHow} {before}, again: opened {count} times in the last minute already, so it is left (open it again to loot the rest).");
return false;
}
if (_chestReopens.Count > 32)
_chestReopens.Clear();
_chestReopens[id] = (firstAt, count + 1);
_chestReopenId = id;
_chestReopenDueAt = now + ChestReopenDelayMs;
_chestReopenSentAt = 0;
LootDiag($"[RynthAi] Chest loot: chest 0x{(uint)id:X8} {ChestClosedHow} {before}; opening it again ({count + 1} of {ChestReopenMax}).");
return true;
}
/// <summary>HasLootWork: a chest waits to be opened again (no state changed).</summary>
private bool HasChestReopenWork() =>
_chestReopenId != 0 && _targetCorpseId == 0 && _openedContainerId == 0;
/// <summary>
/// TickCorpseOpening, nothing claimed or open: uses the chest booked by ConsiderChestReopen once
/// its delay is over, then waits for it to open (OnViewObjectContents makes it the candidate and
/// TryTakeOpenChest takes it). True while this tick belongs to it, so no corpse is claimed and
/// opened meanwhile (that would close the chest again).
/// </summary>
private bool TryReopenChest(LegacyUiSettings settings, long now)
{
int id = _chestReopenId;
if (id == 0 || _targetCorpseId != 0 || _openedContainerId != 0)
return false;
if (_objectCache?[id] == null)
{
ClearChestReopen();
return false;
}
if (_chestReopenSentAt != 0)
{
if (now - _chestReopenSentAt < ChestReopenAnswerMs)
return true;
LootDiag($"[RynthAi] Chest loot: chest 0x{(uint)id:X8} didn't open again within {ChestReopenAnswerMs / 1000} s of the use; it is left (open it again to loot the rest).");
ClearChestReopen();
return false;
}
if (now - _chestReopenDueAt >= ChestReopenStaleMs)
{
LootDiag($"[RynthAi] Chest loot: the reopen of chest 0x{(uint)id:X8} got no turn in {ChestReopenStaleMs / 1000} s; dropped (open it again to loot the rest).");
ClearChestReopen();
return false;
}
if (now < _chestReopenDueAt || _activity != BotActivity.Looting)
return true;
if (IsLootingBlockedByPack(settings))
{
LootDiag($"[RynthAi] Chest loot: not reopening chest 0x{(uint)id:X8} - the pack is full (Stop Looting When Pack Full).");
ClearChestReopen();
return false;
}
double maxMeters = GetCorpseApproachRangeMaxMeters(settings);
double distance = _objectCache.Distance(unchecked((int)_playerId), id);
if (double.IsNaN(distance) || distance > Math.Max(maxMeters * 1.5, maxMeters + 2.0))
{
LootDiag($"[RynthAi] Chest loot: not reopening chest 0x{(uint)id:X8} - it is {distance:0.0} m away, past the loot range ({maxMeters:0.0} m).");
ClearChestReopen();
return false;
}
PauseNavigationForCorpse();
StopCorpseMovement();
bool sent = Host.UseFor(unchecked((uint)id), "Loot", "open the chest again: it closed before the looter was done");
if (!sent)
{
LootDiag($"[RynthAi] Chest loot: the use to reopen chest 0x{(uint)id:X8} wasn't taken; it is left (open it again to loot the rest).");
ClearChestReopen();
return false;
}
_chestReopenSentAt = now;
LootDiag($"[RynthAi] Chest loot: used chest 0x{(uint)id:X8} to open it again.");
return true;
}
// ── Pickup with macro off (2026-11-02) ─────────────────────────────────────────────────────
// A chest the player opens is looted by the loaded loot profile with the macro or Looting off
// (LootChestsMacroOff, on by default), the way /ra lootthis would. With both on the macro's

View file

@ -41,6 +41,10 @@ public sealed partial class RynthAiPlugin
private volatile bool _classicLook; // the engine's look is Classic (its file)
private long _classicAskedMs; // "Classic look" clicked: the window steps aside now
private volatile FightTarget? _dashFight; // tick writes, render reads
private volatile int _dashStance = CombatMode.Melee; // the Combat key's stance (tick writes, render reads)
private volatile NavTrail.Kind _dashNav; // the Navigation key's shape (tick writes, render reads)
private volatile bool _dashMetaLoaded; // the Meta key: a meta with rules is loaded (tick writes, render reads)
private volatile bool _dashSortMoving; // the auto-sort key: RynthSort is moving items (tick writes, render reads)
private int _dashFailures; // draws in a row that threw
/// <summary>The monster RynthAi is fighting, for the target bar: its name, health (0..1, -1 unknown) and vitals.</summary>
@ -104,13 +108,18 @@ public sealed partial class RynthAiPlugin
_nextDashVitalsMs = now + 100;
_dashboard?.RefreshDashboardVitals();
_dashFight = ReadFightTarget(_dashFight);
_dashStance = ReadStance(_dashStance);
_dashNav = ReadNavKind();
_dashMetaLoaded = ReadMetaLoaded();
}
if (now >= _nextDashSortMs)
{
// Twice a second for the dashboard's key; every 2 s otherwise, for Auto Cram (AutoSortOn).
_nextDashSortMs = now + (shown ? 500 : 2000);
_dashSort = ReadAutoSort();
_dashSort = ReadAutoSort(out bool sortMoving);
_dashSortMoving = sortMoving;
if (_dashboard?.Settings is { } sortSettings) sortSettings.AutoSortOn = _dashSort == 1;
if (shown) RefreshDashProfileState(); // the Loaded files drawer's unsaved mark (RynthAiPlugin.ProfileFiles.cs)
}
if (now >= _nextDashClassicMs)
{
@ -156,9 +165,58 @@ public sealed partial class RynthAiPlugin
return new FightTarget(uid, name, health, st, maxSt, mn, maxMn);
}
/// <summary>The readout with the target bar on the monster RynthAi is fighting, when it is fighting one. Render thread.</summary>
/// <summary>
/// The stance the Combat key draws: the client's combat mode when it is Melee, Missile or Magic;
/// in peace (or with no engine call) the last one, so a resting mage keeps the wands. Plugin tick.
/// </summary>
private int ReadStance(int last)
{
int mode = Host.HasGetCurrentCombatMode ? Host.GetCurrentCombatMode() : CombatMode.NonCombat;
return mode is CombatMode.Melee or CombatMode.Missile or CombatMode.Magic ? mode : last;
}
/// <summary>
/// What the Navigation key draws: the Outdoor Hunt while it runs, else a dungeon patrol's
/// route, else following (a fellow or a Follow route), else the loaded route's type; nothing
/// loaded is None. Plugin tick.
/// </summary>
private NavTrail.Kind ReadNavKind()
{
var settings = _dashboard?.Settings;
if (settings == null) return NavTrail.Kind.None;
if (HuntActive) return NavTrail.Kind.Hunt;
NavRouteParser? route = settings.CurrentRoute;
if (_dunPatrolActive && route != null && ReferenceEquals(route, _dunPatrolRoute)) return NavTrail.Kind.Patrol;
if (IsFollowActive(settings)) return NavTrail.Kind.Follow;
if (route == null || route.Points.Count == 0) return NavTrail.Kind.None;
return route.RouteType switch
{
NavRouteType.Circular => NavTrail.Kind.Circular,
NavRouteType.Linear => NavTrail.Kind.Linear,
NavRouteType.Once => NavTrail.Kind.Once,
NavRouteType.Follow => NavTrail.Kind.Follow,
_ => NavTrail.Kind.None,
};
}
/// <summary>
/// A meta with rules is loaded (the Meta key draws its states hollow otherwise). Read on the
/// tick, under the rules' lock, so the render thread never takes it. Plugin tick.
/// </summary>
private bool ReadMetaLoaded()
{
var settings = _dashboard?.Settings;
if (settings == null) return false;
lock (settings.MetaRulesLock) return settings.MetaRules is { Count: > 0 };
}
/// <summary>
/// The readout with the Combat key's stance, the Navigation key's shape and whether a meta is
/// loaded, and the target bar on the monster RynthAi is fighting when it is fighting one. Render thread.
/// </summary>
internal DashboardReadout WithFightTarget(DashboardReadout r)
{
r = r with { CombatStance = _dashStance, NavKind = _dashNav, MetaLoaded = _dashMetaLoaded };
FightTarget? f = _dashFight;
if (f == null) return r;
return r with
@ -178,16 +236,22 @@ public sealed partial class RynthAiPlugin
/// <summary>RynthSort's auto-sort for the dashboard's key: -1 not loaded / not logged in / too old, 0 off, 1 on.</summary>
internal int DashAutoSort => _dashSort;
/// <summary>RynthSort is moving items right now (the auto-sort key's sorting look); false when it can't say.</summary>
internal bool DashSortMoving => _dashSortMoving;
/// <summary>
/// RynthSort's auto-sort state, through the engine's JSON broker (RynthSort's
/// RynthPluginGetAutoSortJson, {"auto":-1|0|1}); -1 when RynthSort isn't loaded or predates
/// the export. Plugin tick.
/// RynthPluginGetAutoSortJson, {"auto":-1|0|1,"moving":0|1}); -1 when RynthSort isn't loaded or
/// predates the export. <paramref name="moving"/>: it is moving items (false from a RynthSort
/// older than the flag). Plugin tick.
/// </summary>
private int ReadAutoSort()
private int ReadAutoSort(out bool moving)
{
moving = false;
if (!Host.HasGetPluginExportJson) return -1;
string? json = Host.GetPluginExportJson("RynthSort", "RynthPluginGetAutoSortJson");
if (json == null) return -1;
moving = json.Contains("\"moving\":1", StringComparison.Ordinal);
return json.Contains("\"auto\":1", StringComparison.Ordinal) ? 1
: json.Contains("\"auto\":0", StringComparison.Ordinal) ? 0 : -1;
}
@ -255,6 +319,7 @@ internal sealed class DashboardBridge : IDashboardHost
public void SelectProfile(int kind, int index) => Queue(() => _p.DashboardRenderer?.SelectProfileAtIndex(kind, index));
public void SetLootMode(int mode) => Queue(() => _p.SetLootModeFromPanel(mode));
public int AutoSort => _p.DashAutoSort;
public bool AutoSortMoving => _p.DashSortMoving;
public bool FightSelectedTarget => _p.DashboardRenderer?.Settings.FightSelectedTarget == true;
public void SetAutoSort(bool on) => Queue(() => _p.SetDashAutoSort(on));
public void ToggleSortWindow() => Queue(() => _p.SendSortCommand(string.Empty));
@ -262,7 +327,30 @@ internal sealed class DashboardBridge : IDashboardHost
public void ToggleHunt() => Queue(_p.ToggleHunt);
public bool HuntActive => _p.HuntActive;
public void ToggleHuntPanel() => _p.ToggleHuntPanel();
public void ToggleDfHeightPanel() => _p.ToggleDfHeightPanel();
public bool DfHeightRotation => _p.DfHeightRotationOn;
public void ToggleSpells() => _p.EnqueueRemoteCommand("spells", "toggle");
public void ToggleActiveGear() => Queue(_p.ToggleActiveGearWindow);
public void ToggleTimedCommands() => Queue(_p.ToggleTimedCommandsWindow);
public void UseClassicLook() => _p.UseClassicLook();
public ProfileFileInfo ProfileInfo(int kind)
{
var k = (ProfileKind)kind;
ProfileFileInfo info = Renderer.ProfileInfo(k);
if (k == ProfileKind.Loot && _p.DashLootEditorDirty) info = info with { Unsaved = true };
else if (k == ProfileKind.Buffs && _p.DashSpellsDirty) info = info with { Unsaved = true };
return info;
}
public void ProfileAction(int kind, ProfileVerb verb, string name, bool replace, Action<ProfileResult> done) => Queue(() =>
{
ProfileResult r;
try { r = _p.RunProfileAction((ProfileKind)kind, verb, name, replace); }
catch (Exception ex) { r = ProfileResult.Failed($"{verb} failed: {ex.Message}"); }
// A Save As that would replace another file waits for the drawer's yes: nothing in chat yet.
if (!r.NeedsReplace) _p.DashHost.WriteToChat(r.Text, r.Ok ? CommandReply.OkColor : CommandReply.FailColor);
done(r);
});
public bool DrawMiniRemote(out Vector2 want) => _p.DrawDashMiniRemote(out want);
}

View file

@ -37,6 +37,8 @@ public sealed partial class RynthAiPlugin
private void PostDataWriteProblems()
{
// A meta file that lost data (CallState rules with no target): its load warning.
_dashboard?.DrainMetaNotices(line => Host.WriteToChat(line, CommandReply.FailColor));
if (DataWriteGuard.PendingCount == 0) return;
DataWriteGuard.DrainChat(line => Host.WriteToChat(line, 2));
}

View file

@ -0,0 +1,142 @@
// RynthAiPlugin.DirtyFighting.cs — the Dirty Fighting rotation's window and /ra dfheight (2026-11-11).
//
// The rotation itself is CombatManager.DirtyFighting.cs (which height each attack aims at) and
// Combat/DirtyFightingHeights.cs (the pure choice). Here: the small "Dirty Fighting" window, opened
// from the dashboard's options menu (the ⋯ button, or right-click the header) or /ra dfheight window,
// with the on/off checkbox, the order, the height once all three effects are on, and what is on the
// current target; and the command. Render thread for the window: its controls write the settings
// straight into the live settings (as the Outdoor Hunt window does; the autosave picks them up).
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using Ui = RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
internal const string DfHeightUsage = "Usage: /ra dfheight [on|off|status|window]";
private volatile bool _dfPanelOpen;
private string _dfPanelStatus = string.Empty; // render thread
private long _dfPanelStatusAtMs;
public void ToggleDfHeightPanel() => _dfPanelOpen = !_dfPanelOpen;
internal bool DfHeightRotationOn => _dashboard?.Settings.DfHeightRotation == true;
// ── /ra dfheight ─────────────────────────────────────────────────────
private void HandleDfHeightCommand(string[] parts)
{
var s = _dashboard?.Settings;
if (s == null) { ReplyFail("[RynthAi] Settings not ready."); return; }
string verb = parts.Length > 2 ? parts[2].ToLowerInvariant() : "status";
switch (verb)
{
case "on":
case "off":
s.DfHeightRotation = verb == "on";
_dashboard!.SaveSettings();
ReplyOk($"[RynthAi] Dirty Fighting rotation {verb}. {DfHeightStatusLine()}");
break;
case "status":
ChatLine($"[RynthAi] Dirty Fighting rotation: {DfHeightStatusLine()}");
break;
case "window":
case "show":
_dfPanelOpen = true;
ReplyOk("[RynthAi] Dirty Fighting window open.");
break;
default:
ReplyFail($"[RynthAi] dfheight: '{parts[2]}' isn't a choice. {DfHeightUsage}");
break;
}
}
private string DfHeightStatusLine()
{
if (_combatManager != null) return _combatManager.DirtyFightingStatus();
var s = _dashboard?.Settings;
return s == null ? "settings not ready." : (s.DfHeightRotation ? "On" : "Off") + " (not logged in yet).";
}
// ── The window (render thread) ───────────────────────────────────────
private static readonly string[] DfOrderLabels = Array.ConvertAll(DirtyFightingHeights.OrderChoices, DirtyFightingHeights.OrderLabel);
private static readonly string[] DfDefaultLabels = { "Attack Height setting", "Low", "Medium", "High" };
private void RenderDfHeightPanel()
{
if (!_dfPanelOpen) return;
var s = _dashboard?.Settings;
if (s == null) return;
float k = Math.Max(0.5f, Ui.Font(RynthUiFont.Ui14).FontSize / 14f);
ImGui.SetNextWindowSize(new Vector2(420 * k, 330 * k), ImGuiCond.FirstUseEver);
ImGui.SetNextWindowSizeConstraints(new Vector2(300 * k, 200 * k), new Vector2(1400 * k, 1000 * k));
ImGui.PushStyleColor(ImGuiCol.WindowBg, Ui.WithAlpha(Ui.Background, 0xF2));
ImGui.PushStyleColor(ImGuiCol.TitleBg, Ui.Color(RynthUiColor.TitleBar));
ImGui.PushStyleColor(ImGuiCol.TitleBgActive, Ui.Color(RynthUiColor.TitleBar));
ImGui.PushStyleColor(ImGuiCol.Border, Ui.Accent);
ImGui.PushStyleColor(ImGuiCol.Text, Ui.Text);
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(12 * k, 10 * k));
bool open = true;
bool visible = ImGui.Begin("Dirty Fighting##rynthdfheight", ref open, ImGuiWindowFlags.NoCollapse);
ImGui.PopStyleVar();
ImGui.PopStyleColor(5);
if (!open) _dfPanelOpen = false;
if (!visible) { ImGui.End(); return; }
try
{
using (Ui.PushFont(RynthUiFont.Ui14))
DfHeightPanelBody(s, k);
}
finally { ImGui.End(); }
}
private void DfHeightPanelBody(LegacyUiSettings s, float k)
{
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(8 * k, 5 * k));
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(8 * k, 6 * k));
try
{
ImGui.Checkbox("Dirty Fighting rotation##dfrot", ref s.DfHeightRotation);
Wrapped("Melee and missile attacks aim at the height of the next Dirty Fighting effect the target "
+ "doesn't have: High lowers its attack skills and the heals it gets, Medium makes it bleed, "
+ "Low lowers its defense skills. Needs Dirty Fighting trained; off, or untrained, the Melee and "
+ "Missile Attack Height settings apply.", Ui.Text);
ImGui.Separator();
if (!s.DfHeightRotation) ImGui.BeginDisabled();
float fieldW = Math.Max(120 * k, ImGui.GetContentRegionAvail().X * 0.55f);
int orderIdx = Array.IndexOf(DirtyFightingHeights.OrderChoices, DirtyFightingHeights.NormalizeOrder(s.DfHeightOrder));
if (orderIdx < 0) orderIdx = 0;
ImGui.SetNextItemWidth(fieldW);
if (ImGui.Combo("Order##dforder", ref orderIdx, DfOrderLabels, DfOrderLabels.Length))
s.DfHeightOrder = DirtyFightingHeights.OrderChoices[orderIdx];
int defIdx = Math.Clamp(s.DfDefaultHeight, -1, 2) + 1;
ImGui.SetNextItemWidth(fieldW);
if (ImGui.Combo("Then attack##dfdefault", ref defIdx, DfDefaultLabels, DfDefaultLabels.Length))
s.DfDefaultHeight = defIdx - 1;
if (!s.DfHeightRotation) ImGui.EndDisabled();
Wrapped("Once all three are on, attacks use the Then attack height (Attack Height setting: the Melee "
+ "or Missile Attack Height), and go back to an effect about 5 seconds before it runs out. "
+ "Each effect lands on up to 1 hit in 4 and lasts 20 seconds; RynthAi sees it land from the "
+ "\"Dirty Fighting! ...\" combat line.", Ui.Mute);
ImGui.Separator();
// The status reads skills from the host: refreshed twice a second, not every frame.
long now = Environment.TickCount64;
if (now - _dfPanelStatusAtMs > 500 || _dfPanelStatus.Length == 0)
{
_dfPanelStatusAtMs = now;
try { _dfPanelStatus = DfHeightStatusLine(); } catch { _dfPanelStatus = string.Empty; }
}
using (Ui.PushFont(RynthUiFont.UiBold14)) ImGui.TextUnformatted("Now");
if (_dfPanelStatus.Length > 0) Wrapped(_dfPanelStatus, Ui.Text);
}
finally { ImGui.PopStyleVar(2); }
}
}

View file

@ -183,7 +183,7 @@ public sealed partial class RynthAiPlugin
{
if (_dashboard == null || _itemInfoUi != null) return;
_itemInfoUi = new LegacyItemInfoUi(_dashboard.Settings);
_itemInfoUi.SetHooks(DescribeSelectedItemForPreview, PrintSelectedItemInfo, TestItemInfoChatType);
_itemInfoUi.SetHooks(DescribeSelectedItemForPreview, PrintSelectedItemInfo, TestItemInfoChatType, TestItemInfoPartColors);
}
/// <summary>Pump-thread work for the ported features. Safe before login (each call is null-checked).</summary>
@ -195,6 +195,8 @@ public sealed partial class RynthAiPlugin
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats tick"); }
try { TickMonsterStats(); } // after the session's tick: follows its start (RynthAiPlugin.MonsterStats.cs)
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats tick"); }
try { TickActiveGear(); } // RynthAiPlugin.ActiveGear.cs
catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "active gear tick"); }
try { _serverHub?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "server plugin hub lookup"); }
try { _miniRemote?.Tick(); }
@ -229,6 +231,7 @@ public sealed partial class RynthAiPlugin
Huds.ServerCommandModel.Clear();
_itemInfoUi = null;
_spellsUi = null;
ResetActiveGear();
ResetGroundLoot(clearCaches: true);
Loot.T11ItemSupport.Reset();
if (!disposeTranslator) return;
@ -280,6 +283,7 @@ public sealed partial class RynthAiPlugin
RenderTranslateWindow();
RenderLootWhyWindow();
RenderHuntPanel();
RenderDfHeightPanel();
}
catch (Exception ex)
{
@ -329,6 +333,7 @@ public sealed partial class RynthAiPlugin
_spellsUi?.Render();
RenderLootWhyWindow();
RenderHuntPanel();
RenderDfHeightPanel();
}
catch (Exception ex)
{
@ -488,7 +493,8 @@ public sealed partial class RynthAiPlugin
{
if (!_initialized || !_loginComplete) return null;
return Huds.SectionsManifest.Build(Huds.SectionsManifest.Views(), Huds.SectionsManifest.OwnSections,
dashboard: DashboardWindowWanted, monsterStats: MonsterStatsWindowWanted);
dashboard: DashboardWindowWanted, monsterStats: MonsterStatsWindowWanted, timedCommands: TimedCommandsWindowWanted,
activeGear: ActiveGearWindowWanted);
}
/// <summary>Chat Translate window in the dashboard colours (no-op while hidden).</summary>
private void RenderTranslateWindow()

View file

@ -87,6 +87,7 @@ public sealed partial class RynthAiPlugin
}
_metaManager.RestoreRuntime(s);
_patrolOnLoginPending = false; // the meta's own route (or patrol) carries on instead
_huntOnLoginPending = false; // and no Hunt On Login either
Log($"RynthAi: hot reload - the meta carries on in state '{s.State}' (macro {(s.MacroRunning ? "on" : "off")}, " +
$"{s.Variables.Count} variable(s), {s.FiredRules.Count} rule(s) already fired, call depth {s.CallStack.Count}, " +
$"route {(s.RouteLines.Count > 0 ? $"at [{s.NavIndex}]" : "none")}).");

View file

@ -27,6 +27,7 @@ public sealed partial class RynthAiPlugin
private BuildingMap? _huntBuildings;
private long _huntPortalsAt;
private string _huntNoteLogged = "";
private bool _huntOnLoginPending; // Hunt On Login: read at login, run once by TickLoginAutoStart
private const int HuntMaxCorners = 128;
private const int HuntPathFlags = RynthNavPathApiV1.PathAvoidPortals | RynthNavPathApiV1.PathWallClearance
| RynthNavPathApiV1.PathAllowPartial | RynthNavPathApiV1.PathQuiet;
@ -58,6 +59,9 @@ public sealed partial class RynthAiPlugin
case "pick":
SetHuntPick(parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3) : "");
break;
case "login":
SetHuntOnLogin(parts.Length > 3 ? parts[3] : "");
break;
case "panel":
case "settings":
ToggleHuntPanel();
@ -66,7 +70,7 @@ public sealed partial class RynthAiPlugin
if (_hunt.Active) StopHunt("stopped", say: true); else StartHunt();
break;
default:
ChatLine("[RynthAi] /ra hunt [start|stop|status|panel] | /ra hunt range <yd> | /ra hunt radius <yd, 0 = anywhere> | " + HuntPickUsage);
ChatLine("[RynthAi] /ra hunt [start|stop|status|panel] | /ra hunt range <yd> | /ra hunt radius <yd, 0 = anywhere> | " + HuntPickUsage + " | " + HuntLoginUsage);
break;
}
}
@ -188,6 +192,7 @@ public sealed partial class RynthAiPlugin
Wrapped(status, !on ? Ui.Mute : _hunt.TargetId != 0 || _hunt.WalkingOut ? Ui.Green : Ui.Highlight);
string note = _hunt.Note;
if (on && note.Length > 0) Wrapped(note, Ui.Text);
HuntOnLoginCheckbox(s);
ImGui.Separator();
float range = s.OutdoorHuntRange;
@ -252,21 +257,27 @@ public sealed partial class RynthAiPlugin
else StartHunt();
}
internal void StartHunt()
internal const string HuntOnLoginRefusedPrefix = "[RynthAi] Hunt On Login: the hunt didn't start. ";
/// <summary>The Hunt button, /ra hunt and Hunt On Login (<paramref name="onLogin"/>: its lines say so).</summary>
internal void StartHunt(bool onLogin = false)
{
var s = _dashboard?.Settings;
if (s == null) { ChatLine("[RynthAi] Settings not ready."); return; }
if (!TryHuntPosition(out uint cell, out var me)) { ChatLine("[RynthAi] Outdoor hunt: no position yet."); return; }
if (InDungeon(cell)) { ChatLine("[RynthAi] Outdoor hunt is for outdoors; in a dungeon the Dungeon Patrol hunts (Patrol)."); return; }
uint cell = 0;
OutdoorHunt.Vec me = default;
bool hasPosition = s != null && TryHuntPosition(out cell, out me);
uint at = cell;
var from = me;
// In a building: it can start when it knows the building's doors (and RynthNav plans from a doorstep).
if (OutdoorHunt.IsIndoorCell(cell) && !HuntKnowsBuilding(cell))
var block = OutdoorHunt.WhyNoStart(s != null, hasPosition,
inDungeon: () => InDungeon(at),
unknownBuilding: () => OutdoorHunt.IsIndoorCell(at) && !HuntKnowsBuilding(at),
noRynthNav: () => HuntPath(from, from).Status == OutdoorHunt.PathStatus.Unavailable);
if (block != OutdoorHunt.StartBlock.None || s == null)
{
ChatLine("[RynthAi] Outdoor hunt: start it outdoors (it doesn't know this building's doors; it finds its own way out of a building it went into).");
return;
}
if (HuntPath(me, me).Status == OutdoorHunt.PathStatus.Unavailable)
{
ChatLine("[RynthAi] Outdoor hunt needs RynthNav 2026.10.23 or newer (its map shows the way round obstacles).");
string why = OutdoorHunt.StartBlockText(block);
if (onLogin) Host.Log("[RynthAi] Hunt On Login: not started (" + block + ").");
ChatLine((onLogin ? HuntOnLoginRefusedPrefix : "[RynthAi] ") + why);
return;
}
if (!s.IsMacroRunning && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge)
@ -284,7 +295,74 @@ public sealed partial class RynthAiPlugin
s.IsMacroRunning = true;
_macroWasRunning = true; // no macro-start "nearest waypoint" pick: the hunt plans its own walks
}
ChatLine("[RynthAi] Outdoor hunt on: " + HuntSettingsText(s) + " /ra hunt range <yd> to change.");
ChatLine((onLogin ? "[RynthAi] Hunt On Login: outdoor hunt on: " : "[RynthAi] Outdoor hunt on: ")
+ HuntSettingsText(s) + " /ra hunt range <yd> to change.");
}
/// <summary>
/// "/ra hunt login [on|off]": Hunt On Login, the box in the Outdoor Hunt window. No word: says it now.
/// On clears Patrol On Login (one or the other) and says so.
/// </summary>
private void SetHuntOnLogin(string value)
{
var s = _dashboard?.Settings;
if (s == null) { ReplyFail("[RynthAi] Settings not ready."); return; }
string v = value.Trim().ToLowerInvariant();
bool? on = v switch
{
"on" or "true" or "1" or "yes" => true,
"off" or "false" or "0" or "no" => false,
_ => null,
};
if (v.Length == 0)
{
ReplyOk($"[RynthAi] Hunt On Login: {(s.HuntOnLogin ? "on" : "off")}. {HuntLoginUsage} to change it.");
return;
}
if (on is not bool want)
{
ReplyFail($"[RynthAi] Hunt On Login: '{value.Trim()}' isn't on or off (it is {(s.HuntOnLogin ? "on" : "off")} now). Usage: {HuntLoginUsage}");
return;
}
bool patrolWas = s.PatrolOnLogin;
(s.PatrolOnLogin, s.HuntOnLogin) = LoginAutoStart.Exclusive(s.PatrolOnLogin, s.HuntOnLogin, s.PatrolOnLogin, want);
ReplyOk($"[RynthAi] Hunt On Login set: {(s.HuntOnLogin ? "on, the Outdoor Hunt starts once you're in the world" : "off")}."
+ (patrolWas && !s.PatrolOnLogin ? " Patrol On Login is off now (one or the other)." : ""));
}
internal const string HuntLoginUsage = "/ra hunt login [on|off]";
/// <summary>The Hunt On Login box (the Outdoor Hunt window; render thread, as its sliders). On clears Patrol On Login.</summary>
private static void HuntOnLoginCheckbox(LegacyUiSettings s)
{
bool on = s.HuntOnLogin;
if (ImGui.Checkbox("Hunt On Login##huntonlogin", ref on))
(s.PatrolOnLogin, s.HuntOnLogin) = LoginAutoStart.Exclusive(s.PatrolOnLogin, s.HuntOnLogin, s.PatrolOnLogin, on);
if (ImGui.IsItemHovered()) ImGui.SetTooltip(LoginAutoStart.HuntOnLoginTip);
}
/// <summary>
/// Patrol On Login / Hunt On Login, once the character is in the world and the dats are open (the same
/// gate Patrol On Login always had): the Dungeon Patrol, the Outdoor Hunt, or (both on) the one that
/// fits where the character is. The flags are read at login and cleared here, so it runs once.
/// </summary>
private void TickLoginAutoStart()
{
if (!_patrolOnLoginPending && !_huntOnLoginPending) return;
if (_raycast?.GeometryLoader?.CellDat?.IsLoaded != true) return;
bool patrol = _patrolOnLoginPending, hunt = _huntOnLoginPending;
_patrolOnLoginPending = false;
_huntOnLoginPending = false;
bool inDungeon = patrol && hunt && TryHuntPosition(out uint cell, out _) && InDungeon(cell);
switch (LoginAutoStart.Choose(patrol, hunt, inDungeon))
{
case LoginAutoStart.Start.Patrol:
HandleDungeonNavPatrol();
break;
case LoginAutoStart.Start.Hunt:
if (!_hunt.Active) StartHunt(onLogin: true);
break;
}
}
private void StopHunt(string why, bool say = false)

View file

@ -0,0 +1,154 @@
// RynthAiPlugin.ProfileFiles.cs - the Loaded files drawer's profile buttons and their /ra verbs
// (2026-11-11).
//
// "I can't find a way to save profiles": saving, copying and making profiles was chat commands
// (/vt nav save, /ra settings savechar ...) and a new loot profile needed the external editor. The
// dashboard's Loaded files drawer now has a "..." key on each row (PROFILE, NAV, LOOT, META, BUFFS)
// that opens that row's file buttons: Save, Save As (a name, and a yes before replacing another
// file), New, Rename, Move to Deleted and Open folder; LOOT opens the Loot Editor (New opens it on a
// new, empty profile that its Save creates) and BUFFS the Spells window, where buff profiles are
// made. Each button runs RunProfileAction on the tick, as the matching /ra verb does
// (/ra nav|meta|settings|loot ...), so both say the same thing in chat.
//
// The file work is LegacyDashboardRenderer.ProfileFiles.cs and LegacyUi/ProfileFileOps.cs; the
// loads and saves are the ones the pickers and the older commands use. Formats and folders are
// unchanged; nothing is deleted (a profile removed from a list goes to the Deleted folder beside it).
using System;
using System.IO;
using System.Threading;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
/// <summary>The Loot Editor has unsaved edits in the loot profile in use (tick writes, render reads).</summary>
private volatile bool _dashLootEditorDirty;
internal bool DashLootEditorDirty => _dashLootEditorDirty;
/// <summary>The Spells window has unsaved edits (render thread, where it draws).</summary>
internal bool DashSpellsDirty => _spellsUi?.Dirty == true;
/// <summary>Plugin tick, twice a second while the dashboard shows.</summary>
private void RefreshDashProfileState()
{
string loot = _dashboard?.Settings?.CurrentLootPath ?? string.Empty;
_dashLootEditorDirty = _lootEditor != null && loot.Length > 0 && _lootEditor.IsDirtyFor(loot);
}
/// <summary>
/// One profile button or verb (plugin tick): <paramref name="name"/> is the name typed for
/// Save As, New and Rename; <paramref name="replace"/> is the button's yes to replacing another
/// file with Save As. The result is the chat line.
/// </summary>
internal ProfileResult RunProfileAction(ProfileKind kind, ProfileVerb verb, string? name, bool replace = false)
{
var dash = _dashboard;
if (dash == null || !dash.ProfileLoaded)
return ProfileResult.Failed("Settings not ready (log in first).");
if (kind == ProfileKind.Loot && verb is ProfileVerb.SaveAs or ProfileVerb.Rename or ProfileVerb.Delete)
{
string inUse = dash.ProfilePath(ProfileKind.Loot);
if (_lootEditor != null && inUse.Length > 0 && _lootEditor.IsDirtyFor(inUse))
return ProfileResult.Failed($"The Loot Editor has unsaved changes in {Path.GetFileName(inUse)}. Save or discard them there first.");
}
switch (verb)
{
case ProfileVerb.Save:
return dash.SaveProfileNow(kind);
case ProfileVerb.SaveAs:
return dash.SaveProfileAs(kind, name, replace);
case ProfileVerb.New:
return kind == ProfileKind.Loot ? NewLootProfile(dash, name) : dash.NewProfile(kind, name);
case ProfileVerb.Rename:
{
string before = dash.ProfilePath(kind);
ProfileResult r = dash.RenameProfile(kind, name);
if (r.Ok && kind == ProfileKind.Loot) ForgetLootProfile(before);
return r;
}
case ProfileVerb.Delete:
{
string before = dash.ProfilePath(kind);
ProfileResult r = dash.DeleteProfile(kind);
if (r.Ok && kind == ProfileKind.Loot) ForgetLootProfile(before);
return r;
}
case ProfileVerb.Folder:
return dash.OpenProfileFolder(kind);
default:
return OpenProfileEditor(kind);
}
}
/// <summary>
/// New loot profile: the Loot Editor opened on LootProfiles\&lt;name&gt;.utl, empty; its Save
/// writes the file (nothing is written before). RynthAi keeps looting with the profile it has
/// until the new one is picked under LOOT.
/// </summary>
private ProfileResult NewLootProfile(LegacyDashboardRenderer dash, string? name)
{
string? why = dash.NewLootProfilePath(name, out string path);
if (why != null) return ProfileResult.Failed(why);
if (!Host.HasSetPanelOpen)
return ProfileResult.Failed("This RynthCore can't open the Loot Editor from here; open it from the LOOT row's chest button.");
if (!LootEditor.OpenFile(path, out string message))
return ProfileResult.Failed($"Loot Editor: {message}");
Host.SetPanelOpen("Loot Editor", RynthPanelOpen.Open);
return ProfileResult.Done($"New loot profile {Path.GetFileName(path)} is open in the Loot Editor: add rules, then Save there to create it. Pick it under LOOT to loot with it.");
}
/// <summary>/ra loot edit: the Loot Editor on the loot profile in use.</summary>
private ProfileResult OpenProfileEditor(ProfileKind kind)
{
if (kind != ProfileKind.Loot) return ProfileResult.Failed($"The {LegacyDashboardRenderer.KindWord(kind)} is edited in its own window.");
if (!Host.HasSetPanelOpen) return ProfileResult.Failed("This RynthCore can't open the Loot Editor from here.");
string inUse = _dashboard?.ProfilePath(ProfileKind.Loot) ?? string.Empty;
if (inUse.Length > 0) LootEditor.OpenFile(inUse, out _);
Host.SetPanelOpen("Loot Editor", RynthPanelOpen.Open);
return ProfileResult.Done(inUse.Length > 0
? $"Loot Editor opened on {Path.GetFileName(inUse)}."
: "Loot Editor opened. No loot profile is in use: New makes one, or pick one under LOOT.");
}
/// <summary>A profile verb's reply: what it did, or why not plus <paramref name="usage"/>.</summary>
private void ReplyProfile(ProfileResult r, string usage)
{
if (r.Ok) ReplyOk(r.Text);
else ReplyFail(r.NeedsReplace
? r.Text.Replace(" Replace it?", " Not saved: commands never replace a file; pick another name (the Save As button asks first).", StringComparison.Ordinal)
: r.Text + " Usage: " + usage);
}
/// <summary>
/// The profile verbs shared by /ra nav, /ra meta, /ra settings and /ra loot: saveas, rename,
/// delete (to Deleted), folder, and save / new where the kind has them. False when
/// <paramref name="sub"/> isn't one of them.
/// </summary>
private bool TryProfileVerb(ProfileKind kind, string sub, string rest, string usage)
{
ProfileVerb verb;
switch (sub)
{
case "saveas": verb = ProfileVerb.SaveAs; break;
case "rename": verb = ProfileVerb.Rename; break;
case "delete": verb = ProfileVerb.Delete; break;
case "folder": verb = ProfileVerb.Folder; break;
case "save" when kind is ProfileKind.Meta or ProfileKind.Settings: verb = ProfileVerb.Save; break;
case "new" when kind is ProfileKind.Nav or ProfileKind.Loot: verb = ProfileVerb.New; break;
case "edit" when kind == ProfileKind.Loot: verb = ProfileVerb.Edit; break;
default: return false;
}
if ((verb is ProfileVerb.SaveAs or ProfileVerb.Rename or ProfileVerb.New) && rest.Trim().Length == 0)
{
ReplyFail($"[RynthAi] {sub} needs a name. Usage: {usage}");
return true;
}
ReplyProfile(RunProfileAction(kind, verb, rest, replace: false), usage);
return true;
}
}

View file

@ -27,6 +27,8 @@ public sealed partial class RynthAiPlugin
_spellsUi.SetHooks(
path => Interlocked.Exchange(ref _pendingBuffProfilePath, path ?? string.Empty),
() => _dashboard?.RefreshBuffProfileFiles());
// The Buff Items tab's Add buttons: /ra buffitems add|addselected on the plugin tick.
_spellsUi.SetBuffItemsCommand(args => EnqueueRemoteCommand("buffitems", args));
}
/// <summary>Pump thread: applies the window's profile choice and feeds the open window.</summary>
@ -50,6 +52,7 @@ public sealed partial class RynthAiPlugin
_spellsKnownPushedAt = now;
ui.SetKnownSpells(_spellManager.CopyKnownSpellIds());
}
PushBuffItemRows();
}
/// <summary>/ra spells [show|hide|toggle] (also the dashboard's "spells" remote command).</summary>

View file

@ -0,0 +1,267 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.Threading;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.Diagnostics;
using RynthCore.Plugin.RynthAi.TimedCommands;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
// Timed commands (2026-11-03): chat commands sent every N seconds, per character, per server and
// for every character (TimedCommands/TimedCommands.cs has the rules and the files). The lists load
// once the character's settings folder is known (after login, a hot reload or the late settings
// retry), the tick sends what is due and saves edits a second after the last one, and the Timed
// Commands window (a plugin window, API v89, with no bar button: the dashboard's options menu and
// /ra timed show open it) and /ra timed edit them.
public sealed partial class RynthAiPlugin
{
internal const string TimedCommandsTitle = "Timed Commands", TimedCommandsSurface = "window:timedcommands";
private const long TimedSaveAfterMs = 1000;
private readonly TimedCommandSet _timed = new();
private readonly TimedCommandScheduler _timedScheduler = new();
private TimedCommandsWindow? _timedWindow;
private string _timedLoadedFor = string.Empty; // the settings folder the lists are for
private int _timedFailures;
/// <summary>The tick (TickStep.TimedCommands): load for this character, save edits, send what is due.</summary>
private void TickTimedCommands()
{
if (!_loginComplete || _dashboard == null) return;
string charFolder = _dashboard.CharFolder;
if (string.IsNullOrEmpty(charFolder)) return;
long now = Environment.TickCount64;
if (!string.Equals(charFolder, _timedLoadedFor, StringComparison.OrdinalIgnoreCase))
{
SaveTimedCommands();
var problems = new List<string>();
_timed.Load(charFolder, problems);
_timedLoadedFor = charFolder;
_timedScheduler.OnLogin(_timed, now);
foreach (string p in problems) ChatLine($"[RynthAi] Timed commands: couldn't read the list for {p}.");
int n;
lock (_timed.Sync) n = _timed.List(TimedScope.Character).Count + _timed.List(TimedScope.Server).Count + _timed.List(TimedScope.All).Count;
if (n > 0) Host.Log($"[RynthAi] Timed commands: {n} loaded for {_timed.Character} on {_timed.Server}.");
}
if (_timed.AnyDirty && now - _timed.ChangedAtMs >= TimedSaveAfterMs) SaveTimedCommands();
var st = new TimedRunState(now, InWorld: Host.GetPlayerId() != 0, Portaling: RynthCore.Plugin.Shared.ActionPacer.IsPortaling(Host),
MacroRunning: _dashboard.Settings.IsMacroRunning);
if (_timedScheduler.TryNext(_timed, in st, out string command, out TimedScope scope))
SendTimedCommand(command, scope, "timed");
}
private void SendTimedCommand(string command, TimedScope scope, string why)
{
Host.Log($"[RynthAi] Timed command ({TimedCommandSet.ScopeName(scope)}, {why}): {command}");
// As a script's line (a nav route's chat waypoint does the same): quiet when it works.
Reply.AsScript(() => { HandleRynthChatSubmit(command); return true; });
}
private void SaveTimedCommands()
{
if (!_timed.AnyDirty) return;
var problems = new List<string>();
_timed.SaveDirty(problems);
foreach (string p in problems) ChatLine($"[RynthAi] Timed commands: couldn't save the list for {p}.");
}
/// <summary>Logout: the lists are saved and forgotten (the next character loads its own).</summary>
private void OnLogoutTimedCommands()
{
SaveTimedCommands();
_timed.Unload();
_timedLoadedFor = string.Empty;
}
/// <summary>The window's Run now (queued from the render thread): sent on the tick, next run one interval later.</summary>
private void RunTimedNow(TimedScope scope, int index)
{
string command;
lock (_timed.Sync)
{
List<TimedCommand> list = _timed.List(scope);
if (index < 0 || index >= list.Count || list[index].Command.Length == 0) return;
command = list[index].Command;
_timedScheduler.RanNow(list[index], Environment.TickCount64);
}
SendTimedCommand(command, scope, "Run now");
}
/// <summary>The dashboard's ⋯ > Timed commands: the window open or closed. Any thread.</summary>
internal void ToggleTimedCommandsWindow()
{
if (Host.HasSetPanelOpen) Host.SetPanelOpen(TimedCommandsTitle, RynthPanelOpen.Toggle);
}
// ── /ra timed ────────────────────────────────────────────────────────
internal const string TimedUsage =
"Usage: /ra timed [server|all] list | add <seconds> <command> | remove <n> | on <n> | off <n> | run <n>; /ra timed show | hide";
/// <summary>
/// "/ra timed ...": the lists by chat. The list word ("server" or "all"; none = this character)
/// comes right after timed. Every form replies.
/// </summary>
private void HandleTimedCommand(string[] parts)
{
int at = 2;
TimedScope scope = TimedScope.Character;
if (parts.Length > at)
{
string s = parts[at].ToLowerInvariant();
if (s is "server") { scope = TimedScope.Server; at++; }
else if (s is "all" or "global") { scope = TimedScope.All; at++; }
else if (s is "char" or "character" or "me") at++;
}
string verb = parts.Length > at ? parts[at].ToLowerInvariant() : "list";
string listName = TimedCommandSet.ScopeName(scope);
if (verb is "show" or "open" or "hide" or "close" or "toggle" or "window")
{
if (!Host.HasSetPanelOpen) { ReplyFail("[RynthAi] The Timed Commands window needs RynthCore with plugin windows (plugin API 89+); /ra timed list works."); return; }
RynthPanelOpen mode = verb is "hide" or "close" ? RynthPanelOpen.Close : verb is "toggle" or "window" ? RynthPanelOpen.Toggle : RynthPanelOpen.Open;
int open = Host.SetPanelOpen(TimedCommandsTitle, mode);
if (open < 0) { ReplyFail("[RynthAi] The Timed Commands window isn't there yet (RynthCore adds it a few seconds after login). Try again in a moment."); return; }
ReplyOk(open == 1 ? "[RynthAi] Timed Commands window open." : "[RynthAi] Timed Commands window closed.");
return;
}
if (!_timed.Loaded) { ReplyFail("[RynthAi] Timed commands load once you are in the world (your settings folder isn't known yet)."); return; }
long now = Environment.TickCount64;
bool macro = _dashboard?.Settings.IsMacroRunning == true;
switch (verb)
{
case "list":
case "ls":
{
var lines = new List<string>();
lock (_timed.Sync)
{
List<TimedCommand> list = _timed.List(scope);
for (int i = 0; i < list.Count; i++)
{
TimedCommand c = list[i];
lines.Add($"[RynthAi] {i + 1}. {(c.Command.Length > 0 ? c.Command : "(empty)")} - {c.EveryText()}" +
$"{(c.MacroOnly ? ", macro only" : "")}, {TimedCommandScheduler.NextText(c, now, macro)}");
}
}
if (lines.Count == 0) { ReplyOk($"[RynthAi] No timed commands for {listName}. /ra timed{ScopeWord(scope)} add <seconds> <command> adds one."); return; }
ReplyOk($"[RynthAi] Timed commands for {listName} ({lines.Count}):");
foreach (string l in lines) ChatLine(l);
return;
}
case "add":
{
if (parts.Length <= at + 2 || !int.TryParse(parts[at + 1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int seconds)
|| seconds < TimedCommand.MinSeconds || seconds > TimedCommand.MaxSeconds)
{
ReplyFail($"[RynthAi] Usage: /ra timed{ScopeWord(scope)} add <seconds {TimedCommand.MinSeconds}-{TimedCommand.MaxSeconds}> <command> (600 = every 10 minutes)");
return;
}
string text = TimedCommand.CleanCommand(string.Join(' ', parts, at + 2, parts.Length - at - 2));
if (text.Length == 0) { ReplyFail($"[RynthAi] Usage: /ra timed{ScopeWord(scope)} add <seconds> <command>"); return; }
int n;
var c = new TimedCommand { Command = text, Seconds = seconds };
lock (_timed.Sync)
{
_timed.List(scope).Add(c);
n = _timed.List(scope).Count;
_timed.MarkChanged(scope, now);
}
SaveTimedCommands();
ReplyOk($"[RynthAi] Timed command {n} for {listName}: {text} - {c.EveryText()}, first in {TimedCommand.Duration(seconds)}.");
return;
}
case "remove":
case "rm":
case "delete":
case "on":
case "off":
case "run":
{
if (parts.Length <= at + 1 || !int.TryParse(parts[at + 1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int n) || n < 1)
{
ReplyFail($"[RynthAi] Usage: /ra timed{ScopeWord(scope)} {verb} <n> (the number in /ra timed{ScopeWord(scope)} list)");
return;
}
string? text = null; // null: no such command
bool remove = verb is "remove" or "rm" or "delete";
lock (_timed.Sync)
{
List<TimedCommand> list = _timed.List(scope);
if (n <= list.Count)
{
TimedCommand c = list[n - 1];
text = c.Command;
if (remove) list.RemoveAt(n - 1);
else if (verb == "on") { c.Enabled = true; c.NextDueMs = 0; }
else if (verb == "off") c.Enabled = false;
if (verb != "run") _timed.MarkChanged(scope, now);
}
}
if (text == null)
{
ReplyFail($"[RynthAi] There is no timed command {n} for {listName} (/ra timed{ScopeWord(scope)} list).");
return;
}
if (verb == "run")
{
if (text.Length == 0) { ReplyFail($"[RynthAi] Timed command {n} for {listName} has no command to run."); return; }
RunTimedNow(scope, n - 1);
ReplyOk($"[RynthAi] Ran timed command {n} for {listName}: {text}");
return;
}
SaveTimedCommands();
ReplyOk(remove
? $"[RynthAi] Removed timed command {n} for {listName}: {text}"
: $"[RynthAi] Timed command {n} for {listName} {verb}: {text}");
return;
}
default:
ReplyFail("[RynthAi] " + TimedUsage);
return;
}
}
private static string ScopeWord(TimedScope s) => s switch { TimedScope.Server => " server", TimedScope.All => " all", _ => string.Empty };
// ── The window (render thread) ───────────────────────────────────────
/// <summary>
/// RynthPluginRenderEmbed "window:timedcommands": the Timed Commands window body, docked or popped
/// out (the engine's current context). 1 drawn, 0 not ready, -2 failed (three draws in a row threw).
/// </summary>
internal int RenderTimedCommands(bool popped, out Vector2 want)
{
want = default;
if (!_initialized || Host.ImGuiContext == IntPtr.Zero) return 0;
IntPtr previous = ImGui.GetCurrentContext();
ImGui.SetCurrentContext(EmbedContext());
try
{
_timedWindow ??= new TimedCommandsWindow(_timed,
(scope, index) => QueueDashAction(() => RunTimedNow(scope, index)),
() => _dashboard?.Settings.IsMacroRunning == true);
want = _timedWindow.Draw();
_timedFailures = 0;
return 1;
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.UI, ex, "RenderTimedCommands");
return ++_timedFailures >= 3 ? -2 : 0;
}
finally
{
ImGui.SetCurrentContext(previous);
}
}
/// <summary>The window goes in the sections manifest on an engine with plugin windows (v89).</summary>
private bool TimedCommandsWindowWanted => Host.HasUiTheme && Host.HasSetPanelOpen;
}

View file

@ -306,6 +306,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
try { _dashboard?.SaveSettings(); } catch { }
try { _sessionStats?.Shutdown(); } catch { }
try { ShutdownMonsterStats(); } catch { } // kept for the next copy, with the session
try { SaveTimedCommands(); } catch { } // an edit made just before the unload
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.
@ -364,6 +365,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
try { _dashboard?.SaveSettings(); } catch { }
try { _sessionStats?.OnLogout(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats logout"); }
try { OnLogoutMonsterStats(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats logout"); }
try { OnLogoutTimedCommands(); } catch (Exception ex) { RynthLog.Exception(LogCat.Commands, ex, "timed commands logout"); }
Loot.T11ItemSupport.Reset();
_boostNavNoticeSaid = false; // the Boost Nav Priority notice: once per session
// A real logout: the next OnLoginComplete is a fresh login, not a hot reload.
@ -700,6 +702,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
_dashboard.LoadSettings(charName);
_patrolOnLoginPending = _dashboard.Settings.PatrolOnLogin;
_huntOnLoginPending = _dashboard.Settings.HuntOnLogin;
}
// Query own health to get the ratio → derive true MaxHealth immediately
@ -1113,7 +1116,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "trace":
case "logs":
case "iteminfo":
// Settings panel buttons (Diagnostics tab, Item Info options); value carries the
case "buffitems":
// Settings panel buttons (Diagnostics tab, Item Info options, the Spells window's Buff Items tab); value carries the
// same arguments as "/ra trace|logs|iteminfo ...".
{
var args = new List<string> { "/ra", action.ToLowerInvariant() };
@ -1124,6 +1128,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "trace": HandleTraceCommand(parts); break;
case "logs": HandleLogsCommand(parts); break;
case "iteminfo": HandleItemInfoCommand(parts); break;
case "buffitems": HandleBuffItemsCommand(parts); break;
}
}
break;
@ -1156,7 +1161,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
["TopOffHP"] = (0, 100), ["TopOffStam"] = (0, 100), ["TopOffMana"] = (0, 100),
["HealOthersAt"] = (0, 100), ["RestamOthersAt"] = (0, 100), ["InfuseOthersAt"] = (0, 100),
["MeleeAttackPower"] = (-1, 100), ["MissileAttackPower"] = (-1, 100),
["MeleeAttackHeight"] = (0, 2), ["MissileAttackHeight"] = (0, 2),
["MeleeAttackHeight"] = (0, 2), ["MissileAttackHeight"] = (0, 2), ["DfDefaultHeight"] = (-1, 2),
["VariablePowerMin"] = (0, 100), ["VariablePowerMax"] = (0, 100),
["MissileEnvironmentResponse"] = (0, 3), ["MagicEnvironmentResponse"] = (0, 3),
["EnvironmentImpactLimit"] = (1, 10), ["EnvironmentImpactWindowSec"] = (5, 120),
@ -1640,6 +1645,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_damageStore?.SetCharacter(_dashboard.CharFolder);
SetXpTableCharacter(_dashboard.CharFolder);
_patrolOnLoginPending = _dashboard.Settings.PatrolOnLogin;
_huntOnLoginPending = _dashboard.Settings.HuntOnLogin;
if (_miniRemote == null)
{
CreateMiniRemote();
@ -1683,6 +1689,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (diag) Host.Log("[RynthAi] OnTick: after quest tracker");
Guard(TickStep.GiveQueue, DrainGiveQueue);
Guard(TickStep.ItemTool, TickItemTool); // the Item Tool: chest looter + Quick give (RynthAiPlugin.ItemTool.cs)
Guard(TickStep.TimedCommands, TickTimedCommands); // commands every N seconds (RynthAiPlugin.TimedCommands.cs)
if (diag) Host.Log("[RynthAi] OnTick: after drain give queue");
Guard(TickStep.Jumper, () => _jumper?.Tick());
if (diag) Host.Log("[RynthAi] OnTick: after jumper tick");
@ -1835,11 +1842,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
Guard(TickStep.PatrolReroute, () =>
{
if (_patrolOnLoginPending && _raycast?.GeometryLoader?.CellDat?.IsLoaded == true)
{
_patrolOnLoginPending = false;
HandleDungeonNavPatrol();
}
// Patrol On Login / Hunt On Login, once the dats are open (RynthAiPlugin.OutdoorHunt.cs).
TickLoginAutoStart();
// Reroute the active dungeon patrol around any lava/acid hotspot sighted
// since the route was built — treats the hotspot as a wall instead of
@ -2529,6 +2533,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_petManager?.OnChatWindowText(text);
_combatManager?.TraceCastChat(text, chatType);
_combatManager?.HandleChatForDebuffs(text);
try { _combatManager?.NoteDirtyFightingChat(text); } catch (Exception ex) { Host.Log($"[RynthAi] Dirty Fighting chat check failed: {ex.Message}"); }
_combatManager?.HandleChatForDamage(text, chatType);
_missileCraftingManager?.HandleChat(text);
_scrollLearner?.OnChat(text);
@ -4097,10 +4102,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "ii": HandleItemInfoCommand(parts); break;
case "spells": HandleSpellsCommand(parts.Length > 2 ? parts[2] : string.Empty); break;
case "buffprofile": HandleBuffProfileCommand(parts); break;
case "buffitems": HandleBuffItemsCommand(parts); break;
case "groundloot": HandleGroundLootCommand(parts); break;
case "addnavpt": HandleAddNavPointCommand(); break;
case "lootname": HandleLootNameCommand(parts); break;
case "navheading": HandleNavHeadingCommand(parts); break;
case "dfheight": HandleDfHeightCommand(parts); break;
case "nav": HandleNavCommand(parts); break;
case "meta": HandleMetaCommand(parts); break;
case "lua": ForwardLuaCommand(parts); break;
@ -4141,7 +4148,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "dumpinv": HandleDumpInventoryCommand(); break;
case "combat": HandleCombatStateCommand(); break;
case "mstats": HandleMonsterStatsCommand(parts); break; // RynthAiPlugin.MonsterStats.cs
case "gear": HandleGearCommand(parts); break; // RynthAiPlugin.ActiveGear.cs
case "timed": HandleTimedCommand(parts); break; // RynthAiPlugin.TimedCommands.cs
case "aetheria": HandleAetheriaCommand(parts); break; // RynthAiPlugin.Aetheria.cs
case "autoconfirm": HandleAutoConfirmCommand(parts); break; // RynthAiPlugin.AutoConfirm.cs
case "why": HandleWhyCommand(); break;
case "ghost":
case "ghosts": HandleGhostsCommand(cmd, parts); break;

View file

@ -54,6 +54,6 @@ public sealed partial class RynthAiPlugin
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.");
ChatLine("[RynthAi] Change the server: RynthCore Settings > Game Client > Server, or /rc server pick <id>|auto.");
}
}

View file

@ -0,0 +1,335 @@
// ============================================================================
// RynthAi - TimedCommands/TimedCommands.cs
// Timed commands (2026-11-03, players asked for MagTools' periodic commands):
// chat commands RynthAi sends every N seconds, in three lists as MagTools
// keeps them: this character, every character on this server, and every
// character. A character runs all three.
//
// Files (beside the settings profiles, so switching a settings profile keeps
// them): SettingsProfiles\<server>\<character>\timed_commands.json,
// SettingsProfiles\<server>\timed_commands.json and
// SettingsProfiles\timed_commands.json.
//
// Each command: the text (sent as a script's line: a /ra, /mt, /ub or /rc
// command, an emote, a channel...), every how many seconds (1 to 86400), the
// first run how many seconds after login (0 = one interval), on/off, and
// "only while the macro runs". Rules (TimedCommandScheduler): at most one command a second,
// none before login completes, while in portal space or before the first
// delay; a command that came due while it couldn't run goes once when it can
// (no backlog), then every interval from then.
//
// Pure (no host): the host tests drive it.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
namespace RynthCore.Plugin.RynthAi.TimedCommands;
/// <summary>Which list a timed command is in.</summary>
internal enum TimedScope { Character = 0, Server = 1, All = 2 }
/// <summary>One timed command (edited by the window and /ra timed; run by TimedCommandScheduler).</summary>
internal sealed class TimedCommand
{
public const int MinSeconds = 1, MaxSeconds = 86400, DefaultSeconds = 600;
public const int MaxLength = 200;
public string Command = string.Empty;
/// <summary>Every how many seconds (1 to 86400).</summary>
public int Seconds = DefaultSeconds;
/// <summary>Seconds after login before the first run (0 to 86400); 0 = one interval.</summary>
public int FirstAfter;
public bool Enabled = true;
/// <summary>Only while the macro runs (it waits while the macro is stopped).</summary>
public bool MacroOnly;
/// <summary>Environment.TickCount64 when it is due next (0 = not scheduled yet). Not saved.</summary>
internal long NextDueMs;
/// <summary>An interval in whole seconds, 1 to 86400 (not a number: the default 600).</summary>
public static int ClampSeconds(double s) =>
double.IsNaN(s) || double.IsInfinity(s) ? DefaultSeconds : (int)Math.Clamp(Math.Round(s), MinSeconds, MaxSeconds);
/// <summary>A first delay in whole seconds, 0 to 86400 (negative or not a number: 0).</summary>
public static int ClampFirstAfter(double s) =>
double.IsNaN(s) || double.IsInfinity(s) || s < 0 ? 0 : (int)Math.Min(Math.Round(s), MaxSeconds);
public static string CleanCommand(string? text)
{
string t = (text ?? string.Empty).Replace('\r', ' ').Replace('\n', ' ').Trim();
return t.Length > MaxLength ? t[..MaxLength] : t;
}
/// <summary>"every 30 s" / "every 600 s (10 min)".</summary>
public string EveryText() => Every(Seconds);
public static string Every(int seconds) => "every " + Duration(seconds);
/// <summary>"30 s", "90 s (1 min 30 s)", "600 s (10 min)", "86400 s (24 h)".</summary>
public static string Duration(int seconds)
{
string s = seconds.ToString(CultureInfo.InvariantCulture) + " s";
if (seconds < 60) return s;
int h = seconds / 3600, m = seconds / 60 % 60, rest = seconds % 60;
var parts = new List<string>(3);
if (h > 0) parts.Add(h.ToString(CultureInfo.InvariantCulture) + " h");
if (m > 0) parts.Add(m.ToString(CultureInfo.InvariantCulture) + " min");
if (rest > 0) parts.Add(rest.ToString(CultureInfo.InvariantCulture) + " s");
return s + " (" + string.Join(' ', parts) + ")";
}
}
/// <summary>The three lists and their files.</summary>
internal sealed class TimedCommandSet
{
public const string FileName = "timed_commands.json";
/// <summary>Locks every read and edit of the lists (the window is on the render thread, the scheduler on the tick).</summary>
public readonly object Sync = new();
private readonly List<TimedCommand>[] _lists = { new(), new(), new() };
private readonly string[] _paths = { string.Empty, string.Empty, string.Empty };
private readonly bool[] _dirty = new bool[3];
/// <summary>The character and server the lists are for (folder names; empty before login).</summary>
public string Character { get; private set; } = string.Empty;
public string Server { get; private set; } = string.Empty;
public bool Loaded { get; private set; }
/// <summary>Changed since the last save (any list). Under <see cref="Sync"/> or from the tick.</summary>
public long ChangedAtMs { get; private set; }
/// <summary>The list for <paramref name="scope"/>; lock <see cref="Sync"/> around any use.</summary>
public List<TimedCommand> List(TimedScope scope) => _lists[(int)scope];
public static string ScopeName(TimedScope s) => s switch
{
TimedScope.Character => "this character",
TimedScope.Server => "this server",
_ => "all characters",
};
/// <summary>
/// Loads the three lists for the character whose settings folder is <paramref name="charFolder"/>
/// (SettingsProfiles\&lt;server&gt;\&lt;character&gt;). Problems go to <paramref name="problems"/>; a missing file is an empty list.
/// </summary>
public void Load(string charFolder, List<string>? problems = null)
{
string? serverFolder = Path.GetDirectoryName(charFolder);
string? baseFolder = serverFolder != null ? Path.GetDirectoryName(serverFolder) : null;
lock (Sync)
{
Character = Path.GetFileName(charFolder);
Server = serverFolder != null ? Path.GetFileName(serverFolder) : string.Empty;
_paths[(int)TimedScope.Character] = Path.Combine(charFolder, FileName);
_paths[(int)TimedScope.Server] = serverFolder != null ? Path.Combine(serverFolder, FileName) : string.Empty;
_paths[(int)TimedScope.All] = baseFolder != null ? Path.Combine(baseFolder, FileName) : string.Empty;
for (int i = 0; i < 3; i++)
{
_lists[i].Clear();
_dirty[i] = false;
if (_paths[i].Length == 0 || !File.Exists(_paths[i])) continue;
try { _lists[i].AddRange(Parse(File.ReadAllText(_paths[i]))); }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
{
problems?.Add($"{ScopeName((TimedScope)i)} ({_paths[i]}): {ex.Message}");
}
}
Loaded = true;
}
}
/// <summary>Forgets the character (logout): nothing runs until the next load.</summary>
public void Unload()
{
lock (Sync)
{
for (int i = 0; i < 3; i++) { _lists[i].Clear(); _paths[i] = string.Empty; _dirty[i] = false; }
Character = Server = string.Empty;
Loaded = false;
}
}
/// <summary>A list was edited: saved by <see cref="SaveDirty"/>. Call under <see cref="Sync"/>.</summary>
public void MarkChanged(TimedScope scope, long nowMs)
{
_dirty[(int)scope] = true;
ChangedAtMs = nowMs;
}
public bool AnyDirty { get { lock (Sync) return _dirty[0] || _dirty[1] || _dirty[2]; } }
/// <summary>Writes every edited list (temp file, then replace). Problems go to <paramref name="problems"/>.</summary>
public void SaveDirty(List<string>? problems = null)
{
lock (Sync)
{
for (int i = 0; i < 3; i++)
{
if (!_dirty[i] || _paths[i].Length == 0) continue;
_dirty[i] = false;
try
{
Directory.CreateDirectory(Path.GetDirectoryName(_paths[i])!);
string tmp = _paths[i] + ".tmp";
File.WriteAllText(tmp, Serialize(_lists[i]));
File.Move(tmp, _paths[i], overwrite: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
problems?.Add($"{ScopeName((TimedScope)i)} ({_paths[i]}): {ex.Message}");
}
}
}
}
// ── File format: {"version":2,"commands":[{"command","seconds","firstAfterSeconds","enabled","macroOnly"}]} ──
// Version 1 (before 2026-11-12) kept "minutes" and "firstAfter" in minutes: read and turned into
// seconds (×60), so an old list keeps its timing; the next save writes version 2.
public const int FileVersion = 2;
public static string Serialize(IReadOnlyList<TimedCommand> list)
{
using var stream = new MemoryStream();
using (var w = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteNumber("version", FileVersion);
w.WriteStartArray("commands");
foreach (TimedCommand c in list)
{
w.WriteStartObject();
w.WriteString("command", c.Command);
w.WriteNumber("seconds", c.Seconds);
w.WriteNumber("firstAfterSeconds", c.FirstAfter);
w.WriteBoolean("enabled", c.Enabled);
w.WriteBoolean("macroOnly", c.MacroOnly);
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteEndObject();
}
return Encoding.UTF8.GetString(stream.ToArray());
}
public static List<TimedCommand> Parse(string json)
{
var list = new List<TimedCommand>();
using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
if (doc.RootElement.ValueKind != JsonValueKind.Object || !doc.RootElement.TryGetProperty("commands", out JsonElement arr)
|| arr.ValueKind != JsonValueKind.Array)
return list;
foreach (JsonElement e in arr.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object) continue;
var c = new TimedCommand
{
Command = TimedCommand.CleanCommand(e.TryGetProperty("command", out JsonElement t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null),
Seconds = TimedCommand.ClampSeconds(
Number(e, "seconds", out double sec) ? sec
: Number(e, "minutes", out double min) ? min * 60
: TimedCommand.DefaultSeconds),
FirstAfter = TimedCommand.ClampFirstAfter(
Number(e, "firstAfterSeconds", out double fsec) ? fsec
: Number(e, "firstAfter", out double fmin) ? fmin * 60
: 0),
Enabled = !e.TryGetProperty("enabled", out JsonElement en) || en.ValueKind != JsonValueKind.False,
MacroOnly = e.TryGetProperty("macroOnly", out JsonElement mo) && mo.ValueKind == JsonValueKind.True,
};
list.Add(c);
}
return list;
}
private static bool Number(JsonElement e, string name, out double value)
{
value = 0;
return e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out value);
}
}
/// <summary>What the scheduler needs to know about the client this tick.</summary>
internal readonly record struct TimedRunState(long NowMs, bool InWorld, bool Portaling, bool MacroRunning);
/// <summary>When each timed command runs (see the file header for the rules).</summary>
internal sealed class TimedCommandScheduler
{
/// <summary>Two timed commands are never sent less than this apart.</summary>
public const long GapMs = 1000;
private long _lastSentMs = long.MinValue / 2;
private long _loginMs;
/// <summary>Login completed at <paramref name="nowMs"/>: every command starts its first delay from here.</summary>
public void OnLogin(TimedCommandSet set, long nowMs)
{
_loginMs = nowMs;
lock (set.Sync)
for (int s = 0; s < 3; s++)
foreach (TimedCommand c in set.List((TimedScope)s))
c.NextDueMs = c.Enabled && c.Command.Length > 0 ? FirstDue(c, nowMs) : 0;
}
/// <summary>The first run of <paramref name="c"/> after login (or after it was added or turned on, when that's later).</summary>
public long FirstDue(TimedCommand c, long fromMs) =>
Math.Max(_loginMs, fromMs) + (c.FirstAfter > 0 ? Math.Min(c.FirstAfter, TimedCommand.MaxSeconds) * 1000L : IntervalMs(c));
/// <summary>
/// The interval in ms. Clamped here as well: the window's box holds what is typed until it is left
/// (typing "600" passes through "6" and an empty box is 0), and that must never mean "every tick".
/// </summary>
public static long IntervalMs(TimedCommand c) => TimedCommand.ClampSeconds(c.Seconds) * 1000L;
/// <summary>
/// The command to send now, if any (at most one per call, <see cref="GapMs"/> apart): of those due,
/// the one that has waited longest. Schedules commands seen for the first time (added or turned on
/// since login: their first delay starts now). Locks the set.
/// </summary>
public bool TryNext(TimedCommandSet set, in TimedRunState st, out string command, out TimedScope scope)
{
command = string.Empty;
scope = TimedScope.Character;
if (!set.Loaded) return false;
lock (set.Sync)
{
TimedCommand? pick = null;
for (int s = 0; s < 3; s++)
foreach (TimedCommand c in set.List((TimedScope)s))
{
if (!c.Enabled || c.Command.Length == 0) { c.NextDueMs = 0; continue; }
if (c.NextDueMs == 0) c.NextDueMs = FirstDue(c, st.NowMs);
if (st.NowMs >= c.NextDueMs && (!c.MacroOnly || st.MacroRunning) && (pick == null || c.NextDueMs < pick.NextDueMs))
{
pick = c;
scope = (TimedScope)s;
}
}
if (pick == null || !st.InWorld || st.Portaling || st.NowMs - _lastSentMs < GapMs) return false;
_lastSentMs = st.NowMs;
pick.NextDueMs = st.NowMs + IntervalMs(pick);
command = pick.Command;
return true;
}
}
/// <summary>A command sent by hand (Run now): the next run is one interval from now.</summary>
public void RanNow(TimedCommand c, long nowMs)
{
c.NextDueMs = nowMs + IntervalMs(c);
_lastSentMs = nowMs;
}
/// <summary>"in 4:30" / "waiting for the macro" / "off" for the window and /ra timed list. Under the set's lock.</summary>
public static string NextText(TimedCommand c, long nowMs, bool macroRunning)
{
if (!c.Enabled) return "off";
if (c.Command.Length == 0) return "no command";
if (c.MacroOnly && !macroRunning) return "waits for the macro";
if (c.NextDueMs == 0) return "scheduling";
long left = Math.Max(0, c.NextDueMs - nowMs) / 1000;
return left >= 3600
? $"in {left / 3600}:{left / 60 % 60:00}:{left % 60:00}"
: $"in {left / 60}:{left % 60:00}";
}
}

View file

@ -0,0 +1,309 @@
// ============================================================================
// RynthAi - TimedCommands/TimedCommandsWindow.cs
// The Timed Commands window (2026-11-03): the three lists (this character,
// this server, all characters) as tabs, one row per command: on/off, the
// command, every how many seconds, the first run after login (seconds), only
// while the macro runs, when it runs next, Run now and Remove; Add command
// under them. RynthCore hosts the window (the sections manifest's
// "timedcommands" window, plugin API v89: header, pop-out, resize, remembered
// place; no bar button, the dashboard's options menu and /ra timed show open
// it) and calls Draw through RynthPluginRenderEmbed.
//
// AC's render thread. Edits go straight into the lists under the set's lock
// and mark them changed (the tick saves them a moment later); Run now is
// queued for the tick. Looks: Shared/RynthUi (the player's theme).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthAi.TimedCommands;
internal sealed class TimedCommandsWindow
{
private readonly TimedCommandSet _set;
private readonly Action<TimedScope, int> _runNow; // queued for the tick
private readonly Func<bool> _macroRunning;
private TimedScope _scope = TimedScope.Character;
private int _focusRow = -1; // a row just added: focus its command box
private float _k = 1f;
private float Px(float v) => v * _k;
private const string HelpText =
"Chat commands RynthAi sends every so many seconds, like MagTools' periodic commands.\n\n" +
"Three lists: This character (only this character), This server (every character on this server) " +
"and All characters. A character runs all three.\n\n" +
"Every: how many seconds between runs (1 to 86400, a day; 600 = 10 minutes). First after: seconds " +
"after login before the first run (0 = one interval). Macro only: it waits while the macro is stopped.\n\n" +
"A command can be anything you'd type: /ra, /mt, /ub and /rc commands, emotes, channels. Commands " +
"are sent at least a second apart, never in portal space, and a command that came due while it " +
"couldn't run goes once when it can.\n\n" +
"/ra timed list | add <seconds> <command> | remove <n> | on|off <n> | run <n> (add \"server\" or " +
"\"all\" after timed for the other lists); /ra timed show opens this window, and so does " +
"Timed commands in the RynthAi window's options menu.";
public TimedCommandsWindow(TimedCommandSet set, Action<TimedScope, int> runNow, Func<bool> macroRunning)
{
_set = set;
_runNow = runNow;
_macroRunning = macroRunning;
}
/// <summary>Draws the window body into the current ImGui window and returns the size it would like. Render thread.</summary>
public Vector2 Draw()
{
_k = Math.Max(0.5f, Font(RynthUiFont.Ui11).FontSize / 11f);
Vector2 origin = ImGui.GetCursorScreenPos();
Vector2 size = ImGui.GetContentRegionAvail();
var want = new Vector2(Px(640), Px(300));
if (size.X < 60 || size.Y < 40) return want;
ImDrawListPtr frame = ImGui.GetWindowDrawList();
frame.AddRectFilled(origin, origin + size, Background, 4);
using (PushFont(RynthUiFont.Ui11))
{
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4));
ImGui.SetCursorScreenPos(origin + new Vector2(6, 6));
ImGui.Indent(6);
float w = size.X - 12;
lock (_set.Sync)
{
DrawTabs(w);
if (!_set.Loaded)
{
Label("Timed commands load once you are in the world.", Mute);
}
else
{
DrawHeader(w);
float bodyH = Math.Max(Px(30), origin.Y + size.Y - 6 - ImGui.GetCursorScreenPos().Y - Px(34));
ImGui.PushStyleColor(ImGuiCol.ChildBg, Field);
ImGui.BeginChild("##tc_rows", new Vector2(w, bodyH));
DrawRows();
ImGui.EndChild();
ImGui.PopStyleColor();
DrawAdd(w);
}
}
ImGui.Unindent(6);
ImGui.PopStyleVar();
}
frame.AddRect(origin, origin + size, Border, 4);
return want;
}
// ── Tabs: the three lists, and help ─────────────────────────────────
private void DrawTabs(float w)
{
Vector2 p = ImGui.GetCursorScreenPos();
float h = Px(22), x = p.X, iconW = Px(22);
for (int s = 0; s < 3; s++)
{
var scope = (TimedScope)s;
string who = scope switch
{
TimedScope.Character => _set.Character.Length > 0 ? _set.Character : "This character",
TimedScope.Server => _set.Server.Length > 0 ? _set.Server : "This server",
_ => "All characters",
};
int n = _set.List(scope).Count;
string label = n > 0 ? $"{who} ({n})" : who;
float bw = ButtonWidth(label) + Px(8);
bool on = _scope == scope;
if (Button("##tc_tab" + s.ToString(CultureInfo.InvariantCulture), label, new Vector2(x, p.Y), new Vector2(bw, h),
on ? Text : Mute, on ? Selected : ButtonFill, border: on ? Accent : 0))
_scope = scope;
ImGui.SetItemTooltip(scope switch
{
TimedScope.Character => "Commands only this character runs.",
TimedScope.Server => "Commands every character on this server runs.",
_ => "Commands every character runs, on every server.",
});
x += bw + Px(4);
}
IconButton("##tc_help", RynthIcons.Info, new Vector2(p.X + w - iconW, p.Y), new Vector2(iconW, h), Mute, ButtonFill, font: RynthUiFont.Ui11);
if (ImGui.IsItemHovered())
{
ImGui.BeginTooltip();
ImGui.PushTextWrapPos(ImGui.GetFontSize() * 32);
ImGui.TextUnformatted(HelpText);
ImGui.PopTextWrapPos();
ImGui.EndTooltip();
}
ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h + Px(6)));
ImGui.Dummy(Vector2.Zero);
}
// ── Columns ─────────────────────────────────────────────────────────
private float OnW => Px(26);
private float EveryW => Px(70);
private float FirstW => Px(84);
private float MacroW => Px(48);
private float NextW => Px(96);
private float BtnW => Px(24);
/// <summary>The command column's width in a row <paramref name="w"/> wide.</summary>
private float CommandW(float w) => Math.Max(Px(80), w - OnW - EveryW - FirstW - MacroW - NextW - 2 * BtnW - Px(36));
private void DrawHeader(float w)
{
Vector2 p = ImGui.GetCursorScreenPos();
float h = Px(16), x = p.X + Px(4);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
void Head(string text, float width, string tip)
{
ImGui.SetCursorScreenPos(new Vector2(x, p.Y));
ImGui.InvisibleButton("##tch_" + text, new Vector2(Math.Max(1, width), h));
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(tip);
dl.AddText(new Vector2(x, p.Y + (h - ImGui.GetFontSize()) * 0.5f), Mute, text);
x += width + Px(4);
}
Head("On", OnW, "Runs while ticked.");
Head("Command", CommandW(w), "What is sent, as you would type it.");
Head("Every (s)", EveryW, "Seconds between runs (1 to 86400 = a day; 600 = 10 minutes).");
Head("First after (s)", FirstW, "Seconds after login before the first run (0 = one interval, up to 86400).");
Head("Macro", MacroW, "Only while the macro runs.");
Head("Next", NextW, "When it runs next.");
ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h + Px(2)));
ImGui.Dummy(Vector2.Zero);
}
// ── Rows (under the set's lock) ─────────────────────────────────────
private void DrawRows()
{
List<TimedCommand> list = _set.List(_scope);
float w = ImGui.GetContentRegionAvail().X;
if (list.Count == 0)
{
ImGui.SetCursorPos(new Vector2(Px(8), Px(8)));
ImGui.PushTextWrapPos(w - Px(8));
Label(_scope switch
{
TimedScope.Character => "No timed commands for this character. Add command puts one here.",
TimedScope.Server => "No timed commands for every character on this server. Add command puts one here.",
_ => "No timed commands for every character. Add command puts one here.",
}, Mute);
ImGui.PopTextWrapPos();
return;
}
long now = Environment.TickCount64;
bool macro = _macroRunning();
float rowH = Px(24);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
int remove = -1;
for (int i = 0; i < list.Count; i++)
{
TimedCommand c = list[i];
ImGui.PushID(i);
Vector2 p = ImGui.GetCursorScreenPos();
if (i % 2 == 1) dl.AddRectFilled(p, p + new Vector2(w, rowH), RowAlt);
float x = p.X + Px(4), y = p.Y + Px(2);
float fieldH = rowH - Px(4);
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(Px(4), Math.Max(1, (fieldH - ImGui.GetFontSize()) * 0.5f)));
ImGui.PushStyleColor(ImGuiCol.FrameBg, Background);
ImGui.SetCursorScreenPos(new Vector2(x, y));
bool en = c.Enabled;
if (ImGui.Checkbox("##on", ref en)) { c.Enabled = en; c.NextDueMs = 0; Changed(); }
x += OnW + Px(4);
ImGui.SetCursorScreenPos(new Vector2(x, y));
ImGui.SetNextItemWidth(CommandW(w));
if (_focusRow == i) { ImGui.SetKeyboardFocusHere(); _focusRow = -1; }
string cmd = c.Command;
if (ImGui.InputTextWithHint("##cmd", "/ra ... or anything you'd type", ref cmd, (uint)TimedCommand.MaxLength))
{
c.Command = TimedCommand.CleanCommand(cmd);
Changed();
}
x += CommandW(w) + Px(4);
ImGui.SetCursorScreenPos(new Vector2(x, y));
ImGui.SetNextItemWidth(EveryW);
int every = c.Seconds;
if (ImGui.InputInt("##every", ref every, 0, 0))
{
c.Seconds = every; // clamped when the box is left, so typing "600" passes through "6" (the scheduler clamps too)
Changed();
}
if (ImGui.IsItemDeactivatedAfterEdit()) { c.Seconds = TimedCommand.ClampSeconds(c.Seconds); c.NextDueMs = 0; Changed(); }
ImGui.SetItemTooltip(c.EveryText() + " (seconds, 1 to 86400)");
x += EveryW + Px(4);
ImGui.SetCursorScreenPos(new Vector2(x, y));
ImGui.SetNextItemWidth(FirstW);
int first = c.FirstAfter;
if (ImGui.InputInt("##first", ref first, 0, 0))
{
c.FirstAfter = first;
Changed();
}
if (ImGui.IsItemDeactivatedAfterEdit()) { c.FirstAfter = TimedCommand.ClampFirstAfter(c.FirstAfter); Changed(); }
ImGui.SetItemTooltip(c.FirstAfter > 0
? "First run " + TimedCommand.Duration(c.FirstAfter) + " after login (seconds, 0 to 86400)"
: "First run one interval after login (0; seconds, up to 86400)");
x += FirstW + Px(4);
ImGui.SetCursorScreenPos(new Vector2(x + (MacroW - ImGui.GetFrameHeight()) * 0.5f, y));
bool mo = c.MacroOnly;
if (ImGui.Checkbox("##macro", ref mo)) { c.MacroOnly = mo; Changed(); }
x += MacroW + Px(4);
ImGui.PopStyleColor();
ImGui.PopStyleVar();
string next = TimedCommandScheduler.NextText(c, now, macro);
dl.AddText(new Vector2(x, p.Y + (rowH - ImGui.GetFontSize()) * 0.5f), c.Enabled ? Text : Mute, next);
x += NextW + Px(4);
if (IconButton("##run", RynthIcons.Play, new Vector2(x, y), new Vector2(BtnW, fieldH), Text, ButtonFill,
enabled: c.Command.Length > 0, font: RynthUiFont.Ui11))
_runNow(_scope, i);
ImGui.SetItemTooltip("Run now (the next run is one interval from now).");
x += BtnW + Px(4);
if (IconButton("##del", RynthIcons.Trash, new Vector2(x, y), new Vector2(BtnW, fieldH), Red, ButtonFill, font: RynthUiFont.Ui11))
remove = i;
ImGui.SetItemTooltip("Remove this command.");
ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + rowH));
ImGui.Dummy(Vector2.Zero);
ImGui.PopID();
}
if (remove >= 0)
{
list.RemoveAt(remove);
Changed();
}
}
private void DrawAdd(float w)
{
Vector2 p = ImGui.GetCursorScreenPos();
float h = Px(22);
string label = "Add command";
if (Button("##tc_add", label, new Vector2(p.X, p.Y + Px(2)), new Vector2(ButtonWidth(label) + Px(8), h), Text, ButtonFill))
{
List<TimedCommand> list = _set.List(_scope);
list.Add(new TimedCommand());
_focusRow = list.Count - 1;
Changed();
}
ImGui.SetItemTooltip("A new command in this list: " + TimedCommand.Every(TimedCommand.DefaultSeconds) + ", on.");
string scopeNote = "Saved for " + TimedCommandSet.ScopeName(_scope) + ".";
ImGui.GetWindowDrawList().AddText(new Vector2(p.X + ButtonWidth(label) + Px(18), p.Y + Px(2) + (h - ImGui.GetFontSize()) * 0.5f), Mute, scopeNote);
ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h + Px(4)));
ImGui.Dummy(Vector2.Zero);
}
/// <summary>An edit to the shown list (under the set's lock): saved by the tick a moment later.</summary>
private void Changed() => _set.MarkChanged(_scope, Environment.TickCount64);
}

View file

@ -152,11 +152,11 @@ public sealed partial class RynthAiPlugin
// ── RynthCore's window placement ────────────────────────────────────
// The engine has no chat command for it ("/rc window save" never existed and went nowhere):
// its Settings > Display saves the game window for each character and puts it back at login.
// its Settings > Game Client saves the game window for each character and puts it back at login.
case "window":
UbNoEquivalent(cmd + (sub.Length > 0 ? " " + sub : ""), null,
$"[RynthAi] /ub window{(sub.Length > 0 ? " " + sub : "")}: RynthCore keeps the game window itself - Settings > Display, "
+ "'Remember Game Window Position' (saved for each character, put back after login), or 'Save Layout Now' there.");
$"[RynthAi] /ub window{(sub.Length > 0 ? " " + sub : "")}: RynthCore keeps the game window itself - Settings > Game Client, "
+ "'Remember Game Window Position' (saved for each character, put back after login), or 'Save Layout Now' (Settings > Interface).");
return true;
// ── RynthAi's Mini Remote ───────────────────────────────────────────

View file

@ -9,7 +9,7 @@
//
// anywhere drag to move; Ctrl+wheel: bigger or smaller (30-250%);
// right-click: hide it (/rdef daynight, the bar button, or
// Settings > UI > Toolbar show it again).
// Settings > Interface > In The Retail Toolbar's Place show it again).
//
// AC's render thread; reads the view the tick built (DayNightView) and counts
// the seconds down from when it was read, so the seconds move every frame.

View file

@ -121,7 +121,7 @@ number (the game gets no keys while the box has the keyboard) or pick 1, 10, 100
## The Day/Night timer
A one-row window (its RynthCore bar button is the sun; `/rdef daynight [show|hide]`; Settings > UI > Toolbar >
A one-row window (its RynthCore bar button is the sun; `/rdef daynight [show|hide]`; Settings > Interface > In The Retail Toolbar's Place >
*Day/Night timer*): a sun by day, a moon at night, and the **real** time until the next change, "Night in 23m",
"Day in 4m 10s" (seconds from 10 minutes down), with the Dereth hour's name when there is room. A Dereth day is
16 hours of 476.25 s, 2 h 7 min of real time: day (Dawnsong to Warmtide-and-Half) and night (Evensong to

View file

@ -55,8 +55,8 @@ internal sealed class PanelButtonsWindow
private float Px(float v) => v * _k;
/// <summary>
/// The layout's scale and the text's against the baked font: the window's own size (Settings > UI >
/// Toolbar, Ctrl+wheel: 30-250%, PanelScale) or, unset, the text size the engine baked for it.
/// The layout's scale and the text's against the baked font: the window's own size (Settings > Interface >
/// In The Retail Toolbar's Place, Ctrl+wheel: 30-250%, PanelScale) or, unset, the text size the engine baked for it.
/// </summary>
private void Scale()
{

View file

@ -11,7 +11,7 @@
// the name row drag to move; Ctrl+wheel: bigger or smaller (30-250%);
// right-click: a menu (2026-10-31): "Why this loot rule?" for
// an item (RynthAi's /ra loot why, in its window) and hide it
// (Settings > UI > Toolbar, /rdef selection show it again).
// (Settings > Interface > In The Retail Toolbar's Place, /rdef selection show it again).
// the quantity under a stack or a vendor's item (2026-10-30): how many, and
// Split / Give / Buy that many (SelectionWindow.Quantity.cs).
//
@ -230,7 +230,7 @@ internal sealed partial class SelectionWindow
: "Select an item (on a corpse, the ground or in a pack) first.");
}
if (ImGui.MenuItem("Hide the Selection window")) _host.SetPanelOpen(Title, RynthPanelOpen.Close);
SafeImGui.SetItemTooltip("/rdef selection, or Settings > UI > Toolbar > Selection, shows it again.");
SafeImGui.SetItemTooltip("/rdef selection, or Settings > Interface > In The Retail Toolbar's Place > Selection, shows it again.");
}
finally { ImGui.EndPopup(); }
}

View file

@ -102,8 +102,8 @@ internal sealed class ShortcutBarWindow
private float Fs(ImFontPtr f) => f.FontSize * _r;
/// <summary>
/// The layout's scale and the text's against the baked font: the window's own size (Settings > UI >
/// Toolbar, Ctrl+wheel: 30-250%, PanelScale) or, unset, the text size the engine baked for it.
/// The layout's scale and the text's against the baked font: the window's own size (Settings > Interface >
/// In The Retail Toolbar's Place, Ctrl+wheel: 30-250%, PanelScale) or, unset, the text size the engine baked for it.
/// </summary>
private void Scale()
{

View file

@ -25,7 +25,10 @@ internal sealed class LuaScriptHost
public static string LegacyScriptFolder => RynthLuaPaths.LegacyScripts;
private const int MaxConsoleLines = 400;
private const int AutoYieldCounter = 5_000; // VM instructions before a forced pause
// VM instructions before a forced pause. A forced pause resumes at once while the tick has time,
// so this only sets how often the time budget and the memory guard look: 1,000 (it was 5,000,
// which let one stretch of string.rep in a loop use over a gigabyte before the guard saw it).
private const int AutoYieldCounter = 1_000;
private sealed class LuaThread
{
@ -256,6 +259,90 @@ internal sealed class LuaScriptHost
public bool HasHandlers(string evt)
=> _script != null && _handlers.TryGetValue(evt, out var l) && l.Count > 0;
// ── Memory guard ────────────────────────────────────────────────────────
//
// A script can allocate without limit, and the game client is a 32-bit process with 4 GB for
// everything. 11-10: a player's script took a client from 0.7 GB to 1.9 GB in 6 seconds,
// twice, and the third burst ended it with an OutOfMemoryException inside MoonSharp; another of
// his clients took +730 MB in 1.3 s every 5 minutes (hence 512 MB in 5 s, not more). Each run
// of a script (a thread's turn in Tick, a hud pass) is measured with the allocating thread's
// own counter, so other plugins' allocations don't count against it; a script that allocates
// more than RunLimitBytes in one run, or WindowLimitBytes within 5 seconds, is stopped. Kept
// memory is the other way to run out (small tables piling up never reach either limit): once the
// .NET heap passes HeapPressureBytes, a script that allocated over HeapPressureScriptBytes in
// the last 5 seconds is stopped too.
/// <summary>The most one run of a script (a thread's turn, a hud pass) may allocate.</summary>
internal const long RunLimitBytes = 256L * 1024 * 1024;
/// <summary>The most a script may allocate in <see cref="WindowMs"/>.</summary>
internal const long WindowLimitBytes = 512L * 1024 * 1024;
private const long WindowMs = 5000;
/// <summary>A turn past this much allocation makes its thread pause every <see cref="FastAllocYieldCounter"/> instructions.</summary>
private const long FastAllocBytes = 32L * 1024 * 1024;
private const int FastAllocYieldCounter = 250;
/// <summary>The .NET heap size (every plugin's) past which a script still allocating is stopped; RynthCore's own is ~100-200 MB.</summary>
internal const long HeapPressureBytes = 800L * 1024 * 1024;
/// <summary>What a script may still allocate in 5 s while the heap is past <see cref="HeapPressureBytes"/>.</summary>
internal const long HeapPressureScriptBytes = 64L * 1024 * 1024;
private long _allocWindowStart;
private long _allocWindowBytes;
private static long _heapReadAt;
private static long _heapBytes;
/// <summary>The .NET heap size, read at most every 250 ms.</summary>
private static long HeapBytes(long nowMs)
{
if (nowMs - _heapReadAt >= 250) { _heapReadAt = nowMs; _heapBytes = GC.GetTotalMemory(false); }
return _heapBytes;
}
/// <summary>Set by the plugin: says a stop for memory in chat (the console alone is easy to miss).</summary>
public Action<string>? MemoryStopped;
private static long AllocatedNow() => GC.GetAllocatedBytesForCurrentThread();
/// <summary>
/// Counts <paramref name="bytes"/> allocated by one run of this script (<paramref name="what"/>:
/// "turn", "hud pass"). Stops the script and returns true when a limit is passed.
/// </summary>
internal bool ChargeAllocation(long bytes, string what)
{
if (_script == null || bytes <= 0) return false;
long now = Environment.TickCount64;
if (now - _allocWindowStart > WindowMs) { _allocWindowStart = now; _allocWindowBytes = 0; }
_allocWindowBytes += bytes;
string? why = bytes >= RunLimitBytes ? $"{bytes >> 20} MB of memory in one {what}"
: _allocWindowBytes >= WindowLimitBytes ? $"{_allocWindowBytes >> 20} MB of memory in 5 seconds"
: null;
if (why == null && _allocWindowBytes >= HeapPressureScriptBytes)
{
long heap = HeapBytes(now);
if (heap >= HeapPressureBytes)
why = $"{_allocWindowBytes >> 20} MB of memory in 5 seconds while the game's .NET memory was at {heap >> 20} MB";
}
if (why == null) return false;
StopForMemory($"it used {why} (limits: {RunLimitBytes >> 20} MB in one run, {WindowLimitBytes >> 20} MB in 5 s, "
+ $"{HeapPressureScriptBytes >> 20} MB in 5 s once the game's .NET memory passes {HeapPressureBytes >> 20} MB)", $"used {why}");
return true;
}
/// <summary>Stops the script for its memory use, saying why in its console and in chat.</summary>
internal void StopForMemory(string because, string shortReason)
{
if (_script == null) return;
string name = ScriptName.Length > 0 ? ScriptName : "editor script";
string msg = $"{name} was stopped: {because}. The game has 4 GB for everything, so a script that "
+ "uses memory this fast crashes it. Restart it once it's fixed: /lua start " + name;
Print(msg);
try { MemoryStopped?.Invoke(msg); } catch { }
Stop("stopped: " + shortReason);
}
/// <summary>True when the run that started at <paramref name="startBytes"/> is already past the one-run limit.</summary>
internal static bool RunOverLimit(long startBytes) => AllocatedNow() - startBytes >= RunLimitBytes;
internal static long AllocationMark() => AllocatedNow();
// ── Scheduler ───────────────────────────────────────────────────────────
/// <summary>
@ -309,6 +396,7 @@ internal sealed class LuaScriptHost
_current = t;
DynValue r = DynValue.Nil;
long alloc0 = AllocatedNow();
try
{
while (_script != null)
@ -316,8 +404,14 @@ internal sealed class LuaScriptHost
r = t.Started ? t.Co.Coroutine.Resume() : t.Co.Coroutine.Resume(t.Args);
t.Started = true;
if (t.Co.Coroutine.State == CoroutineState.Dead) break;
// Forced (auto) yield: keep going while this tick has budget.
if (r.Type == DataType.YieldRequest && !OverBudget()) continue;
// A thread allocating fast pauses far more often, so the guard sees it before
// a single stretch of 5,000 instructions can use a gigabyte (string.rep in a loop).
if (t.Co.Coroutine.AutoYieldCounter > FastAllocYieldCounter
&& AllocatedNow() - alloc0 >= FastAllocBytes)
t.Co.Coroutine.AutoYieldCounter = FastAllocYieldCounter;
// Forced (auto) yield: keep going while this tick has budget, and while
// this turn hasn't used too much memory (the guard below stops it then).
if (r.Type == DataType.YieldRequest && !OverBudget() && !RunOverLimit(alloc0)) continue;
break;
}
}
@ -328,6 +422,13 @@ internal sealed class LuaScriptHost
Done(t, null, ex.DecoratedMessage ?? ex.Message);
continue;
}
catch (OutOfMemoryException)
{
// The client is out of memory: this script goes at once, whoever used it up.
_current = null;
StopForMemory("the game ran out of memory while it was running", "the game ran out of memory while it ran");
return;
}
catch (Exception ex)
{
Print("error: " + ex.Message);
@ -338,6 +439,7 @@ internal sealed class LuaScriptHost
finally { _current = null; }
if (_script == null) return;
if (ChargeAllocation(AllocatedNow() - alloc0, "turn")) return;
if (t.Co.Coroutine.State == CoroutineState.Dead)
{
_threads.Remove(t);
@ -351,10 +453,29 @@ internal sealed class LuaScriptHost
private readonly Dictionary<string, DynValue> _modules = new(StringComparer.OrdinalIgnoreCase);
/// <summary>The longest string string.rep may make (32M characters, 64 MB): one call is one VM step, which the memory guard can't stop part-way.</summary>
internal const long MaxRepChars = 32L * 1024 * 1024;
private void RegisterCore(Script s)
{
_modules.Clear();
// string.rep(s, n [, sep]) with a size cap: MoonSharp builds the whole result in one step.
DynValue strLib = s.Globals.Get("string");
DynValue rep = strLib.Type == DataType.Table ? strLib.Table.Get("rep") : DynValue.Nil;
if (rep.Type == DataType.ClrFunction)
{
strLib.Table.Set("rep", DynValue.NewCallback((ctx, a) =>
{
long len = a.Count > 0 && a[0].Type is DataType.String or DataType.Number ? a[0].CastToString().Length : 0;
long n = a.Count > 1 && a[1].Type == DataType.Number ? (long)Math.Max(0, a[1].Number) : 0;
long sep = a.Count > 2 && a[2].Type is DataType.String or DataType.Number ? a[2].CastToString().Length : 0;
if (n > 0 && len * n + sep * (n - 1) > MaxRepChars)
throw new ScriptRuntimeException($"string.rep: the result would be {(len * n + sep * (n - 1)) / (1024 * 1024)}M characters (the limit is {MaxRepChars / (1024 * 1024)}M; the game client is short of memory)");
return rep.Callback.Invoke(ctx, a.GetArray());
}, "rep"));
}
// sleep(ms): park the calling thread. Implemented as a CLR call that
// sets the wake time, then a Lua-side yield (a CLR callback can't
// yield by itself).

View file

@ -98,6 +98,8 @@ public sealed partial class RynthLuaPlugin
var host = new LuaScriptHost(s => Log(s), (s, h) => RegisterApi(s, h, ctx!))
{
MacroRunning = () => _ai.MacroRunning,
// The memory guard's stop is said in chat in the failure colour (it's in the log via Reply too).
MemoryStopped = msg => ChatFail(msg),
};
ctx = new ScriptContext(name, folder, entry, manifest, host) { Transient = transient };
host.ResolveModule = (s, module) => ResolveModule(s, ctx, module);

View file

@ -527,6 +527,7 @@ public sealed partial class RynthLuaPlugin
_recorder.Begin(hud, _maxOps, _maxBytes);
string? error = null;
long alloc0 = LuaScriptHost.AllocationMark();
try
{
DynValue co = s.CreateCoroutine(runner);
@ -541,8 +542,20 @@ public sealed partial class RynthLuaPlugin
}
}
catch (InterpreterException ex) { error = ex.DecoratedMessage ?? ex.Message; }
catch (OutOfMemoryException) { error = "the game ran out of memory"; }
catch (Exception ex) { error = ex.Message; }
// The memory guard (LuaScriptHost.ChargeAllocation): a pass that used too much stops the script.
if (error == "the game ran out of memory")
hud.Ctx.Host.StopForMemory("the game ran out of memory during its hud pass", "the game ran out of memory in a hud pass");
else
hud.Ctx.Host.ChargeAllocation(LuaScriptHost.AllocationMark() - alloc0, $"hud pass ({hud.Name})");
if (!hud.Ctx.Host.Loaded)
{
_recorder.Abort();
return;
}
if (error != null)
{
// An error can quote a huge string (error(string.rep(...))): keep what the window,

View file

@ -46,7 +46,7 @@ internal sealed partial class OracleView
w.TextDisabled($"{st.ProfilePlugin} ({RynthCore.Plugin.Shared.RynthServerProfileApiV1.InterfaceName}): {prof.Summary()}");
else if (es.ActivePlugin.Length > 0)
w.TextDisabled($"{es.ActivePlugin} hasn't sent its server settings (an older plugin?).");
w.TextDisabled("Change the server: RynthCore Options > Diagnostics > Server, or /rc server pick <id>|auto.");
w.TextDisabled("Change the server: RynthCore Settings > Game Client > Server, or /rc server pick <id>|auto.");
}
else if (_c.Host.Version > 0 && _c.Host.Version < 86)
w.TextDisabled($"This engine is API v{_c.Host.Version}; server quest packs need v86 (RynthCore's server list).");

View file

@ -62,16 +62,21 @@ public static unsafe class PluginExports
// The same state for RynthAi's own dashboard (2026-10-23): a plugin reads another's exports only
// through the engine's RynthPluginGet*Json broker (GetPluginExportJson). {"auto":-1|0|1}, a
// literal (nothing to free).
// literal (nothing to free). 2026-11-11: "moving":1 while items are being moved (RynthSortPlugin.Moving),
// for the key's sorting look; a reader that only looks for "auto" is unchanged.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetAutoSortJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr AutoSortJson()
{
int state;
try { state = Runtime.Plugin?.AutoState ?? -1; } catch { state = -1; }
return state switch
bool moving;
try { state = Runtime.Plugin?.AutoState ?? -1; moving = Runtime.Plugin?.Moving ?? false; }
catch { state = -1; moving = false; }
return (state, moving) switch
{
1 => LiteralPointer("{\"auto\":1}"u8),
0 => LiteralPointer("{\"auto\":0}"u8),
(1, true) => LiteralPointer("{\"auto\":1,\"moving\":1}"u8),
(1, false) => LiteralPointer("{\"auto\":1,\"moving\":0}"u8),
(0, true) => LiteralPointer("{\"auto\":0,\"moving\":1}"u8),
(0, false) => LiteralPointer("{\"auto\":0,\"moving\":0}"u8),
_ => LiteralPointer("{\"auto\":-1}"u8),
};
}

View file

@ -56,10 +56,25 @@ public sealed class RynthSortPlugin : RynthPluginBase
private bool _backupOnSave;
private readonly List<string> _warnings = new();
private volatile int _autoState = -1;
private volatile bool _moving;
private int _movedSeen;
private long _lastMoveMs;
/// <summary>
/// How long after a move lands RynthSort still counts as moving, so a run of moves (a gap of
/// up to a second or two between them) reads as one on RynthAi's dashboard key.
/// </summary>
private const long MovingHoldMs = 1500;
/// <summary>For the engine's dashboard toggle (RynthSortAutoState): -1 not logged in yet, 0 auto-sort off, 1 on. Any thread.</summary>
public int AutoState => _autoState;
/// <summary>
/// RynthSort is moving items: a move is out, or one landed in the last <see cref="MovingHoldMs"/>.
/// RynthAi's auto-sort key plays its sorting look while this is true. Any thread.
/// </summary>
public bool Moving => _moving;
/// <summary>
/// A command from another plugin (RynthPluginApplyRemoteCommand): the /rsort argument when
/// <paramref name="action"/> is "rsort" (value "now", "status"...), else null (not ours).
@ -235,6 +250,9 @@ public sealed class RynthSortPlugin : RynthPluginBase
}
if (_saveDueMs != 0 && now >= _saveDueMs) SaveNow();
_autoState = _inWorld && _identityKnown ? (_sort.Data.Settings.Auto ? 1 : 0) : -1;
if (_sort.Moved > _movedSeen) _lastMoveMs = now; // a move landed (Moved goes back to 0 on Reset: not a move)
_movedSeen = _sort.Moved;
_moving = _inWorld && _identityKnown && (_sort.HasMoveOut || (_lastMoveMs != 0 && now - _lastMoveMs < MovingHoldMs));
if (!Host.HasUi || _window == null || _panel == null) return;
Record(_window, now);

View file

@ -19,6 +19,9 @@
// rises are ignored. "Deposited N luminance" and "Received N
// luminance from X" move lum into the bank without earning it:
// they are taken out of the next bank rises.
// Both a server that sends a bank AND Aelrynth's 9102/9103
// (DreamWeave): the bank alone counts; 9102's auto-banked lum
// is the same lum as the bank's rise (it counted twice).
// Server bank a server that banks earned luminance out of the client's
// sight: its server plugin reads the bank (a chat command once
// a minute) and publishes it in its profile ("bankLuminance");
@ -354,8 +357,11 @@ internal sealed class SessionStats
long up = _lumRise.Take(lum);
if (!BankTracked) charUp += up;
}
if (s.AelDrawn is long drawn) charUp -= _drawnRise.Take(drawn);
if (s.AelBanked is long banked) charUp += _bankedRise.Take(banked);
// With a bank read, its rises already hold what was auto-banked (and a draw is a bank drop):
// DreamWeave sends both the bank and 9102, and counting both doubled Lum/hr (2026-11-12).
// The baselines still move, so a bank that stops being read doesn't count the gap.
if (s.AelDrawn is long drawn) { long d = _drawnRise.Take(drawn); if (!BankTracked) charUp -= d; }
if (s.AelBanked is long banked) { long b = _bankedRise.Take(banked); if (!BankTracked) charUp += b; }
if (charUp > 0) lumUp += charUp;
if (lumUp > 0) AddLum(lumUp, now);

View file

@ -269,6 +269,8 @@ internal static unsafe class FakeHost
public static bool PluginCommandCalls;
/// <summary>What SendPluginCommand answers: true = delivered (the target plugin is loaded).</summary>
public static bool PluginCommandDelivered = true;
/// <summary>When set, answers each SendPluginCommand (plugin, action, value) instead of <see cref="PluginCommandDelivered"/>.</summary>
public static Func<string, string, string, bool>? PluginCommandAnswer;
/// <summary>Every SendPluginCommand (plugin, action, value), in order.</summary>
public static readonly List<(string Plugin, string Action, string Value)> PluginCommands = new();
/// <summary>For each <see cref="PluginCommands"/> entry, how many chat lines were written before it (call order).</summary>
@ -342,7 +344,7 @@ internal static unsafe class FakeHost
CloseContainerCalls = false; Closes.Clear(); GroundContainer = 0;
SelectedItem = 0;
UseOnCalls = false; UsesOn.Clear();
PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear(); PluginCommandChatCounts.Clear();
PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommandAnswer = null; PluginCommands.Clear(); PluginCommandChatCounts.Clear();
TradeVendorCalls = false; TradeActions.Clear(); VendorSells.Clear(); VendorBuys.Clear();
CombatModeCalls = false; CombatModeRequests.Clear(); CombatModeRefuse = false; CombatModeRefusals = 0;
BusyCalls = false; ForceResets = 0; BusyStateValue = 0;
@ -648,7 +650,8 @@ internal static unsafe class FakeHost
{
PluginCommands.Add((Marshal.PtrToStringAnsi(plugin) ?? "", Marshal.PtrToStringAnsi(action) ?? "", Marshal.PtrToStringAnsi(value) ?? ""));
PluginCommandChatCounts.Add(Chat.Count);
return PluginCommandDelivered ? 1 : 0;
var (p, a, v) = PluginCommands[^1];
return (PluginCommandAnswer?.Invoke(p, a, v) ?? PluginCommandDelivered) ? 1 : 0;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]

View file

@ -70,6 +70,7 @@ internal static class Program
LootRaresModeTests.Register(runner);
LootChatLineTests.Register(runner);
ItemInfoTextColorTests.Register(runner);
ItemInfoPartColorTests.Register(runner);
LootSurveyTests.Register(runner);
PropertyDumpTests.Register(runner);
T11LootTests.Register(runner);
@ -88,6 +89,7 @@ internal static class Program
PatrolPortalTests.Register(runner);
DunRouteTests.Register(runner);
BuffTests.Register(runner);
BuffItemsTests.Register(runner);
SpellCatalogTests.Register(runner);
CombatMathTests.Register(runner);
WeaponTests.Register(runner);
@ -98,6 +100,7 @@ internal static class Program
OffhandTests.Register(runner);
HandSwapTests.Register(runner);
OutdoorHuntTests.Register(runner);
HuntOnLoginTests.Register(runner);
HuntBuildingTests.Register(runner);
FloodPerfTests.Register(runner);
LootSalvageTests.Register(runner);
@ -109,6 +112,7 @@ internal static class Program
LootNothingLineTests.Register(runner);
ChestLootTests.Register(runner);
ItemToolTests.Register(runner);
TimedCommandsTests.Register(runner);
VanishedItemTests.Register(runner);
KitUsedUpTests.Register(runner);
VitalWandGateTests.Register(runner);
@ -199,10 +203,13 @@ internal static class Program
SaveFailureTests.Register(runner);
EnvironmentImpactTests.Register(runner);
SkCombatAddonTests.Register(runner);
DirtyFightingRotationTests.Register(runner);
DoorTests.Register(runner);
ServerPolicyTests.Register(runner);
PatrolModeTests.Register(runner);
BlankLoadTests.Register(runner);
CallStateRepairTests.Register(runner);
ProfileButtonTests.Register(runner);
GiveProfileTests.Register(runner);
TinkerTests.Register(runner);
LauncherSwapTests.Register(runner);
@ -214,12 +221,14 @@ internal static class Program
TickIsolationTests.Register(runner);
ChoresInFightTests.Register(runner);
AetheriaUnboxTests.Register(runner);
AutoConfirmCraftTests.Register(runner);
CommandReplyTests.Register(runner);
MonsterStatsTests.Register(runner);
MetaSaveTests.Register(runner);
MetaResumeTests.Register(runner);
FellowOpenTests.Register(runner);
WieldBanTests.Register(runner);
ActiveGearTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -67,6 +67,9 @@
RynthAi exactly what the engine sends (engine 2026-10-13). -->
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Compatibility\PropertyWire.cs" Link="Engine\PropertyWire.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Compatibility\ObjectPropertyRecord.cs" Link="Engine\ObjectPropertyRecord.cs" />
<!-- The engine's confirmation arms (v85 one-shot, v97 sticky; pure), so the auto-confirm tests'
fake engine answers prompts by the engine's own rules (engine 2026-11-11). -->
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Compatibility\ConfirmationArmPolicy.cs" Link="Engine\ConfirmationArmPolicy.cs" />
</ItemGroup>
<ItemGroup>

View file

@ -0,0 +1,196 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Engine.UI.Sections;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.ActiveGear;
using RynthCore.Plugin.RynthAi.Huds;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The Active Gear window and /ra gear (RynthAiPlugin.ActiveGear.cs) on the fake engine: what is
// worn (the v87 tracker), each item's appraisal (spells, mana, rate, when identified), the
// player's endless enchantments, the summary line /ra gear says, Check items' identifies, and the
// window in the sections manifest without a bar button.
internal static class ActiveGearTests
{
private const uint Player = 0x50000F31, Ring = 0x80000F01, Amulet = 0x80000F02, Coat = 0x80000F03, Sword = 0x80000F04;
private const int LeftRing = 0x00040000, Neck = 0x00008000, CoatMask = 0x00000200 | 0x00000400 | 0x00000800, MeleeMask = 0x00100000;
private const uint MajorStrength = 2576, Impen = 1483;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("active gear: /ra gear says the summary and opens the window", Summary);
r.Add("active gear: /ra gear list, check (unidentified first, gently) and a wrong option", ListCheckAndUsage);
r.Add("active gear: the window is in the manifest with no bar button", Manifest);
}
private static readonly List<(string Key, int Mode)> PanelCalls = new();
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint FakeUiColor(int token) => 0xFFFFFFFF;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr FakeUiFont(int font) => IntPtr.Zero;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static unsafe int FakeSetPanelOpen(byte* key, int mode)
{
PanelCalls.Add((Marshal.PtrToStringUTF8((IntPtr)key) ?? "", mode));
return mode == 0 ? 0 : 1;
}
private static unsafe void PluginWindows(ref RynthCoreApiNative api)
{
api.Version = Math.Max(api.Version, 89u);
api.GetUiColorFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, uint>)&FakeUiColor;
api.GetUiFontFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, IntPtr>)&FakeUiFont;
api.SetPanelOpenFn = (IntPtr)(delegate* unmanaged[Cdecl]<byte*, int, int>)&FakeSetPanelOpen;
}
private sealed class Rig
{
public readonly RynthAiPlugin P = new();
public Rig()
{
FakeHost.Reset();
PanelCalls.Clear();
EquippedState.Invalidate();
FakeHost.ConfigureApi = PluginWindows;
FakeHost.EquippedCalls = true;
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.TargetCalls = true; // GetLastIdTime
FakeHost.Names[Player] = "Tester";
long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
// A ring whose cantrip is on the player: 370 mana at 0.5 a second is 12 minutes and some.
Item(Ring, "Ring of Testing", LeftRing, spells: new[] { MajorStrength }, cur: 370, max: 2000, rate: -0.5, idAt: now);
FakeHost.Enchantments.Add((MajorStrength, double.MaxValue));
// A coat out of mana.
Item(Coat, "Test Coat", CoatMask, spells: new[] { Impen }, cur: 0, max: 1000, rate: -0.2, idAt: now);
// An amulet never identified.
FakeHost.Names[Amulet] = "Test Amulet";
FakeHost.Equipped[Amulet] = Neck;
// A plain sword: identified, no spells, no mana: not listed.
FakeHost.Names[Sword] = "Plain Sword";
FakeHost.Equipped[Sword] = MeleeMask;
FakeHost.Appraised.Add(Sword);
RynthCoreHost host = FakeHost.Create(playerId: Player);
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var cache = new WorldObjectCache(host);
cache.SetPlayerId(Player);
foreach (uint id in new[] { Ring, Amulet, Coat, Sword }) _ = cache[unchecked((int)id)];
Set("_objectCache", cache);
Set("_playerId", Player);
Set("_initialized", true);
Set("_loginComplete", true);
}
private static void Item(uint id, string name, int slot, uint[] spells, int cur, int max, double rate, long idAt)
{
FakeHost.Names[id] = name;
FakeHost.Equipped[id] = unchecked((uint)slot);
FakeHost.Appraised.Add(id);
FakeHost.SpellIds[id] = spells;
FakeHost.Ints[(id, 107)] = cur;
FakeHost.Ints[(id, 108)] = max;
FakeHost.Doubles[(id, 5)] = rate;
FakeHost.IdTimes[id] = idAt;
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public object? Call(string method, params object?[] args) => typeof(RynthAiPlugin).GetMethod(method, Any)!.Invoke(P, args);
public List<string> Typed(string line)
{
int before = FakeHost.Chat.Count;
int eat = 0;
P.OnChatBarEnter(line, ref eat);
return FakeHost.Chat.Skip(before).ToList();
}
}
private static string Show(List<string> lines) => string.Join(" | ", lines);
private static void Summary()
{
var rig = new Rig();
List<string> lines = rig.Typed("/ra gear");
Check.Eq(lines.Count, 1, "one line: " + Show(lines));
Check.True(lines.Count == 1 && lines[0].Contains("1 of 3 items active, 1 unknown, off: Chest (out of mana), lowest: Left Ring 12 min"),
"the summary: " + Show(lines));
Check.True(lines.Count == 1 && lines[0].Contains("Active Gear window open"), "says the window opened: " + Show(lines));
Check.True(PanelCalls.Count > 0 && PanelCalls[^1] == (RynthAiPlugin.ActiveGearTitle, (int)RynthPanelOpen.Open), "opened by its panel key");
ActiveGearView view = rig.P.ActiveGearViewForTests;
Check.Eq(view.Rows.Length, 3, "ring, coat, amulet; the plain sword isn't listed");
Check.True(view.Rows.All(r => r.Id != unchecked((int)Sword)), "no sword row");
ActiveGearRow ring = view.Rows.Single(r => r.Id == unchecked((int)Ring));
Check.Eq(ring.Verdict.Active, GearActive.Yes, "ring on");
Check.Eq(ring.SlotName, "Left Ring", "ring slot");
Check.Eq(ActiveGearText.Mana(ring), "370 / 2,000", "ring mana");
ActiveGearRow amulet = view.Rows.Single(r => r.Id == unchecked((int)Amulet));
Check.Eq(amulet.Verdict.Active, GearActive.Unknown, "amulet unknown");
Check.Eq(ActiveGearText.Mana(amulet), "?", "amulet mana unknown");
Check.Eq(view.Rows[0].Id, unchecked((int)Coat), "armor listed first");
lines = rig.Typed("/ra gear hide");
Check.True(lines.Count == 1 && lines[0].Contains("closed"), "hide replies: " + Show(lines));
}
private static void ListCheckAndUsage()
{
var rig = new Rig();
List<string> lines = rig.Typed("/ra gear list");
Check.Eq(lines.Count, 4, "summary + 3 items: " + Show(lines));
Check.True(lines.Any(l => l.Contains("Left Ring, Ring of Testing: Yes") && l.Contains("12 min left") && l.Contains("1/1 spells on")), Show(lines));
Check.True(lines.Any(l => l.Contains("Chest, Test Coat: No (out of mana)")), Show(lines));
Check.True(lines.Any(l => l.Contains("Neck, Test Amulet: ? (not identified yet)")), Show(lines));
rig.Call("TickActiveGear"); // the worn items tracked
FakeHost.IdRequests.Clear();
lines = rig.Typed("/ra gear check");
Check.True(lines.Count == 1 && lines[0].Contains("identifying 3 worn items"), "check replies: " + Show(lines));
rig.Call("TickActiveGear");
Check.Eq(FakeHost.IdRequests.Count, 1, "one identify at a time");
Check.True(FakeHost.IdRequests.Count == 1 && FakeHost.IdRequests[0] == Amulet, "the unidentified one first");
rig.Call("TickActiveGear");
Check.Eq(FakeHost.IdRequests.Count, 1, "the next waits its 1.5 s");
lines = rig.Typed("/ra gear sideways");
Check.True(lines.Count == 1 && lines[0].Contains("unknown option") && lines[0].Contains(RynthAiPlugin.ActiveGearUsage), "usage: " + Show(lines));
// Without the object cache (before the world loads) it says why instead of an empty summary.
rig.Set("_objectCache", null);
lines = rig.Typed("/ra gear");
Check.True(lines.Count == 1 && lines[0].Contains("not in the world"), "not ready: it says why: " + Show(lines));
}
private static void Manifest()
{
string json = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, dashboard: true, monsterStats: true, activeGear: true);
SectionManifest m = SectionManifestParser.Parse("RynthAi", json, out string error);
Check.Eq(error, string.Empty, "no parse error");
Check.Eq(m.Windows.Length, 3, "dashboard, Monster Stats, Active Gear");
SectionWindowDecl w = m.Windows.Single(x => x.Id == "activegear");
Check.Eq(w.Title, RynthAiPlugin.ActiveGearTitle, "title (its panel key)");
Check.Eq(w.Surface, "window:activegear", "the surface PluginExports.RenderEmbed draws");
Check.False(w.Bar, "no bar button");
Check.False(w.TakeOver || w.Frameless, "the engine's frame");
Check.True(w.Width >= w.MinWidth && w.Height >= w.MinHeight, "sizes");
SectionManifest alone = SectionManifestParser.Parse("RynthAi",
SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, activeGear: true), out error);
Check.True(error.Length == 0 && alone.Windows.Length == 1 && alone.Windows[0].Id == "activegear", "alone");
}
}

View file

@ -0,0 +1,405 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.Json;
using RynthCore.Engine.Compatibility;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Auto-confirm crafting (a players' request, 2026-11-11: "auto confirm on 100% tinker and crafting
// chance"). RynthAi keeps the engine's sticky CraftInteraction answer armed (plugin API v97): Yes at
// the threshold, a lower chance shows AC's dialog, never a No. The fake engine here answers prompts
// with the engine's own rules (ConfirmationArmPolicy.cs, linked), two slots: the one-shot that the
// tinker runner arms per step goes first and never disturbs the sticky arm.
internal static unsafe class AutoConfirmCraftTests
{
private const uint Craft = RynthCoreHost.ConfirmationKind.CraftInteraction;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
private const uint Player = 0x50000F61;
public static void Register(Runner r)
{
r.Add("autoconfirm: on keeps a sticky Yes-at-100 arm, re-armed before it runs out; off drops it", ArmsAndReArms);
r.Add("autoconfirm: 100% is answered with one chat line; below the threshold AC's dialog shows, no line, never a No", AnswersAndLines);
r.Add("autoconfirm: the tinker runner's one-shot goes first, its disarm and re-arms never fight the sticky arm", NeverFightsTheRunner);
r.Add("autoconfirm: an engine before v97 - nothing armed, the reason in the status and the command", OldEngine);
r.Add("autoconfirm: the threshold is clamped to 50-100 and a change re-arms at once", Threshold);
r.Add("autoconfirm: logout releases the arm", Logout);
r.Add("autoconfirm: settings - off at 100 by default, saved, copied, sent to the engine face as nullable fields", Settings);
r.Add("autoconfirm: /ra autoconfirm on|off|<percent>|status always answers", Command);
}
// ── The fake engine's confirmation calls (static: function pointers can't capture) ──────────
private static ConfirmationArm _oneShot, _sticky;
private static long _now;
private static int _seq, _lastPercent = -1, _lastOutcome;
private static uint _lastType;
private static readonly List<(uint Type, int Min, int Timeout)> ArmCalls = new();
private static void ResetEngine()
{
_oneShot = default;
_sticky = default;
_now = 1_000_000;
_seq = 0;
_lastPercent = -1;
_lastOutcome = 0;
_lastType = 0;
ArmCalls.Clear();
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int FakeArm(uint type, int minPercent, int timeoutMs)
{
ArmCalls.Add((type, minPercent, timeoutMs));
return ConfirmationArmPolicy.Apply(ref _oneShot, ref _sticky, type, minPercent, timeoutMs, _now, available: true);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int FakeLast(uint* type, uint* contextId, int* percent, int* outcome, int* ageMs)
{
if (type != null) *type = _lastType;
if (contextId != null) *contextId = 0x1234;
if (percent != null) *percent = _lastPercent;
if (outcome != null) *outcome = _lastOutcome;
if (ageMs != null) *ageMs = 0;
return _seq;
}
/// <summary>The server's prompt reaches the engine; returns the outcome code (as GetLastConfirmation reports it).</summary>
private static int Prompt(int percent, uint type = Craft)
{
var v = ConfirmationArmPolicy.Decide(ref _oneShot, ref _sticky, type, percent, _now);
_seq++;
_lastType = type;
_lastPercent = percent;
_lastOutcome = v switch
{
ConfirmationArmPolicy.Verdict.Accept => RynthCoreHost.ConfirmationOutcome.Accepted,
ConfirmationArmPolicy.Verdict.Decline => RynthCoreHost.ConfirmationOutcome.Declined,
ConfirmationArmPolicy.Verdict.AcceptSticky => RynthCoreHost.ConfirmationOutcome.AcceptedSticky,
_ => RynthCoreHost.ConfirmationOutcome.Shown,
};
return _lastOutcome;
}
/// <summary>A host whose confirmation calls are the fake engine's, reporting <paramref name="version"/>.</summary>
private static RynthCoreHost Host(uint version = RynthCoreHost.CurrentApiVersion, bool calls = true)
{
FakeHost.Reset();
ResetEngine();
FakeHost.ConfigureApi = (ref RynthCoreApiNative api) =>
{
api.Version = version;
if (!calls) return;
api.ArmConfirmationFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int, int>)&FakeArm;
api.GetLastConfirmationFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, uint*, int*, int*, int*, int>)&FakeLast;
};
try { return FakeHost.Create(); }
finally { FakeHost.ConfigureApi = null; }
}
private sealed class Rig
{
public readonly LegacyUiSettings S = new() { AutoConfirmCraft = true };
public readonly List<string> Lines = new();
public readonly CraftAutoConfirm A;
public Rig(RynthCoreHost host)
{
A = new CraftAutoConfirm(() => host, () => S, Lines.Add);
}
public void Tick(long advanceMs = 0)
{
_now += advanceMs;
A.Tick(_now);
}
}
private static void ArmsAndReArms()
{
var rig = new Rig(Host());
rig.Tick();
Check.True(rig.A.Supported, "a v97 engine supports it");
Check.True(rig.A.Armed && _sticky.Armed, "on: the sticky arm is up");
Check.Eq(_sticky.MinPercent, 100, "at 100%");
Check.Eq(_sticky.Type, Craft, "for craft prompts");
Check.Eq(ArmCalls.Count, 1, "one arm call");
Check.Eq(ArmCalls[0].Min, 100 | RynthCoreHost.ConfirmationArmFlags.LeaveBelow, "with the leave-below flag");
Check.Eq(ArmCalls[0].Timeout, CraftAutoConfirm.ArmTimeoutMs, "for the arm's life");
Check.True(CraftAutoConfirm.RearmAfterMs < CraftAutoConfirm.ArmTimeoutMs / 2, "re-armed well inside its life");
Check.False(_oneShot.Armed, "the one-shot slot is not used");
for (int i = 0; i < 10; i++) rig.Tick(100);
Check.Eq(ArmCalls.Count, 1, "no call every tick");
rig.Tick(CraftAutoConfirm.RearmAfterMs);
Check.Eq(ArmCalls.Count, 2, "re-armed after RearmAfterMs");
long until = _sticky.Until;
Check.True(until - _now == CraftAutoConfirm.ArmTimeoutMs, "the re-arm pushes the timeout out");
// Ticking for ten minutes: never lapses.
bool lapsed = false;
for (int i = 0; i < 600; i++) { rig.Tick(1_000); lapsed |= !_sticky.Armed || _now > _sticky.Until; }
Check.False(lapsed, "never lapses while on");
rig.S.AutoConfirmCraft = false;
rig.Tick(100);
Check.False(_sticky.Armed, "off: the engine's sticky arm is dropped");
Check.False(rig.A.Armed, "and RynthAi knows");
Check.Eq(ArmCalls.Last().Min, RynthCoreHost.ConfirmationArmFlags.LeaveBelow, "the drop is the sticky disarm (the flag)");
Check.Eq(ArmCalls.Last().Timeout, 0, "with timeout 0");
int calls = ArmCalls.Count;
rig.Tick(CraftAutoConfirm.RearmAfterMs * 3);
Check.Eq(ArmCalls.Count, calls, "off: no more calls");
Check.Eq(rig.A.Status, "off", "status off");
rig.S.AutoConfirmCraft = true;
rig.Tick(100);
Check.True(_sticky.Armed, "on again: armed at once");
}
private static void AnswersAndLines()
{
var rig = new Rig(Host());
rig.Tick();
Check.Eq(Prompt(100), RynthCoreHost.ConfirmationOutcome.AcceptedSticky, "100%: Yes without the dialog");
rig.Tick(16);
Check.Eq(rig.Lines.Count, 1, "one chat line");
Check.Eq(rig.Lines.FirstOrDefault() ?? "", "[RynthAi] Auto-confirmed: 100% chance", "the line");
rig.Tick(16);
Check.Eq(rig.Lines.Count, 1, "said once, not every tick");
Check.Eq(Prompt(99), RynthCoreHost.ConfirmationOutcome.Shown, "99%: AC's dialog");
rig.Tick(16);
Check.Eq(rig.Lines.Count, 1, "no line for a prompt below the threshold");
Check.True(_sticky.Armed && rig.A.Armed, "still armed");
Check.Eq(Prompt(-1), RynthCoreHost.ConfirmationOutcome.Shown, "a prompt without a percent: AC's dialog");
Check.Eq(Prompt(100, RynthCoreHost.ConfirmationKind.YesNo), RynthCoreHost.ConfirmationOutcome.Shown, "another kind of prompt: AC's dialog");
rig.Tick(16);
Check.Eq(rig.Lines.Count, 1, "no line for those");
bool anyNo = false;
for (int pct = 0; pct <= 100; pct++) anyNo |= Prompt(pct) == RynthCoreHost.ConfirmationOutcome.Declined;
Check.False(anyNo, "never a No, at any chance");
Prompt(100);
rig.Tick(16);
Prompt(100);
rig.Tick(16);
Check.Eq(rig.Lines.Count, 3, "a line per confirmed craft (repeated crafts)");
Check.Eq(rig.A.AcceptedCount, 3, "counted");
// Prompts from before RynthAi was looking are not reported.
var late = new Rig(Host());
Prompt(100); // nothing armed yet: AC's dialog
_lastOutcome = RynthCoreHost.ConfirmationOutcome.AcceptedSticky; // even if it had been a sticky Yes
late.Tick();
Check.Eq(late.Lines.Count, 0, "the first look only takes the sequence number");
}
private static void NeverFightsTheRunner()
{
var host = Host();
var rig = new Rig(host);
rig.Tick();
Check.True(_sticky.Armed, "sticky arm up");
// A tinker step: TinkerRunner arms its one-shot (Yes at the tab's Min chance %, else No) for 15 s.
rig.Tick(CraftAutoConfirm.RearmAfterMs - 1_000);
Check.Eq(host.ArmConfirmation(Craft, 70, 15_000), 1, "the runner's one-shot arms");
Check.True(_oneShot.Armed && _sticky.Armed, "both armed");
// RynthAi re-arms in the middle of the step: the step's one-shot stays as the runner left it.
int calls = ArmCalls.Count;
rig.Tick(2_000);
Check.Eq(ArmCalls.Count, calls + 1, "RynthAi re-armed during the step");
Check.True(_oneShot.Armed && _oneShot.MinPercent == 70, "a sticky re-arm leaves the runner's one-shot");
Check.Eq(Prompt(60), RynthCoreHost.ConfirmationOutcome.Declined, "the step's prompt follows the runner's rule (60% under 70: No)");
rig.Tick(16);
Check.Eq(rig.Lines.Count, 0, "the runner's answer is not reported as an auto-confirm");
Check.True(_sticky.Armed, "the sticky arm is untouched");
Check.Eq(host.ArmConfirmation(Craft, 70, 15_000), 1, "next step");
Check.Eq(Prompt(100), RynthCoreHost.ConfirmationOutcome.Accepted, "the runner's Yes is its own (outcome Accepted)");
rig.Tick(16);
Check.Eq(rig.Lines.Count, 0, "still no auto-confirm line");
// The runner stops mid-step and disarms its one-shot (ArmConfirmation(type, 0, 0)).
Check.Eq(host.ArmConfirmation(Craft, 70, 15_000), 1, "a step");
Check.Eq(host.ArmConfirmation(Craft, 0, 0), 1, "the runner's disarm");
Check.False(_oneShot.Armed, "the one-shot is gone");
Check.True(_sticky.Armed, "the sticky arm is still there after the run");
rig.Tick(16);
Check.True(rig.A.Armed, "RynthAi still has it");
Check.Eq(Prompt(100), RynthCoreHost.ConfirmationOutcome.AcceptedSticky, "a hand-made 100% craft after the run: auto-confirmed");
rig.Tick(16);
Check.Eq(rig.Lines.Count, 1, "with its line");
Check.Eq(Prompt(50), RynthCoreHost.ConfirmationOutcome.Shown, "a hand-made 50% craft: AC's dialog");
// Turning it off never touches a runner's one-shot.
Check.Eq(host.ArmConfirmation(Craft, 70, 15_000), 1, "a step");
rig.S.AutoConfirmCraft = false;
rig.Tick(16);
Check.False(_sticky.Armed, "off: the sticky arm is gone");
Check.True(_oneShot.Armed && _oneShot.MinPercent == 70, "the runner's one-shot is still there");
}
private static void OldEngine()
{
foreach (uint version in new uint[] { 85, 95, 96 })
{
var rig = new Rig(Host(version));
rig.Tick();
Check.False(rig.A.Supported, $"v{version}: not supported");
Check.False(rig.A.Armed, $"v{version}: nothing armed");
Check.Eq(ArmCalls.Count, 0, $"v{version}: the engine is not called (its disarm would clear another plugin's one-shot)");
Check.True(rig.A.Status.Contains("plugin API 97"), $"v{version}: the status says why: {rig.A.Status}");
rig.S.AutoConfirmCraft = false;
rig.Tick(16);
Check.Eq(ArmCalls.Count, 0, $"v{version}: turning it off calls nothing");
}
var none = new Rig(Host(RynthCoreHost.CurrentApiVersion, calls: false));
none.Tick();
Check.False(none.A.Supported, "no confirmation calls at all: not supported");
}
private static void Threshold()
{
Check.Eq(CraftAutoConfirm.ClampPercent(0), 50, "0 -> 50");
Check.Eq(CraftAutoConfirm.ClampPercent(49), 50, "49 -> 50");
Check.Eq(CraftAutoConfirm.ClampPercent(75), 75, "75");
Check.Eq(CraftAutoConfirm.ClampPercent(150), 100, "150 -> 100");
var rig = new Rig(Host());
rig.S.AutoConfirmCraftPercent = 90;
rig.Tick();
Check.Eq(_sticky.MinPercent, 90, "armed at 90");
Check.Eq(Prompt(92), RynthCoreHost.ConfirmationOutcome.AcceptedSticky, "92% at 90: Yes");
rig.Tick(16);
Check.Eq(rig.Lines.LastOrDefault() ?? "", "[RynthAi] Auto-confirmed: 92% chance", "the line says the chance");
rig.S.AutoConfirmCraftPercent = 100;
rig.Tick(16);
Check.Eq(_sticky.MinPercent, 100, "a change re-arms at once");
rig.S.AutoConfirmCraftPercent = 10;
rig.Tick(16);
Check.Eq(_sticky.MinPercent, 50, "a saved value under 50 arms at 50");
}
private static void Logout()
{
var rig = new Rig(Host());
rig.Tick();
Check.True(_sticky.Armed, "armed");
rig.A.Release();
Check.False(_sticky.Armed, "logout drops the engine's arm");
Check.False(rig.A.Armed, "and RynthAi's");
}
private static void Settings()
{
var d = new LegacyUiSettings();
Check.False(d.AutoConfirmCraft, "off by default");
Check.Eq(d.AutoConfirmCraftPercent, 100, "100% by default");
var old = JsonSerializer.Deserialize("{\"EnableAutostack\":true}", RynthAiJsonContext.Default.LegacyUiSettings)!;
Check.False(old.AutoConfirmCraft, "a profile from before the setting: off");
Check.Eq(old.AutoConfirmCraftPercent, 100, "and 100%");
var saved = JsonSerializer.Deserialize(
JsonSerializer.Serialize(new LegacyUiSettings { AutoConfirmCraft = true, AutoConfirmCraftPercent = 80 }, RynthAiJsonContext.Default.LegacyUiSettings),
RynthAiJsonContext.Default.LegacyUiSettings)!;
Check.True(saved.AutoConfirmCraft, "on saves and loads");
Check.Eq(saved.AutoConfirmCraftPercent, 80, "the percent saves and loads");
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
var dst = new LegacyUiSettings();
copy.Invoke(null, new object[] { new LegacyUiSettings { AutoConfirmCraft = true, AutoConfirmCraftPercent = 70 }, dst });
Check.True(dst.AutoConfirmCraft, "a profile switch copies it");
Check.Eq(dst.AutoConfirmCraftPercent, 70, "and the percent");
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
Check.True(payload != null && payload.AutoConfirmCraft == null && payload.AutoConfirmCraftPercent == null, "an older engine's payload has no value");
var s = new LegacyUiSettings { AutoConfirmCraft = true, AutoConfirmCraftPercent = 90 };
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", Any)!.SetValue(dash, new LegacyAdvancedSettingsUi(s));
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
Check.True(sent != null && sent.AutoConfirmCraft == true && sent.AutoConfirmCraftPercent == 90, "sent to the engine face");
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
Check.True(s.AutoConfirmCraft, "an engine save without the fields leaves them");
Check.Eq(s.AutoConfirmCraftPercent, 90, "(the percent too)");
dash.ApplySettingsJson("{\"AutoConfirmCraft\":false,\"AutoConfirmCraftPercent\":20}");
Check.False(s.AutoConfirmCraft, "an engine save with it sets it");
Check.Eq(s.AutoConfirmCraftPercent, 50, "a percent under 50 is clamped");
}
// ── /ra autoconfirm ──────────────────────────────────────────────────────
private static (RynthAiPlugin P, LegacyUiSettings S) Plugin(uint version)
{
FakeHost.Reset();
ResetEngine();
FakeHost.Names[Player] = "Tester";
FakeHost.ConfigureApi = (ref RynthCoreApiNative api) =>
{
api.Version = version;
api.ArmConfirmationFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int, int>)&FakeArm;
api.GetLastConfirmationFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, uint*, int*, int*, int*, int>)&FakeLast;
};
try { FakeHost.Create(playerId: Player); }
finally { FakeHost.ConfigureApi = null; }
var p = new RynthAiPlugin();
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
var s = new LegacyUiSettings();
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(p, dash);
return (p, s);
}
private static string Say(RynthAiPlugin p, string line)
{
FakeHost.Chat.Clear();
typeof(RynthAiPlugin).GetMethod("HandleAutoConfirmCommand", Any)!.Invoke(p, new object[] { line.Split(' ') });
return string.Join(" | ", FakeHost.Chat);
}
private static void Command()
{
var (p, s) = Plugin(RynthCoreHost.CurrentApiVersion);
string r = Say(p, "/ra autoconfirm");
Check.True(r.Contains("Auto-confirm crafting: off"), "status (the default): off: " + r);
r = Say(p, "/ra autoconfirm on");
Check.True(s.AutoConfirmCraft, "on turns it on");
Check.True(r.Contains("on, Yes at 100% or better"), "and says the value now: " + r);
r = Say(p, "/ra autoconfirm status");
Check.True(r.Contains("on, Yes at 100%"), "status: on: " + r);
r = Say(p, "/ra autoconfirm 90%");
Check.Eq(s.AutoConfirmCraftPercent, 90, "a percent sets it");
Check.True(r.Contains("Yes at 90%"), "and says so: " + r);
r = Say(p, "/ra autoconfirm 30");
Check.Eq(s.AutoConfirmCraftPercent, 90, "30 is refused");
Check.True(r.Contains("50-100") && r.Contains("Usage"), "with the range and the usage: " + r);
r = Say(p, "/ra autoconfirm banana");
Check.True(r.Contains("unknown option") && r.Contains("Usage"), "an unknown word: why and the usage: " + r);
r = Say(p, "/ra autoconfirm off");
Check.False(s.AutoConfirmCraft, "off turns it off");
Check.True(r.Contains("off"), "and says so: " + r);
var (oldP, oldS) = Plugin(96);
r = Say(oldP, "/ra autoconfirm on");
Check.False(oldS.AutoConfirmCraft, "an older engine: on is refused");
Check.True(r.Contains("plugin API 97"), "with the reason: " + r);
r = Say(oldP, "/ra autoconfirm 90");
Check.True(r.Contains("plugin API 97") && oldS.AutoConfirmCraftPercent == 100, "a percent too, nothing changed: " + r);
r = Say(oldP, "/ra autoconfirm");
Check.True(r.Contains("plugin API 97"), "status says why: " + r);
}
}

View file

@ -0,0 +1,235 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Buff items (Use Buff Items, BuffManager.BuffItems.cs) on the fake engine: a blocked built-in is
// never used, a custom item's spell is read from the item (data id 28, else its appraisal) and its
// buff is matched against the enchantments, one with no spell is used on its repeat time, only
// pack items are used, and the lists are saved, loaded, copied and bridged like DisabledBuffs.
internal static class BuffItemsTests
{
private const uint Player = 0x50000B01;
private const uint Benediction = 0x80001001, Favor = 0x80001002, Elixir = 0x80001003, Gem = 0x80001004, Unappraised = 0x80001005;
private const uint ElixirSpell = 1; // Strength Other I: a buff with a duration in the spell catalog
private const BindingFlags Priv = BindingFlags.NonPublic | BindingFlags.Instance;
private static readonly MethodInfo TryUse = typeof(BuffManager).GetMethod("TryUseBuffItems", Priv)!;
private static readonly FieldInfo LastCheck = typeof(BuffManager).GetField("_lastBuffItemCheck", Priv)!;
public static void Register(Runner r)
{
r.Add("buff items (host): a blocked built-in isn't used, an allowed one is, only while its buff is off", BlockedBuiltIn);
r.Add("buff items (host): a custom item's spell is read from the item; its buff on/off decides", CustomItemSpell);
r.Add("buff items (host): an item with no spell is used on its repeat time; none in the pack, none used", TimerAndPack);
r.Add("buff items (host): Add selected item / add by name / an unappraised item asks for its appraisal", AddPaths);
r.Add("buff items (host): the lists default empty, save, load, copy and bridge (absent = unchanged)", ListsSetting);
}
private sealed class Rig
{
public readonly LegacyUiSettings S = new() { UseBuffItems = true, EnableBuffing = false };
public readonly BuffManager B;
public readonly RynthCoreHost Host;
public DateTime Now = new(2026, 11, 11, 12, 0, 0);
public Rig(Action? setup = null)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true; // UseObject and RequestId
FakeHost.Names[Benediction] = "Asheron's Benediction";
FakeHost.Names[Favor] = "Blackmoor's Favor";
FakeHost.Names[Elixir] = "Elixir of the Hunt";
FakeHost.Names[Gem] = "Gem of Waking";
FakeHost.DataIds[(Elixir, 28)] = ElixirSpell; // the spell its use casts (CreateObject header)
FakeHost.SpellIds[Gem] = Array.Empty<uint>(); // appraised: casts nothing
setup?.Invoke();
Host = FakeHost.Create(Player);
var skills = new CharacterSkills(Host);
skills.SetPlayerId(Player);
var sm = new SpellManager(Host, S);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
B = new BuffManager(Host, S, sm, new PlayerVitalsCache());
B.SetCharacterSkills(skills);
var ids = FakeHost.Names.Keys.ToArray();
B.SetWorldObjectCache(FakeHost.MakeCache(Host, Player, ids));
RynthClock.TestNow = () => Now;
}
/// <summary>One buff-item check, 3 s after the last one; the ids used in it.</summary>
public List<uint> Check(params uint[] enchantments)
{
FakeHost.Enchantments.Clear();
foreach (uint e in enchantments) FakeHost.Enchantments.Add((e, double.MaxValue));
Now = Now.AddSeconds(3.1);
int before = FakeHost.Uses.Count;
TryUse.Invoke(B, null);
return FakeHost.Uses.Skip(before).ToList();
}
public void Wait(double seconds) => Now = Now.AddSeconds(seconds);
}
private static void Run(Action body)
{
try { body(); }
finally { RynthClock.TestNow = null; }
}
private static void BlockedBuiltIn() => Run(() =>
{
var rig = new Rig();
rig.S.CustomBuffItems = new List<CustomBuffItem>();
rig.S.SetBuffItemAllowed("Asheron's Benediction", false, out _);
var used = rig.Check();
Check.True(used.SequenceEqual(new[] { Favor }), $"Benediction blocked: Favor is used ({string.Join(",", used.Select(u => u.ToString("X")))})");
rig.Wait(20);
used = rig.Check(3811);
Check.Eq(used.Count, 0, "Favor's buff on, Benediction blocked: nothing used");
rig.S.SetBuffItemAllowed("asheron's benediction", true, out _);
used = rig.Check(3811);
Check.True(used.SequenceEqual(new[] { Benediction }), "allowed again: Benediction is used");
rig.S.UseBuffItems = false;
rig.Wait(60);
Check.Eq(rig.Check().Count, 0, "Use Buff Items off: nothing at all");
});
private static void CustomItemSpell() => Run(() =>
{
var rig = new Rig();
rig.S.SetBuffItemAllowed("Asheron's Benediction", false, out _);
rig.S.SetBuffItemAllowed("Blackmoor's Favor", false, out _);
rig.S.AddCustomBuffItem("Elixir of the Hunt", null, out _); // by name: spells not read yet
var used = rig.Check();
Check.True(used.SequenceEqual(new[] { Elixir }), "its spell is read from the item (data id 28) and its buff is off: used");
var item = rig.S.CustomBuffItems.Single();
Check.True(item.SpellsRead && item.SpellIds.SequenceEqual(new[] { ElixirSpell }), "the spell is kept on the item (saved)");
rig.Wait(20);
Check.Eq(rig.Check(ElixirSpell).Count, 0, "its buff on: not used again");
rig.Wait(60);
Check.Eq(rig.Check(ElixirSpell).Count, 0, "still on a minute later: not used");
Check.True(rig.Check().SequenceEqual(new[] { Elixir }), "the buff ran out: used again");
item = rig.S.CustomBuffItems.Single();
rig.S.SetBuffItemAllowed(item.Name, false, out _);
rig.Wait(20);
Check.Eq(rig.Check().Count, 0, "blocked: never used");
});
private static void TimerAndPack() => Run(() =>
{
var rig = new Rig();
rig.S.SetBuffItemAllowed("Asheron's Benediction", false, out _);
rig.S.SetBuffItemAllowed("Blackmoor's Favor", false, out _);
rig.S.AddCustomBuffItem("Gem of Waking", null, out var gem);
gem!.RepeatMinutes = 30;
rig.S.AddCustomBuffItem("Potion Not Carried", null, out _);
var used = rig.Check();
Check.True(used.SequenceEqual(new[] { Gem }), "an appraised item that casts nothing: used on its timer");
var saved = rig.S.CustomBuffItems.First(c => c.Name == "Gem of Waking");
Check.True(saved.SpellsRead && saved.SpellIds.Count == 0 && saved.LastUsedUtc != null, "read as no spell; the use is kept");
Check.Eq(rig.Check().Count, 0, "3 s later: not again");
// The repeat time counts on the saved UTC time (a reload keeps it): put it 29 min back.
saved.LastUsedUtc = DateTime.UtcNow.AddMinutes(-29);
rig.Wait(20);
Check.Eq(rig.Check().Count, 0, "29 min after the last use: not yet");
saved.LastUsedUtc = DateTime.UtcNow.AddMinutes(-31);
Check.True(rig.Check().SequenceEqual(new[] { Gem }), "31 min: used again");
Check.False(FakeHost.Uses.Any(u => !FakeHost.Names.ContainsKey(u)), "nothing outside the pack was ever used");
});
private static void AddPaths() => Run(() =>
{
var rig = new Rig(() => FakeHost.Names[Unappraised] = "Odd Draught");
FakeHost.SelectedItem = Elixir;
Check.True(rig.B.AddSelectedBuffItem(out string reply), "Add selected item: added");
Check.True(reply.Contains("Elixir of the Hunt") && reply.Contains("its buff counts as on"), $"says how it is checked: {reply}");
var elixir = BuffItemRules.FindCustom(rig.S.CustomBuffItems, "elixir of the hunt");
Check.True(elixir != null && elixir.SpellsRead && elixir.SpellIds.SequenceEqual(new[] { ElixirSpell }), "with its spell");
FakeHost.SelectedItem = Benediction;
Check.False(rig.B.AddSelectedBuffItem(out reply), "a built-in is refused");
Check.True(reply.Contains("built in"), reply);
FakeHost.SelectedItem = 0;
Check.False(rig.B.AddSelectedBuffItem(out reply), "nothing selected");
Check.True(reply.Contains("nothing selected"), reply);
Check.True(rig.B.AddBuffItemByName("gem of waking", out reply), "add by name, in the pack");
Check.True(BuffItemRules.FindCustom(rig.S.CustomBuffItems, "Gem of Waking") is { SpellsRead: true, SpellIds.Count: 0 } && reply.Contains("used every"),
$"its own spelling, read as no spell: the timer ({reply})");
int idsBefore = FakeHost.IdRequests.Count;
Check.True(rig.B.AddBuffItemByName("Odd Draught", out reply), "an item with no spell header and no appraisal");
Check.True(BuffItemRules.FindCustom(rig.S.CustomBuffItems, "Odd Draught") is { SpellsRead: false }, "added with its spell not read");
Check.Eq(FakeHost.IdRequests.Count, idsBefore + 1, "its appraisal is asked for");
Check.True(reply.Contains("read from the item"), reply);
Check.True(rig.B.AddBuffItemByName("Not In My Pack", out reply), "a name not in the pack is added");
Check.True(BuffItemRules.FindCustom(rig.S.CustomBuffItems, "Not In My Pack") is { SpellsRead: false }, "spells read later");
var rows = rig.B.DescribeBuffItems();
Check.Eq(rows.Count, 3 + 4, "the list: three built-ins and four of the player's");
Check.True(rows.First(r => r.Name == "Not In My Pack").Status == "not in your pack", "a missing item says so");
Check.True(rows.First(r => r.Name == "Odd Draught").Status == "reading its spell", "the unappraised one waits");
});
private static void ListsSetting()
{
var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true,\"UseBuffItems\":true}", RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(old != null && old.BlockedBuffItems.Count == 0 && old.CustomBuffItems.Count == 0, "a profile saved before the setting: all built-ins allowed, none added");
var nul = JsonSerializer.Deserialize("{\"BlockedBuffItems\":null,\"CustomBuffItems\":null}", RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(nul != null && nul.BlockedBuffItems.Count == 0 && nul.CustomBuffItems.Count == 0, "null lists load empty");
var some = new LegacyUiSettings();
some.SetBuffItemAllowed("Blackmoor's Favor", false, out _);
some.AddCustomBuffItem("Elixir of the Hunt", new uint[] { ElixirSpell }, out var e);
e!.RepeatMinutes = 45;
e.LastUsedUtc = new DateTime(2026, 11, 11, 18, 0, 0, DateTimeKind.Utc);
some.AddCustomBuffItem("Gem of Waking", null, out _);
some.SetBuffItemAllowed("Gem of Waking", false, out _);
string json = JsonSerializer.Serialize(some, RynthAiJsonContext.Default.LegacyUiSettings);
var back = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!;
Check.True(back.BlockedBuffItems.SequenceEqual(new[] { "Blackmoor's Favor" }), "the blocked built-in is saved and loaded");
var be = BuffItemRules.FindCustom(back.CustomBuffItems, "Elixir of the Hunt");
Check.True(be != null && be.Allowed && be.SpellsRead && be.SpellIds.SequenceEqual(new[] { ElixirSpell }) && be.RepeatMinutes == 45
&& be.LastUsedUtc == e.LastUsedUtc, "a custom item with its spell, repeat time and last use");
Check.True(BuffItemRules.FindCustom(back.CustomBuffItems, "Gem of Waking") is { Allowed: false, SpellsRead: false }, "a blocked, unread one");
// Profile switch/load copies them (CopySettings is the hand-written field list).
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
var dst = new LegacyUiSettings();
copy.Invoke(null, new object[] { some, dst });
Check.True(dst.BlockedBuffItems.Count == 1 && dst.CustomBuffItems.Count == 2, "a profile with them loads them");
Check.False(ReferenceEquals(dst.CustomBuffItems[0], some.CustomBuffItems[0]), "as copies, not the other profile's objects");
copy.Invoke(null, new object[] { old!, dst });
Check.True(dst.BlockedBuffItems.Count == 0 && dst.CustomBuffItems.Count == 0, "an old profile loads none");
// The settings bridge: sent, and an engine save without the fields leaves them alone.
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
Check.True(payload != null && payload.BlockedBuffItems == null && payload.CustomBuffItems == null, "an engine payload without them has none");
var s = new LegacyUiSettings();
s.SetBuffItemAllowed("Asheron's Benediction", false, out _);
s.AddCustomBuffItem("Elixir of the Hunt", new uint[] { ElixirSpell }, out _);
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Priv)!.SetValue(dash, true);
typeof(LegacyDashboardRenderer).GetField("_settings", Priv)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", Priv)!.SetValue(dash, new LegacyAdvancedSettingsUi(s));
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
Check.True(sent?.BlockedBuffItems != null && sent.BlockedBuffItems.SequenceEqual(new[] { "Asheron's Benediction" }), "the blocked list is sent");
Check.True(sent?.CustomBuffItems is { Count: 1 } list && list[0].Name == "Elixir of the Hunt", "the custom list is sent");
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
Check.True(s.BlockedBuffItems.Count == 1 && s.CustomBuffItems.Count == 1, "a save without them leaves them alone");
dash.ApplySettingsJson("{\"BlockedBuffItems\":[],\"CustomBuffItems\":[]}");
Check.True(s.BlockedBuffItems.Count == 0 && s.CustomBuffItems.Count == 0, "a save with empty lists clears them");
}
}

View file

@ -0,0 +1,519 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-11-11: CallState rules that lost their target. Before 34b7d45e (2026-09-30) the .met parser
// left a CallState's target empty and the .af writer saved it as "CallState {} {<its own state>}"
// ("{Default}" inside a DoAll); such a rule fires, calls nothing and the meta never leaves the
// state. A load now says so in chat, and Repair from .met fills the targets and return states
// from the .met of the same name, matched by order within each state (CallStateRepair).
// Everything is written under the runner's scratch folder.
internal static class CallStateRepairTests
{
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("callstate: empty targets are found, nested DoAll ones too (an old .af as written)", Detection);
r.Add("callstate: the .met next to the .af (or above it inside MetaFiles) is found", FindsMet);
r.Add("callstate: repair by order fills targets and return states, nested ones included", RepairMatches);
r.Add("callstate: repair is refused, nothing changed, when a state's counts differ or it isn't in the .met", RepairRefused);
r.Add("callstate: a repaired meta writes and parses back with its targets and return states", RoundTrip);
r.Add("callstate: loading a broken .af warns in chat once; Repair from .met backs up, writes and reloads", LoadWarnsAndRepairs);
r.Add("callstate: without a .met the warning says so and repair changes nothing", NoMet);
r.Add("callstate: /ra meta repair replies either way", RepairCommand);
string? sample = Environment.GetEnvironmentVariable("RYNTH_CALLSTATE_SAMPLE");
if (!string.IsNullOrEmpty(sample) && Directory.Exists(sample))
r.Add("callstate: sample metas (RYNTH_CALLSTATE_SAMPLE)", () => Sample(sample));
}
// ── A hand-built VTank .met ──────────────────────────────────────────
/// <summary>One action of a .met row: VTank's action type and its data lines.</summary>
private sealed record Act(int Type, string[] Data);
private static Act Call(string to, string ret) => new(5, new[] { "TABLE", "2", "k", "v", "n", "n", "2", "s", "st", "s", to, "s", "ret", "s", ret });
private static Act Chat(string text) => new(2, new[] { "s", text });
private static Act SetState(string state) => new(1, new[] { "s", state });
private static Act DoAll(params Act[] children)
{
var data = new List<string> { "TABLE", "2", "K", "V", "n", "n", children.Length.ToString() };
foreach (Act c in children) { data.Add("i"); data.Add(c.Type.ToString()); data.AddRange(c.Data); }
return new Act(3, data.ToArray());
}
/// <summary>A .met of Always rules, one per (state, action), in this order.</summary>
private static string MetText(params (string State, Act Action)[] rows)
{
var lines = new List<string> { "1", "CondAct", "5", "CType", "AType", "CData", "AData", "State", "n", "n", "n", "n", "n", rows.Length.ToString() };
foreach (var (state, act) in rows)
{
lines.AddRange(new[] { "i", "1", "i", act.Type.ToString(), "i", "0" });
lines.AddRange(act.Data);
lines.Add("s");
lines.Add(state);
}
return string.Join("\r\n", lines) + "\r\n";
}
/// <summary>The fixture: calls at the top, inside a DoAll and inside a DoAll inside a DoAll.</summary>
private static string FixtureMet() => MetText(
("Default", SetState("20_Upper")),
("20_Upper", Chat("/vt nav load upper")),
("20_Upper", Call("90_Stone", "21_West")),
("21_West", DoAll(Chat("/ra start"), Call("90_Stone", "22_North"))),
("22_North", DoAll(Chat("/ra stop"), DoAll(Call("91_Turnin", "99_Done"), Chat("x"))) ),
("22_North", Call("90_Stone", "")), // VTank's ret empty: the calling state
("90_Stone", new Act(6, new[] { "i", "0" }))); // Return
private static string Scratch(string name)
{
string dir = Path.Combine(Program.TempRoot, "callstate", name);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
Directory.CreateDirectory(dir);
return dir;
}
private static LoadedMeta LoadMet(string name, string text)
{
string path = Path.Combine(Scratch("met-" + name), name + ".met");
File.WriteAllText(path, text);
return MetFileParser.Load(path);
}
/// <summary>
/// What an older RynthAi saved for <paramref name="met"/>: its parser left every CallState target
/// (and return state) empty, and its writer filled the return with the rule's State. Nested DoAll
/// children have State "Default" from the .met parser, so theirs came out as {Default}.
/// </summary>
private static string BrokenAfText(LoadedMeta met)
{
static void Clear(MetaRule r)
{
if (r.Action == MetaActionType.CallMetaState) { r.ActionData = ""; r.CallReturnState = ""; }
foreach (MetaRule c in r.ActionChildren) Clear(c);
}
foreach (MetaRule r in met.Rules) Clear(r);
return AfFileWriter.SaveToString(met.Rules, met.EmbeddedNavs);
}
private static List<MetaRule> Calls(IEnumerable<MetaRule> rules, string state)
=> CallStateRepair.CallStatesByState(rules).First(s => s.State == state).Calls;
// ── Tests ────────────────────────────────────────────────────────────
private static void Detection()
{
// As the older RynthAi wrote it (a top-level call, one in a DoAll, one in a DoAll in a DoAll).
LoadedMeta m = AfFileParser.LoadFromText(string.Join("\n", new[]
{
"STATE: {20_Upper} ~~ {",
"\tIF:\tAlways",
"\t\tDO:\tCallState {} {20_Upper}",
"\tIF:\tAlways",
"\t\tDO:\tCallState {90_Stone} {21_West}",
"~~ }",
"STATE: {21_West} ~~ {",
"\tIF:\tAlways",
"\t\tDO:\tDoAll",
"\t\t\t\t\tChat {/ra start}",
"\t\t\t\t\tCallState {} {Default}",
"\t\t\t\t\tDoAll",
"\t\t\t\t\t\tCallState {} {Default}",
"~~ }",
}));
Check.Eq(m.Warnings.Count, 0, "parses cleanly: " + string.Join(" | ", m.Warnings));
Check.Eq(m.Rules.Count, 3, "three rules");
Check.Eq(m.Rules[0].ActionData, "", "CallState {} reads as an empty target");
Check.True(CallStateRepair.IsEmptyTarget(m.Rules[0]), "...which is an empty target");
Check.False(CallStateRepair.IsEmptyTarget(m.Rules[1]), "a call with a target is fine");
var empty = CallStateRepair.EmptyTargets(m.Rules);
Check.Eq(string.Join(",", empty.Select(e => $"{e.State}={e.Count}")), "20_Upper=1,21_West=2", "per state, nested DoAll ones counted");
Check.Eq(CallStateRepair.CountEmpty(m.Rules), 3, "three in all");
Check.Eq(Calls(m.Rules, "21_West").Count, 2, "depth first: both nested calls");
// A target from an expression that is only spaces is still nothing to call; other actions don't count.
var rules = new List<MetaRule>
{
new() { State = "A", Action = MetaActionType.CallMetaState, ActionData = " " },
new() { State = "A", Action = MetaActionType.SetMetaState, ActionData = "" },
new() { State = "A", Action = MetaActionType.All }, // an empty DoAll
};
Check.Eq(CallStateRepair.CountEmpty(rules), 1, "blank target counts, an empty SetState or DoAll doesn't");
Check.Eq(CallStateRepair.CountEmpty(new List<MetaRule>()), 0, "no rules, nothing");
// The chat line.
string withMet = CallStateRepair.WarningLine("aeth.af", 15, @"C:\x\MetaFiles\aeth.met");
Check.True(withMet.StartsWith("[RynthAi] aeth.af: 15 CallState rules have no state to call."), "names the file and count: " + withMet);
Check.True(withMet.Contains("saved by an older RynthAi") && withMet.Contains("Load the original .met instead")
&& withMet.Contains("Repair from .met") && withMet.Contains("aeth.met"), "says why and both ways out");
string one = CallStateRepair.WarningLine("x.af", 1, null);
Check.True(one.Contains("1 CallState rule has no state"), "singular");
Check.True(one.Contains("No x.met is next to it") && !one.Contains("Repair from .met"), "no .met: says so, offers no repair: " + one);
}
private static void FindsMet()
{
string root = Scratch("find");
string metas = Path.Combine(root, "MetaFiles");
string sub = Path.Combine(metas, "Server", "Char");
Directory.CreateDirectory(sub);
string af = Path.Combine(metas, "Farm.af");
Check.Null(CallStateRepair.FindSourceMet(af), "no .met: null");
File.WriteAllText(Path.Combine(metas, "Farm.met"), "x");
Check.Eq(CallStateRepair.FindSourceMet(af), Path.Combine(metas, "Farm.met"), "next to it");
Check.True(CallStateRepair.FindSourceMet(Path.Combine(metas, "farm.AF")) is string s && s.EndsWith("Farm.met", StringComparison.OrdinalIgnoreCase), "names ignore case");
string subAf = Path.Combine(sub, "Farm.af");
Check.Eq(CallStateRepair.FindSourceMet(subAf), Path.Combine(metas, "Farm.met"), "in a subfolder of MetaFiles: MetaFiles' .met");
File.WriteAllText(Path.Combine(sub, "Farm.met"), "x");
Check.Eq(CallStateRepair.FindSourceMet(subAf), Path.Combine(sub, "Farm.met"), "its own folder first");
// Outside MetaFiles only its own folder counts (nothing above MetaFiles either).
File.WriteAllText(Path.Combine(root, "Other.met"), "x");
string outside = Path.Combine(root, "elsewhere");
Directory.CreateDirectory(outside);
Check.Null(CallStateRepair.FindSourceMet(Path.Combine(outside, "Other.af")), "not from the folder above an outside .af");
Check.Null(CallStateRepair.FindSourceMet(Path.Combine(metas, "Other.af")), "not above MetaFiles");
Check.Null(CallStateRepair.FindSourceMet(""), "no path");
}
private static void RepairMatches()
{
LoadedMeta met = LoadMet("match", FixtureMet());
Check.Eq(met.Warnings.Count, 0, ".met parses: " + string.Join(" | ", met.Warnings));
Check.Eq(met.Rules.Count, 7, "seven rules");
LoadedMeta broken = AfFileParser.LoadFromText(BrokenAfText(LoadMet("match2", FixtureMet())));
Check.Eq(CallStateRepair.CountEmpty(broken.Rules), 4, "the old .af: all four calls empty");
// What the old writer did to the return states.
Check.Eq(Calls(broken.Rules, "20_Upper")[0].CallReturnState, "20_Upper", "top level: its own state");
Check.Eq(Calls(broken.Rules, "21_West")[0].CallReturnState, "Default", "in a DoAll: Default");
CallStateRepair.Result r = CallStateRepair.Repair(broken.Rules, met.Rules);
Check.True(r.Ok, "repaired: " + r.Why);
Check.Eq(r.Filled, 4, "four filled");
Check.Eq(r.States, 3, "in three states");
Check.Eq(CallStateRepair.CountEmpty(broken.Rules), 0, "none left");
MetaRule up = Calls(broken.Rules, "20_Upper")[0];
Check.Eq(up.ActionData, "90_Stone", "top level: target");
Check.Eq(up.CallReturnState, "21_West", "top level: the .met's return state, not its own");
MetaRule west = Calls(broken.Rules, "21_West")[0];
Check.Eq(west.ActionData, "90_Stone", "in a DoAll: target");
Check.Eq(west.CallReturnState, "22_North", "in a DoAll: return state (was Default)");
var north = Calls(broken.Rules, "22_North");
Check.Eq(north.Count, 2, "22_North: two calls");
Check.Eq(north[0].ActionData + ">" + north[0].CallReturnState, "91_Turnin>99_Done", "in a DoAll in a DoAll, first in order");
Check.Eq(north[1].ActionData + ">" + north[1].CallReturnState, "90_Stone>22_North", "the .met's empty return: the calling state");
Check.True(r.Details.Any(d => d.StartsWith("22_North: 91_Turnin (return 99_Done), 90_Stone (return 22_North)")), "details name what went where: " + string.Join(" | ", r.Details));
// A call that already has a target is left alone (hand-fixed since), the rest still filled.
LoadedMeta partly = AfFileParser.LoadFromText(BrokenAfText(LoadMet("match3", FixtureMet())));
MetaRule fixedByHand = Calls(partly.Rules, "22_North")[1];
fixedByHand.ActionData = "Elsewhere";
fixedByHand.CallReturnState = "Back";
r = CallStateRepair.Repair(partly.Rules, met.Rules);
Check.True(r.Ok, "partly repaired by hand: still repairs");
Check.Eq(r.Filled, 3, "three filled");
Check.Eq(fixedByHand.ActionData + ">" + fixedByHand.CallReturnState, "Elsewhere>Back", "the hand-set one is kept");
// Nothing to do.
r = CallStateRepair.Repair(partly.Rules, met.Rules);
Check.False(r.Ok, "a second repair has nothing to do");
Check.Eq(r.Why, "no CallState rule is missing its target", "and says so");
}
private static void RepairRefused()
{
LoadedMeta met = LoadMet("refuse", FixtureMet());
// The .af lost a CallState in 22_North (edited since): that state's counts differ.
LoadedMeta af = AfFileParser.LoadFromText(BrokenAfText(LoadMet("refuse2", FixtureMet())));
af.Rules.RemoveAll(x => x.State == "22_North" && x.Action == MetaActionType.CallMetaState);
string before = AfFileWriter.SaveToString(af.Rules, af.EmbeddedNavs);
CallStateRepair.Result r = CallStateRepair.Repair(af.Rules, met.Rules);
Check.False(r.Ok, "refused");
Check.True(r.Why.Contains("state '22_North' has 1 CallState rule in the .af and 2 in the .met"), "says which state and the counts: " + r.Why);
Check.True(r.Why.Contains("nothing was changed"), "and that nothing changed");
Check.Eq(r.Filled, 0, "none filled");
Check.Eq(AfFileWriter.SaveToString(af.Rules, af.EmbeddedNavs), before, "the rules are as they were (other states too)");
Check.Eq(CallStateRepair.CountEmpty(af.Rules), 3, "the other states' calls still empty");
// More calls in the .af than in the .met.
af = AfFileParser.LoadFromText(BrokenAfText(LoadMet("refuse3", FixtureMet())));
af.Rules.Add(new MetaRule { State = "20_Upper", Condition = MetaConditionType.Always, Action = MetaActionType.CallMetaState });
r = CallStateRepair.Repair(af.Rules, met.Rules);
Check.False(r.Ok, "an extra call: refused");
Check.True(r.Why.Contains("state '20_Upper' has 2 CallState rules in the .af and 1 in the .met"), r.Why);
// A state the .met doesn't have.
af = AfFileParser.LoadFromText(BrokenAfText(LoadMet("refuse4", FixtureMet())));
foreach (MetaRule x in af.Rules.Where(x => x.State == "21_West")) x.State = "21_Renamed";
r = CallStateRepair.Repair(af.Rules, met.Rules);
Check.False(r.Ok, "a renamed state: refused");
Check.True(r.Why.Contains("state '21_Renamed' isn't in the .met"), r.Why);
Check.Eq(CallStateRepair.CountEmpty(af.Rules), 4, "nothing filled anywhere");
// The .met's own call is empty too (it came from somewhere else broken).
LoadedMeta emptyMet = LoadMet("refuse5", MetText(("A", Call("", "A"))));
var one = new List<MetaRule> { new() { State = "A", Action = MetaActionType.CallMetaState } };
r = CallStateRepair.Repair(one, emptyMet.Rules);
Check.False(r.Ok, "the .met has no target either: refused");
Check.True(r.Why.Contains("CallState 1 has no target in the .met either"), r.Why);
}
private static void RoundTrip()
{
LoadedMeta met = LoadMet("roundtrip", FixtureMet());
LoadedMeta af = AfFileParser.LoadFromText(BrokenAfText(LoadMet("roundtrip2", FixtureMet())));
Check.True(CallStateRepair.Repair(af.Rules, met.Rules).Ok, "repaired");
string text = AfFileWriter.SaveToString(af.Rules, af.EmbeddedNavs);
Check.True(text.Contains("CallState {90_Stone} {21_West}"), "written: top level");
Check.True(text.Contains("CallState {91_Turnin} {99_Done}"), "written: nested");
Check.False(text.Contains("CallState {}"), "no empty target written");
LoadedMeta back = AfFileParser.LoadFromText(text);
Check.Eq(back.Warnings.Count, 0, "parses cleanly");
Check.Eq(back.Rules.Count, af.Rules.Count, "every rule back");
Check.Eq(CallStateRepair.CountEmpty(back.Rules), 0, "no empty targets after a reload");
string Pairs(IEnumerable<MetaRule> rules) => string.Join(" | ",
CallStateRepair.CallStatesByState(rules).SelectMany(s => s.Calls.Select(c => $"{s.State}:{c.ActionData}>{c.CallReturnState}")));
Check.Eq(Pairs(back.Rules), Pairs(af.Rules), "same targets and return states");
Check.Eq(Pairs(back.Rules),
"20_Upper:90_Stone>21_West | 21_West:90_Stone>22_North | 22_North:91_Turnin>99_Done | 22_North:90_Stone>22_North",
"as in the .met");
Check.Eq(AfFileWriter.SaveToString(back.Rules, back.EmbeddedNavs), text, "writes back the same");
}
private static void LoadWarnsAndRepairs()
{
DataWriteGuard.Reset();
string metas = Path.Combine(Scratch("load"), "MetaFiles");
Directory.CreateDirectory(metas);
string metPath = Path.Combine(metas, "Tower.met");
string afPath = Path.Combine(metas, "Tower.af");
File.WriteAllText(metPath, FixtureMet());
File.WriteAllText(afPath, BrokenAfText(MetFileParser.Load(metPath)));
byte[] brokenBytes = File.ReadAllBytes(afPath);
byte[] metBytes = File.ReadAllBytes(metPath);
var log = new List<string>();
var settings = new LegacyUiSettings();
var ui = new LegacyMetaUi(settings, new List<string>()) { Log = log.Add };
Check.True(ui.LoadMacroFile(afPath), "the broken .af loads: " + ui.LastLoadStatus);
Check.Eq(ui.PendingNotices, 1, "one chat line waits");
var chat = new List<string>();
ui.DrainNotices(l => { chat.Add(l); return true; });
Check.Eq(chat.Count, 1, "one line posted");
Check.True(chat[0].StartsWith("[RynthAi] Tower.af: 4 CallState rules have no state to call.") && chat[0].Contains("Tower.met"), "the warning: " + string.Join(" / ", chat));
Check.Eq(ui.PendingNotices, 0, "nothing left");
Check.True(log.Any(l => l.Contains("state '22_North' has 2 CallState rules with no state to call")), "the log names each state: " + string.Join(" / ", log));
Check.True(log.Any(l => l.Contains("state '20_Upper' has 1 CallState rule with")), "...every one");
Check.Eq(ui.EmptyCallStatesNow(out string? found), 4, "the window sees four");
Check.Eq(found, metPath, "...and the .met to repair from");
// A refused write: the host is busy (a line it doesn't take waits for the next tick).
ui.LoadMacroFile(afPath);
int tries = 0;
ui.DrainNotices(_ => { tries++; return false; });
Check.Eq(ui.PendingNotices, 1, "a refused line waits");
ui.DrainNotices(l => { tries++; return true; });
Check.Eq(ui.PendingNotices, 0, "and goes out on a later tick");
Check.Eq(tries, 2, "offered once per tick");
// An unsaved edit in memory is not thrown away by the reload.
settings.MetaUnsaved = true;
Check.False(ui.RepairFromMet(out string reply), "refused with an unsaved edit");
Check.True(reply.StartsWith("[RynthAi] Can't repair Tower.af: your last change"), reply);
settings.MetaUnsaved = false;
settings.CurrentState = "21_West";
Check.True(ui.RepairFromMet(out reply), "repaired: " + reply);
Check.True(reply.StartsWith("[RynthAi] Repaired Tower.af: 4 CallState rules in 3 states filled from Tower.met, and loaded it again"), reply);
string[] backups = Directory.GetFiles(metas, "Tower.af.bak-*");
Check.Eq(backups.Length, 1, "one backup copy next to it");
if (backups.Length == 1)
{
Check.True(System.Text.RegularExpressions.Regex.IsMatch(Path.GetFileName(backups[0]), @"^Tower\.af\.bak-\d{8}-\d{6}$"), "named <name>.af.bak-yyyyMMdd-HHmmss: " + backups[0]);
Check.True(((ReadOnlySpan<byte>)File.ReadAllBytes(backups[0])).SequenceEqual(brokenBytes), "the backup is the file as it was");
Check.True(reply.Contains(Path.GetFileName(backups[0])), "the reply names it");
}
Check.True(((ReadOnlySpan<byte>)File.ReadAllBytes(metPath)).SequenceEqual(metBytes), "the .met is never written");
LoadedMeta onDisk = AfFileParser.Load(afPath);
Check.Eq(CallStateRepair.CountEmpty(onDisk.Rules), 0, "the .af on disk has its targets");
Check.Eq(Calls(onDisk.Rules, "21_West")[0].CallReturnState, "22_North", "...and return states");
Check.Eq(CallStateRepair.CountEmpty(settings.MetaRules), 0, "the loaded rules are the repaired ones");
Check.Eq(settings.CurrentMetaPath, afPath, "still the .af");
Check.Eq(settings.CurrentState, "Default", "loaded again: starts over");
Check.True(settings.ForceStateReset, "state reset forced");
Check.Eq(ui.PendingNotices, 0, "the reload has nothing to warn about");
Check.Eq(ui.EmptyCallStatesNow(out _), 0, "the window has nothing to repair");
Check.True(ui.StatusLine.StartsWith("[RynthAi] Repaired Tower.af"), "the status line says so");
Check.Eq(DataWriteGuard.PendingCount, 0, "no save problem reported");
// Again: nothing to do, nothing written.
DateTime stamp = File.GetLastWriteTimeUtc(afPath);
Check.False(ui.RepairFromMet(out reply), "a second repair does nothing");
Check.True(reply.StartsWith("[RynthAi] No CallState rule in Tower.af is missing its target"), reply);
Check.Eq(File.GetLastWriteTimeUtc(afPath), stamp, "not rewritten");
Check.Eq(Directory.GetFiles(metas, "Tower.af.bak-*").Length, 1, "no second backup");
// A mismatch from the window: refused, file and folder unchanged.
File.WriteAllText(afPath, BrokenAfText(MetFileParser.Load(metPath)).Replace("STATE: {22_North}", "STATE: {22_Elsewhere}"));
byte[] mismatch = File.ReadAllBytes(afPath);
Check.True(ui.LoadMacroFile(afPath), "a mismatched .af loads");
Check.False(ui.RepairFromMet(out reply), "refused");
Check.True(reply.StartsWith("[RynthAi] Can't repair Tower.af: the .met doesn't match the .af (state '22_Elsewhere' isn't in the .met)"), reply);
Check.True(((ReadOnlySpan<byte>)File.ReadAllBytes(afPath)).SequenceEqual(mismatch), "file unchanged");
Check.Eq(Directory.GetFiles(metas, "Tower.af.bak-*").Length, 1, "no backup made for a refusal");
Check.True(log.Any(l => l.Contains("refused") && l.Contains("22_Elsewhere")), "the refusal is logged");
// A .met loaded directly: nothing to check, no warning.
Check.True(ui.LoadMacroFile(metPath), "the .met loads");
Check.Eq(ui.EmptyCallStatesNow(out _), 0, "a .met has its targets");
Check.False(ui.RepairFromMet(out reply), "repair refuses a .met");
Check.True(reply.Contains("only an .af can be repaired"), reply);
}
private static void NoMet()
{
string metas = Path.Combine(Scratch("nomet"), "MetaFiles");
Directory.CreateDirectory(metas);
string afPath = Path.Combine(metas, "Lonely.af");
File.WriteAllText(afPath, BrokenAfText(LoadMet("nomet-src", FixtureMet())));
byte[] before = File.ReadAllBytes(afPath);
var settings = new LegacyUiSettings();
var ui = new LegacyMetaUi(settings, new List<string>());
Check.True(ui.LoadMacroFile(afPath), "loads");
var chat = new List<string>();
ui.DrainNotices(l => { chat.Add(l); return true; });
Check.Eq(chat.Count, 1, "one warning");
Check.True(chat.Count == 1 && chat[0].Contains("4 CallState rules have no state to call") && chat[0].Contains("No Lonely.met is next to it"), "says there's no .met: " + string.Join(" / ", chat));
Check.Eq(ui.EmptyCallStatesNow(out string? met), 4, "the window still counts them");
Check.Null(met, "...with no .met (no Repair button)");
Check.False(ui.RepairFromMet(out string reply), "repair refused");
Check.True(reply.StartsWith("[RynthAi] Can't repair Lonely.af: there is no Lonely.met next to it."), reply);
Check.True(((ReadOnlySpan<byte>)File.ReadAllBytes(afPath)).SequenceEqual(before), "file unchanged");
Check.Eq(Directory.GetFiles(metas).Length, 1, "no backup, nothing else written");
// A healthy .af: no warning at all.
string good = Path.Combine(metas, "Good.af");
File.WriteAllText(good, "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tCallState {B} {Default}\n~~ }\n");
Check.True(ui.LoadMacroFile(good), "a healthy .af loads");
Check.Eq(ui.PendingNotices, 0, "no warning for it");
}
private static void RepairCommand()
{
FakeHost.Reset();
DataWriteGuard.Reset();
string metas = Path.Combine(Scratch("command"), "MetaFiles");
Directory.CreateDirectory(metas);
string metPath = Path.Combine(metas, "Cmd.met");
string afPath = Path.Combine(metas, "Cmd.af");
File.WriteAllText(metPath, FixtureMet());
File.WriteAllText(afPath, BrokenAfText(MetFileParser.Load(metPath)));
var settings = new LegacyUiSettings();
var navFiles = new List<string>();
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
void Set(string f, object v) => typeof(LegacyDashboardRenderer).GetField(f, Any)!.SetValue(dash, v);
Set("_profileLoaded", true);
Set("_settings", settings);
Set("_host", FakeHost.Create());
Set("_metaFolder", metas);
Set("_navFiles", navFiles);
Set("_metaFiles", new List<string>());
Set("_profileListsLock", new object());
Set("_metaUi", new LegacyMetaUi(settings, navFiles));
var plugin = new RynthAiPlugin();
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi });
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(plugin, dash);
MethodInfo dispatch = typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!;
void Ra(string line)
{
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
dispatch.Invoke(plugin, new object[] { parts[1].ToLowerInvariant(), parts, 0 });
}
string Said() => string.Join(" / ", FakeHost.Chat);
Ra("/ra meta repair");
Check.True(FakeHost.Chat.Exists(l => l.Contains("Can't repair the meta: no meta is loaded")), "no meta loaded: says so: " + Said());
FakeHost.Chat.Clear();
Ra("/ra meta load Cmd");
Check.True(FakeHost.Chat.Exists(l => l.Contains("Loaded meta 'Cmd'")), "loaded: " + Said());
FakeHost.Chat.Clear();
Ra("/ra meta repair now");
Check.True(FakeHost.Chat.Exists(l => l.Contains("Usage: /ra meta repair")), "extra words: usage: " + Said());
FakeHost.Chat.Clear();
Ra("/ra meta repair");
Check.True(FakeHost.Chat.Exists(l => l.StartsWith("[RynthAi] Repaired Cmd.af: 4 CallState rules in 3 states")), "repaired: " + Said());
Check.Eq(CallStateRepair.CountEmpty(settings.MetaRules), 0, "the loaded meta has its targets");
FakeHost.Chat.Clear();
Ra("/ra meta repair");
Check.True(FakeHost.Chat.Exists(l => l.Contains("nothing to repair")), "again: nothing to repair: " + Said());
FakeHost.Chat.Clear();
Ra("/ra meta");
Check.True(FakeHost.Chat.Exists(l => l.Contains("/ra meta") && l.Contains("| repair")), "the verb list names repair: " + Said());
}
/// <summary>
/// Opt-in: a folder with real metas (copies; never the live install). For each &lt;name&gt;.af with a
/// &lt;name&gt;.met beside it, the repair must fill every empty target; when &lt;name&gt;.reference.af is
/// there too (repaired by hand), every state's CallState targets and return states must match it.
/// </summary>
private static void Sample(string dir)
{
string work = Scratch("sample");
int checkedAny = 0;
foreach (string af in Directory.GetFiles(dir, "*.af"))
{
if (af.EndsWith(".reference.af", StringComparison.OrdinalIgnoreCase)) continue;
string stem = Path.GetFileNameWithoutExtension(af);
string met = Path.Combine(dir, stem + ".met");
if (!File.Exists(met)) continue;
string copyAf = Path.Combine(work, stem + ".af");
File.Copy(af, copyAf, overwrite: true);
File.Copy(met, Path.Combine(work, stem + ".met"), overwrite: true);
var settings = new LegacyUiSettings();
var ui = new LegacyMetaUi(settings, new List<string>());
Check.True(ui.LoadMacroFile(copyAf), $"{stem}: loads");
int empty = ui.EmptyCallStatesNow(out string? found);
Check.True(empty > 0, $"{stem}: has empty CallState targets ({empty})");
Check.NotNull(found, $"{stem}: the .met is found");
Check.True(ui.RepairFromMet(out string reply), $"{stem}: {reply}");
Check.Eq(CallStateRepair.CountEmpty(AfFileParser.Load(copyAf).Rules), 0, $"{stem}: no empty target left");
Console.WriteLine(" " + reply);
string reference = Path.Combine(dir, stem + ".reference.af");
if (File.Exists(reference))
{
static string Pairs(IEnumerable<MetaRule> rules) => string.Join("\n",
CallStateRepair.CallStatesByState(rules).SelectMany(s => s.Calls.Select(c => $"{s.State}:{c.ActionData}>{c.CallReturnState}")));
Check.Eq(Pairs(AfFileParser.Load(copyAf).Rules), Pairs(AfFileParser.Load(reference).Rules), $"{stem}: matches the hand-repaired copy");
}
checkedAny++;
}
Check.True(checkedAny > 0, "found an .af with its .met in " + dir);
}
}

View file

@ -47,7 +47,11 @@ internal static class ChestLootTests
r.Add("chest loot: a salvage-only item is left when no UST is carried, as on corpses", SalvageWithoutUstLeft);
r.Add("chest loot: opened mid-fight it waits for combat, then is looted if still open", ChestWaitsForCombat);
r.Add("chest loot: an open chest is looted before a fight further than 5 yd off (a chest closes when you walk away)", OpenChestBeforeDistantFight);
r.Add("chest loot: closed by the player mid-loot -> session ends, chest not reopened", ClosedMidLootNotReopened);
r.Add("chest loot: closed mid-loot -> the looter opens it again and takes the rest", ClosedMidLootReopened);
r.Add("chest loot: a chest that keeps closing is opened again twice in a minute, then left", ReopenIsBounded);
r.Add("chest loot: a chest the player opened with the macro off is not reopened when it closes", ManualChestNotReopened);
r.Add("chest loot: an open chest that closes before the looter gets to it (a fight had the tick) is opened again", ClosedBeforeTakenReopened);
r.Add("chest loot: no jump-loot from a chest (a hop can take the character out of its use radius)", NoJumpLootFromChest);
r.Add("chest loot: a chest gets 2 minutes (not the 12 s corpse timeout), restarted by each pickup", ChestTimeoutLongAndRestarted);
}
@ -533,7 +537,13 @@ internal static class ChestLootTests
Check.False((bool)close.Call("IsOpenChestTurn", true, true)!, "a monster at the chest is fought first");
}
private static void ClosedMidLootNotReopened()
private static int ChestUses() => FakeHost.Uses.Count(u => u == Chest);
// 2026-11-12: the client closes a container once the character is outside its use radius at its
// once-a-second check (a jump-loot hop, the walk back for the next item, a step toward a monster).
// 8 of 134 chest loots in a week of logs ended that way with items left; a corpse was reopened,
// a chest was not.
private static void ClosedMidLootReopened()
{
BaseWorld();
var host = FakeHost.Create(Player);
@ -543,14 +553,138 @@ internal static class ChestLootTests
bot.TickUntil(() => bot.Moved(Gem));
Check.True(bot.Moved(Gem), "the gem's move is sent");
// The player closes it before the gem arrives.
// The chest closes before the gem arrives.
bot.ServerCloses(Chest);
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "the session ends");
bot.TickFor(300);
Check.False(FakeHost.Uses.Contains(Chest), "the chest is never reopened by the looter");
Check.Eq(bot.Get<uint>("_lastChestLootedId"), 0u, "a chest closed mid-loot doesn't count as looted");
Check.Eq(FakeHost.Closes.Count, 0, "nothing to close: it is closed already");
Check.False(bot.Marked(Chest), "and not marked: opening it again loots it");
Check.Eq(bot.Get<uint>("_lastChestLootedId"), 0u, "a chest closed mid-loot doesn't count as looted (a meta opens it again)");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("before looting finished")), "logged");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("before looting finished; opening it again (1 of 2)")), "logged");
Check.True(bot.HasLootWork(), "the chest to open again is loot work: Looting keeps the tick");
bot.Tick();
Check.Eq(ChestUses(), 0, "not at once: the close settles first");
bot.TickUntil(() => ChestUses() > 0);
Check.Eq(ChestUses(), 1, "then the looter uses the chest to open it again");
bot.TickFor(200);
Check.Eq(ChestUses(), 1, "one use, not one a tick, while it waits for the chest to open");
Check.Eq(bot.Get<int>("_targetCorpseId"), 0, "and nothing else is claimed meanwhile");
// It opens: the gem is still in it and is taken, then the chest is closed as usual.
int movesBefore = FakeHost.ExternalMoves.Count;
bot.ServerOpens(Chest);
bot.TickUntil(() => FakeHost.ExternalMoves.Count > movesBefore);
Check.True(FakeHost.ExternalMoves.Count > movesBefore, "the gem's move is sent again");
FakeHost.Containers[Gem] = Player;
bot.TickUntil(() => FakeHost.Closes.Count > 0);
Check.Eq(FakeHost.Closes.Count, 1, "closed when done");
Check.Eq(bot.Get<uint>("_lastChestLootedId"), Chest, "now it counts as looted to the end");
Check.False(bot.Moved(Spoon), "the spoon is still left");
Check.False(bot.Marked(Chest), "and the chest is still never marked");
Check.Eq(ChestUses(), 1, "no further use");
}
private static void ReopenIsBounded()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
bot.TickUntil(() => bot.Moved(Gem));
// It closes mid-loot, is opened again, and closes again: twice.
for (int round = 1; round <= RynthAiPlugin.ChestReopenMax; round++)
{
bot.ServerCloses(Chest);
bot.TickUntil(() => ChestUses() >= round);
Check.Eq(ChestUses(), round, $"close {round}: the looter opens it again");
bot.ServerOpens(Chest);
bot.TickUntil(() => bot.Get<int>("_openedContainerId") != 0);
Check.Eq(bot.Get<int>("_openedContainerId"), unchecked((int)Chest), $"close {round}: and takes it again");
}
// The third close in a minute: left alone.
bot.ServerCloses(Chest);
bot.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 400);
Check.Eq(ChestUses(), RynthAiPlugin.ChestReopenMax, "no third use");
Check.False(bot.HasLootWork(), "and nothing left to do");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("so it is left")), "logged");
}
private static void ManualChestNotReopened()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.IsMacroRunning = false; // Pickup with macro off takes the chest the player opened
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
bot.TickUntil(() => bot.Moved(Gem));
Check.True(bot.Moved(Gem), "the gem's move is sent");
bot.ServerCloses(Chest); // the player closes it
bot.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 400);
Check.Eq(ChestUses(), 0, "the player's chest is the player's to close: never reopened");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("not reopening it")), "logged as before");
}
// The 2026-11-11 20:02 case: a meta opened a cache while the looter was on a corpse; the corpse's
// open closed the cache untouched. Here a fight holds the tick instead: same thing, never taken.
private static void ClosedBeforeTakenReopened()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
bot.TickFor(150, BotActivity.Combat);
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "open, but the looter hasn't taken it");
bot.ServerCloses(Chest);
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("before the looter got to it; opening it again (1 of 2)")), "booked and logged");
bot.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 200, BotActivity.Combat);
Check.Eq(ChestUses(), 0, "no use while the fight has the tick");
bot.TickUntil(() => ChestUses() > 0);
Check.Eq(ChestUses(), 1, "used once Looting has the tick");
bot.ServerOpens(Chest);
LootGemAndFinish(bot, Gem);
Check.Eq(FakeHost.Closes.Count, 1, "looted and closed");
Check.Eq(bot.Get<uint>("_lastChestLootedId"), Chest, "and counts as looted to the end");
// Looting off: a chest that closes books nothing.
BaseWorld();
var bot2 = new Bot(FakeHost.Create(Player));
bot2.S.LootChestsMacroOff = false;
bot2.S.EnableLooting = false;
bot2.Create(Chest, Gem, Spoon);
bot2.ServerOpens(Chest);
bot2.TickFor(100);
bot2.ServerCloses(Chest);
bot2.S.EnableLooting = true;
bot2.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 300);
Check.Eq(ChestUses(), 0, "Looting was off when it closed: not reopened");
}
private static void NoJumpLootFromChest()
{
BaseWorld();
FakeHost.TapJumpCalls = true;
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.LootJumpEnabled = true;
bot.Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
bot.TickUntil(() => bot.Get<int>("_openedContainerId") != 0);
Check.False((bool)bot.Call("ShouldJumpLoot", bot.S)!, "no jump-loot while the open container is a chest");
bot.Set("_lootChestId", 0);
Check.True((bool)bot.Call("ShouldJumpLoot", bot.S)!, "control: the same state with a corpse open jumps");
bot.Set("_lootChestId", unchecked((int)Chest));
LootGemAndFinish(bot, Gem);
Check.True(bot.Moved(Gem), "the gem is taken");
Check.Eq(FakeHost.TapJumps, 0, "and no jump was sent for it");
}
}

View file

@ -96,6 +96,9 @@ internal static class CommandReplyTests
new("/ra cast 1234", "/ra cast banana", K.Act),
new("/ra targetlock off", null, K.Act),
new("/ra fightselected off", "/ra fightselected banana", K.Act),
new("/ra dfheight on", "/ra dfheight banana", K.Act),
new("/ra dfheight off", null, K.Act),
new("/ra dfheight window", null, K.Act),
new("/ra meleelow", null, K.Act),
new("/ra meleemid", null, K.Act),
new("/ra meleehigh", null, K.Act),
@ -165,11 +168,16 @@ internal static class CommandReplyTests
new(null, "/ra mstats show", K.Act), // this rig's engine has no plugin windows: says so
new("/ra aetheria off", "/ra aetheria banana", K.Act),
new(null, "/ra aetheria unbox", K.Act), // nothing coalesced in this rig's pack: says so
new("/ra autoconfirm off", "/ra autoconfirm banana", K.Act),
new(null, "/ra autoconfirm 30", K.Act), // under 50: the range and the usage
new(null, "/ra autoconfirm on", K.Act), // this rig's engine has no confirmation answers: says why
new(null, "/ra nosuchverb", K.Act),
// ── /ra: output asked for ──
new("/ra help", null, K.Query),
new("/ra aetheria", null, K.Query),
new("/ra aetheria status", null, K.Query),
new("/ra autoconfirm", null, K.Query),
new("/ra autoconfirm status", null, K.Query),
new("/ra", null, K.Query),
new("/ra version", null, K.Query),
new("/ra server", null, K.Query),
@ -198,6 +206,8 @@ internal static class CommandReplyTests
new("/ra combat", null, K.Query),
new("/ra mstats list", "/ra mstats Nobody Here At All", K.Query),
new("/ra mstats help", null, K.Query),
new("/ra dfheight status", null, K.Query),
new("/ra dfheight", null, K.Query),
new("/ra why", null, K.Query),
new("/ra ghosts", null, K.Query),
new("/ra ghost", null, K.Query),

View file

@ -0,0 +1,181 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The Dirty Fighting rotation through CombatManager (CombatManager.DirtyFighting.cs): the height each
// melee attack is sent at follows this character's "Dirty Fighting! ..." landing lines for the target
// being fought, High, then Medium, then Low, then the chosen default; with the rotation off or Dirty
// Fighting untrained the fixed Melee Attack Height goes out exactly as before. The pure choice and the
// expiry timing are RynthCore.RynthAiTests' DirtyFightingHeightTests.
internal static class DirtyFightingRotationTests
{
private const uint Player = 0x50000F71;
private const uint Lb = 0xA9B40000;
private const uint Mob = 0x80000471, Other = 0x80000472;
private const uint DfSkill = 52, HeavySkill = 44;
// The game's attack heights (what the server is sent): High 1, Medium 2, Low 3.
private const int AcHigh = 1, AcMedium = 2, AcLow = 3;
public static void Register(Runner r)
{
r.Add("dfheight rotation: High, then Medium, then Low, then the default as each effect lands", RotationFollowsLandings);
r.Add("dfheight rotation: off, or Dirty Fighting untrained, sends the fixed Melee Attack Height", FixedWhenOffOrUntrained);
r.Add("dfheight rotation: a landing on another monster, or by someone else, isn't counted", OtherLandingsIgnored);
r.Add("dfheight rotation: the settings ride the Settings bridge; a sender without them leaves them alone", SettingsBridge);
}
private sealed class Rig
{
public readonly LegacyUiSettings S;
public readonly CombatManager C;
public Rig(Action<LegacyUiSettings> set, int dfTraining = 2)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.AttackSendCalls = true;
FakeHost.CombatModeValue = CombatMode.Melee;
Place(Player, "Me", 96, 96, creature: false);
Place(Mob, "Drudge Skulker", 96, 99);
Place(Other, "Drudge Slinker", 110, 110);
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
FakeHost.HeadingDeg = 0;
FakeHost.Skills[(Player, DfSkill)] = (300, dfTraining);
FakeHost.Skills[(Player, HeavySkill)] = (300, 3);
S = new LegacyUiSettings { MonsterRange = 50, IsMacroRunning = true, EnableCombat = true, MeleeAttackHeight = 1 };
set(S);
var host = FakeHost.Create(Player);
var cache = FakeHost.MakeCache(host, Player, new[] { Mob, Other });
C = new CombatManager(host, S, cache);
C.SetPlayerId(Player);
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
C.SetCharacterSkills(skills);
C.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
C.ScanNearbyTargets();
C.HandleCombatTrigger();
FakeHost.AttackCalls.Clear();
}
/// <summary>Thinks until an attack reaches the server; its height (-1 if none in 30 ticks).</summary>
public int NextHeight()
{
int before = FakeHost.AttackCalls.Count;
for (int i = 0; i < 30 && FakeHost.AttackCalls.Count == before; i++)
{
LastAttackCmd.SetValue(C, DateTime.MinValue);
C.Think();
}
return FakeHost.AttackCalls.Count > before ? FakeHost.AttackCalls[^1].Height : -1;
}
private static readonly FieldInfo LastAttackCmd = typeof(CombatManager).GetField("lastAttackCmd", BindingFlags.NonPublic | BindingFlags.Instance)!;
}
private static void Place(uint id, string name, float x, float y, bool creature = true)
{
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f);
if (creature) FakeHost.ItemTypes[id] = 0x10;
}
private static string Landing(string spell, string target = "Drudge Skulker", string who = "Me") =>
$"Dirty Fighting! {who} delivers a {spell} to {target}!";
private static void RotationFollowsLandings()
{
var rig = new Rig(s => { s.DfHeightRotation = true; s.DfDefaultHeight = 0; }); // then Low
Check.Eq(rig.NextHeight(), AcHigh, "a fresh target: High first");
Check.Eq(rig.NextHeight(), AcHigh, "nothing landed yet: High again");
rig.C.NoteDirtyFightingChat(Landing("Blinding Blow"));
rig.C.NoteDirtyFightingChat(Landing("Traumatic Blow"));
Check.Eq(rig.NextHeight(), AcMedium, "High's effects landed: Medium for the bleed");
rig.C.NoteDirtyFightingChat(Landing("Bleeding Blow"));
Check.Eq(rig.NextHeight(), AcLow, "bleeding: Low next");
rig.C.NoteDirtyFightingChat(Landing("Unbalancing Blow"));
Check.Eq(rig.NextHeight(), AcLow, "all three on: the default (Low)");
var toFixed = new Rig(s => { s.DfHeightRotation = true; s.DfDefaultHeight = -1; s.MeleeAttackHeight = 2; s.DfHeightOrder = "LMH"; });
Check.Eq(toFixed.NextHeight(), AcLow, "order LMH: Low first");
toFixed.C.NoteDirtyFightingChat(Landing("Unbalancing Assault"));
toFixed.C.NoteDirtyFightingChat(Landing("Bleeding Assault"));
toFixed.C.NoteDirtyFightingChat(Landing("Blinding Assault"));
Check.Eq(toFixed.NextHeight(), AcHigh, "all on, default = the Melee Attack Height (High)");
Check.True(FakeHost.Logs.Any(l => l.Contains("[DFHeight]") && l.Contains("landed on")), "landings are logged");
string status = toFixed.C.DirtyFightingStatus();
Check.True(status.Contains("Target 'Drudge Skulker'") && status.Contains("Low 20 s"), "status shows the target's effects: " + status);
Check.True(status.Contains("about 25% per hit"), "status shows the chance: " + status);
}
private static void FixedWhenOffOrUntrained()
{
var off = new Rig(s => { s.DfHeightRotation = false; s.MeleeAttackHeight = 0; });
Check.Eq(off.NextHeight(), AcLow, "rotation off: the fixed height (Low)");
off.C.NoteDirtyFightingChat(Landing("Unbalancing Blow"));
Check.Eq(off.NextHeight(), AcLow, "rotation off: landings change nothing");
Check.False(FakeHost.Logs.Any(l => l.Contains("attacking")), "rotation off: no height choice logged");
var untrained = new Rig(s => { s.DfHeightRotation = true; s.MeleeAttackHeight = 1; }, dfTraining: 1);
Check.Eq(untrained.NextHeight(), AcMedium, "Dirty Fighting untrained: the fixed height (Medium)");
Check.True(untrained.C.DirtyFightingStatus().Contains("not trained"), "status says it isn't trained");
}
private static void OtherLandingsIgnored()
{
var rig = new Rig(s => { s.DfHeightRotation = true; s.DfDefaultHeight = 0; });
Check.Eq(rig.NextHeight(), AcHigh, "High first");
rig.C.NoteDirtyFightingChat(Landing("Blinding Blow", target: "Drudge Slinker"));
Check.Eq(rig.NextHeight(), AcHigh, "a landing on a monster not being fought: still High");
rig.C.NoteDirtyFightingChat(Landing("Blinding Blow", who: "Someone Else"));
Check.Eq(rig.NextHeight(), AcHigh, "another attacker's landing: still High");
rig.C.NoteDirtyFightingChat(Landing("Blinding Blow", target: "Me", who: "Drudge Skulker"));
Check.Eq(rig.NextHeight(), AcHigh, "the monster's landing on this character: still High");
rig.C.NoteDirtyFightingChat("Someone says, \"" + Landing("Blinding Blow") + "\"");
Check.Eq(rig.NextHeight(), AcHigh, "the words said in chat: still High");
}
/// <summary>A dashboard stand-in with its profile in memory (as SkCombatAddonTests builds one).</summary>
private static LegacyDashboardRenderer Dash(LegacyUiSettings s)
{
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(dash, true);
typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)!
.SetValue(dash, new LegacyAdvancedSettingsUi(s));
return dash;
}
private static void SettingsBridge()
{
var s = new LegacyUiSettings { DfHeightRotation = true, DfHeightOrder = "MLH", DfDefaultHeight = 2 };
var dash = Dash(s);
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!;
Check.True(sent.DfHeightRotation == true && sent.DfHeightOrder == "MLH" && sent.DfDefaultHeight == 2,
"the bridge carries the three settings");
dash.ApplySettingsJson("{\"HealAt\":50}");
Check.True(s.DfHeightRotation, "a sender without them: rotation kept");
Check.Eq(s.DfHeightOrder, "MLH", "order kept");
Check.Eq(s.DfDefaultHeight, 2, "default kept");
dash.ApplySettingsJson("{\"DfHeightRotation\":false,\"DfHeightOrder\":\"bad\",\"DfDefaultHeight\":9}");
Check.False(s.DfHeightRotation, "rotation set off");
Check.Eq(s.DfHeightOrder, "HML", "a bad order normalizes to HML");
Check.Eq(s.DfDefaultHeight, 2, "an out-of-range default is clamped");
var fresh = new LegacyUiSettings();
Check.False(fresh.DfHeightRotation, "off by default");
Check.Eq(fresh.DfHeightOrder, "HML", "High, Medium, Low by default");
Check.Eq(fresh.DfDefaultHeight, -1, "default height = the Attack Height setting");
}
}

View file

@ -44,6 +44,12 @@ internal static class HandSwapTests
r.Add("a monster with the wand in hand: peace, the Sceptre out, both Hand Wraps on, then Melee (no client use)", FightFromWand);
r.Add("a monster with the wand in hand, burst: the Sceptre out and both Hand Wraps on in one tick", FightFromWandBurst);
r.Add("a monster with the wand in hand: a fight swap that fails leaves that weapon to the client's own swap", FightSwapFallsBack);
r.Add("wand to wand (hunt report 11-07): the next monster's caster goes in through peace, then Magic (no client use, no bare-hands stance)", WandToWandFromMagic);
r.Add("wand to wand from peace (Peace Mode When Idle between targets): the old caster out, the new one in, then Magic; no peace request", WandToWandFromPeace);
r.Add("wand to wand: the swap tracker records the swap (no swap straight back for the same fight)", WandToWandTracked);
r.Add("WandSwapRules.UseHandsSwap: a swap away from a caster goes through peace, a caster wanted too", UseHandsSwapRules);
r.Add("WandSwapRules.EquipCastHoldMs: the first cast waits for the stance after a wield, never past the old 3 s", EquipCastHoldRules);
r.Add("equip gate: held while the stance settles, then the cast goes; one log line per wield", EquipGateHolds);
r.Add("weapons back burst: peace, the Sceptre out and both Hand Wraps on in one tick, then Melee", RearmBurst);
r.Add("weapons back burst: the quiet check reads BuffManager's mode change, not combat's late one (Drakkon 23:06-23:21)", RearmBurstQuietFromBuff);
r.Add("Fast Weapon Swap: on by default, an old saved off (the opt-in name) loads on, an untick since stays off", OnByDefault);
@ -522,7 +528,7 @@ internal static class HandSwapTests
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!;
public double SimMs;
public CombatRig(bool putCalls = false)
public CombatRig(bool putCalls = false, bool secondWand = false)
{
FakeHost.Reset();
FakeHost.PutCalls = putCalls;
@ -531,7 +537,7 @@ internal static class HandSwapTests
FakeHost.EquippedCalls = true;
FakeHost.CombatModeCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
foreach (var (id, name, type, slots) in new[] { (Acid, "Acid Hand Wraps", 0x1u, Melee), (Frost, "Frost Hand Wraps", 0x1u, Melee), (Sceptre, "Sceptre", 0x8000u, Held) })
foreach (var (id, name, type, slots) in new[] { (Acid, "Acid Hand Wraps", 0x1u, Melee), (Frost, "Frost Hand Wraps", 0x1u, Melee), (Sceptre, "Sceptre", 0x8000u, Held), (OtherWand, "Fire Wand", 0x8000u, Held) })
{
FakeHost.Names[id] = name; FakeHost.ItemTypes[id] = type; FakeHost.Ints[(id, 9)] = slots;
}
@ -543,7 +549,8 @@ internal static class HandSwapTests
new() { Id = I(Frost), Name = "Frost Hand Wraps", Element = "", ElementSource = "", Action = "Weapon" },
new() { Id = I(Sceptre), Name = "Sceptre", Element = "", ElementSource = "", Action = "Weapon" },
};
var cache = FakeHost.MakeCache(host, Player, new[] { Acid, Frost, Sceptre });
if (secondWand) S.ItemRules.Add(new() { Id = I(OtherWand), Name = "Fire Wand", Element = "Fire", ElementSource = "", Action = "Weapon" });
var cache = FakeHost.MakeCache(host, Player, secondWand ? new[] { Acid, Frost, Sceptre, OtherWand } : new[] { Acid, Frost, Sceptre });
C = new CombatManager(host, S, cache);
C.SetPlayerId(Player);
C.OpenPackOverride = () => I(Player);
@ -683,6 +690,139 @@ internal static class HandSwapTests
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
}
// ── Caster to caster (2026-11-11, WandSwapRules) ──────────────────────────
/// <summary>A wand fight: the Sceptre in hand, the Default rule's weapon the Fire Wand, war magic usable.</summary>
private static CombatRig WandFightRig(bool fromPeace)
{
var rig = new CombatRig(secondWand: true);
rig.C.CanCastOverride = _ => true;
rig.S.MonsterRules = new List<MonsterRule> { new() { Name = "Default", WeaponId = I(OtherWand) } };
rig.C.LastVitalCastAt = () => DateTime.MinValue; // no weapons back pending
rig.C.SwapBurstEnabled = () => false;
if (fromPeace) FakeHost.CombatModeValue = CombatMode.NonCombat;
rig.Fighting();
return rig;
}
private static string Trail() => string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("[EquipDiag]")).TakeLast(20));
private static void WandToWandFromMagic()
{
try
{
var rig = WandFightRig(fromPeace: false);
double ready = rig.Fight(3000);
Check.True(ready > 0, "ready to cast within 3 s: " + Trail());
Check.False(FakeHost.Uses.Any(), "no use (the client's own use of a caster in Magic plays a forced change to bare hands): "
+ string.Join(",", FakeHost.Uses.Select(u => $"{u:X8}")));
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1,8", "peace, then Magic; nothing else");
Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0].Id == Sceptre, "the Sceptre into the pack");
Check.True(FakeHost.Wields.Count == 1 && FakeHost.Wields[0] == (OtherWand, (uint)Held),
"the Fire Wand into the Held slot: " + string.Join(", ", FakeHost.Wields.Select(w => $"{w.Id:X8}@{w.Mask:X}")));
Check.True(rig.Logged("weapons for the fight in hand"), "the swap's time and steps are logged: " + Trail());
Check.True(rig.Logged("weapons for the fight: Magic mode"), "the Magic request is logged: " + Trail());
Check.Eq(FakeHost.CombatModeValue, CombatMode.Magic, "in Magic mode");
Check.True(ready <= 1000, $"ready {ready:0} ms in (one peace leg and one Magic leg)");
Console.WriteLine($" (simulated: caster to caster, ready to cast {ready:0} ms in)");
Check.Eq(rig.Gate.HeldBy, "", "the gate is free");
}
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
}
private static void WandToWandFromPeace()
{
try
{
var rig = WandFightRig(fromPeace: true);
double ready = rig.Fight(3000);
Check.True(ready > 0, "ready to cast within 3 s: " + Trail());
Check.False(FakeHost.Uses.Any(), "no use");
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", "Magic once the Fire Wand is in (no Magic beside the use, no peace)");
Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0].Id == Sceptre, "the Sceptre into the pack (answered at once in peace)");
Check.True(FakeHost.Wields.Count == 1 && FakeHost.Wields[0] == (OtherWand, (uint)Held), "the Fire Wand into the Held slot");
Check.True(ready <= 900, $"ready {ready:0} ms in");
Check.Eq(rig.Gate.HeldBy, "", "the gate is free");
}
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
}
private static void WandToWandTracked()
{
try
{
var rig = WandFightRig(fromPeace: false);
Check.True(rig.Fight(3000) > 0, "the swap finished: " + Trail());
var step = rig.C.SwapTracker.Next(I(Sceptre), I(OtherWand), RynthClock.Now, forKey: rig.Target.Id);
Check.Eq(step, WeaponSwapTracker.Step.Hold, "the Sceptre straight back for the same fight: held");
Check.Eq(rig.C.SwapTracker.HoldReason, "just swapped away from it", "as for the client's own use");
}
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
}
private static void UseHandsSwapRules()
{
const int MagicKind = CombatMode.Magic, MeleeKind = CombatMode.Melee;
Check.True(WandSwapRules.UseHandsSwap(true, true, 1, 2, MagicKind), "a caster in hand, another weapon wanted (a caster or not): through peace");
Check.False(WandSwapRules.UseHandsSwap(false, true, 1, 2, MagicKind), "Fast Weapon Swap off: the old route");
Check.False(WandSwapRules.UseHandsSwap(true, false, 1, 2, MagicKind), "the swap tracker held it: no swap");
Check.False(WandSwapRules.UseHandsSwap(true, true, 1, 1, MagicKind), "the wanted caster is in hand: no swap");
Check.False(WandSwapRules.UseHandsSwap(true, true, 0, 2, 0), "nothing in hand: combat's own wield");
Check.False(WandSwapRules.UseHandsSwap(true, true, 1, 2, MeleeKind), "a melee weapon in hand: combat's own swap, as before");
Check.False(WandSwapRules.UseHandsSwap(true, true, 1, 0, MagicKind), "nothing chosen");
}
private static void EquipCastHoldRules()
{
static double H(double equip, double change, double request) => WandSwapRules.EquipCastHoldMs(equip, change, request);
Check.Eq(H(-1, -1, -1), 0.0, "no wield seen: no wait");
Check.Eq(H(3000, -1, -1), 0.0, "the old 3 s are up: no wait");
Check.Eq(H(500, 4000, -1), 2500.0, "no stance change seen since the wield: the old wait (the client may not have caught up)");
Check.Eq(H(500, -1, -1), 2500.0, "never a stance change seen: the old wait");
Check.Eq(H(800, 100, -1), 200.0, "the server's own change to Magic 100 ms ago: 300 ms after it");
Check.Eq(H(800, 400, -1), 200.0, "Magic read for 400 ms, the wield 800 ms ago: 1 s after the wield");
Check.Eq(H(1100, 400, -1), 0.0, "1.1 s after the wield, Magic read for 400 ms: cast now");
Check.Eq(H(800, 400, 600), 400.0, "our own Magic request 600 ms ago: 1 s after it");
Check.Eq(H(1200, 400, 1100), 0.0, "request 1.1 s ago, Magic read for 400 ms: cast now");
Check.Eq(H(800, 400, 900), 200.0, "a stance request from before the wield doesn't count: 1 s after the wield");
Check.Eq(H(2900, 50, 60), 100.0, "never past the old 3 s");
}
private static void EquipGateHolds()
{
try
{
var rig = WandFightRig(fromPeace: false);
const System.Reflection.BindingFlags NP = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
var holds = typeof(CombatManager).GetMethod("EquipCastHoldsNow", NP)!;
void Set(string field, DateTime v) => typeof(CombatManager).GetField(field, NP)!.SetValue(rig.C, v);
bool Held() => (bool)typeof(CombatManager).GetField("_equipGateHeld", NP)!.GetValue(rig.C)!;
bool Holds() => (bool)holds.Invoke(rig.C, null)!;
int Lines() => FakeHost.Logs.Count(l => l.Contains("[CombatCast] equip-gate"));
DateTime now = RynthClock.Now;
Set("_lastEquipTime", now.AddMilliseconds(-700));
Set("_cmModeChangedAt", now.AddMilliseconds(-100)); // the client read Magic 100 ms ago
Set("lastStanceAttempt", now.AddMilliseconds(-600)); // our Magic request 600 ms ago
Check.True(Holds(), "held: the stance is still settling");
Check.True(Held(), "the tick is marked held (not an attack)");
Holds();
Check.Eq(Lines(), 1, "one line per wield");
Set("_lastEquipTime", now.AddMilliseconds(-1500));
Set("_cmModeChangedAt", now.AddMilliseconds(-400));
Set("lastStanceAttempt", now.AddMilliseconds(-1200));
Check.False(Holds(), "Magic read for 400 ms, 1.2 s after the request: the cast goes (the old gate: 1.5 s more)");
Set("_cmModeChangedAt", now.AddSeconds(-20)); // combat's own read is old...
rig.C.LastModeChangeAt = () => now.AddMilliseconds(-400); // ...BuffManager's every-heartbeat read is fresh
Check.False(Holds(), "the freshest mode-change read counts");
rig.C.LastModeChangeAt = null;
Check.True(Holds(), "no change seen since the wield: the old 3 s");
Check.Eq(Lines(), 2, "a new wield, a new line");
}
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
}
private static void RearmThroughPeace()
{
try

View file

@ -0,0 +1,161 @@
using System;
using System.Reflection;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Hunt On Login (2026-11-11): the Outdoor Hunt starts once the character is in the world, as Patrol On
// Login starts the Dungeon Patrol. One or the other; the same checks as the Hunt button.
internal static class HuntOnLoginTests
{
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("hunt on login: Patrol On Login and Hunt On Login are one choice; both on: the one that fits the place", Choice);
r.Add("hunt on login: the start checks run in order, each only once the ones before passed; chat says why", StartChecks);
r.Add("hunt on login: no position or no RynthNav at login: it doesn't start, says why (Hunt On Login), the macro stays off", LoginRefused);
r.Add("hunt on login: /ra hunt login answers, sets it, clears Patrol On Login, and says why not with the usage", Command);
r.Add("hunt on login: HuntOnLogin round-trips (saved, copied, engine payload); the engine ticking Patrol On Login clears it", Setting);
}
private static void Choice()
{
Check.Eq(LoginAutoStart.Choose(false, false, false), LoginAutoStart.Start.None, "neither: nothing");
Check.Eq(LoginAutoStart.Choose(true, false, false), LoginAutoStart.Start.Patrol, "patrol only: the patrol (it says why itself outdoors)");
Check.Eq(LoginAutoStart.Choose(false, true, true), LoginAutoStart.Start.Hunt, "hunt only: the hunt (it says why itself in a dungeon)");
Check.Eq(LoginAutoStart.Choose(true, true, true), LoginAutoStart.Start.Patrol, "both, in a dungeon: the patrol");
Check.Eq(LoginAutoStart.Choose(true, true, false), LoginAutoStart.Start.Hunt, "both, outdoors: the hunt");
Check.Eq(LoginAutoStart.Exclusive(false, false, false, true), (false, true), "hunt ticked");
Check.Eq(LoginAutoStart.Exclusive(true, false, true, true), (false, true), "hunt ticked clears patrol");
Check.Eq(LoginAutoStart.Exclusive(false, true, true, true), (true, false), "patrol ticked clears hunt");
Check.Eq(LoginAutoStart.Exclusive(true, false, false, false), (false, false), "patrol unticked: hunt stays off");
Check.Eq(LoginAutoStart.Exclusive(true, true, true, false), (true, false), "hunt unticked: patrol stays as it was");
Check.Eq(LoginAutoStart.Exclusive(false, false, true, true), (true, false), "both ticked in one change: the patrol");
Check.Eq(LoginAutoStart.Exclusive(true, true, true, true), (true, true), "nothing changed: left as it is");
}
private static void StartChecks()
{
int asked = 0;
Func<bool> Yes() => () => { asked++; return true; };
Func<bool> No() => () => { asked++; return false; };
Check.Eq(OutdoorHunt.WhyNoStart(false, true, Yes(), Yes(), Yes()), OutdoorHunt.StartBlock.NoSettings, "no settings first");
Check.Eq(OutdoorHunt.WhyNoStart(true, false, Yes(), Yes(), Yes()), OutdoorHunt.StartBlock.NoPosition, "then a position");
Check.Eq(asked, 0, "nothing else asked before those pass");
Check.Eq(OutdoorHunt.WhyNoStart(true, true, Yes(), Yes(), Yes()), OutdoorHunt.StartBlock.InDungeon, "then the dungeon");
Check.Eq(asked, 1, "only the dungeon asked");
asked = 0;
Check.Eq(OutdoorHunt.WhyNoStart(true, true, No(), Yes(), Yes()), OutdoorHunt.StartBlock.UnknownBuilding, "then the building");
Check.Eq(asked, 2, "RynthNav not asked");
Check.Eq(OutdoorHunt.WhyNoStart(true, true, No(), No(), Yes()), OutdoorHunt.StartBlock.NoRynthNav, "then RynthNav");
Check.Eq(OutdoorHunt.WhyNoStart(true, true, No(), No(), No()), OutdoorHunt.StartBlock.None, "all passed: it can start");
foreach (OutdoorHunt.StartBlock b in Enum.GetValues(typeof(OutdoorHunt.StartBlock)))
Check.True(b == OutdoorHunt.StartBlock.None ? OutdoorHunt.StartBlockText(b).Length == 0 : OutdoorHunt.StartBlockText(b).Length > 10,
$"{b}: a reason in words");
Check.True(OutdoorHunt.StartBlockText(OutdoorHunt.StartBlock.NoRynthNav).Contains("RynthNav"), "no RynthNav says so");
}
private static (RynthAiPlugin P, LegacyDashboardRenderer Dash, Action<string> Ra, Func<string> All) Rig()
{
FakeHost.Reset();
var host = FakeHost.Create();
var p = new RynthAiPlugin();
typeof(RynthCore.PluginCore.RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
var dash = new LegacyDashboardRenderer(host);
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(p, dash);
var chat = FakeHost.Chat;
void Ra(string line)
{
chat.Clear();
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(p, new object[] { parts[1].ToLowerInvariant(), parts, 0 });
}
return (p, dash, Ra, () => string.Join(" | ", chat));
}
private static void LoginRefused()
{
var (p, dash, _, All) = Rig();
var start = typeof(RynthAiPlugin).GetMethod("StartHunt", Any)!;
FakeHost.HasPose = false;
FakeHost.Chat.Clear();
start.Invoke(p, new object[] { true });
Check.False(p.HuntActive, "no position: not started");
Check.True(All().Contains(RynthAiPlugin.HuntOnLoginRefusedPrefix.Trim()) && All().Contains("no position yet"), "says Hunt On Login and why: " + All());
// Outdoors, with a position, but no RynthNav on this host: the Hunt button's own check refuses it.
FakeHost.HasPose = true;
FakeHost.PlayerPose = (0xA9B40021u, 100f, 100f, 50f);
FakeHost.Chat.Clear();
start.Invoke(p, new object[] { true });
Check.False(p.HuntActive, "no RynthNav: not started");
Check.False(dash.Settings.IsMacroRunning, "and the macro isn't turned on");
Check.True(All().Contains("Hunt On Login") && All().Contains("needs RynthNav"), "says why: " + All());
// The Hunt button's own wording is unchanged.
FakeHost.Chat.Clear();
start.Invoke(p, new object[] { false });
Check.True(All().StartsWith("[RynthAi] Outdoor hunt needs RynthNav") && !All().Contains("Hunt On Login"), "the button says it as before: " + All());
}
private static void Command()
{
var (_, dash, Ra, All) = Rig();
var s = dash.Settings;
Ra("/ra hunt login");
Check.True(All().Contains("Hunt On Login: off") && All().Contains(RynthAiPlugin.HuntLoginUsage), "no word: off, and the usage: " + All());
s.PatrolOnLogin = true;
Ra("/ra hunt login on");
Check.True(s.HuntOnLogin && !s.PatrolOnLogin, "on, and Patrol On Login off");
Check.True(All().Contains("Hunt On Login set: on") && All().Contains("Patrol On Login is off now"), "and says both: " + All());
Ra("/ra hunt login on");
Check.False(All().Contains("Patrol On Login is off now"), "patrol was already off: not said again: " + All());
Ra("/ra hunt login maybe");
Check.True(s.HuntOnLogin, "an unknown word changes nothing");
Check.True(All().Contains("isn't on or off") && All().Contains("on now") && All().Contains("Usage: " + RynthAiPlugin.HuntLoginUsage),
"why, what it is, the usage: " + All());
Ra("/ra hunt login off");
Check.True(!s.HuntOnLogin && !s.PatrolOnLogin, "off; patrol stays off");
Check.True(All().Contains("Hunt On Login set: off"), "and says so: " + All());
Ra("/ra hunt nonsense");
Check.True(All().Contains(RynthAiPlugin.HuntLoginUsage), "the hunt's usage lists it: " + All());
}
private static void Setting()
{
Check.False(new LegacyUiSettings().HuntOnLogin, "off by default");
var ctx = RynthAiJsonContext.Default.LegacyUiSettings;
var saved = JsonSerializer.Deserialize(JsonSerializer.Serialize(new LegacyUiSettings { HuntOnLogin = true }, ctx), ctx)!;
Check.True(saved.HuntOnLogin, "saved");
var live = new LegacyUiSettings();
typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)!
.Invoke(null, new object[] { saved, live });
Check.True(live.HuntOnLogin, "copied");
var old = JsonSerializer.Deserialize("{\"PatrolOnLogin\":true}", ctx)!;
Check.True(old.PatrolOnLogin && !old.HuntOnLogin, "a profile from before the setting: off, its patrol kept");
var s = new LegacyUiSettings { HuntOnLogin = true };
var dash = (LegacyDashboardRenderer)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic;
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", F)!.SetValue(dash, true);
typeof(LegacyDashboardRenderer).GetField("_settings", F)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", F)!.SetValue(dash, new LegacyAdvancedSettingsUi(s));
string json = dash.BuildSettingsJson();
using (var doc = JsonDocument.Parse(json))
Check.True(doc.RootElement.TryGetProperty("HuntOnLogin", out var he) && he.GetBoolean(), "sent to the engine as \"HuntOnLogin\"");
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
Check.True(s.HuntOnLogin && !s.PatrolOnLogin, "an engine without it leaves it alone");
dash.ApplySettingsJson("{\"PatrolOnLogin\":true}");
Check.True(s.PatrolOnLogin && !s.HuntOnLogin, "the engine ticking Patrol On Login clears Hunt On Login");
dash.ApplySettingsJson("{\"HuntOnLogin\":true}");
Check.True(s.HuntOnLogin && !s.PatrolOnLogin, "HuntOnLogin sent: on, and Patrol On Login off");
dash.ApplySettingsJson("{\"HuntOnLogin\":false}");
Check.True(!s.HuntOnLogin && !s.PatrolOnLogin, "and off");
}
}

View file

@ -0,0 +1,301 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.ItemInfo;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-11-11, a player asked for the one-line item info with each part (name, set, damage,
// spells, value ...) in its own colour. "Colour each part" sends the parts' ranges just before the
// line (SendPluginCommand "RynthCore.Chat" nextspans, engine UI/Data/ChatOwnColors.cs), after the
// whole-line Info text colour, so an engine without runs still shows the line in that colour.
internal static class ItemInfoPartColorTests
{
private const uint Player = 0x50000E52;
private const uint Sword = 0x80266101;
private const uint ItemTypeMelee = 0x1;
private const string Target = "RynthCore.Chat";
private const string Prefix = "[RynthAi Item] ";
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("item info parts: off by default, nothing asked, the line as before", DefaultOff);
r.Add("item info parts: on, one-line: the ranges asked for just before the line", OneLine);
r.Add("item info parts: with Info text colour, the colour first and then the ranges", WithTextColor);
r.Add("item info parts: the pet-style layout is left alone", PetLayout);
r.Add("item info parts: an engine without runs is asked once; the line keeps one colour", OlderEngine);
r.Add("item info parts: a refused payload is logged, not taken for an older engine", RefusedPayload);
r.Add("item info parts: the Test button", TestButton);
r.Add("item info parts: saved with the profile, reset, the settings map, /ra iteminfo parts", Settings);
}
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new();
public Bot(RynthCoreHost host)
{
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
Set("_dashboard", dash);
var cache = new WorldObjectCache(host);
cache.SetPlayerId(Player);
Set("_objectCache", cache);
Set("_playerId", Player);
cache.OnCreateObject(Sword);
cache.OnCreateObject(Player);
cache.Tick();
S.ItemInfoSettings.Layout = MagItemInfoSettings.LayoutOneLine;
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public void Call(string method, params object[] args) => typeof(RynthAiPlugin).GetMethod(method, Any, null,
args.Select(a => a.GetType()).ToArray(), null)!.Invoke(P, args);
public void Print() => Call("PrintItemInfo", unchecked((int)Sword), true);
public void Cmd(params string[] words) => Call("HandleItemInfoCommand", new object[] { new[] { "ra", "iteminfo" }.Concat(words).ToArray() });
}
/// <summary>A gold long sword with a set, a spell, damage, workmanship, value and burden.</summary>
private static Bot World(Func<string, string, string, bool>? answer = null)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.PluginCommandCalls = true;
FakeHost.PluginCommandAnswer = answer;
FakeHost.Names[Player] = "Colour Tester";
FakeHost.Names[Sword] = "Long Sword";
FakeHost.ItemTypes[Sword] = ItemTypeMelee;
FakeHost.Containers[Sword] = Player;
foreach (var (k, v) in new (uint, int)[] { (1, (int)ItemTypeMelee), (19, 9000), (5, 300), (131, 60), (105, 6), (353, 2), (45, 1), (44, 236), (265, 13) })
FakeHost.Ints[(Sword, k)] = v;
FakeHost.SpellIds[Sword] = new[] { (uint)SpellDatabase.GetIdByName("Legendary Blood Thirst") };
FakeHost.Appraised.Add(Sword);
var bot = new Bot(FakeHost.Create(Player));
bot.S.ItemInfoSettings.ShowValueAndBurden = true;
return bot;
}
private static List<int> ItemLines() =>
Enumerable.Range(0, FakeHost.Chat.Count).Where(i => FakeHost.Chat[i].StartsWith(Prefix, StringComparison.Ordinal)).ToList();
private static List<int> Asks(string action) =>
Enumerable.Range(0, FakeHost.PluginCommands.Count)
.Where(i => FakeHost.PluginCommands[i].Plugin == Target && FakeHost.PluginCommands[i].Action == action).ToList();
private static string All() => string.Join(" | ", FakeHost.Chat) + " || " + string.Join(" | ", FakeHost.PluginCommands);
/// <summary>The payload's ranges as (text, colour) in <paramref name="line"/>; null if a range doesn't fit.</summary>
private static List<(string Text, string Color)>? Read(string payload, string line)
{
var list = new List<(string, string)>();
foreach (string run in payload.Split(';'))
{
string[] f = run.Split(':');
if (f.Length != 3) return null;
int start = int.Parse(f[0]), len = int.Parse(f[1]);
if (start < 0 || len < 1 || start + len > line.Length) return null;
list.Add((line.Substring(start, len), "#" + f[2]));
}
return list;
}
private static void DefaultOff()
{
Check.False(new MagItemInfoSettings().PartColors, "off by default");
Bot bot = World();
bot.Print();
Check.Eq(ItemLines().Count, 1, "one line: " + All());
Check.Eq(FakeHost.PluginCommands.Count, 0, "nothing sent to the engine");
}
private static void OneLine()
{
Bot bot = World();
bot.Print();
string plain = FakeHost.Chat[ItemLines().Single()];
bot = World();
bot.S.ItemInfoSettings.PartColors = true;
bot.Print();
List<int> lines = ItemLines();
Check.Eq(lines.Count, 1, "one line: " + All());
string line = FakeHost.Chat[lines[0]];
Check.Eq(line, plain, "the same text as without part colours");
Check.Eq(FakeHost.ChatTypes[lines[0]], 1, "in its chat type");
List<int> asks = Asks("nextspans");
Check.Eq(asks.Count, 1, "the ranges asked for once: " + All());
Check.Eq(Asks("nextcolor").Count, 0, "no Info text colour set: no nextcolor");
if (asks.Count != 1) return;
Check.Eq(FakeHost.PluginCommandChatCounts[asks[0]], lines[0], "just before the line");
var runs = Read(FakeHost.PluginCommands[asks[0]].Value, line);
Check.NotNull(runs, "every range inside the line: " + FakeHost.PluginCommands[asks[0]].Value);
if (runs == null) return;
Check.True(runs[0].Text.StartsWith("Gold Long Sword", StringComparison.Ordinal), "the first range is the name: " + runs[0].Text);
Check.Eq(runs[0].Color, ItemInfoPartColors.ColorOf(ItemInfoPart.Name), "in the name's colour");
Check.True(runs.Any(r => r.Text == "Legendary Blood Thirst" && r.Color == ItemInfoPartColors.ColorOf(ItemInfoPart.Spells)), "the spell in the spells' colour: " + string.Join(" | ", runs));
Check.True(runs.Any(r => r.Text == "Craft 6" && r.Color == ItemInfoPartColors.ColorOf(ItemInfoPart.Craft)), "workmanship in its colour");
Check.True(runs.Any(r => r.Text == "Value 9,000, BU 300" && r.Color == ItemInfoPartColors.ColorOf(ItemInfoPart.ValueBurden)), "value and burden, one range");
Check.True(runs.Any(r => r.Color == ItemInfoPartColors.ColorOf(ItemInfoPart.Set)), "the set in its colour");
Check.True(runs.All(r => !r.Text.StartsWith("[RynthAi", StringComparison.Ordinal)), "the prefix keeps the line's colour");
}
private static void WithTextColor()
{
Bot bot = World();
bot.S.ItemInfoSettings.PartColors = true;
bot.S.ItemInfoSettings.TextColor = "#EE921E";
bot.Print();
int line = ItemLines().Single();
List<int> colours = Asks("nextcolor"), spans = Asks("nextspans");
Check.Eq(colours.Count, 1, "the whole-line colour once: " + All());
Check.Eq(spans.Count, 1, "the ranges once");
if (colours.Count == 1 && spans.Count == 1)
{
Check.True(colours[0] < spans[0], "the colour first (an engine without runs still uses it)");
Check.Eq(FakeHost.PluginCommands[colours[0]].Value, "#EE921E", "the Info text colour");
Check.Eq(FakeHost.PluginCommandChatCounts[spans[0]], line, "both just before the line");
}
}
private static void PetLayout()
{
Bot bot = World();
bot.S.ItemInfoSettings.PartColors = true;
bot.S.ItemInfoSettings.Layout = MagItemInfoSettings.LayoutPetLines;
bot.Print();
Check.True(ItemLines().Count >= 2, "pet-style lines: " + All());
Check.Eq(Asks("nextspans").Count, 0, "no ranges for them");
}
private static void OlderEngine()
{
// An engine from 2026-11-05..11-10: "nextcolor" yes, "nextspans" (and its "none") no.
Bot bot = World((p, a, v) => p == Target && a == "nextcolor");
bot.S.ItemInfoSettings.PartColors = true;
bot.S.ItemInfoSettings.TextColor = "#EE921E";
bot.Print();
bot.Print();
Check.Eq(ItemLines().Count, 2, "both lines written: " + All());
Check.Eq(Asks("nextcolor").Count, 2, "each still in the Info text colour");
List<int> spans = Asks("nextspans");
Check.Eq(spans.Count, 2, "asked once, plus the \"none\" that tells why");
if (spans.Count == 2) Check.Eq(FakeHost.PluginCommands[spans[1]].Value, "none", "the second ask is \"none\"");
Check.True(Asks("nextcolor").All(i => FakeHost.PluginCommandChatCounts[i] == 0 || FakeHost.PluginCommandChatCounts[i] == ItemLines()[1]),
"the colour asked for just before each line");
// An engine before 2026-11-05 (no "RynthCore.Chat" at all): nextcolor refused, no runs asked.
bot = World((p, a, v) => false);
bot.S.ItemInfoSettings.PartColors = true;
bot.S.ItemInfoSettings.TextColor = "#EE921E";
bot.Print();
bot.Print();
Check.Eq(ItemLines().Count, 2, "both lines written");
Check.Eq(Asks("nextcolor").Count, 1, "the colour asked once");
Check.Eq(Asks("nextspans").Count, 0, "no runs asked of an engine without line colours");
// Same, with no Info text colour: the ranges are asked once (and "none"), then never.
bot = World((p, a, v) => false);
bot.S.ItemInfoSettings.PartColors = true;
bot.Print();
bot.Print();
Check.Eq(ItemLines().Count, 2, "both lines written (the chat type's colour)");
Check.Eq(Asks("nextspans").Count, 2, "asked once, plus \"none\"");
}
private static void RefusedPayload()
{
// The engine knows "nextspans" but refuses this payload: logged, still on for the next line.
Bot bot = World((p, a, v) => a != "nextspans" || v == "none");
bot.S.ItemInfoSettings.PartColors = true;
bot.Print();
bot.Print();
Check.Eq(ItemLines().Count, 2, "both lines written: " + All());
Check.Eq(Asks("nextspans").Count, 4, "each line asks (and \"none\"): not taken for an older engine");
}
private static void TestButton()
{
Bot bot = World();
bot.S.ItemInfoSettings.PartColors = true;
bot.Call("TestItemInfoPartColors");
string line = FakeHost.Chat.LastOrDefault() ?? "";
Check.True(line.StartsWith(Prefix + "Name, Set, ", StringComparison.Ordinal), "a sample line naming the parts: " + line);
Check.Eq(FakeHost.ChatTypes.LastOrDefault(), 1, "in the Item Info chat type");
List<int> spans = Asks("nextspans");
Check.Eq(spans.Count, 1, "with the ranges: " + All());
if (spans.Count != 1) return;
var runs = Read(FakeHost.PluginCommands[spans[0]].Value, line);
Check.NotNull(runs, "inside the line");
if (runs == null) return;
Check.Eq(runs.Count, ItemInfoPartColors.Defaults.Length, "one per part");
Check.True(runs.Select(r => r.Text).SequenceEqual(ItemInfoPartColors.Defaults.Select(d => d.Label)), "each part's label");
Check.True(runs.Select(r => r.Color).SequenceEqual(ItemInfoPartColors.Defaults.Select(d => d.Color)), "in its colour");
}
private static void Settings()
{
var saved = new LegacyUiSettings();
saved.ItemInfoSettings.PartColors = true;
string json = JsonSerializer.Serialize(saved, RynthAiJsonContext.Default.LegacyUiSettings);
var live = new LegacyUiSettings();
typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.Static | Any)!
.Invoke(null, new object[] { JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!, live });
Check.True(live.ItemInfoSettings.PartColors, "survives a save and load");
Check.Eq(JsonSerializer.Serialize(live, RynthAiJsonContext.Default.LegacyUiSettings), json, "and saves back unchanged");
var doc = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject();
var info = doc[doc.Select(kv => kv.Key).Single(k => k.Equals("ItemInfoSettings", StringComparison.OrdinalIgnoreCase))]!.AsObject();
string? key = info.Select(kv => kv.Key).SingleOrDefault(k => k.Equals("PartColors", StringComparison.OrdinalIgnoreCase));
Check.True(key != null, "the field is in the profile JSON");
if (key != null) info.Remove(key);
var old = new LegacyUiSettings();
typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.Static | Any)!
.Invoke(null, new object[] { JsonSerializer.Deserialize(doc.ToJsonString(), RynthAiJsonContext.Default.LegacyUiSettings)!, old });
Check.False(old.ItemInfoSettings.PartColors, "a profile without it: off");
var s = new MagItemInfoSettings { PartColors = true };
s.ResetToDefaults();
Check.False(s.PartColors, "reset: off");
var mapSettings = new LegacyUiSettings();
var e = ExpressionTests.Engine(settings: mapSettings);
e.Evaluate("rasetsetting[ItemInfoPartColors, 1]");
Check.True(mapSettings.ItemInfoSettings.PartColors, "set through the settings map");
Check.Eq(e.Evaluate("ragetsetting[ItemInfoPartColors]"), "1", "map reads it");
e.Evaluate("rasetsetting[ItemInfoPartColors, 0]");
Check.False(mapSettings.ItemInfoSettings.PartColors, "off through the map");
Bot bot = World();
bot.Cmd("parts", "on");
Check.True(bot.S.ItemInfoSettings.PartColors, "/ra iteminfo parts on");
Check.True(FakeHost.Chat.Any(c => c == "[RynthAi] Item info colour per part: ON"), "replies with the value: " + All());
FakeHost.Chat.Clear();
bot.Cmd("parts");
Check.True(FakeHost.Chat.Any(c => c == "[RynthAi] Item info colour per part: ON"), "no argument: says the value now");
FakeHost.Chat.Clear();
bot.Cmd("parts", "maybe");
Check.True(bot.S.ItemInfoSettings.PartColors, "a bad argument changes nothing");
Check.True(FakeHost.Chat.Any(c => c == "[RynthAi] Usage: /ra iteminfo parts on|off"), "and gets the usage: " + All());
FakeHost.Chat.Clear();
bot.S.ItemInfoSettings.Layout = MagItemInfoSettings.LayoutPetLines;
bot.Cmd("parts", "on");
Check.True(FakeHost.Chat.Any(c => c.Contains("the one-line layout only")), "on with the pet layout: says it needs the one-line layout");
FakeHost.Chat.Clear();
bot.Cmd("parts", "off");
Check.False(bot.S.ItemInfoSettings.PartColors, "/ra iteminfo parts off");
Check.True(FakeHost.Chat.Any(c => c == "[RynthAi] Item info colour per part: OFF"), "replies off");
}
}

View file

@ -64,7 +64,7 @@ internal static class LootCorpseTests
r.Add("corpse close: an abandoned open corpse is closed once", AbandonedCorpseClosed);
r.Add("corpse close: stopping the macro mid-loot closes the open corpse, not marked completed", MacroStopClosesCorpse);
r.Add("loot pacing: a pickup waits for the last bend-down, and no retry is timed while it plays", PickupWaitsForAnimation);
r.Add("loot: a pack that takes none of an item's tries is left out; the item tries another, else looting stops", RefusingPackIsLeftOut);
r.Add("loot: the main pack, the only place loot can go, takes none of an item's tries: judged full, the item given up, and one item's mark goes with it", RefusingPackIsLeftOut);
r.Add("loot pacing: no pickup (first or retry) while the server owes an answer to a cast; it goes on the UseDone", PickupWaitsForCastAnswer);
r.Add("corpse close: not while the last item is between the corpse and the pack - it closes once the item is in the inventory", CloseWaitsForInventory);
r.Add("loot pacing: an item merged into a stack in the pack is confirmed without the 4 s arrival wait", MergedPickupConfirmedQuickly);
@ -981,7 +981,7 @@ internal static class LootCorpseTests
int seen = 0;
var refuseAt = new List<long>();
long end = Environment.TickCount64 + 6000;
while (Environment.TickCount64 < end && !FakeHost.Logs.Any(l => l.Contains("no pack has a free slot")))
while (Environment.TickCount64 < end && !FakeHost.Logs.Any(l => l.Contains("pickup failed")))
{
for (; seen < FakeHost.ExternalMoves.Count; seen++)
if (FakeHost.ExternalMoves[seen].Id == Gem) refuseAt.Add(Environment.TickCount64 + 800);
@ -993,12 +993,19 @@ internal static class LootCorpseTests
bot.Tick(BotActivity.Looting);
Thread.Sleep(10);
}
// 2026-11-12: loot goes only to the main pack (the client takes nothing from a corpse straight
// into a side pack), so one item refused there may be the server refusing the item (a pickup
// timer), not the pack: it is given up and its mark goes with it. A second item refused
// there keeps the mark (LootRetryTimingTests.FullMainPackRefusals).
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 3, "three tries into the main pack, each after the last one's refusal");
Check.True(FakeHost.ExternalMoves.Where(m => m.Id == Gem).All(m => m.Target == Player), "all into the main pack");
Check.True(FakeHost.Logs.Any(l => l.Contains("took none of 3 tries") && l.Contains("trying another pack")), "the refusing pack is left out, said once");
Check.True(FakeHost.Logs.Any(l => l.Contains("no pack has a free slot")), "no other pack: the corpse is left");
Check.True(FakeHost.Chat.Any(l => l.Contains("Pack full")), "and the player is told");
Check.False(FakeHost.Logs.Any(l => l.Contains("pickup failed")), "not three more wasted tries into the same pack");
Check.True(FakeHost.Logs.Any(l => l.Contains("the main pack took none of 3 tries") && l.Contains("treating it as full") && l.Contains("nowhere else to put it")),
"the refusing pack is judged full, and there is nowhere else to go, said once");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("took none of 3 tries")), 1, "said once");
Check.True(FakeHost.Logs.Any(l => l.Contains("pickup failed for")), "the gem is given up after its three tries, not sent round again");
Check.True(FakeHost.Logs.Any(l => l.Contains("the only place loot can go")), "one item's refusals: its mark goes with it");
Check.False(bot.Get<RynthCore.Plugin.RynthAi.Loot.PackRefusals>("_packRefusals").IsRefused(unchecked((int)Player), Environment.TickCount64),
"so the main pack is not left out for the next item");
}
// A pickup sent while Bloodstone Bolt VII was unanswered came back

View file

@ -41,8 +41,9 @@ internal static class LootRetryTimingTests
public static void Register(Runner r)
{
r.Add("loot retry (R-20261029-122319-321f): with 1.7 s answers no move is resent while one is out, no pack is marked full, every item lands", SlowServerNoFalseFull);
r.Add("loot retry (R-20261029-122319-321f): a full main pack's refusals after the pickup count as tries (no free resends) and mark it full; the items go to the side pack", FullMainPackRefusals);
r.Add("loot retry (R-20261029-122319-321f): unanswered moves are retried only after the answer wait; their pack marks end with the item, the next item starts fresh", UnansweredMovesDontPoison);
r.Add("loot retry (R-20261029-122319-321f): a full main pack's refusals after the pickup count as tries (no free resends); a second item refused there keeps it marked full; nothing goes to a side pack", FullMainPackRefusals);
r.Add("loot retry (R-20261029-122319-321f): unanswered moves are retried only after the answer wait, three tries, then given up (no side-pack round); their pack marks end with the item, the next item starts fresh", UnansweredMovesDontPoison);
r.Add("loot pickup, main pack full (2026-11-12 'You must first pick up the Silver Pea'): a pea joins the stack you carry, a gem is left at once with one chat line, nothing is aimed at a side pack, the corpse completes", FullMainPackPeaJoinsGemLeft);
r.Add("loot retry (R-20261029-122319-321f): an item that lands late, after its pack was given up on, un-marks that pack", LateLandingUnmarks);
r.Add("loot retry (R-20261029-122319-321f): a refusal on arrival is 'too busy' (free resend), one after the pickup is the pack's answer", RefusalTiming);
r.Add("loot retry (R-20261029-122319-321f): the answer wait grows with the server's measured answers, within 4-8 s", AnswerWaitAdapts);
@ -390,17 +391,22 @@ internal static class LootRetryTimingTests
Run(bot, () => bot.Completed, 60_000);
// The real client takes nothing from a corpse straight into a side pack ("You must first pick
// up the X", nothing sent, 2026-11-12), so the main pack is the only place to try.
var mapMoves = FakeHost.ExternalMoves.Where(m => m.Id == Map).ToList();
Check.Eq(mapMoves.Count(m => m.Target == Player), 3, "three tries into the main pack (each refused after the pickup ran), no free resends");
Check.False(Logged("as too busy"), "a refusal after the pickup is not taken for 'too busy'");
Check.True(Logged("the main pack took none of 3 tries") && Logged("the server refused 3 after the pickup ran") && Logged("treating it as full"),
"the main pack is judged full on the server's refusals");
Check.True(mapMoves.Last().Target == SidePack && sim.Landed.Any(l => l.Id == Map && l.Pack == SidePack), "then the map goes into the side pack and lands");
Check.True(FakeHost.ExternalMoves.Where(m => m.Id == G2).All(m => m.Target == SidePack), "the next item goes straight to the side pack");
Check.True(sim.Landed.Any(l => l.Id == G2), "and lands");
Check.True(bot.Refusals.IsConfirmed(unchecked((int)Player), _now), "the main pack stays marked (confirmed by the server)");
Check.False(bot.Refusals.IsRefused(unchecked((int)SidePack), _now), "the side pack is not marked");
Check.True(Logged("pickup failed for 0x80263111"), "then the map is given up: there is nowhere else to put it");
Check.True(Logged("the only place loot can go") && Logged("no longer treated as full (unless another item is refused there too)"),
"one item's refusals alone could be the item's, not the pack's: its mark goes with it");
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == G2 && m.Target == Player), 3, "the next item tries the main pack too, and is refused three times");
Check.True(bot.Refusals.IsConfirmed(unchecked((int)Player), _now), "a second item refused there: the main pack stays marked (it is the pack)");
Check.True(FakeHost.ExternalMoves.All(m => m.Target != SidePack), "no move ever goes to the side pack");
Check.False(sim.Landed.Any(), "nothing lands: the server's main pack is full");
Check.Eq(sim.LocalRefused, 0, "no move sent while another was unanswered");
Check.True(bot.Completed, "the corpse completes");
});
// ── 3. Moves the server never answers ─────────────────────────────────────
@ -415,13 +421,14 @@ internal static class LootRetryTimingTests
var sends = Run(bot, () => bot.Completed, 90_000).Where(s => s.Id == Lost).ToList();
var lostMoves = FakeHost.ExternalMoves.Where(m => m.Id == Lost).ToList();
Check.Eq(lostMoves.Count, 6, "three tries into the main pack, three into the side pack");
Check.Eq(lostMoves.Count, 3, "three tries into the main pack, and no round into the side pack (the client refuses that from a corpse)");
Check.True(lostMoves.All(m => m.Target == Player), "all of them into the main pack");
var gaps = sends.Zip(sends.Skip(1), (a, b) => b.At - a.At).ToList();
Check.True(gaps.Count > 0 && gaps.All(g => g >= RynthAiPlugin.PickupAnswerWaitMinMs - TickMs),
$"each retry only after the answer wait ({string.Join(", ", gaps)} ms)");
Check.True(Logged("trying another pack for this item only"), "the main pack is left out for this item only");
Check.False(Logged("trying another pack"), "no other pack to try");
Check.False(Logged("treating it as full"), "no pack is judged full on unanswered tries");
Check.True(Logged("pickup failed for 0x80263121"), "the item is given up after the second round");
Check.True(Logged("pickup failed for 0x80263121"), "the item is given up after its three tries");
Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now), "the main pack's mark ended with the item");
Check.False(bot.Refusals.IsRefused(unchecked((int)SidePack), _now), "so did the side pack's");
Check.True(FakeHost.ExternalMoves.Where(m => m.Id == Next).All(m => m.Target == Player), "the next item goes into the main pack again");
@ -430,24 +437,72 @@ internal static class LootRetryTimingTests
Check.False(Logged("no pack has a free slot"), "looting does not stop for want of a pack");
});
// ── 3b. The main pack is full by the client's own count ───────────────────
// 2026-11-12, Drakkon on DreamWeave (and R-20261112-110130-5d71): the main pack filled at 07:35,
// the looter aimed every pickup at a side pack, the client refused each one ("You must first
// pick up the Silver Pea", nothing sent), and each item waited out 3 + 3 unanswered tries and
// was left: 48 peas and maps in two hours, the bot stuck on one corpse after another.
private static void FullMainPackPeaJoinsGemLeft() => Clocked(() =>
{
const uint Gem = 0x80263171, Pea = 0x80263172, PeaStack = 0x80263173, JunkBase = 0x80264000;
World(sidePack: true, Gem, Pea);
FakeHost.Names[Pea] = "Silver Pea";
FakeHost.Ints[(Pea, 11)] = 100; // MaxStackSize
FakeHost.Ints[(Pea, 12)] = 1; // StackCount
FakeHost.Names[PeaStack] = "Silver Pea"; // the stack you carry, in the side pack
FakeHost.ItemTypes[PeaStack] = ItemTypeGem;
FakeHost.Ints[(PeaStack, 11)] = 100;
FakeHost.Ints[(PeaStack, 12)] = 40;
FakeHost.Containers[PeaStack] = SidePack;
var ids = new List<uint> { Gem, Pea, PeaStack };
for (uint i = 0; i < 102; i++) // a full main pack
{
uint j = JunkBase + i;
FakeHost.Names[j] = $"Junk {i}";
FakeHost.ItemTypes[j] = 0x80;
FakeHost.Containers[j] = Player;
ids.Add(j);
}
var sim = new SlowAce();
var bot = Open(sim, sidePack: true, ids.ToArray());
long started = _now;
Run(bot, () => bot.Completed, 60_000);
Check.True(FakeHost.ExternalMoves.All(m => m.Target != SidePack), "no pickup is aimed at the side pack (the client would refuse it)");
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 0, "the gem is not sent at all: the main pack has no slot and it joins no stack");
Check.True(Logged("leaving 'Gem 113' 0x80263171") && Logged("the main pack is full"), "the gem is left, and the log says why");
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Pea), 1, "the pea is sent once");
Check.True(FakeHost.ExternalMoves.Where(m => m.Id == Pea).All(m => m.Target == Player), "aimed at the main pack: the client joins it to your stack");
Check.True(sim.Landed.Any(l => l.Id == Pea), "and it lands");
Check.Eq(FakeHost.Chat.Count(c => c.Contains("Main pack full")), 1, "one chat line says the main pack is full and loot is left");
Check.False(Logged("pickup failed"), "nothing is waited out and given up");
Check.False(Logged("no pack has a free slot"), "and looting doesn't stop: the side pack has room");
Check.True(bot.Completed, "the corpse completes");
Check.True(_now - started < 10_000, $"quickly ({_now - started} ms), not after 3 + 3 tries per item");
});
// ── 4. A late landing ─────────────────────────────────────────────────────
private static void LateLandingUnmarks() => Clocked(() =>
{
const uint Slow = 0x80263131, Next = 0x80263132;
World(sidePack: true, Slow, Next);
// One item: with no side-pack round (the client takes nothing from a corpse straight into one)
// it is given up at its third unanswered try, before the late answer; a second item would be
// the server's next pickup then and the late one would be refused as too busy.
const uint Slow = 0x80263131;
World(sidePack: true, Slow);
var sim = new SlowAce();
sim.Lag[Slow] = 12_500; // a lag spike: the server takes up the first move 12.5 s late
var bot = Open(sim, sidePack: true, Slow, Next);
var bot = Open(sim, sidePack: true, Slow);
Run(bot, () => bot.Completed, 90_000);
Run(bot, () => bot.Completed && sim.Landed.Any(l => l.Id == Slow), 90_000);
Run(bot, () => Logged("after it was given up"), 3_000);
Check.True(sim.Landed.Any(l => l.Id == Slow && l.Pack == Player), "the first move lands in the main pack, late");
Check.True(Logged("trying another pack for this item only"), "after three unanswered tries the main pack was left out for the item");
Check.True(Logged("0x80263131 landed in the main pack; it has room after all and is no longer treated as full"), "the late landing un-marks the main pack");
Check.True(Logged("pickup failed for 0x80263131"), "after three unanswered tries the item was given up (no side-pack round)");
Check.True(Logged("0x80263131 landed in the main pack") && Logged("after it was given up"), "the late landing is seen and logged");
Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now), "the main pack is not marked");
Check.True(sim.Landed.Any(l => l.Id == Next), "the next item lands too");
Check.False(Logged("pickup failed for 0x80263132"), "the next item is not given up on");
Check.False(Logged("no pack has a free slot"), "looting does not stop");
Check.Eq((long)bot.Call("PickupAnswerWaitMs")!, RynthAiPlugin.PickupAnswerWaitMinMs,
"the lag spike's late answer (to an earlier, timed-out send) does not stretch the answer wait");
@ -661,10 +716,10 @@ internal static class LootRetryTimingTests
var mapMoves = FakeHost.ExternalMoves.Where(m => m.Id == QuestMap).ToList();
Check.Eq(mapMoves.Count(m => m.Target == Player), 3, "three tries into the main pack");
Check.Eq(mapMoves.Count(m => m.Target == SidePack), 3, "three into the side pack");
Check.Eq(mapMoves.Count(m => m.Target == SidePack), 0, "none into the side pack (the client refuses that from a corpse)");
Check.True(Logged("pickup failed for 0x80263151"), "then the map is given up");
Check.True(Logged("it is refusing the item, not the packs") && Logged("the main pack and pack 0x80263001 are no longer treated as full"),
"both marks go with the map");
Check.True(Logged("the only place loot can go") && Logged("the main pack is no longer treated as full"),
"the main pack is the only place it could go, and its mark goes with the map");
Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now) || bot.Refusals.IsRefused(unchecked((int)SidePack), _now), "no pack marked");
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == G2) && FakeHost.ExternalMoves.Where(m => m.Id == G2).All(m => m.Target == Player), "the next item goes into the main pack");
Check.True(sim.Landed.Any(l => l.Id == G2 && l.Pack == Player), "and lands");

View file

@ -4,6 +4,7 @@ using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
@ -34,7 +35,7 @@ internal static class LootSalvageTests
public static void Register(Runner r)
{
r.Add("loot pickup: a corpse item is moved into the main pack, never used (no get-and-wield)", PickupMovesNeverUses);
r.Add("loot pickup: a full main pack sends the item to a side pack with room", PickupFullMainPackGoesToSidePack);
r.Add("loot pickup: a full main pack never sends an item to a side pack (the client refuses that from a corpse); a stack you carry is still joined, anything else is left", PickupFullMainPackNeverSidePack);
r.Add("loot pickup: no move call -> wearables are left, other items are used", PickupWithoutMoveCall);
r.Add("salvage: a worn item is left alone and never taken off", SalvageLeavesWornItem);
r.Add("salvage: a corpse's items go in one batch and all are salvaged", SalvageOneBatch);
@ -82,7 +83,12 @@ internal static class LootSalvageTests
Check.Eq(FakeHost.Wields.Count, 0, "no WieldItem");
}
private static void PickupFullMainPackGoesToSidePack()
// 2026-11-12: with the main pack full the looter aimed pickups at a side pack, and the client
// refused every one ("You must first pick up the Silver Pea", nothing sent): 75 in a week of
// logs, none landed, each item waited out 3 + 3 tries and was left.
private const uint PeaInPack = 0x80262E01, Pea = 0x80262E02, SpareMain = 0x80262E03;
private static (RynthCoreHost Host, WorldObjectCache Cache) FullMainPack(bool sideRoom, bool peaStack)
{
FakeHost.Reset();
FakeHost.SalvageCalls = true;
@ -97,20 +103,60 @@ internal static class LootSalvageTests
}
FakeHost.Names[SidePack] = "Backpack";
FakeHost.ItemTypes[SidePack] = ItemTypeContainer;
FakeHost.Ints[(SidePack, 6)] = 24; // ItemsCapacity
FakeHost.Ints[(SidePack, 6)] = sideRoom ? 24 : 1; // ItemsCapacity
FakeHost.Containers[SidePack] = Player;
ids.Add(SidePack);
if (peaStack)
{
// The pea stack lives in the side pack (RynthSort's "Pea" rule), with room for more.
FakeHost.Names[PeaInPack] = "Silver Pea";
FakeHost.ItemTypes[PeaInPack] = 0x1000; // spell component
FakeHost.Ints[(PeaInPack, 11)] = 100; // MaxStackSize
FakeHost.Ints[(PeaInPack, 12)] = 40; // StackCount
FakeHost.Containers[PeaInPack] = SidePack;
ids.Add(PeaInPack);
}
else if (!sideRoom)
{
FakeHost.Names[SpareMain] = "Junk side";
FakeHost.ItemTypes[SpareMain] = ItemTypeGem;
FakeHost.Containers[SpareMain] = SidePack; // the one slot taken
ids.Add(SpareMain);
}
FakeHost.Names[Ring] = "Gold Ring";
FakeHost.ItemTypes[Ring] = ItemTypeJewelry;
ids.Add(Ring);
FakeHost.Names[Pea] = "Silver Pea";
FakeHost.ItemTypes[Pea] = 0x1000;
FakeHost.Ints[(Pea, 11)] = 100;
FakeHost.Ints[(Pea, 12)] = 1;
ids.Add(Pea);
var host = FakeHost.Create(Player);
var cache = FakeHost.MakeCache(host, Player, ids);
return (host, FakeHost.MakeCache(host, Player, ids));
}
var result = LootPickup.Send(host, cache, Ring, Player, out uint dest);
private static void PickupFullMainPackNeverSidePack()
{
var (host, cache) = FullMainPack(sideRoom: true, peaStack: true);
Check.Eq(result, LootPickupResult.Moved, "a move was sent");
Check.Eq(dest, SidePack, "the main pack is full: the side pack");
Check.Eq(LootPickup.Send(host, cache, Ring, Player, out uint dest), LootPickupResult.MainPackFull,
"a ring with the main pack full and room in a side pack: left (MainPackFull)");
Check.Eq(dest, 0u, "no destination");
Check.Eq(FakeHost.ExternalMoves.Count, 0, "and no move sent, least of all into the side pack");
Check.Eq(LootPickup.Send(host, cache, Pea, Player, out dest), LootPickupResult.Moved,
"a Silver Pea joins the stack you carry: sent");
Check.Eq(dest, Player, "aimed at the main pack: the client joins it to the stack in the side pack");
Check.True(FakeHost.ExternalMoves.All(m => m.Target != SidePack), "never aimed at the side pack");
Check.Eq(FakeHost.Uses.Count, 0, "no UseObject");
var (host2, cache2) = FullMainPack(sideRoom: true, peaStack: false);
Check.Eq(LootPickup.Send(host2, cache2, Pea, Player, out _), LootPickupResult.MainPackFull,
"a pea with no stack to join, main pack full: left too");
var (host3, cache3) = FullMainPack(sideRoom: false, peaStack: false);
Check.Eq(LootPickup.Send(host3, cache3, Ring, Player, out _), LootPickupResult.NoRoom,
"no room in any pack: NoRoom, as before");
}
private static void PickupWithoutMoveCall()

View file

@ -0,0 +1,413 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-11-11: the Loaded files drawer's profile buttons (Save, Save As, New, Rename, Move to
// Deleted, Open folder) and their /ra verbs. The name and path helpers (ProfileFileOps), then each
// kind through the dashboard: settings profiles, navs, metas, loot profiles, and the Spells window's
// buff profile Delete. Nothing is ever deleted: a removed profile goes to the Deleted folder beside
// it, and a file replaced by Save As has its old copy kept there first. Scratch folders only (the
// dashboard's NavProfiles / MetaFiles / LootProfiles fields and ProfilesBase are pointed at them).
internal static class ProfileButtonTests
{
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("profile buttons: Save As names are tidied and unsafe ones refused", NameSanitising);
r.Add("profile buttons: replace detection: another existing file only, never the file in use", OverwriteDetection);
r.Add("profile buttons: Move to Deleted moves (never deletes), names never collide", MoveToDeleted);
r.Add("profile buttons: Save As over another file keeps its old copy in Deleted", CopyToDeleted);
r.Add("profile buttons: rename refuses a name taken, allows a change of case", RenameHelper);
r.Add("profile buttons: settings Save As / replace / rename / Move to Deleted", SettingsProfiles);
r.Add("profile buttons: nav New / Save As asks before replacing / rename / Move to Deleted", NavProfiles);
r.Add("profile buttons: meta New / Save As / replace / rename / Move to Deleted", MetaProfiles);
r.Add("profile buttons: loot Save As copies, New checks the name, rename, Move to Deleted", LootProfiles);
r.Add("profile buttons: the Spells window's Delete moves the buff profile to Deleted", BuffDelete);
r.Add("profile buttons: the /ra verbs reply (worked, or why and the usage)", CommandsReply);
}
// ── helpers ──────────────────────────────────────────────────────────────
private static string Dir(string name)
{
string dir = Path.Combine(Program.TempRoot, "profile-buttons", name);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
Directory.CreateDirectory(dir);
return dir;
}
private static int AllFiles(string dir) => Directory.GetFiles(dir, "*", SearchOption.AllDirectories).Length;
private static string[] DeletedFiles(string folder)
{
string d = Path.Combine(folder, ProfileFileOps.DeletedFolderName);
return Directory.Exists(d) ? Directory.GetFiles(d).Select(Path.GetFileName).ToArray()! : Array.Empty<string>();
}
/// <summary>A dashboard whose nav, meta and loot folders are scratch folders under <paramref name="root"/>.</summary>
private static LegacyDashboardRenderer Dash(string root, out LegacyUiSettings s)
{
FakeHost.Reset();
DataWriteGuard.Reset();
var dash = new LegacyDashboardRenderer(FakeHost.Create());
foreach (var (field, sub) in new[] { ("_navFolder", "NavProfiles"), ("_metaFolder", "MetaFiles"), ("_lootFolder", "LootProfiles") })
{
string folder = Path.Combine(root, sub);
Directory.CreateDirectory(folder);
typeof(LegacyDashboardRenderer).GetField(field, Any)!.SetValue(dash, folder);
}
s = (LegacyUiSettings)typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.GetValue(dash)!;
return dash;
}
// ── ProfileFileOps ───────────────────────────────────────────────────────
private static void NameSanitising()
{
Check.Null(ProfileFileOps.CleanName(" \"Night Farm.nav\" ", LegacyDashboardRenderer.NavExtensions, out string n), "quotes, spaces and .nav are fine");
Check.Eq(n, "Night Farm", "tidied");
Check.Null(ProfileFileOps.CleanName("Loot.v2.utl", LegacyDashboardRenderer.LootExtensions, out n), "dots inside are fine");
Check.Eq(n, "Loot.v2", "only the known extension is dropped");
Check.Null(ProfileFileOps.CleanName("farm.AF", LegacyDashboardRenderer.MetaExtensions, out n), "extension case");
Check.Eq(n, "farm", "farm");
foreach (string bad in new[] { "", " ", "a/b", "..\\x", "..", "a:b", "what?", "con", "LPT1", "x.", new string('a', 130) })
Check.NotNull(ProfileFileOps.CleanName(bad, LegacyDashboardRenderer.NavExtensions, out _), $"refused: '{bad}'");
Check.True(LegacyDashboardRenderer.IsReservedSettingsName("Monsters"), "monsters.json is RynthAi's own");
Check.True(LegacyDashboardRenderer.IsReservedSettingsName("metamanager"), "metamanager.json is RynthAi's own");
Check.False(LegacyDashboardRenderer.IsReservedSettingsName("Hunting"), "a plain name is not");
}
private static void OverwriteDetection()
{
string dir = Dir("overwrite");
string a = Path.Combine(dir, "a.nav"), b = Path.Combine(dir, "b.nav"), c = Path.Combine(dir, "c.nav");
File.WriteAllText(a, "a");
File.WriteAllText(b, "b");
Check.True(ProfileFileOps.WouldReplace(b, a), "another file that exists");
Check.False(ProfileFileOps.WouldReplace(a, a), "the file in use is a plain save");
Check.False(ProfileFileOps.WouldReplace(Path.Combine(dir, "A.NAV"), a), "the file in use, another case");
Check.False(ProfileFileOps.WouldReplace(c, a), "a name not taken");
Check.True(ProfileFileOps.WouldReplace(b, string.Empty), "nothing in use: an existing file is still replaced");
}
private static void MoveToDeleted()
{
string dir = Dir("move");
string path = Path.Combine(dir, "farm.nav");
File.WriteAllText(path, "route");
var when = new DateTime(2026, 11, 11, 15, 30, 12);
Check.Eq(Path.GetFileName(ProfileFileOps.DeletedPathFor(path, when)), "farm.2026-11-11_153012.nav", "the time before the extension");
Check.True(ProfileFileOps.MoveToDeleted(path, when, out string moved, out string error), "moved: " + error);
Check.False(File.Exists(path), "gone from its folder");
Check.Eq(File.ReadAllText(moved), "route", "the same file in Deleted");
Check.Eq(Path.GetDirectoryName(moved), Path.Combine(dir, "Deleted"), "in <folder>\\Deleted");
Check.Eq(Directory.GetFiles(dir, "*.nav").Length, 0, "the picker's folder no longer lists it");
// The same name at the same second: a second copy, never over the first.
File.WriteAllText(path, "route 2");
Check.True(ProfileFileOps.MoveToDeleted(path, when, out string moved2, out _), "second move");
Check.Eq(Path.GetFileName(moved2), "farm.2026-11-11_153012 (2).nav", "numbered");
Check.Eq(File.ReadAllText(moved), "route", "the first copy kept");
Check.Eq(AllFiles(dir), 2, "nothing lost");
Check.False(ProfileFileOps.MoveToDeleted(path, when, out _, out error), "a file that isn't there");
Check.True(error.Contains("isn't there"), "says why: " + error);
}
private static void CopyToDeleted()
{
string dir = Dir("copy");
string path = Path.Combine(dir, "farm.af");
File.WriteAllText(path, "old");
Check.True(ProfileFileOps.CopyToDeleted(path, new DateTime(2026, 11, 11, 9, 0, 0), out string copy, out string error), "kept: " + error);
Check.Eq(File.ReadAllText(copy), "old", "the old copy");
Check.True(File.Exists(path), "the file itself stays (it is saved over next)");
Check.True(ProfileFileOps.CopyToDeleted(Path.Combine(dir, "none.af"), DateTime.Now, out copy, out _), "nothing to keep is fine");
Check.Eq(copy, string.Empty, "and keeps nothing");
}
private static void RenameHelper()
{
string dir = Dir("rename");
string a = Path.Combine(dir, "farm.nav"), b = Path.Combine(dir, "hunt.nav");
File.WriteAllText(a, "a");
File.WriteAllText(b, "b");
Check.False(ProfileFileOps.Rename(a, b, out string error), "a name taken");
Check.True(error.Contains("already exists"), error);
Check.Eq(File.ReadAllText(b), "b", "the other file untouched");
Check.True(ProfileFileOps.Rename(a, Path.Combine(dir, "Farm.nav"), out error), "a change of case: " + error);
Check.Eq(Path.GetFileName(Directory.GetFiles(dir, "farm.nav").Single()), "Farm.nav", "the new case is on disk");
Check.False(ProfileFileOps.Rename(Path.Combine(dir, "Farm.nav"), Path.Combine(dir, "Farm.nav"), out _), "the same name");
Check.Eq(AllFiles(dir), 2, "nothing lost");
}
// ── Settings profiles ────────────────────────────────────────────────────
private static void SettingsProfiles()
{
string root = Dir("settings");
LegacyDashboardRenderer.ProfilesBase = Path.Combine(root, "SettingsProfiles");
LegacyDashboardRenderer.MonstersBase = Path.Combine(root, "MonsterProfiles");
string? buffs = BuffProfileStore.FolderOverride;
BuffProfileStore.FolderOverride = Path.Combine(root, "BuffProfiles");
try
{
FakeHost.WorldName = "TestWorld";
var dash = Dash(root, out var s);
FakeHost.WorldName = "TestWorld";
dash.LoadSettings("Tester");
string dir = Path.Combine(LegacyDashboardRenderer.ProfilesBase, "TestWorld", "Tester");
ProfileResult r = dash.SaveProfileNow(ProfileKind.Settings);
Check.True(r.Ok && File.Exists(Path.Combine(dir, "Default.json")), "Save writes Default.json: " + r.Text);
r = dash.SaveProfileAs(ProfileKind.Settings, "monsters", replace: false);
Check.False(r.Ok, "a name RynthAi keeps for itself is refused");
Check.True(r.Text.Contains("monsters.json"), r.Text);
Check.False(dash.SaveProfileAs(ProfileKind.Settings, "a/b", replace: false).Ok, "a folder in the name is refused");
s.MonsterRange = 33;
r = dash.SaveProfileAs(ProfileKind.Settings, "Farm", replace: false);
Check.True(r.Ok, "Save As: " + r.Text);
Check.Eq(s.SelectedProfile, "Farm", "Farm is in use");
Check.True(File.Exists(Path.Combine(dir, "Farm.json")), "Farm.json");
Check.True(dash.ReadDashboardFiles().Profiles.Contains("Farm"), "listed");
// Back to Default; Save As Farm again asks first and writes nothing.
dash.SelectProfileAtIndex(3, Array.IndexOf(dash.ReadDashboardFiles().Profiles, "Default"));
Check.Eq(s.SelectedProfile, "Default", "Default again");
string farmBefore = File.ReadAllText(Path.Combine(dir, "Farm.json"));
r = dash.SaveProfileAs(ProfileKind.Settings, "Farm", replace: false);
Check.True(r.NeedsReplace && !r.Ok, "asks before replacing: " + r.Text);
Check.Eq(File.ReadAllText(Path.Combine(dir, "Farm.json")), farmBefore, "Farm untouched");
Check.Eq(DeletedFiles(dir).Length, 0, "nothing kept yet");
r = dash.SaveProfileAs(ProfileKind.Settings, "Farm", replace: true);
Check.True(r.Ok, "replaced: " + r.Text);
Check.Eq(DeletedFiles(dir).Length, 1, "the old Farm kept in Deleted");
Check.Eq(File.ReadAllText(Path.Combine(dir, "Deleted", DeletedFiles(dir)[0])), farmBefore, "the old Farm's content");
Check.Eq(s.SelectedProfile, "Farm", "Save As puts the replaced profile in use");
dash.SelectProfileAtIndex(3, Array.IndexOf(dash.ReadDashboardFiles().Profiles, "Default"));
Check.False(dash.RenameProfile(ProfileKind.Settings, "Other").Ok, "Default keeps its name");
Check.False(File.Exists(Path.Combine(dir, "Other.json")), "nothing renamed");
dash.SelectProfileAtIndex(3, Array.IndexOf(dash.ReadDashboardFiles().Profiles, "Farm"));
Check.Eq(s.SelectedProfile, "Farm", "Farm again");
Check.False(dash.RenameProfile(ProfileKind.Settings, "Default").Ok, "nothing can be renamed to Default");
r = dash.RenameProfile(ProfileKind.Settings, "Hunt");
Check.True(r.Ok, "rename: " + r.Text);
Check.Eq(s.SelectedProfile, "Hunt", "Hunt in use");
Check.False(File.Exists(Path.Combine(dir, "Farm.json")), "Farm.json renamed");
Check.True(File.Exists(Path.Combine(dir, "Hunt.json")), "Hunt.json");
Check.Eq(File.ReadAllText(Path.Combine(dir, "active_profile.txt")), "Hunt", "the active-profile marker follows");
r = dash.DeleteProfile(ProfileKind.Settings);
Check.True(r.Ok, "move to Deleted: " + r.Text);
Check.Eq(s.SelectedProfile, "Default", "back on Default");
Check.False(File.Exists(Path.Combine(dir, "Hunt.json")), "Hunt.json out of the list's folder");
Check.True(DeletedFiles(dir).Any(f => f.StartsWith("Hunt.", StringComparison.Ordinal)), "Hunt in Deleted");
Check.False(dash.ReadDashboardFiles().Profiles.Contains("Hunt"), "not listed");
Check.False(dash.DeleteProfile(ProfileKind.Settings).Ok, "Default is never moved");
Check.False(dash.RenameProfile(ProfileKind.Settings, "Main").Ok, "Default keeps its name");
Check.True(File.Exists(Path.Combine(dir, "Default.json")), "Default.json stays");
}
finally { BuffProfileStore.FolderOverride = buffs; }
}
// ── Navs ─────────────────────────────────────────────────────────────────
private static void NavProfiles()
{
string root = Dir("nav");
var dash = Dash(root, out var s);
string navs = Path.Combine(root, "NavProfiles");
ProfileResult r = dash.NewProfile(ProfileKind.Nav, "Loop");
Check.True(r.Ok, "New: " + r.Text);
Check.Eq(s.CurrentNavPath, Path.Combine(navs, "Loop.nav"), "Loop is loaded");
Check.False(dash.NewProfile(ProfileKind.Nav, "loop.nav").Ok, "New never opens an existing nav");
// Save As onto another nav asks first; nothing is written. (The write itself is SaveRoute,
// which saves to the install's NavProfiles, so it isn't run here.)
File.WriteAllText(Path.Combine(navs, "Other.nav"), "keep me");
r = dash.SaveProfileAs(ProfileKind.Nav, "Other", replace: false);
Check.True(r.NeedsReplace, "asks: " + r.Text);
Check.Eq(File.ReadAllText(Path.Combine(navs, "Other.nav")), "keep me", "Other untouched");
Check.Eq(DeletedFiles(navs).Length, 0, "nothing kept yet");
Check.False(dash.RenameProfile(ProfileKind.Nav, "Other").Ok, "rename onto a taken name is refused");
r = dash.RenameProfile(ProfileKind.Nav, "Ring");
Check.True(r.Ok, "rename: " + r.Text);
Check.Eq(s.CurrentNavPath, Path.Combine(navs, "Ring.nav"), "Ring stays loaded");
Check.True(dash.NavFileNames().Contains("Ring") && !dash.NavFileNames().Contains("Loop"), "the list follows");
s.CurrentRoute.Points.Add(new NavPoint { NS = 1, EW = 2 });
r = dash.DeleteProfile(ProfileKind.Nav);
Check.True(r.Ok, "move to Deleted: " + r.Text);
Check.Eq(s.CurrentNavPath, string.Empty, "no nav in use");
Check.Eq(s.CurrentRoute.Points.Count, 0, "the route is cleared, as picking None");
Check.False(dash.NavFileNames().Contains("Ring"), "not listed");
Check.True(DeletedFiles(navs).Single().StartsWith("Ring.", StringComparison.Ordinal), "Ring in NavProfiles\\Deleted");
Check.False(dash.DeleteProfile(ProfileKind.Nav).Ok, "nothing in use: nothing to move");
Check.True(File.Exists(Path.Combine(navs, "Other.nav")), "Other is never touched");
}
// ── Metas ────────────────────────────────────────────────────────────────
private static void MetaProfiles()
{
string root = Dir("meta");
var dash = Dash(root, out var s);
string metas = Path.Combine(root, "MetaFiles");
ProfileResult r = dash.NewProfile(ProfileKind.Meta, "Farm");
Check.True(r.Ok, "New: " + r.Text);
Check.Eq(s.CurrentMetaPath, Path.Combine(metas, "Farm.af"), "Farm.af in use");
Check.False(dash.NewProfile(ProfileKind.Meta, "Farm").Ok, "New never opens an existing meta");
r = dash.SaveProfileAs(ProfileKind.Meta, "Copy", replace: false);
Check.True(r.Ok, "Save As: " + r.Text);
Check.Eq(s.CurrentMetaPath, Path.Combine(metas, "Copy.af"), "Copy.af in use");
Check.True(File.Exists(Path.Combine(metas, "Copy.af")), "written");
string farmBefore = File.ReadAllText(Path.Combine(metas, "Farm.af"));
r = dash.SaveProfileAs(ProfileKind.Meta, "Farm", replace: false);
Check.True(r.NeedsReplace, "asks before replacing Farm: " + r.Text);
r = dash.SaveProfileAs(ProfileKind.Meta, "Farm", replace: true);
Check.True(r.Ok, "replaced: " + r.Text);
Check.Eq(File.ReadAllText(Path.Combine(metas, "Deleted", DeletedFiles(metas).Single())), farmBefore, "Farm's old copy kept");
r = dash.SaveProfileNow(ProfileKind.Meta);
Check.True(r.Ok, "Save: " + r.Text);
r = dash.RenameProfile(ProfileKind.Meta, "Run.af");
Check.True(r.Ok, "rename: " + r.Text);
Check.Eq(s.CurrentMetaPath, Path.Combine(metas, "Run.af"), "Run.af in use");
Check.True(dash.MetaFileNames().Contains("Run.af") && !dash.MetaFileNames().Contains("Farm.af"), "the list follows");
r = dash.DeleteProfile(ProfileKind.Meta);
Check.True(r.Ok, "move to Deleted: " + r.Text);
Check.Eq(s.CurrentMetaPath, string.Empty, "no meta in use");
Check.Eq(s.MetaRules.Count, 0, "unloaded, as picking None");
Check.Eq(DeletedFiles(metas).Length, 2, "Farm's old copy and Run");
Check.True(File.Exists(Path.Combine(metas, "Copy.af")), "Copy untouched");
Check.False(dash.SaveProfileNow(ProfileKind.Meta).Ok, "no file: Save says to use Save As");
}
// ── Loot profiles ────────────────────────────────────────────────────────
private static void LootProfiles()
{
string root = Dir("loot");
var dash = Dash(root, out var s);
string loot = Path.Combine(root, "LootProfiles");
Check.False(dash.SaveProfileAs(ProfileKind.Loot, "Copy", replace: false).Ok, "no loot profile in use: nothing to copy");
string snob = Path.Combine(loot, "Snob.utl");
VTankLootWriter.Save(new VTankLootProfile(), snob);
s.CurrentLootPath = snob;
ProfileResult r = dash.SaveProfileAs(ProfileKind.Loot, "Snob Copy.utl", replace: false);
Check.True(r.Ok, "Save As copies: " + r.Text);
string copy = Path.Combine(loot, "Snob Copy.utl");
Check.Eq(s.CurrentLootPath, copy, "the copy is in use");
Check.Eq(File.ReadAllText(copy), File.ReadAllText(snob), "the same rules");
Check.True(dash.ReadDashboardFiles().Loots.Contains("Snob Copy.utl"), "listed");
Check.True(dash.SaveProfileAs(ProfileKind.Loot, "Snob", replace: false).NeedsReplace, "asks before replacing Snob");
Check.NotNull(dash.NewLootProfilePath("Snob", out _), "New refuses a name taken");
Check.Null(dash.NewLootProfilePath("Fresh", out string fresh), "a free name");
Check.Eq(fresh, Path.Combine(loot, "Fresh.utl"), "a .utl in LootProfiles");
Check.False(File.Exists(fresh), "nothing written (the Loot Editor's Save creates it)");
r = dash.RenameProfile(ProfileKind.Loot, "Mine");
Check.True(r.Ok, "rename: " + r.Text);
Check.Eq(s.CurrentLootPath, Path.Combine(loot, "Mine.utl"), "Mine.utl in use");
r = dash.DeleteProfile(ProfileKind.Loot);
Check.True(r.Ok, "move to Deleted: " + r.Text);
Check.Eq(s.CurrentLootPath, string.Empty, "no loot profile in use");
Check.Eq(s.LootProfileIdx, 0, "the picker shows None");
Check.True(DeletedFiles(loot).Single().StartsWith("Mine.", StringComparison.Ordinal), "Mine in LootProfiles\\Deleted");
Check.True(File.Exists(snob), "Snob untouched");
}
// ── Buff profiles (the Spells window) ────────────────────────────────────
private static void BuffDelete()
{
string root = Dir("buffs");
string? previous = BuffProfileStore.FolderOverride;
BuffProfileStore.FolderOverride = root;
try
{
string path = BuffProfileStore.PathFor("Mage");
BuffProfileStore.Save(new BuffProfile { Name = "Mage" }, path);
Check.True(BuffProfileStore.Delete(path), "Delete works");
Check.Eq(BuffProfileStore.ListFileNames().Count, 0, "off the list");
Check.True(DeletedFiles(root).Single().StartsWith("Mage.", StringComparison.Ordinal), "kept in BuffProfiles\\Deleted");
Check.False(BuffProfileStore.Delete(path), "a file that isn't there");
}
finally { BuffProfileStore.FolderOverride = previous; }
}
// ── The /ra verbs ────────────────────────────────────────────────────────
private static void CommandsReply()
{
string root = Dir("commands");
var dash = Dash(root, out var s);
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
var plugin = new RynthAiPlugin();
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi });
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(plugin, dash);
MethodInfo dispatch = typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!;
string Ra(string line)
{
FakeHost.Chat.Clear();
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
dispatch.Invoke(plugin, new object[] { parts[1].ToLowerInvariant(), parts, 0 });
return string.Join(" / ", FakeHost.Chat);
}
string chat = Ra("/ra nav new Loop");
Check.True(chat.Contains("Created new nav 'Loop'"), "/ra nav new: " + chat);
chat = Ra("/ra nav rename");
Check.True(chat.Contains("needs a name") && chat.Contains("Usage: /ra nav"), "no name: why + usage: " + chat);
chat = Ra("/ra nav rename Ring");
Check.True(chat.Contains("Renamed Loop.nav to Ring.nav"), "/ra nav rename: " + chat);
chat = Ra("/ra nav delete");
Check.True(chat.Contains("Moved Ring.nav to NavProfiles\\Deleted"), "/ra nav delete: " + chat);
chat = Ra("/ra nav delete");
Check.True(chat.Contains("No nav file in use") && chat.Contains("Usage:"), "nothing to move: why + usage: " + chat);
chat = Ra("/ra meta new Farm");
Check.True(chat.Contains("Created new meta 'Farm'"), "/ra meta new: " + chat);
File.WriteAllText(Path.Combine(root, "MetaFiles", "Taken.af"), RynthCore.Plugin.RynthAi.Meta.AfFileWriter.BlankMetaText());
chat = Ra("/ra meta saveas Taken");
Check.True(chat.Contains("commands never replace a file"), "saveas never replaces: " + chat);
chat = Ra("/ra meta saveas Night Run");
Check.True(chat.Contains("Saved the meta as Night Run.af"), "/ra meta saveas: " + chat);
Check.Eq(s.CurrentMetaPath, Path.Combine(root, "MetaFiles", "Night Run.af"), "a name with a space");
chat = Ra("/ra meta bogus");
Check.True(chat.Contains("Unknown /ra meta verb") && chat.Contains("saveas <name>"), "the usage lists the new verbs: " + chat);
chat = Ra("/ra loot saveas Copy");
Check.True(chat.Contains("No loot profile in use to copy") && chat.Contains("Usage: /ra loot"), "/ra loot saveas: " + chat);
chat = Ra("/ra settings rename X");
Check.True(chat.Contains("No settings profile file in use") || chat.Contains("Default"), "/ra settings rename before login: " + chat);
chat = Ra("/ra settings");
Check.True(chat.Contains("Usage: /ra settings") && chat.Contains("saveas"), "/ra settings usage: " + chat);
}
}

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