RynthSuite as of 2026-12-02 (internal 152e13d): release 2026.12.1.1
This commit is contained in:
parent
e8e4228d15
commit
6b5a9c7e99
65 changed files with 3920 additions and 237 deletions
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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}");
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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}.");
|
||||
}
|
||||
}
|
||||
|
|
@ -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\<name>.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)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
|
|
|
|||
|
|
@ -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; }
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
102
Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryRules.cs
Normal file
102
Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryRules.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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" : ""));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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, ...)
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
{
|
||||
|
|
|
|||
250
Plugins/RynthCore.Plugin.RynthAi/Meta/MetaNavEmbedding.cs
Normal file
250
Plugins/RynthCore.Plugin.RynthAi/Meta/MetaNavEmbedding.cs
Normal 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\<name>.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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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) ──
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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.");
|
||||
}
|
||||
|
||||
|
|
|
|||
512
Plugins/RynthCore.Plugin.RynthAi/UtilityBeltInventoryCommands.cs
Normal file
512
Plugins/RynthCore.Plugin.RynthAi/UtilityBeltInventoryCommands.cs
Normal 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 <name>: LootProfiles\<name>.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();
|
||||
}
|
||||
}
|
||||
|
|
@ -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";
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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})."
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -55,6 +55,8 @@ internal static class Program
|
|||
// Appraised creatures are saved to C:\Games\RynthSuite\RynthAi\CreatureData\creatures.json.
|
||||
LiveCreatureFolder = RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder;
|
||||
RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder = Path.Combine(TempRoot, "CreatureData");
|
||||
// /ub equip create writes an equipment profile into C:\Games\RynthSuite\RynthAi\LootProfiles.
|
||||
RynthCore.Plugin.RynthAi.RynthAiPlugin.UbEquipFolder = Path.Combine(TempRoot, "UbEquip");
|
||||
|
||||
// Spell names (item spells, spell expiry by name) come from the plugin's embedded table.
|
||||
SpellDatabase.Load();
|
||||
|
|
@ -77,6 +79,7 @@ internal static class Program
|
|||
MagItemDescriberTests.Register(runner);
|
||||
ExpressionTests.Register(runner);
|
||||
MetaTests.Register(runner);
|
||||
MetaCommandAuditTests.Register(runner);
|
||||
SelfTestMetaTests.Register(runner);
|
||||
NoKillTests.Register(runner);
|
||||
MetaSchedulerTests.Register(runner);
|
||||
|
|
@ -161,6 +164,7 @@ internal static class Program
|
|||
LootAddItemTests.Register(runner);
|
||||
GiveTests.Register(runner);
|
||||
UbCompatTests.Register(runner);
|
||||
UbInventoryTests.Register(runner);
|
||||
MetaAuditTests.Register(runner);
|
||||
MetaSampleCompatTests.Register(runner);
|
||||
IdRefusalTests.Register(runner);
|
||||
|
|
@ -240,6 +244,7 @@ internal static class Program
|
|||
ProfileButtonTests.Register(runner);
|
||||
MonsterProfileTests.Register(runner);
|
||||
ProfileStartTests.Register(runner);
|
||||
NamedLayoutRowTests.Register(runner);
|
||||
GiveProfileTests.Register(runner);
|
||||
TinkerTests.Register(runner);
|
||||
KitRunnerTests.Register(runner);
|
||||
|
|
@ -258,6 +263,7 @@ AmmoAutoPluginTests.Register(runner);
|
|||
CommandReplyTests.Register(runner);
|
||||
MonsterStatsTests.Register(runner);
|
||||
MetaSaveTests.Register(runner);
|
||||
MetaEmbedNavTests.Register(runner);
|
||||
MetaResumeTests.Register(runner);
|
||||
FellowOpenTests.Register(runner);
|
||||
WieldBanTests.Register(runner);
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ internal static unsafe class AutoConfirmCraftTests
|
|||
r.Add("autoconfirm: logout releases the arm", Logout);
|
||||
r.Add("autoconfirm: settings - off at 100 by default, saved, copied, sent to the engine face as nullable fields", Settings);
|
||||
r.Add("autoconfirm: /ra autoconfirm on|off|<percent>|status always answers", Command);
|
||||
r.Add("/ub prepclick yes [ms] arms a Yes for the next yes/no prompt (5-60 s); no disarms (R-20261125-144721-b49a)", UbPrepClick);
|
||||
r.Add("/ub prepclick yes [seconds] arms a Yes for the next yes/no prompt (15 s by default, 5 s-5 min); no and stop disarm (R-20261125-144721-b49a, 12-01 audit)", UbPrepClick);
|
||||
}
|
||||
|
||||
// ── The fake engine's confirmation calls (static: function pointers can't capture) ──────────
|
||||
|
|
@ -146,15 +146,22 @@ internal static unsafe class AutoConfirmCraftTests
|
|||
|
||||
Check.True(Run("/ub prepclick yes 100"), "taken");
|
||||
Check.Eq(ArmCalls.Count, 1, "one arm");
|
||||
Check.Eq(ArmCalls[0], (RynthCoreHost.ConfirmationKind.YesNo, 0, RynthAiPlugin.PrepClickMinMs), "a Yes for the next yes/no prompt, 100 ms raised to 5 s");
|
||||
Check.Eq(ArmCalls[0], (RynthCoreHost.ConfirmationKind.YesNo, 0, 100_000), "a Yes for the next yes/no prompt within 100 s (UtilityBelt's seconds)");
|
||||
Check.Eq(Prompt(0, RynthCoreHost.ConfirmationKind.YesNo), RynthCoreHost.ConfirmationOutcome.Accepted, "the prompt is answered Yes");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("no RynthAi equivalent")), "no longer 'ignored'");
|
||||
|
||||
Run("/ub prepclick yes");
|
||||
Check.Eq(ArmCalls[^1].Timeout, RynthAiPlugin.PrepClickDefaultMs, "no number: 15 s");
|
||||
Run("/ub prepclick yes 2");
|
||||
Check.Eq(ArmCalls[^1].Timeout, RynthAiPlugin.PrepClickMinMs, "2 s raised to 5 s (metas send it again before each hand-in)");
|
||||
Run("/ub prepclick yes 999999");
|
||||
Check.Eq(ArmCalls[^1].Timeout, RynthAiPlugin.PrepClickMaxMs, "at most 60 s");
|
||||
Check.Eq(ArmCalls[^1].Timeout, RynthAiPlugin.PrepClickMaxMs, "at most 5 min");
|
||||
Run("/ub prepclick no");
|
||||
Check.Eq(ArmCalls[^1].Timeout, 0, "no: disarmed");
|
||||
Check.Eq(Prompt(0, RynthCoreHost.ConfirmationKind.YesNo), RynthCoreHost.ConfirmationOutcome.Shown, "the next prompt is left to the client");
|
||||
Run("/ub prepclick yes 30");
|
||||
Check.True(Run("/ub prepclick stop"), "stop: taken (it answered with the usage before)");
|
||||
Check.Eq(ArmCalls[^1].Timeout, 0, "stop: disarmed");
|
||||
}
|
||||
finally { TickIsolationTests.Done(); FakeHost.ConfigureApi = null; }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -55,6 +55,7 @@ internal static class CombatHookTests
|
|||
r.Add("blacklist: casts answered 'too busy' (UseDone 0x1D) are not no-damage casts (answered 0: the target is dropped)", RefusedCastsNotJudged);
|
||||
r.Add("ghost (R-20261115-172110-9e6a): two casts answered 'target not acquired' (UseDone 0x42C) mark the target a ghost and stop the casting", NotAcquiredMarksGhost);
|
||||
r.Add("out of range (R-20261119-155301-121a): a cast answered 'Out of Range!' (UseDone 0x550) drops the target until it comes 3 m nearer", OutOfRangeDropsTarget);
|
||||
r.Add("out of range (R-20261201-190034-03c5): the target dropped in the tick's answer check gets no debuff cast at target 0 that tick", DroppedTargetNoDebuff);
|
||||
r.Add("blacklist (2026-11-15): melee landing nothing across a building's wall (one inside, one out) keeps the target off 5 min; elsewhere the usual timeout", AcrossWallBlacklistLonger);
|
||||
r.Add("loot jump: Think sends no cast while in the air after a loot jump; it casts on the landing, or at the cap", LootJumpHoldsAttack);
|
||||
r.Add("loot jump: a swing refused in the air (WeenieError 0x4EB) is not a no-damage attack (without it: a miss)", MeleeInAirNotJudged);
|
||||
|
|
@ -1092,6 +1093,41 @@ internal static class CombatHookTests
|
|||
// hourglass going round), never dropping it.
|
||||
// 2026.11.15.3: an Olthoi Hive Warrior 88 m off, every Incantation of Force Arc at it answered UseDone
|
||||
// 0x550 about 60 ms after the send, and combat cast again at once (1,027 casts since the last kill).
|
||||
// R-20261201-190034-03c5 (Conquest): a bolt answered 'Out of Range!', Think's answer check dropped the target, and
|
||||
// the same tick's attack still cast Imperil, at target 0: the client refused it locally, nothing reached the server,
|
||||
// and combat waited 7 s for an answer, jumped, went to Peace: about 13 s stood still.
|
||||
private static void DroppedTargetNoDebuff() => Guard(() =>
|
||||
{
|
||||
var rig = new AttackRig(setup: () =>
|
||||
{
|
||||
FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true;
|
||||
foreach (var row in SpellTable.Named("Imperil Other VI")) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
});
|
||||
rig.S.EnableRaycasting = false;
|
||||
rig.Attack();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "the bolt goes out");
|
||||
rig.S.MonsterRules[0].Imperil = true; // the next cast would be a debuff
|
||||
FakeHost.UseDone(CombatManager.MissileOutOfRangeErr);
|
||||
SetField(rig.C, "_pendingOffensiveCastAt", DateTime.Now.AddSeconds(-5));
|
||||
CallPrivate(rig.C, "JudgePendingOffensiveCast"); // Think's answer check, before the attack
|
||||
Check.Eq(rig.C.activeTargetId, 0, "'Out of Range!': the target is dropped");
|
||||
rig.Attack();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "no debuff goes out in the same tick: " + string.Join(", ", FakeHost.Casts.Select(c => $"{NameOf(c.SpellId)}@0x{c.Target:X8}")));
|
||||
Check.False(FakeHost.Casts.Any(c => c.Target == 0), "nothing is ever cast at target 0");
|
||||
|
||||
// Control: with the target still locked the debuff goes, at the target.
|
||||
var ok = new AttackRig(setup: () =>
|
||||
{
|
||||
FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true;
|
||||
foreach (var row in SpellTable.Named("Imperil Other VI")) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
});
|
||||
ok.S.EnableRaycasting = false;
|
||||
ok.S.MonsterRules[0].Imperil = true;
|
||||
ok.Attack();
|
||||
Check.Eq(ok.LastCast, "Imperil Other VI", "with the target locked: Imperil first");
|
||||
Check.Eq(FakeHost.Casts[^1].Target, (uint)Target, "at the target");
|
||||
});
|
||||
|
||||
private static void OutOfRangeDropsTarget() => Guard(() =>
|
||||
{
|
||||
var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; });
|
||||
|
|
|
|||
|
|
@ -57,6 +57,9 @@ internal static class CommandReplyTests
|
|||
new("/ra navhud off", null, K.Act),
|
||||
new("/ra navtrail on", null, K.Act),
|
||||
new("/ra navtrail clear", null, K.Act),
|
||||
// No trail in the rig (breadcrumbs come from walking): route|back fail here, as they say how to get one.
|
||||
new(null, "/ra navtrail route", K.Act),
|
||||
new(null, "/ra navtrail back", K.Act),
|
||||
new("/ra navoverlay off", null, K.Act),
|
||||
new("/ra debug off", null, K.Act),
|
||||
new("/ra lootcheck off", "/ra lootcheck", K.Act),
|
||||
|
|
@ -327,6 +330,7 @@ internal static class CommandReplyTests
|
|||
new(null, "/mt vendor sell", K.Act),
|
||||
new(null, "/mt vendor buy", K.Act),
|
||||
new("/mt autopack", null, K.Act),
|
||||
new(null, "/mt attack_melee banana", K.Act), // Mag-Tools (2026-12-01); this rig has no attack call
|
||||
new("/mt click ok", "/mt click", K.Act),
|
||||
new("/mt click 10 20", "/mt click banana", K.Act),
|
||||
new("/mt movement w 0", "/mt movement", K.Act),
|
||||
|
|
@ -424,6 +428,8 @@ internal static class CommandReplyTests
|
|||
new("/ub combatstate peace", "/ub combatstate", K.Act),
|
||||
new("/ub cast 1234", "/ub cast", K.Act),
|
||||
new("/ub equip Sharp Sword", "/ub equip", K.Act),
|
||||
new("/ub equip list", "/ub equip load", K.Query), // UtilityBelt's equipment profiles (2026-12-01)
|
||||
new(null, "/ub autosalvage banana", K.Act),
|
||||
new("/ub drop Faran Robe", "/ub drop", K.Act),
|
||||
new("/ub select Faran Robe", "/ub select", K.Act),
|
||||
new("/ub loot Gem", "/ub loot", K.Act),
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ internal static class ExpressionTests
|
|||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("expressions (R-20261201-211257-d2be, -4871): createlist[...] (UtilityBelt's name) makes a list; listcontains[...] == 0 is a number", LandblockListReports);
|
||||
r.Add("expr: safety - var files point at the scratch folder", VarPathsRedirected);
|
||||
r.Add("expr: arithmetic and precedence", Arithmetic);
|
||||
r.Add("expr: unary minus, negative and hex literals", UnaryAndLiterals);
|
||||
|
|
@ -1105,6 +1106,30 @@ internal static class ExpressionTests
|
|||
|
||||
// ── UtilityBelt reference audit ──────────────────────────────────────────
|
||||
|
||||
// R-20261201-211257-d2be / R-20261201-211007-4871 (Coldeve, a meta author): a landblock list made with
|
||||
// UtilityBelt's createlist[...] and checked with listcontains[...] == 0.
|
||||
private static void LandblockListReports()
|
||||
{
|
||||
var e = Engine();
|
||||
Is(e, "setvar[lbs, createlist[2271412224,2271477760,2305163264]]", "[2271412224,2271477760,2305163264]");
|
||||
Is(e, "listcount[getvar[lbs]]", "3");
|
||||
Is(e, "listcontains[getvar[lbs], 2271477760]", "1");
|
||||
Is(e, "listcontains[getvar[lbs], 2271477760] == 0", "0");
|
||||
Is(e, "listcontains[getvar[lbs], 5] == 0", "1");
|
||||
Is(e, "listcontains[getvar[lbs], 2271477760]==1", "1");
|
||||
// The report's own line (getvar's ] in the wrong place): still a number, never the text back.
|
||||
string r = e.Evaluate("listcontains[getvar[lbs, getplayerlandblock[]]] == 0");
|
||||
Check.True(r == "0" || r == "1", "the report's line gives a number: '" + r + "'");
|
||||
// As in game: the list never made (createlist unknown then), so the variable is empty or unset.
|
||||
e.Evaluate("setvar[nosuch, nosuchfunction[1,2]]"); // set, to empty, as an unknown function left it
|
||||
foreach (string line in new[] { "listcontains[getvar[nosuch, getplayerlandblock[]]] == 0", "listcontains[getvar[nosuch], getplayerlandblock[]] == 0",
|
||||
"listcontains[getvar[nosuch, getplayerlandblock[]]]" })
|
||||
{
|
||||
string v = e.Evaluate(line);
|
||||
Check.True(v == "0" || v == "1", $"'{line}' gives a number: '{v}'");
|
||||
}
|
||||
}
|
||||
|
||||
private static void DocSemicolon()
|
||||
{
|
||||
var e = Engine();
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ internal static class ManaStoneChoiceTests
|
|||
r.Add("mana stones: in a fight, worn gear that runs low is still refilled (armor without mana drops its spells)", RefillInFight);
|
||||
r.Add("eternal charge: tapping is ignored while it is in the pack, and applies again when it leaves", EternalIgnoresTapping);
|
||||
r.Add("eternal charge: a use with no answer is tried again in 20 s, not 5 minutes", EternalRetriesSoon);
|
||||
r.Add("eternal charge (11-30): one only the pack walk has (not in the cache yet) refills worn gear, tapping on or off", EternalOnlyInPackWalk);
|
||||
r.Add("mana tap with macro off (on by default): the macro stopped, stones still refill gear and drain tap loot", TapWithMacroOff);
|
||||
r.Add("mana tap with macro off, unticked: nothing while the macro is stopped; it starts with the macro", NoTapWithMacroOffUnticked);
|
||||
}
|
||||
|
|
@ -100,6 +101,21 @@ internal static class ManaStoneChoiceTests
|
|||
Check.Eq(rig.OnRing.Count, 1, "tapping applies again: the item is drained");
|
||||
}
|
||||
|
||||
// 11-30: gear at 30-46% for an hour with "eternal=True needs=True" and "no charged stone is known":
|
||||
// the Eternal Mana Charge was in the client's pack lists but not in the cache, and the stone search
|
||||
// read the cache alone.
|
||||
private static void EternalOnlyInPackWalk()
|
||||
{
|
||||
foreach (bool tapping in new[] { true, false })
|
||||
{
|
||||
using var rig = new Rig(tapping, new (uint, int?)[] { (ChargeA, null) }, stoneName: EternalCharge, maceMana: 0, contents: true,
|
||||
before: ids => ids.Remove(ChargeA));
|
||||
Check.False(rig.C.AllKnownObjects().Any(o => o.Id == unchecked((int)ChargeA)), "the cache doesn't know the charge");
|
||||
rig.Run(1000);
|
||||
Check.Eq(rig.OnPlayer.Count, 1, $"tapping {(tapping ? "on" : "off")}: the charge goes on the gear");
|
||||
}
|
||||
}
|
||||
|
||||
private static void EternalRetriesSoon()
|
||||
{
|
||||
using var rig = new Rig(tapping: false, new (uint, int?)[] { (ChargeA, null) }, stoneName: EternalCharge, maceMana: 0);
|
||||
|
|
@ -635,12 +651,23 @@ internal static class ManaStoneChoiceTests
|
|||
rig.Chat("The Mana Stone gives 2,000 points of mana to the following items: Khanda-handled Mace.\nYour items are fully charged.");
|
||||
rig.Run(60_000);
|
||||
Check.Eq(rig.OnPlayer.Count, 2, "fully charged: no stone for a while though the mace still reads 0%");
|
||||
rig.Run(70_000);
|
||||
Check.Eq(rig.OnPlayer.Count, 3, "after the hold the stale read is tried once more");
|
||||
// R-20261201-171624-0bcf: the stale read asked for a stone every 2 minutes, each "fully charged".
|
||||
rig.Run(600_000);
|
||||
Check.Eq(rig.OnPlayer.Count, 2, "after the hold too: the server's 'fully charged' stands while the read is the same stale one");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("fullPerServer=1")), "the gear check says so");
|
||||
// A newer appraisal is real again: the mace really at 10%.
|
||||
FakeHost.Ints[(Mace, CurManaKey)] = 500;
|
||||
rig.Run(5000);
|
||||
Check.Eq(rig.OnPlayer.Count, 3, "a newer read (10%) refills");
|
||||
Check.Eq(rig.OnPlayer[2], StoneC, "with stone C");
|
||||
rig.Chat("You have no items equipped that need mana.");
|
||||
rig.Run(60_000);
|
||||
Check.Eq(rig.OnPlayer.Count, 3, "the server says nothing needs mana: held again, C kept");
|
||||
rig.Chat("The Mana Stone gives 1,000 points of mana to the following items: Khanda-handled Mace.\nYour items are fully charged.");
|
||||
rig.Run(600_000);
|
||||
Check.Eq(rig.OnPlayer.Count, 3, "full again: nothing more though the read says 10%");
|
||||
// The server's own word that the gear is low beats the kept read.
|
||||
FakeHost.Ints[(StoneA, CurManaKey)] = 2900; // stone A read again (a newer read): charged
|
||||
rig.Chat("Your Khanda-handled Mace is low on Mana.");
|
||||
rig.Run(5000);
|
||||
Check.Eq(rig.OnPlayer.Count, 4, "'low on Mana': refilled whatever the kept read");
|
||||
}
|
||||
|
||||
private static void UnreadableStoneIdentified()
|
||||
|
|
|
|||
254
Tools/RynthCore.RynthAiHostTests/Tests/MetaCommandAuditTests.cs
Normal file
254
Tools/RynthCore.RynthAiHostTests/Tests/MetaCommandAuditTests.cs
Normal file
|
|
@ -0,0 +1,254 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Meta;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
using C = RynthCore.Plugin.RynthAi.LegacyUi.MetaConditionType;
|
||||
using A = RynthCore.Plugin.RynthAi.LegacyUi.MetaActionType;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The 2026-12-01 command audit, wave 2: /vt verbs and VTank options that were accepted but did
|
||||
// nothing, or the wrong thing. Each line runs as a meta's chat command.
|
||||
internal static class MetaCommandAuditTests
|
||||
{
|
||||
private const uint Player = 0x50000A71;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("meta action (12-01 audit 2): /vt settings load|save, /vt meta save, /vt loot save go to RynthAi's profile verbs", ProfileVerbs);
|
||||
r.Add("meta action (12-01 audit 2): VTank options with a RynthAi setting set it (LootOnlyRareCorpses, TargetSelectMethod, ...)", VtOptions);
|
||||
r.Add("ub opt / mt opt (12-01 audit 2): UtilityBelt and Mag-Tools option names with a RynthAi setting set it", UbMtOptions);
|
||||
r.Add("mt attack_melee (12-01 audit 2): melee mode first, then one attack on the selected or closest monster", MtAttackMelee);
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S = new() { IsMacroRunning = true, EnableMeta = true, CurrentState = "Default" };
|
||||
public readonly MetaManager M;
|
||||
public readonly List<string> Ra = new();
|
||||
|
||||
public Rig()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
M = new MetaManager(S, FakeHost.Create(), new PlayerVitalsCache());
|
||||
M.SetPlayerId(Player);
|
||||
M.SetRaCommandHandler(Ra.Add);
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="line"/> as a meta's chat command (one rule, one tick).</summary>
|
||||
public void Run(string line)
|
||||
{
|
||||
S.MetaRules = new List<MetaRule> { new() { State = S.CurrentState, Condition = C.Always, Action = A.ChatCommand, ActionData = line } };
|
||||
S.ForceStateReset = true;
|
||||
M.Think();
|
||||
}
|
||||
}
|
||||
|
||||
private static void ProfileVerbs()
|
||||
{
|
||||
var rig = new Rig();
|
||||
// VTank's shared settings profiles are RynthAi's character profiles (it has no other kind).
|
||||
rig.Run("/vt settings load Hunting");
|
||||
Check.True(rig.Ra.Contains("/ra settings loadchar Hunting"), "/vt settings load -> /ra settings loadchar");
|
||||
rig.Run("/vt settings save After Buffs");
|
||||
Check.True(rig.Ra.Contains("/ra settings savechar After Buffs"), "/vt settings save -> /ra settings savechar, spaces kept");
|
||||
rig.Run("/vt settings loadchar Banes");
|
||||
Check.True(rig.Ra.Contains("/ra settings loadchar Banes"), "loadchar as before");
|
||||
int before = rig.Ra.Count;
|
||||
rig.Run("/vt settings banana Hunting");
|
||||
Check.Eq(rig.Ra.Count, before, "another settings verb is still ignored");
|
||||
|
||||
rig.Run("/vt meta save My Meta");
|
||||
Check.True(rig.Ra.Contains("/ra meta saveas My Meta"), "/vt meta save -> /ra meta saveas");
|
||||
|
||||
rig.S.CurrentLootPath = @"X:\RynthAi\LootProfiles\Main Loot.utl";
|
||||
rig.Run("/vt loot save Copy Of Loot");
|
||||
Check.True(rig.Ra.Contains("/ra loot saveas Copy Of Loot"), "/vt loot save -> /ra loot saveas (a copy, then looted with)");
|
||||
before = rig.Ra.Count;
|
||||
rig.Run("/vt loot save main loot");
|
||||
Check.Eq(rig.Ra.Count, before, "the loot profile in use's own name: nothing to copy");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Main Loot.utl is the loot profile in use")), "said (in the log, a meta's line)");
|
||||
rig.Run("/vt loot save Main Loot.utl");
|
||||
Check.Eq(rig.Ra.Count, before, "with the extension too");
|
||||
|
||||
Check.True(MetaManager.VtUsageFor("/vt meta").Contains("load|save"), "the usage names save");
|
||||
}
|
||||
|
||||
private static void VtOptions()
|
||||
{
|
||||
var rig = new Rig();
|
||||
var s = rig.S;
|
||||
s.MineOnly = false;
|
||||
rig.Run("/vt opt set LootOnlyRareCorpses true");
|
||||
Check.True(s.LootOnlyRareCorpses, "LootOnlyRareCorpses is RynthAi's Loot Only Rare Corpses");
|
||||
Check.False(s.MineOnly, "not MineOnly, which nothing reads");
|
||||
rig.Run("/vt opt set lootonlyrarecorpses false");
|
||||
Check.False(s.LootOnlyRareCorpses, "and off");
|
||||
|
||||
rig.Run("/vt opt set CorpeApproachRange-Min 0.0125");
|
||||
Check.Near(s.CorpseApproachRangeMin, 3, 1e-3, "VTank's misspelt CorpeApproachRange-Min: landblock units to 3 yd");
|
||||
rig.Run("/vt opt set BlacklistMonsterAttemptCount 6");
|
||||
Check.Eq(s.BlacklistAttempts, 6, "BlacklistMonsterAttemptCount -> BlacklistAttempts");
|
||||
s.ManaTapMacroOff = true;
|
||||
rig.Run("/vt opt set ManaChargesWhenOff false");
|
||||
Check.False(s.ManaTapMacroOff, "ManaChargesWhenOff -> mana tapping with the macro off");
|
||||
rig.Run("/vt opt set ManaTankMinimumMana 4000");
|
||||
Check.Eq(s.ManaTapMinMana, 4000, "ManaTankMinimumMana -> ManaTapMinMana");
|
||||
rig.Run("/vt opt set Recharge-Helper-Stam 35");
|
||||
Check.Eq(s.RestamOthersAt, 35, "Recharge-Helper-Stam -> Re-stam Others");
|
||||
rig.Run("/vt opt set Recharge-Helper-Mana 25");
|
||||
Check.Eq(s.InfuseOthersAt, 25, "Recharge-Helper-Mana -> Infuse Others");
|
||||
rig.Run("/vt opt set Recharge-Helper-HitP 45");
|
||||
Check.Eq(s.HealOthersAt, 45, "Recharge-Helper-HitP -> Heal Others");
|
||||
|
||||
// TargetSelectMethod: 1 range = Closest, 2 angle = Least turning, 3 both: no RynthAi mode, kept.
|
||||
s.TargetSelection = 0;
|
||||
rig.Run("/vt opt set TargetSelectMethod 1");
|
||||
Check.Eq(s.TargetSelection, 1, "1 (range) -> Closest");
|
||||
rig.Run("/vt opt set TargetSelectMethod 2");
|
||||
Check.Eq(s.TargetSelection, 3, "2 (angle) -> Least turning");
|
||||
rig.Run("/vt opt set TargetSelectMethod 3");
|
||||
Check.Eq(s.TargetSelection, 3, "3 (both) leaves Targeting as it is");
|
||||
s.TargetSelection = 0;
|
||||
FakeHost.Chat.Clear();
|
||||
rig.M.TryHandleVtCommand("/vt opt get TargetSelectMethod");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("TargetSelectMethod = 3")), "with no VTank mode in use it reads back as set");
|
||||
|
||||
// DebuffEachFirst: 3 All = debuff every monster first, 1 One = off, 2 Priority: kept.
|
||||
rig.Run("/vt opt set DebuffEachFirst 3");
|
||||
Check.True(s.DebuffAllBeforeAttacking, "3 (all) -> Debuff every monster in range before attacking");
|
||||
rig.Run("/vt opt set DebuffEachFirst 1");
|
||||
Check.False(s.DebuffAllBeforeAttacking, "1 (one) -> off");
|
||||
rig.Run("/vt opt set DebuffEachFirst 2");
|
||||
Check.False(s.DebuffAllBeforeAttacking, "2 (priority) leaves it as it is");
|
||||
|
||||
// One that stays only stored: NavFarStopRange (VTank stops nav; RynthAi detours back instead).
|
||||
float offTrack = s.NavOffTrackYards;
|
||||
rig.Run("/vt opt set NavFarStopRange 0.5");
|
||||
Check.Eq(s.NavOffTrackYards, offTrack, "NavFarStopRange doesn't touch the off-track detour distance");
|
||||
}
|
||||
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
private static void UbMtOptions()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var p = new RynthAiPlugin();
|
||||
var s = new LegacyUiSettings();
|
||||
var host = FakeHost.Create(playerId: Player);
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
|
||||
void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(p, v);
|
||||
Set("_dashboard", dash);
|
||||
var m = new MetaManager(s, host, new PlayerVitalsCache());
|
||||
Set("_metaManager", m);
|
||||
Set("_playerId", Player);
|
||||
Set("_initialized", true);
|
||||
Set("_loginComplete", true);
|
||||
bool Ub(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleUbCommand", Any)!.Invoke(p, new object[] { line })!;
|
||||
bool Mt(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMtCommand", Any)!.Invoke(p, new object[] { line })!;
|
||||
|
||||
s.EnableAutocram = false;
|
||||
Check.True(Ub("/ub opt set InventoryManager.AutoCram true"), "/ub opt set InventoryManager.AutoCram");
|
||||
Check.True(s.EnableAutocram, "-> RynthAi's autocram");
|
||||
s.EnableAutostack = true;
|
||||
Ub("/ub opt toggle InventoryManager.AutoStack");
|
||||
Check.False(s.EnableAutostack, "/ub opt toggle takes UtilityBelt's name too");
|
||||
|
||||
s.AutoVendorEnabled = false;
|
||||
Mt("/mt opt set AutoBuySell.Enabled true");
|
||||
Check.True(s.AutoVendorEnabled, "Mag-Tools AutoBuySell.Enabled -> AutoVendor");
|
||||
s.LootChestsMacroOff = true;
|
||||
Mt("/mt opt set Looting.AutoLootChests false");
|
||||
Check.False(s.LootChestsMacroOff, "Looting.AutoLootChests -> Pickup with macro off");
|
||||
s.LootOwnCorpse = true;
|
||||
Mt("/mt opt set Looting.AutoLootMyCorpse false");
|
||||
Check.False(s.LootOwnCorpse, "Looting.AutoLootMyCorpse -> Loot own corpse");
|
||||
Mt("/mt opt set InventoryManagement.AetheriaRevealer true");
|
||||
Check.True(s.UnboxAetheriaWhenIdle, "AetheriaRevealer -> Unbox Aetheria When Idle");
|
||||
s.AutoConfirmCraft = false;
|
||||
s.AutoConfirmCraftPercent = 80;
|
||||
Mt("/mt opt set Tinkering.AutoClickYes true");
|
||||
Check.True(s.AutoConfirmCraft && s.AutoConfirmCraftPercent == 100, "Tinkering.AutoClickYes -> Auto-confirm crafting at 100%");
|
||||
FakeHost.Chat.Clear();
|
||||
Mt("/mt opt get Tinkering.AutoClickYes");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("Tinkering.AutoClickYes = 1")), "reads back");
|
||||
Mt("/mt opt set Tinkering.AutoClickYes false");
|
||||
Check.False(s.AutoConfirmCraft, "and off");
|
||||
|
||||
// Store-only names are still kept for metas, and say so.
|
||||
FakeHost.Chat.Clear();
|
||||
Mt("/mt opt set InventoryManagement.KeyRinger true");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("kept only for metas to read")), "KeyRinger: no RynthAi setting, kept");
|
||||
}
|
||||
|
||||
private const uint Lb = 0xA9B40000, NearMob = 0x80000771, FarMob = 0x80000772;
|
||||
|
||||
private static void MtAttackMelee()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = FakeHost.CombatModeCalls = FakeHost.AttackSendCalls = true;
|
||||
FakeHost.Names[Player] = "Attacker";
|
||||
FakeHost.PlayerIdValue = Player;
|
||||
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
foreach (var (id, name, y) in new[] { (NearMob, "Drudge Skulker", 98f), (FarMob, "Drudge Ravener", 110f) })
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Positions[id] = (Lb | 0x1C, 96f, y, 0f);
|
||||
FakeHost.ItemTypes[id] = 0x10;
|
||||
}
|
||||
var p = new RynthAiPlugin();
|
||||
var s = new LegacyUiSettings { MeleeAttackHeight = 2, MeleeAttackPower = 60 };
|
||||
var host = FakeHost.Create(playerId: Player);
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
|
||||
void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(p, v);
|
||||
Set("_dashboard", dash);
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
cache.Tick();
|
||||
foreach (uint id in new[] { NearMob, FarMob }) _ = cache[unchecked((int)id)];
|
||||
Set("_objectCache", cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_initialized", true);
|
||||
Set("_loginComplete", true);
|
||||
bool Mt(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMtCommand", Any)!.Invoke(p, new object[] { line })!;
|
||||
|
||||
// Peace mode: the first call goes to melee mode and attacks nothing.
|
||||
FakeHost.CombatModeValue = 1;
|
||||
Check.True(Mt("/mt attack_melee"), "/mt attack_melee is handled (it was unknown)");
|
||||
Check.True(FakeHost.CombatModeRequests.Contains(2), "out of melee mode: melee mode first");
|
||||
Check.Eq(FakeHost.AttackCalls.Count, 0, "no attack yet");
|
||||
|
||||
// Melee mode, nothing selected: the closest monster, once, at the settings' height and power.
|
||||
FakeHost.CombatModeValue = 2;
|
||||
Mt("/mt attack_melee");
|
||||
Check.Eq(FakeHost.AttackCalls.Count, 1, "one attack");
|
||||
Check.Eq(FakeHost.AttackCalls[0].Target, NearMob, "on the closest monster");
|
||||
Check.Eq(FakeHost.AttackCalls[0].Height, 1, "High (RynthAi 2) is AC's height 1");
|
||||
Check.Near(FakeHost.AttackCalls[0].Power, 0.6, 1e-3, "at the melee attack power");
|
||||
|
||||
// A selected monster is attacked, unless "closest" is given.
|
||||
FakeHost.SelectedItem = FarMob;
|
||||
Mt("/mt attack_melee");
|
||||
Check.Eq(FakeHost.AttackCalls[^1].Target, FarMob, "the selected monster");
|
||||
Mt("/mt attack_melee closest");
|
||||
Check.Eq(FakeHost.AttackCalls[^1].Target, NearMob, "closest: the closest one, whatever is selected");
|
||||
|
||||
Check.True(Mt("/mt attack_melee banana"), "a wrong word is handled");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("Usage: /mt attack_melee")), "with the usage");
|
||||
}
|
||||
}
|
||||
343
Tools/RynthCore.RynthAiHostTests/Tests/MetaEmbedNavTests.cs
Normal file
343
Tools/RynthCore.RynthAiHostTests/Tests/MetaEmbedNavTests.cs
Normal file
|
|
@ -0,0 +1,343 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Meta;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-11-30 hot fix: embedded nav routes in metas only loaded a nav file; they should embed the
|
||||
// loaded route, so the meta still works with the .nav file deleted. The Meta panel's route picker stored a NavProfiles file
|
||||
// name and the meta was saved without the route, so the meta read the file at run time; and in a meta
|
||||
// with any NAVDATA block, a rule naming a route without one was blanked on load (no route at all).
|
||||
// Scratch folders only: the meta's NavProfiles is redirected through MetaSaver.NavFolder.
|
||||
internal static class MetaEmbedNavTests
|
||||
{
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private static readonly DateTime T0 = new(2026, 11, 30, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("meta embed nav: a route picked in the Meta panel is written inside the .af and runs with its .nav deleted", PickEmbeds);
|
||||
r.Add("meta embed nav: re-picking takes the file's newer route; other edits keep the meta's copy", RepickRefreshes);
|
||||
r.Add("meta embed nav: an older .af naming a NavProfiles route gets it written in on load (other blocks kept)", LoadEmbedsOldMeta);
|
||||
r.Add("meta embed nav: a rule naming a route with no NAVDATA block keeps its name on load (was blanked)", ParserKeepsFileRef);
|
||||
r.Add("meta embed nav: Patrol, Camp and [None] with no file, and an empty .nav, are not embedded", PseudoRoutesNotEmbedded);
|
||||
r.Add("meta embed loaded: a recorded route never saved goes in as 'Route N' and runs with no file; the nav is the meta's now", EmbedLoadedUnsaved);
|
||||
r.Add("meta embed loaded: a loaded .nav goes in under its own name, the loaded copy (not the file), in a DoAll too", EmbedLoadedFileRoute);
|
||||
r.Add("meta embed loaded: a route a feature built (patrol, hunt) isn't embedded; the snapshot and chat say why", EmbedLoadedRefusesGenerated);
|
||||
r.Add("meta embed loaded: the generated mark survives a hot-reload resume", MadeBySurvivesResume);
|
||||
}
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static string Dir(string name)
|
||||
{
|
||||
string dir = Path.Combine(Program.TempRoot, "meta-embednav", name);
|
||||
if (Directory.Exists(dir))
|
||||
{
|
||||
foreach (string f in Directory.GetFiles(dir, "*", SearchOption.AllDirectories)) File.SetAttributes(f, FileAttributes.Normal);
|
||||
Directory.Delete(dir, recursive: true);
|
||||
}
|
||||
Directory.CreateDirectory(Path.Combine(dir, "NavProfiles"));
|
||||
return dir;
|
||||
}
|
||||
|
||||
private static string NavDir(string dir) => Path.Combine(dir, "NavProfiles");
|
||||
|
||||
private static void WriteNav(string dir, string name, int points)
|
||||
{
|
||||
var lines = new List<string> { "uTank2 NAV 1.2", "1", points.ToString() };
|
||||
for (int i = 0; i < points; i++)
|
||||
lines.AddRange(new[] { "0", (30 + i).ToString(), (40 + i).ToString(), "0", "0" });
|
||||
File.WriteAllLines(Path.Combine(NavDir(dir), name + ".nav"), lines);
|
||||
}
|
||||
|
||||
private static LegacyMetaUi MetaUi(LegacyDashboardRenderer dash) =>
|
||||
(LegacyMetaUi)typeof(LegacyDashboardRenderer).GetField("_metaUi", Any)!.GetValue(dash)!;
|
||||
|
||||
private static MetaSaver Saver(LegacyDashboardRenderer dash) =>
|
||||
(MetaSaver)typeof(LegacyDashboardRenderer).GetField("_metaSaver", Any)!.GetValue(dash)!;
|
||||
|
||||
/// <summary>A dashboard whose meta NavProfiles is <paramref name="dir"/>\NavProfiles, with <paramref name="path"/> loaded.</summary>
|
||||
private static LegacyDashboardRenderer Dash(string dir, string path)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
DataWriteGuard.Reset();
|
||||
var dash = new LegacyDashboardRenderer(FakeHost.Create());
|
||||
Saver(dash).NavFolder = () => NavDir(dir);
|
||||
var ui = MetaUi(dash);
|
||||
Check.True(ui.LoadMacroFile(path), "loads: " + ui.LastLoadStatus);
|
||||
return dash;
|
||||
}
|
||||
|
||||
private static string RuleJson(int action, string data) =>
|
||||
"{\"State\":\"Default\",\"Condition\":" + (int)MetaConditionType.Always + ",\"ConditionData\":\"\",\"Action\":" + action +
|
||||
",\"ActionData\":\"" + data + "\",\"Children\":[],\"ActionChildren\":[],\"Enabled\":true,\"Name\":\"\",\"LastFiredMs\":0}";
|
||||
|
||||
private static string EmbedNavJson(string route) => RuleJson((int)MetaActionType.EmbeddedNavRoute, route);
|
||||
|
||||
private static void Send(LegacyDashboardRenderer dash, string op, int index, string rule)
|
||||
{
|
||||
dash.HandleMetaCommand("{\"Op\":\"" + op + "\",\"Index\":" + index + ",\"Value\":\"\",\"Path\":\"\",\"Text\":\"\",\"Rule\":" + rule + "}");
|
||||
dash.DrainMetaCommands();
|
||||
}
|
||||
|
||||
private static int Points(IDictionary<string, List<string>> navs, string name) =>
|
||||
navs.TryGetValue(name, out var lines) ? NavRouteParser.LoadFromLines(lines).Points.Count : -1;
|
||||
|
||||
/// <summary>Runs <paramref name="settings"/>' meta for one tick the way the bot does, NavProfiles in <paramref name="navFolder"/>.</summary>
|
||||
private static void RunMeta(LegacyUiSettings settings, string navFolder)
|
||||
{
|
||||
FakeHost.PlayerPose = (0xA9B4001Cu, 96f, 96f, 0f);
|
||||
settings.IsMacroRunning = true;
|
||||
settings.EnableMeta = true;
|
||||
settings.CurrentState = "Default";
|
||||
settings.ForceStateReset = true;
|
||||
var m = new MetaManager(settings, FakeHost.Create(), new PlayerVitalsCache()) { Clock = () => T0, NavFolder = navFolder };
|
||||
m.Think();
|
||||
}
|
||||
|
||||
// ── tests ────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void PickEmbeds()
|
||||
{
|
||||
string dir = Dir("pick");
|
||||
string path = Path.Combine(dir, "farm.af");
|
||||
File.WriteAllText(path, "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tChat {/say one}\n~~ }\n");
|
||||
WriteNav(dir, "Hunt", 3);
|
||||
var dash = Dash(dir, path);
|
||||
|
||||
// The Meta panel picks "Hunt" (a NavProfiles file) for rule 1's Embedded Nav Route.
|
||||
Send(dash, "update_rule", 0, EmbedNavJson("Hunt"));
|
||||
Check.Eq(Points(dash.Settings.EmbeddedNavs, "Hunt"), 3, "the route is in the meta in memory");
|
||||
string text = File.ReadAllText(path);
|
||||
Check.True(text.Contains("NAVDATA: Hunt "), "the .af carries the route: " + text);
|
||||
|
||||
// The file goes; the meta still has it.
|
||||
File.Delete(Path.Combine(NavDir(dir), "Hunt.nav"));
|
||||
var back = AfFileParser.Load(path);
|
||||
Check.Eq(back.Rules[0].ActionData, "Hunt", "the rule still names it");
|
||||
Check.Eq(Points(back.EmbeddedNavs, "Hunt"), 3, "the route reads back from the .af with its points");
|
||||
|
||||
var s = new LegacyUiSettings();
|
||||
s.MetaRules = back.Rules;
|
||||
foreach (var kv in back.EmbeddedNavs) s.EmbeddedNavs[kv.Key] = kv.Value;
|
||||
FakeHost.Reset();
|
||||
RunMeta(s, NavDir(dir));
|
||||
Check.Eq(s.CurrentRoute.Points.Count, 3, "the meta runs the route with no .nav on disk");
|
||||
Check.Eq(s.CurrentNavPath, "<embedded:Hunt>", "...from inside the meta");
|
||||
Check.False(FakeHost.Chat.Exists(c => c.Contains("Route missing")), "no 'Route missing'");
|
||||
}
|
||||
|
||||
private static void RepickRefreshes()
|
||||
{
|
||||
string dir = Dir("repick");
|
||||
string path = Path.Combine(dir, "farm.af");
|
||||
File.WriteAllText(path, "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tChat {/say one}\n~~ }\n");
|
||||
WriteNav(dir, "Hunt", 3);
|
||||
var dash = Dash(dir, path);
|
||||
Send(dash, "update_rule", 0, EmbedNavJson("Hunt"));
|
||||
Check.Eq(Points(dash.Settings.EmbeddedNavs, "Hunt"), 3, "first pick: 3 points");
|
||||
|
||||
// The route is re-recorded on disk. An edit that keeps the route (the rule's name here) keeps the meta's copy.
|
||||
WriteNav(dir, "Hunt", 5);
|
||||
Send(dash, "update_rule", 0, EmbedNavJson("Hunt").Replace("\"Name\":\"\"", "\"Name\":\"go hunt\""));
|
||||
Check.Eq(Points(dash.Settings.EmbeddedNavs, "Hunt"), 3, "an edit that doesn't change the route keeps the embedded copy");
|
||||
|
||||
// Picking it again (another action, then the route) takes the file as it is now.
|
||||
Send(dash, "update_rule", 0, RuleJson((int)MetaActionType.ChatCommand, "/say two"));
|
||||
Send(dash, "update_rule", 0, EmbedNavJson("Hunt"));
|
||||
Check.Eq(Points(dash.Settings.EmbeddedNavs, "Hunt"), 5, "a fresh pick copies the newer file");
|
||||
Check.Eq(Points(AfFileParser.Load(path).EmbeddedNavs, "Hunt"), 5, "...and the .af has it");
|
||||
|
||||
// A new rule picking a route copies it too.
|
||||
WriteNav(dir, "Bank Run", 2);
|
||||
Send(dash, "add_rule", -1, EmbedNavJson("Bank Run"));
|
||||
Check.Eq(Points(AfFileParser.Load(path).EmbeddedNavs, "Bank Run"), 2, "add_rule: a route name with a space is embedded and reads back");
|
||||
}
|
||||
|
||||
private static void LoadEmbedsOldMeta()
|
||||
{
|
||||
string dir = Dir("load");
|
||||
string path = Path.Combine(dir, "old.af");
|
||||
// Written before the fix: rule 1 names a NavProfiles route, rule 2 a route the meta carries.
|
||||
File.WriteAllText(path,
|
||||
"STATE: {Default} ~~ {\n" +
|
||||
"\tIF:\tAlways\n\t\tDO:\tEmbedNav Hunt {[none]}\n" +
|
||||
"\tIF:\tNever\n\t\tDO:\tEmbedNav Other {[none]}\n" +
|
||||
"~~ }\n" +
|
||||
"NAVDATA: Other 8 ~~ {\nuTank2 NAV 1.2\n1\n1\n0\n10\n20\n0\n0\n~~ }\n");
|
||||
WriteNav(dir, "Hunt", 4);
|
||||
var dash = Dash(dir, path);
|
||||
Check.Eq(dash.Settings.MetaRules[0].ActionData, "Hunt", "the rule keeps its route name");
|
||||
Check.Eq(Points(dash.Settings.EmbeddedNavs, "Hunt"), 4, "the file route is in the meta after the load");
|
||||
|
||||
File.Delete(Path.Combine(NavDir(dir), "Hunt.nav"));
|
||||
var back = AfFileParser.Load(path);
|
||||
Check.Eq(Points(back.EmbeddedNavs, "Hunt"), 4, "the load wrote it into the .af");
|
||||
Check.Eq(Points(back.EmbeddedNavs, "Other"), 1, "the route it already carried is kept");
|
||||
Check.Eq(back.Rules.Count, 2, "both rules kept");
|
||||
|
||||
// A read-only .af isn't written by a load.
|
||||
string ro = Path.Combine(dir, "readonly.af");
|
||||
File.WriteAllText(ro, "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tEmbedNav Hunt2 {[none]}\n~~ }\n");
|
||||
WriteNav(dir, "Hunt2", 2);
|
||||
File.SetAttributes(ro, FileAttributes.ReadOnly);
|
||||
var dash2 = Dash(dir, ro);
|
||||
Check.Eq(Points(dash2.Settings.EmbeddedNavs, "Hunt2"), 2, "read-only: the route is still embedded in memory");
|
||||
Check.False(File.ReadAllText(ro).Contains("NAVDATA"), "read-only: the file isn't written on load");
|
||||
File.SetAttributes(ro, FileAttributes.Normal);
|
||||
}
|
||||
|
||||
private static void ParserKeepsFileRef()
|
||||
{
|
||||
var m = AfFileParser.LoadFromText(
|
||||
"STATE: {Default} ~~ {\n" +
|
||||
"\tIF:\tAlways\n\t\tDO:\tDoAll\n\t\t\t\tEmbedNav Hunt {[none]}\n\t\t\t\tEmbedNav Empty {[none]}\n" +
|
||||
"\tIF:\tNever\n\t\tDO:\tEmbedNav Other {[none]}\n" +
|
||||
"~~ }\n" +
|
||||
"NAVDATA: Other 8 ~~ {\nuTank2 NAV 1.2\n1\n1\n0\n10\n20\n0\n0\n~~ }\n" +
|
||||
"NAVDATA: Empty 3 ~~ {\nuTank2 NAV 1.2\n1\n0\n~~ }\n");
|
||||
var doAll = m.Rules[0].ActionChildren;
|
||||
Check.Eq(doAll[0].ActionData, "Hunt", "a route with no block keeps its name (a NavProfiles route)");
|
||||
Check.Eq(doAll[1].ActionData, "", "a route whose block is empty is still cleared");
|
||||
Check.Eq(m.Rules[1].ActionData, "Other", "an embedded route is untouched");
|
||||
}
|
||||
|
||||
// ── "Embed loaded" (the Meta panel's button) ─────────────────────────────
|
||||
|
||||
private static NavRouteParser Route(int points, string madeBy = "")
|
||||
{
|
||||
var route = new NavRouteParser { RouteType = NavRouteType.Circular, MadeBy = madeBy };
|
||||
for (int i = 0; i < points; i++)
|
||||
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 40 + i, EW = 30 + i, Z = 0 });
|
||||
return route;
|
||||
}
|
||||
|
||||
/// <summary>The snapshot's loadedRoute, as the engine panel reads it.</summary>
|
||||
private static (string Name, int Points, string Note) Loaded(LegacyDashboardRenderer dash)
|
||||
{
|
||||
using var doc = System.Text.Json.JsonDocument.Parse(dash.BuildMetaJson());
|
||||
var e = doc.RootElement.GetProperty("loadedRoute");
|
||||
return (e.GetProperty("name").GetString() ?? "", e.GetProperty("points").GetInt32(), e.GetProperty("note").GetString() ?? "");
|
||||
}
|
||||
|
||||
private static string Marked(string name) => name + MetaNavEmbedding.LoadedMarker;
|
||||
|
||||
private static void EmbedLoadedUnsaved()
|
||||
{
|
||||
string dir = Dir("loaded-unsaved");
|
||||
string path = Path.Combine(dir, "farm.af");
|
||||
File.WriteAllText(path, "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tChat {/say one}\n~~ }\n");
|
||||
WriteNav(dir, "Route 1", 2); // NavProfiles has a "Route 1": the new name skips it
|
||||
var dash = Dash(dir, path);
|
||||
dash.Settings.CurrentRoute = Route(4); // recorded in the nav editor, never saved
|
||||
dash.Settings.CurrentNavPath = string.Empty;
|
||||
|
||||
var loaded = Loaded(dash);
|
||||
Check.Eq(loaded.Note, "", "embeddable");
|
||||
Check.Eq(loaded.Name, "Route 2", "a new name no file or meta route has");
|
||||
Check.Eq(loaded.Points, 4, "its points");
|
||||
|
||||
Send(dash, "update_rule", 0, EmbedNavJson(Marked(loaded.Name)));
|
||||
Check.Eq(dash.Settings.MetaRules[0].ActionData, "Route 2", "the rule keeps the plain name (the marker is gone)");
|
||||
Check.Eq(Points(dash.Settings.EmbeddedNavs, "Route 2"), 4, "the route in memory went in");
|
||||
Check.Eq(dash.Settings.CurrentNavPath, "<embedded:Route 2>", "the loaded route is the meta's route now");
|
||||
Check.Eq(Loaded(dash).Name, "Route 2", "the button now names that route (no second copy)");
|
||||
|
||||
var back = AfFileParser.Load(path);
|
||||
Check.True(File.ReadAllText(path).Contains("NAVDATA: Route 2 "), "written into the .af");
|
||||
Check.False(File.ReadAllText(path).Contains(MetaNavEmbedding.LoadedMarker), "no marker in the file");
|
||||
var s = new LegacyUiSettings();
|
||||
s.MetaRules = back.Rules;
|
||||
foreach (var kv in back.EmbeddedNavs) s.EmbeddedNavs[kv.Key] = kv.Value;
|
||||
FakeHost.Reset();
|
||||
RunMeta(s, NavDir(dir));
|
||||
Check.Eq(s.CurrentRoute.Points.Count, 4, "the meta runs it; it never had a file");
|
||||
}
|
||||
|
||||
private static void EmbedLoadedFileRoute()
|
||||
{
|
||||
string dir = Dir("loaded-file");
|
||||
string path = Path.Combine(dir, "farm.af");
|
||||
File.WriteAllText(path, "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tChat {/say one}\n~~ }\n");
|
||||
WriteNav(dir, "Hunt", 3);
|
||||
var dash = Dash(dir, path);
|
||||
string navPath = Path.Combine(NavDir(dir), "Hunt.nav");
|
||||
dash.Settings.CurrentNavPath = navPath;
|
||||
dash.Settings.CurrentRoute = Route(6); // the loaded copy, edited since the file was written
|
||||
|
||||
var loaded = Loaded(dash);
|
||||
Check.Eq(loaded.Name, "Hunt", "a .nav's own name");
|
||||
// Inside a DoAll, as a second step.
|
||||
string doAll = "{\"State\":\"Default\",\"Condition\":" + (int)MetaConditionType.Always + ",\"ConditionData\":\"\",\"Action\":" + (int)MetaActionType.All +
|
||||
",\"ActionData\":\"\",\"Children\":[],\"ActionChildren\":[" + RuleJson((int)MetaActionType.ChatCommand, "/say go") + "," + EmbedNavJson(Marked("Hunt")) +
|
||||
"],\"Enabled\":true,\"Name\":\"\",\"LastFiredMs\":0}";
|
||||
Send(dash, "update_rule", 0, doAll);
|
||||
Check.Eq(dash.Settings.MetaRules[0].ActionChildren[1].ActionData, "Hunt", "the DoAll step keeps the plain name");
|
||||
Check.Eq(Points(dash.Settings.EmbeddedNavs, "Hunt"), 6, "the loaded copy went in, not the file's 3 points");
|
||||
Check.Eq(dash.Settings.CurrentNavPath, navPath, "a file route stays the file's");
|
||||
Check.Eq(Points(AfFileParser.Load(path).EmbeddedNavs, "Hunt"), 6, "...and the .af has it");
|
||||
}
|
||||
|
||||
private static void EmbedLoadedRefusesGenerated()
|
||||
{
|
||||
string dir = Dir("loaded-generated");
|
||||
string path = Path.Combine(dir, "farm.af");
|
||||
File.WriteAllText(path, "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tChat {/say one}\n~~ }\n");
|
||||
var dash = Dash(dir, path);
|
||||
|
||||
dash.Settings.CurrentRoute = new NavRouteParser();
|
||||
dash.Settings.CurrentNavPath = string.Empty;
|
||||
Check.True(Loaded(dash).Note.Contains("No nav route"), "nothing loaded: " + Loaded(dash).Note);
|
||||
|
||||
// /ra dunnav leaves the old file path while its route runs: the mark is what counts.
|
||||
dash.Settings.CurrentNavPath = Path.Combine(NavDir(dir), "Hunt.nav");
|
||||
dash.Settings.CurrentRoute = Route(9, "the dungeon patrol");
|
||||
var loaded = Loaded(dash);
|
||||
Check.True(loaded.Name == "" && loaded.Note.Contains("the dungeon patrol"), "the snapshot says why: " + loaded.Note);
|
||||
|
||||
Send(dash, "update_rule", 0, EmbedNavJson(Marked("Hunt")));
|
||||
Check.Eq(dash.Settings.EmbeddedNavs.Count, 0, "nothing embedded");
|
||||
Check.Eq(dash.Settings.MetaRules[0].ActionData, "Hunt", "the rule has the plain name, no marker");
|
||||
Check.True(FakeHost.Chat.Exists(c => c.Contains("wasn't embedded") && c.Contains("the dungeon patrol")), "chat says why");
|
||||
|
||||
dash.Settings.CurrentNavPath = "<navheading>";
|
||||
dash.Settings.CurrentRoute = Route(2);
|
||||
Check.True(Loaded(dash).Note.Length > 0, "a <navheading> route isn't a nav route");
|
||||
}
|
||||
|
||||
private static void MadeBySurvivesResume()
|
||||
{
|
||||
var s = new MetaResumeState { RouteLines = Route(3).ToLines(), RouteMadeBy = "the hunt", NavPath = "", State = "Default" };
|
||||
string text = MetaResumeStore.Serialize(s);
|
||||
Check.True(MetaResumeStore.TryParse(text, out MetaResumeState back), "reads back");
|
||||
Check.Eq(back.RouteMadeBy, "the hunt", "the mark is kept");
|
||||
}
|
||||
|
||||
private static void PseudoRoutesNotEmbedded()
|
||||
{
|
||||
string dir = Dir("pseudo");
|
||||
WriteNav(dir, "Blank", 0);
|
||||
var rules = new List<MetaRule>();
|
||||
foreach (string r in new[] { "Patrol", "Camp", "[None]", "Blank", "NotThere", "..\\farm" })
|
||||
rules.Add(new MetaRule { State = "Default", Condition = MetaConditionType.Always, Action = MetaActionType.EmbeddedNavRoute, ActionData = r });
|
||||
File.WriteAllLines(Path.Combine(dir, "farm.nav"), new[] { "uTank2 NAV 1.2", "1", "1", "0", "1", "2", "0", "0" });
|
||||
var navs = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
|
||||
var added = MetaNavEmbedding.EmbedMissing(rules, navs, NavDir(dir));
|
||||
Check.Eq(added.Count, 0, "nothing embedded: " + string.Join(", ", added));
|
||||
Check.Eq(navs.Count, 0, "no routes");
|
||||
|
||||
// A Patrol.nav that exists is a real route (MetaManager runs it): that one is embedded.
|
||||
WriteNav(dir, "Patrol", 2);
|
||||
added = MetaNavEmbedding.EmbedMissing(rules, navs, NavDir(dir));
|
||||
Check.Eq(string.Join(",", added), "Patrol", "a real Patrol.nav is embedded");
|
||||
}
|
||||
}
|
||||
|
|
@ -46,6 +46,7 @@ internal static class MetaTests
|
|||
r.Add("meta: need-to-buff with no buff manager, unknown condition types", NeedToBuffAndUnknown);
|
||||
r.Add("meta action: chat commands, /ra, /vt and /mt", ChatCommands);
|
||||
r.Add("meta action: the /vt verbs and options the metas use that were missing (2026-10-17)", VtPortedVerbs);
|
||||
r.Add("meta action (12-01 command audit): reverseroute true|false sets the direction, query says it; addnavjump; SwitchWandToDebuff leaves dispel items alone", VtCommandAudit);
|
||||
r.Add("meta action: SetMetaState, CallMetaState and ReturnFromCall", CallReturn);
|
||||
r.Add("meta action: All runs every child in order", AllAction);
|
||||
r.Add("meta action: embedded nav route", EmbeddedNav);
|
||||
|
|
@ -924,6 +925,43 @@ internal static class MetaTests
|
|||
Check.Eq(reversed.S.ActiveNavIndex, 2, "index mirrored");
|
||||
}
|
||||
|
||||
// 2026-12-01 command audit (every command a meta sends must work, or metas break): commands taken
|
||||
// but done wrong. reverseroute flipped on every call whatever its true/false; addnavjump wasn't known;
|
||||
// SwitchWandToDebuff switched dispel items on.
|
||||
private static void VtCommandAudit()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var rig = new Rig(FakeHost.Create(), Player);
|
||||
rig.S.CurrentRoute = NavRouteParser.LoadFromLines(NavLines(2,
|
||||
(0, 1, 1, NoTrailer), (0, 2, 2, NoTrailer), (0, 3, 3, NoTrailer)));
|
||||
rig.S.ActiveNavIndex = 0;
|
||||
RunAction(rig, A.ChatCommand, "/vt reverseroute true");
|
||||
Check.Near(rig.S.CurrentRoute.Points[0].EW, 3, 1e-9, "true: reversed");
|
||||
RunAction(rig, A.ChatCommand, "/vt reverseroute true");
|
||||
Check.Near(rig.S.CurrentRoute.Points[0].EW, 3, 1e-9, "true again (each state entry): still reversed, not flipped back");
|
||||
Check.True(rig.M.RouteReversed, "it knows it is reversed");
|
||||
RunAction(rig, A.ChatCommand, "/vt reverseroute false");
|
||||
Check.Near(rig.S.CurrentRoute.Points[0].EW, 1, 1e-9, "false: the file's own order");
|
||||
RunAction(rig, A.ChatCommand, "/vt reverseroute false");
|
||||
Check.Near(rig.S.CurrentRoute.Points[0].EW, 1, 1e-9, "false again: unchanged");
|
||||
RunAction(rig, A.ChatCommand, "/vt reverseroute");
|
||||
Check.Near(rig.S.CurrentRoute.Points[0].EW, 3, 1e-9, "no argument: the other way");
|
||||
Check.True(rig.M.TryHandleVtCommand("/vt reverseroutequery"), "reverseroutequery is taken");
|
||||
rig.S.CurrentRoute = NavRouteParser.LoadFromLines(NavLines(2, (0, 5, 5, NoTrailer), (0, 6, 6, NoTrailer)));
|
||||
Check.False(rig.M.RouteReversed, "a route newly loaded is in its own order");
|
||||
RunAction(rig, A.ChatCommand, "/vt reverseroute false");
|
||||
Check.Near(rig.S.CurrentRoute.Points[0].EW, 5, 1e-9, "false on the new route: left as it is");
|
||||
|
||||
RunAction(rig, A.ChatCommand, "/vt addnavjump 270 true 650");
|
||||
Check.True(rig.Ra.Contains("/ra nav addjump 650 shift heading 270"), "/vt addnavjump -> /ra nav addjump with the heading: " + string.Join(" | ", rig.Ra));
|
||||
RunAction(rig, A.ChatCommand, "/vt addnavjump 90 false 2000");
|
||||
Check.True(rig.Ra.Contains("/ra nav addjump 1000 heading 90"), "held 1000 ms at most, no shift");
|
||||
|
||||
rig.S.UseDispelItems = false;
|
||||
RunAction(rig, A.ChatCommand, "/vt opt set SwitchWandToDebuff true");
|
||||
Check.False(rig.S.UseDispelItems, "SwitchWandToDebuff no longer turns dispel items on");
|
||||
}
|
||||
|
||||
// /vt verbs and options found in ub-IT and the metas on disk (universalremote.met, SASocietyTasks.met,
|
||||
// FoundryIzexi.met, DerethExploration (1).met) that RynthAi didn't handle.
|
||||
private static void VtPortedVerbs()
|
||||
|
|
|
|||
114
Tools/RynthCore.RynthAiHostTests/Tests/NamedLayoutRowTests.cs
Normal file
114
Tools/RynthCore.RynthAiHostTests/Tests/NamedLayoutRowTests.cs
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Named window layouts in the Loaded files drawer (2026-12-01, report R-20261127-150927-7938; named
|
||||
// layouts, in the files drawer). The engine keeps them
|
||||
// (/rc layout save|load|delete <name>); the LAYOUT row lists the folder, loads a pick, and its "..." saves,
|
||||
// saves as, renames and deletes. Here against a test folder, never the PC's real layouts.
|
||||
internal static class NamedLayoutRowTests
|
||||
{
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("named layouts (R-20261127 7938): the LAYOUT row lists the saved layouts, loads a pick and remembers it per character", ListAndLoad);
|
||||
r.Add("named layouts: Save, Save As (asks before replacing), Rename and Delete; names checked as the engine does", Verbs);
|
||||
}
|
||||
|
||||
private static (LegacyDashboardRenderer Dash, string Root, string Char) Rig(string name)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var host = FakeHost.Create();
|
||||
var dash = new LegacyDashboardRenderer(host);
|
||||
string root = Path.Combine(Program.TempRoot, "layouts-" + name);
|
||||
string saved = Path.Combine(root, "_saved");
|
||||
string charFolder = Path.Combine(root, "char");
|
||||
Directory.CreateDirectory(saved);
|
||||
Directory.CreateDirectory(charFolder);
|
||||
LegacyDashboardRenderer.LayoutsFolderForTests = saved;
|
||||
typeof(LegacyDashboardRenderer).GetField("_charFolder", Any)!.SetValue(dash, charFolder);
|
||||
return (dash, saved, charFolder);
|
||||
}
|
||||
|
||||
private static void Saved(string folder, string name)
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(folder, name));
|
||||
File.WriteAllText(Path.Combine(folder, name, "panel_state.txt"), "x\n");
|
||||
}
|
||||
|
||||
private static void ListAndLoad()
|
||||
{
|
||||
var (dash, saved, charFolder) = Rig("list");
|
||||
try
|
||||
{
|
||||
Saved(saved, "Raid");
|
||||
Saved(saved, "Mule");
|
||||
Directory.CreateDirectory(Path.Combine(saved, "_deleted", "Old"));
|
||||
Directory.CreateDirectory(Path.Combine(saved, "Empty")); // no panel_state.txt: not a layout
|
||||
dash.RefreshLayoutFiles();
|
||||
DashboardFiles f = dash.ReadDashboardFiles();
|
||||
Check.True(f.Layouts != null && f.Layouts.SequenceEqual(new[] { "Mule", "Raid" }), "listed, sorted, _deleted and empty folders left out: " + string.Join(",", f.Layouts ?? Array.Empty<string>()));
|
||||
Check.Eq(f.LayoutName, "None", "none in use yet");
|
||||
|
||||
dash.SelectProfileAtIndex(5, 1); // Raid
|
||||
Check.True(FakeHost.ChatCommands.Contains("/rc layout load Raid"), "a pick loads it through the engine: " + string.Join(" | ", FakeHost.ChatCommands));
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("Loading the layout 'Raid'")), "and says so");
|
||||
f = dash.ReadDashboardFiles();
|
||||
Check.True(f.LayoutName == "Raid" && f.LayoutIdx == 1, $"the row shows it ({f.LayoutName}, {f.LayoutIdx})");
|
||||
Check.Eq(File.ReadAllText(Path.Combine(charFolder, "layout.txt")).Trim(), "Raid", "remembered beside the character's profiles");
|
||||
|
||||
var again = new LegacyDashboardRenderer(FakeHost.Create());
|
||||
typeof(LegacyDashboardRenderer).GetField("_charFolder", Any)!.SetValue(again, charFolder);
|
||||
typeof(LegacyDashboardRenderer).GetMethod("ReadLayoutName", Any)!.Invoke(again, null);
|
||||
Check.Eq(again.LayoutName, "Raid", "read back at the next login");
|
||||
Check.True(again.ProfileInfo(ProfileKind.Layout).HasFile, "the menu has a layout in use");
|
||||
}
|
||||
finally { LegacyDashboardRenderer.LayoutsFolderForTests = null; }
|
||||
}
|
||||
|
||||
private static void Verbs()
|
||||
{
|
||||
var (dash, saved, _) = Rig("verbs");
|
||||
try
|
||||
{
|
||||
ProfileResult r = dash.LayoutAction(ProfileVerb.Save, null, false);
|
||||
Check.False(r.Ok, "Save with no layout in use: says to use Save As");
|
||||
r = dash.LayoutAction(ProfileVerb.SaveAs, "a/b", false);
|
||||
Check.True(!r.Ok && r.Text.Contains("can't be in a layout name"), "a bad name: said why: " + r.Text);
|
||||
Check.Eq(FakeHost.ChatCommands.Count, 0, "nothing sent for either");
|
||||
|
||||
r = dash.LayoutAction(ProfileVerb.SaveAs, "Raid Setup", false);
|
||||
Check.True(r.Ok && FakeHost.ChatCommands.Contains("/rc layout save Raid Setup"), "Save As: the engine saves it: " + r.Text);
|
||||
Check.Eq(dash.LayoutName, "Raid Setup", "and it is the one in use");
|
||||
Saved(saved, "Raid Setup"); // what the engine's save leaves
|
||||
|
||||
r = dash.LayoutAction(ProfileVerb.Save, null, false);
|
||||
Check.True(r.Ok && FakeHost.ChatCommands.Count(c => c == "/rc layout save Raid Setup") == 2, "Save: into the one in use");
|
||||
|
||||
Saved(saved, "Other");
|
||||
r = dash.LayoutAction(ProfileVerb.SaveAs, "Other", false);
|
||||
Check.True(!r.Ok && r.NeedsReplace, "Save As onto another layout asks first");
|
||||
r = dash.LayoutAction(ProfileVerb.SaveAs, "Other", true);
|
||||
Check.True(r.Ok && FakeHost.ChatCommands.Contains("/rc layout save Other"), "and replaces it on the yes");
|
||||
|
||||
r = dash.LayoutAction(ProfileVerb.Rename, "Raid", false);
|
||||
Check.True(r.Ok && Directory.Exists(Path.Combine(saved, "Raid")) && !Directory.Exists(Path.Combine(saved, "Other")),
|
||||
"Rename moves the layout's folder: " + r.Text);
|
||||
Check.Eq(dash.LayoutName, "Raid", "the renamed one is in use");
|
||||
r = dash.LayoutAction(ProfileVerb.Rename, "Raid Setup", false);
|
||||
Check.True(!r.Ok && r.Text.Contains("already"), "not onto another layout");
|
||||
|
||||
r = dash.LayoutAction(ProfileVerb.Delete, null, false);
|
||||
Check.True(r.Ok && FakeHost.ChatCommands.Contains("/rc layout delete Raid"), "Delete: the engine moves it aside: " + r.Text);
|
||||
Check.Eq(dash.LayoutName, string.Empty, "none in use after");
|
||||
}
|
||||
finally { LegacyDashboardRenderer.LayoutsFolderForTests = null; }
|
||||
}
|
||||
}
|
||||
|
|
@ -12,6 +12,107 @@ internal static class NavHeadingTests
|
|||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("navheading: RynthNav's corners become a Once route in nav coordinates, doorways kept", CornersToRoute);
|
||||
r.Add("navheading: a step that goes takes no detour", PlainStepGoes);
|
||||
r.Add("navheading: a goal in a rock or cliff face: the same heading, closer", GoalOffMapPulledBack);
|
||||
r.Add("navheading: no walkable ground ahead at any distance: the way round at 45°", OffMapAheadGoesRound);
|
||||
r.Add("navheading: no way to the goal (NoPath): closer, not a straight line", NoPathPulledBack);
|
||||
r.Add("navheading: nothing walkable on any goal: straight, saying why", NothingWalkable);
|
||||
r.Add("navheading: RynthNav not loaded: straight at once", RynthNavMissing);
|
||||
r.Add("navheading: a blocked step keeps to the side the last one took", KeepsSide);
|
||||
}
|
||||
|
||||
// A fake RynthNav for PlanHeading: `walkable(goal)` says Ok (a straight path to it), NoMesh, NoPath, or a short
|
||||
// Partial path that gets nowhere (blocked). Heading 0 = north (+y), 90 = east (+x); the character stands at 0,0.
|
||||
private static readonly OutdoorHunt.Vec At = new(0, 0, 0);
|
||||
private static double Yd(OutdoorHunt.Vec v) => Math.Sqrt(v.X * v.X + v.Y * v.Y) / 1.0;
|
||||
private static double BearingOf(OutdoorHunt.Vec v)
|
||||
{
|
||||
double b = Math.Atan2(v.X, v.Y) * 180 / Math.PI;
|
||||
return b < 0 ? b + 360 : b;
|
||||
}
|
||||
private static OutdoorHunt.PathResult Ok(OutdoorHunt.Vec goal) =>
|
||||
new(OutdoorHunt.PathStatus.Ok, new[] { goal }, Yd(goal), 0);
|
||||
private static OutdoorHunt.PathResult Fail(OutdoorHunt.PathStatus s) =>
|
||||
new(s, Array.Empty<OutdoorHunt.Vec>(), 0, 0);
|
||||
private static OutdoorHunt.PathResult Stuck() =>
|
||||
new(OutdoorHunt.PathStatus.Partial, new[] { new OutdoorHunt.Vec(0, 1, 0) }, 1, 0);
|
||||
|
||||
// PlanHeading works in world units; the tests treat them as yards (only ratios and bearings matter).
|
||||
private static void PlainStepGoes()
|
||||
{
|
||||
var plan = RynthAiPlugin.PlanHeading(At, 0, 50, 0, g => Ok(g));
|
||||
Check.True(plan.Found, "found");
|
||||
Check.True(plan.Detour == "", $"no detour note, got '{plan.Detour}'");
|
||||
Check.True(Math.Abs(Yd(plan.Path.Corners[^1]) - 50) < 0.01, "the full 50");
|
||||
Check.True(plan.Side == 0, "no side taken");
|
||||
}
|
||||
|
||||
private static void GoalOffMapPulledBack()
|
||||
{
|
||||
// A rock face from 40 yd on: goals past it are off the mesh.
|
||||
int calls = 0;
|
||||
var plan = RynthAiPlugin.PlanHeading(At, 0, 50, 0, g => { calls++; return Yd(g) > 40 ? Fail(OutdoorHunt.PathStatus.NoMesh) : Ok(g); });
|
||||
Check.True(plan.Found, "found");
|
||||
Check.True(Math.Abs(Yd(plan.Path.Corners[^1]) - 30) < 0.01, $"30 yd (60% of 50), got {Yd(plan.Path.Corners[^1]):0.0}");
|
||||
Check.True(Math.Abs(BearingOf(plan.Path.Corners[^1])) < 0.01, "still north");
|
||||
Check.True(plan.Detour.Contains("off walkable ground"), $"says why, got '{plan.Detour}'");
|
||||
Check.True(calls == 2, $"the 50 yd goal, then 30 (calls {calls})");
|
||||
}
|
||||
|
||||
private static void OffMapAheadGoesRound()
|
||||
{
|
||||
// A cliff ahead (north, any distance) and to the left: only the north-east is walkable.
|
||||
var plan = RynthAiPlugin.PlanHeading(At, 0, 50, 0, g =>
|
||||
{
|
||||
double b = BearingOf(g);
|
||||
return b > 30 && b < 60 ? Ok(g) : Fail(OutdoorHunt.PathStatus.NoMesh);
|
||||
});
|
||||
Check.True(plan.Found, "found a way round");
|
||||
Check.True(Math.Abs(BearingOf(plan.Path.Corners[^1]) - 45) < 0.01, "45° right");
|
||||
Check.True(plan.Detour.Contains("45° right"), $"says so, got '{plan.Detour}'");
|
||||
Check.True(plan.Side == 1, "the right side is kept from now on");
|
||||
}
|
||||
|
||||
private static void NoPathPulledBack()
|
||||
{
|
||||
var plan = RynthAiPlugin.PlanHeading(At, 90, 50, 0, g => Yd(g) > 20 ? Fail(OutdoorHunt.PathStatus.NoPath) : Ok(g));
|
||||
Check.True(plan.Found, "found");
|
||||
Check.True(Math.Abs(Yd(plan.Path.Corners[^1]) - 15) < 0.01, $"15 yd (30% of 50), got {Yd(plan.Path.Corners[^1]):0.0}");
|
||||
Check.True(Math.Abs(BearingOf(plan.Path.Corners[^1]) - 90) < 0.01, "still east");
|
||||
}
|
||||
|
||||
private static void NothingWalkable()
|
||||
{
|
||||
int calls = 0;
|
||||
var plan = RynthAiPlugin.PlanHeading(At, 0, 50, 0, g => { calls++; return Fail(OutdoorHunt.PathStatus.NoMesh); });
|
||||
Check.True(!plan.Found, "nothing found");
|
||||
Check.True(plan.Straight.Contains("no walkable ground"), $"says why, got '{plan.Straight}'");
|
||||
Check.True(calls > 7, $"every goal tried, closer ones too (calls {calls})");
|
||||
}
|
||||
|
||||
private static void RynthNavMissing()
|
||||
{
|
||||
int calls = 0;
|
||||
var plan = RynthAiPlugin.PlanHeading(At, 0, 50, 0, g => { calls++; return Fail(OutdoorHunt.PathStatus.Unavailable); });
|
||||
Check.True(!plan.Found, "nothing found");
|
||||
Check.True(plan.Straight.Contains("isn't loaded"), $"says why, got '{plan.Straight}'");
|
||||
Check.True(calls == 1, $"asked once (calls {calls})");
|
||||
}
|
||||
|
||||
private static void KeepsSide()
|
||||
{
|
||||
// Ahead is blocked at every distance (a path that gets nowhere); both 45° sides are open. The last detour
|
||||
// went left: this one goes left too.
|
||||
Func<OutdoorHunt.Vec, OutdoorHunt.PathResult> nav = g =>
|
||||
{
|
||||
double b = BearingOf(g);
|
||||
return (b < 1 || b > 359) ? Stuck() : Ok(g);
|
||||
};
|
||||
var left = RynthAiPlugin.PlanHeading(At, 0, 50, -1, nav);
|
||||
Check.True(left.Found && Math.Abs(BearingOf(left.Path.Corners[^1]) - 315) < 0.01, "45° left, as the last step");
|
||||
Check.True(left.Side == -1, "left kept");
|
||||
var none = RynthAiPlugin.PlanHeading(At, 0, 50, 0, nav);
|
||||
Check.True(none.Found && Math.Abs(BearingOf(none.Path.Corners[^1]) - 45) < 0.01, "no side yet: the first way round (right)");
|
||||
}
|
||||
|
||||
private static double World(double navUnits) => (navUnits * 10.0 + 1019.5) * 24.0;
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ internal static class NavJumpStepTests
|
|||
r.Add("nav jump step: /ra nav addjump adds a Jump where you stand, facing your way, held 300 ms (or as asked), saved to the file", AddJump);
|
||||
r.Add("nav jump step: while recording, no point is laid until you have jumped and landed", RecordingHolds);
|
||||
r.Add("nav jump step: ranav[] gives the route's name, place on it, type and whether a Once route ended", RaNav);
|
||||
r.Add("nav trail (R-20261129 0574): /ra navtrail route|back makes the breadcrumb trail the route; too short or off says how", TrailToRoute);
|
||||
}
|
||||
|
||||
private static DunRouteTests.Rig Rig(string folder, out string navPath)
|
||||
|
|
@ -100,6 +101,54 @@ internal static class NavJumpStepTests
|
|||
$"never still (a long fall): let go after {NavBreadcrumbTracker.JumpHoldMaxMs} ms ({at - t0})");
|
||||
}
|
||||
|
||||
// R-20261129-210845-0574: "an option to have a nav route made from your breadcrumbs". The Nav panel's
|
||||
// Tools menu had it (Walk it again / Walk it back); /ra navtrail route|back [name] does it from chat.
|
||||
// A name saves NavProfiles\<name>.nav through Save As; not used here (the tests share the real folder).
|
||||
private static void TrailToRoute()
|
||||
{
|
||||
var rig = Rig("NavProfiles-trail", out string navPath);
|
||||
var dash = (LegacyDashboardRenderer)rig.Get("_dashboard")!;
|
||||
var t = new NavBreadcrumbTracker(new RynthCore.PluginSdk.RynthCoreHost(FakeHost.LastApi), rig.S, _ => null, _ => { });
|
||||
dash.NavBreadcrumbs = t;
|
||||
// The rig's dashboard is built bare: what login and the constructor set in game.
|
||||
typeof(LegacyDashboardRenderer).GetField("_navFolder", Any)!.SetValue(dash, Path.GetDirectoryName(navPath));
|
||||
foreach (var (f, v) in new (string, object)[] { ("_profileListsLock", new object()), ("_navFiles", new System.Collections.Generic.List<string>()) })
|
||||
{
|
||||
var fi = typeof(LegacyDashboardRenderer).GetField(f, Any)!;
|
||||
if (fi.GetValue(dash) == null) fi.SetValue(dash, v);
|
||||
}
|
||||
rig.S.NavOverlay.TrackBreadcrumbs = false;
|
||||
|
||||
var said = rig.Typed("/ra navtrail route");
|
||||
Check.True(said.Any(l => l.Contains("No trail") && l.Contains("/ra navtrail on")), "no trail, Breadcrumbs off: says how: " + string.Join(" | ", said));
|
||||
Check.Eq(rig.S.CurrentNavPath, navPath, "the loaded route is left alone");
|
||||
|
||||
var crumbs = new[]
|
||||
{
|
||||
new NavCrumb(10.0, 20.0, 0f, true),
|
||||
new NavCrumb(10.1, 20.0, 0f, false),
|
||||
new NavCrumb(10.2, 20.0, 0f, false),
|
||||
new NavCrumb(10.3, 20.1, 0f, false),
|
||||
};
|
||||
typeof(NavBreadcrumbTracker).GetField("_snapshot", Any)!.SetValue(t, crumbs);
|
||||
rig.S.NavOverlay.RecordSpacingYards = 1;
|
||||
|
||||
said = rig.Typed("/ra navtrail route");
|
||||
var pts = rig.S.CurrentRoute.Points;
|
||||
Check.True(said.Any(l => l.Contains("Trail route created") && l.Contains("(unsaved)")), "made, unsaved: " + string.Join(" | ", said));
|
||||
Check.True(pts.Count >= 2 && Math.Abs(pts[0].NS - 10.0) < 1e-9 && Math.Abs(pts[^1].NS - 10.3) < 1e-9, "walked again: first crumb first");
|
||||
Check.Eq(rig.S.CurrentNavPath, string.Empty, "a new route, not the loaded file");
|
||||
Check.True(File.Exists(navPath) && NavRouteParser.Load(navPath).Points.Count == 1, "the loaded file on disk is unchanged");
|
||||
|
||||
said = rig.Typed("/ra navtrail back");
|
||||
pts = rig.S.CurrentRoute.Points;
|
||||
Check.True(said.Any(l => l.Contains("Backtrack route created")), "backtrack said: " + string.Join(" | ", said));
|
||||
Check.True(Math.Abs(pts[0].NS - 10.3) < 1e-9 && Math.Abs(pts[^1].NS - 10.0) < 1e-9, "walked back: last crumb first");
|
||||
|
||||
said = rig.Typed("/ra navtrail");
|
||||
Check.True(said.Any(l => l.Contains("/ra navtrail route [name]")), "the status line tells how: " + string.Join(" | ", said));
|
||||
}
|
||||
|
||||
private static void RaNav()
|
||||
{
|
||||
var rig = Rig("NavProfiles-ranav", out _);
|
||||
|
|
|
|||
|
|
@ -24,6 +24,10 @@ internal static class OutdoorHuntTests
|
|||
r.Add("hunt fence (\"here and there nav takes him outside\"): a walk round the outside is no walk; from outside, a walk back in is", FenceWalk);
|
||||
r.Add("hunt: plans again when the monster moves, the walk runs out, or a while passes; not every tick", Replan);
|
||||
r.Add("hunt: nothing in range: it waits where it is (no walk back to the start); Hunt Radius defaults to anywhere", WaitsWhereItIs);
|
||||
r.Add("hunt roam (R-20261127 32e4): nothing in range: walks to the nearest part of the area not seen, keeps walking, a monster ends it", RoamWalks);
|
||||
r.Add("hunt roam: walks the whole Hunt Radius, never outside it, then waits; looks again after 5 min", RoamCoversArea);
|
||||
r.Add("hunt roam: a part no walk gets to, or a walk stopping short, is left out; the rest is still roamed", RoamUnreachable);
|
||||
r.Add("hunt roam: inside the fence only; Hunt Radius anywhere roams Hunt Range round the start; on by default (and the setting)", RoamFenceAndDefaults);
|
||||
r.Add("hunt: /ra hunt range|radius answer and cap; status and stop don't toggle it; panel opens the window", Commands);
|
||||
r.Add("hunt: the target dies: the next one; no pathfinder: it stands", NextAndNoPathfinder);
|
||||
r.Add("hunt: the settings round-trip with the rest (saved, copied, engine payload)", Settings);
|
||||
|
|
@ -317,7 +321,7 @@ internal static class OutdoorHuntTests
|
|||
private static void FloorApartLeftOut()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var h = new OutdoorHunt();
|
||||
var h = new OutdoorHunt { Roam = false };
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
var up = new OutdoorHunt.Vec(1006, 1000, 3.3);
|
||||
|
|
@ -351,7 +355,7 @@ internal static class OutdoorHuntTests
|
|||
private static void TooFarRoundForIt()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RangeYd = 300 }; // Hunt Range big enough that 2x it allows the walk
|
||||
var h = new OutdoorHunt { RangeYd = 300, Roam = false }; // Hunt Range big enough that 2x it allows the walk
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
nav.Overrides[(1068, 1000)] = new(OutdoorHunt.PathStatus.Ok, new[] { V(1000, 1150), V(1068, 1150), V(1068, 1000) }, 425, 0);
|
||||
|
|
@ -639,13 +643,13 @@ internal static class OutdoorHuntTests
|
|||
// An open-world Thread's circle, its fence 50 yd round (1000, 1000): a monster past it is no pick, even nearer.
|
||||
private static void FenceHunt()
|
||||
{
|
||||
var h = new OutdoorHunt { RangeYd = 100, Fence = p => (p.X - 1000) * (p.X - 1000) + (p.Y - 1000) * (p.Y - 1000) <= 50 * 50 };
|
||||
var h = new OutdoorHunt { Roam = false, RangeYd = 100, Fence = p => (p.X - 1000) * (p.X - 1000) + (p.Y - 1000) * (p.Y - 1000) <= 50 * 50 };
|
||||
var me = V(1040, 1000);
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
var d = h.Tick(T0, me, true, Sorted(C(1, 1060, 1000, me), C(2, 1000, 1030, me)), nav.Path);
|
||||
Check.Eq(d.TargetId, 2, "the one 60 yd from the middle is outside the fence (20 yd off); the one inside is walked to");
|
||||
var h2 = new OutdoorHunt { RangeYd = 100, Fence = p => (p.X - 1000) * (p.X - 1000) + (p.Y - 1000) * (p.Y - 1000) <= 50 * 50 };
|
||||
var h2 = new OutdoorHunt { Roam = false, RangeYd = 100, Fence = p => (p.X - 1000) * (p.X - 1000) + (p.Y - 1000) * (p.Y - 1000) <= 50 * 50 };
|
||||
h2.Start(T0, me);
|
||||
var d2 = h2.Tick(T0, me, true, Sorted(C(1, 1060, 1000, me), C(3, 1090, 1000, me)), nav.Path);
|
||||
Check.Eq(d2.TargetId, 0, "every monster outside it: no pick");
|
||||
|
|
@ -796,7 +800,7 @@ internal static class OutdoorHuntTests
|
|||
private static void WaitsWhereItIs()
|
||||
{
|
||||
var start = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RadiusYd = 100 };
|
||||
var h = new OutdoorHunt { RadiusYd = 100, Roam = false }; // roaming off: waits (RoamTests for on)
|
||||
h.Start(T0, start);
|
||||
var nav = new Nav();
|
||||
var me = V(1060, 1000);
|
||||
|
|
@ -813,6 +817,126 @@ internal static class OutdoorHuntTests
|
|||
Check.Eq(new OutdoorHunt().RadiusYd, 0.0, "Hunt Radius defaults to 0 (anywhere)");
|
||||
}
|
||||
|
||||
// ── Roaming (2026-12-01, report R-20261127-181056-32e4: "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) ──
|
||||
|
||||
/// <summary>Ticks the hunt with no monsters, walking each walk to its end; the walks' ends, in order.</summary>
|
||||
private static List<OutdoorHunt.Vec> RoamAll(OutdoorHunt h, Nav nav, ref OutdoorHunt.Vec me, ref DateTime t, int maxWalks = 200)
|
||||
{
|
||||
var ends = new List<OutdoorHunt.Vec>();
|
||||
bool done = true;
|
||||
for (int i = 0; i < maxWalks * 3 && ends.Count < maxWalks; i++)
|
||||
{
|
||||
t = t.AddSeconds(1.1);
|
||||
var d = h.Tick(t, me, done, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
if (d.Act == OutdoorHunt.Act.Walk && d.Corners != null)
|
||||
{
|
||||
me = d.Corners[^1];
|
||||
ends.Add(me);
|
||||
done = true; // the next tick: arrived
|
||||
}
|
||||
else if (d.Act == OutdoorHunt.Act.Idle) break;
|
||||
}
|
||||
return ends;
|
||||
}
|
||||
|
||||
private static void RoamWalks()
|
||||
{
|
||||
var start = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RadiusYd = 100 };
|
||||
h.Start(T0, start);
|
||||
var nav = new Nav();
|
||||
var d = h.Tick(T0, start, true, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Walk, "nothing in range: it walks on");
|
||||
Check.True(h.Roaming && d.TargetId == 0, "roaming, no monster target");
|
||||
Check.True(h.Note.Contains("roaming to"), "says so: " + h.Note);
|
||||
Check.True(d.Corners![^1].FlatDistanceTo(start) <= h.RoamCellYd * 1.5, "to a part right next to the start (nearest first)");
|
||||
int calls = nav.Calls;
|
||||
d = h.Tick(T0.AddSeconds(0.4), start, false, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.None, "on the way: keeps walking (not stopped between picks)");
|
||||
d = h.Tick(T0.AddSeconds(1.5), start, false, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.None, "a pick with still nothing in range: keeps walking, no new walk");
|
||||
Check.Eq(nav.Calls, calls, "no path asked for while on the way");
|
||||
var me = V(1010, 990);
|
||||
d = h.Tick(T0.AddSeconds(3), me, false, Sorted(C(7, 1040, 990, me)), nav.Path);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.TargetId == 7, $"a monster comes in range: hunted ({d.Act} {d.TargetId})");
|
||||
Check.False(h.Roaming, "the roam is over");
|
||||
Check.True(h.PendingNotes.Any(n => n.Contains("the roam ends")), "said so");
|
||||
}
|
||||
|
||||
private static void RoamCoversArea()
|
||||
{
|
||||
var start = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RadiusYd = 100 };
|
||||
h.Start(T0, start);
|
||||
var nav = new Nav();
|
||||
var me = start;
|
||||
var t = T0;
|
||||
var ends = RoamAll(h, nav, ref me, ref t);
|
||||
Check.True(ends.Count >= 10, $"it walks round the area ({ends.Count} walks)");
|
||||
Check.True(ends.All(e => e.FlatDistanceTo(start) <= h.RadiusYd), "never outside Hunt Radius");
|
||||
var seen = new HashSet<(int, int)>(ends.Select(e => h.RoamSquareOf(e)));
|
||||
seen.Add(h.RoamSquareOf(start));
|
||||
Check.Eq(h.RoamSquaresToSee(t, me).Count, 0, "every part of the area seen");
|
||||
Check.True(h.Note.Contains("whole area") && h.Note.Contains("waiting here"), "then waits, and says why: " + h.Note);
|
||||
var d = h.Tick(t.AddSeconds(2), me, true, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Idle, "all seen lately: stands");
|
||||
t = t.AddSeconds(h.RoamRevisitSec + 5);
|
||||
d = h.Tick(t, me, true, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Walk, "5 min on: it looks round again (respawns)");
|
||||
}
|
||||
|
||||
private static void RoamUnreachable()
|
||||
{
|
||||
var start = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RadiusYd = 60 };
|
||||
h.Start(T0, start);
|
||||
var nav = new Nav();
|
||||
// The nearest part's centre: a wall in the way, every walk to it ends 30 yd short.
|
||||
var first = h.RoamSquaresToSee(T0, start)[0];
|
||||
var goal = h.RoamSquareCentre(first, start.Z + 30);
|
||||
nav.Walls[(goal.X, goal.Y)] = (V(goal.X - 30, goal.Y), 30);
|
||||
var d = h.Tick(T0, start, true, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Walk, "it still roams");
|
||||
Check.True(h.RoamSquareOf(d.Corners![^1]) != first, "but not to the part no walk gets to");
|
||||
Check.False(h.RoamSquaresToSee(T0, start).Contains(first), "that part is left out");
|
||||
|
||||
// A walk that stops short (blocked on the way): its part is left out too.
|
||||
var target = d.Corners[^1];
|
||||
var sq = h.RoamSquareOf(target);
|
||||
var shortOf = V(start.X + (target.X - start.X) * 0.1, start.Y + (target.Y - start.Y) * 0.1);
|
||||
d = h.Tick(T0.AddSeconds(1.2), shortOf, true, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.True(h.PendingNotes.Any(n => n.Contains("stopped") && n.Contains("left out")), "said: " + string.Join(" | ", h.PendingNotes));
|
||||
Check.False(h.RoamSquaresToSee(T0.AddSeconds(1.2), shortOf).Contains(sq), "the part it couldn't get to is left out");
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Walk, "and it goes on to another part");
|
||||
}
|
||||
|
||||
private static void RoamFenceAndDefaults()
|
||||
{
|
||||
var start = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RadiusYd = 200, Fence = p => p.X >= 1000 }; // only the east half
|
||||
h.Start(T0, start);
|
||||
var nav = new Nav();
|
||||
var me = start;
|
||||
var t = T0;
|
||||
var ends = RoamAll(h, nav, ref me, ref t);
|
||||
Check.True(ends.Count > 0 && ends.All(e => e.X >= 1000 - h.RoamCellYd * 0.5), "only inside the fence");
|
||||
|
||||
var any = new OutdoorHunt { RadiusYd = 0, RangeYd = 150 };
|
||||
any.Start(T0, start);
|
||||
Check.Eq(any.RoamRadiusYd, 150.0, "Hunt Radius anywhere: it roams Hunt Range round the start");
|
||||
me = start; t = T0;
|
||||
ends = RoamAll(any, new Nav(), ref me, ref t);
|
||||
Check.True(ends.Count > 0 && ends.All(e => e.FlatDistanceTo(start) <= 150), "and never farther");
|
||||
|
||||
var big = new OutdoorHunt { RadiusYd = 2000 };
|
||||
Check.True(big.RoamCellYd > big.RoamCellMinYd, $"a big area has bigger parts ({big.RoamCellYd:0} yd), not thousands of them");
|
||||
|
||||
Check.True(new OutdoorHunt().Roam, "roaming is on by default");
|
||||
Check.True(new LegacyUiSettings().OutdoorHuntRoam, "and so is the setting");
|
||||
}
|
||||
|
||||
// Tom 10-23: "/mt opt set" gave no answer, and "/ra hunt status" toggled the hunt (the command read
|
||||
// the word "hunt" as its argument). The /ra hunt settings answer, and status/stop don't start it.
|
||||
private static void Commands()
|
||||
|
|
|
|||
|
|
@ -18,8 +18,10 @@ namespace RynthCore.RynthAiHostTests.Tests;
|
|||
// idle moments. With it on and the bot idle (no fight target, no monster within Monster Range, no
|
||||
// corpse to loot, no salvage), a rebuff starts once a buff has Rebuff With + the margin (default 2
|
||||
// minutes) left. The regular rebuff is unchanged; an early top-off never starts in a fight and stops
|
||||
// when one begins; margin 0 adds nothing. Since 2026-11-20 no buff cast starts in a fight at all (the
|
||||
// owner: "clear the mobs nearby before we rebuff"), except a Force Buff the player asked for.
|
||||
// when one begins; margin 0 adds nothing. 2026-11-20 to 2026-12-01 no buff cast started in a fight at all.
|
||||
// 2026-12-01: once under the set timer, the rebuff starts regardless, and the idle timer is higher and for
|
||||
// quiet moments: when a monster comes, the fight goes on until a buff reaches the regular timer. So at or under Rebuff With (or dispelled) a buff goes now, fight or not; only health under
|
||||
// Heal At in a fight holds it back.
|
||||
internal static class RebuffWhenIdleTests
|
||||
{
|
||||
private const uint Player = 0x50000F01;
|
||||
|
|
@ -31,9 +33,10 @@ internal static class RebuffWhenIdleTests
|
|||
{
|
||||
r.Add("rebuff when idle: idle, a buff inside Rebuff With + the margin is rebuffed early", IdleInsideMarginRebuffed);
|
||||
r.Add("rebuff when idle: in a fight, a buff inside the margin but over Rebuff With is not rebuffed", FightInsideMarginWaits);
|
||||
r.Add("rebuff when idle: in a fight, a buff at or under Rebuff With (or dispelled) waits for the fight's end, then is rebuffed (2026-11-20)", FightRegularRebuff);
|
||||
r.Add("rebuff: a fight that never ends (constant respawn): after 2 min of waiting a full pass goes in it, never under Heal At (R-20261125-130039-e3bc)", FightThatNeverEnds);
|
||||
r.Add("rebuff when idle: a rebuff run under way when a monster comes: the cast sent resolves, the rest waits for the fight's end", RunPausesForFight);
|
||||
r.Add("rebuff (2026-12-01): in a fight, a buff at or under Rebuff With (or dispelled) is rebuffed right away", FightRegularRebuff);
|
||||
r.Add("rebuff: a fight that never ends (constant respawn): rebuffed at Rebuff With at once, never under Heal At (R-20261125-130039-e3bc)", FightThatNeverEnds);
|
||||
r.Add("rebuff (2026-12-01): a regular rebuff run under way when a monster comes carries on in the fight", RunGoesOnInFight);
|
||||
r.Add("rebuff (2026-12-01): Recast dispelled buffs in a fight off: a dispelled buff waits for the fight's end, a buff at Rebuff With still goes and takes it along; the setting is saved, loaded, bridged, mapped", DispelOption);
|
||||
r.Add("rabuffsdue[seconds]: how many buffs a rebuff with that line would cast (a dispelled one too); -1 with buffing off or no buff manager; asking casts nothing", BuffsDueCount);
|
||||
r.Add("rebuff when idle: margin 0, or the option off, adds nothing", MarginZeroAddsNothing);
|
||||
r.Add("rebuff when idle: an early top-off under way stops when a fight starts (the cast sent resolves); the regular rules take over", EarlyRunStopsForFight);
|
||||
|
|
@ -185,21 +188,32 @@ internal static class RebuffWhenIdleTests
|
|||
Check.Eq(Show(rig.Beats(5)), Strength, "the fight over: topped off then");
|
||||
}
|
||||
|
||||
// 2026-11-20 (Thread 0x5C47: two buffs dispelled mid-fight, recast with a Rager on him, dead 4 s later): "clear
|
||||
// the mobs nearby before we rebuff". Due in a fight, a buff waits for the fight's end, then goes.
|
||||
// 2026-12-01: once under the set timer, the rebuff starts regardless. (2026-11-20 to 12-01 it waited for the fight's end.)
|
||||
private static void FightRegularRebuff()
|
||||
{
|
||||
var low = new Rig(rebuffWhenIdle: true) { Idle = false };
|
||||
low.Live((Strength, 290), (Willpower, 3000)); // under Rebuff With 300
|
||||
Check.True(low.B.NeedsAnyBuff(), "290 s left: due, fight or not");
|
||||
Check.Eq(low.Arbiter(), BotActivity.Combat, "in a fight combat keeps the tick");
|
||||
Check.Eq(Show(low.Beats(5)), "(none)", "nothing cast in the fight");
|
||||
Check.Eq(low.Logged("[Buff] buffs wait: a fight; they go on once the fight is over"), 1, "the wait is logged once");
|
||||
low.Idle = true;
|
||||
Check.Eq(low.Arbiter(), BotActivity.Buffing, "the fight over: buffing has it");
|
||||
Check.Eq(Show(low.Beats(5)), Strength, "and rebuffs");
|
||||
Check.Eq(low.Logged("[Buff] buffs go on: the fight is over"), 1, "the end is logged");
|
||||
Check.False(low.B.BuffsWaitForFight(), "nothing holds it in the fight");
|
||||
Check.Eq(low.Arbiter(), BotActivity.Buffing, "buffing takes the tick in the fight");
|
||||
Check.Eq(Show(low.Beats(5)), Strength, "rebuffed in the fight (Willpower, 3000 s left, left alone)");
|
||||
Check.Eq(low.Logged("[Buff] rebuffing in the fight (a fight): a buff is at or under Rebuff With (300 s)"), 1, "logged once");
|
||||
Check.Eq(low.Logged("[Buff] buffs wait"), 0, "no wait");
|
||||
Check.Eq(low.B.IdleTopOffRuns, 0, "a regular run, not an early top-off");
|
||||
Check.Eq(low.Arbiter(), BotActivity.Combat, "then combat has it");
|
||||
|
||||
// 2026-12-01: when one buff reaches the timer, everything with under 20 minutes left is rebuffed too, so
|
||||
// it isn't forever switching to a wand: the run takes every buff under Also Refresh Under
|
||||
// (RebuffTopOffSecondsRemaining, default 1200 s), in a fight too.
|
||||
Check.Eq(low.S.RebuffTopOffSecondsRemaining, 1200, "Also Refresh Under defaults to 20 minutes");
|
||||
var batch = new Rig(rebuffWhenIdle: false) { Idle = false };
|
||||
batch.Live((Strength, 290), (Willpower, 1100)); // Willpower: over Rebuff With, under 20 minutes
|
||||
var both = batch.Beats(6);
|
||||
Check.True(both.Contains(Strength) && both.Contains(Willpower), "in a fight, one buff at Rebuff With takes the one under 20 minutes along: " + Show(both));
|
||||
Check.Eq(Show(batch.Beats(5)), "(none)", "then nothing more");
|
||||
var single = new Rig(rebuffWhenIdle: false) { Idle = false };
|
||||
single.Live((Strength, 290), (Willpower, 1300)); // Willpower: over 20 minutes
|
||||
Check.Eq(Show(single.Beats(6)), Strength, "a buff with over 20 minutes left is left alone");
|
||||
|
||||
var dispel = new Rig(rebuffWhenIdle: true);
|
||||
dispel.Live((Strength, 3000), (Willpower, 3000));
|
||||
|
|
@ -207,25 +221,34 @@ internal static class RebuffWhenIdleTests
|
|||
dispel.Idle = false;
|
||||
dispel.Dispel(Strength);
|
||||
Check.True(dispel.B.NeedsAnyBuff(), "a buff dispelled mid-fight is due");
|
||||
Check.Eq(dispel.Arbiter(), BotActivity.Combat, "but combat keeps the tick");
|
||||
Check.Eq(Show(dispel.Beats(5)), "(none)", "not recast while the fight goes on");
|
||||
dispel.Idle = true;
|
||||
Check.Eq(Show(dispel.Beats(5)), Strength, "recast once the monsters nearby are dead");
|
||||
Check.Eq(dispel.Arbiter(), BotActivity.Buffing, "and goes in the fight");
|
||||
Check.Eq(Show(dispel.Beats(5)), Strength, "recast right away");
|
||||
|
||||
var off = new Rig(rebuffWhenIdle: false) { Idle = false };
|
||||
off.Live((Strength, 290), (Willpower, 3000));
|
||||
Check.Eq(Show(off.Beats(5)), "(none)", "the same with the option off: nothing in the fight");
|
||||
off.Idle = true;
|
||||
Check.Eq(Show(off.Beats(5)), Strength, "then rebuffed");
|
||||
Check.Eq(Show(off.Beats(5)), Strength, "the same with the option off");
|
||||
|
||||
// Fighting with every buff up isn't a wait: nothing is logged.
|
||||
// Under Heal At in the fight: the heals first, the buff once health is back over it.
|
||||
var hurt = new Rig(rebuffWhenIdle: false) { Idle = false };
|
||||
hurt.S.HealAt = 60;
|
||||
hurt.Live((Strength, 290), (Willpower, 3000));
|
||||
SetHealth(hurt, 50);
|
||||
Check.True(hurt.B.BuffsWaitForFight(), "50% under Heal At 60% in a fight: it waits");
|
||||
Check.Eq(Show(hurt.Beats(5)), "(none)", "nothing cast");
|
||||
Check.Eq(hurt.Logged("[Buff] buffs wait: a fight, health 50% under Heal At 60%"), 1, "the wait is logged once");
|
||||
SetHealth(hurt, 90);
|
||||
Check.Eq(Show(hurt.Beats(5)), Strength, "back over Heal At, the fight still on: rebuffed");
|
||||
Check.Eq(hurt.Logged("[Buff] buffs go on: health 90%, back over Heal At"), 1, "the end is logged");
|
||||
|
||||
// Fighting with every buff up: nothing is logged.
|
||||
var up = new Rig(rebuffWhenIdle: false) { Idle = false };
|
||||
up.Live((Strength, 3000), (Willpower, 3000));
|
||||
up.Beats(5);
|
||||
Check.Eq(up.Logged("[Buff] buffs wait"), 0, "no wait logged with nothing due");
|
||||
Check.Eq(up.Logged("[Buff] buffs wait") + up.Logged("[Buff] rebuffing in the fight"), 0, "nothing logged with nothing due");
|
||||
}
|
||||
|
||||
// Conquest, constant respawn, Monster Range 10: buffs waited almost 7 hours, ran out, and the character died.
|
||||
// Conquest, constant respawn, Monster Range 10: buffs waited almost 7 hours for the fight's end, ran out, and the
|
||||
// character died. Now nothing waits for the fight's end at all.
|
||||
private static void FightThatNeverEnds()
|
||||
{
|
||||
var rig = new Rig(rebuffWhenIdle: false) { Idle = false };
|
||||
|
|
@ -235,23 +258,17 @@ internal static class RebuffWhenIdleTests
|
|||
rig.Live((Strength, 2900), (Willpower, 3000));
|
||||
rig.Beats(2);
|
||||
rig.Live((Strength, 290), (Willpower, 3000));
|
||||
Check.Eq(Show(rig.Beats(110)), "(none)", "110 s of an unbroken fight: Strength (290 s left) still waits");
|
||||
Check.Eq(rig.Logged("[Buff] buffs wait: a fight"), 1, "the wait is logged once");
|
||||
Check.Eq(rig.Arbiter(), BotActivity.Combat, "combat keeps the tick meanwhile");
|
||||
Check.Eq(Show(rig.Beats(20)), Strength, "past 2 min: the pass goes in the fight and Strength is rebuffed");
|
||||
Check.Eq(rig.Logged("for a fight that doesn't end"), 1, "the pass is logged");
|
||||
Check.Eq(Show(rig.Beats(10)), "(none)", "nothing more to cast");
|
||||
Check.Eq(rig.Logged("the rebuff pass in the fight is done (nothing left to cast)"), 1, "its end is logged");
|
||||
Check.Eq(Show(rig.Beats(5)), Strength, "an unbroken fight: Strength (290 s left) is rebuffed at once");
|
||||
Check.Eq(Show(rig.Beats(120)), "(none)", "nothing more to cast");
|
||||
|
||||
// Under Heal At the pass never starts.
|
||||
// Under Heal At it never goes.
|
||||
var hurt = new Rig(rebuffWhenIdle: false) { Idle = false };
|
||||
RynthClock.TestNow = () => hurt.Now;
|
||||
hurt.S.HealAt = 50;
|
||||
hurt.Live((Strength, 2900), (Willpower, 3000));
|
||||
hurt.Beats(2);
|
||||
hurt.Live((Strength, 290), (Willpower, 3000));
|
||||
var v = (PlayerVitalsCache)typeof(BuffManager).GetField("_vitals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(hurt.B)!;
|
||||
v.CurrentHealth = 30;
|
||||
SetHealth(hurt, 30);
|
||||
Check.Eq(Show(hurt.Beats(150)), "(none)", "health 30% under Heal At 50%: no buff cast however long the fight");
|
||||
}
|
||||
finally { RynthClock.TestNow = null; }
|
||||
|
|
@ -279,22 +296,77 @@ internal static class RebuffWhenIdleTests
|
|||
Check.Eq(m.Expressions.Evaluate("rabuffsdue[1200]"), "-1", "buffing off: -1");
|
||||
}
|
||||
|
||||
// A rebuff run under way when a monster comes: the cast in flight resolves, the next waits for the fight's end.
|
||||
private static void RunPausesForFight()
|
||||
// A regular rebuff run under way when a monster comes: it carries on (2026-12-01; it used to wait for the fight's end).
|
||||
private static void RunGoesOnInFight()
|
||||
{
|
||||
var rig = new Rig(rebuffWhenIdle: false);
|
||||
rig.Live((Strength, 200), (Willpower, 250)); // both under Rebuff With: one run
|
||||
string first = rig.Beat(answer: false);
|
||||
Check.True(first == Strength || first == Willpower, $"the run starts ('{first}', hold: {rig.B.LastBuffSkipReason})");
|
||||
rig.Idle = false; // a monster comes
|
||||
Check.Eq(rig.Arbiter(), BotActivity.Buffing, "the cast in flight keeps the slot until it resolves");
|
||||
rig.Answer(first);
|
||||
Check.Eq(rig.Arbiter(), BotActivity.Combat, "then combat has it");
|
||||
Check.Eq(Show(rig.Beats(10)), "(none)", "nothing more is cast in the fight");
|
||||
Check.True(rig.Running, "the run is held, not ended");
|
||||
Check.Eq(rig.Arbiter(), BotActivity.Buffing, "the run keeps the tick in the fight");
|
||||
Check.Eq(Show(rig.Beats(5)), first == Strength ? Willpower : Strength, "and finishes");
|
||||
Check.False(rig.Running, "then ends");
|
||||
Check.Eq(rig.Arbiter(), BotActivity.Combat, "combat has it");
|
||||
}
|
||||
|
||||
// 2026-12-01: recasting dispelled buffs mid-fight is an option.
|
||||
private static void DispelOption()
|
||||
{
|
||||
var rig = new Rig(rebuffWhenIdle: false);
|
||||
Check.True(rig.S.RecastDispelledInFight, "on by default");
|
||||
rig.S.RecastDispelledInFight = false;
|
||||
rig.Live((Strength, 3000), (Willpower, 3000));
|
||||
rig.Beats(2);
|
||||
rig.Idle = false;
|
||||
rig.Dispel(Strength);
|
||||
Check.True(rig.B.NeedsAnyBuff(), "dispelled: due");
|
||||
Check.True(rig.B.BuffsWaitForFight(), "option off: it waits in the fight");
|
||||
Check.Eq(rig.Arbiter(), BotActivity.Combat, "combat keeps the tick");
|
||||
Check.Eq(Show(rig.Beats(5)), "(none)", "not recast in the fight");
|
||||
Check.Eq(rig.Logged("a dispelled buff waits for the fight's end"), 1, "the wait is logged once");
|
||||
rig.Idle = true;
|
||||
Check.Eq(Show(rig.Beats(5)), first == Strength ? Willpower : Strength, "the fight over: the run carries on");
|
||||
Check.False(rig.Running, "and ends");
|
||||
Check.Eq(Show(rig.Beats(5)), Strength, "the fight over: recast");
|
||||
|
||||
// A buff at Rebuff With still goes in the fight, and the run takes the dispelled one along.
|
||||
var both = new Rig(rebuffWhenIdle: false);
|
||||
both.S.RecastDispelledInFight = false;
|
||||
both.Live((Strength, 3000), (Willpower, 3000));
|
||||
both.Beats(2);
|
||||
both.Idle = false;
|
||||
both.Dispel(Strength);
|
||||
both.Beats(3);
|
||||
both.Live((Willpower, 290));
|
||||
var sent = both.Beats(6);
|
||||
Check.True(sent.Contains(Willpower) && sent.Contains(Strength), "Willpower at Rebuff With goes in the fight, Strength with it: " + Show(sent));
|
||||
|
||||
// Option on (the default): recast in the fight.
|
||||
var on = new Rig(rebuffWhenIdle: false);
|
||||
on.Live((Strength, 3000), (Willpower, 3000));
|
||||
on.Beats(2);
|
||||
on.Idle = false;
|
||||
on.Dispel(Strength);
|
||||
Check.Eq(Show(on.Beats(5)), Strength, "option on: recast in the fight");
|
||||
|
||||
// Saved, loaded, bridged, in the settings map.
|
||||
var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true,\"RebuffSecondsRemaining\":300}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(old != null && old.RecastDispelledInFight, "a profile saved before the setting: on");
|
||||
var off = JsonSerializer.Deserialize(
|
||||
JsonSerializer.Serialize(new LegacyUiSettings { RecastDispelledInFight = false }, RynthAiJsonContext.Default.LegacyUiSettings),
|
||||
RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(off != null && !off.RecastDispelledInFight, "off is saved and loaded");
|
||||
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
var dst = new LegacyUiSettings();
|
||||
copy.Invoke(null, new object[] { new LegacyUiSettings { RecastDispelledInFight = false }, dst });
|
||||
Check.False(dst.RecastDispelledInFight, "a profile with it off loads off");
|
||||
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(payload != null && payload.RecastDispelledInFight == null, "an older engine's payload has no value (left alone)");
|
||||
var live = new LegacyUiSettings();
|
||||
var map = ExpressionTests.Engine(settings: live).BuildSettingsMapPublic();
|
||||
Check.True(map.TryGetValue("RecastDispelledInFight", out var entry), "in the settings map");
|
||||
entry.Set("0");
|
||||
Check.False(live.RecastDispelledInFight, "and sets off");
|
||||
}
|
||||
|
||||
private static void MarginZeroAddsNothing()
|
||||
|
|
@ -334,13 +406,14 @@ internal static class RebuffWhenIdleTests
|
|||
Check.Eq(Show(rig.Beats(10)), "(none)", "nothing more is cast in the fight");
|
||||
Check.Eq(rig.Logged("the early top-off stops"), 1, "logged once");
|
||||
|
||||
// The regular rules take over: the other buff dropping under Rebuff With waits for the fight's end (2026-11-20).
|
||||
// The regular rules take over: the other buff, still over Rebuff With, waits; once it drops under, it goes in
|
||||
// the fight (2026-12-01: the fight goes on until a buff reaches the regular timer).
|
||||
string other = first == Strength ? Willpower : Strength;
|
||||
rig.Live((first, 2700), (other, 350));
|
||||
Check.Eq(Show(rig.Beats(5)), "(none)", "350 s left in the fight, over Rebuff With 300: it waits");
|
||||
rig.Live((first, 2700), (other, 290));
|
||||
Check.Eq(Show(rig.Beats(5)), "(none)", "under Rebuff With in the fight: it waits");
|
||||
rig.Idle = true;
|
||||
Check.Eq(Show(rig.Beats(5)), other, "the fight over: rebuffed as usual");
|
||||
rig.Idle = false;
|
||||
Check.Eq(Show(rig.Beats(5)), other, "under Rebuff With: rebuffed in the fight");
|
||||
Check.Eq(rig.B.IdleTopOffRuns, 1, "that was a regular run");
|
||||
|
||||
// And an early run interrupted with the other buff still inside the margin finishes when idle again.
|
||||
var again = new Rig(rebuffWhenIdle: true);
|
||||
|
|
|
|||
291
Tools/RynthCore.RynthAiHostTests/Tests/UbInventoryTests.cs
Normal file
291
Tools/RynthCore.RynthAiHostTests/Tests/UbInventoryTests.cs
Normal file
|
|
@ -0,0 +1,291 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Loot.VTank;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// /ub equip list|load|test|create and /ub autosalvage [force] (2026-12-01 command audit): equip went on
|
||||
// to /mt equip ("Item not found: load ...") so a meta's armor or weapon swap did nothing; autosalvage
|
||||
// was accepted and ignored. Both judge the carried items by a loot profile's rules.
|
||||
internal static class UbInventoryTests
|
||||
{
|
||||
private const uint Player = 0x50000F71;
|
||||
private const uint WornRobe = 0x80287101, HelmA = 0x80287102, HelmB = 0x80287103;
|
||||
private const uint Ring1 = 0x80287104, Ring2 = 0x80287105, Ring3 = 0x80287106;
|
||||
private const uint Sword = 0x80287107, Bow = 0x80287108, Junk = 0x80287109;
|
||||
private const uint Scrap1 = 0x8028710A, Tinked = 0x8028710B, Imbued = 0x8028710C, Unknown = 0x8028710D, WornScrap = 0x8028710E;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("ub equip: the plan puts one item in each slot (two rings, one weapon) and keeps what is worn", PlanSlots);
|
||||
r.Add("ub equip: load wields the profile's carried items one at a time, never a worn one; test only says", LoadAndTest);
|
||||
r.Add("ub equip: create writes the worn items as a profile, never over a file; list names it", CreateAndList);
|
||||
r.Add("ub equip: '/ub equip <item name>' still wields that item (the /mt equip it was)", ByNameStillWorks);
|
||||
r.Add("ub autosalvage: lists without force; force queues the Salvage items, never worn, tinkered or imbued", AutoSalvage);
|
||||
r.Add("ub count profile: counts against the named profile without making it the one looting uses", CountProfileKeepsLootProfile);
|
||||
r.Add("ub autosalvage: an item its rule needs identified is identified first", AutoSalvageWaitsForId);
|
||||
}
|
||||
|
||||
private static string Folder => Path.Combine(Program.TempRoot, "UbEquip");
|
||||
|
||||
private sealed class World
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new();
|
||||
public long Now = 1_000_000;
|
||||
public readonly WorldObjectCache Cache;
|
||||
|
||||
public World(params (uint Id, string Name, int Slots, uint WornAt)[] items)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true; // UseObject, and GetObjectWielderInfo answering from Wielded
|
||||
FakeHost.WeaponCalls = true; // RequestId and HasAppraisalData
|
||||
FakeHost.Names[Player] = "Equipper";
|
||||
FakeHost.PlayerIdValue = Player;
|
||||
foreach (var (id, name, slots, wornAt) in items)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Containers[id] = Player;
|
||||
FakeHost.ItemTypes[id] = slots != 0 ? 0x2u : 0x1u;
|
||||
if (slots != 0) FakeHost.Ints[(id, 9)] = slots; // ValidLocations
|
||||
if (wornAt != 0) FakeHost.Wielded[id] = wornAt;
|
||||
FakeHost.Appraised.Add(id);
|
||||
}
|
||||
var host = FakeHost.Create(playerId: Player);
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_initialized", true);
|
||||
Set("_loginComplete", true);
|
||||
Set("_salvageManager", new RynthCore.Plugin.RynthAi.Loot.SalvageManager(host, S, Cache));
|
||||
foreach (var it in items) Cache.OnCreateObject(it.Id);
|
||||
Cache.Tick();
|
||||
P.UbInvClock = () => Now;
|
||||
RynthAiPlugin.UbEquipFolder = Folder;
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public object? Get(string f) => typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P);
|
||||
public bool Ub(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleUbCommand", Any)!.Invoke(P, new object[] { line })!;
|
||||
public void Tick(long advanceMs)
|
||||
{
|
||||
Now += advanceMs;
|
||||
typeof(RynthAiPlugin).GetMethod("TickUbInventoryJobs", Any)!.Invoke(P, null);
|
||||
}
|
||||
public bool ChatHas(string text) => FakeHost.Chat.Any(c => c.Contains(text, StringComparison.OrdinalIgnoreCase));
|
||||
public int SalvageQueued => ((RynthCore.Plugin.RynthAi.Loot.SalvageManager)Get("_salvageManager")!).GetStateSnapshot().QueueCount;
|
||||
}
|
||||
|
||||
private static VTankLootRule Rule(string name, VTankLootAction action, params VTankLootCondition[] conds)
|
||||
{
|
||||
var r = new VTankLootRule { Name = name, Action = action, CustomExpression = string.Empty };
|
||||
r.Conditions.AddRange(conds);
|
||||
return r;
|
||||
}
|
||||
|
||||
private static VTankLootCondition NameIs(string pattern) => new(VTankNodeTypes.StringValueMatch, "0", new[] { pattern, "1" });
|
||||
|
||||
private static string WriteProfile(string fileName, params VTankLootRule[] rules)
|
||||
{
|
||||
Directory.CreateDirectory(Folder);
|
||||
var p = new VTankLootProfile();
|
||||
p.Rules.AddRange(rules);
|
||||
string path = Path.Combine(Folder, fileName);
|
||||
VTankLootWriter.Save(p, path);
|
||||
return path;
|
||||
}
|
||||
|
||||
private static void PlanSlots()
|
||||
{
|
||||
const int Head = 0x1, Fingers = 0x000C0000;
|
||||
var plan = UbEquipPlan.Plan(new[]
|
||||
{
|
||||
new UbEquipPlan.Item(1, "Helm A", Head, false, 0, 0),
|
||||
new UbEquipPlan.Item(2, "Helm B", Head, false, 0, 1),
|
||||
new UbEquipPlan.Item(3, "Ring 1", Fingers, false, 0, 2),
|
||||
new UbEquipPlan.Item(4, "Ring 2", Fingers, false, 0, 3),
|
||||
new UbEquipPlan.Item(5, "Ring 3", Fingers, false, 0, 4),
|
||||
new UbEquipPlan.Item(6, "Sword", UbEquipPlan.MeleeWeapon, false, 0, 5),
|
||||
new UbEquipPlan.Item(7, "Bow", UbEquipPlan.MissileWeapon, false, 0, 6),
|
||||
new UbEquipPlan.Item(8, "Robe", 0x2, true, 0x2, 7),
|
||||
new UbEquipPlan.Item(9, "Coat", 0x2, false, 0, 8),
|
||||
new UbEquipPlan.Item(10, "Pea", 0, false, 0, 9),
|
||||
});
|
||||
Check.Eq(string.Join(",", plan.Equip.Select(i => i.Name)), "Helm A,Ring 1,Ring 2,Sword", "first helm, two rings, one weapon");
|
||||
Check.Eq(string.Join(",", plan.AlreadyWorn.Select(i => i.Name)), "Robe", "the worn robe stays");
|
||||
Check.Eq(string.Join(",", plan.Skipped.Select(s => s.Item.Name)), "Helm B,Ring 3,Bow,Coat,Pea", "the rest is left out");
|
||||
|
||||
// A worn ring keeps its finger: one more ring fits, not two.
|
||||
var rings = UbEquipPlan.Plan(new[]
|
||||
{
|
||||
new UbEquipPlan.Item(1, "Worn Ring", Fingers, true, 0x00040000, 0),
|
||||
new UbEquipPlan.Item(2, "Ring 2", Fingers, false, 0, 1),
|
||||
new UbEquipPlan.Item(3, "Ring 3", Fingers, false, 0, 2),
|
||||
});
|
||||
Check.Eq(rings.Equip.Count, 1, "one free finger");
|
||||
// Worn with its slot unknown: kept, and it takes no slot by guess.
|
||||
var unknown = UbEquipPlan.Plan(new[]
|
||||
{
|
||||
new UbEquipPlan.Item(1, "Worn Thing", Head, true, 0, 0),
|
||||
new UbEquipPlan.Item(2, "Helm", Head, false, 0, 1),
|
||||
});
|
||||
Check.True(unknown.AlreadyWorn.Count == 1 && unknown.Equip.Count == 1, "worn with no known slot: kept, nothing blocked");
|
||||
}
|
||||
|
||||
private static World EquipWorld() => new(
|
||||
(WornRobe, "Faran Robe", 0x2, 0x2),
|
||||
(HelmA, "Helm of A", 0x1, 0),
|
||||
(HelmB, "Helm of B", 0x1, 0),
|
||||
(Ring1, "Ring", 0x000C0000, 0),
|
||||
(Ring2, "Ring", 0x000C0000, 0),
|
||||
(Ring3, "Ring", 0x000C0000, 0),
|
||||
(Sword, "Sword", UbEquipPlan.MeleeWeapon, 0),
|
||||
(Bow, "Bow", UbEquipPlan.MissileWeapon, 0),
|
||||
(Junk, "Junk Hat", 0x1, 0));
|
||||
|
||||
private static void LoadAndTest()
|
||||
{
|
||||
WriteProfile("melee.utl",
|
||||
Rule("Robe", VTankLootAction.Keep, NameIs("^Faran Robe$")),
|
||||
Rule("Helm A", VTankLootAction.Keep, NameIs("^Helm of A$")),
|
||||
Rule("Helms", VTankLootAction.Keep, NameIs("^Helm of")),
|
||||
Rule("Rings", VTankLootAction.Keep, NameIs("^Ring$")),
|
||||
Rule("Sword", VTankLootAction.Keep, NameIs("^Sword$")),
|
||||
Rule("Bow", VTankLootAction.Keep, NameIs("^Bow$")),
|
||||
Rule("Junk", VTankLootAction.Sell, NameIs("^Junk")));
|
||||
|
||||
var w = EquipWorld();
|
||||
Check.True(w.Ub("/ub equip test melee"), "/ub equip test is handled");
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "test wields nothing");
|
||||
Check.True(w.ChatHas("would equip") && w.ChatHas("Helm of A") && w.ChatHas("already worn: Faran Robe"), "test says what would go on");
|
||||
|
||||
Check.True(w.Ub("/ub equip load melee.utl"), "/ub equip load is handled (a name with .utl)");
|
||||
Check.Eq(FakeHost.Uses.Count, 1, "the first wield goes at once");
|
||||
for (int i = 0; i < 10; i++) w.Tick(RynthAiPlugin.UbEquipSpacingMs);
|
||||
var used = FakeHost.Uses.ToList();
|
||||
Check.Eq(used.Count, 4, "helm, two rings, the sword: one item a slot");
|
||||
Check.True(used.Contains(HelmA) && !used.Contains(HelmB), "the helm of the first rule that takes one");
|
||||
Check.Eq(used.Count(u => u is Ring1 or Ring2 or Ring3), 2, "two rings of three");
|
||||
Check.True(used.Contains(Sword) && !used.Contains(Bow), "one weapon: the earlier rule's");
|
||||
Check.False(used.Contains(WornRobe), "the worn robe is never used (that would take it off)");
|
||||
Check.False(used.Contains(Junk), "a Sell rule's item isn't equipped");
|
||||
// Nothing went on in the fake: the check after the last wield says so.
|
||||
w.Tick(RynthAiPlugin.UbEquipSettleMs);
|
||||
Check.True(w.ChatHas("equipped 0 of 4"), "after the wields: how many went on");
|
||||
|
||||
Check.True(w.Ub("/ub equip load nosuchprofile"), "a missing profile is handled");
|
||||
Check.True(w.ChatHas("no profile 'nosuchprofile'"), "and said");
|
||||
Check.True(w.Ub("/ub equip load"), "no name: handled");
|
||||
Check.True(w.ChatHas("Usage: /ub equip"), "with the usage");
|
||||
}
|
||||
|
||||
private static void CreateAndList()
|
||||
{
|
||||
var w = EquipWorld();
|
||||
FakeHost.Wielded[HelmA] = 0x1;
|
||||
Check.True(w.Ub("/ub equip create mysuit"), "/ub equip create is handled");
|
||||
string path = Path.Combine(Folder, "mysuit.utl");
|
||||
Check.True(File.Exists(path), "mysuit.utl written in the equipment folder");
|
||||
VTankLootProfile p = VTankLootParser.Load(path);
|
||||
Check.Eq(p.Rules.Count, 2, "a rule for each worn item");
|
||||
Check.True(p.Rules.All(r => r.Action == VTankLootAction.Keep), "Keep rules");
|
||||
|
||||
// The profile made from the worn items takes them (and nothing else).
|
||||
FakeHost.Uses.Clear();
|
||||
FakeHost.Chat.Clear();
|
||||
Check.True(w.Ub("/ub equip test mysuit"), "test the new profile");
|
||||
Check.True(w.ChatHas("nothing to equip") && w.ChatHas("Faran Robe") && w.ChatHas("Helm of A"), "both already worn, nothing else");
|
||||
|
||||
DateTime before = File.GetLastWriteTimeUtc(path);
|
||||
Check.True(w.Ub("/ub equip create mysuit"), "again");
|
||||
Check.True(w.ChatHas("already exists"), "never over an existing file");
|
||||
Check.Eq(File.GetLastWriteTimeUtc(path), before, "the file is untouched");
|
||||
|
||||
FakeHost.Chat.Clear();
|
||||
Check.True(w.Ub("/ub equip list"), "/ub equip list");
|
||||
Check.True(w.ChatHas("mysuit.utl"), "lists it");
|
||||
}
|
||||
|
||||
private static void ByNameStillWorks()
|
||||
{
|
||||
var w = EquipWorld();
|
||||
Check.True(w.Ub("/ub equip Helm of B"), "/ub equip <item name> is handled");
|
||||
Check.True(FakeHost.Uses.Count == 1 && FakeHost.Uses[0] == HelmB, "it wields that item, as /mt equip did");
|
||||
}
|
||||
|
||||
private static World SalvageWorld() => new(
|
||||
(Scrap1, "Iron Scrap Sword", 0, 0),
|
||||
(Tinked, "Iron Tinked Sword", 0, 0),
|
||||
(Imbued, "Iron Imbued Sword", 0, 0),
|
||||
(WornScrap, "Iron Worn Sword", UbEquipPlan.MeleeWeapon, UbEquipPlan.MeleeWeapon),
|
||||
(Junk, "Junk Hat", 0x1, 0));
|
||||
|
||||
private static void AutoSalvage()
|
||||
{
|
||||
string path = WriteProfile("salv.utl",
|
||||
Rule("Iron", VTankLootAction.Salvage, NameIs("^Iron")),
|
||||
Rule("Junk", VTankLootAction.Sell, NameIs("^Junk")));
|
||||
var w = SalvageWorld();
|
||||
FakeHost.Ints[(Tinked, 171)] = 2; // NumTimesTinkered
|
||||
FakeHost.Ints[(Imbued, 179)] = 0x1; // ImbuedEffect
|
||||
Check.True(w.Ub("/ub autosalvage"), "no loot profile in use: handled");
|
||||
Check.True(w.ChatHas("no loot profile in use"), "and said");
|
||||
|
||||
w.S.CurrentLootPath = path;
|
||||
FakeHost.Chat.Clear();
|
||||
Check.True(w.Ub("/ub autosalvage"), "/ub autosalvage");
|
||||
Check.True(w.ChatHas("1 item(s) would be salvaged: Iron Scrap Sword"), "lists the one item it would salvage");
|
||||
Check.True(w.ChatHas("Iron Tinked Sword (tinkered)") && w.ChatHas("Iron Imbued Sword (imbued)"), "says why the others are left");
|
||||
Check.Eq(w.SalvageQueued, 0, "without force nothing is salvaged");
|
||||
|
||||
Check.True(w.Ub("/ub autosalvage force"), "/ub autosalvage force");
|
||||
Check.Eq(w.SalvageQueued, 1, "force queues the one item");
|
||||
Check.True(w.ChatHas("salvaging 1 item(s): Iron Scrap Sword"), "and says so");
|
||||
Check.True(w.Ub("/ub autosalvage banana"), "a wrong word is handled");
|
||||
Check.True(w.ChatHas("Usage: /ub autosalvage"), "with the usage");
|
||||
}
|
||||
|
||||
private static void AutoSalvageWaitsForId()
|
||||
{
|
||||
string path = WriteProfile("salvid.utl", Rule("Iron", VTankLootAction.Salvage, NameIs("^Iron")));
|
||||
var w = new World((Unknown, "Iron Unknown Sword", 0, 0));
|
||||
FakeHost.Appraised.Remove(Unknown);
|
||||
w.S.CurrentLootPath = path;
|
||||
Check.True(w.Ub("/ub autosalvage force"), "handled");
|
||||
Check.True(w.ChatHas("identifying 1 item(s) first"), "it identifies the item first");
|
||||
Check.Eq(w.SalvageQueued, 0, "nothing queued yet");
|
||||
w.Tick(RynthAiPlugin.UbIdSpacingMs);
|
||||
Check.True(FakeHost.IdRequests.Contains(Unknown), "the identify is sent");
|
||||
FakeHost.Appraised.Add(Unknown);
|
||||
w.Tick(100);
|
||||
Check.Eq(w.SalvageQueued, 1, "once identified, it is salvaged");
|
||||
}
|
||||
|
||||
// 2026-12-01 command audit: /ub count profile <name> loaded the profile through TryLoadLootProfile, which
|
||||
// also made it the profile looting uses, so a meta counting against another profile switched its looting.
|
||||
private static void CountProfileKeepsLootProfile()
|
||||
{
|
||||
string inUse = WriteProfile("inuse.utl", Rule("Keep all", VTankLootAction.Keep, NameIs(".")));
|
||||
string other = WriteProfile("count.utl", Rule("Iron", VTankLootAction.Keep, NameIs("^Iron")));
|
||||
var w = SalvageWorld();
|
||||
w.S.CurrentLootPath = inUse;
|
||||
Check.True(w.Ub("/ub count profile " + other), "/ub count profile");
|
||||
Check.True(w.ChatHas("matching count.utl"), "it counts against that profile");
|
||||
Check.Eq(w.S.CurrentLootPath, inUse, "the loot profile in use is unchanged");
|
||||
}
|
||||
}
|
||||
|
|
@ -144,9 +144,9 @@ internal static class VitalWandGateTests
|
|||
SetVitals(b, 54, 100, 100);
|
||||
Check.True(b.BuffsWaitForFight(), "54% under Heal At 60% in a fight: buffs wait");
|
||||
Check.True(b.BuffsWaitForFight(), "still waiting");
|
||||
// Since 2026-11-20 the fight alone holds them ("clear the mobs nearby before we rebuff").
|
||||
// 2026-11-20 to 12-01 the fight alone held them; since 2026-12-01 only Heal At does ("rebuff starts regardless").
|
||||
SetVitals(b, 70, 100, 100);
|
||||
Check.True(b.BuffsWaitForFight(), "back over Heal At, the fight still on: buffs still wait");
|
||||
Check.False(b.BuffsWaitForFight(), "back over Heal At, the fight still on: buffs go");
|
||||
SetVitals(b, 40, 100, 100);
|
||||
b.InCombatOverride = () => false;
|
||||
Check.False(b.BuffsWaitForFight(), "out of a fight: buffs go on even under Heal At");
|
||||
|
|
|
|||
|
|
@ -140,6 +140,14 @@ namespace RynthDefective.Tests
|
|||
DefCommand bad = DefCommandParser.Parse("daynight soon");
|
||||
Check(bad.Verb == DefVerb.Error && bad.Error.Contains("Usage", StringComparison.Ordinal), "a wrong word: the usage");
|
||||
Check(DefCommandParser.Usage.Contains("daynight", StringComparison.Ordinal), "in the usage");
|
||||
// Its background (2026-12-01): clear by default, the dark box on request.
|
||||
Eq(DefCommandParser.Parse("daynight clear").Text, "clear", "daynight clear");
|
||||
Eq(DefCommandParser.Parse("daynight transparent").Text, "clear", "transparent = clear");
|
||||
Eq(DefCommandParser.Parse("daynight box").Text, "box", "daynight box");
|
||||
Check(DefCommandParser.Usage.Contains("daynight [show|hide|clear|box]", StringComparison.Ordinal), "clear and box in the usage");
|
||||
Check(!new DefSettings().DayNightBox, "a clear background by default (and for a settings file from before)");
|
||||
Check(DefReplies.DayNightLook(false).Text.Contains("clear background", StringComparison.Ordinal), "clear: said so");
|
||||
Check(DefReplies.DayNightLook(true).Text.Contains("dark box", StringComparison.Ordinal), "box: said so");
|
||||
|
||||
DerethNow dusk = DerethClock.At(RawAt(5715));
|
||||
Eq(DefReplies.DayNight(1, dusk), (true, "Day/Night timer shown. Night now (Evensong); day in 1h 4m of real time."), "shown, with the time");
|
||||
|
|
|
|||
|
|
@ -106,6 +106,7 @@ namespace RynthDefective.Tests
|
|||
("qty", DefVerb.Quantity), ("qty 25", DefVerb.Quantity), ("split", DefVerb.Split), ("split 25 into Sack", DefVerb.Split),
|
||||
("give 10", DefVerb.Give), ("buy 25 Mana Scarab", DefVerb.Buy), ("buy max", DefVerb.Buy),
|
||||
("daynight", DefVerb.DayNight), ("daynight show", DefVerb.DayNight), ("daynight hide", DefVerb.DayNight),
|
||||
("daynight clear", DefVerb.DayNight), ("daynight box", DefVerb.DayNight),
|
||||
("bars", DefVerb.Bars), ("bars add", DefVerb.Bars), ("bars remove 2", DefVerb.Bars), ("bars slots 2 12", DefVerb.Bars),
|
||||
("bars show 3", DefVerb.Bars), ("shortcuts clearbusy on", DefVerb.Shortcuts), ("shortcuts clearbusy", DefVerb.Shortcuts),
|
||||
("appraisal", DefVerb.Appraisal), ("appraisal pin", DefVerb.Appraisal), ("appraisal popout", DefVerb.Appraisal), ("examine 0x80001234", DefVerb.Appraisal),
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ internal static unsafe class Program
|
|||
var failed = new List<string>();
|
||||
if (filter.Length == 0 && !CheckBuiltInVerbsMatchSwitch()) failed.Add("built-in /lua verbs");
|
||||
if ((filter.Length == 0 || "memoryguard".Contains(filter, StringComparison.OrdinalIgnoreCase)) && !CheckMemoryGuard()) failed.Add("memory guard");
|
||||
if ((filter.Length == 0 || "workers".Contains(filter, StringComparison.OrdinalIgnoreCase)) && !CheckWorkers()) failed.Add("worker coroutines");
|
||||
try
|
||||
{
|
||||
foreach (string file in scripts)
|
||||
|
|
@ -214,6 +215,71 @@ internal static unsafe class Program
|
|||
return allOk;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Worker coroutines (LuaScriptHost): MoonSharp makes ~1 MB of stacks per coroutine (2 MB in
|
||||
/// this 64-bit test), so a coroutine per handler call made a 194-line /myquests read cost a
|
||||
/// chat-handling script ~200 MB and got a script stopped by the memory guard (2026-11-30).
|
||||
/// 300 chat lines through two handlers (one that errors every 50th line, one that sleeps
|
||||
/// every 100th) must all arrive, reuse a handful of workers, and allocate far less than
|
||||
/// 600 coroutines would.
|
||||
/// </summary>
|
||||
private static bool CheckWorkers()
|
||||
{
|
||||
const string name = "workerpool";
|
||||
const string code = @"
|
||||
seen, slept, errs = 0, 0, 0
|
||||
game.World.OnChatText.Add(function(e)
|
||||
seen = seen + 1
|
||||
if e.Message:find('boom', 1, true) then errs = errs + 1; error('boom (expected)') end
|
||||
end)
|
||||
game.World.OnChatText.Add(function(e)
|
||||
if e.Message:find('nap', 1, true) then sleep(30); slept = slept + 1 end
|
||||
end)
|
||||
while true do sleep(200); print('seen=' .. seen .. ' slept=' .. slept) end";
|
||||
FakeWorld.W = new FakeWorld();
|
||||
Harness.Reset();
|
||||
RynthCoreApiNative api = FakeHost.Build();
|
||||
var runtime = new RynthPluginRuntime<RynthLuaPlugin>();
|
||||
if (runtime.Init(&api) != 0 || runtime.Plugin == null) { Console.WriteLine("FAIL worker coroutines: no plugin"); return false; }
|
||||
RynthLuaPlugin plugin = runtime.Plugin;
|
||||
bool ok;
|
||||
try
|
||||
{
|
||||
plugin.OnLoginComplete();
|
||||
for (int i = 0; i < 3; i++) Tick(plugin);
|
||||
Directory.CreateDirectory(RynthLuaPaths.Scripts);
|
||||
File.WriteAllText(Path.Combine(RynthLuaPaths.Scripts, name + ".lua"), code);
|
||||
string? err = plugin.StartScript(name);
|
||||
for (int i = 0; i < 5; i++) Tick(plugin);
|
||||
int before = plugin.ScriptWorkersCreated(name);
|
||||
long alloc0 = GC.GetAllocatedBytesForCurrentThread();
|
||||
for (int i = 1; i <= 300; i++)
|
||||
{
|
||||
int eat = 0;
|
||||
plugin.OnChatWindowText($"line {i}" + (i % 50 == 0 ? " boom" : "") + (i % 100 == 0 ? " nap" : ""), 0, ref eat);
|
||||
if (i % 20 == 0) Tick(plugin);
|
||||
}
|
||||
var sw = Stopwatch.StartNew();
|
||||
while (sw.ElapsedMilliseconds < 2000) { Tick(plugin); Thread.Sleep(1); }
|
||||
long allocMb = (GC.GetAllocatedBytesForCurrentThread() - alloc0) >> 20;
|
||||
int made = plugin.ScriptWorkersCreated(name) - before;
|
||||
string console = plugin.ScriptConsoleText(name);
|
||||
string[] lines = console.Split('\n');
|
||||
int boom = lines.Count(l => l.Contains("boom (expected)", StringComparison.Ordinal));
|
||||
bool loaded = plugin.ScriptIsLoaded(name);
|
||||
string last = lines.LastOrDefault(l => l.StartsWith("seen=", StringComparison.Ordinal))?.Trim() ?? "(no count)";
|
||||
// 300 lines x 2 handlers = 600 threads; errors (6) and sleepers drop or hold workers, the rest reuse.
|
||||
ok = err == null && loaded && boom == 6 && last == "seen=300 slept=3" && made > 0 && made <= 40 && allocMb < 200;
|
||||
Console.WriteLine($"{(ok ? "PASS" : "FAIL")} worker coroutines: 600 handler calls made {made} workers, {allocMb} MB allocated, {boom} handler errors, {last}, {(loaded ? "running" : "stopped")}{(err != null ? ", start error: " + err : "")}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { plugin.StopScript(name); } catch { }
|
||||
runtime.Shutdown();
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
private static void Tick(RynthLuaPlugin plugin)
|
||||
{
|
||||
FakeWorld.W.Step();
|
||||
|
|
|
|||
|
|
@ -107,6 +107,7 @@ namespace RynthLua.ScriptWindowsTests
|
|||
Run("engine parser: truncated, bit-flipped and random submits", ParserFuzz);
|
||||
Run("events into results", Events);
|
||||
Run("Lua: Phase 0 imgui functions and the bench", LuaBench);
|
||||
Run("Lua: hud passes reuse one worker coroutine", HudPassWorkers);
|
||||
Run("Lua: every MVP imgui function, with events", LuaMvpFunctions);
|
||||
Run("Lua: SetNextWindow* by ImGuiCond", LuaWindowCalls);
|
||||
Run("Lua: errors (unsupported, refused, outside a pass)", LuaErrors);
|
||||
|
|
@ -835,6 +836,70 @@ namespace RynthLua.ScriptWindowsTests
|
|||
Check(msg.Type == DataType.String && msg.String.Contains("only work inside a hud's OnRender"), "ImGui outside a pass: " + msg.ToPrintString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hud passes run on pooled worker coroutines (LuaScriptHost): a new MoonSharp coroutine is
|
||||
/// ~1 MB, and a pass every 50 ms made one each time (2026-11-30: a script's 20/s window,
|
||||
/// then a script stopped by the memory guard). 50 good passes take one worker; a pass
|
||||
/// that runs too long, sleeps or errors drops its worker, and the next good pass still draws.
|
||||
/// </summary>
|
||||
private static void HudPassWorkers()
|
||||
{
|
||||
var plugin = new RynthLuaPlugin();
|
||||
ScriptHud? hud = null;
|
||||
var host = new LuaScriptHost(_ => { }, (s, h) => LibraryImGuiValues.Register(s));
|
||||
var ctx = new ScriptContext("hud-workers", null, string.Empty, new ScriptManifest(), host);
|
||||
hud = new ScriptHud(ctx, "Bench", "RynthLua/hud-workers/Bench", ctx.Event("Hud:Bench:OnRender"), ctx.Event("Hud:Bench:OnPreRender"));
|
||||
HudsByHash(plugin)[hud.Hash] = hud;
|
||||
Huds(plugin).Add(hud);
|
||||
host.ResolveModule = (s, name) =>
|
||||
{
|
||||
if (name == "imgui") return CreateImGuiModule(plugin, s);
|
||||
if (name != "views") return null;
|
||||
var fake = new Table(s);
|
||||
fake["OnRender"] = hud.OnRender.CreateTable(s);
|
||||
var huds = new Table(s);
|
||||
huds["CreateHud"] = DynValue.NewCallback((c, a) => DynValue.NewTable(fake));
|
||||
var views = new Table(s);
|
||||
views["Huds"] = DynValue.NewTable(huds);
|
||||
return DynValue.NewTable(views);
|
||||
};
|
||||
host.Run(@"
|
||||
local ImGui = require('imgui'); local views = require('views')
|
||||
mode, passes = 'ok', 0
|
||||
views.Huds.CreateHud('Bench').OnRender.Add(function()
|
||||
passes = passes + 1
|
||||
if mode == 'long' then local x = 0 for i = 1, 10000000 do x = x + i end end
|
||||
if mode == 'sleep' then sleep(10) end
|
||||
if mode == 'error' then error('bad pass') end
|
||||
ImGui.Text('pass ' .. passes)
|
||||
end)", "hud-workers");
|
||||
host.Tick(System.Diagnostics.Stopwatch.GetTimestamp() + System.Diagnostics.Stopwatch.Frequency);
|
||||
Check(host.Loaded, "script loaded: " + host.ConsoleText());
|
||||
|
||||
int made0 = host.WorkersCreated;
|
||||
long alloc0 = GC.GetAllocatedBytesForCurrentThread();
|
||||
for (int i = 0; i < 50; i++) RunPass(plugin, hud);
|
||||
long allocMb = (GC.GetAllocatedBytesForCurrentThread() - alloc0) >> 20;
|
||||
Check(hud.LastError == null, "50 passes ok: " + hud.LastError);
|
||||
Check(host.WorkersCreated - made0 <= 1, $"50 passes, {host.WorkersCreated - made0} new worker(s)");
|
||||
Check(allocMb < 40, $"50 passes allocated {allocMb} MB (a coroutine each was ~100 MB in a 64-bit test)");
|
||||
|
||||
foreach (string bad in new[] { "long", "sleep", "error" })
|
||||
{
|
||||
host.Lua!.Globals["mode"] = bad;
|
||||
RunPass(plugin, hud);
|
||||
Check(hud.LastError != null, $"{bad} pass fails: {hud.LastError}");
|
||||
host.Lua!.Globals["mode"] = "ok";
|
||||
RunPass(plugin, hud);
|
||||
DisplayList l = ParseOne(hud);
|
||||
double n = host.Lua!.Globals.Get("passes").Number;
|
||||
Check(hud.LastError == null && l.OpCount > 0 && S(l, l.Ops[0].Str, l.Ops[0].StrLen) == "pass " + n,
|
||||
$"after a {bad} pass the next one draws 'pass {n}': {hud.LastError}");
|
||||
}
|
||||
Check(host.Loaded, "still running");
|
||||
host.Stop();
|
||||
}
|
||||
|
||||
// ── Lua harness for the imgui module ────────────────────────────
|
||||
|
||||
private sealed class LuaHud
|
||||
|
|
|
|||
Loading…
Reference in a new issue