RynthSuite as of 2026-12-02 (internal 152e13d): release 2026.12.1.1

This commit is contained in:
Tom Bohar 2026-12-02 06:45:07 -05:00
commit 6b5a9c7e99
65 changed files with 3920 additions and 237 deletions

View file

@ -390,71 +390,55 @@ public partial class BuffManager : IDisposable
return _healthFellAt != DateTime.MinValue && (now - _healthFellAt).TotalMilliseconds < HealthFellCountsMs;
}
// ── Buffs wait for the fight (2026-11-07, every buff since 2026-11-20) ──
// ── Buffs in a fight (2026-11-07; 2026-11-20; the rule since 2026-12-01) ──
// 2026-11-07: a character cast four weapon auras (2.4 s each) one after another with a golem's Force Bolts
// hitting him and his health under Heal At; the emergency heal then waited for the last aura's cast and
// he died. Then only health under Heal At held the buffs back.
// 2026-11-20, DreamWeave Thread 0x5C47: a Virindi dispelled Robustify and Executor's Blessing in the
// middle of a fight. RynthAi put his hand wraps away for the staff and cast them with a Rager on him and
// five monsters in range, and he died 4 s later. The owner: "dispel makes sense... but i think we should
// clear the mobs nearby before we rebuff". So in a fight (a monster within Monster Range, or health
// falling: InCombatNow) no new buff cast starts, whatever the health; one already sent finishes. The
// arbiter doesn't give Buffing the tick for buffs, so combat goes first, and the heals (a vital recharge
// keeps its slot). A rebuff run under way stops between two casts and carries on once the fight is over.
// The same for a dispelled buff and one at Rebuff With. A Force Rebuff the player asked for still goes in a
// fight (their own ask), except under Heal At, as before.
// he died. Since then no buff cast starts in a fight while health is under Heal At: the heals go first.
// 2026-11-20 (DreamWeave Thread 0x5C47, two buffs dispelled mid-fight and recast with a Rager on him):
// every buff waited for the fight's end. At a spot that never empties that never came (2026-11-25,
// R-20261125-130039-e3bc: buffs waited almost 7 hours, ran out, the character died); a 2-minute cap
// followed. Since 2026-12-01: once a buff is under the set timer, the rebuff starts regardless; the idle
// rebuff is the higher timer and picks quiet moments, and when a monster comes the fight goes on until a
// buff reaches the regular timer.
// So: a buff at or under Rebuff With (RebuffSecondsRemaining), or gone, is rebuffed now, fight or not;
// a run it starts carries on in a fight. Only health under Heal At in a fight holds a cast back. The
// earlier line (Rebuff When Idle's margin) is used only while idle (IdleTopOffNow); an early run stops
// when a monster comes (EndIdleTopOffRun), and in a fight a buff is due only at Rebuff With again.
// Dispels (2026-12-01, an option): with Recast dispelled buffs in a fight
// (RecastDispelledInFight) off, a fight with only gone buffs due (none present and at Rebuff With) waits
// for its end, as 2026-11-20; a run under way, or one a buff at Rebuff With starts, still goes.
private bool _buffFightWaitOn; // a wait with buffs to cast was logged
private DateTime _buffFightWaitSince = DateTime.MinValue;
private DateTime _buffFightNeedCheckedAt = DateTime.MinValue;
private bool _buffFightRunLogged; // "rebuffing in the fight" logged for this fight
// ── A fight that never ends (2026-11-25, R-20261125-130039-e3bc) ──
// Conquest, a spot that respawns constantly with Monster Range 10: never more than ~15 s without a
// monster in range, so the wait above never ended. Buffs waited 24,811 s (almost 7 hours), ran out,
// and the character died several times; Force Rebuff (cast in the fight) worked. Now once buffs
// have waited BuffFightWaitMaxSec through one unbroken fight, a full pass goes in it, the way a Force
// Rebuff does: never while health is under Heal At, and it stops once nothing is due. A short fight
// (the 11-20 Thread dispel case) is over long before that and still waits.
internal const int BuffFightWaitMaxSec = 120;
private bool _buffFightPass; // a pass let through a fight that doesn't end
private bool _buffFightPassNeed; // NeedsAnyBuff, asked at most once a second during a pass
private DateTime _buffFightPassCheckedAt = DateTime.MinValue;
/// <summary>True in a fight: no new buff cast. A Force Rebuff the player asked for waits only while health
/// is under Heal At. Logs the start (when there are buffs to cast) and the end of each wait.</summary>
/// <summary>True when no new buff cast may start: in a fight with health under Heal At. Logs the start
/// (when there are buffs to cast) and the end of each wait, and once per fight a rebuff that goes in it.</summary>
public bool BuffsWaitForFight()
{
bool fight = InCombatNow();
bool hurt = _settings.HealAt > 0 && _vitals.HealthPct > 0 && _vitals.HealthPct < _settings.HealAt;
bool playersOwn = _isForceRebuffing && !_isAutoBatchRebuff;
DateTime now = RynthClock.Now;
if (_buffFightPass)
{
// The pass ends with the fight or once nothing is due.
if ((now - _buffFightPassCheckedAt).TotalMilliseconds >= 1000)
{
_buffFightPassCheckedAt = now;
_buffFightPassNeed = NeedsAnyBuff();
}
if (!fight || !_buffFightPassNeed)
{
_buffFightPass = false;
_host.Log($"[Buff] the rebuff pass in the fight is done ({(fight ? "nothing left to cast" : "the fight is over")}).");
}
}
else if (fight && _buffFightWaitOn && (now - _buffFightWaitSince).TotalSeconds >= BuffFightWaitMaxSec)
{
_buffFightPass = true;
_buffFightPassNeed = true;
_buffFightPassCheckedAt = now;
_host.Log($"[Buff] buffs have waited {(now - _buffFightWaitSince).TotalSeconds:0} s for a fight that doesn't end (a monster always within range): " +
"a full rebuff pass goes now, in the fight, as Force Rebuff does (never under Heal At).");
}
bool wait = fight && (!(playersOwn || _buffFightPass) || hurt);
if (!fight) _buffFightRunLogged = false;
bool dispelWait = fight && !hurt && !_settings.RecastDispelledInFight && !_isForceRebuffing
&& NeedsAnyBuff() && !AnyBuffOnTimer(BuildDynamicBuffList(), _settings.RebuffSecondsRemaining);
bool wait = fight && (hurt || dispelWait);
if (!wait)
{
if (_buffFightWaitOn)
_host.Log($"[Buff] buffs go on: {(!fight ? "the fight is over" : _buffFightPass ? "the fight doesn't end, so they go in it" : $"health {_vitals.HealthPct}%, back over Heal At, for the Force Rebuff you asked for")} (they waited {(now - _buffFightWaitSince).TotalSeconds:0} s).");
_host.Log($"[Buff] buffs go on: {(!fight ? "the fight is over" : $"health {_vitals.HealthPct}%, back over Heal At")} (they waited {(now - _buffFightWaitSince).TotalSeconds:0} s).");
_buffFightWaitOn = false;
if (fight && !_buffFightRunLogged && (_isForceRebuffing || (now - _buffFightNeedCheckedAt).TotalMilliseconds >= 1000))
{
_buffFightNeedCheckedAt = now;
if (_isForceRebuffing || NeedsAnyBuff())
{
_buffFightRunLogged = true;
_host.Log(_isForceRebuffing && !_isAutoBatchRebuff
? $"[Buff] rebuffing in the fight ({FightWhy(false)}): the Force Rebuff you asked for."
: $"[Buff] rebuffing in the fight ({FightWhy(false)}): a buff is at or under Rebuff With ({_settings.RebuffSecondsRemaining} s) or gone, so it goes now.");
}
}
return false;
}
// Logged only when something is held back (a fight with every buff up isn't a wait); asked once a second.
@ -465,7 +449,9 @@ public partial class BuffManager : IDisposable
{
_buffFightWaitOn = true;
_buffFightWaitSince = now;
_host.Log($"[Buff] buffs wait: {FightWhy(hurt)}; they go on once the fight is over (combat and the heals first).");
_host.Log(dispelWait
? $"[Buff] buffs wait: {FightWhy(false)}; a dispelled buff waits for the fight's end (Recast dispelled buffs in a fight is off)."
: $"[Buff] buffs wait: {FightWhy(hurt)}; the heals first, the buffs once health is back over Heal At or the fight is over.");
}
}
return true;
@ -484,8 +470,8 @@ public partial class BuffManager : IDisposable
// The checkbox was saved and shown since the first version but nothing read it (a player asked,
// 2026-10-30, whether "buff only when idle" was implemented). What it means (the owner): an earlier
// timer for idle moments. The regular rebuff is unchanged: a buff at or under Rebuff With
// (RebuffSecondsRemaining), or dispelled, is recast as always, once a fight is over (BuffsWaitForFight,
// since 2026-11-20; before that in a fight too). With the option
// (RebuffSecondsRemaining), or dispelled, is recast at once, fight or not (2026-11-20 to 12-01 it waited
// for the fight's end; now only health under Heal At in a fight holds it, BuffsWaitForFight). With the option
// on and the bot idle (IdleForTopOff: no fight target, no monster within Monster Range, no corpse
// to loot, no salvage), a rebuff run also starts once a buff is at or under Rebuff With plus the
// margin (default 2 minutes). Such an early run never starts in a fight, and one under way stops
@ -3356,6 +3342,27 @@ public partial class BuffManager : IDisposable
// Families currently parked in _buffFailCooldownUntil are skipped so a parked
// family can't keep retriggering the batch (which would otherwise loop:
// batch starts → clears cooldown → cast again → silent no-show → re-park).
/// <summary>A buff that is on but at or under <paramref name="thresholdSec"/> (a gone one doesn't count): due
/// by its timer, not by a dispel. The shield's count when all of them are on and one is under the line.</summary>
private bool AnyBuffOnTimer(List<string> desiredBuffs, int thresholdSec)
{
DateTime now = RynthClock.Now;
foreach (string buffBaseName in desiredBuffs)
{
AcSkillType castSkill = SkillFor(buffBaseName);
if (!IsSkillUsable(castSkill)) continue;
int spellId = FindBestSpellId(buffBaseName, castSkill);
if (spellId == 0) continue;
int family = SpellTableStub.GetById(spellId)?.Family ?? 0;
if (family != 0
&& _buffFailCooldownUntil.TryGetValue(family, out DateTime coolUntil)
&& now < coolUntil)
continue;
if (IsBuffActive(spellId, 0) && !IsBuffActive(spellId, thresholdSec)) return true;
}
return ShieldBuffBelowThreshold(desiredBuffs, thresholdSec) && !ShieldBuffBelowThreshold(desiredBuffs, 0);
}
private bool AnyBuffBelowThreshold(List<string> desiredBuffs, int thresholdSec)
{
DateTime now = RynthClock.Now;

View file

@ -8300,6 +8300,12 @@ public partial class CombatManager : IDisposable
_scriptHeld = false;
_equipGateHeld = false;
if (_spellManager == null || target == null) return;
// The target was dropped earlier this tick (JudgePendingOffensiveCast read an answer: out of range, a
// ghost) after Think had picked it up. R-20261201-190034-03c5 (Conquest): the debuff went out at it
// anyway, as target 0: the client cast at its own selection ("You must select a suitable target before
// casting this spell", "This spell cannot be cast on Corpse of ..."), sent nothing, and combat waited
// for a server answer that never came: 7 s, a jump, Peace mode, about 13 s stood still each time.
if (activeTargetId == 0) return;
// Hard safety veto: never cast offensive magic at something AC's combat
// system says is not attackable. AC NPCs/vendors are ItemType=Creature,
@ -8633,6 +8639,7 @@ public partial class CombatManager : IDisposable
/// <summary>One debuff cast at <paramref name="targetId"/>; its result is read from chat (HandleChatForDebuffs).</summary>
private bool CastDebuffAt(int targetId, string targetName, string debuffKey, int spellId, int castTier, bool renewal)
{
if (targetId == 0) return false; // target 0 = the client's own selection: never (R-20261201-190034-03c5)
try
{
_host.CastSpellFor((uint)targetId, spellId, "Combat", SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}");

View file

@ -1783,7 +1783,7 @@ internal sealed unsafe class InstrumentDashboard
// 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 FilesHeight() => 6 * Px(22) + 5 * Px(4);
private float FilesBody(ImDrawListPtr dl, float x0, float y, float w)
{
@ -1801,7 +1801,9 @@ internal sealed unsafe class InstrumentDashboard
"Loot Editor: the loot profile in use.", () => _d.Host.SetPanelOpen("Loot Editor", RynthPanelOpen.Toggle), f.LootMode) + Px(4);
y = PickerRow(dl, x0, y, w, "META", f.MetaName, f.Metas, f.MetaIdx, 2, null, null, null) + Px(4);
y = PickerRow(dl, x0, y, w, "BUFFS", f.BuffName, f.Buffs, f.BuffIdx, 4, RynthIcons.Sparkle,
"RynthAi Spells: the spell list and buff profiles.", _d.ToggleSpells);
"RynthAi Spells: the spell list and buff profiles.", _d.ToggleSpells) + Px(4);
// Named window layouts (2026-12-01): pick one to put this character's windows that way.
y = PickerRow(dl, x0, y, w, "LAYOUT", f.LayoutName, f.Layouts ?? Array.Empty<string>(), f.LayoutIdx, 5, null, null, null);
return y;
}
@ -1910,12 +1912,13 @@ internal sealed unsafe class InstrumentDashboard
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.",
5 => "Window layout: Save your windows to it, Save As a new layout, Rename, Move to Deleted, Open folder.\nPick a layout in the list to load it on this character.",
_ => "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",
3 => "SETTINGS PROFILE", 0 => "NAV", 2 => "META", 1 => "LOOT PROFILE", 5 => "WINDOW LAYOUT", _ => "BUFF PROFILE",
};
private void OpenFilesMenu(int kind, Vector2 anchor)
@ -2002,7 +2005,7 @@ internal sealed unsafe class InstrumentDashboard
}
p.Y += Px(4);
bool settings = kind == 3, nav = kind == 0, loot = kind == 1, buffs = kind == 4;
bool settings = kind == 3, nav = kind == 0, loot = kind == 1, buffs = kind == 4, layout = kind == 5;
bool isDefault = settings && string.Equals(info.Name, "Default", StringComparison.OrdinalIgnoreCase);
bool idle = !_filesBusy;
@ -2029,7 +2032,8 @@ internal sealed unsafe class InstrumentDashboard
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)."
string saveTip = layout ? (info.HasFile ? $"Save your windows as they are now into '{info.Name}'." : "No layout in use yet: type a name below and use Save As.")
: 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);
@ -2088,7 +2092,8 @@ internal sealed unsafe class InstrumentDashboard
p.Y += h + gap;
x = p.X;
}
string asTip = loot ? "Copy the loot profile in use to this name; RynthAi loots with the copy."
string asTip = layout ? "Save your windows as they are now as a layout with this name (any character on this PC can load it)."
: loot ? "Copy the loot profile in use to this name; RynthAi loots with the copy."
: settings ? $"Save these settings as a new profile with this name, a copy of '{info.Name}' (its Monsters list too); it becomes the one in use."
: $"Save the {(nav ? "route" : "meta")} under this name; it becomes the one in use.";
if (settings && _filesFresh)
@ -2102,7 +2107,7 @@ internal sealed unsafe class InstrumentDashboard
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)
if (!settings && !layout)
{
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.";
@ -2171,7 +2176,7 @@ internal sealed unsafe class InstrumentDashboard
private static string NameHint(int kind) => kind switch
{
3 => "Profile name...", 0 => "Nav name...", 2 => "Meta name...", _ => "Loot profile name...",
3 => "Profile name...", 0 => "Nav name...", 2 => "Meta name...", 5 => "Layout name...", _ => "Loot profile name...",
};
/// <summary>The faint line under the name: where it lives, and how it is saved.</summary>
@ -2181,6 +2186,7 @@ internal sealed unsafe class InstrumentDashboard
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,
5 => "For every character on this PC; pick one to load it. /rc layout save|load <name>",
_ => info.Unsaved ? "The Spells window has changes not saved yet." : string.Empty,
};

View file

@ -1039,6 +1039,13 @@ internal sealed class LegacyAdvancedSettingsUi
"without waiting for the cast's recoil animation to end.\n" +
"A refused cast turns it off for the rest of that buff pass.\n" +
"On by default. Off = every buff waits for the animation.");
ImGui.Checkbox("Recast dispelled buffs in a fight", ref _settings.RecastDispelledInFight);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"On: a buff a monster dispels is recast at once, fight or not.\n" +
"Off: it waits until no monster is within Monster Range (a melee character\n" +
"doesn't put its weapon away mid-fight for it). A buff at 'Rebuff With'\n" +
"still goes in the fight, and takes the dispelled one along. On by default.");
ImGui.Checkbox("Skip buffs this character can't use", ref _settings.SkipUnusableBuffs);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(

View file

@ -45,7 +45,8 @@ internal sealed record DashboardFiles(
string[] Metas, int MetaIdx,
string[] Buffs, int BuffIdx,
string ProfileName, string NavName, string LootName, string MetaName, string BuffName,
int LootMode = 0);
int LootMode = 0,
string[]? Layouts = null, int LayoutIdx = -1, string LayoutName = "None");
internal sealed partial class LegacyDashboardRenderer
{
@ -76,7 +77,7 @@ internal sealed partial class LegacyDashboardRenderer
/// <summary>The five pickers' lists (copied under the lists' lock) and the entry in use. Any thread.</summary>
internal DashboardFiles ReadDashboardFiles()
{
string[] profiles, navs, loots, metas, buffs;
string[] profiles, navs, loots, metas, buffs, layouts;
lock (_profileListsLock)
{
profiles = _profiles.ToArray();
@ -84,7 +85,10 @@ internal sealed partial class LegacyDashboardRenderer
loots = _lootFiles.ToArray();
metas = _metaFiles.ToArray();
buffs = _buffFiles.ToArray();
layouts = _layoutFiles.ToArray();
}
string layoutName = _layoutName;
int layoutIdx = layoutName.Length > 0 ? Array.FindIndex(layouts, n => n.Equals(layoutName, StringComparison.OrdinalIgnoreCase)) : -1;
string profile = _settings.SelectedProfile ?? "Default";
return new DashboardFiles(
profiles, Math.Max(0, Array.IndexOf(profiles, profile)),
@ -97,7 +101,8 @@ internal sealed partial class LegacyDashboardRenderer
LootLineName(),
string.IsNullOrEmpty(_settings.CurrentMetaPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentMetaPath),
string.IsNullOrEmpty(_settings.CurrentBuffProfilePath) ? BuiltInBuffProfileLabel : Path.GetFileNameWithoutExtension(_settings.CurrentBuffProfilePath),
Loot.LootModes.Clamp(_settings.LootMode));
Loot.LootModes.Clamp(_settings.LootMode),
layouts, layoutIdx, layoutName.Length > 0 ? layoutName : "None");
}
/// <summary>

View file

@ -0,0 +1,167 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
// Named window layouts in the Loaded files drawer (2026-12-01, report R-20261127-150927-7938: "save your
// screen layout and load it on others via chat commands"; named layouts belong in the files drawer, easy
// to reach and change). The engine keeps them
// (/rc layout save|load|list|delete <name>, %LOCALAPPDATA%\RynthCore\layouts\_saved\<name>); this is the
// LAYOUT row: its list is that folder, picking one loads it on this character, and the row's "..." saves,
// saves as, renames, moves to Deleted and opens the folder. Which one this character last loaded or saved
// is kept beside its settings profiles (layout.txt), for the row to show.
internal sealed partial class LegacyDashboardRenderer
{
/// <summary>Where the engine keeps named layouts (PanelLayoutPolicy.NamedFolder).</summary>
internal static string LayoutsFolder => LayoutsFolderForTests ??
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "layouts", "_saved");
/// <summary>Tests: their own folder, never the PC's real layouts.</summary>
internal static string? LayoutsFolderForTests;
private const string LayoutNameFile = "layout.txt";
private readonly List<string> _layoutFiles = new();
private string _layoutName = string.Empty;
private DateTime _layoutFolderStamp;
/// <summary>The named layout this character last loaded or saved ("" none).</summary>
internal string LayoutName => _layoutName;
/// <summary>Why <paramref name="name"/> can't name a layout, or null (the engine's own rule: PanelLayoutPolicy.LayoutNameProblem).</summary>
internal static string? LayoutNameProblem(string? name)
{
string n = (name ?? string.Empty).Trim();
if (n.Length == 0) return "Type a name for the layout first.";
if (n.Length > 40) return "A layout name is at most 40 characters.";
if (n.StartsWith('_')) return "A layout name can't start with _.";
foreach (char ch in n)
if (!(char.IsLetterOrDigit(ch) || ch is ' ' or '-' or '_' or '(' or ')' or '.' or '\''))
return $"'{ch}' can't be in a layout name (letters, digits, spaces and - _ ( ) . ' can).";
if (n.EndsWith('.')) return "A layout name can't end with a dot.";
return null;
}
/// <summary>The named layouts in the folder (those with a panel_state.txt), sorted. Plugin tick.</summary>
internal void RefreshLayoutFiles()
{
var names = new List<string>();
try
{
if (Directory.Exists(LayoutsFolder))
foreach (string dir in Directory.GetDirectories(LayoutsFolder))
{
string n = Path.GetFileName(dir);
if (!n.StartsWith('_') && File.Exists(Path.Combine(dir, "panel_state.txt"))) names.Add(n);
}
}
catch { }
names.Sort(StringComparer.OrdinalIgnoreCase);
lock (_profileListsLock) { _layoutFiles.Clear(); _layoutFiles.AddRange(names); }
}
/// <summary>The layout this character last loaded or saved, from its folder (at login).</summary>
private void ReadLayoutName()
{
_layoutName = string.Empty;
try
{
string path = string.IsNullOrEmpty(_charFolder) ? string.Empty : Path.Combine(_charFolder, LayoutNameFile);
if (path.Length > 0 && File.Exists(path)) _layoutName = File.ReadAllText(path).Trim();
}
catch { }
RefreshLayoutFiles();
}
private void SetLayoutName(string name)
{
_layoutName = name.Trim();
try
{
if (!string.IsNullOrEmpty(_charFolder))
{
Directory.CreateDirectory(_charFolder);
File.WriteAllText(Path.Combine(_charFolder, LayoutNameFile), _layoutName);
}
}
catch { }
}
/// <summary>The folder changed (a layout saved, renamed or deleted, here or by another client): list it again. Plugin tick.</summary>
private void TickLayoutFolder()
{
if (FolderChanged(LayoutsFolder, ref _layoutFolderStamp)) RefreshLayoutFiles();
}
/// <summary>An engine command (/rc layout ...), as typed in chat. False when the engine can't take it.</summary>
private bool LayoutCommand(string args)
{
try { return _host.HasInvokeChatParser && _host.InvokeChatParser("/rc layout " + args); }
catch { return false; }
}
private bool LayoutExists(string name) => File.Exists(Path.Combine(LayoutsFolder, name.Trim(), "panel_state.txt"));
/// <summary>Picked in the LAYOUT row: this character's windows become that layout. Plugin tick.</summary>
internal ProfileResult LoadLayout(string name)
{
if (!LayoutExists(name)) { RefreshLayoutFiles(); return ProfileResult.Failed($"There's no saved layout '{name}' any more."); }
if (!LayoutCommand("load " + name)) return ProfileResult.Failed("This RynthCore can't load layouts: update the core.");
SetLayoutName(name);
return ProfileResult.Done($"Loading the layout '{name}': your windows move to it in a moment.");
}
/// <summary>The LAYOUT row's "..." buttons. Plugin tick (RynthAiPlugin.RunProfileAction).</summary>
internal ProfileResult LayoutAction(ProfileVerb verb, string? raw, bool replace)
{
string name = (raw ?? string.Empty).Trim();
switch (verb)
{
case ProfileVerb.Save:
if (_layoutName.Length == 0) return ProfileResult.Failed("No layout in use yet: type a name and use Save As.");
return SaveLayout(_layoutName);
case ProfileVerb.SaveAs:
case ProfileVerb.New:
{
if (LayoutNameProblem(name) is string bad) return ProfileResult.Failed(bad);
if (LayoutExists(name) && !replace && !name.Equals(_layoutName, StringComparison.OrdinalIgnoreCase))
return new ProfileResult(false, $"[RynthAi] There's a layout '{name}' already.", NeedsReplace: true);
return SaveLayout(name);
}
case ProfileVerb.Rename:
{
if (_layoutName.Length == 0 || !LayoutExists(_layoutName)) return ProfileResult.Failed("No saved layout in use to rename.");
if (LayoutNameProblem(name) is string bad) return ProfileResult.Failed(bad);
if (LayoutExists(name)) return ProfileResult.Failed($"There's a layout '{name}' already.");
try
{
Directory.Move(Path.Combine(LayoutsFolder, _layoutName), Path.Combine(LayoutsFolder, name));
}
catch (Exception ex) { return ProfileResult.Failed($"Couldn't rename the layout: {ex.Message}"); }
string was = _layoutName;
SetLayoutName(name);
RefreshLayoutFiles();
return ProfileResult.Done($"Renamed the layout '{was}' to '{name}'.");
}
case ProfileVerb.Delete:
{
if (_layoutName.Length == 0 || !LayoutExists(_layoutName)) return ProfileResult.Failed("No saved layout in use to delete.");
string was = _layoutName;
if (!LayoutCommand("delete " + was)) return ProfileResult.Failed("This RynthCore can't delete layouts: update the core.");
SetLayoutName(string.Empty);
return ProfileResult.Done($"Moved the layout '{was}' to {Path.Combine(LayoutsFolder, "_deleted")} (nothing is erased).");
}
case ProfileVerb.Folder:
return OpenProfileFolder(ProfileKind.Layout);
default:
return ProfileResult.Failed("Layouts have Save, Save As, Rename, Delete and Open folder.");
}
}
private ProfileResult SaveLayout(string name)
{
if (!LayoutCommand("save " + name)) return ProfileResult.Failed("This RynthCore can't save layouts: update the core.");
SetLayoutName(name);
return ProfileResult.Done($"Saved your windows as the layout '{name}'. Any character on this PC can load it from the LAYOUT row, or with /rc layout load {name}.");
}
}

View file

@ -267,23 +267,43 @@ internal sealed partial class LegacyDashboardRenderer
break;
case "trailToRoute":
{
NavCrumb[] trail = NavBreadcrumbs?.Trail ?? Array.Empty<NavCrumb>();
List<NavPoint> pts = NavBreadcrumbTracker.TrailToPoints(trail, _settings.NavOverlay.RecordSpacingYards, cmd.Reverse);
if (pts.Count < 2) { SetNavEditStatus("The trail is too short to make a route."); return; }
_settings.IsRecordingNav = false;
// A new unsaved route: the loaded file on disk is not changed (Save As keeps it).
_settings.CurrentRoute = new NavRouteParser { RouteType = NavRouteType.Once, Points = pts };
_settings.CurrentNavPath = string.Empty;
_settings.ActiveNavIndex = 0;
RefreshNavFiles();
SaveSettings();
SetNavEditStatus($"{(cmd.Reverse ? "Backtrack" : "Trail")} route created: {pts.Count} points (unsaved).");
SetNavEditStatus(TrailToRoute(cmd.Reverse, null, out _));
break;
}
}
}
/// <summary>
/// The breadcrumb trail (its newest unbroken stretch) becomes the current route, walked again or
/// backwards (<paramref name="reverse"/>), and with <paramref name="saveAs"/> it is saved as
/// NavProfiles\&lt;name&gt;.nav (report R-20261129-210845-0574: "a nav route made from your
/// breadcrumbs"; the Nav panel's Tools menu had it, /ra navtrail route|back gives it a name too).
/// Returns the line to show; <paramref name="made"/> is false when no route was made.
/// </summary>
internal string TrailToRoute(bool reverse, string? saveAs, out bool made)
{
made = false;
NavCrumb[] trail = NavBreadcrumbs?.Trail ?? Array.Empty<NavCrumb>();
List<NavPoint> pts = NavBreadcrumbTracker.TrailToPoints(trail, _settings.NavOverlay.RecordSpacingYards, reverse);
if (pts.Count < 2)
return _settings.NavOverlay.TrackBreadcrumbs
? "The trail is too short to make a route: walk a while first."
: "No trail to make a route from: turn Breadcrumbs on (/ra navtrail on) and walk a while.";
_settings.IsRecordingNav = false;
// A new unsaved route: the loaded file on disk is not changed (Save As keeps it).
_settings.CurrentRoute = new NavRouteParser { RouteType = NavRouteType.Once, Points = pts };
_settings.CurrentNavPath = string.Empty;
_settings.ActiveNavIndex = 0;
made = true;
string what = $"{(reverse ? "Backtrack" : "Trail")} route created: {pts.Count} points";
if (string.IsNullOrWhiteSpace(saveAs))
{
RefreshNavFiles();
SaveSettings();
return what + " (unsaved).";
}
return what + ". " + SaveRoute(saveAs).Replace("[RynthAi] ", "");
}
/// <summary>Copy-on-write route edit, then the route file autosave.</summary>
private void EditRoute(Func<List<NavPoint>, List<NavPoint>> edit)
{

View file

@ -7,7 +7,7 @@ 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 }
internal enum ProfileKind { Nav = 0, Loot = 1, Meta = 2, Settings = 3, Buffs = 4, Layout = 5 }
/// <summary>What a profile button or its /ra verb does.</summary>
internal enum ProfileVerb { Save, SaveAs, New, Rename, Delete, Folder, Edit, ClearMonsters }
@ -58,6 +58,7 @@ internal sealed partial class LegacyDashboardRenderer
ProfileKind.Loot => "loot profile",
ProfileKind.Meta => "meta",
ProfileKind.Settings => "settings profile",
ProfileKind.Layout => "layout",
_ => "buff profile",
};
@ -76,6 +77,7 @@ internal sealed partial class LegacyDashboardRenderer
ProfileKind.Loot => _lootFolder,
ProfileKind.Meta => _metaFolder,
ProfileKind.Settings => _charFolder ?? string.Empty,
ProfileKind.Layout => LayoutsFolder,
_ => BuffProfileStore.Folder,
};
@ -89,6 +91,7 @@ internal sealed partial class LegacyDashboardRenderer
ProfileKind.Loot => _settings.CurrentLootPath ?? string.Empty,
ProfileKind.Meta => _settings.CurrentMetaPath ?? string.Empty,
ProfileKind.Settings => _settingsFilePath ?? string.Empty,
ProfileKind.Layout => _layoutName.Length > 0 ? Path.Combine(LayoutsFolder, _layoutName, "panel_state.txt") : string.Empty,
_ => _settings.CurrentBuffProfilePath ?? string.Empty,
};
@ -133,6 +136,9 @@ internal sealed partial class LegacyDashboardRenderer
case ProfileKind.Buffs:
if (path.Length == 0) name = BuiltInBuffProfileLabel;
break;
case ProfileKind.Layout:
name = _layoutName.Length > 0 ? _layoutName : "None";
break;
}
return new ProfileFileInfo(name, path, hasFile, unsaved, ProfileFolder(k), monsterRules);
}

View file

@ -386,6 +386,7 @@ internal sealed partial class LegacyDashboardRenderer
_serverFolder = ResolveServerFolder();
_charFolder = Path.Combine(_settingsRoot, safeChar);
MigrateToServerFolder(safeChar);
ReadLayoutName(); // the named layout this character last loaded or saved (the LAYOUT row)
// Migrate legacy settings.json → Default.json if needed
string legacyPath = Path.Combine(_charFolder, "settings.json");
@ -600,6 +601,7 @@ internal sealed partial class LegacyDashboardRenderer
_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
_metaUi.EmbedFileRoutes(when); // routes still read from NavProfiles go into the meta
}
catch (Exception ex)
{
@ -1485,6 +1487,7 @@ internal sealed partial class LegacyDashboardRenderer
RebuffIdleMarginMinutes = s.RebuffIdleMarginMinutes,
CastBuffsOverItemBuffs = s.CastBuffsOverItemBuffs,
SkipUnusableBuffs = s.SkipUnusableBuffs,
RecastDispelledInFight = s.RecastDispelledInFight,
UseFellowshipBuffs = s.UseFellowshipBuffs,
DisabledBuffs = new List<string>(s.DisabledBuffs),
BlockedBuffItems = new List<string>(s.BlockedBuffItems),
@ -1786,6 +1789,7 @@ internal sealed partial class LegacyDashboardRenderer
if (p.RebuffIdleMarginMinutes is int idleMargin) s.RebuffIdleMarginMinutes = Math.Max(0, idleMargin); // absent = unchanged
if (p.CastBuffsOverItemBuffs is bool castOverItems) s.CastBuffsOverItemBuffs = castOverItems; // absent = unchanged
if (p.SkipUnusableBuffs is bool skipUnusable) s.SkipUnusableBuffs = skipUnusable; // absent = unchanged
if (p.RecastDispelledInFight is bool recastDispelled) s.RecastDispelledInFight = recastDispelled; // absent = unchanged
if (p.UseFellowshipBuffs is bool fellowBuffs) s.UseFellowshipBuffs = fellowBuffs; // 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
@ -2178,6 +2182,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.OutdoorHuntRange = tmp.OutdoorHuntRange;
dst.OutdoorHuntRadius = tmp.OutdoorHuntRadius;
dst.OutdoorHuntPick = Math.Clamp(tmp.OutdoorHuntPick, 0, 2);
dst.OutdoorHuntRoam = tmp.OutdoorHuntRoam;
dst.T2Speed = tmp.T2Speed;
dst.T2DistanceTo = tmp.T2DistanceTo;
dst.T2ReissueMs = tmp.T2ReissueMs;
@ -2333,6 +2338,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.CastBuffsOverItemBuffs = tmp.CastBuffsOverItemBuffs;
dst.FastBuffChain = tmp.FastBuffChain;
dst.SkipUnusableBuffs = tmp.SkipUnusableBuffs;
dst.RecastDispelledInFight = tmp.RecastDispelledInFight;
dst.UseFellowshipBuffs = tmp.UseFellowshipBuffs;
dst.DisabledBuffs = tmp.DisabledBuffs;
dst.BlockedBuffItems = tmp.BlockedBuffItems;
@ -2938,6 +2944,7 @@ internal sealed partial class LegacyDashboardRenderer
if (FolderChanged(_lootFolder, ref _lootFolderStamp)) RefreshLootFiles();
if (FolderChanged(_metaFolder, ref _metaFolderStamp)) RefreshMetaFiles();
if (FolderChanged(_charFolder, ref _profileFolderStamp)) RefreshProfilesList();
TickLayoutFolder();
}
/// <summary>True when <paramref name="folder"/>'s write time moved since the last call (never on
@ -3733,7 +3740,7 @@ internal sealed partial class LegacyDashboardRenderer
// AddRange() on the pump thread — a torn read or
// ArgumentOutOfRangeException. Snapshot the one list this call needs
// under _profileListsLock first, mirroring BuildSnapshotJson.
string? navFile = null, lootFile = null, metaFile = null, profileName = null, buffFile = null;
string? navFile = null, lootFile = null, metaFile = null, profileName = null, buffFile = null, layoutFile = null;
lock (_profileListsLock)
{
switch (kind)
@ -3743,6 +3750,7 @@ internal sealed partial class LegacyDashboardRenderer
case 2: if (index >= 0 && index < _metaFiles.Count) metaFile = _metaFiles[index]; break;
case 3: if (index >= 0 && index < _profiles.Count) profileName = _profiles[index]; break;
case 4: if (index >= 0 && index < _buffFiles.Count) buffFile = _buffFiles[index]; break;
case 5: if (index >= 0 && index < _layoutFiles.Count) layoutFile = _layoutFiles[index]; break;
}
}
@ -3780,6 +3788,13 @@ internal sealed partial class LegacyDashboardRenderer
if (buffFile != null)
SetActiveBuffProfile(index == 0 ? string.Empty : Path.Combine(BuffProfileStore.Folder, buffFile));
break;
case 5:
if (layoutFile != null)
{
ProfileResult r = LoadLayout(layoutFile);
_host.WriteToChat(r.Text, r.Ok ? 1 : 0x1A);
}
break;
}
}
@ -3900,6 +3915,18 @@ internal sealed partial class LegacyDashboardRenderer
AppendStringArray(sb, "navFiles", _navFiles); sb.Append(',');
AppendStringArray(sb, "embeddedNavKeys", _settings.EmbeddedNavs.Keys); sb.Append(',');
// The loaded nav route, for the Embedded Nav Route's "Embed loaded" button (MetaNavEmbedding):
// the name it is embedded under, its points, and why it can't be (empty note: it can).
{
var loadedRoute = MetaNavEmbedding.DescribeLoaded(_settings.CurrentRoute, _settings.CurrentNavPath,
_metaSaver.NavFolder(), _settings.EmbeddedNavs);
sb.Append("\"loadedRoute\":{");
AppendString(sb, "name", loadedRoute.Name); sb.Append(',');
sb.Append("\"points\":").Append(loadedRoute.Points).Append(',');
AppendString(sb, "note", loadedRoute.Note);
sb.Append("},");
}
string sourceText = "";
try { sourceText = AfFileWriter.SaveToString(_settings.MetaRules, _settings.EmbeddedNavs); } catch { }
AppendString(sb, "sourceText", sourceText);
@ -4121,7 +4148,11 @@ internal sealed partial class LegacyDashboardRenderer
case "add_rule":
if (cmd.Rule == null) { RefuseEdit(op, "the command carried no rule"); break; }
_settings.MetaRules.Add(DtoToMetaRule(cmd.Rule));
{
var added = DtoToMetaRule(cmd.Rule);
EmbedPickedRoutes(added, null);
_settings.MetaRules.Add(added);
}
TryAutoSaveMetaCmd($"add_rule (now {_settings.MetaRules.Count} rules)");
break;
@ -4129,10 +4160,15 @@ internal sealed partial class LegacyDashboardRenderer
// The engine's editor saves every change (2026-10-05): keep the running rule's
// latch (no re-fire) and the fields the panel can't send (MetaRuleEdits).
if (cmd.Rule == null) { RefuseEdit(op, "the command carried no rule"); break; }
if (!MetaRuleEdits.Replace(_settings.MetaRules, cmd.Index, DtoToMetaRule(cmd.Rule), keepName: cmd.Rule.Name == null))
{
RefuseEdit(op, NoSuchRule(cmd.Index));
break;
var edited = DtoToMetaRule(cmd.Rule);
MetaRule? was = HasRule(cmd.Index) ? _settings.MetaRules[cmd.Index] : null;
if (!MetaRuleEdits.Replace(_settings.MetaRules, cmd.Index, edited, keepName: cmd.Rule.Name == null))
{
RefuseEdit(op, NoSuchRule(cmd.Index));
break;
}
if (was != null) EmbedPickedRoutes(edited, was);
}
TryAutoSaveMetaCmd($"update_rule {cmd.Index + 1}");
break;
@ -4168,6 +4204,7 @@ internal sealed partial class LegacyDashboardRenderer
if (!HasRule(cmd.Index)) { RefuseEdit(op, NoSuchRule(cmd.Index)); break; }
{
var copy = DtoToMetaRule(cmd.Rule);
EmbedPickedRoutes(copy, _settings.MetaRules[cmd.Index]); // the same route: nothing to copy
MetaRuleEdits.KeepHidden(_settings.MetaRules[cmd.Index], copy); // CallState return / ChatCapture colours
if (cmd.Rule.Name == null) copy.Name = _settings.MetaRules[cmd.Index].Name;
_settings.MetaRules.Insert(cmd.Index + 1, copy);
@ -4214,6 +4251,35 @@ internal sealed partial class LegacyDashboardRenderer
return -1;
}
/// <summary>A route picked for an Embedded Nav Route (a new rule, or a changed route) is copied
/// into the meta from its NavProfiles file (MetaNavEmbedding); the save below writes it. A route the
/// panel's "Embed loaded" named (MetaNavEmbedding.LoadedMarker) is the loaded route, copied from memory:
/// one never saved to a file becomes the meta's route (nav edits then go to the meta's copy).</summary>
private void EmbedPickedRoutes(MetaRule after, MetaRule? before)
{
string folder = _metaSaver.NavFolder();
lock (_settings.MetaRulesLock)
{
HashSet<string>? fromMemory = null;
foreach (string name in MetaNavEmbedding.TakeLoadedMarkers(after))
{
string? why = MetaNavEmbedding.EmbedLoaded(name, _settings.CurrentRoute, _settings.CurrentNavPath, folder,
_settings.EmbeddedNavs, line => _host.Log(line));
if (why == null)
{
(fromMemory ??= new HashSet<string>(System.StringComparer.OrdinalIgnoreCase)).Add(name);
if (string.IsNullOrEmpty(_settings.CurrentNavPath)) _settings.CurrentNavPath = $"<embedded:{name}>";
}
else
{
_host.Log($"[RynthAi] Meta: the loaded route wasn't embedded as '{name}': {why}");
_host.WriteToChat($"[RynthAi] Meta: the loaded route wasn't embedded: {why}", 1);
}
}
MetaNavEmbedding.EmbedPicked(after, before, _settings.EmbeddedNavs, folder, line => _host.Log(line), fromMemory);
}
}
/// <summary>Writes the meta file after a rule command changed the rules (MetaSaver: logged, and the
/// result goes to the panel in the snapshot's saveResult).</summary>
private void TryAutoSaveMetaCmd(string change)

View file

@ -1262,6 +1262,7 @@ internal sealed class LegacyMetaUi
: $"Loaded {loaded.Rules.Count} rules / {stateCount} states from {name} — {loaded.Warnings.Count} warning(s): {loaded.Warnings[0]}";
_statusTime = RynthClock.Now;
NoteCallStates(filePath, loaded.Rules);
EmbedFileRoutes("load");
return true;
}
catch (Exception ex)
@ -1272,6 +1273,29 @@ internal sealed class LegacyMetaUi
}
}
/// <summary>
/// The loaded meta's Embedded Nav Routes that it doesn't carry (it named a NavProfiles file) are
/// copied in, and a .af is written with them once, so the meta stops needing the files
/// (MetaNavEmbedding). A .met keeps them in memory (its first edit saves the .af); a read-only
/// file isn't written. <paramref name="when"/> names the load for the log.
/// </summary>
internal void EmbedFileRoutes(string when)
{
string path = _settings.CurrentMetaPath ?? string.Empty;
List<string> added;
lock (_settings.MetaRulesLock)
added = MetaNavEmbedding.EmbedMissing(_settings.MetaRules, _settings.EmbeddedNavs, Saver.NavFolder(), Log);
if (added.Count == 0 || path.Length == 0) return;
if (!Path.GetExtension(path).Equals(".af", StringComparison.OrdinalIgnoreCase)) return;
try
{
if (!File.Exists(path) || (File.GetAttributes(path) & FileAttributes.ReadOnly) != 0) return;
}
catch { return; }
Saver.SaveTo(path, $"{when}: routes embedded from NavProfiles",
$"; route{(added.Count == 1 ? "" : "s")} {string.Join(", ", added)} now inside the meta");
}
/// <summary>The status line of the last load (why it failed, or what it loaded).</summary>
internal string LastLoadStatus => _statusMessage ?? string.Empty;

View file

@ -148,6 +148,8 @@ public sealed class LegacyUiSettings
// What the next monster is chosen by (2026-11-08, OutdoorHunt.PickMode): 0 the nearest (the hunt as
// it was), 1 the biggest pack, 2 the pack worth the most experience (learned XP per kill).
public int OutdoorHuntPick = 0;
/// <summary>With nothing in range, walk round the parts of Hunt Radius not looked at lately (2026-12-01; on by default).</summary>
public bool OutdoorHuntRoam = true;
// On: macro start, loading a Circular or Linear route, and nav taking over again after a
// pause that moved the character (combat, looting, buffing, doors) all head for the closest
// waypoint on the route. Off: a pause carries on to the waypoint it was heading for, a macro
@ -617,6 +619,14 @@ public sealed class LegacyUiSettings
/// </summary>
public bool SkipUnusableBuffs = true;
/// <summary>
/// Buffing > Recast dispelled buffs in a fight (on by default; 2026-12-01: recasting dispels is
/// an option). On: a buff a monster dispels is recast at once, fight or not, like any buff at Rebuff With.
/// Off: in a fight a dispelled (gone) buff waits until no monster is within Monster Range; a buff at or
/// under Rebuff With still goes in the fight, and the run it starts takes the dispelled one along.
/// A profile saved before the setting loads it on. Read by BuffManager.BuffsWaitForFight.
/// </summary>
public bool RecastDispelledInFight = true;
/// <summary>
/// Buffing > Use fellowship buffs in a fellowship (off by default): in a fellowship, a buff with a
/// fellowship version (the Conclave attributes, the Clutch defenses, the Chants masteries, the Wards
/// protections, the Winds, the Endless Well) casts that version instead, at the same level rules and
@ -1726,6 +1736,7 @@ public sealed class SettingsBridgePayload
// Settings face must leave the setting alone rather than force it either way.
public bool? CastBuffsOverItemBuffs { get; set; }
public bool? SkipUnusableBuffs { get; set; }
public bool? RecastDispelledInFight { get; set; } // Recast dispelled buffs in a fight (2026-12-01); absent = unchanged
public bool? UseFellowshipBuffs { get; set; } // Use fellowship buffs in a fellowship (2026-11-27); absent = unchanged
// Null (absent) likewise leaves the unticked prots/banes alone; an empty list ticks them all.
public List<string>? DisabledBuffs { get; set; }

View file

@ -35,6 +35,9 @@ internal sealed class MetaSaver
_log = log;
}
/// <summary>Where an Embedded Nav Route's file is read from when the meta doesn't carry the route yet.</summary>
public Func<string> NavFolder { get; set; } = () => LegacyNavigationUi.NavFolder;
/// <summary>Counts results (0 = nothing tried yet this session).</summary>
public long Seq { get; private set; }
public bool LastOk { get; private set; } = true;
@ -72,6 +75,11 @@ internal sealed class MetaSaver
string why;
lock (_settings.MetaRulesLock)
{
// Every route a rule names goes into the file (MetaNavEmbedding): a route still read
// from NavProfiles is copied in now, so the meta runs without the .nav file.
List<string> embedded = MetaNavEmbedding.EmbedMissing(_settings.MetaRules, _settings.EmbeddedNavs, NavFolder(), _log);
if (embedded.Count > 0)
note += $"; route{(embedded.Count == 1 ? "" : "s")} {string.Join(", ", embedded)} now inside the meta";
rules = _settings.MetaRules.Count;
states = _settings.MetaRules.Select(r => r.State ?? "Default").Distinct(StringComparer.OrdinalIgnoreCase).Count();
ok = DataWriteGuard.TrySave("the meta", path,

View file

@ -123,6 +123,14 @@ public sealed class NavRouteParser
/// </summary>
public bool NavmeshCorners { get; set; }
/// <summary>
/// What built this route in memory when no one recorded or loaded it (the dungeon patrol, a hunt's
/// walk, Camp, a go-to...): the Meta panel's "Embed loaded" refuses it, so a meta never freezes a
/// generated path (MetaNavEmbedding.DescribeLoaded, 2026-11-30). Empty for files, metas, the nav
/// editor and recording. Never saved with the route.
/// </summary>
public string MadeBy { get; set; } = string.Empty;
/// <summary>
/// Non-null if the last load hit an unknown waypoint type or a malformed
/// line. The route still holds whatever points parsed cleanly before that.

View file

@ -0,0 +1,102 @@
using System;
using System.IO;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
namespace RynthCore.Plugin.RynthAi.Loot;
/// <summary>What the rule that takes an item says to do with it, for the inventory commands.</summary>
internal enum InventoryRuleKind { None, Keep, Salvage, Other }
/// <summary>
/// A loot profile read for a command that judges what the character carries (2026-12-01 command
/// audit: /ub equip load|test and /ub autosalvage), not for looting: a VTank .utl or RynthAi's own
/// .json, read once for the command. Loading one never changes the loot profile in use.
/// </summary>
internal sealed class InventoryRules
{
private readonly VTankLootProfile? _utl;
private readonly LootProfile? _json;
/// <summary>The file it came from.</summary>
public string Path { get; }
public string FileName => System.IO.Path.GetFileName(Path);
public int RuleCount => _utl?.Rules.Count ?? _json?.Rules.Count ?? 0;
private InventoryRules(string path, VTankLootProfile? utl, LootProfile? json)
{
Path = path;
_utl = utl;
_json = json;
}
/// <summary>The profile at <paramref name="path"/>, or null with why not.</summary>
public static InventoryRules? Load(string path, out string error)
{
error = string.Empty;
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
{
error = "not found";
return null;
}
try
{
return path.EndsWith(".json", StringComparison.OrdinalIgnoreCase)
? new InventoryRules(path, null, LootProfile.Load(path))
: new InventoryRules(path, VTankLootParser.Load(path), null);
}
catch (Exception ex)
{
error = ex.Message;
return null;
}
}
/// <summary>For tests: rules already in memory.</summary>
internal static InventoryRules From(string path, VTankLootProfile profile) => new(path, profile, null);
/// <summary>
/// The first rule that takes <paramref name="item"/>, as the looter decides it
/// (<see cref="VTankLootEvaluator.Decide"/>): <see cref="VTankLootVerdict.NeedsId"/> when a rule
/// that could take it needs the item's identify data and <paramref name="hasIdData"/> is false.
/// A native .json profile needs no ID to decide.
/// </summary>
public VTankLootVerdict Decide(WorldObject item, VTankLootContext? ctx, CharacterSkills? skills, bool hasIdData,
out InventoryRuleKind kind, out string ruleName)
{
kind = InventoryRuleKind.None;
ruleName = string.Empty;
if (_utl != null)
{
VTankLootVerdict v = VTankLootEvaluator.Decide(_utl, item, ctx, hasIdData, out int index);
if (index >= 0)
{
VTankLootRule rule = _utl.Rules[index];
ruleName = LootWhy.NameOf(rule, index);
kind = rule.Action switch
{
VTankLootAction.Keep or VTankLootAction.KeepUpTo => InventoryRuleKind.Keep,
VTankLootAction.Salvage => InventoryRuleKind.Salvage,
_ => InventoryRuleKind.Other,
};
}
return v;
}
if (_json != null)
{
var (action, rule) = LootEvaluator.Classify(_json, item, skills);
if (rule == null) return VTankLootVerdict.NoMatch;
ruleName = string.IsNullOrWhiteSpace(rule.Name) ? "rule" : rule.Name.Trim();
kind = action switch
{
LootAction.Keep or LootAction.KeepUpTo => InventoryRuleKind.Keep,
LootAction.Salvage => InventoryRuleKind.Salvage,
_ => InventoryRuleKind.Other,
};
return VTankLootVerdict.Match;
}
return VTankLootVerdict.NoMatch;
}
}

View file

@ -106,11 +106,68 @@ public sealed partial class RynthAiPlugin
case "config":
// ub-IT: /mt config = /mt opt (list when bare).
return parts.Length < 3 ? HandleMtOpt(new[] { "/mt", "opt", "list" }) : HandleMtOpt(parts);
case "attack_melee": return HandleMtAttackMelee(parts);
default:
return false;
}
}
// ── attack_melee (2026-12-01 command audit) ─────────────────────────────────
internal const string MtAttackMeleeUsage = "[RynthAi] Usage: /mt attack_melee [closest]";
/// <summary>
/// /mt attack_melee [closest] (Mag-Tools), one step a call as Mag-Tools does it, so a meta sends it
/// again and again: out of melee mode it goes to melee mode; in melee mode it attacks the selected
/// monster once (the closest monster when none is selected, or with "closest", which it selects),
/// at RynthAi's melee attack height and power. It was "Unknown /mt command" before.
/// </summary>
private bool HandleMtAttackMelee(string[] parts)
{
bool closest = parts.Length >= 3 && parts[2].Equals("closest", StringComparison.OrdinalIgnoreCase);
if (parts.Length >= 3 && !closest) { ReplyFail(MtAttackMeleeUsage); return true; }
LegacyUi.LegacyUiSettings? s = _dashboard?.Settings;
if (_objectCache == null || _playerId == 0 || s == null) { ReplyFail("[RynthAi] /mt attack_melee: not ready (log in first)."); return true; }
if (!Host.HasMeleeAttack || !Host.HasChangeCombatMode) { ReplyFail("[RynthAi] /mt attack_melee: this RynthCore can't attack from a command."); return true; }
if (!Host.HasGetCurrentCombatMode || Host.GetCurrentCombatMode() != CombatMode.Melee)
{
Host.ChangeCombatModeFor(CombatMode.Melee, "Command", "/mt attack_melee", force: true);
ReplyOk("[RynthAi] /mt attack_melee: going to melee mode (the next one attacks).");
return true;
}
WorldObject? target = null;
uint sel = Host.GetSelectedItemId();
if (!closest && sel != 0 && _objectCache[unchecked((int)sel)] is { ObjectClass: AcObjectClass.Monster } picked)
target = picked;
if (target == null)
{
int me = unchecked((int)_playerId);
double best = double.MaxValue;
foreach (WorldObject wo in _objectCache.GetLandscapeObjects())
{
if (wo.ObjectClass != AcObjectClass.Monster || _objectCache.GetHealthRatio(wo.Id) == 0f) continue;
double d = _objectCache.Distance(me, wo.Id);
if (d < best) { best = d; target = wo; }
}
if (target == null) { ReplyFail("[RynthAi] /mt attack_melee: no monster nearby."); return true; }
if (Host.HasSelectItem) ItemInfo.SelfSelect.SelectAsBot(Host, unchecked((uint)target.Id));
}
int acHeight = s.MeleeAttackHeight switch { 0 => 3, 2 => 1, _ => 2 }; // Low=3, Med=2, High=1
float power = AttackPowerModes.Resolve(AttackPowerModes.Default, s.MeleeAttackPower, s.UseRecklessness,
_charSkills == null || _charSkills[AcSkillType.Recklessness].Training >= 2,
s.VariablePowerMin, s.VariablePowerMax, Random.Shared.NextDouble);
if (Host.MeleeAttack(unchecked((uint)target.Id), acHeight, power))
{
RynthCore.Plugin.Shared.ActionPacer.NoteAttackSent();
ReplyOk($"[RynthAi] /mt attack_melee: attacking {target.Name}.");
}
else ReplyFail($"[RynthAi] /mt attack_melee: the attack on {target.Name} wasn't sent.");
return true;
}
// ── send: keys, as Mag-Tools ────────────────────────────────────────────────
/// <summary>

View file

@ -179,7 +179,8 @@ public sealed partial class RynthAiPlugin
/// <summary>A Mag-Tools / VTank option RynthAi maps, or one a meta has stored (an unknown name reads as 0).</summary>
private bool OptionKnown(string optName)
=> MtOptionMap.ContainsKey(optName) || _metaManager?.Expressions?.Options.ContainsKey(optName) == true;
=> MtOptionMap.ContainsKey(optName) || MtSpecialOptions.Contains(optName)
|| _metaManager?.Expressions?.Options.ContainsKey(optName) == true;
/// <summary>
/// After /mt opt set (and /ub opt set): the option's value now. Bools read back as 1/0; asked as
@ -191,13 +192,13 @@ public sealed partial class RynthAiPlugin
bool askedBool = asked.ToLowerInvariant() is "true" or "false" or "on" or "off";
if (askedBool && now is "1" or "0") now = now == "1" ? "True" : "False";
ReplyOk($"[RynthAi] {optName} = {now}"
+ (MtOptionMap.ContainsKey(optName) ? "" : " (not an option RynthAi maps: kept only for metas to read)"));
+ (MtOptionMap.ContainsKey(optName) || MtSpecialOptions.Contains(optName) ? "" : " (not an option RynthAi maps: kept only for metas to read)"));
}
/// <summary>The /mt verbs RynthAi takes, for the usage line.</summary>
private const string MtVerbList = "opt, combatstate, face, cast[p], use[i|l][p], select[p], give[p], loot[p], drop[p], "
+ "equip[p], dequip[p], fellow, logout, quit, send, jump, trade, vendor, autopack, dumpspells, click, get xy, "
+ "cursor, movement, strafe, client, config, test";
+ "cursor, movement, strafe, client, config, attack_melee, test";
/// <summary>How to use a /mt (or, with <paramref name="prefix"/> "/ub", a translated /ub) verb; null when it isn't one.</summary>
private static string? MtVerbUsage(string verb, string prefix) => verb switch
@ -257,8 +258,8 @@ public sealed partial class RynthAiPlugin
["lootnearbychests"] = "LootNearbyChests", // Settings > Looting > Loot Nearby Chests
["dooropenrange"] = "OpenDoorRange",
["autofellowmanagement"] = "AutoFellowMgmt",
["switchwandstodebuff"] = "UseDispelItems",
["lootonlyrarecorpses"] = "MineOnly",
// switchwandstodebuff: not UseDispelItems (it turned dispel items on); kept for metas to read back (2026-12-01).
["lootonlyrarecorpses"] = "LootOnlyRareCorpses", // was MineOnly, which nothing reads (2026-12-01 command audit)
// VTank-meta migration aliases (mirror of MetaManager.VtOptionMap so options
// set via /ub opt / /mt opt resolve the same as /vt opt set).
["autocram"] = "EnableAutocram",
@ -299,10 +300,45 @@ public sealed partial class RynthAiPlugin
["autotrade.think"] = "AutoTradeThink",
["autotrade.onlyfrommainpack"] = "AutoTradeOnlyFromMainPack",
["autotrade.autoaccept"] = "AutoTradeAutoAccept",
// 2026-12-01 command audit: UtilityBelt and Mag-Tools options with the same RynthAi setting, which
// were only kept for metas to read.
["inventorymanager.autocram"] = "EnableAutocram", // UB: cram items into side packs
["inventorymanager.autostack"] = "EnableAutostack", // UB: stack items
["autobuysell.enabled"] = "AutoVendorEnabled", // Mag-Tools' vendor buy/sell on open (UB AutoVendor grew from it)
["autobuysell.testmode"] = "AutoVendorTestMode",
["autotradeadd.enabled"] = "AutoTradeEnabled", // Mag-Tools: add a profile's items when a trade opens
["looting.autolootchests"] = "LootChestsMacroOff", // Mag-Tools: a chest you open is looted by the loot profile
["looting.autolootmycorpse"] = "LootOwnCorpse", // Mag-Tools: your own corpse is emptied
["inventorymanagement.aetheriarevealer"] = "UnboxAetheriaWhenIdle", // reveal coalesced aetheria
["iteminfoonident.enabled"] = "ItemInfoOnSelect", // RynthAi's item info is Mag-Tools' (MagItemDescriber)
};
/// <summary>
/// Options set by hand below, not through the settings map: Mag-Tools' Tinkering.AutoClickYes ("Auto Click
/// Yes on 100%") is RynthAi's Auto-confirm crafting at 100 percent (2026-12-01 command audit).
/// </summary>
private static readonly HashSet<string> MtSpecialOptions = new(StringComparer.OrdinalIgnoreCase) { "tinkering.autoclickyes" };
private bool TrySetMtSpecialOption(string optName, string value)
{
if (!MtSpecialOptions.Contains(optName)) return false;
LegacyUiSettings? s = _dashboard?.Settings;
if (s == null) return true;
bool on = value is "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase);
bool off = value is "0" || value.Equals("false", StringComparison.OrdinalIgnoreCase);
if (on) { s.AutoConfirmCraft = true; s.AutoConfirmCraftPercent = 100; }
else if (off) s.AutoConfirmCraft = false;
return true;
}
private string? GetMtSpecialOption(string optName)
=> MtSpecialOptions.Contains(optName) && _dashboard?.Settings is { } s
? (s.AutoConfirmCraft && s.AutoConfirmCraftPercent >= 100 ? "1" : "0")
: null;
private string? GetOptionValue(string optName)
{
if (GetMtSpecialOption(optName) is string special) return special;
if (MtOptionMap.TryGetValue(optName, out string? raName))
{
var map = _metaManager?.Expressions?.BuildSettingsMapPublic();
@ -325,6 +361,7 @@ public sealed partial class RynthAiPlugin
_ => optVal
};
if (TrySetMtSpecialOption(optName, value)) return;
if (MtOptionMap.TryGetValue(optName, out string? raName))
{
var map = _metaManager?.Expressions?.BuildSettingsMapPublic();

View file

@ -85,6 +85,14 @@ internal sealed class ManaStoneManager
// low; no refill for a while instead of a stone every think tick.
private long _refillHoldUntil;
private const long RefillHoldMs = 2 * 60 * 1000;
// ...and once the hold ran out, the same stale read asked for a stone again: R-20261201-171624-0bcf (Coldeve),
// Loafers read 21% from before a refill, a stone every 2 minutes, each answered "Your items are fully
// charged" (the re-appraisal of 17 worn items didn't get through while looting was appraising). Now the
// server's "fully charged" stands for each worn item until its read changes (a newer appraisal) or the
// server says it is low: the read each item had then is kept, and that same read counts as full.
private readonly Dictionary<int, int> _gearFullAtRead = new();
private bool _gearFullSnapshotDue;
private long _lastNoStoneDiagAt;
// Worn gear's mana is read from its last appraisal, and ACE never sends a change to it while the
@ -312,16 +320,22 @@ internal sealed class ManaStoneManager
_host.Log($"[RynthAi] ManaStone: the server says worn gear is low ('{text.Trim()}') - refilling whatever the gear's mana reads say.");
_serverSaidGearLowAt = NowMs;
_refillHoldUntil = 0; // the server's word is newer than "fully charged"
_gearFullAtRead.Clear();
_gearFullSnapshotDue = false;
return;
}
// The stone-on-player reply's second line; it may arrive as a line of its own.
if (text.Contains("Your items are fully charged"))
{
_serverSaidGearLowAt = 0;
_gearFullSnapshotDue = true;
HoldRefills("the server says the worn items are fully charged");
}
if (text.Contains("no items equipped that need mana"))
{
_serverSaidGearLowAt = 0;
_gearFullSnapshotDue = true;
}
if (_state == TapState.TappingItem)
{
@ -833,6 +847,22 @@ internal sealed class ManaStoneManager
|| item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// What the charged-stone search looks at: the pack walk (the client's own pack lists, what
/// <see cref="HasEternalCharge"/> reads) first, then every object the cache knows. The walk can
/// hold an item the cache has no entry for yet: on 11-30 a character's gear sat at 30-46% mana for
/// an hour with "eternal=True needs=True" and "no charged stone is known" every minute, because
/// the search read the cache alone and the Eternal Mana Charge was only in the walk.
/// </summary>
private IEnumerable<WorldObject> RefillCandidates()
{
var seen = new HashSet<int>();
foreach (var item in _objectCache.GetDirectInventory(forceRefresh: false))
if (seen.Add(item.Id)) yield return item;
foreach (var item in _objectCache.AllKnownObjects())
if (seen.Add(item.Id)) yield return item;
}
// FindChargedStone walks every known object; with tapping off it gates the whole tick, so
// the answer is kept for a few seconds.
private long _chargedCheckAt;
@ -1014,7 +1044,7 @@ internal sealed class ManaStoneManager
int bestMana = 0;
bool requestedId = false;
foreach (var item in _objectCache.AllKnownObjects())
foreach (var item in RefillCandidates())
{
if (!IsRefillStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId) || !InPack(item.Id)) continue;
@ -1150,6 +1180,9 @@ internal sealed class ManaStoneManager
string lowestName = "";
bool needs = false;
bool requestedThisPass = false;
bool snapshot = _gearFullSnapshotDue; // the server just said full: keep each read it had then
_gearFullSnapshotDue = false;
int trustedFull = 0;
foreach (var item in _objectCache.AllKnownObjects())
{
@ -1214,6 +1247,13 @@ internal sealed class ManaStoneManager
requestedThisPass = true;
}
}
// The server said the gear is full since this read was taken: the same read counts as full.
if (snapshot) _gearFullAtRead[item.Id] = curMana;
if (_gearFullAtRead.TryGetValue(item.Id, out int fullRead))
{
if (fullRead == curMana) { trustedFull++; continue; }
_gearFullAtRead.Remove(item.Id); // a newer appraisal: the read is real again
}
int p = (int)(curMana * 100L / maxMana);
if (p < lowestPct) { lowestPct = p; lowestName = item.Name ?? ""; }
@ -1239,6 +1279,7 @@ internal sealed class ManaStoneManager
_lastGearDiagAt = now;
_host.Log($"[RynthAi] ManaStone: gear check - worn={worn} manaReadable={readable} lowest={(readable > 0 ? $"{lowestPct}% ({lowestName})" : "n/a")} " +
$"refillBelow={(int)(pct * 100)}% eternal={eternal} needs={needs} tapping={_settings.EnableManaTapping}" +
(trustedFull > 0 ? $" fullPerServer={trustedFull}" : "") +
(serverLow ? $" serverSaidLow={(now - _serverSaidGearLowAt) / 1000}s ago" : "") +
(now < _refillHoldUntil ? $" hold={(_refillHoldUntil - now) / 1000}s" : ""));
}

View file

@ -888,13 +888,21 @@ internal static class AfFileParser
/// Drops empty nav routes (header only, 0 points) from the dict and
/// blanks EmbedNav action data on rules whose referenced nav was empty.
/// Non-empty embedded navs survive in the dict for runtime + save.
/// A rule naming a route the file has NO block for keeps its name (2026-11-30): it is a
/// NavProfiles route (MetaNavEmbedding copies it in on load). It used to be blanked whenever
/// the meta had any block at all, so that rule loaded no route.
/// </summary>
private static void PruneEmbeddedNavs(List<MetaRule> rules,
Dictionary<string, List<string>> navRoutes)
{
if (navRoutes.Count == 0) return;
var toRemove = new List<string>();
// AfFileWriter writes an Embedded Nav Route with no route as "EmbedNav empty": no route,
// unless the meta carries one of that name (the blanking below used to catch it).
if (!navRoutes.ContainsKey(AfFileWriter.EmptyNavName))
ClearPlaceholderRefs(rules);
var toRemove = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var kvp in navRoutes)
{
var content = kvp.Value;
@ -904,23 +912,34 @@ internal static class AfFileParser
foreach (string key in toRemove)
navRoutes.Remove(key);
ClearMissingEmbedRefs(rules, navRoutes);
if (toRemove.Count > 0) ClearEmptyEmbedRefs(rules, toRemove);
}
private static void ClearMissingEmbedRefs(List<MetaRule> rules,
Dictionary<string, List<string>> navRoutes)
private static void ClearPlaceholderRefs(List<MetaRule> rules)
{
foreach (var rule in rules)
{
if (rule.Action == MetaActionType.EmbeddedNavRoute &&
string.Equals(rule.ActionData, AfFileWriter.EmptyNavName, StringComparison.Ordinal))
rule.ActionData = "";
if (rule.ActionChildren != null)
ClearPlaceholderRefs(rule.ActionChildren);
}
}
private static void ClearEmptyEmbedRefs(List<MetaRule> rules, HashSet<string> emptyRoutes)
{
foreach (var rule in rules)
{
if (rule.Action == MetaActionType.EmbeddedNavRoute &&
!string.IsNullOrEmpty(rule.ActionData) &&
!navRoutes.ContainsKey(rule.ActionData))
emptyRoutes.Contains(rule.ActionData))
{
rule.ActionData = "";
}
if (rule.ActionChildren != null)
ClearMissingEmbedRefs(rule.ActionChildren, navRoutes);
ClearEmptyEmbedRefs(rule.ActionChildren, emptyRoutes);
}
}

View file

@ -43,7 +43,7 @@ internal static class AfFileWriter
.OrderBy(g => g.Key)
.ToList();
// Collect embedded nav routes referenced by rules
// Collect embedded nav routes referenced by rules (cleaned, as the parser and MetaManager read them)
var navNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
CollectNavNames(rules, navNames);
@ -69,6 +69,18 @@ internal static class AfFileWriter
{
if (embeddedNavs.TryGetValue(navName, out var content))
WriteNavSection(writer, navName, content);
else
{
// A key kept in another spelling ("None]" from an old settings file): the route still goes in.
foreach (var kv in embeddedNavs)
{
if (string.Equals(EmbedNavName.Clean(kv.Key), navName, StringComparison.OrdinalIgnoreCase))
{
WriteNavSection(writer, navName, kv.Value);
break;
}
}
}
}
}
@ -94,6 +106,9 @@ internal static class AfFileWriter
// ── Rule writing ────────────────────────────────────────────────────────
/// <summary>The name written for an Embedded Nav Route with no route (metaf needs a tag); read back as none.</summary>
internal const string EmptyNavName = "empty";
/// <summary>A rule name on one line (it is written as a "~~ @name" comment line).</summary>
internal static string OneLine(string? text)
{
@ -275,7 +290,7 @@ internal static class AfFileWriter
case MetaActionType.EmbeddedNavRoute:
{
string navName = string.IsNullOrEmpty(data) ? "empty" : data.Split(';')[0];
string navName = string.IsNullOrEmpty(data) ? EmptyNavName : data.Split(';')[0];
writer.Write($"{keyword} {navName} {{[none]}}");
break;
}
@ -354,7 +369,8 @@ internal static class AfFileWriter
if (rule.Action == MetaActionType.EmbeddedNavRoute &&
!string.IsNullOrEmpty(rule.ActionData))
{
navNames.Add(rule.ActionData.Split(';')[0]);
string name = EmbedNavName.Clean(rule.ActionData.Split(';')[0]);
if (name.Length > 0) navNames.Add(name);
}
if (rule.ActionChildren != null)

View file

@ -387,6 +387,7 @@ internal sealed partial class ExpressionEngine
// ── List functions ────────────────────────────────────────────────
"listcreate" => EvalListCreate(rawArgs),
"createlist" => EvalListCreate(rawArgs), // UtilityBelt's own name (R-20261201-211257-d2be)
// These change the list (the reference: "Returns the list object"). A list is text
// here, so the changed list is written back to the variable it came from.
"listadd" => ListOp(rawArgs, A(0), l => EvalListAdd(l, A(1))),
@ -3728,6 +3729,12 @@ internal sealed partial class ExpressionEngine
["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),
// 2026-12-01 command audit: settings VTank options map onto (MetaManager.VtOptionMap).
["LootOnlyRareCorpses"] = (() => B(s.LootOnlyRareCorpses), v => s.LootOnlyRareCorpses = ToDouble(v) != 0),
["BlacklistAttempts"] = (() => I(s.BlacklistAttempts), v => { if (double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) && double.IsFinite(d)) s.BlacklistAttempts = Math.Clamp((int)Math.Round(d), 1, 20); }),
["ManaTapMinMana"] = (() => I(s.ManaTapMinMana), v => { if (double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) && double.IsFinite(d)) s.ManaTapMinMana = Math.Clamp((int)Math.Round(d), 0, 1_000_000); }),
["RestamOthersAt"] = (() => I(s.RestamOthersAt), v => { if (int.TryParse(v, out int i)) s.RestamOthersAt = Math.Clamp(i, 0, 100); }),
["InfuseOthersAt"] = (() => I(s.InfuseOthersAt), v => { if (int.TryParse(v, out int i)) s.InfuseOthersAt = Math.Clamp(i, 0, 100); }),
["UseDispelItems"] = (() => B(s.UseDispelItems), v => s.UseDispelItems = ToDouble(v) != 0),
["CastDispelSelf"] = (() => B(s.CastDispelSelf), v => s.CastDispelSelf = ToDouble(v) != 0),
["AutoFellowMgmt"] = (() => B(s.AutoFellowMgmt), v => s.AutoFellowMgmt = ToDouble(v) != 0),
@ -3796,6 +3803,7 @@ internal sealed partial class ExpressionEngine
["CastBuffsOverItemBuffs"] = (() => B(s.CastBuffsOverItemBuffs), v => s.CastBuffsOverItemBuffs = ToDouble(v) != 0),
["FastBuffChain"] = (() => B(s.FastBuffChain), v => s.FastBuffChain = ToDouble(v) != 0),
["SkipUnusableBuffs"] = (() => B(s.SkipUnusableBuffs), v => s.SkipUnusableBuffs = ToDouble(v) != 0),
["RecastDispelledInFight"] = (() => B(s.RecastDispelledInFight), v => s.RecastDispelledInFight = ToDouble(v) != 0),
["UseFellowshipBuffs"] = (() => B(s.UseFellowshipBuffs), v => s.UseFellowshipBuffs = ToDouble(v) != 0),
["BuffShield"] = (() => B(s.BuffShield), v => s.BuffShield = ToDouble(v) != 0),
// AutoVendor (UB names map here through /ub opt: AutoVendor.Enabled -> AutoVendorEnabled, ...)

View file

@ -53,6 +53,7 @@ internal sealed partial class MetaManager
s.RouteLines = _settings.CurrentRoute != null && _settings.CurrentRoute.Points.Count > 0
? new List<string>(_settings.CurrentRoute.ToLines())
: new List<string>();
s.RouteMadeBy = _settings.CurrentRoute?.MadeBy ?? "";
s.NavIndex = _settings.ActiveNavIndex;
s.NavEnabled = _settings.EnableNavigation;
}
@ -107,6 +108,7 @@ internal sealed partial class MetaManager
_settings.CurrentNavPath = s.NavPath;
_settings.CurrentRoute = s.RouteLines.Count > 0 ? NavRouteParser.LoadFromLines(s.RouteLines) : new NavRouteParser();
_settings.CurrentRoute.MadeBy = s.RouteMadeBy ?? "";
_settings.ActiveNavIndex = Math.Clamp(s.NavIndex, 0, Math.Max(0, _settings.CurrentRoute.Points.Count));
_settings.EnableNavigation = s.NavEnabled;
}

View file

@ -1405,6 +1405,32 @@ internal sealed partial class MetaManager
return true;
}
// /vt meta save <name> — the loaded meta saved under that name, which is then its file (2026-12-01
// command audit: it answered with the usage). /ra meta saveas: the same file again saves it, another
// existing one is refused (a command never replaces a file).
if (sub == "meta" && parts.Length >= 4 &&
parts[2].Equals("save", StringComparison.OrdinalIgnoreCase))
{
_raCommandHandler?.Invoke("/ra meta saveas " + string.Join(" ", parts, 3, parts.Length - 3));
return true;
}
// /vt loot save <name> — a copy of the loot profile in use under that name, then looted with (as
// VTank's save does; 2026-12-01 command audit). The profile in use itself is already saved.
if ((sub == "loot" || sub == "lootprofile" || sub == "looting") && parts.Length >= 4 &&
parts[2].Equals("save", StringComparison.OrdinalIgnoreCase))
{
string name = string.Join(" ", parts, 3, parts.Length - 3).Trim().Trim('"');
string current = _settings.CurrentLootPath ?? string.Empty;
if (current.Length > 0 && IsLootProfileNamed(current, name))
{
Reply.Ok($"[RynthAi] {Path.GetFileName(current)} is the loot profile in use; it is saved (the Loot Editor saves its changes).");
return true;
}
_raCommandHandler?.Invoke("/ra loot saveas " + name);
return true;
}
// /vt nav load <name> — load a nav route
// It used to store only the bare name as the nav path, so nothing loaded.
// /vt nav save <name> saves the current route under that name.
@ -1461,15 +1487,20 @@ internal sealed partial class MetaManager
return true;
}
// /vt settings loadchar|savechar <name> — RynthAi's settings profiles (/ra settings ...);
// universalremote.met switches profiles this way. Any other /vt settings verb is ignored.
// /vt settings loadchar|savechar|load|save <name> — RynthAi's settings profiles (/ra settings ...);
// universalremote.met switches profiles this way. VTank's load|save are its shared profiles and
// loadchar|savechar this character's; RynthAi's profiles are all the character's, so both pairs are
// the same here (load|save answered with the usage until the 2026-12-01 command audit).
if (sub == "settings")
{
if (parts.Length >= 4 && (parts[2].Equals("loadchar", StringComparison.OrdinalIgnoreCase)
|| parts[2].Equals("savechar", StringComparison.OrdinalIgnoreCase)))
_raCommandHandler?.Invoke($"/ra settings {parts[2].ToLowerInvariant()} {string.Join(" ", parts, 3, parts.Length - 3)}");
string verb = parts.Length >= 4 ? parts[2].ToLowerInvariant() : "";
if (verb is "loadchar" or "load") verb = "loadchar";
else if (verb is "savechar" or "save") verb = "savechar";
else verb = "";
if (verb.Length > 0)
_raCommandHandler?.Invoke($"/ra settings {verb} {string.Join(" ", parts, 3, parts.Length - 3)}");
else
Reply.Ignored("[RynthAi] Usage: /vt settings loadchar|savechar <name> (other /vt settings verbs are VTank's own; ignored).");
Reply.Ignored("[RynthAi] Usage: /vt settings load|save|loadchar|savechar <name> (other /vt settings verbs are VTank's own; ignored).");
return true;
}
@ -1515,19 +1546,58 @@ internal sealed partial class MetaManager
return true;
}
// /vt reverseroute — reverse the active nav route in place (shared settings;
// the engine re-reads CurrentRoute each tick, so the flip takes effect next tick).
// /vt reverseroute [true|false] — the route's direction (shared settings; the engine re-reads
// CurrentRoute each tick). VTank sets it from the argument: true = reversed, false = the file's own
// order, none = the other way. It flipped on every call before (2026-12-01 command audit: a meta
// sending "reverseroute true" on each state entry ran the route the wrong way every other time).
// A route newly loaded is the file's way round. /vt reverseroutequery says which way it is.
if (sub == "reverseroute")
{
var route = _settings.CurrentRoute;
if (route?.Points != null && route.Points.Count > 0)
if (route?.Points == null || route.Points.Count == 0)
{
Reply.Fail("[RynthAi] /vt reverseroute: no route is loaded.");
return true;
}
bool reversedNow = RouteReversed;
bool? asked = parts.Length >= 3 ? ParseVtBool(parts[2]) : null;
if (parts.Length >= 3 && asked == null)
{
Reply.Fail("[RynthAi] Usage: /vt reverseroute [true|false]");
return true;
}
bool want = asked ?? !reversedNow;
int n = route.Points.Count;
if (want != reversedNow)
{
int n = route.Points.Count;
route.Points.Reverse();
_settings.ActiveNavIndex = Math.Clamp(n - 1 - _settings.ActiveNavIndex, 0, n - 1);
Reply.Ok($"[RynthAi] Route reversed ({n} pts).");
}
else Reply.Fail("[RynthAi] /vt reverseroute: no route is loaded.");
_reversedRoute = route;
_routeReversed = want;
Reply.Ok(want == reversedNow
? $"[RynthAi] Route already {(want ? "reversed" : "in its own order")} ({n} pts)."
: $"[RynthAi] Route {(want ? "reversed" : "back in its own order")} ({n} pts).");
return true;
}
// /vt addnavjump <heading> <shift true|false> <milliseconds> [...]: a jump step at the end of the route
// (VTank's form), as /ra nav addjump does with a given heading (2026-12-01 command audit).
if (sub == "addnavjump")
{
if (parts.Length < 5
|| !float.TryParse(parts[2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float jh)
|| ParseVtBool(parts[3]) is not bool jshift
|| !int.TryParse(parts[4], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int jms))
{
Reply.Fail("[RynthAi] Usage: /vt addnavjump <heading> <shift true|false> <milliseconds>");
return true;
}
_raCommandHandler?.Invoke(FormattableString.Invariant($"/ra nav addjump {Math.Clamp(jms, 0, 1000)}{(jshift ? " shift" : "")} heading {jh}"));
return true;
}
if (sub == "reverseroutequery")
{
Reply.Ok($"[RynthAi] Route reversed: {(RouteReversed ? "true" : "false")}.");
return true;
}
@ -1566,8 +1636,8 @@ internal sealed partial class MetaManager
/// <summary>The /vt verbs RynthAi takes, for the usage line.</summary>
internal const string VtVerbList = "opt set|get|list, <option> <value>, start, stop, e, jump, tapjump, equipitemsfor, "
+ "meta load, nav load|save, loot load, setmetastate, settings loadchar|savechar, setattackbar, forcebuff, "
+ "cancelforcebuff, cancelbuff, addnavpt, mexec, clearbusy, testitem, propertydump, reverseroute, echo";
+ "meta load|save, nav load|save, loot load|save, setmetastate, settings load|save|loadchar|savechar, setattackbar, forcebuff, "
+ "cancelforcebuff, cancelbuff, addnavpt, addnavjump, mexec, clearbusy, testitem, propertydump, reverseroute [true|false], reverseroutequery, echo";
/// <summary>The usage line for a /vt line RynthAi didn't take (an unknown verb or the wrong arguments).</summary>
internal static string VtUsageFor(string line)
@ -1577,9 +1647,9 @@ internal sealed partial class MetaManager
string? usage = verb switch
{
"opt" => "/vt opt set <option> <value> | /vt opt get <option> | /vt opt list",
"meta" => "/vt meta load <name>",
"meta" => "/vt meta load|save <name>",
"nav" => "/vt nav load <name> | /vt nav save <name>",
"loot" or "lootprofile" or "looting" => "/vt loot load <profile>",
"loot" or "lootprofile" or "looting" => "/vt loot load|save <profile>",
"setmetastate" => "/vt setmetastate <state>",
"equipitemsfor" => "/vt equipitemsfor <monster name>",
"setattackbar" => "/vt setattackbar <0 to 1>",
@ -1591,6 +1661,19 @@ internal sealed partial class MetaManager
: $"[RynthAi] Unknown /vt command{(verb.Length > 0 ? $" '{verb}'" : "")}. RynthAi takes: {VtVerbList}.";
}
/// <summary>
/// <paramref name="path"/> is the loot profile <paramref name="name"/> names: its file name, or its file
/// name without the extension (any case).
/// </summary>
internal static bool IsLootProfileNamed(string path, string name)
{
string n = name.Trim().Trim('"');
if (n.Length == 0) return false;
string file = Path.GetFileName(path);
return file.Equals(Path.GetFileName(n), StringComparison.OrdinalIgnoreCase)
|| Path.GetFileNameWithoutExtension(file).Equals(Path.GetFileName(n), StringComparison.OrdinalIgnoreCase);
}
/// <summary>The RynthAi setting a VTank option name maps to (EnableNav → EnableNavigation).</summary>
internal static bool TryMapVtOption(string vtName, out string raName)
{
@ -1633,8 +1716,13 @@ internal sealed partial class MetaManager
["lootnearbychests"] = "LootNearbyChests", // Settings > Looting > Loot Nearby Chests
["dooropenrange"] = "OpenDoorRange",
["autofellowmanagement"] = "AutoFellowMgmt",
["switchwandstodebuff"] = "UseDispelItems",
["lootonlyrarecorpses"] = "MineOnly",
// "SwitchWandToDebuff" (VTank: switch to the monster's wand even just to debuff it) was mapped here, as
// "switchwandstodebuff", to UseDispelItems: a meta setting it turned dispel items on (2026-12-01 command
// audit). RynthAi has no such switch; the option is kept for metas to read back, nothing else.
// VTank's Loot Only Rare Corpses is RynthAi's setting of that name (2026-11-22). It was mapped to
// MineOnly, a setting nothing reads, so a meta asking for rare corpses only looted every corpse
// (2026-12-01 command audit).
["lootonlyrarecorpses"] = "LootOnlyRareCorpses",
// Phase 1.2 VTank-meta migration aliases (targets verified in BuildSettingsMap)
["autocram"] = "EnableAutocram",
["autostack"] = "EnableAutostack",
@ -1674,6 +1762,15 @@ internal sealed partial class MetaManager
["rebufftimeremainingseconds"] = "RebuffSecondsRemaining", // VTank's spelling (the one above is a typo)
["petcustomrange"] = "CustomPetRange", // landblock units -> whole yards
["blacklistmonstertimeoutseconds"] = "BlacklistTimeoutSec",
// 2026-12-01 command audit: VTank options that were only stored though RynthAi has the same setting.
["corpeapproachrange-min"] = "CorpseApproachRangeMin", // VTank's own spelling in its option list
["blacklistmonsterattemptcount"] = "BlacklistAttempts", // misses (no damage) before a monster is blacklisted
["manachargeswhenoff"] = "ManaTapMacroOff", // stones keep worn gear filled with the macro off too
["manatankminimummana"] = "ManaTapMinMana", // an item must hold this much mana to be drained into a stone
// Fellow vitals (Recharge-Helper-*): RynthAi keeps these percents but doesn't heal others yet.
["recharge-helper-hitp"] = "HealOthersAt",
["recharge-helper-stam"] = "RestamOthersAt",
["recharge-helper-mana"] = "InfuseOthersAt",
};
/// <summary>VTank options given in landblock units (x240 = yards) whose RynthAi setting is yards.
@ -1682,6 +1779,7 @@ internal sealed partial class MetaManager
{
"attackdistance", "attackrange", "approachdistance", "dooropenrange", "opendoorrange", "ringdistance",
"corpseapproachrange", "corpseapproachrange-max", "corpseapproachrange-min", "petcustomrange",
"corpeapproachrange-min",
};
/// <summary>RynthAi distance settings kept in whole yards (their setter refuses a decimal).</summary>
@ -1715,12 +1813,28 @@ internal sealed partial class MetaManager
/// <summary>VTank options handled by <see cref="TrySetSpecialVtOption"/> (no 1:1 RynthAi setting).</summary>
private static bool IsSpecialVtOption(string vtName) => vtName.ToLowerInvariant() is
"defaultmeleeattackheight" or "lootfellowcorpses" or "lootallcorpses" or "usearcs" or "minimumhealkitsuccesschance"
or "autoattackpower";
or "autoattackpower" or "targetselectmethod" or "debuffeachfirst";
// The last /vt setattackbar power (percent), for AutoAttackPower false after it was on (-1 = none yet).
private int _lastAttackBarPct = -1;
private bool _deleteMonsterLogged;
// /vt reverseroute: the route the direction was set for, and whether it runs reversed. Another
// route loaded (a new object) is in its own order.
private NavRouteParser? _reversedRoute;
private bool _routeReversed;
/// <summary>The loaded route runs reversed (set by /vt reverseroute; a new route starts in its own order).</summary>
internal bool RouteReversed => _routeReversed && ReferenceEquals(_reversedRoute, _settings.CurrentRoute);
/// <summary>true/false, on/off, 1/0, yes/no (any case); null for anything else.</summary>
private static bool? ParseVtBool(string s) => s.Trim().ToLowerInvariant() switch
{
"true" or "on" or "1" or "yes" => true,
"false" or "off" or "0" or "no" => false,
_ => null,
};
/// <summary>
/// The VTank options whose value means something else in RynthAi:
/// DefaultMeleeAttackHeight 1-3 (low/medium/high) is RynthAi's 0-2; LootFellowCorpses /
@ -1756,6 +1870,22 @@ internal sealed partial class MetaManager
if (!num) return true;
_settings.KitMinSuccessPct = Math.Clamp((int)Math.Round(n > 0 && n <= 1 ? n * 100 : n), 0, 100);
return true;
case "targetselectmethod":
// VTank 1 By Range, 2 By Angle, 3 Both (near by angle, far by range). RynthAi's Targeting has
// Closest (1) and Least turning (3); it has no "both", so 3 is only kept (2026-12-01 command audit).
if (!num) return true;
Expressions.SetOption("TargetSelectMethod", value);
if ((int)Math.Round(n) == 1) _settings.TargetSelection = 1;
else if ((int)Math.Round(n) == 2) _settings.TargetSelection = 3;
return true;
case "debuffeachfirst":
// VTank 1 One (debuff one, attack it), 2 Priority (debuff the same priority first), 3 All. RynthAi's
// Debuff every monster in range before attacking is All on, One off; Priority is only kept.
if (!num) return true;
Expressions.SetOption("DebuffEachFirst", value);
if ((int)Math.Round(n) == 1) _settings.DebuffAllBeforeAttacking = false;
else if ((int)Math.Round(n) == 3) _settings.DebuffAllBeforeAttacking = true;
return true;
case "autoattackpower":
// On: RynthAi picks the power itself (-1, its "auto"). Off: the attack bar's value,
// the last /vt setattackbar (a power already set by hand stays as it is).
@ -1786,9 +1916,19 @@ internal sealed partial class MetaManager
"usearcs" => _settings.UseArcs ? "true" : "false",
"minimumhealkitsuccesschance" => _settings.KitMinSuccessPct.ToString(System.Globalization.CultureInfo.InvariantCulture),
"autoattackpower" => _settings.MeleeAttackPower < 0 ? "true" : "false",
// RynthAi's Targeting as VTank's number; another RynthAi choice reads the value a meta last set.
"targetselectmethod" => _settings.TargetSelection switch { 1 => "1", 3 => "2", _ => StoredVtOption("TargetSelectMethod") },
"debuffeachfirst" => _settings.DebuffAllBeforeAttacking ? "3" : StoredVtOption("DebuffEachFirst") == "2" ? "2" : "1",
_ => null,
};
/// <summary>A VTank option a meta set that is only kept, or null when none was.</summary>
private string? StoredVtOption(string name)
{
string v = Expressions.GetOption(name);
return v.Length == 0 || v == "0" ? null : v;
}
/// <summary>A VTank option's current value (mapped setting, else a stored generic option).</summary>
private string? GetVtOption(string vtName)
{

View file

@ -0,0 +1,250 @@
using System;
using System.Collections.Generic;
using System.IO;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.Meta;
/// <summary>
/// An Embedded Nav Route carries its route inside the meta (2026-11-30: the route is embedded,
/// so the meta still works with the .nav file deleted from the drive).
///
/// It didn't: the Meta panel's route picker stores the name of a NavProfiles file, and the meta was
/// saved with only the routes it already held in memory (those that came in a .met or a NAVDATA
/// block), so a route picked from NavProfiles stayed a file the meta read at run time. Now:
/// - picking a route (a new rule, or a rule whose route changed) copies that file in, replacing an
/// older copy of the same name (<see cref="EmbedPicked"/>);
/// - every meta save copies in any route a rule names that the meta doesn't carry yet
/// (<see cref="EmbedMissing"/>), so an older meta becomes self-contained on its next save or load.
/// Once a route is in the meta, the meta's copy is the one that runs; the file can go.
/// "[None]", "Patrol" and "Camp" with no file behind them are not routes (MetaManager), and a file
/// with no points is not copied (the parser drops an empty route and clears the rules naming it).
/// </summary>
internal static class MetaNavEmbedding
{
/// <summary>The route names the Embedded Nav Route actions of <paramref name="rules"/> (and their DoAll steps) use.</summary>
public static HashSet<string> RouteNames(IEnumerable<MetaRule> rules)
{
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (MetaRule r in rules) Collect(r, names);
return names;
}
/// <summary>The route names one rule's Embedded Nav Route actions use.</summary>
public static HashSet<string> RouteNames(MetaRule? rule)
{
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (rule != null) Collect(rule, names);
return names;
}
/// <summary>
/// Copies into <paramref name="embedded"/> every route <paramref name="rules"/> name that it has no
/// route for yet, from <paramref name="navFolder"/>. Returns the names copied (empty: nothing to do).
/// </summary>
public static List<string> EmbedMissing(IEnumerable<MetaRule> rules, IDictionary<string, List<string>> embedded,
string navFolder, Action<string>? log = null)
{
var done = new List<string>();
foreach (string name in RouteNames(rules))
{
if (FindKey(embedded, name) != null) continue;
if (TryRead(navFolder, name, out List<string> lines))
{
embedded[name] = lines;
done.Add(name);
log?.Invoke($"[RynthAi] Meta: embedded route '{name}' from {Path.Combine(navFolder, name + ".nav")} ({PointCount(lines)} pts)");
}
}
return done;
}
/// <summary>
/// A rule edit picked a route: each route <paramref name="after"/> names that <paramref name="before"/>
/// didn't (a new rule: all of them) is copied in from its NavProfiles file, replacing the meta's older
/// copy of that name. A route with no file keeps the meta's copy. Returns the names copied.
/// </summary>
public static List<string> EmbedPicked(MetaRule after, MetaRule? before, IDictionary<string, List<string>> embedded,
string navFolder, Action<string>? log = null, ISet<string>? fromMemory = null)
{
var done = new List<string>();
HashSet<string> had = RouteNames(before);
foreach (string name in RouteNames(after))
{
if (had.Contains(name)) continue;
if (fromMemory != null && fromMemory.Contains(name)) continue; // "Embed loaded" just copied it
if (!TryRead(navFolder, name, out List<string> lines)) continue;
string? old = FindKey(embedded, name);
if (old != null) embedded.Remove(old);
embedded[name] = lines;
done.Add(name);
log?.Invoke($"[RynthAi] Meta: embedded route '{name}' from {Path.Combine(navFolder, name + ".nav")} ({PointCount(lines)} pts){(old != null ? ", replacing the meta's older copy" : "")}");
}
return done;
}
// ── "Embed loaded" (the Meta panel's button, VTank's way) ───────────────────────────────────
// 2026-11-30: with a nav route loaded, a click on the Meta panel's button embeds that route. The snapshot tells the panel the loaded route's name (or why it
// can't be embedded: DescribeLoaded); the button sets the action to that name with LoadedMarker
// after it; the rule's save carries the marker here once (TakeLoadedMarkers), the route in memory
// is copied in under that name (EmbedLoaded), and the rule keeps the plain name.
/// <summary>After an Embedded Nav Route's name in a rule the panel sends: "copy the loaded route in under this name".</summary>
public const string LoadedMarker = ";loaded";
/// <summary>
/// The loaded route as "Embed loaded" would take it: its name (the meta's own name for a route from
/// the meta, the file's name relative to <paramref name="navFolder"/> for a .nav, a new "Route N"
/// for one made in the nav editor or recorded), its point count, and a note that is empty when it
/// can be embedded, else why not (no route; a route a feature built, <see cref="NavRouteParser.MadeBy"/>).
/// </summary>
public static (string Name, int Points, string Note) DescribeLoaded(NavRouteParser? route, string? navPath,
string navFolder, IDictionary<string, List<string>> embedded)
{
int points = route?.Points.Count ?? 0;
bool follow = route != null && route.RouteType == NavRouteType.Follow && route.FollowTargetName.Length > 0;
if (route == null || (points == 0 && !follow))
return (string.Empty, 0, "No nav route is loaded. Load or record one, then embed it.");
if (route.MadeBy.Length > 0)
return (string.Empty, points, $"The loaded route was made by {route.MadeBy}, not loaded or recorded, so it isn't embedded. Load or record a route.");
string path = navPath ?? string.Empty;
if (path.StartsWith("<embedded:", StringComparison.OrdinalIgnoreCase) && path.EndsWith(">", StringComparison.Ordinal))
{
string key = EmbedNavName.Clean(path.Substring(10, path.Length - 11));
if (key.Length > 0 && !EmbedNavName.IsNone(key)) return (key, points, string.Empty);
return (UniqueName(navFolder, embedded), points, string.Empty);
}
if (path.StartsWith("<", StringComparison.Ordinal))
return (string.Empty, points, $"The loaded route isn't a nav route ({path}), so it isn't embedded.");
if (path.Length > 0)
{
string name = FileRouteName(path, navFolder);
if (name.Length > 0 && !EmbedNavName.IsNone(name)) return (name, points, string.Empty);
}
return (UniqueName(navFolder, embedded), points, string.Empty);
}
/// <summary>
/// Strips <see cref="LoadedMarker"/> from <paramref name="rule"/>'s Embedded Nav Route actions (and its
/// DoAll steps) and returns the names that carried it.
/// </summary>
public static List<string> TakeLoadedMarkers(MetaRule rule)
{
var names = new List<string>();
Take(rule, names);
return names;
static void Take(MetaRule r, List<string> into)
{
if (r.Action == MetaActionType.EmbeddedNavRoute && r.ActionData != null
&& r.ActionData.EndsWith(LoadedMarker, StringComparison.OrdinalIgnoreCase))
{
string name = EmbedNavName.Clean(r.ActionData.Substring(0, r.ActionData.Length - LoadedMarker.Length));
r.ActionData = name;
if (name.Length > 0) into.Add(name);
}
if (r.ActionChildren != null)
foreach (MetaRule c in r.ActionChildren) Take(c, into);
}
}
/// <summary>
/// Copies the loaded <paramref name="route"/> into <paramref name="embedded"/> as <paramref name="name"/>,
/// replacing the meta's copy of that name. Null when it was copied, else why not (DescribeLoaded's note).
/// </summary>
public static string? EmbedLoaded(string name, NavRouteParser? route, string? navPath, string navFolder,
IDictionary<string, List<string>> embedded, Action<string>? log = null)
{
var (_, points, note) = DescribeLoaded(route, navPath, navFolder, embedded);
if (note.Length > 0) return note;
if (string.IsNullOrWhiteSpace(name) || EmbedNavName.IsNone(name)) return "the route has no name to keep it under";
List<string> lines = route!.ToLines();
if (lines.Count < 3) return "the loaded route didn't write out";
string? old = FindKey(embedded, name);
if (old != null) embedded.Remove(old);
embedded[name] = lines;
log?.Invoke($"[RynthAi] Meta: embedded the loaded route as '{name}' ({points} pts{(string.IsNullOrEmpty(navPath) ? ", never saved to a file" : ", from " + navPath)}){(old != null ? ", replacing the meta's older copy" : "")}");
return null;
}
/// <summary>A .nav file's route name: relative to NavProfiles without ".nav" (as the nav list shows it), else the file name.</summary>
internal static string FileRouteName(string path, string navFolder)
{
try
{
string full = Path.GetFullPath(path);
string root = Path.GetFullPath(navFolder).TrimEnd('\\', '/') + Path.DirectorySeparatorChar;
string rel = full.StartsWith(root, StringComparison.OrdinalIgnoreCase) ? full.Substring(root.Length) : Path.GetFileName(full);
if (rel.EndsWith(".nav", StringComparison.OrdinalIgnoreCase)) rel = rel.Substring(0, rel.Length - 4);
return EmbedNavName.Clean(rel);
}
catch { return string.Empty; }
}
/// <summary>"Route N", the first N with no route of that name in the meta or NavProfiles.</summary>
internal static string UniqueName(string navFolder, IDictionary<string, List<string>> embedded)
{
for (int n = 1; ; n++)
{
string name = "Route " + n.ToString(System.Globalization.CultureInfo.InvariantCulture);
if (FindKey(embedded, name) != null) continue;
try { if (!string.IsNullOrEmpty(navFolder) && File.Exists(Path.Combine(navFolder, name + ".nav"))) continue; }
catch { }
return name;
}
}
/// <summary>The key <paramref name="embedded"/> files <paramref name="name"/> under (any case, stray brackets), or null.</summary>
public static string? FindKey(IDictionary<string, List<string>> embedded, string name)
{
if (embedded.ContainsKey(name))
{
foreach (string k in embedded.Keys)
if (string.Equals(k, name, StringComparison.OrdinalIgnoreCase)) return k;
}
foreach (string k in embedded.Keys)
if (string.Equals(EmbedNavName.Clean(k), name, StringComparison.OrdinalIgnoreCase)) return k;
return null;
}
/// <summary>
/// NavProfiles\&lt;name&gt;.nav as the meta keeps it (canonical uTank2 lines), when the file is a route
/// with points (or a Follow nav). A name that leaves the folder, "[None]" and an unreadable file give false.
/// </summary>
public static bool TryRead(string navFolder, string name, out List<string> lines)
{
lines = new List<string>();
if (string.IsNullOrWhiteSpace(navFolder) || string.IsNullOrWhiteSpace(name) || EmbedNavName.IsNone(name)) return false;
string path;
try
{
string root = Path.GetFullPath(navFolder).TrimEnd('\\', '/');
path = Path.GetFullPath(Path.Combine(root, name + ".nav"));
if (!path.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) return false;
}
catch { return false; }
if (!File.Exists(path)) return false;
NavRouteParser route = NavRouteParser.Load(path);
if (route.LoadWarning?.Length > 0) return false;
bool follow = route.RouteType == NavRouteType.Follow && route.FollowTargetName.Length > 0;
if (route.Points.Count == 0 && !follow) return false;
lines = route.ToLines();
return lines.Count >= 3;
}
private static int PointCount(List<string> lines) => NavRouteParser.LoadFromLines(lines).Points.Count;
private static void Collect(MetaRule rule, HashSet<string> names)
{
if (rule.Action == MetaActionType.EmbeddedNavRoute && !string.IsNullOrWhiteSpace(rule.ActionData))
{
string name = EmbedNavName.Clean(rule.ActionData.Split(';')[0]);
if (name.Length > 0) names.Add(name);
}
if (rule.ActionChildren != null)
foreach (MetaRule c in rule.ActionChildren) Collect(c, names);
if (rule.Children != null) // as AfFileWriter collects them
foreach (MetaRule c in rule.Children) Collect(c, names);
}
}

View file

@ -71,6 +71,8 @@ internal sealed class MetaResumeState
public string NavPath = "";
public List<string> RouteLines = new();
/// <summary>NavRouteParser.MadeBy of the running route (a patrol's, a hunt's...): kept so "Embed loaded" still refuses it after the reload.</summary>
public string RouteMadeBy = "";
public int NavIndex;
public bool NavEnabled;
}
@ -152,6 +154,7 @@ internal static class MetaResumeStore
Line(sb, "nextsw", s.NextStopwatchId.ToString(Ic));
Line(sb, "navpath", Esc(s.NavPath));
foreach (string l in s.RouteLines) Line(sb, "route", Esc(l));
if (s.RouteMadeBy.Length > 0) Line(sb, "routemadeby", Esc(s.RouteMadeBy));
Line(sb, "navindex", s.NavIndex.ToString(Ic));
Line(sb, "navon", s.NavEnabled ? "1" : "0");
Line(sb, "end", "1"); // a torn write never parses
@ -244,6 +247,7 @@ internal static class MetaResumeStore
case "nextsw": s.NextStopwatchId = int.Parse(v, Ic); break;
case "navpath": s.NavPath = Un(v); break;
case "route": s.RouteLines.Add(Un(v)); break;
case "routemadeby": s.RouteMadeBy = Un(v); break;
case "navindex": s.NavIndex = int.Parse(v, Ic); break;
case "navon": s.NavEnabled = v == "1"; break;
case "end": end = v == "1"; break;

View file

@ -16,7 +16,8 @@ namespace RynthCore.Plugin.RynthAi;
/// in a straight line. A monster with no walkable way to it (on a cliff, in water, inside a closed
/// building) is left out for <see cref="SkipSec"/>. Monsters are looked for out to <see cref="RangeYd"/>
/// (Hunt Range); <see cref="RadiusYd"/> (Hunt Radius) keeps the picks within that far of where it started
/// (0 = anywhere). With nothing in range it waits where it is. That is <see cref="PickMode.Nearest"/>;
/// (0 = anywhere). With nothing in range it roams (<see cref="Roam"/>, 2026-12-01), else waits where it is.
/// That is <see cref="PickMode.Nearest"/>;
/// since 2026-11-08 the setting can go for the biggest pack or the most experience instead (PickPack).
///
/// Buildings (2026-10-25, Tom: "the entire radar range, also going inside houses"): RynthNav's map ends
@ -217,6 +218,33 @@ internal sealed class OutdoorHunt
private Func<Vec, Vec, PathResult> _path = (_, _) => new PathResult(PathStatus.Unavailable, Array.Empty<Vec>(), 0, 0);
private IBuildings? _buildings;
private int _meBuilding; // the building the character is in this tick (0: outdoors)
private uint _meCellNow; // the character's cell this tick (the roam's walks)
// ── Roaming (2026-12-01, report R-20261127-181056-32e4: "it starts to run around but only when mobs are
// there ... would be ideal to map out the area and continue running around the place for more mobs
// not just stop when it cant see any"; it should move around the Hunt Radius) ──
// The area (Hunt Radius round where it started; Hunt Range when the radius is "anywhere") is cut into
// squares. Every square the character passes through is seen; with no monster to go for, the hunt walks to
// the nearest square not seen for RoamRevisitSec (respawns), and on from there. A square it can't get to is
// left out for RoamSkipSec. A monster in range ends the roam at the next pick, as before.
/// <summary>Roam the area when nothing is in range (the setting OutdoorHuntRoam, on by default).</summary>
public bool Roam { get; set; } = true;
/// <summary>The squares' side, at least this; bigger in a big area so there are at most about RoamMaxSquares.</summary>
public double RoamCellMinYd { get; set; } = 40;
public const int RoamMaxSquares = 400;
/// <summary>A square seen this long ago is worth a look again (monsters respawn).</summary>
public double RoamRevisitSec { get; set; } = 300;
/// <summary>A square no walk gets to is left out this long.</summary>
public double RoamSkipSec { get; set; } = 600;
/// <summary>How many of the nearest unseen squares get a path asked for, per pick.</summary>
public int RoamTries { get; set; } = 4;
private readonly Dictionary<(int, int), DateTime> _roamSeen = new();
private readonly Dictionary<(int, int), DateTime> _roamSkip = new();
private bool _roaming;
private (int, int) _roamSquare;
private Vec _roamTo;
/// <summary>Walking to a square of the area not seen lately (no monster in range).</summary>
public bool Roaming => _roaming;
public void Start(DateTime now, Vec at)
{
@ -226,6 +254,9 @@ internal sealed class OutdoorHunt
_skip.Clear();
_skipCells.Clear();
_snags.Clear();
_roamSeen.Clear();
_roamSkip.Clear();
_roaming = false;
_lastPlan = _lastPick = _arrivedSince = DateTime.MinValue;
Note = $"started at {at.X:0},{at.Y:0}";
}
@ -234,6 +265,7 @@ internal sealed class OutdoorHunt
{
Active = false;
TargetId = 0;
_roaming = false;
WalkingOut = false;
_outTries = 0;
}
@ -287,7 +319,9 @@ internal sealed class OutdoorHunt
_buildings = buildings;
_now = now;
_meNow = me;
_meCellNow = meCell;
_meBuilding = 0;
if (!IsIndoorCell(meCell)) _roamSeen[RoamSquareOf(me)] = now; // where it stands is seen
if (IsIndoorCell(meCell))
{
int inB = buildings?.BuildingOf(meCell) ?? 0;
@ -372,9 +406,12 @@ internal sealed class OutdoorHunt
NewTarget();
}
// A roam walk that ran out: its square is seen (got there) or left out (didn't).
if (_roaming && routeDone) EndRoamWalk(now, me);
// Choosing (at most once every PickEverySec): the few nearest, by the walk to them.
if ((now - _lastPick).TotalSeconds < PickEverySec)
return new Decision(Act.Idle);
return new Decision(_roaming ? Act.None : Act.Idle);
_lastPick = now;
if (Pick != PickMode.Nearest) return PickPack(now, me, meCell, candidates, routeDone);
_viable.Clear();
@ -414,6 +451,7 @@ internal sealed class OutdoorHunt
private Decision Go(DateTime now, Candidate c, HuntWalk w, string pack = "")
{
if (TargetId != c.Id) NewTarget();
if (_roaming) { _roaming = false; Note = $"'{c.Name}' in range: the roam ends"; }
TargetId = c.Id;
_targetName = c.Name;
_plannedTo = c.Pos;
@ -428,14 +466,123 @@ internal sealed class OutdoorHunt
return new Decision(Act.Idle, TargetId: c.Id, Why: Note);
}
/// <summary>Nothing to hunt: wait where it is (no walk back to the start: Tom 10-23, "it shouldn't bother").</summary>
/// <summary>
/// Nothing to hunt: roam the area (<see cref="Roam"/>), else wait where it is (no walk back to the start:
/// 2026-10-23, not worth it).
/// </summary>
private Decision Waiting()
{
if (Roam && _meBuilding == 0 && !IsIndoorCell(_meCellNow))
{
if (_roaming) return new Decision(Act.None); // still on the way
Decision? walk = RoamOn(_now, _meNow);
if (walk is Decision d) return d;
}
string wait = $"nothing within Hunt Range ({RangeYd:0} yd){(RadiusYd > 0 ? $" inside Hunt Radius ({RadiusYd:0} yd)" : "")}{(Fence != null ? " inside the fence" : "")}: waiting here";
if (_note != wait) Note = wait;
return new Decision(Act.Idle);
}
// ── Roaming ───────────────────────────────────────────────────────────────────────────────────
/// <summary>The area roamed: Hunt Radius round the start, else Hunt Range round it.</summary>
internal double RoamRadiusYd => RadiusYd > 0 ? RadiusYd : RangeYd;
/// <summary>The squares' side for the area: <see cref="RoamCellMinYd"/>, or more so there are at most about <see cref="RoamMaxSquares"/>.</summary>
internal double RoamCellYd
{
get
{
double r = RoamRadiusYd;
double forCount = 2 * r / Math.Sqrt(RoamMaxSquares);
return Math.Max(RoamCellMinYd, forCount);
}
}
internal (int, int) RoamSquareOf(Vec p)
{
double c = RoamCellYd;
return ((int)Math.Floor((p.X - Anchor.X) / c), (int)Math.Floor((p.Y - Anchor.Y) / c));
}
internal Vec RoamSquareCentre((int I, int J) sq, double z)
{
double c = RoamCellYd;
return new Vec(Anchor.X + (sq.I + 0.5) * c, Anchor.Y + (sq.J + 0.5) * c, z);
}
/// <summary>The squares inside the area (and the fence) not seen for <see cref="RoamRevisitSec"/> and not left out, nearest first.</summary>
internal List<(int, int)> RoamSquaresToSee(DateTime now, Vec me)
{
double c = RoamCellYd, r = RoamRadiusYd;
int n = (int)Math.Ceiling(r / c);
var list = new List<((int, int) Sq, double D)>();
for (int i = -n; i < n; i++)
for (int j = -n; j < n; j++)
{
var sq = (i, j);
Vec at = RoamSquareCentre(sq, me.Z);
if (at.FlatDistanceTo(Anchor) > r) continue;
if (Fence != null && !Fence(at)) continue;
if (_roamSkip.TryGetValue(sq, out var until) && now < until) continue;
if (_roamSeen.TryGetValue(sq, out var seen) && (now - seen).TotalSeconds < RoamRevisitSec) continue;
list.Add((sq, at.FlatDistanceTo(me)));
}
list.Sort((a, b) => a.D.CompareTo(b.D));
var squares = new List<(int, int)>(list.Count);
foreach (var e in list) squares.Add(e.Sq);
return squares;
}
/// <summary>The walk to the nearest square worth a look, or null when there is none (all seen lately, or none reachable).</summary>
private Decision? RoamOn(DateTime now, Vec me)
{
var squares = RoamSquaresToSee(now, me);
double c = RoamCellYd;
int tried = 0;
foreach (var sq in squares)
{
if (tried >= RoamTries) break;
tried++;
// The goal a little above: the path finder looks for the ground under a goal, and a square up a
// hill would be missed at the character's own height.
Vec goal = RoamSquareCentre(sq, me.Z + 30);
var w = PlanWalk(me, _meCellNow, goal, 0);
var p = w.P;
if (p.Status == PathStatus.Unavailable) return null;
bool gets = p.Corners.Count > 0 && p.Corners[^1].FlatDistanceTo(goal) <= c * 0.5 && WalkInFence(p);
if (!gets)
{
_roamSkip[sq] = now.AddSeconds(RoamSkipSec);
continue;
}
if (p.Length <= ArrivedYd) { _roamSeen[sq] = now; continue; }
_roaming = true;
_roamSquare = sq;
_roamTo = p.Corners[^1];
Note = $"nothing within Hunt Range ({RangeYd:0} yd): roaming to {_roamTo.X:0},{_roamTo.Y:0} ({p.Length:0} yd; "
+ $"{squares.Count} of the area's {c:0} yd squares not seen in {RoamRevisitSec / 60:0} min)";
return new Decision(Act.Walk, p.Corners, 0, Note);
}
string done = squares.Count == 0
? $"nothing within Hunt Range, and the whole area ({RoamRadiusYd:0} yd) was looked at in the last {RoamRevisitSec / 60:0} min: waiting here for respawns"
: $"nothing within Hunt Range, and no way found to the {squares.Count} part(s) of the area not looked at yet: waiting here";
if (_note != done) Note = done;
return new Decision(Act.Idle);
}
/// <summary>A roam walk ran out: its square is seen when it got there, else left out for <see cref="RoamSkipSec"/>.</summary>
private void EndRoamWalk(DateTime now, Vec me)
{
_roaming = false;
if (me.FlatDistanceTo(_roamTo) <= RoamCellYd * 0.5) _roamSeen[_roamSquare] = now;
else
{
_roamSkip[_roamSquare] = now.AddSeconds(RoamSkipSec);
Note = $"the roam walk to {_roamTo.X:0},{_roamTo.Y:0} stopped {me.FlatDistanceTo(_roamTo):0} yd short: that part is left out for {RoamSkipSec / 60:0} min";
}
}
// ── Biggest pack / Most XP (2026-11-08) ────────────────────────────────────────────────────────
// Every monster that could be chosen has a pack: itself and the others within PackYd of it. Its
// worth is the pack's count (Biggest pack) or the sum of the pack's XP per kill (Most XP: a name

View file

@ -1213,6 +1213,11 @@ public sealed partial class RynthAiPlugin
/// (0 north, 90 east). Loads a one-point run-once route and turns navigation on. Lets a meta follow a
/// direction (a treasure map's "the site is to the northwest") with the nav engine, no keystrokes.
/// </summary>
// The side (+1 right, -1 left of the heading) the last blocked navheading step went round, when and where.
private int _navHeadingSide;
private DateTime _navHeadingSideAt;
private OutdoorHunt.Vec _navHeadingSidePos;
private void HandleNavHeadingCommand(string[] parts)
{
var settings = _dashboard?.Settings;
@ -1243,25 +1248,28 @@ public sealed partial class RynthAiPlugin
string how = "straight";
if (TryHuntPosition(out _, out OutdoorHunt.Vec at))
{
var goal = new OutdoorHunt.Vec(at.X + Math.Sin(rad) * yards, at.Y + Math.Cos(rad) * yards, at.Z);
OutdoorHunt.PathResult path = HuntPath(at, goal);
if ((path.Status == OutdoorHunt.PathStatus.Ok || path.Status == OutdoorHunt.PathStatus.Partial) && path.Corners.Count > 0)
int keepSide = _navHeadingSide != 0 && (DateTime.UtcNow - _navHeadingSideAt).TotalSeconds < 180
&& Math.Sqrt((at.X - _navHeadingSidePos.X) * (at.X - _navHeadingSidePos.X) + (at.Y - _navHeadingSidePos.Y) * (at.Y - _navHeadingSidePos.Y)) < 150
? _navHeadingSide : 0;
var plan = PlanHeading(at, deg, yards, keepSide, goal => HuntPath(at, goal));
if (plan.Side != 0) { _navHeadingSide = plan.Side; _navHeadingSideAt = DateTime.UtcNow; _navHeadingSidePos = at; }
if (plan.Found)
{
route = HeadingRoute(path.Corners);
how = path.Status == OutdoorHunt.PathStatus.Ok
route = HeadingRoute(plan.Path.Corners);
// A walk along RynthNav's corners: the nav engine's corner gate holds each turn until the way to the
// next corner is clear on the mesh (as a hunt walk or a planned GoTo), so it doesn't cut a corner
// into the rock it is going round.
route.NavmeshCorners = true;
how = (plan.Path.Status == OutdoorHunt.PathStatus.Ok
? $"round obstacles, {route.Points.Count} point(s)"
: $"round obstacles as far as it goes, {route.Points.Count} point(s)";
: $"round obstacles as far as it goes, {route.Points.Count} point(s)") + plan.Detour;
}
else how = path.Status switch
{
OutdoorHunt.PathStatus.NoMesh => "straight (no RynthNav map here)",
OutdoorHunt.PathStatus.Unavailable => "straight (RynthNav isn't loaded)",
_ => "straight (RynthNav found no way)",
};
else how = plan.Straight;
}
if (route.Points.Count == 0)
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = goalNs, EW = goalEw, Z = z / 240.0 });
route.MadeBy = "/ra navheading";
settings.CurrentNavPath = "<navheading>";
settings.CurrentRoute = route;
settings.ActiveNavIndex = 0;
@ -1270,6 +1278,109 @@ public sealed partial class RynthAiPlugin
ReplyOk($"[RynthAi] Navigating {yards:0} yd on heading {deg:0}° (to NS {goalNs:0.000} EW {goalEw:0.000}), {how}.");
}
/// <summary>What <see cref="PlanHeading"/> chose: a path (Found), the reply's note on any detour, the side a
/// detour took (0: none or unchanged), and when nothing goes, why the step is a straight line.</summary>
internal readonly record struct HeadingPlan(bool Found, OutdoorHunt.PathResult Path, string Detour, int Side, string Straight);
/// <summary>
/// The way for one navheading step: RynthNav's path (<paramref name="findPath"/>: from where you stand to a goal)
/// to the first goal that goes, of the plain step, further on the same heading, then 45° and 90° to either side.
///
/// Impassable terrain ahead (11-10, a character at a treasure site): the 50 yd goal can't be reached, and the partial
/// path ended where he stood, so the route "arrived" at once and the meta used the map, got the same heading and
/// stood still. A step that gains under a fifth of its length (or 5 yd) tries the next goal.
///
/// A goal off walkable ground (2026-11-30: seeking a treasure map's site ignored cliffs,
/// hills and objects it can't pass through): RynthNav answers NoMesh for a goal more than 8 yd from its mesh (a
/// cliff face, a rock, a building, a slope over ~48°) and NoPath when there is no way to it. That used to end the
/// search at the first such goal and walk a straight line into it. Now the same direction is tried closer (60%,
/// then 30% of the way, not under the gain a step needs), then the next goal; straight only when every goal
/// fails, or RynthNav isn't there at all.
///
/// The way round keeps to one side (11-10: the map said south, then southeast, and the two detours went opposite
/// ways round the plateau, so he swung 50 yd back and forth): <paramref name="keepSide"/> (+1 right, -1 left of the
/// heading, 0 none) is the side the last blocked step took; a blocked step takes a way round on that side when
/// there is one, and the side it takes comes back in <see cref="HeadingPlan.Side"/>.
/// </summary>
internal static HeadingPlan PlanHeading(OutdoorHunt.Vec at, double deg, double yards, int keepSide,
Func<OutdoorHunt.Vec, OutdoorHunt.PathResult> findPath)
{
double rad = deg * Math.PI / 180.0;
double need = Math.Max(5.0, yards * 0.2);
(double offDeg, double dist)[] tries =
{
(0, yards), (0, Math.Min(yards * 2, 400)), (0, Math.Min(yards * 4, 400)),
(45, yards), (-45, yards), (90, yards), (-90, yards),
};
double hx = Math.Sin(rad), hy = Math.Cos(rad);
int SideOf(OutdoorHunt.PathResult p)
{
double best = 0;
foreach (var c in p.Corners)
{
double lat = (c.X - at.X) * hy - (c.Y - at.Y) * hx; // + = right of the heading
if (Math.Abs(lat) > Math.Abs(best)) best = lat;
}
return Math.Abs(best) < 3 ? 0 : Math.Sign(best);
}
bool blocked = false, offMap = false, noWay = false;
OutdoorHunt.PathResult firstPath = default;
string firstDetour = "";
bool haveFirst = false;
var tried = new HashSet<(double, double)>();
foreach (var (offDeg, dist) in tries)
{
double r = (deg + offDeg) * Math.PI / 180.0;
// The goal itself, then pulled back toward you while it lands off walkable ground or has no way to it.
OutdoorHunt.PathResult p = default;
double usedDist = dist;
bool got = false;
foreach (double f in new[] { 1.0, 0.6, 0.3 })
{
double d = dist * f;
if (f < 1.0 && d < need) break;
if (!tried.Add((Math.Round(offDeg), Math.Round(d)))) continue; // the same goal as an earlier try
var goal = new OutdoorHunt.Vec(at.X + Math.Sin(r) * d, at.Y + Math.Cos(r) * d, at.Z);
p = findPath(goal);
if (p.Status == OutdoorHunt.PathStatus.Unavailable)
return new HeadingPlan(false, p, "", 0, "straight (RynthNav isn't loaded)");
if (p.Status == OutdoorHunt.PathStatus.NoMesh) { offMap = true; continue; }
if (p.Status != OutdoorHunt.PathStatus.Ok && p.Status != OutdoorHunt.PathStatus.Partial) { noWay = true; continue; }
usedDist = d;
got = true;
break;
}
if (!got || p.Corners.Count == 0) continue;
var end = p.Corners[p.Corners.Count - 1];
double gained = Math.Sqrt((end.X - at.X) * (end.X - at.X) + (end.Y - at.Y) * (end.Y - at.Y));
if (gained < need) { blocked = true; continue; }
string note = offDeg != 0 ? $", {Math.Abs(offDeg):0}° {(offDeg > 0 ? "right" : "left")} of the heading to get past what's ahead"
: usedDist > yards ? $", planned {usedDist:0} yd on to find a way past what's ahead"
: usedDist < yards ? $", {usedDist:0} yd (the {dist:0} yd point is off walkable ground)" : "";
if (offDeg != 0 && usedDist < dist) note += $", {usedDist:0} yd (further is off walkable ground)";
// The plain heading goes (as far as asked, further on, or closer than a goal off walkable ground): no detour.
if (offDeg == 0 && !blocked) return new HeadingPlan(true, p, note, 0, "");
int side = SideOf(p);
if (keepSide == 0 || side == keepSide)
{
if (side != 0 && keepSide != 0) note += $" (keeping to the {(side > 0 ? "right" : "left")} as the last step did)";
return new HeadingPlan(true, p, note, side, "");
}
if (!haveFirst) { firstPath = p; firstDetour = note; haveFirst = true; }
}
if (haveFirst)
{
// No way round on the kept side: the other side, and it becomes the kept one.
return new HeadingPlan(true, firstPath, firstDetour, SideOf(firstPath), "");
}
string why = blocked ? "straight (RynthNav finds no way past what's ahead)"
: offMap ? "straight (no walkable ground on RynthNav's map on any of the 7 goals: cliffs, rocks or water ahead, or no map here)"
: noWay ? "straight (RynthNav found no way)"
: "straight (RynthNav found no way)";
return new HeadingPlan(false, default, "", 0, why);
}
/// <summary>A Once route through RynthNav's corners (world x east, y north, as the Outdoor Hunt installs them).</summary>
internal static NavRouteParser HeadingRoute(IReadOnlyList<OutdoorHunt.Vec> corners)
{
@ -1386,7 +1497,7 @@ public sealed partial class RynthAiPlugin
}
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 import | /ra nav restart | /ra nav addjump [ms] [shift]";
"/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 import | /ra nav restart | /ra nav addjump [ms] [shift] [heading <deg>]";
/// <summary>The hold a recorded jump gets when none is given: the dungeon walk's own hop.</summary>
internal const int AddJumpDefaultMs = DungeonPathfinder.JumpHoldMs;
@ -1404,18 +1515,27 @@ public sealed partial class RynthAiPlugin
if (settings == null) { ReplyFail("[RynthAi] Settings not ready."); return; }
int ms = AddJumpDefaultMs;
bool shift = false;
foreach (string word in args.Split(' ', StringSplitOptions.RemoveEmptyEntries))
float? givenHeading = null;
string[] words = args.Split(' ', StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < words.Length; i++)
{
string word = words[i];
if (word.Equals("shift", StringComparison.OrdinalIgnoreCase)) shift = true;
// "heading <deg>": the jump's direction as given (VTank's /vt addnavjump), not the way you face.
else if (word.Equals("heading", StringComparison.OrdinalIgnoreCase) && i + 1 < words.Length
&& float.TryParse(words[i + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float hd))
{ givenHeading = ((hd % 360f) + 360f) % 360f; i++; }
else if (int.TryParse(word, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int n)) ms = Math.Clamp(n, 0, 1000);
else { ReplyFail("[RynthAi] Usage: /ra nav addjump [ms] [shift] (ms: 0-1000, how long the jump is held)"); return; }
else { ReplyFail("[RynthAi] Usage: /ra nav addjump [ms] [shift] [heading <deg>] (ms: 0-1000, how long the jump is held)"); return; }
}
float heading = 0f;
if (!NavCoordinateHelper.TryGetNavPosition(Host, out double ns, out double ew, out double z)
|| !PlayerCompass.TryGet(Host, out float heading))
|| (givenHeading == null && !PlayerCompass.TryGet(Host, out heading)))
{
ReplyFail("[RynthAi] Could not read your position and heading.");
return;
}
if (givenHeading is float g) heading = g;
var pt = new NavPoint
{
Type = NavPointType.Jump, NS = ns, EW = ew, Z = z,
@ -3430,6 +3550,7 @@ public sealed partial class RynthAiPlugin
if (!settings.IsMacroRunning && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge)
if (walkOnly) BeginWalkTrip(settings, route, landblockKey, byCell ? $"'{name}'" : what); // before the macro start: its state is the player's
settings.SetMacroRunning(true, "/ra dunnav-to");
route.MadeBy = "/ra dunnav-to";
settings.CurrentRoute = route;
settings.ActiveNavIndex = 0;
settings.EnableNavigation = true;
@ -3499,6 +3620,7 @@ public sealed partial class RynthAiPlugin
if (!settings.IsMacroRunning && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge)
settings.SetMacroRunning(true, "/ra dunnav");
route.MadeBy = "/ra dunnav";
settings.CurrentRoute = route;
settings.ActiveNavIndex = 0;
settings.EnableNavigation = true;
@ -3947,6 +4069,7 @@ public sealed partial class RynthAiPlugin
// so the bot walked there, back to waypoint 0, and only then on (2026-10-08).
_macroWasRunning = true;
}
route.MadeBy = "the dungeon patrol";
settings.CurrentNavPath = string.Empty;
settings.CurrentRoute = route;
settings.ActiveNavIndex = startIdx;

View file

@ -371,6 +371,7 @@ public sealed partial class RynthAiPlugin
_dunPatrolActive = false;
_dunPatrolRoute = null;
}
route.MadeBy = "the dungeon explore";
settings.CurrentNavPath = string.Empty;
settings.CurrentRoute = route;
settings.ActiveNavIndex = b.StartIdx;
@ -479,6 +480,7 @@ public sealed partial class RynthAiPlugin
}
run.HuntWalks++;
settings.CurrentNavPath = string.Empty;
b.Route.MadeBy = "the dungeon explore";
settings.CurrentRoute = b.Route;
settings.ActiveNavIndex = 0;
settings.EnableNavigation = true;
@ -703,6 +705,7 @@ public sealed partial class RynthAiPlugin
settings.SetMacroRunning(true, "the dungeon explore");
_macroWasRunning = true;
}
b.Route.MadeBy = "the dungeon explore";
settings.CurrentNavPath = string.Empty;
settings.CurrentRoute = b.Route;
settings.ActiveNavIndex = 0;

View file

@ -662,10 +662,22 @@ public sealed partial class RynthAiPlugin
ReplyOk($"[RynthAi] Nav HUD {(o.ShowHud ? "shown" : "hidden")}.");
}
/// <summary>/ra navtrail [on|off|toggle|clear] — breadcrumb tracking switch, wipe, or a status report.</summary>
/// <summary>
/// /ra navtrail [on|off|toggle|clear|route [name]|back [name]] — breadcrumb tracking switch, wipe,
/// the trail as the route (walked again, or back) and saved as name.nav when a name is given,
/// or a status report.
/// </summary>
private void HandleNavTrailCommand(string[] parts)
{
string arg = parts.Length > 2 ? parts[2].ToLowerInvariant() : "";
if (arg is "route" or "back")
{
if (_dashboard == null) { ReplyFail("[RynthAi] Settings not ready (log in first)."); return; }
string? name = parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3).Trim() : null;
string line = _dashboard.TrailToRoute(arg == "back", name, out bool made);
if (made) ReplyOk("[RynthAi] " + line); else ReplyFail("[RynthAi] " + line);
return;
}
if (arg == "clear")
{
_navBreadcrumbs?.RequestClear();
@ -684,7 +696,8 @@ public sealed partial class RynthAiPlugin
bool tracking = _dashboard?.Settings.NavOverlay.TrackBreadcrumbs ?? false;
int n = _navBreadcrumbs?.Trail.Length ?? 0;
double yd = _navBreadcrumbs?.TrailYards ?? 0;
ChatLine($"[RynthAi] Breadcrumbs {(tracking ? "on" : "off")}: {n} points, {yd:F0} yd. Use /ra navtrail on|off|clear.");
ChatLine($"[RynthAi] Breadcrumbs {(tracking ? "on" : "off")}: {n} points, {yd:F0} yd. Use /ra navtrail on|off|clear, " +
"or /ra navtrail route [name] (back [name] to walk it backwards) to make the trail your route.");
}
/// <summary>/ra navoverlay [on|off] — route overlay (rings / lines, waypoint labels, guide line); no argument toggles.</summary>

View file

@ -198,9 +198,10 @@ public sealed partial class RynthAiPlugin
string status = !on ? "Off."
: _hunt.WalkingOut ? "Walking back out of a building."
: _hunt.TargetId != 0 ? "Walking to a monster."
: _hunt.Roaming ? "Roaming the area for monsters."
: "Waiting for a monster in range.";
using (Ui.PushFont(RynthUiFont.UiBold14))
Wrapped(status, !on ? Ui.Mute : _hunt.TargetId != 0 || _hunt.WalkingOut ? Ui.Green : Ui.Highlight);
Wrapped(status, !on ? Ui.Mute : _hunt.TargetId != 0 || _hunt.WalkingOut || _hunt.Roaming ? Ui.Green : Ui.Highlight);
string note = _hunt.Note;
if (on && note.Length > 0) Wrapped(note, Ui.Text);
HuntOnLoginCheckbox(s);
@ -222,6 +223,11 @@ public sealed partial class RynthAiPlugin
radius < 1f ? "anywhere" : "%.0f yd", "Anywhere", 0f, k))
s.OutdoorHuntRadius = radius < 1f ? 0f : radius;
Wrapped("How far from where it started it may roam. Anywhere: no limit.", Ui.Text);
ImGui.Checkbox("Roam when nothing is in range##huntroam", ref s.OutdoorHuntRoam);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("With no monster in range it walks round the parts of the Hunt Radius it hasn't looked at in\n"
+ "the last 5 minutes (Hunt Range round the start when the radius is Anywhere), and goes for\n"
+ "the first monster that comes in range. Off: it waits where it is.");
ImGui.Spacing();
// Go for (2026-11-08): Nearest, Biggest pack or Most XP (OutdoorHuntPick).
@ -302,7 +308,7 @@ public sealed partial class RynthAiPlugin
_dunPatrolActive = false; // the hunt's route replaces the patrol's
CopyHuntSettings(s);
_hunt.Start(RynthClock.Now, me);
_huntRoute = new NavRouteParser { RouteType = NavRouteType.Once, OutdoorHuntWalk = true };
_huntRoute = new NavRouteParser { RouteType = NavRouteType.Once, OutdoorHuntWalk = true, MadeBy = "the hunt" };
s.CurrentNavPath = string.Empty;
s.CurrentRoute = _huntRoute;
s.ActiveNavIndex = 0;
@ -497,6 +503,7 @@ public sealed partial class RynthAiPlugin
});
}
_huntRoute = route;
route.MadeBy = "the hunt";
s.CurrentNavPath = string.Empty;
s.CurrentRoute = route;
s.ActiveNavIndex = 0;
@ -508,6 +515,7 @@ public sealed partial class RynthAiPlugin
_hunt.RangeYd = Math.Clamp(s.OutdoorHuntRange, OutdoorHuntRangeMin, OutdoorHuntRangeMax);
_hunt.RadiusYd = Math.Clamp(s.OutdoorHuntRadius, 0, OutdoorHuntRadiusMax);
_hunt.Pick = (OutdoorHunt.PickMode)Math.Clamp(s.OutdoorHuntPick, 0, 2);
_hunt.Roam = s.OutdoorHuntRoam;
if (!_huntFenceHooked) { _hunt.Fence = p => InHuntFence(p.X, p.Y); _hunt.WalkFence = WalkInHuntFence; _huntFenceHooked = true; }
_hunt.XpLookup ??= XpPerKill; // the learned XP per kill (MonsterXpTable), for Most XP
}

View file

@ -49,6 +49,8 @@ public sealed partial class RynthAiPlugin
if (dash == null || !dash.ProfileLoaded)
return ProfileResult.Failed("Settings not ready (log in first).");
if (kind == ProfileKind.Layout) return dash.LayoutAction(verb, name, replace); // named layouts (the engine keeps them)
if (kind == ProfileKind.Loot && verb is ProfileVerb.SaveAs or ProfileVerb.Rename or ProfileVerb.Delete)
{
string inUse = dash.ProfilePath(ProfileKind.Loot);

View file

@ -554,6 +554,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
ResetGiveState();
// A /ub delay armed before logout must not fire into the next character's session.
_delayedCommands.Clear();
ResetUbInventoryJobs(); // /ub equip load, /ub autosalvage
ClearPropertyDump();
// Where the character came into its dungeon: the next login's spot is not an arrival.
ForgetDunArrival();
@ -1931,7 +1932,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
&& (_buffManager.PendingSpellId != 0
|| _buffManager.WantsVitalRecharge
|| (settings.EnableBuffing && _buffManager.NeedsAnyBuff()
&& !_buffManager.BuffsWaitForFight())); // in a fight: combat first, buffs after (2026-11-20)
&& !_buffManager.BuffsWaitForFight())); // a fight under Heal At: the heals first (since 2026-12-01 only then)
bool wantBuff = wantBuffRaw;
// ── Buffing-coma watchdog (STEP 5: decides, no longer falls through) ──

View file

@ -252,6 +252,7 @@ public sealed partial class RynthAiPlugin
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = ns, EW = ew, Z = z / 240.0 });
}
Host.Log(string.Create(CultureInfo.InvariantCulture, $"[RynthAi] GoTo: NS {ns:0.0000} EW {ew:0.0000}, {how}"));
route.MadeBy = "a script's GoTo";
st.CurrentRoute = route;
st.CurrentNavPath = string.Empty;
st.ActiveNavIndex = 0;

View file

@ -32,7 +32,7 @@ public sealed partial class RynthAiPlugin
/// </summary>
private static readonly HashSet<string> UbNoEquivalentVerbs = new(StringComparer.OrdinalIgnoreCase)
{
"acobject", "autologin", "autoloot", "autosalvage", "autosalvagedebug", "autosalvagereload",
"acobject", "autologin", "autoloot", "autosalvagedebug", "autosalvagereload",
"bankparse", "breakallegiance", "bridge", "calcdamage", "chat", "chatfilter", "chunkaeth",
"chunkaetheria", "chunkdebug", "chunkreset", "chunkstatus", "clapstatus", "dispel", "dispeltool",
"egg", "element", "enlighten", "enlightenment", "getjob", "getui", "invcache", "joke", "keystore",
@ -200,7 +200,16 @@ public sealed partial class RynthAiPlugin
// "yes" arms a Yes for the next yes/no prompt (ConfirmationRequest YesNo) within the time given in
// ms, never under PrepClickMinMs (metas send it again before each hand-in), at most PrepClickMaxMs.
// "no" disarms (the engine can't say No to a prompt without a percent: the client shows it).
internal const int PrepClickMinMs = 5000, PrepClickMaxMs = 60000;
// 2026-12-01 command audit: UtilityBelt's number is seconds ("yes 100" is 100 s), read here as ms and
// raised to 5 s, so a long hand-in run lost its Yes; "stop" wasn't known. Now seconds, 15 s when none
// is given, 5 s to 5 min; stop and no disarm.
internal const int PrepClickMinMs = 5000, PrepClickMaxMs = 300_000, PrepClickDefaultMs = 15_000;
/// <summary>The Yes window for /ub prepclick's number of seconds (15 s when none), 5 s to 5 min.</summary>
internal static int PrepClickMs(string? seconds) =>
double.TryParse(seconds, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double sec)
? (int)Math.Clamp(sec * 1000, PrepClickMinMs, PrepClickMaxMs)
: PrepClickDefaultMs;
private void UbPrepClick(string answer, string number)
{
@ -209,20 +218,21 @@ public sealed partial class RynthAiPlugin
UbNoEquivalent("prepclick", "this RynthCore can't answer prompts (it needs a newer core)");
return;
}
if (answer is "no" or "n" or "off" or "cancel")
if (answer is "no" or "n" or "off" or "cancel" or "stop")
{
Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.YesNo, 0, 0);
Reply.Answered();
Host.Log("[RynthAi] /ub prepclick no: disarmed; the next yes/no prompt is left to you.");
Host.Log(answer == "stop"
? "[RynthAi] /ub prepclick stop: disarmed; the next yes/no prompt is left to you."
: "[RynthAi] /ub prepclick no: disarmed; the next yes/no prompt is left to you (RynthCore can only answer Yes to it).");
return;
}
if (answer is not ("yes" or "y" or ""))
{
ReplyFail("[RynthAi] Usage: /ub prepclick yes|no [ms]");
ReplyFail("[RynthAi] Usage: /ub prepclick yes|no|stop [seconds]");
return;
}
int ms = int.TryParse(number, out int n) ? n : 0;
ms = Math.Clamp(ms, PrepClickMinMs, PrepClickMaxMs);
int ms = PrepClickMs(number);
int r = Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.YesNo, 0, ms);
if (r == 1)
{

View file

@ -17,7 +17,7 @@ namespace RynthCore.Plugin.RynthAi;
/// names and syntax read from UtilityBelt.dll's CommandPattern/Usage attributes):
/// delay, count, date/dateutc, id, pos, vitae, portal/portalp, playsound,
/// setmotion/getmotion/clearmotion, autostack, autocram, opt, help, simplejump,
/// dumpskills, quests, translateroute.
/// dumpskills, quests, translateroute. equip and autosalvage: UtilityBeltInventoryCommands.cs.
/// </summary>
public sealed partial class RynthAiPlugin
{
@ -29,6 +29,7 @@ public sealed partial class RynthAiPlugin
/// <summary>Runs /ub delay commands that are due. Called every tick.</summary>
private void TickDelayedCommands()
{
TickUbInventoryJobs(); // /ub equip load|test, /ub autosalvage
// Out of world, OnChatBarEnter ignores the line and it went raw to AC's chat
// parser at character select. TeardownSession empties the queue at logout.
if (_delayedCommands.Count == 0 || !_loginComplete) return;
@ -100,6 +101,11 @@ public sealed partial class RynthAiPlugin
case "dumpskills": UbDumpSkills(); return true;
case "quests": UbQuests(args); return true;
case "translateroute": UbTranslateRoute(args); return true;
// Equipment profiles and AutoSalvage by a loot profile (UtilityBeltInventoryCommands.cs,
// 2026-12-01 command audit): equip went on to /mt equip ("Item not found: load ..."),
// autosalvage was accepted and ignored. "/ub equip <item name>" still wields by name (/mt equip).
case "equip" when UbEquipOwns(args): UbEquip(args); return true;
case "autosalvage": UbAutoSalvage(args); return true;
}
return false;
}
@ -149,8 +155,16 @@ public sealed partial class RynthAiPlugin
}
case "profile":
{
// Read for the count only: TryLoadLootProfile also made it the profile looting uses, so a meta
// counting against another profile switched what it looted (2026-12-01 command audit).
string path = ResolveLootProfilePath(what);
if (path.Length == 0 || !TryLoadLootProfile(path, out VTankLootProfile profile, out _)) { ReplyFail($"[RynthAi] count: loot profile not found: {what}"); return; }
VTankLootProfile profile;
try
{
if (path.Length == 0 || !File.Exists(path)) { ReplyFail($"[RynthAi] count: loot profile not found: {what}"); return; }
profile = VTankLootParser.Load(path);
}
catch (Exception ex) { ReplyFail($"[RynthAi] count: couldn't read {Path.GetFileName(path)}: {ex.Message}"); return; }
var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache };
int n = 0;
foreach (var wo in inv)
@ -307,7 +321,9 @@ public sealed partial class RynthAiPlugin
case "toggle" when w.Length >= 2:
foreach (string name in w.Skip(1))
{
if (!map.TryGetValue(name, out var tg)) { ReplyFail($"[RynthAi] No option '{name}'."); continue; }
// UtilityBelt's names (InventoryManager.AutoCram ...) through the /ub opt map (2026-12-01 command audit).
string key = MtOptionMap.TryGetValue(name, out string? mapped) ? mapped : name;
if (!map.TryGetValue(key, out var tg)) { ReplyFail($"[RynthAi] No option '{name}'."); continue; }
tg.Set(tg.Get() is "0" or "" or "False" ? "1" : "0");
ReplyOk($"[RynthAi] {name} = {tg.Get()}");
}
@ -323,7 +339,7 @@ public sealed partial class RynthAiPlugin
{
ChatLine("[RynthAi] /ub commands: use[i][l][p], give[p], ig[p], select, face, fellow, equip, combatstate, close, quit, logout, " +
"follow[p], mexec, myquests, list[g|p]vars, propertydump, jump[swzxc], simplejump, closestportal, portal[p], " +
"autovendor, vendor, autotrade, autostack, autocram, delay, count, date[utc], id, pos, vitae, playsound, " +
"autovendor, vendor, autotrade, autostack, autocram, autosalvage, delay, count, date[utc], id, pos, vitae, playsound, " +
"setmotion, getmotion, clearmotion, opt, dumpskills, quests, translateroute, clearbugged.");
}

View file

@ -0,0 +1,512 @@
// ============================================================================
// RynthAi - UtilityBeltInventoryCommands.cs
// UtilityBelt's /ub equip list|load|test|create and /ub autosalvage [force]
// (2026-12-01 command audit). Both judge what the character carries by a loot
// profile's rules, so they share one job: read the profile, identify the items
// whose rule needs it, then act.
//
// /ub equip used to fall through to /mt equip, which looked for an item named
// "load" and failed, so a meta's armor or weapon swap did nothing. /ub autosalvage
// was accepted and ignored.
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Loot;
using RynthCore.Loot.Editing;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Which items of an equipment profile go on, one per slot (pure, so tests can run it). An item is
/// placed in the order of its rule (then of the inventory); a slot can only take one item. Rings and
/// bracelets fit either of their two slots; the weapon slots (melee, missile, wand, two-handed) are
/// one hand, so one weapon. Items already worn keep their slots.
/// </summary>
internal static class UbEquipPlan
{
// AC's EquipMask bits (ValidLocations / CurrentWieldedLocation).
internal const int MeleeWeapon = 0x00100000, MissileWeapon = 0x00400000, Held = 0x01000000, TwoHanded = 0x02000000;
internal const int WeaponSlots = MeleeWeapon | MissileWeapon | Held | TwoHanded;
internal const int WristPair = 0x00010000 | 0x00020000, FingerPair = 0x00040000 | 0x00080000;
/// <summary>
/// A carried item a Keep rule takes. <see cref="Slots"/> is where it can go (ValidLocations),
/// <see cref="WornSlots"/> where it is worn now (0 when that isn't known); <see cref="Order"/> sorts them.
/// </summary>
public readonly record struct Item(int Id, string Name, int Slots, bool Worn, int WornSlots, int Order);
public sealed class Result
{
public List<Item> Equip { get; } = new();
public List<Item> AlreadyWorn { get; } = new();
public List<(Item Item, string Why)> Skipped { get; } = new();
}
public static Result Plan(IEnumerable<Item> matched)
{
var result = new Result();
var list = matched.OrderBy(i => i.Order).ToList();
int taken = 0;
foreach (Item worn in list.Where(i => i.Worn))
{
taken |= Expand(worn.WornSlots);
result.AlreadyWorn.Add(worn);
}
foreach (Item item in list.Where(i => !i.Worn))
{
if (item.Slots == 0) result.Skipped.Add((item, "it isn't something to wear or wield"));
else if (TryClaim(item.Slots, ref taken)) result.Equip.Add(item);
else result.Skipped.Add((item, "another item of the profile has its slot"));
}
return result;
}
private static int Expand(int slots) => (slots & WeaponSlots) != 0 ? slots | WeaponSlots : slots;
private static bool TryClaim(int slots, ref int taken)
{
foreach (int pair in new[] { WristPair, FingerPair })
{
if ((slots & ~pair) != 0 || (slots & pair) != pair) continue;
int free = pair & ~taken;
if (free == 0) return false;
taken |= free & -free; // the lower free one of the two
return true;
}
int need = Expand(slots);
if ((need & taken) != 0) return false;
taken |= need;
return true;
}
}
public sealed partial class RynthAiPlugin
{
/// <summary>Where /ub equip finds and makes its profiles: RynthAi's LootProfiles (tests point it elsewhere).</summary>
internal static string UbEquipFolder { get; set; } = LootEditorBridge.LootFolder;
internal const string UbEquipUsage = "/ub equip list | load <profile> | test <profile> | create <profile>";
internal const string UbAutoSalvageUsage = "/ub autosalvage [force]";
// Pacing: one identify every IdSpacingMs, a wait of IdWaitMs for the last one, the whole job at
// most JobMaxMs; one wield every EquipSpacingMs, the check EquipSettleMs after the last.
internal const long UbIdSpacingMs = 300, UbIdWaitMs = 3000, UbJobMaxMs = 60_000;
internal const long UbEquipSpacingMs = 700, UbEquipSettleMs = 2000;
internal const int UbMaxIds = 100;
// STypeInts AutoSalvage reads (UtilityBelt leaves tinkered and imbued items alone).
private const uint NumTimesTinkeredInt = 171, ImbuedEffectInt = 179;
private enum UbInvKind { EquipLoad, EquipTest, Salvage, SalvageForce }
private sealed class UbInvJob
{
public UbInvKind Kind;
public InventoryRules Rules = null!;
public bool FromMeta;
public long StartedAt;
public long NextIdAt;
public long LastIdAt;
public readonly Queue<uint> IdQueue = new();
public readonly List<uint> Asked = new();
}
private UbInvJob? _ubInvJob;
private readonly Queue<(uint Id, string Name)> _ubEquipSends = new();
private readonly List<(uint Id, string Name)> _ubEquipSent = new();
private long _ubEquipNextAt, _ubEquipLastAt;
private bool _ubEquipFromMeta;
private string _ubEquipProfile = string.Empty;
/// <summary>Milliseconds for the job's pacing (tests move it on).</summary>
internal Func<long> UbInvClock { get; set; } = () => Environment.TickCount64;
/// <summary>The profile a /ub equip or /ub autosalvage line names: a full path, else LootProfiles\name[.utl|.json].</summary>
internal static string ResolveUbEquipProfile(string name)
{
string n = name.Trim().Trim('"');
if (n.Length == 0) return string.Empty;
if (Path.IsPathFullyQualified(n)) return File.Exists(n) ? n : string.Empty;
foreach (string cand in new[] { n, n + ".utl", n + ".json" })
{
string p = Path.Combine(UbEquipFolder, cand);
if (File.Exists(p)) return p;
}
return string.Empty;
}
// ── /ub equip ─────────────────────────────────────────────────────────
/// <summary>
/// UtilityBelt's own /ub equip line (list, load, test, create, or nothing). Anything else is an item
/// name, as metas wrote for the /mt equip this used to be: that still wields the item.
/// </summary>
internal static bool UbEquipOwns(string args)
{
string first = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries) is { Length: > 0 } w ? w[0].ToLowerInvariant() : "";
return first is "" or "list" or "load" or "test" or "create";
}
private void UbEquip(string args)
{
string[] w = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
string sub = w.Length > 0 ? w[0].ToLowerInvariant() : "";
string name = w.Length > 1 ? w[1].Trim() : "";
switch (sub)
{
case "list":
UbEquipList();
return;
case "load" or "test" when name.Length > 0:
{
string path = ResolveUbEquipProfile(name);
if (path.Length == 0) { ReplyFail($"[RynthAi] /ub equip: no profile '{name}' in {UbEquipFolder}."); return; }
InventoryRules? rules = InventoryRules.Load(path, out string why);
if (rules == null) { ReplyFail($"[RynthAi] /ub equip: couldn't read {Path.GetFileName(path)}: {why}"); return; }
StartUbInvJob(sub == "load" ? UbInvKind.EquipLoad : UbInvKind.EquipTest, rules);
return;
}
case "create" when name.Length > 0:
UbEquipCreate(name);
return;
}
ReplyFail("[RynthAi] Usage: " + UbEquipUsage);
}
private void UbEquipList()
{
var names = new List<string>();
try
{
if (Directory.Exists(UbEquipFolder))
foreach (string f in Directory.GetFiles(UbEquipFolder))
if (f.EndsWith(".utl", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
names.Add(Path.GetFileName(f));
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
names.Sort(StringComparer.OrdinalIgnoreCase);
ChatLine(names.Count == 0
? $"[RynthAi] Equipment profiles: none in {UbEquipFolder}. /ub equip create <name> makes one from what you wear."
: $"[RynthAi] Equipment profiles ({names.Count}, the loot profiles in {UbEquipFolder}): {string.Join(", ", names)}");
}
/// <summary>
/// /ub equip create &lt;name&gt;: LootProfiles\&lt;name&gt;.utl with one Keep rule per worn item (its exact
/// name and object class), so /ub equip load puts the same things on again. Never over an existing file:
/// the folder holds the loot profiles too.
/// </summary>
private void UbEquipCreate(string raw)
{
if (_objectCache == null || _playerId == 0) { ReplyFail("[RynthAi] /ub equip create: not ready (log in first)."); return; }
string? why = LegacyUi.ProfileFileOps.CleanName(raw, LegacyUi.LegacyDashboardRenderer.LootExtensions, out string name);
if (why != null) { ReplyFail($"[RynthAi] /ub equip create: can't use '{name}': {why}."); return; }
string path = Path.Combine(UbEquipFolder, name + ".utl");
if (File.Exists(path) || File.Exists(Path.Combine(UbEquipFolder, name + ".json")))
{
ReplyFail($"[RynthAi] /ub equip create: {name} already exists in {UbEquipFolder}; pick another name.");
return;
}
var profile = new VTankLootProfile();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (WorldObject wo in _objectCache.GetDirectInventory(forceRefresh: true))
{
if (!WorldObjectCache.IsWieldedByPlayer(Host, wo) || string.IsNullOrWhiteSpace(wo.Name)) continue;
if (!seen.Add(wo.Name + "|" + (int)wo.ObjectClass)) continue; // two of the same ring: one rule takes both
var rule = new VTankLootRule { Name = "Equip " + wo.Name.Trim(), Action = VTankLootAction.Keep, CustomExpression = string.Empty };
if (wo.ObjectClass != AcObjectClass.Unknown)
rule.Conditions.Add(new VTankLootCondition(VTankNodeTypes.ObjectClass, "0",
new[] { ((int)wo.ObjectClass).ToString(System.Globalization.CultureInfo.InvariantCulture) }));
rule.Conditions.Add(new VTankLootCondition(VTankNodeTypes.StringValueMatch, "0",
new[] { LootItemRules.ExactPattern(wo.Name.Trim()), "1" }));
profile.Rules.Add(rule);
}
if (profile.Rules.Count == 0) { ReplyFail("[RynthAi] /ub equip create: you aren't wearing anything to put in it."); return; }
if (!DataWriteGuard.TrySave("the equipment profile", path, () =>
{
Directory.CreateDirectory(UbEquipFolder);
VTankLootWriter.Save(profile, path);
}, out string saveWhy, callerShows: true))
{
ReplyFail($"[RynthAi] /ub equip create: couldn't write {Path.GetFileName(path)}: {saveWhy}");
return;
}
ReplyOk($"[RynthAi] Equipment profile {Path.GetFileName(path)}: {profile.Rules.Count} item(s) you wear. /ub equip load {name} puts them on.");
}
// ── /ub autosalvage ───────────────────────────────────────────────────
/// <summary>
/// /ub autosalvage [force] (UtilityBelt): the carried items the loot profile in use says Salvage.
/// As UtilityBelt, nothing is salvaged without "force" (UB only fills its salvage window then):
/// here that lists them. With "force" they go to RynthAi's salvage queue, which skips what it
/// always skips (worn, retained, the Items list, the UST, bags). Tinkered and imbued items are
/// left out as UtilityBelt does; AutoSalvage.OnlyFromMainPack (a /ub opt) keeps to the main pack.
/// </summary>
private void UbAutoSalvage(string args)
{
string a = args.Trim().ToLowerInvariant();
if (a.Length > 0 && a != "force") { ReplyFail("[RynthAi] Usage: " + UbAutoSalvageUsage); return; }
string path = (_dashboard?.Settings?.CurrentLootPath ?? string.Empty).Trim().Trim('"');
if (path.Length == 0) { ReplyFail("[RynthAi] /ub autosalvage: no loot profile in use (pick one under LOOT)."); return; }
InventoryRules? rules = InventoryRules.Load(path, out string why);
if (rules == null) { ReplyFail($"[RynthAi] /ub autosalvage: couldn't read {Path.GetFileName(path)}: {why}"); return; }
if (a == "force" && _salvageManager == null) { ReplyFail("[RynthAi] /ub autosalvage: salvaging isn't ready (log in first)."); return; }
StartUbInvJob(a == "force" ? UbInvKind.SalvageForce : UbInvKind.Salvage, rules);
}
// ── The job ───────────────────────────────────────────────────────────
private bool IsEquipJob(UbInvKind k) => k is UbInvKind.EquipLoad or UbInvKind.EquipTest;
private string UbVerb(UbInvKind k) => k switch
{
UbInvKind.EquipLoad => "/ub equip load",
UbInvKind.EquipTest => "/ub equip test",
UbInvKind.Salvage => "/ub autosalvage",
_ => "/ub autosalvage force",
};
/// <summary>The items the job judges: wearables for equip (worn ones too), else what is in the packs.</summary>
private List<WorldObject> UbInvCandidates(UbInvKind kind)
{
var list = new List<WorldObject>();
if (_objectCache == null) return list;
foreach (WorldObject wo in _objectCache.GetDirectInventory(forceRefresh: true))
{
if (IsEquipJob(kind))
{
if (wo.Values(LongValueKey.Locations, 0) != 0 || WorldObjectCache.IsWieldedByPlayer(Host, wo)) list.Add(wo);
}
else if (wo.ObjectClass != AcObjectClass.Container && !WorldObjectCache.IsWieldedByPlayer(Host, wo))
list.Add(wo);
}
return list;
}
private bool HasIdData(uint id) => !Host.HasHasAppraisalData || Host.HasAppraisalData(id);
private void StartUbInvJob(UbInvKind kind, InventoryRules rules)
{
if (_objectCache == null || _playerId == 0) { ReplyFail($"[RynthAi] {UbVerb(kind)}: not ready (log in first)."); return; }
if (_ubInvJob != null) Log($"[RynthAi] {UbVerb(kind)}: replaces {UbVerb(_ubInvJob.Kind)} ({_ubInvJob.Rules.FileName}), which hadn't finished.");
if (kind == UbInvKind.EquipLoad) { _ubEquipSends.Clear(); _ubEquipSent.Clear(); }
var job = new UbInvJob { Kind = kind, Rules = rules, FromMeta = Reply.FromScript, StartedAt = UbInvClock() };
var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache };
bool salvage = !IsEquipJob(kind);
foreach (WorldObject wo in UbInvCandidates(kind))
{
uint id = unchecked((uint)wo.Id);
if (HasIdData(id) || !Host.HasRequestId) continue;
VTankLootVerdict v = rules.Decide(wo, ctx, _charSkills, hasIdData: false, out InventoryRuleKind k, out _);
// Salvage also needs the ID to tell a tinkered or imbued item.
if (v == VTankLootVerdict.NeedsId || (salvage && v == VTankLootVerdict.Match && k == InventoryRuleKind.Salvage))
if (job.IdQueue.Count < UbMaxIds) job.IdQueue.Enqueue(id);
}
_ubInvJob = job;
if (job.IdQueue.Count == 0) { FinishUbInvJob(job); return; }
Log($"[RynthAi] {UbVerb(kind)} {rules.FileName}: identifying {job.IdQueue.Count} item(s) first.");
Reply.Ok($"[RynthAi] {UbVerb(kind)} {rules.FileName}: identifying {job.IdQueue.Count} item(s) first.");
}
/// <summary>Pump thread, every tick: the job's identifies, then its result; the wields of an equip load.</summary>
private void TickUbInventoryJobs()
{
if (!_loginComplete) return;
long now = UbInvClock();
UbInvJob? job = _ubInvJob;
if (job != null)
{
if (job.IdQueue.Count > 0)
{
if (now >= job.NextIdAt)
{
uint id = job.IdQueue.Dequeue();
if (!HasIdData(id) && Host.RequestId(id)) job.Asked.Add(id);
job.NextIdAt = now + UbIdSpacingMs;
job.LastIdAt = now;
}
}
else if (job.Asked.All(HasIdData) || now - job.LastIdAt >= UbIdWaitMs || now - job.StartedAt >= UbJobMaxMs)
{
FinishUbInvJob(job);
}
}
TickUbEquipSends(now);
}
private void FinishUbInvJob(UbInvJob job)
{
if (ReferenceEquals(_ubInvJob, job)) _ubInvJob = null;
if (IsEquipJob(job.Kind)) FinishUbEquip(job);
else FinishUbAutoSalvage(job);
}
/// <summary>A job's answer: as its command would have said it (quiet in chat when a meta sent it, except Info).</summary>
private void UbJobSay(UbInvJob job, string text, bool fail = false, bool info = false)
{
if (job.FromMeta) RunAsMeta(() => { Say(); return true; });
else Say();
void Say()
{
if (info) ChatLine(text);
else if (fail) ReplyFail(text);
else ReplyOk(text);
}
}
private static string Names(IEnumerable<string> names, int max = 12)
{
var l = names.ToList();
return l.Count <= max ? string.Join(", ", l) : string.Join(", ", l.Take(max)) + $" and {l.Count - max} more";
}
private void FinishUbEquip(UbInvJob job)
{
var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache };
var matched = new List<UbEquipPlan.Item>();
int order = 0, unidentified = 0;
var ruleOrder = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (WorldObject wo in UbInvCandidates(job.Kind))
{
uint id = unchecked((uint)wo.Id);
VTankLootVerdict v = job.Rules.Decide(wo, ctx, _charSkills, HasIdData(id), out InventoryRuleKind k, out string rule);
if (v == VTankLootVerdict.NeedsId) { unidentified++; continue; }
if (v != VTankLootVerdict.Match || k != InventoryRuleKind.Keep) continue;
if (!ruleOrder.TryGetValue(rule, out int r)) ruleOrder[rule] = r = ruleOrder.Count;
bool worn = WorldObjectCache.IsWieldedByPlayer(Host, wo);
int slots = wo.Values(LongValueKey.Locations, 0);
int wornAt = 0;
if (worn)
{
wornAt = wo.Values(LongValueKey.CurrentWieldedLocation, 0);
if (wornAt <= 0 && Host.HasGetObjectWielderInfo && Host.TryGetObjectWielderInfo(id, out _, out uint loc)) wornAt = unchecked((int)loc);
if (wornAt < 0) wornAt = 0;
}
matched.Add(new UbEquipPlan.Item(wo.Id, wo.Name, slots, worn, wornAt, r * 10_000 + order++));
}
UbEquipPlan.Result plan = UbEquipPlan.Plan(matched);
string profile = job.Rules.FileName;
string idNote = unidentified > 0 ? $" {unidentified} item(s) couldn't be identified in time and were left out." : "";
if (job.Kind == UbInvKind.EquipTest)
{
UbJobSay(job, $"[RynthAi] /ub equip test {profile}: "
+ (plan.Equip.Count > 0 ? $"would equip {Names(plan.Equip.Select(i => i.Name))}" : "nothing to equip")
+ (plan.AlreadyWorn.Count > 0 ? $"; already worn: {Names(plan.AlreadyWorn.Select(i => i.Name))}" : "")
+ (plan.Skipped.Count > 0 ? $"; left out: {Names(plan.Skipped.Select(s => $"{s.Item.Name} ({s.Why})"))}" : "")
+ "." + idNote, info: true);
return;
}
if (plan.Equip.Count == 0)
{
UbJobSay(job, matched.Count == 0
? $"[RynthAi] /ub equip load {profile}: nothing you carry matches its rules.{idNote}"
: $"[RynthAi] /ub equip load {profile}: nothing to put on ({plan.AlreadyWorn.Count} already worn).{idNote}",
fail: matched.Count == 0);
return;
}
if (!Host.HasUseObject) { UbJobSay(job, "[RynthAi] /ub equip load: this RynthCore can't use items.", fail: true); return; }
_ubEquipSends.Clear();
_ubEquipSent.Clear();
foreach (UbEquipPlan.Item i in plan.Equip) _ubEquipSends.Enqueue((unchecked((uint)i.Id), i.Name));
_ubEquipFromMeta = job.FromMeta;
_ubEquipProfile = profile;
_ubEquipNextAt = 0;
Log($"[RynthAi] /ub equip load {profile}: equipping {Names(plan.Equip.Select(i => i.Name), 40)}"
+ (plan.Skipped.Count > 0 ? $"; left out: {Names(plan.Skipped.Select(s => $"{s.Item.Name} ({s.Why})"), 40)}" : "") + "." + idNote);
UbJobSay(job, $"[RynthAi] /ub equip load {profile}: equipping {plan.Equip.Count} item(s).{idNote}");
TickUbEquipSends(UbInvClock());
}
/// <summary>One wield per <see cref="UbEquipSpacingMs"/>; after the last, says how many went on.</summary>
private void TickUbEquipSends(long now)
{
if (_ubEquipSends.Count > 0)
{
if (now < _ubEquipNextAt) return;
var (id, name) = _ubEquipSends.Dequeue();
WorldObject? wo = _objectCache?[unchecked((int)id)];
// Already on (worn since the plan): using it again would take it off.
if (wo != null && WorldObjectCache.IsWieldedByPlayer(Host, wo)) { _ubEquipSent.Add((id, name)); return; }
Host.UseFor(id, "Command", "/ub equip load", UseKind.Asked);
_ubEquipSent.Add((id, name));
_ubEquipNextAt = _ubEquipLastAt = now;
_ubEquipNextAt += UbEquipSpacingMs;
return;
}
if (_ubEquipSent.Count == 0 || now - _ubEquipLastAt < UbEquipSettleMs) return;
var missing = new List<string>();
foreach (var (id, name) in _ubEquipSent)
{
WorldObject? wo = _objectCache?[unchecked((int)id)];
if (wo == null || !WorldObjectCache.IsWieldedByPlayer(Host, wo)) missing.Add(name);
}
int on = _ubEquipSent.Count - missing.Count;
string text = missing.Count == 0
? $"[RynthAi] /ub equip load {_ubEquipProfile}: equipped {on} item(s)."
: $"[RynthAi] /ub equip load {_ubEquipProfile}: equipped {on} of {_ubEquipSent.Count}; not on: {Names(missing)}.";
_ubEquipSent.Clear();
var job = new UbInvJob { FromMeta = _ubEquipFromMeta };
UbJobSay(job, text, fail: missing.Count > 0);
}
private void FinishUbAutoSalvage(UbInvJob job)
{
var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache };
bool mainOnly = _metaManager?.Expressions is { } ex && ex.GetOption("AutoSalvage.OnlyFromMainPack") is string o
&& (o == "1" || o.Equals("true", StringComparison.OrdinalIgnoreCase));
var take = new List<WorldObject>();
var left = new List<string>();
int unidentified = 0;
foreach (WorldObject wo in UbInvCandidates(job.Kind))
{
uint id = unchecked((uint)wo.Id);
bool hasId = HasIdData(id);
VTankLootVerdict v = job.Rules.Decide(wo, ctx, _charSkills, hasId, out InventoryRuleKind k, out _);
if (v == VTankLootVerdict.NeedsId) { unidentified++; continue; }
if (v != VTankLootVerdict.Match || k != InventoryRuleKind.Salvage) continue;
if (!hasId) { unidentified++; continue; } // tinkered or imbued can't be told without it
if (wo.Values(unchecked((int)NumTimesTinkeredInt), 0) > 0) { left.Add(wo.Name + " (tinkered)"); continue; }
if (wo.Values(unchecked((int)ImbuedEffectInt), 0) != 0) { left.Add(wo.Name + " (imbued)"); continue; }
if (mainOnly && wo.Container != 0 && wo.Container != unchecked((int)_playerId)) continue;
take.Add(wo);
}
string profile = job.Rules.FileName;
string notes = (left.Count > 0 ? $" Left alone: {Names(left)}." : "")
+ (unidentified > 0 ? $" {unidentified} item(s) couldn't be identified in time and were left out." : "");
if (take.Count == 0)
{
UbJobSay(job, $"[RynthAi] /ub autosalvage ({profile}): nothing you carry is marked Salvage.{notes}",
info: job.Kind == UbInvKind.Salvage);
return;
}
if (job.Kind == UbInvKind.Salvage)
{
UbJobSay(job, $"[RynthAi] /ub autosalvage ({profile}): {take.Count} item(s) would be salvaged: {Names(take.Select(t => t.Name))}."
+ notes + " /ub autosalvage force salvages them.", info: true);
return;
}
if (_salvageManager == null) { UbJobSay(job, "[RynthAi] /ub autosalvage: salvaging isn't ready.", fail: true); return; }
foreach (WorldObject wo in take) _salvageManager.EnqueueItem(unchecked((uint)wo.Id));
Log($"[RynthAi] /ub autosalvage force ({profile}): queued {Names(take.Select(t => $"{t.Name} 0x{(uint)t.Id:X8}"), 60)}.{notes}");
UbJobSay(job, $"[RynthAi] /ub autosalvage force ({profile}): salvaging {take.Count} item(s): {Names(take.Select(t => t.Name))}.{notes}");
}
/// <summary>At logout: nothing of a job carries into the next character's session.</summary>
private void ResetUbInventoryJobs()
{
_ubInvJob = null;
_ubEquipSends.Clear();
_ubEquipSent.Clear();
}
}

View file

@ -7,6 +7,10 @@
// Plugins/Shared/DerethClock.cs has the math; RynthCore hosts the frameless
// window (plugin API v90) and remembers where it is.
//
// A clear background by default (2026-12-01: no box, the sun or moon and the text shadowed, so it
// can sit on the radar or under the arrow without taking room); /rdef daynight box brings the
// dark box back (DefSettings.DayNightBox). While hovered a faint box shows where to grab it.
//
// anywhere drag to move; Ctrl+wheel: bigger or smaller (30-250%);
// right-click: hide it (/rdef daynight, the bar button, or
// Settings > Interface > In The Retail Toolbar's Place show it again).
@ -64,10 +68,12 @@ internal sealed class DayNightWindow
private const float Pad = 5, RowH = 16, Mark = 14, Gap = 4, Radius = 4;
private static readonly uint SunColor = Argb(0xFFF2C14E), MoonColor = Argb(0xFFB8C7F0);
private static readonly uint ShadowColor = Argb(0xD8000000); // under the text and icon on a clear background
private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
/// <summary>Draws the timer into the host's window; returns the height it needs (pixels). Render thread.</summary>
public float Draw(DayNightView v)
/// <summary>Draws the timer into the host's window; returns the height it needs (pixels).
/// <paramref name="box"/>: the dark box; false = a clear background, the text shadowed. Render thread.</summary>
public float Draw(DayNightView v, bool box = false)
{
Scale();
uint bg = Color(RynthUiColor.Background), line = Color(RynthUiColor.Hairline);
@ -81,8 +87,11 @@ internal sealed class DayNightWindow
if (width < 30) return height;
ImDrawListPtr dl = ImGui.GetWindowDrawList();
Vector2 max = origin + new Vector2(width, height);
dl.AddRectFilled(origin, max, A(bg, 0.94f), Px(Radius));
dl.AddRect(origin, max, line, Px(Radius));
if (box)
{
dl.AddRectFilled(origin, max, A(bg, 0.94f), Px(Radius));
dl.AddRect(origin, max, line, Px(Radius));
}
// The whole window is the drag surface.
ImGui.SetCursorScreenPos(origin);
@ -90,6 +99,8 @@ internal sealed class DayNightWindow
_host.PanelDragWithLastItem();
if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) _host.SetPanelOpen(Title, RynthPanelOpen.Close);
bool hot = ImGui.IsItemHovered();
if (!box && hot) dl.AddRectFilled(origin, max, A(bg, 0.45f), Px(Radius)); // where to grab it
Vector2 sh = new(MathF.Max(1f, MathF.Round(Px(1))), MathF.Max(1f, MathF.Round(Px(1)))); // the shadow's offset
long nowMs = Environment.TickCount64;
double left = v.Ready ? v.SecondsLeft(nowMs) : 0;
@ -99,12 +110,15 @@ internal sealed class DayNightWindow
Vector2 at = origin + new Vector2(pad, pad);
string icon = !v.Ready || v.Now.IsDay ? RynthIcons.Sun : HasGlyph(RynthIcons.Moon) ? RynthIcons.Moon : RynthIcons.Star;
uint iconColor = !v.Ready ? faint : v.Now.IsDay ? SunColor : MoonColor;
if (!box) PanelButtonsWindow.DrawIcon(dl, icon, at + sh, new Vector2(Px(Mark), rowH), Px(13), ShadowColor);
PanelButtonsWindow.DrawIcon(dl, icon, at, new Vector2(Px(Mark), rowH), Px(13), iconColor);
ImFontPtr nf = Font(RynthUiFont.NarrowBold11), sf = Font(RynthUiFont.Narrow9);
float tx = at.X + Px(Mark) + Px(Gap), right = origin.X + width - pad;
float lw = nf.CalcTextSizeA(Fs(nf), float.MaxValue, 0f, label).X;
dl.AddText(nf, Fs(nf), new Vector2(MathF.Round(tx), MathF.Round(at.Y + (rowH - Fs(nf)) * 0.5f)), v.Ready ? text : faint, label);
Vector2 labelAt = new(MathF.Round(tx), MathF.Round(at.Y + (rowH - Fs(nf)) * 0.5f));
if (!box) dl.AddText(nf, Fs(nf), labelAt + sh, ShadowColor, label);
dl.AddText(nf, Fs(nf), labelAt, v.Ready ? text : faint, label);
// The hour's name, right-aligned, only when it fits whole.
if (v.Ready)
@ -112,7 +126,11 @@ internal sealed class DayNightWindow
string hour = v.Now.HourName;
float hw = sf.CalcTextSizeA(Fs(sf), float.MaxValue, 0f, hour).X;
if (tx + lw + Px(8) + hw <= right)
dl.AddText(sf, Fs(sf), new Vector2(MathF.Round(right - hw), MathF.Round(at.Y + (rowH - Fs(sf)) * 0.5f)), faint, hour);
{
Vector2 hourAt = new(MathF.Round(right - hw), MathF.Round(at.Y + (rowH - Fs(sf)) * 0.5f));
if (!box) dl.AddText(sf, Fs(sf), hourAt + sh, ShadowColor, hour);
dl.AddText(sf, Fs(sf), hourAt, box ? faint : A(text, 0.8f), hour);
}
}
if (hot) SafeImGui.SetItemTooltip(Tip(v, left));
@ -139,7 +157,8 @@ internal sealed class DayNightWindow
internal static string Tip(DayNightView v, double left)
{
const string help = "A Dereth day is 2 h 7 min of real time: 63.5 minutes of day, then 63.5 of night.\n"
+ "Drag to move; Ctrl+wheel: bigger or smaller; right-click: hide (/rdef daynight).";
+ "Drag to move; Ctrl+wheel: bigger or smaller; right-click: hide (/rdef daynight).\n"
+ "/rdef daynight box: the dark box; /rdef daynight clear: no background.";
if (!v.Ready) return "Day or night in Dereth, and the real minutes until it changes. Shown once you're in the world.\n" + help;
TimeSpan t = TimeSpan.FromSeconds(Math.Ceiling(left));
string until = t.TotalMinutes >= 1 ? $"{(int)t.TotalMinutes} min {t.Seconds} s" : $"{t.Seconds} s";

View file

@ -21,9 +21,9 @@ internal static class DefCommandParser
"/rdef [use <slot or item name> | set <slot> [item name] | spell <slot> <spell name> | clear <slot> | bind <slot> <key> | unbind <slot> | "
+ "weapons [search] | fav | slots <count> | list | status | settings | panels (the game panel buttons) | selection | appraisal [pin|unpin|again|popout|dock] | corpses [clear] | "
+ "bars [add | remove <bar> | slots <bar> <count> | show <bar>] | shortcuts clearbusy [on|off] | "
+ "qty [number|max|half] | split [number] [into <pack>] | give [number] | buy [number] [item name] | daynight [show|hide]]";
+ "qty [number|max|half] | split [number] [into <pack>] | give [number] | buy [number] [item name] | daynight [show|hide|clear|box]]";
public const string DayNightUsage = "Usage: /rdef daynight [show|hide], e.g. /rdef daynight show (the Day/Night timer: real minutes to the next dawn or dusk)";
public const string DayNightUsage = "Usage: /rdef daynight [show|hide|clear|box], e.g. /rdef daynight show (the Day/Night timer: real minutes to the next dawn or dusk; clear = no background, box = its dark box)";
public const string ClearBusyUsage =
"Usage: /rdef shortcuts clearbusy on|off, e.g. /rdef shortcuts clearbusy on (a press held only by a stuck busy count clears it first; off by default)";
@ -59,14 +59,16 @@ internal static class DefCommandParser
case "selection": case "target":
// "/rdef selection 0x80001234": select that object (a test hook for the Selection window).
return new DefCommand(DefVerb.Selection, Text: rest);
// The Day/Night timer (2026-11-04): Text "show", "hide" or "" (toggle).
// The Day/Night timer (2026-11-04): Text "show", "hide" or "" (toggle); "clear" or "box" (2026-12-01) its background.
case "daynight":
return rest.ToLowerInvariant() switch
{
"" or "toggle" => new DefCommand(DefVerb.DayNight),
"show" or "on" or "open" => new DefCommand(DefVerb.DayNight, Text: "show"),
"hide" or "off" or "close" => new DefCommand(DefVerb.DayNight, Text: "hide"),
_ => Fail($"'{rest}' isn't show or hide. {DayNightUsage}"),
"clear" or "transparent" or "nobox" => new DefCommand(DefVerb.DayNight, Text: "clear"),
"box" or "background" => new DefCommand(DefVerb.DayNight, Text: "box"),
_ => Fail($"'{rest}' isn't show, hide, clear or box. {DayNightUsage}"),
};
case "fav": case "favourite": case "favorite": return new DefCommand(DefVerb.Favourite);
case "weapons": case "weapon": case "picker": return new DefCommand(DefVerb.Weapons, Text: rest);

View file

@ -118,6 +118,13 @@ internal sealed class DefSettings
/// </summary>
public bool QuantityBox = true;
/// <summary>
/// The Day/Night timer's dark box (2026-12-01: a clear background, so it takes no
/// room of its own). Off (the default, and what a file from before reads as): the timer
/// is drawn on a clear background, its sun or moon and text shadowed so they read over the radar,
/// the arrow or the world. On: the dark box as before. /rdef daynight clear | box.
/// </summary>
public bool DayNightBox;
/// <summary>
/// Shortcuts clear a stuck busy state (2026-11-04, a player's ask): a press held only by the client's
/// busy count (nothing of ours or RynthAi's in flight, no gesture, no "You're too busy" just now) resets
/// the count as RynthAi's /ra clearbusy does (the engine's ForceResetBusyCount), then goes, once per

View file

@ -41,6 +41,11 @@ internal static class DefReplies
: (true, CommandReply.Shown("Day/Night timer", state == 1) + time);
}
/// <summary>/rdef daynight clear | box: the timer's background after it.</summary>
public static (bool Ok, string Text) DayNightLook(bool box) => (true, box
? "Day/Night timer: on its dark box (/rdef daynight clear for no background)."
: "Day/Night timer: on a clear background (/rdef daynight box brings the dark box back).");
/// <summary>A slot's use started (the result shows on the bar; a problem is said in chat).</summary>
public static string UseSlot(DefSlot slot, int number) => slot.IsSpell
? $"Casting {slot.SpellLabel} (slot {number})."

View file

@ -121,7 +121,9 @@ 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 > Interface > In The Retail Toolbar's Place >
A one-row window (its RynthCore bar button is the sun; `/rdef daynight [show|hide]`; on a clear background, the text
shadowed, so it can sit on the radar or under the arrow, and `/rdef daynight box` / `clear` puts its dark box back or
takes it away (per character, 2026-12-01); 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

@ -34,7 +34,7 @@ public sealed partial class RynthDefectivePlugin
try
{
_dayNightWindow ??= new DayNightWindow(Host);
wantHeight = _dayNightWindow.Draw(_dayNightView);
wantHeight = _dayNightWindow.Draw(_dayNightView, _session.Settings.DayNightBox);
_dayNightFailures = 0;
return 1;
}

View file

@ -235,6 +235,14 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
break;
case DefVerb.DayNight:
{
if (c.Text is "clear" or "box")
{
// The timer's background (2026-12-01): kept with the character's settings.
_session.Settings.DayNightBox = c.Text == "box";
RequestSave();
Answer(DefReplies.DayNightLook(_session.Settings.DayNightBox));
break;
}
// The window shown or hidden, and the time now in the reply (an engine without the window: the time only).
RynthPanelOpen mode = c.Text == "show" ? RynthPanelOpen.Open : c.Text == "hide" ? RynthPanelOpen.Close : RynthPanelOpen.Toggle;
int state = UsesShortcutBar ? Host.SetPanelOpen(Clock.DayNightWindow.Title, mode) : -1;

View file

@ -139,6 +139,10 @@ public sealed partial class RynthLuaPlugin
/// <summary>Test harness only: whether a script's Lua state is still alive.</summary>
internal bool ScriptIsLoaded(string name) => _scripts.TryGetValue(name, out var ctx) && ctx.Host.Loaded;
/// <summary>Test harness only: worker coroutines a running script has made (-1 when it isn't running).</summary>
internal int ScriptWorkersCreated(string name) =>
_scripts.TryGetValue(name, out var ctx) && ctx.Host.Loaded ? ctx.Host.WorkersCreated : -1;
private void RegisterGame(Script s, ScriptContext ctx)
{
var game = new Table(s);

View file

@ -32,15 +32,127 @@ internal sealed class LuaScriptHost
private sealed class LuaThread
{
public DynValue Co = DynValue.Nil;
public DynValue Co = DynValue.Nil; // set when the thread first runs (TakeCoroutine)
public DynValue Fn = DynValue.Nil; // the function, until then
public long WakeAt;
public Func<bool>? WaitFor; // await: resume only once this is true
public DynValue[] Args = Array.Empty<DynValue>();
public bool Started;
/// <summary>Runs on a pooled worker coroutine (see <see cref="RentWorker"/>): it ends by yielding the done token.</summary>
public bool Pooled;
/// <summary>Called once when the thread ends: its return values, or the error message.</summary>
public Action<DynValue?, string?>? OnDone;
}
// ── Worker coroutines ───────────────────────────────────────────────────
//
// MoonSharp 2.0 gives every coroutine two 131,072-slot stacks the moment it is created:
// about 1 MB in the 32-bit client (2 MB in a 64-bit process), all on the Large Object Heap,
// which only a full collection frees. RynthLua used to make one per event handler call and
// per hud pass, so a 194-line /myquests read cost each script with a chat handler ~200 MB and
// a 20-per-second window 20 MB/s. The heap figure the memory guard reads then passed 800 MB
// and the guard stopped scripts that had done nothing wrong (2026-11-30).
// Now a thread runs on a worker: a Lua loop that calls the function it is given, yields the
// done token with the results, and waits for the next function. A worker whose function
// ended normally goes back to a small pool; one that raised an error, or was aborted or
// stopped part-way, is simply dropped (it can't be reused).
private const string WorkerCode = @"
local DONE, yield, select, unpack = ...
local function packn(...) return { n = select('#', ...), ... } end
return function(fn, args)
while true do
fn, args = yield(DONE, packn(fn(unpack(args, 1, args.n))))
end
end";
/// <summary>Idle workers kept per script; more than this are left to the GC.</summary>
internal const int MaxIdleWorkers = 8;
private DynValue _workerFn = DynValue.Nil;
private Table? _doneToken;
private readonly Stack<DynValue> _idleWorkers = new();
/// <summary>Test hook: workers made since the script started (a fresh coroutine each).</summary>
internal int WorkersCreated { get; private set; }
/// <summary>
/// Makes the worker function from the state's own coroutine.yield, select and table.unpack,
/// taken before any script code runs (a script that replaces them later doesn't touch workers).
/// </summary>
private void CreateWorkers(Script s)
{
_idleWorkers.Clear();
_workerFn = DynValue.Nil;
_doneToken = null;
WorkersCreated = 0;
try
{
DynValue co = s.Globals.Get("coroutine");
DynValue tbl = s.Globals.Get("table");
DynValue yield = co.Type == DataType.Table ? co.Table.Get("yield") : DynValue.Nil;
DynValue select = s.Globals.Get("select");
DynValue unpack = tbl.Type == DataType.Table ? tbl.Table.Get("unpack") : DynValue.Nil;
if (unpack.IsNil()) unpack = s.Globals.Get("unpack");
if (yield.IsNil() || select.IsNil() || unpack.IsNil()) return; // old behaviour: a coroutine per thread
var token = new Table(s);
DynValue factory = s.LoadString(WorkerCode, new Table(s), "rynth worker");
DynValue fn = s.Call(factory, DynValue.NewTable(token), yield, select, unpack);
if (fn.Type != DataType.Function) return;
_doneToken = token;
_workerFn = fn;
}
catch { _workerFn = DynValue.Nil; _doneToken = null; }
}
/// <summary>An idle worker, or a new one; null when workers aren't available (a coroutine per thread then).</summary>
internal DynValue? RentWorker()
{
if (_script == null || _workerFn.Type != DataType.Function) return null;
while (_idleWorkers.Count > 0)
{
DynValue w = _idleWorkers.Pop();
if (w.Coroutine.State is CoroutineState.Suspended or CoroutineState.NotStarted) return w;
}
WorkersCreated++;
return _script.CreateCoroutine(_workerFn);
}
/// <summary>Puts a worker that yielded the done token back in the pool.</summary>
internal void ReturnWorker(DynValue worker)
{
if (_script == null || worker.Coroutine.State is not (CoroutineState.Suspended or CoroutineState.NotStarted)) return;
if (_idleWorkers.Count < MaxIdleWorkers) _idleWorkers.Push(worker);
}
/// <summary>What a worker is resumed with to run <paramref name="fn"/>(<paramref name="args"/>...).</summary>
internal DynValue[] WorkerArgs(DynValue fn, DynValue[] args)
{
var t = new Table(_script);
for (int i = 0; i < args.Length; i++) t.Set(i + 1, args[i]);
t.Set("n", DynValue.NewNumber(args.Length));
return new[] { fn, DynValue.NewTable(t) };
}
/// <summary>True when <paramref name="r"/> (a worker's Resume result) says its function returned.</summary>
internal bool IsWorkerDone(DynValue r) =>
_doneToken != null && r.Type == DataType.Tuple && r.Tuple is { Length: 2 } tu
&& tu[0].Type == DataType.Table && ReferenceEquals(tu[0].Table, _doneToken);
/// <summary>The function's return values from a done worker's result: Void for none, the value for one, else a tuple.</summary>
internal static DynValue WorkerResults(DynValue r)
{
DynValue packed = r.Tuple[1];
if (packed.Type != DataType.Table) return DynValue.Void;
Table t = packed.Table;
DynValue nv = t.RawGet("n") ?? DynValue.Nil;
int n = nv.Type == DataType.Number ? (int)nv.Number : 0;
if (n <= 0) return DynValue.Void;
if (n == 1) return t.Get(1);
var values = new DynValue[n];
for (int i = 0; i < n; i++) values[i] = t.Get(i + 1);
return DynValue.NewTuple(values);
}
private readonly Action<string> _log;
private readonly Action<Script, LuaScriptHost> _registerApi;
private readonly List<LuaThread> _threads = new();
@ -157,6 +269,7 @@ internal sealed class LuaScriptHost
try
{
RegisterCore(script);
CreateWorkers(script);
_registerApi(script, this);
DynValue chunk = script.LoadString(code, null, ScriptName.Length > 0 ? ScriptName : "editor");
Start(chunk, Array.Empty<DynValue>());
@ -198,6 +311,9 @@ internal sealed class LuaScriptHost
bool was = _script != null;
_threads.Clear();
_handlers.Clear();
_idleWorkers.Clear();
_workerFn = DynValue.Nil;
_doneToken = null;
_current = null;
_botTickThread = null;
_script = null;
@ -223,13 +339,29 @@ internal sealed class LuaScriptHost
public object? Start(DynValue fn, DynValue[] args, Action<DynValue?, string?>? onDone)
{
if (_script == null || fn.Type != DataType.Function) return null;
DynValue co = _script.CreateCoroutine(fn);
co.Coroutine.AutoYieldCounter = AutoYieldCounter;
var t = new LuaThread { Co = co, Args = args, OnDone = onDone };
// The coroutine is taken when the thread first runs (Tick), not here: a burst of events
// (194 /myquests lines between two ticks) then runs one after another on the same few
// workers instead of holding a worker each while they wait for their turn.
var t = new LuaThread { Fn = fn, Args = args, OnDone = onDone };
_threads.Add(t);
return t;
}
/// <summary>Gives a thread that is about to run for the first time its coroutine.</summary>
private void TakeCoroutine(LuaThread t)
{
DynValue? worker = RentWorker();
if (worker != null)
{
t.Co = worker;
t.Args = WorkerArgs(t.Fn, t.Args);
t.Pooled = true;
}
else t.Co = _script!.CreateCoroutine(t.Fn);
t.Fn = DynValue.Nil;
t.Co.Coroutine.AutoYieldCounter = AutoYieldCounter;
}
/// <summary>
/// Ends the thread <paramref name="handle"/> (from <see cref="Start(DynValue, DynValue[], Action{DynValue?, string?}?)"/>)
/// without resuming it again; its onDone is not called. Returns false when it had already ended.
@ -239,7 +371,7 @@ internal sealed class LuaScriptHost
if (handle is not LuaThread t) return false;
t.OnDone = null;
if (ReferenceEquals(_botTickThread, t)) _botTickThread = null;
return _threads.Remove(t);
return _threads.Remove(t); // a worker stopped part-way is dropped with it
}
private static void Done(LuaThread t, DynValue? result, string? error)
@ -401,9 +533,10 @@ internal sealed class LuaScriptHost
{
while (_script != null)
{
if (!t.Started) TakeCoroutine(t);
r = t.Started ? t.Co.Coroutine.Resume() : t.Co.Coroutine.Resume(t.Args);
t.Started = true;
if (t.Co.Coroutine.State == CoroutineState.Dead) break;
if (t.Co.Coroutine.State == CoroutineState.Dead || (t.Pooled && IsWorkerDone(r))) break;
// 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
@ -445,6 +578,14 @@ internal sealed class LuaScriptHost
_threads.Remove(t);
Done(t, r, null);
}
else if (t.Pooled && IsWorkerDone(r))
{
// The function returned: the worker waits at its yield for the next one.
_threads.Remove(t);
if (ReferenceEquals(_botTickThread, t)) _botTickThread = null;
ReturnWorker(t.Co);
Done(t, WorkerResults(r), null);
}
if (OverBudget()) break;
}
}

View file

@ -530,10 +530,17 @@ public sealed partial class RynthLuaPlugin
long alloc0 = LuaScriptHost.AllocationMark();
try
{
DynValue co = s.CreateCoroutine(runner);
// A pooled worker (LuaScriptHost: a new coroutine is ~1 MB) when the host has them.
LuaScriptHost host = hud.Ctx.Host;
DynValue? worker = host.RentWorker();
DynValue co = worker ?? s.CreateCoroutine(runner);
co.Coroutine.AutoYieldCounter = PassInstructionCap;
DynValue r = co.Coroutine.Resume(DynValue.NewTable(list));
if (co.Coroutine.State != CoroutineState.Dead)
DynValue r = worker != null
? co.Coroutine.Resume(host.WorkerArgs(runner, new[] { DynValue.NewTable(list) }))
: co.Coroutine.Resume(DynValue.NewTable(list));
if (worker != null && host.IsWorkerDone(r))
host.ReturnWorker(co); // the pass ran to its end; anything else drops the worker
else if (co.Coroutine.State != CoroutineState.Dead)
{
error = r.Type == DataType.YieldRequest
? $"OnRender ran too long (over {PassInstructionCap} instructions); the last good frame stays"