Snapshot for release 2026.10.28.2 (internal 48c46bd)

This commit is contained in:
Tom Bohar 2026-10-28 19:47:19 -04:00
commit 636adfcef2
41 changed files with 3402 additions and 120 deletions

View file

@ -120,7 +120,7 @@ public partial class BuffManager
}
_bowDequipAttempts++;
if (_worldObjectCache?[bowId] is WorldObject blocker && IsInOffhandSlot(blocker))
OffhandStowed?.Invoke(bowId); // a shield: combat puts it back after
OffhandPutAway(bowId); // a shield: combat puts it back after (and it is buffed in the pack)
_host.MoveItemInternal((uint)bowId, (uint)openPack, 0, 1); // amount>=1 (engine rejects 0)
_weaponSwapGate?.NoteMove(bowId, wieldedNow: true);
_bowDequipPendingId = bowId;

View file

@ -0,0 +1,549 @@
using System;
using System.Collections.Generic;
using RynthCore.PluginSdk;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// The shield's armor spells (2026-10-28). Impenetrability and the seven Banes are cast on the
/// player, and ACE puts them on every worn piece of armor and a worn shield
/// (WorldObject_Magic.TryCastItemEnchantment_WithRedirects). But buffing holds a wand, and ACE won't
/// wield a caster beside a shield: the wand swap puts the shield into a pack first, so the
/// self-cast never reached it. The shield now gets its own casts, aimed at it, after the armor's.
///
/// * Which shield: one in the Items list (the Shield action, or a shield filed as a weapon) that
/// is in use: in the off hand, or put into a pack by buffing's own wand swap (combat puts it
/// back). A listed shield that was in a pack before (not worn) is left alone, as armor in a
/// pack is; an unlisted shield is never a target. No listed shield: nothing here runs.
/// * Which spells: the armor's, Impenetrability and the Banes still in the buff list (the
/// Protections and Banes ticks, or a buff profile), at the level the armor gets. Weapon
/// enchantments never go on the shield. Buff the shield (LegacyUiSettings.BuffShield, on by
/// default) turns it off.
/// * When: on the armor's rules (Rebuff With, Also Refresh Under in a batch, Force Rebuff), on the
/// shield's own timers, recorded from the "You cast X on &lt;shield&gt;" line.
/// * Never at a shield being moved (its pack move or wield not settled, a swap under way).
/// * A cast at the shield that gets no answer twice in a row, or that the server says can't be
/// cast on it, stops shield buffing for ShieldParkTime; the armor is never held up by it.
/// </summary>
public partial class BuffManager
{
/// <summary>The shield's armor spells: keyed by (shield id, spell family), <see cref="ShieldKey"/>.</summary>
private readonly Dictionary<long, ItemSpellRecord> _shieldSpellTimers = new();
internal static long ShieldKey(int shieldId, int family) => ((long)unchecked((uint)shieldId) << 32) | unchecked((uint)family);
// The shield the pending cast is aimed at. Means something only while _pendingSpellId is set:
// every other cast clears it when it is sent.
private int _pendingShieldId;
private bool PendingIsShield => _pendingSpellId != 0 && _pendingShieldId != 0;
// Families confirmed on the shield in this force/batch run, at their level (ClearRunFamilies).
private readonly Dictionary<int, int> _shieldRunLevels = new();
// A family the server refused on the shield (no components, no mana): rested, the armor's not touched.
private readonly Dictionary<int, DateTime> _shieldFamilyRestUntil = new();
// Casts at the shield with no answer in a row; at ShieldNoShowsToPark the shield is parked.
private int _shieldNoShows;
private int _shieldParkedId;
private DateTime _shieldParkedUntil = DateTime.MinValue;
internal const int ShieldNoShowsToPark = 2;
internal static readonly TimeSpan ShieldParkTime = TimeSpan.FromMinutes(30);
// The off-hand item buffing's wand swap put into a pack (combat puts it back on), and when.
// Seen in the off hand again after StowedSightingGraceMs, it is forgotten: the next time it is
// in a pack, something else put it there.
private int _stowedShieldId;
private DateTime _stowedShieldAt = DateTime.MinValue;
private const double StowedSightingGraceMs = 10000;
// ShieldToBuff walks the inventory: its answer is kept ShieldReadMs (the arbiter asks every tick),
// and worked out again at once when the Items list or the cache changes. Tests set ShieldReadMs 0.
internal long ShieldReadMs = 1000;
private int _shieldChoice;
private string _shieldChoiceWhy = "";
private long _shieldChoiceAt = long.MinValue / 2;
private List<ItemRule>? _shieldChoiceRules;
private int _shieldChoiceRuleCount;
private WorldObjectCache? _shieldChoiceCache;
private string _shieldChoiceLogged = "";
/// <summary>Impenetrability (Brogard's Defiance) and the Banes: the armor spells, which a shield takes too.</summary>
internal static bool IsArmorItemSpell(string name) =>
name.IndexOf("Impenetrability", StringComparison.OrdinalIgnoreCase) >= 0
|| name.IndexOf("Brogard's Defiance", StringComparison.OrdinalIgnoreCase) >= 0
|| name.IndexOf(" Bane", StringComparison.OrdinalIgnoreCase) >= 0
|| name.StartsWith("Bane", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Buffing's wand swap put <paramref name="id"/> (the off hand) into a pack: combat puts it back
/// (OffhandStowed), and a shield there is still the one in use, so it is buffed in the pack.
/// </summary>
internal void OffhandPutAway(int id)
{
if (id != 0)
{
_stowedShieldId = id;
_stowedShieldAt = RynthClock.Now;
_shieldChoiceAt = long.MinValue / 2;
}
OffhandStowed?.Invoke(id);
}
/// <summary>The Items list's shields the cache knows, in list order.</summary>
private List<int> ListedShields()
{
var found = new List<int>();
var cache = _worldObjectCache;
if (cache == null) return found;
List<ItemRule> rules;
try { rules = new List<ItemRule>(_settings.ItemRules); }
catch { return found; } // the list edited mid-copy: next read
foreach (var r in rules)
{
if (r.Id == 0 || found.Contains(r.Id)) continue;
var wo = cache[r.Id];
if (wo == null) continue;
if (CombatManager.IsShieldItem(wo) || (WeaponList.IsShieldRule(r) && wo.ObjectClass == AcObjectClass.Armor))
found.Add(r.Id);
}
return found;
}
private bool InInventory(int id)
{
if (_worldObjectCache == null || id == 0) return false;
foreach (var wo in _worldObjectCache.GetDirectInventory())
if (wo.Id == id) return true;
return false;
}
/// <summary>
/// The listed shield to buff now (0 = none) and where it is: the one in the off hand, else the
/// one buffing put into a pack for the wand. <paramref name="fresh"/> reads it again now.
/// </summary>
internal int ShieldToBuff(out string where, bool fresh = false)
{
long now = KitClockMs();
var rules = _settings.ItemRules;
if (!fresh && ReferenceEquals(rules, _shieldChoiceRules) && rules.Count == _shieldChoiceRuleCount
&& ReferenceEquals(_worldObjectCache, _shieldChoiceCache) && now >= _shieldChoiceAt && now - _shieldChoiceAt < ShieldReadMs)
{
where = _shieldChoiceWhy;
return _shieldChoice;
}
int id = FindShieldToBuff(out where, out bool anyListed);
_shieldChoice = id;
_shieldChoiceWhy = where;
_shieldChoiceAt = now;
_shieldChoiceRules = rules;
_shieldChoiceRuleCount = rules.Count;
_shieldChoiceCache = _worldObjectCache;
// One log line when the answer changes, only for a character with a shield listed.
string line = anyListed ? $"{id:X8}|{where}" : "";
if (line != _shieldChoiceLogged)
{
_shieldChoiceLogged = line;
if (anyListed)
_host.Log(id != 0
? $"[Buff] shield: 0x{(uint)id:X8} '{ItemName(id)}' ({where}) takes the armor spells"
: $"[Buff] shield: none buffed ({where})");
}
return id;
}
private int FindShieldToBuff(out string where, out bool anyListed)
{
anyListed = false;
if (!_settings.BuffShield) { where = "Buff the shield is off"; return 0; }
var listed = ListedShields();
anyListed = listed.Count > 0;
if (!anyListed) { where = "no shield listed"; return 0; }
foreach (int id in listed)
{
if (!IsWieldedLive(id)) continue;
if (id == _stowedShieldId && !ShieldMidSwap(id, out _)
&& (RynthClock.Now - _stowedShieldAt).TotalMilliseconds > StowedSightingGraceMs)
_stowedShieldId = 0; // back in the off hand
where = "in the off hand";
return id;
}
if (_stowedShieldId != 0 && listed.Contains(_stowedShieldId) && InInventory(_stowedShieldId))
{
where = "put into a pack for the wand";
return _stowedShieldId;
}
where = "the listed shield is in a pack, not worn";
return 0;
}
/// <summary>
/// True while <paramref name="shieldId"/> may be on its way into or out of a hand: the wand swap
/// under way, the shield's move into a pack not confirmed, or a swap the shared gate says just
/// moved it (combat's off-hand wield or dequip, a held multi-step swap).
/// </summary>
private bool ShieldMidSwap(int shieldId, out string why)
{
if (_wandSwap.Active) { why = "the wand swap is under way"; return true; }
if (_pendingWieldId != 0) { why = "the wand's wield is in flight"; return true; }
if (_bowDequipPendingId == shieldId && shieldId != 0) { why = "its move into a pack is in flight"; return true; }
if (_weaponSwapGate != null && _weaponSwapGate.MayBeMoving(shieldId))
{
why = $"a swap is moving it ({_weaponSwapGate.LastSwapBy})";
return true;
}
why = "";
return false;
}
private bool ShieldParked(int shieldId) =>
shieldId != 0 && shieldId == _shieldParkedId && RynthClock.Now < _shieldParkedUntil;
/// <summary>A family resting after a refusal: on the shield, or for the armor too (no components, a parked family).</summary>
private bool ShieldFamilyResting(int family)
{
DateTime now = RynthClock.Now;
return (_shieldFamilyRestUntil.TryGetValue(family, out DateTime s) && now < s)
|| (_buffFailCooldownUntil.TryGetValue(family, out DateTime a) && now < a);
}
/// <summary>The armor spells of <paramref name="desiredBuffs"/> this character can cast, resolved like the armor's.</summary>
private List<(SpellInfo Spell, string BaseName)> ShieldSpells(List<string> desiredBuffs)
{
var list = new List<(SpellInfo, string)>();
foreach (string baseName in desiredBuffs)
{
if (!IsArmorItemSpell(baseName)) continue; // weapon enchantments never go on the shield
AcSkillType skill = SkillFor(baseName);
if (!IsSkillUsable(skill)) continue;
int spellId = FindBestSpellId(baseName, skill);
if (spellId == 0) continue;
var spell = SpellTableStub.GetById(spellId);
if (spell == null || !IsArmorItemSpell(spell.Name)) continue;
list.Add((spell, baseName));
}
return list;
}
/// <summary>IsBuffActive for the shield: its own timer, the armor's rules.</summary>
private bool IsShieldBuffActive(int shieldId, SpellInfo spell, int? rebufferSecOverride = null)
{
int level = GetSpellLevel(spell);
if (_isForceRebuffing)
{
// Cast on the shield in this run: done, unless a higher level is castable now.
if (_shieldRunLevels.TryGetValue(spell.Family, out int ran)) return UpgradeParked(spell.Family) || level <= ran;
if (!_isAutoBatchRebuff) return false;
rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, _settings.RebuffSecondsRemaining);
}
int rebufferSec = Math.Max(0, rebufferSecOverride ?? _settings.RebuffSecondsRemaining);
if (!_shieldSpellTimers.TryGetValue(ShieldKey(shieldId, spell.Family), out ItemSpellRecord? rec)) return false;
if (rec.SpellLevel < level && !UpgradeParked(spell.Family)) return false; // a higher level: recast, as the armor's
return RynthClock.Now < rec.ExpiresAt.AddSeconds(-rebufferSec);
}
/// <summary>AnyBuffBelowThreshold's shield half: an armor spell on the shield to buff under <paramref name="thresholdSec"/>.</summary>
private bool ShieldBuffBelowThreshold(List<string> desiredBuffs, int thresholdSec)
{
int shield = ShieldToBuff(out _);
if (shield == 0 || ShieldParked(shield)) return false;
foreach (var (spell, _) in ShieldSpells(desiredBuffs))
{
if (ShieldFamilyResting(spell.Family)) continue;
if (!IsShieldBuffActive(shield, spell, thresholdSec)) return true;
}
return false;
}
/// <summary>
/// CheckAndCastSelfBuffs' last step, once every buff on the character is on: the next armor
/// spell the shield needs, aimed at the shield. True when it acted (a cast, or the tick yielded
/// to the wand swap or a move of the shield).
/// </summary>
private bool CastShieldBuffs(List<string> desiredBuffs, bool diagnose)
{
// This step runs on every buff tick: the kept answer first (no inventory walk while
// nothing is due), a fresh read only once a spell is due on the shield.
int shield = ShieldToBuff(out string where);
if (shield == 0) return false;
if (ShieldParked(shield))
{
LastBuffSkipReason = $"shield buffs parked ({(_shieldParkedUntil - RynthClock.Now).TotalMinutes:0} min left)";
return false;
}
var spells = ShieldSpells(desiredBuffs);
if (!spells.Exists(s => !IsShieldBuffActive(shield, s.Spell) && !ShieldFamilyResting(s.Spell.Family))) return false;
int read = ShieldToBuff(out where, fresh: true);
if (read != shield) return read != 0; // another shield (next tick), or none any more
foreach (var (spell, baseName) in spells)
{
if (IsShieldBuffActive(shield, spell)) continue;
if (ShieldFamilyResting(spell.Family))
{
LastBuffSkipReason = $"resting on the shield: {baseName}";
if (diagnose) DiagSkip(baseName + "@shield", $"[FR] skip '{baseName}' on the shield — resting after a refusal");
continue;
}
if (!EnsureMagicMode(forBuff: true))
{
if (_wandSwapExhausted)
{
// The wand can't be wielded now (see the self-buff loop): rest this family on the
// shield so buffing lets go and combat runs.
_shieldFamilyRestUntil[spell.Family] = RynthClock.Now.AddSeconds(BuffFailCooldownSec);
LastBuffSkipReason = $"wand-swap exhausted: {baseName} on the shield";
continue;
}
LastBuffSkipReason = "magic-mode swap in progress (yielding tick)";
return true;
}
// The wand swap may just have put the shield into a pack: where is it now?
int now = ShieldToBuff(out where, fresh: true);
if (now != shield) return now != 0; // another shield (next tick), or none any more
if (ShieldMidSwap(shield, out string moving))
{
LastBuffSkipReason = $"the shield is being moved: {moving}";
return true;
}
// The mana reserve holds these as it holds every buff (see the self-buff loop).
if (_fastChainTick && BuffNeedsManaFirst(spell.Id, out _, out _))
{
_fastChainTick = false;
_chain.HoldForAnimation();
LastBuffSkipReason = "mana reserve before " + baseName + " on the shield: Stamina to Mana waits for the animation";
return true;
}
if (BuffWaitsForMana(spell.Id, baseName))
return true;
SendShieldCast(shield, spell, baseName, where, diagnose);
return true;
}
return false;
}
private void SendShieldCast(int shield, SpellInfo spell, string baseName, string where, bool diagnose)
{
int spellId = spell.Id;
string shieldName = ItemName(shield);
_pendingSpellId = spellId;
_pendingShieldId = shield;
_pendingUpgradeSpellId = 0; // the upgrade bookkeeping is the armor's
_host.WriteToChat($"[RynthAi] Casting: {spell.Name} on {shieldName}", 5);
if (diagnose) _host.Log($"[FR] CAST '{baseName}' on the shield 0x{(uint)shield:X8} '{shieldName}' ({where}) resolvedSpellId={spellId} (pending now set)");
NoteBuffCastMana(SpellManaCost(spellId));
_host.Log($"[Buff] mana {_vitals.CurrentMana}/{_vitals.MaxMana} ({_vitals.ManaPct}%) before {spell.Name} on the shield '{shieldName}' ({where}) (cost {SpellManaCost(spellId)}, reserve {ManaReserve()}, Get Mana At {_settings.GetManaAt}%)");
bool fast = _fastChainTick;
if (fast)
_host.Log($"[BuffChain] '{spell.Name}' on the shield goes without waiting for the animation: {_fastChainWhy}");
int seqAtSend = UseDoneSeqNow();
bool castOk = _host.CastSpellFor(unchecked((uint)shield), spellId, "Buff", $"{spell.Name} on the shield");
_lastCastAttempt = RynthClock.Now;
if (castOk)
{
NoteCastIssued(spellId);
_chain.Sent(spellId, spell.Name, seqAtSend, ActionPacer.Started, ActionPacer.AttacksSent, MoveAudit.MovementSends, fast);
}
else
{
_chain.ClientRefused(spellId, spell.Name, fast, s => _host.Log(s));
_pendingSpellId = 0; // the packet never went out: no answer will come
_pendingShieldId = 0;
LastBuffSkipReason = $"local CastSpell rejected: {baseName} on the shield (id={spellId})";
}
}
/// <summary>An armor spell landed on the shield: its timer, and in a force/batch run the family is done on it.</summary>
private void ShieldSpellLanded(int shieldId, SpellInfo spell)
{
RecordShieldSpell(shieldId, spell);
int level = GetSpellLevel(spell);
if (_isForceRebuffing && (shieldId == _pendingShieldId || shieldId == ShieldToBuff(out _))
&& (!_shieldRunLevels.TryGetValue(spell.Family, out int ran) || level > ran))
_shieldRunLevels[spell.Family] = level;
}
private void RecordShieldSpell(int shieldId, SpellInfo spell)
{
int level = GetSpellLevel(spell);
double duration = GetCustomSpellDuration(level);
var now = RynthClock.Now;
_shieldSpellTimers[ShieldKey(shieldId, spell.Family)] = new ItemSpellRecord
{
CastAt = now,
ExpiresAt = now.AddSeconds(duration),
SpellName = spell.Name,
SpellLevel = level,
};
_host.Log($"[BuffDiag] RECORD '{spell.Name}' on the shield 0x{(uint)shieldId:X8} (fam={spell.Family}, lvl={level}, durSec={duration:F0}, expiresAt={now.AddSeconds(duration):HH:mm:ss})");
SaveBuffTimers();
}
/// <summary>"Flame Bane VI on Kite Shield, refreshing Flame Bane V" -> "Kite Shield"; "" with no target.</summary>
internal static string CastTarget(string afterCast)
{
int on = afterCast.IndexOf(" on ", StringComparison.OrdinalIgnoreCase);
if (on < 0) return "";
string rest = afterCast.Substring(on + 4);
int comma = rest.IndexOf(',');
if (comma >= 0) rest = rest.Substring(0, comma);
return rest.Trim().TrimEnd('.', '!').Trim();
}
private bool NamesShield(string target, int shieldId)
{
string name = _worldObjectCache?[shieldId]?.Name ?? "";
return name.Length == 0 || target.Equals(name, StringComparison.OrdinalIgnoreCase);
}
/// <summary>The listed shield a cast line names (the pending one first), 0 = none.</summary>
private int ListedShieldNamed(string target)
{
if (target.Length == 0) return 0;
var listed = ListedShields();
if (_pendingShieldId != 0 && listed.Contains(_pendingShieldId) && NamesShield(target, _pendingShieldId)
&& (_worldObjectCache?[_pendingShieldId]?.Name ?? "").Length > 0)
return _pendingShieldId;
foreach (int id in listed)
{
string name = _worldObjectCache?[id]?.Name ?? "";
if (name.Length > 0 && target.Equals(name, StringComparison.OrdinalIgnoreCase)) return id;
}
return 0;
}
/// <summary>
/// OnChatWindowText's "You cast X on Y" for the shield, before the armor's handling: the pending
/// shield cast's result, a late line for a listed shield, or a self-cast that reached a worn
/// shield. Records the shield's timer. True when the line is done with here.
/// </summary>
private bool ShieldCastLine(SpellInfo spell, string afterCast)
{
if (!IsArmorItemSpell(spell.Name)) return false;
string target = CastTarget(afterCast);
var pending = PendingIsShield ? SpellTableStub.GetById(_pendingSpellId) : null;
if (pending != null && pending.Family == spell.Family)
{
if (target.Length > 0 && !NamesShield(target, _pendingShieldId))
{
// A late line of the armor's own cast of this family: the armor's; the shield's cast waits.
RecordItemSpellCast(spell);
_host.Log($"[BuffChat] '{spell.Name}' on '{target}' is the armor's, not pending={_pendingSpellId} on the shield - recorded, pending kept.");
return true;
}
ShieldSpellLanded(_pendingShieldId, spell);
_shieldFamilyRestUntil.Remove(spell.Family);
_shieldNoShows = 0;
NoteCastAccepted();
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} (on the shield 0x{(uint)_pendingShieldId:X8}) via ou-cast match name='{spell.Name}'");
_pendingSpellId = 0;
_pendingShieldId = 0;
_onCastResolved?.Invoke($"cast '{spell.Name}' on the shield");
return true;
}
int named = ListedShieldNamed(target);
if (named == 0) return false;
ShieldSpellLanded(named, spell);
// A self-cast of this family that reached a worn shield: the armor's result as well.
var selfPending = _pendingSpellId != 0 && !PendingIsShield ? SpellTableStub.GetById(_pendingSpellId) : null;
if (selfPending != null && selfPending.Family == spell.Family) return false;
_host.Log($"[BuffChat] '{spell.Name}' on the shield '{target}' - a late line, recorded{(_pendingSpellId != 0 ? $"; pending={_pendingSpellId} kept" : "")}.");
return true;
}
/// <summary>The pending shield cast was refused or fizzled: the armor's timers and families are left alone.</summary>
private void ShieldCastRefused(SpellInfo? spell, string why, double restSec)
{
if (spell != null && restSec > 0)
_shieldFamilyRestUntil[spell.Family] = RynthClock.Now.AddSeconds(restSec);
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} on the shield 0x{(uint)_pendingShieldId:X8} - {why}" +
(restSec > 0 ? $"; {spell?.Name} rests on the shield {restSec:0}s." : "; tried again."));
}
/// <summary>The pending shield cast got no answer in time (the tick's no-chat give-up).</summary>
private void ShieldCastNoShow(SpellInfo? spell)
{
int shield = _pendingShieldId;
_shieldNoShows++;
if (_shieldNoShows >= ShieldNoShowsToPark)
{
_shieldNoShows = 0;
ParkShield(shield, $"{ShieldNoShowsToPark} casts on it got no answer");
}
else
_host.Log($"[BuffChat] NO-CHAT TIMEOUT (shield) pending={_pendingSpellId} ('{spell?.Name}') on 0x{(uint)shield:X8} - " +
$"no answer in {NoChatResolveTimeoutMs:0}ms ({_shieldNoShows}/{ShieldNoShowsToPark} before shield buffing rests).");
}
private void ParkShield(int shield, string why)
{
_shieldParkedId = shield;
_shieldParkedUntil = RynthClock.Now + ShieldParkTime;
_host.Log($"[Buff] shield 0x{(uint)shield:X8} '{ItemName(shield)}': {why} - not buffing it for {ShieldParkTime.TotalMinutes:0} min.");
_host.WriteToChat($"[RynthAi] Not buffing the shield '{ItemName(shield)}' for {ShieldParkTime.TotalMinutes:0} min ({why}).", 2);
}
/// <summary>Force Rebuff: the shield starts over too.</summary>
private void ResetShieldBuffs()
{
_shieldSpellTimers.Clear();
_shieldRunLevels.Clear();
_shieldFamilyRestUntil.Clear();
_shieldNoShows = 0;
_shieldParkedId = 0;
_shieldParkedUntil = DateTime.MinValue;
_pendingShieldId = 0;
}
/// <summary>bufftimers.txt lines for the shield: "shield|id|family|castTicks|expiresTicks|level|name".</summary>
private void SaveShieldTimers(List<string> lines)
{
foreach (var kvp in _shieldSpellTimers)
{
var info = kvp.Value;
uint id = unchecked((uint)(kvp.Key >> 32));
int family = unchecked((int)(kvp.Key & 0xFFFFFFFF));
lines.Add($"shield|{id}|{family}|{info.CastAt.Ticks}|{info.ExpiresAt.Ticks}|{info.SpellLevel}|{info.SpellName}");
}
}
/// <summary>One "shield|..." line of bufftimers.txt; false when the line is something else.</summary>
private bool LoadShieldTimer(string[] p)
{
if (p[0] != "shield") return false;
if (p.Length < 7) return true;
if (!uint.TryParse(p[1], out uint id) || !int.TryParse(p[2], out int family)
|| !long.TryParse(p[3], out long cast) || !long.TryParse(p[4], out long expires) || !int.TryParse(p[5], out int level))
return true;
var expiresAt = new DateTime(expires);
if (expiresAt > RynthClock.Now)
_shieldSpellTimers[ShieldKey(unchecked((int)id), family)] = new ItemSpellRecord
{
CastAt = new DateTime(cast), ExpiresAt = expiresAt, SpellLevel = level, SpellName = p[6],
};
return true;
}
/// <summary>/ra buffs and /ra buffs item: the shield's timers.</summary>
private void PrintShieldSpellTimers()
{
if (_shieldSpellTimers.Count == 0) return;
_host.WriteToChat($"[RynthAi] -- Shield spells ({_shieldSpellTimers.Count}) --", 1);
foreach (var kvp in _shieldSpellTimers)
{
var info = kvp.Value;
int id = unchecked((int)(uint)(kvp.Key >> 32));
TimeSpan left = info.ExpiresAt - RynthClock.Now;
_host.WriteToChat(left.TotalSeconds <= 0
? $"[RynthAi] {ItemName(id)}: {info.SpellName} (Lvl {info.SpellLevel}): EXPIRED"
: $"[RynthAi] {ItemName(id)}: {info.SpellName} (Lvl {info.SpellLevel}): {Math.Round(left.TotalMinutes, 1)}m left / {Math.Round((info.ExpiresAt - info.CastAt).TotalMinutes, 0)}m total", 1);
}
}
/// <summary>Shield spell timers recorded (tests, status).</summary>
internal int ShieldSpellCount => _shieldSpellTimers.Count;
}

View file

@ -916,6 +916,9 @@ public partial class BuffManager : IDisposable
var info = kvp.Value;
lines.Add($"item|{kvp.Key}|{info.CastAt.Ticks}|{info.ExpiresAt.Ticks}|{info.SpellLevel}|{info.SpellName}");
}
// Last: a build from before the shield's lines reads them as old-style lines that
// expired long ago (no exception, so the lines above are loaded either way).
SaveShieldTimers(lines);
// The "char doesn't know this spell" blacklist is NO LONGER persisted.
// Persisting it meant one lag-induced no-chat timeout permanently
// poisoned a KNOWN spell across all future sessions, collapsing the
@ -934,9 +937,11 @@ public partial class BuffManager : IDisposable
{
_ramBuffTimers.Clear();
_itemSpellTimers.Clear();
_shieldSpellTimers.Clear();
foreach (string line in System.IO.File.ReadAllLines(_buffTimerPath))
{
string[] p = line.Split('|');
if (LoadShieldTimer(p)) continue;
if (p[0] == "item" && p.Length >= 6)
{
@ -973,9 +978,10 @@ public partial class BuffManager : IDisposable
_ramBuffTimers[family] = new RamTimerInfo { Expiration = expiration, SpellLevel = level, SpellName = name };
}
}
int total = _ramBuffTimers.Count + _itemSpellTimers.Count;
int total = _ramBuffTimers.Count + _itemSpellTimers.Count + _shieldSpellTimers.Count;
if (total > 0)
_host.WriteToChat($"[RynthAi] Restored {_ramBuffTimers.Count} player + {_itemSpellTimers.Count} item spell timer(s).", 1);
_host.WriteToChat($"[RynthAi] Restored {_ramBuffTimers.Count} player + {_itemSpellTimers.Count} item spell timer(s)" +
(_shieldSpellTimers.Count > 0 ? $" + {_shieldSpellTimers.Count} on the shield." : "."), 1);
}
catch { }
}
@ -1020,6 +1026,7 @@ public partial class BuffManager : IDisposable
_upgradeParkedUntil.Clear();
_ramBuffTimers.Clear();
_itemSpellTimers.Clear();
ResetShieldBuffs(); // the shield's timers, rests and park too
EndPendingUpgrade(_pendingSpellId, "a new Force Rebuff");
_pendingSpellId = 0;
_lastCastAttempt = DateTime.MinValue;
@ -1522,6 +1529,20 @@ public partial class BuffManager : IDisposable
// switch in mid-cast.
if (_pendingSpellId != 0) { TryEmergencyHealWhilePending(); Hold("buff cast in flight", pendingSpell.Name); return; }
}
else if (pendingIsArmor && PendingIsShield)
{
// An armor spell aimed at the shield (BuffManager.Shield.cs): chat is authoritative,
// as for the armor, but a give-up counts against the shield only. No blacklist (the
// same spell just went on the armor) and no family park for the armor.
if (PendingGiveUpReached(NoChatResolveTimeoutMs))
{
ShieldCastNoShow(pendingSpell);
_pendingSpellId = 0;
_pendingShieldId = 0;
_onCastResolved?.Invoke("no-chat timeout (shield)");
}
if (_pendingSpellId != 0) { TryEmergencyHealWhilePending(); Hold("item spell in flight", pendingSpell?.Name ?? ""); return; }
}
else if (pendingIsArmor)
{
// ARMOR/ITEM: chat is authoritative. No-chat valve abandons a cast
@ -2299,6 +2320,7 @@ public partial class BuffManager : IDisposable
// ever come; setting pending anyway waited 2.5 s and counted a no-show
// strike. Mirror the buff path: not handled, so the potion gets its turn.
_pendingSpellId = spellId;
_pendingShieldId = 0; // on the player, not the shield
_pendingVitalSpellId = spellId; // instant: confirmed by chat, never by the registry
_pendingVitalLabel = label;
_pendingVitalBase = what;
@ -2785,7 +2807,8 @@ public partial class BuffManager : IDisposable
continue;
if (!IsBuffActive(spellId, thresholdSec)) return true;
}
return false;
// The shield's armor spells start a batch the same way (BuffManager.Shield.cs).
return ShieldBuffBelowThreshold(desiredBuffs, thresholdSec);
}
// "[FR] skip ..." lines while a rebuff runs: the selector runs every tick (~30 ms), and a
@ -2912,6 +2935,7 @@ public partial class BuffManager : IDisposable
int upgradeFrom = spellInfo != null && buffFamily != 0 ? ActiveLevelBelow(buffFamily, upgradeTo) : 0;
_pendingSpellId = spellId;
_pendingShieldId = 0; // on the player, not the shield
if (buffFamily != 0)
{
_lastCastSpellIdByFamily[buffFamily] = spellId;
@ -2967,7 +2991,8 @@ public partial class BuffManager : IDisposable
}
return true;
}
return false;
// Everything on the character is on: the shield's armor spells (BuffManager.Shield.cs).
return CastShieldBuffs(desiredBuffs, diagnose);
}
/// <summary>Casts that replaced an active buff of the same family at a lower level (tests, status).</summary>
@ -3310,6 +3335,7 @@ public partial class BuffManager : IDisposable
{
_forceRebuffCastFamilies.Clear();
_runConfirmedLevelByFamily.Clear();
_shieldRunLevels.Clear();
}
/// <summary>
@ -3572,10 +3598,12 @@ public partial class BuffManager : IDisposable
// left them "active" for up to an hour and the bot fought unbuffed (reported as
// "buffing skips missile weapons"). The player's registry dropping to zero (a death,
// or logging in after one) is the signal: forget them so they get recast.
if (count == 0 && _lastLivePlayerEnchantCount != 0 && _itemSpellTimers.Count > 0)
if (count == 0 && _lastLivePlayerEnchantCount != 0 && (_itemSpellTimers.Count > 0 || _shieldSpellTimers.Count > 0))
{
_host.Log($"[BuffDiag] player enchantments dropped to 0 (was {_lastLivePlayerEnchantCount}) - clearing {_itemSpellTimers.Count} item-spell timer(s) so weapon/armor buffs recast");
_host.Log($"[BuffDiag] player enchantments dropped to 0 (was {_lastLivePlayerEnchantCount}) - clearing {_itemSpellTimers.Count} item-spell timer(s)" +
$"{(_shieldSpellTimers.Count > 0 ? $" and {_shieldSpellTimers.Count} on the shield" : "")} so weapon/armor buffs recast");
_itemSpellTimers.Clear();
_shieldSpellTimers.Clear();
}
_lastLivePlayerEnchantCount = count;
@ -3808,7 +3836,7 @@ public partial class BuffManager : IDisposable
_host.WriteToChat($"[RynthAi] ServerTime={Math.Round(serverNow)} (no live read: serverTime=0 or API missing)", 1);
}
if (_ramBuffTimers.Count == 0 && _itemSpellTimers.Count == 0)
if (_ramBuffTimers.Count == 0 && _itemSpellTimers.Count == 0 && _shieldSpellTimers.Count == 0)
{
_host.WriteToChat("[RynthAi] No buff timers active.", 1);
return;
@ -3819,6 +3847,7 @@ public partial class BuffManager : IDisposable
_host.WriteToChat($"[RynthAi] -- Item spells ({_itemSpellTimers.Count}) --", 1);
PrintItemSpellTimers();
}
PrintShieldSpellTimers();
if (_ramBuffTimers.Count > 0)
{
@ -3882,13 +3911,17 @@ public partial class BuffManager : IDisposable
public void PrintItemBuffDebug()
{
if (_itemSpellTimers.Count == 0)
if (_itemSpellTimers.Count == 0 && _shieldSpellTimers.Count == 0)
{
_host.WriteToChat("[RynthAi] No item spell timers recorded yet.", 1);
return;
}
_host.WriteToChat($"[RynthAi] -- Item spells ({_itemSpellTimers.Count}) --", 1);
PrintItemSpellTimers();
if (_itemSpellTimers.Count > 0)
{
_host.WriteToChat($"[RynthAi] -- Item spells ({_itemSpellTimers.Count}) --", 1);
PrintItemSpellTimers();
}
PrintShieldSpellTimers();
}
private void PrintItemSpellTimers()
@ -4228,8 +4261,9 @@ public partial class BuffManager : IDisposable
// Only clear pending if this enchantment matches what we were casting.
// Armor/item enchantments fire on the item, not the player — clearing
// _pendingSpellId unconditionally would lose track of pending item casts
// and prevent the chat handler from recording their timers.
if (_pendingSpellId != 0)
// and prevent the chat handler from recording their timers. A cast at the shield never
// lands on the player: only its chat line resolves it.
if (_pendingSpellId != 0 && !PendingIsShield)
{
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
if (pendingSpell != null && pendingSpell.Family == spellInfo.Family)
@ -4368,12 +4402,12 @@ public partial class BuffManager : IDisposable
else if (_pendingSpellId != 0)
{
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name))
if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name) && !PendingIsShield) // the shield's refusal leaves the armor's timer
{
_itemSpellTimers.Remove(pendingSpell.Family);
SaveBuffTimers();
}
_host.Log($"[BuffChat] PARKED pending={_pendingSpellId} — AC too busy (cast gesture in progress); throttle kept, backing off before re-issue.");
_host.Log($"[BuffChat] PARKED pending={_pendingSpellId}{(PendingIsShield ? " (on the shield)" : "")} — AC too busy (cast gesture in progress); throttle kept, backing off before re-issue.");
if (_pendingSpellId != _pendingVitalSpellId)
_chain.TooBusyLine(_pendingSpellId, s => _host.Log(s));
}
@ -4432,6 +4466,14 @@ public partial class BuffManager : IDisposable
_noComponentsUntil[_pendingSpellId] = RynthClock.Now.AddSeconds(NoComponentsLevelSec);
_host.WriteToChat($"[RynthAi] No components for {pendingSpell.Name}: using a lower level for {NoComponentsLevelSec / 60:0} min.", 2);
}
else if (pendingSpell != null && PendingIsShield)
{
// Aimed at the shield: the family rests on the shield only; the armor's is on.
bool noComps = lower.Contains("components") || lower.Contains("missing some required");
ShieldCastRefused(pendingSpell, "hard rejection", BuffFailCooldownSec);
_host.WriteToChat($"[RynthAi] Skipping {pendingSpell.Name} on the shield for {BuffFailCooldownSec / 60:0} min " +
$"({(noComps ? "no components for it" : "the server refused it")}).", 2);
}
else if (pendingSpell != null)
{
if (IsItemEnchantment(pendingSpell.Name))
@ -4481,7 +4523,9 @@ public partial class BuffManager : IDisposable
return;
}
double restSec = LowManaFamilyRestSec;
if (pendingSpell != null)
if (pendingSpell != null && PendingIsShield)
ShieldCastRefused(pendingSpell, "not enough mana", restSec); // rests on the shield; the armor's timer stays
else if (pendingSpell != null)
{
if (IsItemEnchantment(pendingSpell.Name))
{
@ -4515,12 +4559,12 @@ public partial class BuffManager : IDisposable
if (_pendingSpellId != 0)
{
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name))
if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name) && !PendingIsShield) // a fizzle at the shield leaves the armor's timer
{
_itemSpellTimers.Remove(pendingSpell.Family);
SaveBuffTimers();
}
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} via soft-fail in '{text}'");
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId}{(PendingIsShield ? " (on the shield)" : "")} via soft-fail in '{text}'");
}
_lastCastAttempt = DateTime.MinValue;
EndPendingUpgrade(_pendingSpellId, "fizzled");
@ -4529,6 +4573,19 @@ public partial class BuffManager : IDisposable
return;
}
// "Flame Bane VI cannot be cast on Kite Shield." (ACE IsInvalidTarget: an item that takes no
// spells). Read only for a cast at the shield: shield buffing rests; the armor carries on.
if (PendingIsShield && lower.Contains(" cannot be cast on "))
{
_cast.Result(null, "refused by the server", atStart: true);
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} on the shield 0x{(uint)_pendingShieldId:X8} - '{text}'");
ParkShield(_pendingShieldId, "the server says these spells can't be cast on it");
_pendingSpellId = 0;
_pendingShieldId = 0;
_onCastResolved?.Invoke("can't be cast on the shield");
return;
}
// A script heal (a transfer such as Vitality Siphon) cast at a monster that resists it:
// "Doorheld Surveyor resists your spell" is its only result, no "due to casting" line
// follows. Closed here as CombatManager reads the same line for its own casts.
@ -4605,6 +4662,11 @@ public partial class BuffManager : IDisposable
if (spellInfo == null && _pendingSpellId != 0)
spellInfo = SpellTableStub.GetById(_pendingSpellId);
// An armor spell's line for the shield (its own cast, a late line, or a self-cast that
// reached a worn shield) goes on the shield's timer, not the armor's (BuffManager.Shield.cs).
if (spellInfo != null && !viaDueToCasting && ShieldCastLine(spellInfo, afterCast))
return;
// A result that names another spell than the pending one is not the pending cast's
// result: the pending cast keeps waiting for its own (or its give-up time).
var pendingInfo = _pendingSpellId != 0 ? SpellTableStub.GetById(_pendingSpellId) : null;
@ -5428,7 +5490,7 @@ public partial class BuffManager : IDisposable
return WandSwapFailed(_wandSwap.Abandon("no pack with room"), forBuff, wandId, now);
}
bool offhand = hands.TryGetValue(step.Id, out int slot) && (slot & HandSwapSequence.ShieldSlot) != 0;
if (offhand) OffhandStowed?.Invoke(step.Id); // combat puts it back after
if (offhand) OffhandPutAway(step.Id); // combat puts it back after (and it is buffed in the pack)
_host.MoveItemInternal((uint)step.Id, (uint)pack, 0, 1); // amount>=1 (engine rejects 0)
_wandSwap.Sent(step, now);
_wandSwapLastMoved = step.Id;
@ -5554,7 +5616,7 @@ public partial class BuffManager : IDisposable
if (!_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "wand swap burst: peace, the hands and the wand at once")) return 1;
foreach (int id in moves)
{
if (hands.TryGetValue(id, out int slot) && (slot & HandSwapSequence.ShieldSlot) != 0) OffhandStowed?.Invoke(id);
if (hands.TryGetValue(id, out int slot) && (slot & HandSwapSequence.ShieldSlot) != 0) OffhandPutAway(id);
_host.PutItemInContainer(unchecked((uint)id), unchecked((uint)pack), 0);
}
_host.WieldItem(unchecked((uint)wandId), HeldSlot);

View file

@ -147,6 +147,22 @@ public sealed class WeaponSwapGate
}
}
/// <summary>
/// True while <paramref name="itemId"/> may still be on its way into or out of a hand: a
/// multi-step swap holds the gate, or the last claimed swap noted a move of this item and the
/// next swap would still wait for it (MinIntervalMs). Buffing doesn't aim a spell at a shield
/// then (BuffManager.Shield.cs).
/// </summary>
public bool MayBeMoving(int itemId)
{
long now = NowMs();
lock (_lock)
{
if (_heldBy.Length > 0 && now < _heldUntilMs) return true;
return itemId != 0 && _movingId == itemId && now - _lastSwapTickMs < MinIntervalMs;
}
}
/// <summary>Milliseconds since the last successful swap (diagnostics).</summary>
public long MsSinceLastSwap
{

View file

@ -1006,6 +1006,13 @@ internal sealed class LegacyAdvancedSettingsUi
}
ImGui.EndTable();
}
ImGui.Checkbox("Buff the shield", ref _settings.BuffShield);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Cast the ticked Impenetrability and Banes on your shield too, after\n" +
"the armor, renewed with it. The shield is the one in the Items list\n" +
"(Shield) that you wear: buffing puts it in a pack for the wand, so it\n" +
"is buffed there. On by default. No shield listed: nothing changes.");
ImGui.Spacing();
ImGui.Separator();

View file

@ -2055,7 +2055,8 @@ internal sealed partial class LegacyDashboardRenderer
dst.FastBuffChain = tmp.FastBuffChain;
dst.SkipUnusableBuffs = tmp.SkipUnusableBuffs;
dst.DisabledBuffs = tmp.DisabledBuffs;
dst.BlacklistAttempts = tmp.BlacklistAttempts;
dst.BuffShield = tmp.BuffShield;
dst.BlacklistAttempts = tmp.BlacklistAttempts;
dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec;
// 0 is never meant (every UI floors it at 250+) and is what the Settings-panel bug
// saved into profiles: it judges each cast before its damage can land.
@ -2870,6 +2871,7 @@ internal sealed partial class LegacyDashboardRenderer
switch (cmd.Cmd)
{
case "startNav":
_settings.RearmFinishedNavRoute(); // the player's Start Navigation re-runs a finished Once route
_settings.IsMacroRunning = true;
_settings.EnableNavigation = true;
if (_settings.BotAction != "Navigating")
@ -3202,7 +3204,12 @@ internal sealed partial class LegacyDashboardRenderer
{
case 0: _settings.EnableCombat = enabled; break;
case 1: _settings.EnableBuffing = enabled; break;
case 2: _settings.EnableNavigation = enabled; break;
case 2:
// The player switching nav on over a finished Once route re-runs it (a meta's
// enablenav doesn't, NavigationEngine.HandleRouteEnd).
if (enabled && !_settings.EnableNavigation) _settings.RearmFinishedNavRoute();
_settings.EnableNavigation = enabled;
break;
case 3: _settings.EnableLooting = enabled; break;
case 4: _settings.EnableMeta = enabled; break;
}

View file

@ -63,6 +63,7 @@ internal sealed class LegacyNavigationUi
ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(0.08f, 0.28f, 0.08f, 1f));
if (ImGui.Button("Start Navigation", new Vector2(-1, 28)))
{
_settings.RearmFinishedNavRoute(); // a finished Once route runs again
_settings.IsMacroRunning = true;
_settings.EnableNavigation = true;
if (_settings.BotAction != "Navigating")

View file

@ -389,6 +389,14 @@ public sealed class LegacyUiSettings
else next.Add(buffBaseName);
_disabledBuffs = next;
}
/// <summary>
/// Cast the armor spells (Impenetrability and the Banes still ticked above) on the shield
/// listed in the Items list too, after the armor, on the armor's timers (BuffManager.Shield.cs).
/// The self-cast never reaches it: ACE won't wield the wand beside a shield, so buffing puts
/// the shield into a pack first. On by default; a profile saved before this setting existed
/// loads it as on. No shield listed: nothing changes.
/// </summary>
public bool BuffShield = true;
public bool StartMacroOnLogin;
public bool PatrolOnLogin;
/// <summary>
@ -726,6 +734,32 @@ public sealed class LegacyUiSettings
[JsonIgnore] public NavRouteParser CurrentRoute { get; set; } = new();
public int ActiveNavIndex;
/// <summary>
/// True for a Once route that has walked off its last point (the nav engine leaves the
/// index past the end). It stays finished over a macro stop/start and a meta turning nav
/// on, until it is loaded again, edited, or restarted (/ra nav restart, or
/// <see cref="RearmFinishedNavRoute"/> from the player's own nav-on controls).
/// </summary>
public bool NavRouteFinished()
{
var route = CurrentRoute;
return route != null && route.RouteType == NavRouteType.Once
&& route.Points.Count > 0 && ActiveNavIndex >= route.Points.Count;
}
/// <summary>
/// The player turned nav on (the Nav switch, a Start Navigation button): a finished Once
/// route runs again from [0], as re-enabling nav did before 2026-10-28. Metas and scripts
/// that switch nav on don't call this, so a stop/start replaying a meta's
/// "/vt opt set enablenav true" no longer re-runs a finished route. True if it rewound.
/// </summary>
public bool RearmFinishedNavRoute()
{
if (!NavRouteFinished()) return false;
ActiveNavIndex = 0;
return true;
}
public bool ShowAdvancedWindow;
public int SelectedAdvancedTab;

View file

@ -3701,6 +3701,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),
["BuffShield"] = (() => B(s.BuffShield), v => s.BuffShield = ToDouble(v) != 0),
// AutoVendor (UB names map here through /ub opt: AutoVendor.Enabled -> AutoVendorEnabled, ...)
["AutoVendorEnabled"] = (() => B(s.AutoVendorEnabled), v => s.AutoVendorEnabled = ToDouble(v) != 0),
["AutoVendorEnableBuying"] = (() => B(s.AutoVendorEnableBuying), v => s.AutoVendorEnableBuying = ToDouble(v) != 0),

View file

@ -76,6 +76,22 @@ internal sealed class MetaManager
private long _evalChatSeq; // newest chat line its condition matched
private Match? _lastChatMatch;
// ── Macro stop/start replay ──────────────────────────────────────────────
// Starting the macro re-arms every rule of the state it is in (so a meta puts back a
// route the player changed or cleared while it was stopped). The rules that had already
// fired in that state before the stop "replay" when they fire again. A replayed nav load
// (EmbedNav, /vt nav load, /ra nav load) of the route that is still loaded and unchanged
// keeps the route where it was: its waypoint, a Linear route's direction, a finished
// Once route finished; a replayed "/ra nav restart" is skipped. Reloading here restarted
// Once routes on every stop/start (2026-10-28). Cleared by the next real state entry; a
// rule that first fires after the start is not a replay, and its nav load starts the
// route fresh as before.
private readonly HashSet<MetaRule> _replayRules = new(ReferenceEqualityComparer.Instance);
private bool _replaying; // the action running now belongs to a replayed rule
/// <summary>Where a meta's nav names are looked for as .nav files. Tests point it at a scratch folder.</summary>
internal string NavFolder { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
// ── Call stack (CallMetaState / ReturnFromCall) ──────────────────────────
private readonly Stack<string> _stateStack = new();
@ -236,6 +252,73 @@ internal sealed class MetaManager
? 0
: FindNearestWaypoint(route);
/// <summary>
/// A replayed nav load (see <see cref="_replayRules"/>): true, and nothing reloaded, when
/// <paramref name="path"/> is the route loaded now and it still has the points of its source
/// <paramref name="source"/> (not edited, reversed or swapped for another since). The route
/// keeps its waypoint and a Linear route its direction (the engine sees the same route
/// object); nav is switched on as the load would, except for a finished Once route, which
/// stays finished. False: the caller loads the route fresh, as before.
/// </summary>
private bool KeepRunningRoute(string path, NavRouteParser source, string what)
{
var cur = _settings.CurrentRoute;
if (cur == null || cur.Points.Count == 0 || source.Points.Count == 0) return false;
if (!SameNavPath(_settings.CurrentNavPath, path)) return false;
if (!SameLines(cur.ToLines(), source.ToLines())) return false;
bool finished = _settings.NavRouteFinished();
if (!finished) _settings.EnableNavigation = true;
RynthLog.Write(LogCat.Meta, finished
? $"[Meta] {what}: the macro started again on the same route, which is finished - it stays finished (/ra nav restart re-runs it)"
: $"[Meta] {what}: the macro started again on the same route - it carries on at [{_settings.ActiveNavIndex}] instead of starting over");
return true;
}
/// <summary>A replayed "/vt nav load" or "/ra nav load" of the .nav file that is still the loaded, unchanged route.</summary>
private bool KeepRunningNavFile(string rawName)
{
string name = NewProfileFiles.Tidy(rawName, NewProfileFiles.NavExtensions, out _);
if (NewProfileFiles.Validate(name) != null) return false;
string path = Path.Combine(NavFolder, name + ".nav");
if (!File.Exists(path)) return false;
return KeepRunningRoute(path, NavRouteParser.Load(path), $"nav load '{name}'");
}
/// <summary>
/// A replayed /ra nav command that would start the route over: "/ra nav load" of the running,
/// unchanged route, or "/ra nav restart". True: skipped, the nav stays where it was.
/// </summary>
private bool SkipReplayedNavCommand(string cmd)
{
string[] parts = cmd.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 3 || !parts[1].Equals("nav", StringComparison.OrdinalIgnoreCase)) return false;
if (parts[2].Equals("restart", StringComparison.OrdinalIgnoreCase))
{
RynthLog.Write(LogCat.Meta, "[Meta] /ra nav restart: not run again for the macro start (it ran when the rule first fired)");
return true;
}
return parts[2].Equals("load", StringComparison.OrdinalIgnoreCase) && parts.Length >= 4
&& KeepRunningNavFile(string.Join(" ", parts, 3, parts.Length - 3));
}
private static bool SameNavPath(string? a, string? b)
{
if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b)) return false;
if (string.Equals(a, b, StringComparison.OrdinalIgnoreCase)) return true;
if (a.StartsWith('<') || b.StartsWith('<')) return false; // "<embedded:...>" is not a file
try { return string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), StringComparison.OrdinalIgnoreCase); }
catch { return false; }
}
private static bool SameLines(List<string> a, List<string> b)
{
if (a.Count != b.Count) return false;
for (int i = 0; i < a.Count; i++)
if (!string.Equals(a[i], b[i], StringComparison.Ordinal)) return false;
return true;
}
public ExpressionEngine Expressions => _expressions ??= CreateExpressionEngine();
private ExpressionEngine CreateExpressionEngine()
@ -312,7 +395,10 @@ internal sealed class MetaManager
// Macro just started — force reset so rules re-evaluate even if state
// name matches where we stopped. Otherwise HasFired stays latched across
// a stop/start cycle and IF:Always rules like EmbedNav never re-fire.
if (!_lastMacroRunning)
// The rules that had already fired replay (see _replayRules): a replayed nav
// load of the route still running keeps its place instead of starting it over.
bool macroStarted = !_lastMacroRunning;
if (macroStarted)
_settings.ForceStateReset = true;
_lastMacroRunning = true;
@ -343,9 +429,21 @@ internal sealed class MetaManager
_statePStartTime = _statePResume is double resumed ? Clock().AddSeconds(-resumed) : Clock();
_statePResume = null;
_settings.ForceStateReset = false;
// A bare stop/start (no state entry, no meta load pending) replays the rules that
// had fired; any other reset is a real state entry and nothing is a replay.
bool replay = macroStarted && !realStateEntry && !metaReloaded;
lock (_settings.MetaRulesLock)
foreach (var r in _settings.MetaRules) r.HasFired = false;
{
_replayRules.Clear();
foreach (var r in _settings.MetaRules)
{
if (replay && r.HasFired) _replayRules.Add(r);
r.HasFired = false;
}
}
}
else if (stateChanged)
_replayRules.Clear();
_lastState = _settings.CurrentState;
double secondsInState = (Clock() - _stateStartTime).TotalSeconds;
@ -434,7 +532,9 @@ internal sealed class MetaManager
if (_settings.MetaDebug)
_host.WriteToChat($"[Meta] {rule.State} | {DescribeCondition(rule)} → {DescribeAction(rule)}", 1);
ExecuteAction(rule);
_replaying = _replayRules.Contains(rule);
try { ExecuteAction(rule); }
finally { _replaying = false; }
// If state changed during this action, stop evaluating further rules this tick
if (_settings.CurrentState != _lastState || _settings.ForceStateReset)
@ -888,7 +988,10 @@ internal sealed class MetaManager
if (cmd.StartsWith("/ra ", StringComparison.OrdinalIgnoreCase)
|| cmd.Equals("/ra", StringComparison.OrdinalIgnoreCase))
{
_raCommandHandler?.Invoke(cmd);
// A replayed "/ra nav load" of the route still running, or "/ra nav restart",
// would start the route over: skipped.
if (!(_replaying && SkipReplayedNavCommand(cmd)))
_raCommandHandler?.Invoke(cmd);
}
else if (_host.HasInvokeChatParser)
_host.InvokeChatParser(cmd);
@ -977,7 +1080,7 @@ internal sealed class MetaManager
// circular hunt through every cell of this dungeon, no nav file). The Meta panel
// offers it first in Embedded Nav Route's list. A real route called Patrol wins.
if (IsPatrolRoute(routeName) && !_settings.EmbeddedNavs.ContainsKey(routeName)
&& !File.Exists(Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles", routeName + ".nav")))
&& !File.Exists(Path.Combine(NavFolder, routeName + ".nav")))
{
_host.Log("[Meta] EmbedNav: Patrol -> /ra dunnav-patrol");
if (_raCommandHandler != null) _raCommandHandler("/ra dunnav-patrol");
@ -1002,6 +1105,8 @@ internal sealed class MetaManager
if (_settings.EmbeddedNavs.TryGetValue(routeName, out var embedded))
{
var newRoute = NavRouteParser.LoadFromLines(embedded);
// The macro was started again: the route still running keeps its place.
if (_replaying && KeepRunningRoute($"<embedded:{routeName}>", newRoute, $"EmbedNav '{routeName}'")) break;
_settings.CurrentNavPath = $"<embedded:{routeName}>";
_settings.CurrentRoute = newRoute;
_settings.ActiveNavIndex = StartIndexForRoute(newRoute);
@ -1012,11 +1117,11 @@ internal sealed class MetaManager
}
// Fallback: a standalone .nav file in NavProfiles.
string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
string fullPath = Path.Combine(navFolder, routeName + ".nav");
string fullPath = Path.Combine(NavFolder, routeName + ".nav");
if (File.Exists(fullPath))
{
var newRoute = NavRouteParser.Load(fullPath);
if (_replaying && KeepRunningRoute(fullPath, newRoute, $"EmbedNav file '{routeName}'")) break;
_settings.CurrentNavPath = fullPath;
_settings.CurrentRoute = newRoute;
_settings.ActiveNavIndex = StartIndexForRoute(newRoute);
@ -1257,6 +1362,9 @@ internal sealed class MetaManager
|| parts[2].Equals("save", StringComparison.OrdinalIgnoreCase)))
{
string name = string.Join(" ", parts, 3, parts.Length - 3);
// The macro was started again: the route still running keeps its place.
if (_replaying && parts[2].Equals("load", StringComparison.OrdinalIgnoreCase) && KeepRunningNavFile(name))
return true;
_raCommandHandler?.Invoke($"/ra nav {parts[2].ToLowerInvariant()} {name}");
return true;
}

View file

@ -763,8 +763,9 @@ internal sealed class NavigationEngine
/// Points the route at the waypoint nearest the player (macro start). Circular
/// and Linear routes pick from the whole route; a Once route only from the
/// current waypoint onward, so finished steps (a recall, a portal) aren't
/// repeated. Only plain waypoints are candidates; if the current one is a
/// Recall/Portal/Chat/Pause step it is kept. With <c>NavResumeNearest</c> off the
/// repeated, and a finished Once route stays finished. Only plain waypoints are
/// candidates; if the current one is a Recall/Portal/Chat/Pause step it is kept.
/// A Linear route keeps its direction. With <c>NavResumeNearest</c> off the
/// route keeps its last waypoint, unless <paramref name="always"/> (hazard escapes
/// and corpse runs, which leave the route behind).
/// </summary>
@ -781,6 +782,9 @@ internal sealed class NavigationEngine
var route = _settings.CurrentRoute;
if (route == null || route.Points.Count == 0) return;
if (route.RouteType == NavRouteType.Follow) return;
// A finished Once route (index left past its end) is done: picking from [0] here
// used to turn it back on at the nearest point, so a stop + start re-ran it.
if (_settings.NavRouteFinished()) return;
if (!TryGetPos(out double ns, out double ew)) return;
int cur = _settings.ActiveNavIndex;
@ -922,6 +926,23 @@ internal sealed class NavigationEngine
_hasGoodHeading = false;
}
/// <summary>
/// /ra nav restart: the loaded route starts over from its first point, as when it was
/// loaded with NavResumeNearest off (a Linear route heading out again, a finished Once
/// route running again). Nav is switched on; the macro is left as it is. False (nothing
/// done) with no waypoints to walk (none loaded, or a Follow route).
/// </summary>
public bool RestartRoute()
{
var route = _settings.CurrentRoute;
if (route == null || route.Points.Count == 0 || route.RouteType == NavRouteType.Follow) return false;
ResetRouteState();
_settings.ActiveNavIndex = 0;
_settings.EnableNavigation = true;
_host.Log($"Nav: route restarted from [0] ({route.RouteType}, {route.Points.Count} pts)");
return true;
}
/// <summary>
/// One-shot view of everything the nav engine is keying off. Nav had no
/// snapshot (Combat/Buff/Meta did), so a wedged route meant guessing which
@ -1454,14 +1475,17 @@ internal sealed class NavigationEngine
/// A finite (Once) route ran off its last point: stop and disable nav, but leave
/// the points intact. This used to <c>Points.Clear()</c> the in-memory route, so
/// re-enabling nav was a silent no-op until the profile was reloaded
/// (2026-06-03 audit P2). The index is left past the end; re-enabling nav lands
/// in <see cref="HandleRouteEnd"/>, which rewinds it for a genuine re-run.
/// (2026-06-03 audit P2). The index is left past the end, which marks the route
/// finished (<see cref="LegacyUiSettings.NavRouteFinished"/>): it stays finished
/// over a macro stop/start and a meta turning nav on, and runs again when it is
/// loaded again, edited, or restarted (/ra nav restart, or the player's Nav switch /
/// Start Navigation button, <see cref="LegacyUiSettings.RearmFinishedNavRoute"/>).
/// </summary>
private void CompleteOnceRoute(NavRouteParser route)
{
_settings.EnableNavigation = false;
StopMovement();
_host.Log($"Nav: Once route complete ({route.Points.Count} pts) — nav disabled, route retained for re-run");
_host.Log($"Nav: Once route complete ({route.Points.Count} pts) — nav disabled, route retained (load it again or /ra nav restart to re-run)");
}
private void HandleRouteEnd(NavRouteParser route)
@ -1472,16 +1496,19 @@ internal sealed class NavigationEngine
return;
}
// Nav was re-enabled on a finished Once route (CompleteOnceRoute leaves the
// index past the end). Rewind so the re-run actually walks instead of
// silently doing nothing. Cannot loop: completion always disables nav, and
// Tick returns early while it is disabled.
if (route.RouteType == NavRouteType.Once
&& _settings.ActiveNavIndex >= route.Points.Count
&& route.Points.Count > 0)
// Nav was switched on over a finished Once route (CompleteOnceRoute leaves the
// index past the end). This used to rewind it to [0], so anything that turned nav
// on re-ran the route: a meta's "/vt opt set enablenav true" replayed by a macro
// start, an expression. It stays finished, as a finished VTank Once route (its
// points used up) does; the player's Nav switch / Start Navigation button and
// /ra nav restart rewind it before nav gets here. Nav goes off again so the
// arbiter doesn't hold "Navigating" (above combat with BoostNavPriority) for a
// route with nothing left to walk.
if (_settings.NavRouteFinished())
{
_host.Log("Nav: Once route re-armed — restarting from point [0]");
_settings.ActiveNavIndex = 0;
_settings.EnableNavigation = false;
StopMovement();
_host.Log($"Nav: the Once route is finished ({route.Points.Count} pts) — nav stays off; load it again or /ra nav restart to re-run it");
return;
}

View file

@ -66,6 +66,7 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra nav save [name] — save the route; a name saves it as <name>.nav");
ChatLine("[RynthAi] /ra nav load <name> — load a nav from NavProfiles (none by that name: a new empty one)");
ChatLine("[RynthAi] /ra nav list — list the navs in NavProfiles");
ChatLine("[RynthAi] /ra nav restart — run the loaded route again from its first point (a stop/start keeps its place; a finished Once route stays done)");
ChatLine("[RynthAi] /ra meta load <name> — load a meta from MetaFiles (none by that name: a new blank one)");
ChatLine("[RynthAi] /ra meta new <name> — create a blank meta and load it");
ChatLine("[RynthAi] /ra meta list — list the metas in MetaFiles");
@ -1148,8 +1149,24 @@ public sealed partial class RynthAiPlugin
var names = _dashboard.NavFileNames();
ChatLine(names.Count == 0 ? "[RynthAi] No navs in NavProfiles." : $"[RynthAi] Navs ({names.Count}): {string.Join(", ", names)}");
break;
case "restart":
{
// Stopping and starting the macro keeps the route where it was (a finished Once
// route stays finished); this is the way to run it again from the top on purpose.
var route = _dashboard.Settings.CurrentRoute;
if (_navigationEngine == null) { ChatLine("[RynthAi] Navigation engine not ready."); break; }
if (!_navigationEngine.RestartRoute())
{
ChatLine(route != null && route.RouteType == NavRouteType.Follow && route.FollowTargetName.Length > 0
? "[RynthAi] A Follow route has no waypoints to restart."
: "[RynthAi] No nav route loaded to restart.");
break;
}
ChatLine($"[RynthAi] Nav route restarted from its first point ({route!.RouteType}, {route.Points.Count} waypoints).");
break;
}
default:
ChatLine("[RynthAi] /ra nav save [name] | /ra nav load <name> | /ra nav list");
ChatLine("[RynthAi] /ra nav save [name] | /ra nav load <name> | /ra nav list | /ra nav restart");
break;
}
}

View file

@ -1795,7 +1795,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// The hold timer keys off wantBuffRaw, NOT off the decision: keying it
// off the decision would reset it on the bypass tick itself and the
// ~10s retry cadence would silently become "once every 5 minutes".
if (!wantBuffRaw)
// Only while the macro runs (2026-10-28): stopped mid-heal, buffing still "wanted"
// a vital recharge nothing acts on, and 5 min later a stopped character was told
// buffing was stuck (stance wedge?) with nothing wrong.
if (!wantBuffRaw || !settings.IsMacroRunning)
{
_buffingHeldSince = DateTime.MinValue;
_buffComaWarned = false;

View file

@ -30,6 +30,8 @@ internal sealed class DefSession
public Func<uint[], uint[], bool> ReadRetail = (_, _) => false;
/// <summary>An object's name as the client knows it (an item in one of AC's slots that the pack read missed); null = unknown.</summary>
public Func<uint, string?> ObjectName = _ => null;
/// <summary>The spells the character knows, with names, A-Z (empty = can't be read now). Spell slots.</summary>
public Func<IReadOnlyList<SpellInfo>> KnownSpells = () => Array.Empty<SpellInfo>();
/// <summary>The keys the engine's hotkeys give a chat command ("/rdef use 3"): "F9, Ctrl+1"; "" = none.</summary>
public Func<string, string> CommandKeys = _ => string.Empty;
/// <summary>Gives own slot N the key (it comes off whatever had it): the plugin's BindOwnSlotKey. False when it can't.</summary>
@ -70,6 +72,11 @@ internal sealed class DefSession
{
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
DefSlot slot = Data.Slots[slotNumber - 1];
if (slot.IsSpell)
{
Use.Request(UseRequest.Cast(slot.SpellId, slot.SpellLabel, "slot " + slotNumber, Now()));
return null;
}
if (slot.Item == null) return $"Slot {slotNumber} is empty. Set it from the bar (Edit slots) or with /rdef set {slotNumber}.";
Use.Request(new UseRequest(slot.Item, null, slot.Mode, "slot " + slotNumber, Now()));
return null;
@ -129,12 +136,48 @@ internal sealed class DefSession
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
DefSlot slot = Data.Slots[slotNumber - 1];
slot.Item = ItemRef.From(it);
slot.SpellId = 0;
slot.SpellName = string.Empty;
slot.Mode = UseMode.Auto;
Save();
ItemKind kind = ItemKinds.Classify(it);
return $"Slot {slotNumber}: {it.FullName} ({UseModes.Describe(ItemKinds.DefaultAction(kind))} when pressed).";
}
/// <summary>
/// Puts a spell the character knows in a slot (the bar's "Put a spell here...": a search over the
/// known spells; the engine can't tell which spell is selected in the game's spellbook). Refused for
/// a spell the character doesn't know, when the spellbook can be read.
/// </summary>
public string SetSpell(int slotNumber, uint spellId)
{
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
if (spellId == 0) return "That isn't a spell.";
IReadOnlyList<SpellInfo> known = KnownSpells();
SpellInfo? spell = null;
foreach (SpellInfo s in known)
if (s.Id == spellId) { spell = s; break; }
if (spell == null && known.Count > 0) return $"You don't know {SpellTable.Name(spellId)}, so it can't go in a slot.";
SpellInfo info = spell ?? (SpellTable.TryGet(spellId, out SpellInfo t) ? t : new SpellInfo(spellId, SpellTable.Name(spellId), false, false));
Data.Slots[slotNumber - 1] = new DefSlot { SpellId = spellId, SpellName = info.Name };
Save();
return $"Slot {slotNumber}: {info.Name} ({SpellTargeting.Describe(info)} when pressed).";
}
/// <summary>/rdef spell &lt;slot&gt; &lt;name&gt;: one of the character's spells by what the player typed.</summary>
public string SetSpellFromName(int slotNumber, string text)
{
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
IReadOnlyList<SpellInfo> known = KnownSpells();
if (known.Count == 0) return "Your spells can't be read right now (in the world, on RynthCore with ReadKnownSpells).";
List<SpellInfo> found = SpellTable.Search(known, text, 6, out int total);
if (total == 0) return $"You know no spell named '{text}'.";
bool exact = found[0].Name.Equals((text ?? string.Empty).Trim(), StringComparison.OrdinalIgnoreCase);
if (total > 1 && !exact)
return $"{total} of your spells match '{text}': {string.Join(", ", found.ConvertAll(s => s.Name))}{(total > found.Count ? ", ..." : "")}. Type more of the name.";
return SetSpell(slotNumber, found[0].Id);
}
public string ClearSlot(int slotNumber)
{
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
@ -212,6 +255,7 @@ internal sealed class DefSession
if (combo.IndexOf(' ') >= 0) return "A key has no spaces, e.g. Ctrl+F9.";
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
ItemRef? item = Data.Slots[slotNumber - 1].Item;
if (byName && Data.Slots[slotNumber - 1].IsSpell) return $"Slot {slotNumber} holds a spell: bind the slot itself (/rdef bind {slotNumber} <key>).";
if (byName && item == null) return $"Slot {slotNumber} is empty: nothing to bind by name.";
string command = byName ? NameCommand(item!) : DefCommandParser.UseCommand(slotNumber);
@ -261,12 +305,12 @@ internal sealed class DefSession
return "The Shortcuts bar shows the game's 18 slots first again; RynthDefective's own slots follow them from slot 19 (its slot 1 there).";
var ids = new uint[DefSettings.RetailSlots];
var spells = new uint[DefSettings.RetailSlots];
int items = ReadRetail(ids, spells) ? BarMapping.RetailItems(ids) : 0;
int items = ReadRetail(ids, spells) ? BarMapping.RetailShortcuts(ids, spells) : 0;
CopyOffer = items;
const string what = "The Shortcuts bar is independent of the game's toolbar now: every slot is RynthDefective's own "
+ "(clicks one-touch, keys RynthCore hotkeys). The game's toolbar and its keys are unchanged.";
return items == 0 ? what
: what + $" The game's 18 slots hold {items} item{(items == 1 ? "" : "s")}: Defective Settings offers to copy them in.";
: what + $" The game's 18 slots hold {items} shortcut{(items == 1 ? "" : "s")} (items and spells): Defective Settings offers to copy them in.";
}
/// <summary>The player said no to the copy.</summary>
@ -301,8 +345,8 @@ internal sealed class DefSession
if (BindOwnKey(to, key)) keysMoved++; else keysFailed++;
Keys.Invalidate();
string msg = r.Copied == 0 ? "None of the game's slots held an item to copy." : $"Copied {r.Copied} of the game's slots into this bar (slots 1-18).";
if (r.Skipped > 0) msg += $" {r.Skipped} couldn't be (a spell, or an item not in your pack).";
string msg = r.Copied == 0 ? "None of the game's slots held an item or a spell to copy." : $"Copied {r.Copied} of the game's slots into this bar (slots 1-18).";
if (r.Skipped > 0) msg += $" {r.Skipped} couldn't be (an item not in your pack whose name the game doesn't know).";
if (r.Moved.Count > 0)
msg += $" Your own {r.Moved.Count} slot{(r.Moved.Count == 1 ? "" : "s")} moved after them, to 19 and on"
+ (keysMoved > 0 ? $", {keysMoved} key{(keysMoved == 1 ? "" : "s")} with them" : "") + ".";

View file

@ -2,7 +2,7 @@ using System;
namespace RynthCore.Plugin.RynthDefective.Model;
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings }
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings, Spell }
/// <summary>A parsed "/rdef ..." line. Use: <see cref="Slot"/> (1-based) or <see cref="Text"/> (an item name).</summary>
internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "");
@ -10,7 +10,7 @@ internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "",
internal static class DefCommandParser
{
public const string Usage =
"/rdef [use <slot or item name> | set <slot> [item name] | clear <slot> | bind <slot> <key> | unbind <slot> | "
"/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]";
/// <summary>Parses the arguments after "/rdef" (blank = show or hide the bar).</summary>
@ -43,6 +43,13 @@ internal static class DefCommandParser
if (slotText == null || !TrySlot(slotText, out int slot)) return Fail("Which slot? e.g. /rdef set 3 (the item selected in the game goes in slot 3) or /rdef set 3 Peerless Healing Kit");
return new DefCommand(DefVerb.Set, slot, tail);
}
case "spell":
{
SplitSlot(rest, out string? slotText, out string tail);
if (slotText == null || !TrySlot(slotText, out int slot) || tail.Length == 0)
return Fail("Usage: /rdef spell <slot> <spell name>, e.g. /rdef spell 3 Heal Self VI (one of your spells; the slot casts it)");
return new DefCommand(DefVerb.Spell, slot, tail);
}
case "clear":
{
return TrySlot(rest, out int slot) ? new DefCommand(DefVerb.Clear, slot) : Fail("Which slot? e.g. /rdef clear 3");

View file

@ -4,17 +4,29 @@ using RynthCore.Plugin.RynthDefective.Items;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>One slot of the bar: an item (or nothing) and how pressing it uses that item.</summary>
/// <summary>One slot of the bar: an item or a spell (or nothing), and how pressing it uses that item.</summary>
internal sealed class DefSlot
{
/// <summary>The item the slot holds; null = empty.</summary>
/// <summary>The item the slot holds; null = none.</summary>
public ItemRef? Item;
/// <summary>How pressing it uses the item. <see cref="UseMode.Auto"/> picks by what the item is.</summary>
public UseMode Mode = UseMode.Auto;
/// <summary>The spell the slot casts (2026-10-28); 0 = none. A slot holds an item or a spell, never both.</summary>
public uint SpellId;
/// <summary>The spell's name when it was put in the slot (shown when the spell table doesn't know it).</summary>
public string SpellName = string.Empty;
public bool Empty => Item == null;
public bool Empty => Item == null && SpellId == 0;
public bool IsSpell => Item == null && SpellId != 0;
public DefSlot Clone() => new() { Item = Item?.Clone(), Mode = Mode };
/// <summary>What the slot holds, by name: the item's, the spell's, or "".</summary>
public string Label => Item?.FullName ?? (SpellId != 0 ? SpellLabel : string.Empty);
/// <summary>The spell's name: the table's, else the saved one, else "Spell 1234".</summary>
public string SpellLabel =>
SpellTable.TryGet(SpellId, out SpellInfo s) ? s.Name : SpellName.Length > 0 ? SpellName : SpellTable.Name(SpellId);
public DefSlot Clone() => new() { Item = Item?.Clone(), Mode = Mode, SpellId = SpellId, SpellName = SpellName };
}
/// <summary>The "use as" choice of a slot.</summary>

View file

@ -83,6 +83,12 @@ internal sealed class DefStore
slot.Item = ParseRef(e, "item");
int mode = Int(e, "mode", 0);
slot.Mode = mode >= 0 && mode <= (int)UseMode.Equip ? (UseMode)mode : UseMode.Auto;
// A spell (2026-10-28; a file from before has none): only in a slot without an item.
if (slot.Item == null && e.TryGetProperty("spell", out JsonElement sp) && sp.ValueKind == JsonValueKind.Object)
{
slot.SpellId = UInt(sp, "id");
slot.SpellName = slot.SpellId != 0 ? Str(sp, "name") : string.Empty;
}
}
}
ParseRefs(root, "favourites", d.Favourites, DefData.MaxFavourites);
@ -167,6 +173,13 @@ internal sealed class DefStore
{
w.WriteStartObject();
if (slot.Item != null) WriteRef(w, "item", slot.Item);
else if (slot.SpellId != 0)
{
w.WriteStartObject("spell");
w.WriteNumber("id", slot.SpellId);
w.WriteString("name", slot.SpellLabel);
w.WriteEndObject();
}
w.WriteNumber("mode", (int)slot.Mode);
w.WriteEndObject();
}

View file

@ -0,0 +1,188 @@
// ============================================================================
// RynthDefective - Model/Spells.cs
// Spell slots (2026-10-28): what a spell is called, whom it is cast on, and
// finding one of the character's spells by name. Pure (the tests run it).
//
// The engine's plugin API has no spell names or targets and no way to read
// the spell selected in AC's spellbook or spell bar, so the names and the
// "self-targeted" / "harmful" flags come from RynthAi's spell table
// (Combat\SpellData.txt, linked in as RynthInventory and RynthOracle link it:
// id, name, category, family, words, duration, difficulty, then three flags,
// the second harmful, the third self-targeted), and the player picks a spell
// by name from the ones the character knows (ReadKnownSpells).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>One spell: its name, and whether it is cast on yourself only (recalls, Self buffs) or harms its target (war, debuffs).</summary>
internal readonly record struct SpellInfo(uint Id, string Name, bool SelfTargeted, bool Harmful);
internal static class SpellTable
{
private const string ResourceName = "RynthDefective.SpellData.txt";
private static Dictionary<uint, SpellInfo>? _byId;
public static bool TryGet(uint id, out SpellInfo info)
{
EnsureLoaded();
return _byId!.TryGetValue(id, out info);
}
/// <summary>The spell's name, or "Spell 1234" for one the table doesn't have (a server's own).</summary>
public static string Name(uint id) => TryGet(id, out SpellInfo s) ? s.Name : "Spell " + id.ToString(CultureInfo.InvariantCulture);
public static int Count
{
get { EnsureLoaded(); return _byId!.Count; }
}
private static void EnsureLoaded()
{
if (_byId != null) return;
Dictionary<uint, SpellInfo> map;
try
{
using Stream? s = Assembly.GetExecutingAssembly().GetManifestResourceStream(ResourceName);
if (s == null) map = new Dictionary<uint, SpellInfo>();
else
{
using var reader = new StreamReader(s, detectEncodingFromByteOrderMarks: true);
map = Parse(reader);
}
}
catch
{
map = new Dictionary<uint, SpellInfo>(); // a missing table costs names ("Spell 1234") and targets (by the selection)
}
_byId = map;
}
/// <summary>The table's lines (the tests read their own).</summary>
internal static Dictionary<uint, SpellInfo> Parse(TextReader reader)
{
var map = new Dictionary<uint, SpellInfo>(6400);
while (reader.ReadLine() is string line)
{
string[] c = line.Split('\t');
if (c.Length < 2 || !uint.TryParse(c[0].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out uint id) || id == 0) continue;
string name = c[1].Trim();
if (name.Length == 0) continue;
bool harmful = c.Length > 8 && c[8].Trim().Equals("True", StringComparison.OrdinalIgnoreCase);
bool self = c.Length > 9 && c[9].Trim().Equals("True", StringComparison.OrdinalIgnoreCase);
map[id] = new SpellInfo(id, name, self, harmful);
}
return map;
}
/// <summary>The character's spells (ids) with names, A-Z; ones the table doesn't name are listed by number.</summary>
public static SpellInfo[] Known(ReadOnlySpan<uint> ids)
{
var list = new List<SpellInfo>(ids.Length);
var seen = new HashSet<uint>();
foreach (uint id in ids)
{
if (id == 0 || !seen.Add(id)) continue;
list.Add(TryGet(id, out SpellInfo s) ? s : new SpellInfo(id, Name(id), false, false));
}
list.Sort((a, b) =>
{
int c = string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
return c != 0 ? c : a.Id.CompareTo(b.Id);
});
return list.ToArray();
}
/// <summary>
/// The spells in <paramref name="known"/> that match what the player typed, best first: the exact
/// name, then names starting with it, then names holding every word of it ("heal self", "vi heal").
/// At most <paramref name="max"/>; <paramref name="total"/> is how many matched. Blank = all of them.
/// </summary>
public static List<SpellInfo> Search(IReadOnlyList<SpellInfo> known, string? query, int max, out int total)
{
string q = (query ?? string.Empty).Trim();
string[] words = q.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var exact = new List<SpellInfo>();
var starts = new List<SpellInfo>();
var contains = new List<SpellInfo>();
foreach (SpellInfo s in known)
{
if (q.Length == 0) { contains.Add(s); continue; }
if (s.Name.Equals(q, StringComparison.OrdinalIgnoreCase)) exact.Add(s);
else if (s.Name.StartsWith(q, StringComparison.OrdinalIgnoreCase)) starts.Add(s);
else if (AllWords(s.Name, words)) contains.Add(s);
}
total = exact.Count + starts.Count + contains.Count;
var result = new List<SpellInfo>(Math.Min(total, Math.Max(0, max)));
foreach (List<SpellInfo> group in new[] { exact, starts, contains })
foreach (SpellInfo s in group)
{
if (result.Count >= max) return result;
result.Add(s);
}
return result;
}
private static bool AllWords(string name, string[] words)
{
if (words.Length == 0) return false;
foreach (string w in words)
if (name.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) return false;
return true;
}
}
/// <summary>Whom a spell slot's cast goes to.</summary>
internal enum CastAt { Yourself, Selection, Refused }
internal static class SpellTargeting
{
/// <summary>
/// The target for casting <paramref name="spell"/> now. A self-targeted spell (a recall, a Self buff)
/// is cast on yourself whatever is selected. Any other spell goes on the selection; with nothing
/// selected a beneficial one (Heal Other, a buff, an item spell) is cast on yourself, a harmful one
/// (war, void, a debuff) is refused, and so is a harmful one with yourself selected. A spell the table
/// doesn't know goes on the selection, else on yourself. <paramref name="why"/> says why it was refused.
/// </summary>
public static CastAt Decide(SpellInfo? spell, uint selected, uint player, out uint target, out string why)
{
why = string.Empty;
target = 0;
if (player == 0)
{
why = "the character isn't ready";
return CastAt.Refused;
}
if (spell is { SelfTargeted: true })
{
target = player;
return CastAt.Yourself;
}
bool harmful = spell is { Harmful: true };
if (selected != 0 && selected != player)
{
target = selected;
return CastAt.Selection;
}
if (harmful)
{
why = selected == player ? "select a monster first (you have yourself selected)" : "select a target first";
return CastAt.Refused;
}
target = player;
return CastAt.Yourself;
}
/// <summary>"cast on you" / "cast on the selection (else on you)" / "cast on the selected monster", for the slot's tooltip.</summary>
public static string Describe(SpellInfo? spell) => spell switch
{
{ SelfTargeted: true } => "cast on you",
{ Harmful: true } => "cast on the selected target",
_ => "cast on the selected target, or on you with nothing selected",
};
}

View file

@ -30,7 +30,7 @@ all three go.
* **Independent of the game's toolbar** (per character, off by default): every slot on the bar is
RynthDefective's own. The game's 18 slots are not on it; clicks are one-touch (a kit on yourself, a
potion used, a weapon wielded) and keys are RynthCore hotkeys (`/rdef use N` for bar slot N). Turning it
on offers to copy the items in the game's 18 slots into the bar's slots 1-18 (nothing is copied unless you
on offers to copy the items and spells in the game's 18 slots into the bar's slots 1-18 (nothing is copied unless you
say so); your own slots move after them, to 19 and on, with their keys, so the bar looks as it did. The
game's toolbar and its keys are not changed. Turning it off shows the game's 18 first again, RynthDefective's
slot 1 at 19.
@ -51,6 +51,17 @@ a potion, a scroll, a weapon, a wand, a shield... Click a slot, or press its key
A slot can be set to another way: use it, use it on me, use it on the selected target, or wield it.
**Spell slots.** One of RynthDefective's own slots can hold a spell instead: right-click it on the Shortcuts
bar and choose *Put a spell here...*, then find the spell by name among the ones the character knows (the
engine can't tell RynthDefective which spell is selected in the game's spellbook, so it is picked there), or
type `/rdef spell 3 Heal Self VI`. Its picture is the spell's. Pressing it casts the spell, in Magic mode
(asked for first when the character is in another stance; the cast waits for the stance to settle): a spell
cast on yourself only (Self buffs, recalls) goes on you; any other on the selection, or on you when nothing is
selected and the spell is a helpful one (Heal Other, a buff); a war, void or debuff spell with nothing (or
yourself) selected is refused and says so, as is a spell the character doesn't know. The same one-at-a-time
and busy rules as items apply. The game's own 18 slots keep the game's own spell handling; copying them into an
independent bar brings their spells along as spell slots.
**Put an item in a slot** (Edit slots in the bar): *Set from selected* takes the item you have selected
in the game, or *Pick from pack* chooses from a searchable list of what you carry. `/rdef set 3` does the
first, `/rdef set 3 Health Potion` the second.
@ -84,6 +95,13 @@ weapons you wielded are listed first (they are also in their kind's group).
the server, or the last action is unanswered (the server's UseDone; a wield is answered by the item
reading in hand). Pressing again while one waits does not queue a second; pressing another slot replaces the
waiting one. A request not sent within 6 s gives up and says why.
* A busy reading that just sits there is a leftover, not a reason to wait: the client's busy count can stay
up with nothing in flight after a death, a login or an interrupted action (and RynthAi's "waiting on the
server" with it). A count that hasn't moved for 4 s with nothing of RynthDefective's in flight, a gesture
that has "animated" for 4 s, or RynthAi's bit on for 5.5 s holds nothing (logged once); only a count above
that leftover holds again. RynthDefective never resets the count itself (the engine owns it). If the server
really is busy it answers "You're too busy" and the use is tried once more a second later.
* A key pressed in portal space (a death's too) is not kept for later: it says so.
* After a wield from a fighting stance the stance follows the weapon (wand: magic, melee weapon: melee,
launcher with ammunition in hand: missile) once the character is still. At peace you stay at peace. A bow
without arrows in hand returns you to peace rather than leaving a stance it can't use. Shields, armor and
@ -99,6 +117,7 @@ weapons you wielded are listed first (they are also in their kind's group).
/rdef panels | selection show / hide the Game Panels buttons, the Selection window
/rdef use <slot | item name> use the slot's item, or the carried item with that name
/rdef set <slot> [item name] put the selected item (or the named one) in a slot
/rdef spell <slot> <name> put one of your spells in a slot (it casts it)
/rdef clear <slot> empty a slot
/rdef bind <slot> <key> bind a key (F9, Ctrl+1 ...) to the slot; /rdef unbind <slot>
/rdef weapons [search] show the weapon picker
@ -107,7 +126,7 @@ weapons you wielded are listed first (they are also in their kind's group).
/rdef list | status | help
```
`/rdef use`, `set`, `clear`, `bind` take RynthDefective's own slot numbers (1-42): on the Shortcuts bar own
`/rdef use`, `set`, `spell`, `clear`, `bind` take RynthDefective's own slot numbers (1-42): on the Shortcuts bar own
slot N is bar slot 18+N, or bar slot N when the bar is independent of the game's toolbar.
## Settings
@ -120,8 +139,8 @@ with the slots, favourites and recent weapons in
## Not in 0.1
Pages, spell slots, arrow auto-equip, gear highlight, summon cooldown counters and the war-magic element
changer (Defective has them).
Pages, arrow auto-equip, gear highlight, summon cooldown counters and the war-magic element changer
(Defective has them).
## Needs

View file

@ -31,7 +31,7 @@
pictures) are checked first; so are the UseDone count (v63), wield/refusal info (v70) and
the chat parser the key binding goes through. Below v71 it still uses items (/rdef use). -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window: one-touch kits, potions and weapons by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings.</RynthPluginDescription>
<RynthPluginDescription>Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window: one-touch kits, potions, weapons and spells by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>
@ -42,6 +42,11 @@
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
</ItemGroup>
<ItemGroup>
<!-- Spell slots (2026-10-28): spell names and whom a spell is cast on, from RynthAi's spell table
(linked as RynthInventory and RynthOracle link it; Model/Spells.cs reads it). -->
<EmbeddedResource Include="..\RynthCore.Plugin.RynthAi\Combat\SpellData.txt" LogicalName="RynthDefective.SpellData.txt" Link="Shared\SpellData.txt" />
</ItemGroup>
<ItemGroup>
<!-- The shortcut bar (2026-10-22): drawn with ImGui.NET bound to the engine's cimgui, in the
engine's look (Shared\RynthUi; plugin API v90 hosts the frameless window and gives AC's

View file

@ -235,6 +235,14 @@ public sealed partial class RynthDefectivePlugin : IBarActions
_nextBarBuildMs = 0;
});
public void SetSpell(int number, uint spellId) => QueueBar(() =>
{
// The game's own slots take spells from the game's spellbook (drag one onto the retail toolbar).
if (IsRetail(number)) { Print($"Slot {number} is the game's own: drag the spell onto it from the game's spellbook."); return; }
Print(_session.SetSpell(OwnOf(number), spellId));
_nextBarBuildMs = 0;
});
public void ChangeSlotCount(int delta) => QueueBar(() =>
{
DefSettings st = _session.Settings;

View file

@ -72,6 +72,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
_session.Save = RequestSave;
_session.ReadRetail = ReadRetail;
_session.ObjectName = id => Host.TryGetObjectName(id, out string n) && n.Length > 0 ? n : null;
_session.KnownSpells = () => _world.KnownSpells(HostDefWorld.KnownMaxAgeMs);
_session.CommandKeys = command => Host.HasKeyBinding ? Host.GetActionKeys(command) : string.Empty;
_session.BindOwnKey = (own, key) => Host.HasKeyBinding && BindOwnSlotKey(own, key, out _);
@ -108,7 +109,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
_inWorld = true;
_identityKnown = false;
_nextIdentityTryMs = Environment.TickCount64;
_session.Use.Reset();
_session.Use.ResetSession();
_world?.Reset();
}
@ -118,7 +119,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
_inWorld = false;
_identityKnown = false;
_session.LoggedIn = false;
_session.Use.Reset();
_session.Use.ResetSession();
_world?.Reset();
_barView = RynthCore.Plugin.RynthDefective.ShortcutBar.BarSnapshot.NotReady;
foreach (UiWindow? w in new[] { _barWindow, _pickerWindow, _settingsWindow })
@ -130,7 +131,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
public override void Shutdown()
{
SaveNow();
_session.Use.Reset();
_session.Use.ResetSession();
_ui.SubmitEmpty(Host);
}
@ -209,6 +210,9 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
case DefVerb.Set:
Print(c.Text.Length > 0 ? _session.SetFromName(c.Slot, c.Text) : _session.SetFromSelected(c.Slot));
break;
case DefVerb.Spell:
Print(_session.SetSpellFromName(c.Slot, c.Text));
break;
case DefVerb.Clear:
Print(_session.ClearSlot(c.Slot));
break;
@ -252,6 +256,11 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
for (int i = 1; i <= _session.Settings.SlotCount; i++)
{
DefSlot slot = _session.Data.Slots[i - 1];
if (slot.IsSpell)
{
Print($"{i}: {slot.SpellLabel} (a spell){(_session.KeyOfSlot(i) is { } sk ? " [" + sk + "]" : "")}");
continue;
}
if (slot.Item == null) { Print($"{i}: (empty)"); continue; }
SlotStatus s = ItemMatcher.Status(slot.Item, items);
sb.Clear();

View file

@ -59,8 +59,9 @@ internal static class BarMapping
/// Copies AC's 18 slots (<paramref name="ids"/>, <paramref name="spells"/>, slot 1 first) into the own
/// slots 1-18, so an independent bar looks as the usual one did: the own slots that were after AC's
/// (own N at bar 18+N) move to own 18+N, where an independent bar shows them. <see cref="BarCopyResult.Moved"/>
/// lists the moves of the slots that held something (their "/rdef use N" keys go with them). A spell, or
/// an item <paramref name="resolve"/> can't name, can't go in an own slot: that slot stays empty (Skipped).
/// lists the moves of the slots that held something (their "/rdef use N" keys go with them). A spell goes
/// in as a spell slot (2026-10-28); an item <paramref name="resolve"/> can't name can't go in an own slot:
/// that slot stays empty (Skipped).
/// Refused (nothing changed) when an own slot past 24 holds something: there is no room to move it.
/// </summary>
public static BarCopyResult CopyRetail(List<DefSlot> own, ReadOnlySpan<uint> ids, ReadOnlySpan<uint> spells, Func<uint, ItemRef?> resolve)
@ -68,7 +69,7 @@ internal static class BarMapping
const int retail = DefSettings.RetailSlots, room = DefSettings.SlotsMax - DefSettings.RetailSlots;
for (int n = room + 1; n <= own.Count; n++)
if (!own[n - 1].Empty)
return new BarCopyResult(0, 0, Array.Empty<(int, int)>(), $"Your slot {n} holds {own[n - 1].Item!.FullName}: there is no room to move "
return new BarCopyResult(0, 0, Array.Empty<(int, int)>(), $"Your slot {n} holds {own[n - 1].Label}: there is no room to move "
+ $"slots {room + 1}-{DefSettings.SlotsMax} after the game's {retail}. Empty them (or copy by hand) first.");
var next = DefData.NewSlots();
@ -85,7 +86,11 @@ internal static class BarMapping
uint id = i < ids.Length ? ids[i] : 0, spell = i < spells.Length ? spells[i] : 0;
if (id == 0)
{
if (spell != 0) skipped++;
if (spell != 0)
{
next[i] = new DefSlot { SpellId = spell, SpellName = SpellTable.Name(spell) };
copied++;
}
continue;
}
ItemRef? r = resolve(id);
@ -97,11 +102,12 @@ internal static class BarMapping
return new BarCopyResult(copied, skipped, moved, null);
}
/// <summary>How many of AC's slots hold an item (spells can't be copied, so they don't count).</summary>
public static int RetailItems(ReadOnlySpan<uint> ids)
/// <summary>How many of AC's slots hold an item or a spell (what a copy would bring over).</summary>
public static int RetailShortcuts(ReadOnlySpan<uint> ids, ReadOnlySpan<uint> spells)
{
int n = 0;
foreach (uint id in ids) if (id != 0) n++;
for (int i = 0; i < ids.Length; i++)
if (ids[i] != 0 || (i < spells.Length && spells[i] != 0)) n++;
return n;
}

View file

@ -11,6 +11,8 @@
// the bar shows (DefSettings.BarSlots).
// An independent bar (DefSettings.IndependentBar) has no AC slots: every slot
// N is own slot N (BarMapping), and AC's toolbar isn't read at all.
// An own slot can hold a spell (2026-10-28): its picture is the spell's, and
// the snapshot carries the character's spells for the slot menu's search.
// ============================================================================
using System;
@ -43,10 +45,17 @@ internal sealed record BarSlot(
public bool Empty => ObjectId == 0 && SpellId == 0 && Name.Length == 0;
}
/// <summary>The bar as drawn. Independent: every slot is RynthDefective's own (DefSettings.IndependentBar).</summary>
internal sealed record BarSnapshot(BarSlot[] Slots, bool Ready, int IconSize, bool Independent = false)
/// <summary>
/// The bar as drawn. Independent: every slot is RynthDefective's own (DefSettings.IndependentBar).
/// Spells: the character's spells, A-Z, for "Put a spell here..." (empty when they can't be read);
/// CanCast: the engine casts for plugins.
/// </summary>
internal sealed record BarSnapshot(BarSlot[] Slots, bool Ready, int IconSize, bool Independent = false,
IReadOnlyList<SpellInfo>? Spells = null, bool CanCast = false)
{
public static readonly BarSnapshot NotReady = new(Array.Empty<BarSlot>(), false, 36);
public IReadOnlyList<SpellInfo> KnownSpells => Spells ?? Array.Empty<SpellInfo>();
}
/// <summary>Builds the snapshot on the plugin tick (reads the host and the carried items).</summary>
@ -82,12 +91,14 @@ internal sealed class BarSnapshotBuilder
{
if (!_host.HasShortcuts) return BarSnapshot.NotReady;
DefSettings st = session.Settings;
IReadOnlyList<SpellInfo> spells = session.KnownSpells();
bool canCast = _host.HasCastSpell;
if (st.IndependentBar)
{
// Every slot is RynthDefective's own: AC's toolbar isn't read or shown (BarMapping).
var own = new BarSlot[st.BarSlots];
for (int n = 1; n <= st.BarSlots; n++) own[n - 1] = Own(n, BarMapping.OwnSlot(n, true), true, session, items, _host);
return new BarSnapshot(own, true, st.ButtonSize, true);
for (int n = 1; n <= st.BarSlots; n++) own[n - 1] = Own(n, BarMapping.OwnSlot(n, true), true, session, items, spells, _host);
return new BarSnapshot(own, true, st.ButtonSize, true, spells, canCast);
}
if (_host.GetShortcuts(_ids, _spells) == 0) return BarSnapshot.NotReady;
RefreshKeys(now);
@ -96,8 +107,8 @@ internal sealed class BarSnapshotBuilder
var slots = new BarSlot[st.BarSlots];
for (int n = 1; n <= st.BarSlots; n++)
slots[n - 1] = BarMapping.IsRetail(n, false) ? Retail(n, byId) : Own(n, BarMapping.OwnSlot(n, false), false, session, items, _host);
return new BarSnapshot(slots, true, st.ButtonSize);
slots[n - 1] = BarMapping.IsRetail(n, false) ? Retail(n, byId) : Own(n, BarMapping.OwnSlot(n, false), false, session, items, spells, _host);
return new BarSnapshot(slots, true, st.ButtonSize, false, spells, canCast);
}
private BarSlot Retail(int n, Dictionary<uint, CarriedItem> byId)
@ -123,13 +134,14 @@ internal sealed class BarSnapshotBuilder
count = "none";
tone = CountTone.Missing;
}
else name = $"Spell {spell}";
else name = SpellTable.Name(spell);
string tip = $"Slot {n} (the game's own): {name}{(count.Length > 0 ? " - " + count : "")}.{KeysLine(allKeys)}\n" +
"Click: use it, as its key does. Right-click: change the slot or its keys.";
return new BarSlot(n, true, 0, id, id == 0 ? spell : 0, name, count, tone, key, allKeys, tip);
}
private static BarSlot Own(int n, int own, bool independent, DefSession session, IReadOnlyList<CarriedItem> items, RynthCoreHost host)
private static BarSlot Own(int n, int own, bool independent, DefSession session, IReadOnlyList<CarriedItem> items,
IReadOnlyList<SpellInfo> spells, RynthCoreHost host)
{
DefSlot slot = own >= 1 && own <= session.Data.Slots.Count ? session.Data.Slots[own - 1] : new DefSlot();
// Every key of "/rdef use N" (the engine's hotkeys), else the one bound to the item by name.
@ -137,9 +149,10 @@ internal sealed class BarSnapshotBuilder
string key = all.Length > 0 ? FirstKey(all) : session.KeyOfSlot(own) ?? string.Empty;
if (all.Length == 0) all = key;
string whose = independent ? "RynthCore's: this bar is independent of the game's toolbar" : "RynthCore's: the game holds 18";
if (slot.IsSpell) return OwnSpell(n, own, slot, whose, key, all, spells);
if (slot.Item == null)
return new BarSlot(n, false, own, 0, 0, string.Empty, string.Empty, CountTone.Plain, SlotText.ShortKey(key), all,
$"Slot {n} ({whose}): empty.{KeysLine(all)}\nRight-click: put the selected item here, or change its keys.");
$"Slot {n} ({whose}): empty.{KeysLine(all)}\nRight-click: put the selected item or one of your spells here, or change its keys.");
SlotStatus s = ItemMatcher.Status(slot.Item, items);
string count = SlotText.Count(s, out uint color);
CountTone tone = color == SlotText.InHand ? CountTone.InHand : color == SlotText.Missing ? CountTone.Missing : CountTone.Plain;
@ -149,6 +162,24 @@ internal sealed class BarSnapshotBuilder
SlotText.ShortKey(key), all, tip);
}
/// <summary>
/// A spell slot: the spell's picture and name. A spell the character doesn't know (another
/// character's file, a spell lost) shows dimmed with "?" (when the spellbook can be read at all).
/// </summary>
private static BarSlot OwnSpell(int n, int own, DefSlot slot, string whose, string key, string all, IReadOnlyList<SpellInfo> spells)
{
string name = slot.SpellLabel;
SpellInfo? info = SpellTable.TryGet(slot.SpellId, out SpellInfo si) ? si : null;
bool known = spells.Count == 0;
foreach (SpellInfo s in spells)
if (s.Id == slot.SpellId) { known = true; break; }
string tip = $"Slot {n}: {name}, a spell.\nClick or press the key: {SpellTargeting.Describe(info)} (Magic mode first)."
+ (known ? "" : "\nYou don't know this spell: pressing it does nothing.")
+ (key.Length > 0 ? "\nKey: " + key : "\nNo key yet.") + $"\n({whose}.)\nRight-click: change the slot or its keys.";
return new BarSlot(n, false, own, 0, slot.SpellId, name, known ? string.Empty : "?", known ? CountTone.Plain : CountTone.Missing,
SlotText.ShortKey(key), all, tip);
}
/// <summary>The first of "1, Ctrl+1": what fits on the slot.</summary>
private static string FirstKey(string keys)
{

View file

@ -25,12 +25,16 @@
// /rdef use N. A key comes off whatever had it, after the player says so.
// An independent bar (DefSettings.IndependentBar) has only RynthDefective's
// own slots: every key is an engine hotkey (BarMapping, BarSlot.Own).
// Spells (2026-10-28): an own slot's menu has "Put a spell here...", a search
// over the character's spells (the engine can't read the spell selected in
// the game's spellbook); the slot then casts it (UseController).
//
// AC's render thread. Reads the snapshot the tick built; every click is
// queued for the tick (IBarActions).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthDefective.Model;
@ -48,6 +52,8 @@ internal interface IBarActions
void SetFromSelected(int number);
void Clear(int number);
void ChangeSlotCount(int delta);
/// <summary>Puts spell <paramref name="spellId"/> in bar slot <paramref name="number"/> (one of RynthDefective's own).</summary>
void SetSpell(int number, uint spellId);
/// <summary>An item dragged out of AC's UI was let go over slot <paramref name="number"/>.</summary>
void DropItem(int number, uint objectId);
/// <summary>A key was bound or removed: the bar asks for its keys again.</summary>
@ -155,6 +161,12 @@ internal sealed class ShortcutBarWindow
ImGui.OpenPopup(KeyPopupId);
}
KeyPopup();
if (_openSpellPopup)
{
_openSpellPopup = false;
ImGui.OpenPopup(SpellPopupId);
}
SpellPopup(view);
return height;
}
@ -367,6 +379,15 @@ internal sealed class ShortcutBarWindow
ImGui.Separator();
bool hasSelection = _host.HasGetSelectedItemId && _host.GetSelectedItemId() != 0;
if (ImGui.MenuItem("Put the selected item here", null, false, hasSelection)) _act.SetFromSelected(s.Number);
if (!s.Retail)
{
if (ImGui.MenuItem("Put a spell here...", null, false, view.CanCast)) StartSpellPick(s);
SafeImGui.SetItemTooltip(view.CanCast
? "One of your spells, found by name: the slot casts it, in Magic mode, on the selection\n"
+ "(on you for your own spells, or with nothing selected for a helpful one).\n"
+ "The game doesn't tell RynthCore which spell is selected in its spellbook, so you find it here."
: "This RynthCore can't cast spells for a plugin.");
}
if (ImGui.MenuItem("Empty this slot", null, false, !s.Empty)) _act.Clear(s.Number);
ImGui.Separator();
if (!_host.HasKeyBinding)
@ -441,6 +462,95 @@ internal sealed class ShortcutBarWindow
SafeImGui.SetItemTooltip(tip);
}
// ── Spells: "Put a spell here..." ─────────────────────────────────────
private const string SpellPopupId = "##sb_spell_popup";
private const int SpellRows = 40;
private bool _openSpellPopup, _spellFocus;
private BarSlot? _spellSlot;
private string _spellSearch = string.Empty, _spellQuery = "\0";
private IReadOnlyList<SpellInfo>? _spellSource;
private List<SpellInfo> _spellMatches = new();
private int _spellTotal;
private void StartSpellPick(BarSlot slot)
{
_spellSlot = slot;
_spellSearch = string.Empty;
_spellSource = null;
_spellFocus = true;
_openSpellPopup = true;
}
private void SpellPopup(BarSnapshot view)
{
if (!ImGui.IsPopupOpen(SpellPopupId)) return;
ImGui.PushStyleColor(ImGuiCol.PopupBg, WithAlpha(_bg, 0xFA));
ImGui.PushStyleColor(ImGuiCol.Border, _line);
ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, Px(4));
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(8), Px(7)));
bool open = ImGui.BeginPopup(SpellPopupId);
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(2);
if (!open) return;
try
{
BarSlot? ss = _spellSlot;
if (ss == null) { ImGui.CloseCurrentPopup(); return; }
float w = Px(250), row = Px(20);
ImGui.TextDisabled($"Slot {ss.Number}: a spell to cast");
IReadOnlyList<SpellInfo> known = view.KnownSpells;
if (_spellFocus)
{
ImGui.SetKeyboardFocusHere();
_spellFocus = false;
}
ImGui.SetNextItemWidth(w);
ImGui.InputTextWithHint("##sb_spell_search", "type a spell's name", ref _spellSearch, 64u);
if (!ReferenceEquals(known, _spellSource) || _spellSearch != _spellQuery)
{
_spellSource = known;
_spellQuery = _spellSearch;
_spellMatches = SpellTable.Search(known, _spellSearch, SpellRows, out _spellTotal);
}
if (known.Count == 0) ImGui.TextDisabled("Your spells can't be read right now.");
else
{
int shown = Math.Clamp(_spellMatches.Count, 1, 10);
if (ImGui.BeginChild("##sb_spell_list", new Vector2(w, shown * (row + Px(2)) + Px(8)), ImGuiChildFlags.Borders))
{
foreach (SpellInfo sp in _spellMatches)
{
ImGui.PushID(unchecked((int)sp.Id));
Vector2 start = ImGui.GetCursorPos();
bool clicked = ImGui.Selectable("##sp", false, ImGuiSelectableFlags.AllowOverlap, new Vector2(0, row));
SafeImGui.SetItemTooltip($"{sp.Name}: {SpellTargeting.Describe(sp)}.");
ImGui.SetCursorPos(start);
IntPtr tex = _host.GetIconTexture(RynthIconKind.Spell, sp.Id);
if (tex != IntPtr.Zero) ImGui.Image(tex, new Vector2(row, row));
else ImGui.Dummy(new Vector2(row, row));
ImGui.SameLine();
ImGui.SetCursorPosY(start.Y + (row - ImGui.GetTextLineHeight()) * 0.5f);
ImGui.TextUnformatted(sp.Name);
ImGui.PopID();
if (clicked)
{
_act.SetSpell(ss.Number, sp.Id);
_spellSlot = null;
ImGui.CloseCurrentPopup();
break;
}
}
}
ImGui.EndChild();
if (_spellMatches.Count == 0) ImGui.TextDisabled("You know no spell by that name.");
else if (_spellTotal > _spellMatches.Count) SafeImGui.TextDisabled($"{_spellTotal - _spellMatches.Count} more: type more of the name.");
}
if (ImGui.Button("Cancel")) { _spellSlot = null; ImGui.CloseCurrentPopup(); }
}
finally { ImGui.EndPopup(); }
}
// ── Keys: "press a key" ───────────────────────────────────────────────
private enum KeyStep { Waiting, Confirm, Message }

View file

@ -60,6 +60,7 @@ internal static class UiFormat
// Image icon kinds (op level 2)
public const byte IconKindIcon = 0; // a 0x06 texture id
public const byte IconKindObject = 1; // a live object's icon with underlay and overlay
public const byte IconKindSpell = 2; // a spell id: the spell's icon
// Selectable flags
public const uint SelectableAllowDoubleClick = 4;

View file

@ -0,0 +1,200 @@
// ============================================================================
// RynthDefective - Use/BusyGate.cs
// Whether the client's "busy" readings really hold a use back (2026-10-28).
//
// Why: the busy count the engine reports (GetBusyState) can stay above zero
// with nothing at all in flight: after a death (the engine's own resync waits
// out the death portal and 5 s more), after a logout and a login (the engine
// keeps its count across the session and can't clear it again), after an
// interrupted action. Holding every use on it made the bar "not work at all
// after logging in" until the client was restarted, and kits wait seconds
// after every death. RynthAi copes the same way (Combat/CombatBusyGate: a
// leftover count doesn't hold a heal), and RynthAi's "waiting on the server"
// bit includes its copy of the same count, so it sticks with it.
//
// The rule (pure: BusyRule.Decide; BusyGate keeps the clocks):
// * a gesture animating holds, for at most AnimationMaxMs without a break
// (RynthAi's ActionPacer.GestureHoldMaxMs: no real gesture lasts longer);
// * the busy count holds while it is above the count already judged a
// leftover AND it moved within CountTrustMs or our own last use went out
// within OwnTrustMs. A count that has read the same for longer, with
// nothing of ours in flight, is a leftover: it holds nothing, and only a
// count above it holds again (our own next use raises it and the server's
// answer brings it back down to the leftover);
// * RynthAi's "waiting on the server" bit holds while it is fresh:
// BotTrustMs since it came on (RynthAi's own actions are answered or let
// go well inside it), or only CountTrustMs when a leftover count explains it.
// After that the use is sent: if the server really is busy it answers
// "You're too busy" (UseDone 0x1D) and the use controller tries once more.
//
// RynthDefective never resets the client's count itself (ForceResetBusyCount):
// the count is the engine's (its reconciler and watchdogs own it), RynthAi
// stopped resetting it on 2026-10-06 because a reset zeroes actions the server
// hasn't answered yet (each later answer then drives it negative), and nothing
// here needs it at zero: ignoring a leftover is enough to send.
// ============================================================================
using System;
namespace RynthCore.Plugin.RynthDefective.Use;
/// <summary>What holds a use back now; None = send.</summary>
internal enum BusyHold { None, Busy, Animation, Bot }
/// <summary>The readings that were ignored as leftovers (each logged once).</summary>
[Flags]
internal enum BusyStale { None = 0, Count = 1, Animation = 2, Bot = 4 }
/// <summary>The readings at one moment, and how long each has read so. Pure data.</summary>
/// <param name="Count">The client's busy count (GetBusyState).</param>
/// <param name="CountSteadyMs">How long it has read this value.</param>
/// <param name="Leftover">The count already judged a leftover (0 = none): a reading at or under it holds nothing.</param>
/// <param name="SinceOwnSendMs">Since RynthDefective's own last use or cast went out.</param>
/// <param name="Animating">A cast or use gesture is animating.</param>
/// <param name="AnimatingMs">How long it has animated without a break.</param>
/// <param name="BotWaiting">RynthAi is waiting on the server (null = RynthAi isn't there).</param>
/// <param name="BotSteadyMs">How long that bit has read its current value.</param>
internal readonly record struct BusyFacts(
int Count, long CountSteadyMs, int Leftover, long SinceOwnSendMs,
bool Animating, long AnimatingMs, bool? BotWaiting, long BotSteadyMs);
internal static class BusyRule
{
/// <summary>A count that moved this recently is an action under way (a kit 2.5 s, a corpse use 3.7 s at the most seen).</summary>
public const long CountTrustMs = 4000;
/// <summary>After our own use went out the count is ours this long.</summary>
public const long OwnTrustMs = 4000;
/// <summary>A gesture that lasts longer is a stuck motion queue (RynthAi's ActionPacer.GestureHoldMaxMs).</summary>
public const long AnimationMaxMs = 4000;
/// <summary>RynthAi's bit this long: its corpse uses are let go at 5 s (ActionPacer.WorldUseMaxMs).</summary>
public const long BotTrustMs = 5500;
/// <summary>What holds a use back; <paramref name="stale"/> names the readings ignored as leftovers.</summary>
public static BusyHold Decide(in BusyFacts f, out BusyStale stale)
{
stale = BusyStale.None;
if (f.Animating)
{
if (f.AnimatingMs < AnimationMaxMs) return BusyHold.Animation;
stale |= BusyStale.Animation;
}
if (f.Count > 0)
{
bool fresh = f.CountSteadyMs < CountTrustMs || f.SinceOwnSendMs < OwnTrustMs;
if (f.Count > f.Leftover && fresh) return BusyHold.Busy;
stale |= BusyStale.Count;
}
if (f.BotWaiting == true)
{
// RynthAi's bit includes its copy of the same count: a leftover count explains it.
long trust = (stale & BusyStale.Count) != 0 ? CountTrustMs : BotTrustMs;
if (f.BotSteadyMs < trust) return BusyHold.Bot;
stale |= BusyStale.Bot;
}
return BusyHold.None;
}
}
/// <summary>
/// The clocks behind <see cref="BusyRule"/>: how long each reading has read the same, our own last
/// send, and the leftover count. <see cref="Observe"/> every tick (in or out of the world: a count
/// left by a death has read the same all through the death portal), <see cref="Judge"/> when a use
/// wants to go. Plugin pump thread only.
/// </summary>
internal sealed class BusyGate
{
private bool _started;
private int _count, _leftover;
private long _countSinceMs;
private bool _animating;
private long _animatingSinceMs;
private bool? _bot;
private long _botSinceMs;
private long _ownSendMs = long.MinValue / 4;
private BusyStale _logged;
/// <summary>The count judged a leftover (0 = none).</summary>
public int Leftover => _leftover;
public void Observe(int count, bool animating, bool? botWaiting, long now)
{
if (count < 0) count = 0;
if (!_started)
{
_started = true;
_count = count;
_countSinceMs = now;
_animating = animating;
_animatingSinceMs = now;
_bot = botWaiting;
_botSinceMs = now;
}
if (count != _count)
{
_count = count;
_countSinceMs = now;
}
if (_leftover > count) _leftover = count; // part of it was answered or cleared: what is left is the leftover
if (count == 0) _logged &= ~BusyStale.Count;
if (animating != _animating)
{
_animating = animating;
_animatingSinceMs = now;
if (!animating) _logged &= ~BusyStale.Animation;
}
if (botWaiting != _bot)
{
_bot = botWaiting;
_botSinceMs = now;
if (botWaiting != true) _logged &= ~BusyStale.Bot;
}
}
/// <summary>Our own use or cast went out now.</summary>
public void NoteOwnSend(long now) => _ownSendMs = now;
public BusyFacts Facts(long now) => new(
_count, now - _countSinceMs, _leftover, now - _ownSendMs,
_animating, _animating ? now - _animatingSinceMs : 0, _bot, now - _botSinceMs);
/// <summary>
/// What holds a use back now. A count found to be a leftover becomes the new leftover;
/// <paramref name="newlyIgnored"/> names the leftovers not reported before (log them once).
/// </summary>
public BusyHold Judge(long now, out BusyStale newlyIgnored)
{
BusyHold hold = BusyRule.Decide(Facts(now), out BusyStale stale);
if ((stale & BusyStale.Count) != 0 && _count > _leftover)
{
_leftover = _count;
_logged &= ~BusyStale.Count; // a new leftover is worth its own line
}
newlyIgnored = stale & ~_logged;
_logged |= stale;
return hold;
}
/// <summary>The words for the log line when a leftover is first ignored.</summary>
public string Describe(BusyStale what, long now)
{
BusyFacts f = Facts(now);
var parts = new System.Collections.Generic.List<string>(3);
if ((what & BusyStale.Count) != 0)
parts.Add($"the client's busy count has read {f.Count} for {f.CountSteadyMs / 1000.0:0.0} s with nothing of ours in flight");
if ((what & BusyStale.Animation) != 0)
parts.Add($"the character has read 'animating' for {f.AnimatingMs / 1000.0:0.0} s");
if ((what & BusyStale.Bot) != 0)
parts.Add($"RynthAi has read 'waiting on the server' for {f.BotSteadyMs / 1000.0:0.0} s"
+ ((what & BusyStale.Count) != 0 || (_logged & BusyStale.Count) != 0 ? " (its copy of the same count)" : ""));
return "[RynthDefective] " + string.Join("; ", parts)
+ ": a leftover (a death, a login or an interrupted action), not waited on. The count itself is left alone.";
}
public void Reset()
{
_started = false;
_leftover = 0;
_logged = BusyStale.None;
_ownSendMs = long.MinValue / 4;
}
}

View file

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.Json;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
@ -29,9 +30,12 @@ internal sealed unsafe class HostDefWorld : IDefWorld
public bool InWorld => _host.HasGetPlayerId && _host.GetPlayerId() != 0 && !(_host.HasIsPortaling && _host.IsPortaling());
public uint PlayerId => _host.HasGetPlayerId ? _host.GetPlayerId() : 0;
public uint SelectedId => _host.HasGetSelectedItemId ? _host.GetSelectedItemId() : 0;
public bool ClientBusy => _host.HasGetBusyState && _host.GetBusyState() != 0;
public int BusyCount => _host.HasGetBusyState ? Math.Max(0, _host.GetBusyState()) : 0;
public bool Animating => _host.HasGetCastBusyState && _host.GetCastBusyState() != 0;
public int UseDoneSeq => _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
public uint UseDoneError(int seqAtSend) =>
_host.TryGetLastUseDone(out int seq, out uint error) && seq == seqAtSend + 1 ? error : 0;
public int CombatMode => _host.GetCurrentCombatMode();
public bool? BotWaitingOnServer => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.ServerAction) != 0 : null;
@ -67,11 +71,81 @@ internal sealed unsafe class HostDefWorld : IDefWorld
public bool UseObjectOn(uint id, uint target) => _host.HasUseObjectOn && _host.UseObjectOn(id, target);
public bool SetCombatMode(int mode) => _host.HasChangeCombatMode && _host.ChangeCombatMode(mode);
// ── Spells (spell slots) ────────────────────────────────────────────────
/// <summary>The character's spells are re-read when older than this (a spell scribed since shows within it).</summary>
public const long KnownMaxAgeMs = 5000;
private uint[] _knownBuf = new uint[2048];
private HashSet<uint>? _known;
private SpellInfo[] _knownList = Array.Empty<SpellInfo>();
private long _knownAtMs = long.MinValue / 4;
public bool CanCast => _host.HasCastSpell;
public bool CastSpell(uint target, uint spellId) =>
_host.HasCastSpell && spellId != 0 && spellId <= int.MaxValue && _host.CastSpell(target, (int)spellId);
/// <summary>
/// From the spellbook the engine reads (ReadKnownSpells; RynthAi's note: the engine's IsSpellKnown
/// answers "known" for spells the character doesn't have, so it isn't asked). A "no" is checked
/// against a fresh read before it is believed. Null when the spellbook can't be read.
/// </summary>
public bool? KnowsSpell(uint spellId)
{
HashSet<uint>? known = KnownIds(KnownMaxAgeMs);
if (known == null) return null;
if (known.Contains(spellId)) return true;
known = KnownIds(0);
return known == null ? null : known.Contains(spellId);
}
/// <summary>The character's spells with names, A-Z (the bar's spell search); empty when they can't be read.</summary>
public SpellInfo[] KnownSpells(long maxAgeMs)
{
KnownIds(maxAgeMs);
return _knownList;
}
private HashSet<uint>? KnownIds(long maxAgeMs)
{
long now = NowMs;
if (now - _knownAtMs < maxAgeMs) return _known;
_knownAtMs = now;
if (!_host.HasReadKnownSpells)
{
_known = null;
_knownList = Array.Empty<SpellInfo>();
return null;
}
int n = _host.ReadKnownSpells(_knownBuf, _knownBuf.Length);
if (n > _knownBuf.Length && n <= 65536)
{
_knownBuf = new uint[n];
n = _host.ReadKnownSpells(_knownBuf, _knownBuf.Length);
}
if (n <= 0)
{
// Not readable yet (before the character's description arrives): can't tell.
_known = null;
_knownList = Array.Empty<SpellInfo>();
return null;
}
n = Math.Min(n, _knownBuf.Length);
var set = new HashSet<uint>(n);
for (int i = 0; i < n; i++) if (_knownBuf[i] != 0) set.Add(_knownBuf[i]);
if (_known == null || !set.SetEquals(_known)) _knownList = SpellTable.Known(_knownBuf.AsSpan(0, n));
_known = set;
return set;
}
public void Reset()
{
_reader.Reset();
_items = new List<CarriedItem>();
_itemsAtMs = long.MinValue / 4;
_known = null;
_knownList = Array.Empty<SpellInfo>();
_knownAtMs = long.MinValue / 4;
}
}

View file

@ -16,8 +16,11 @@ internal interface IDefWorld
bool InWorld { get; }
uint PlayerId { get; }
uint SelectedId { get; }
/// <summary>The client's busy count is above zero (an item action it sent has not been answered).</summary>
bool ClientBusy { get; }
/// <summary>
/// The client's busy count (0 = idle): the item actions and casts it sent that the server hasn't
/// answered. It can read above zero with nothing in flight (BusyGate says when it holds a use).
/// </summary>
int BusyCount { get; }
/// <summary>A cast or use gesture is animating.</summary>
bool Animating { get; }
/// <summary>RynthAi is waiting on the server for an action it sent (null = RynthAi isn't there).</summary>
@ -26,6 +29,8 @@ internal interface IDefWorld
bool? BotMacroRunning { get; }
/// <summary>Count of the server's UseDone events; 0 when the engine can't report them.</summary>
int UseDoneSeq { get; }
/// <summary>The error of the server's first UseDone after <paramref name="seqAtSend"/> (0x1D: "You're too busy"); 0 = none or unknown.</summary>
uint UseDoneError(int seqAtSend);
/// <summary>1 NonCombat, 2 Melee, 4 Missile, 8 Magic.</summary>
int CombatMode { get; }
/// <summary>The server's refusals so far (0x028A / 0x00A0 ... count), to tell a new one.</summary>
@ -41,18 +46,40 @@ internal interface IDefWorld
bool UseObject(uint id);
bool UseObjectOn(uint id, uint target);
bool SetCombatMode(int mode);
/// <summary>The engine can cast (CastSpell).</summary>
bool CanCast { get; }
/// <summary>Whether the character knows the spell; null = can't tell (the server refuses one it doesn't).</summary>
bool? KnowsSpell(uint spellId);
/// <summary>Casts the spell at <paramref name="target"/> (the player id for yourself).</summary>
bool CastSpell(uint target, uint spellId);
}
/// <summary>One thing the player asked to use: an exact item (a slot's) or a name typed in a command.</summary>
/// <summary>
/// One thing the player asked to use: an exact item (a slot's), a name typed in a command, or a spell
/// to cast (<see cref="Spell"/>, a spell slot's; Item and Name are null then).
/// </summary>
internal sealed record UseRequest(ItemRef? Item, string? Name, UseMode Mode, string Source, long AtMs)
{
/// <summary>Same item, same way: pressing the key again must not queue a second one.</summary>
/// <summary>Sent once already and answered "You're too busy": this is the one more try.</summary>
public bool Retry { get; init; }
/// <summary>The spell to cast (2026-10-28); 0 = an item.</summary>
public uint Spell { get; init; }
/// <summary>The spell's name as the slot has it.</summary>
public string SpellName { get; init; } = string.Empty;
/// <summary>A spell slot's cast for <paramref name="spellId"/>.</summary>
public static UseRequest Cast(uint spellId, string name, string source, long atMs) =>
new(null, null, UseMode.Auto, source, atMs) { Spell = spellId, SpellName = name };
/// <summary>Same item (or spell), same way: pressing the key again must not queue a second one.</summary>
public bool SameAs(UseRequest o) =>
Mode == o.Mode
&& ((Item != null && o.Item != null && Item.SameAs(o.Item))
|| (Name != null && o.Name != null && string.Equals(Name, o.Name, StringComparison.OrdinalIgnoreCase)));
|| (Name != null && o.Name != null && string.Equals(Name, o.Name, StringComparison.OrdinalIgnoreCase))
|| (Spell != 0 && Spell == o.Spell));
public string Label => Item?.FullName ?? Name ?? "item";
public string Label => Item?.FullName ?? (Spell != 0 ? (SpellName.Length > 0 ? SpellName : SpellTable.Name(Spell)) : Name) ?? "item";
}
/// <summary>The combat stance a weapon swap leaves the character in.</summary>
@ -104,8 +131,11 @@ internal static class Stance
/// is put right (<see cref="Stance.Wanted"/>) once the character is still.
/// Busy: nothing is sent while the client's busy count is up, a gesture animates, RynthAi waits on
/// the server, the last action is unanswered, or for <see cref="MinGapMs"/> after it - the "one item
/// action at a time" rule RynthAi's ActionPacer keeps. Weapon swaps also wait out a running RynthAi
/// macro unless the player allowed them (it would swap straight back).
/// action at a time" rule RynthAi's ActionPacer keeps. A busy reading that has sat unchanged with
/// nothing in flight (a count left by a death, a login or an interrupted action) is a leftover and
/// holds nothing (<see cref="BusyGate"/>, logged once); if the server really is busy it answers
/// "You're too busy" and the use is tried once more after <see cref="RetryAfterMs"/>. Weapon swaps
/// also wait out a running RynthAi macro unless the player allowed them (it would swap straight back).
/// </summary>
internal sealed class UseController
{
@ -119,25 +149,44 @@ internal sealed class UseController
public const long MinGapMs = 250;
public const long StanceSettleMs = 500;
public const long StanceTimeoutMs = 4000;
/// <summary>A cast waits this long after the client reads Magic mode (RynthAi's ActionPacer.ModeSettleMs: a cast
/// sent into the stance animation hangs).</summary>
public const long MagicSettleMs = 800;
/// <summary>A use the server answered "You're too busy" is tried once more after this.</summary>
public const long RetryAfterMs = 1000;
/// <summary>ACE's YoureTooBusy, as a UseDone error.</summary>
public const uint TooBusyError = 0x1D;
private enum Stage { Sent, WaitWield, Stance }
private enum Stage { Sent, WaitWield, Stance, Magic }
private sealed class Flight
{
public UseRequest Request = null!;
/// <summary>The item used (null for a cast).</summary>
public CarriedItem Item = null!;
/// <summary>What the player reads ("Peerless Healing Kit", "Heal Self VI") and what the log reads.</summary>
public string Name = string.Empty, What = string.Empty;
public UseAction Action;
public ItemKind Kind;
public long SentMs;
public int UseDoneAtSend, RefusalAtSend, ModeBefore;
public Stage Stage;
public long StageMs;
// A cast: the spell, its target, and the Magic stance it waits for.
public uint SpellId, Target;
public bool ModeAsked;
public long MagicSeenMs;
}
private UseRequest? _pending;
private Flight? _flight;
private long _lastDoneMs = long.MinValue / 4;
private long _retryNotBeforeMs = long.MinValue / 4;
private string _lastWait = string.Empty;
private readonly BusyGate _busy = new();
/// <summary>The busy readings' clocks (tests look at the leftover).</summary>
internal BusyGate Busy => _busy;
/// <summary>Plain information ("Using Peerless Healing Kit ..."): the status line, not the chat.</summary>
public Action<string>? Say;
@ -155,6 +204,10 @@ internal sealed class UseController
public bool Involves(ItemRef r) =>
(_pending?.Item != null && _pending.Item.SameAs(r)) || (_flight?.Request.Item != null && _flight.Request.Item.SameAs(r));
/// <summary>The spell a cast in flight or waiting is about.</summary>
public bool InvolvesSpell(uint spellId) =>
spellId != 0 && (_pending?.Spell == spellId || _flight?.Request.Spell == spellId);
public DefSettings Settings = new();
/// <summary>Queues a request. False when it is the one already waiting or in flight (a held key).</summary>
@ -167,22 +220,38 @@ internal sealed class UseController
return true;
}
/// <summary>Drops what is waiting and forgets what is in flight (logout, portal space, shutdown).</summary>
/// <summary>Drops what is waiting and forgets what is in flight (portal space).</summary>
public void Reset()
{
_pending = null;
_flight = null;
_lastWait = string.Empty;
_retryNotBeforeMs = long.MinValue / 4;
}
/// <summary>
/// <see cref="Reset"/>, and the busy readings' clocks start again (login, logout, shutdown). Not on
/// portal space: a count a death left has read the same all through the death portal, and that is
/// what shows it is a leftover once the character lands.
/// </summary>
public void ResetSession()
{
Reset();
_busy.Reset();
}
public void Tick(IDefWorld w)
{
long now = w.NowMs;
_busy.Observe(w.BusyCount, w.Animating, w.BotWaitingOnServer, now);
if (!w.InWorld)
{
// Portal space (a death's too): what was waiting is dropped, and said so (a key pressed in the
// portal did nothing). A use in flight is the server's now; nothing to say about it.
if (_pending != null) Warn?.Invoke($"{_pending.Label}: not used, the character is in portal space.");
if (_pending != null || _flight != null) Reset();
return;
}
long now = w.NowMs;
if (_flight != null && !AdvanceFlight(w, now)) return; // still in flight: nothing new goes out
if (_pending == null) return;
@ -205,16 +274,36 @@ internal sealed class UseController
private string? WaitReason(IDefWorld w, long now)
{
if (now - _lastDoneMs < MinGapMs) return "the last action just finished";
if (w.ClientBusy) return "the character is busy";
if (w.Animating) return "an animation is playing";
if (w.BotWaitingOnServer == true) return "RynthAi is waiting on the server";
return null;
if (now < _retryNotBeforeMs) return "the server said the character was busy";
return Hold(now) switch
{
BusyHold.Busy => "the character is busy",
BusyHold.Animation => "an animation is playing",
BusyHold.Bot => "RynthAi is waiting on the server",
_ => null,
};
}
/// <summary>The busy gate's verdict now; a leftover it ignores for the first time is logged.</summary>
private BusyHold Hold(long now)
{
BusyHold hold = _busy.Judge(now, out BusyStale ignored);
if (ignored != BusyStale.None) Log?.Invoke(_busy.Describe(ignored, now));
return hold;
}
/// <summary>The client's count or a gesture holds the character (RynthAi's bit doesn't: it is about RynthAi's own actions).</summary>
private bool CharacterHeld(long now) => Hold(now) is BusyHold.Busy or BusyHold.Animation;
// ── Sending ─────────────────────────────────────────────────────────────
private void Send(IDefWorld w, UseRequest req, long now)
{
if (req.Spell != 0)
{
SendSpell(w, req, now);
return;
}
IReadOnlyList<CarriedItem> items = w.Items();
CarriedItem? item = req.Item != null
? ItemMatcher.Find(req.Item, items, out _)
@ -268,11 +357,14 @@ internal sealed class UseController
Warn?.Invoke($"{name}: the client didn't take the request (nothing was sent).");
return;
}
_busy.NoteOwnSend(now);
_flight = new Flight
{
Request = req,
Item = item,
Name = name,
What = item.ToString(),
Action = action,
Kind = kind,
SentMs = now,
@ -282,10 +374,124 @@ internal sealed class UseController
ModeBefore = w.CombatMode,
Stage = action == UseAction.Equip ? Stage.WaitWield : Stage.Sent,
};
Log?.Invoke($"[RynthDefective] {req.Source}: {(action == UseAction.Equip ? "wield" : target != 0 ? "use on " + (target == w.PlayerId ? "you" : "0x" + target.ToString("X8")) : "use")} {item} (stack {item.Stack}, mode {Stance.Name(w.CombatMode)})");
Log?.Invoke($"[RynthDefective] {req.Source}: {(action == UseAction.Equip ? "wield" : target != 0 ? "use on " + (target == w.PlayerId ? "you" : "0x" + target.ToString("X8")) : "use")} {item} (stack {item.Stack}, mode {Stance.Name(w.CombatMode)}{(req.Retry ? ", the one more try" : "")})");
Say?.Invoke(action == UseAction.Equip ? $"Wielding {name}..." : $"Using {name}...");
}
/// <summary>
/// The server answered "You're too busy" (UseDone 0x1D) to <paramref name="f"/>'s use: it is tried
/// once more after <see cref="RetryAfterMs"/>, unless a newer request is waiting (the newest wish
/// wins) or this was the one more try already. Returns whether it was queued again.
/// </summary>
private bool RetryTooBusy(Flight f, long now)
{
string name = f.Name;
if (f.Request.Retry)
{
Warn?.Invoke($"{name}: not {(f.SpellId != 0 ? "cast" : "used")}, the server says the character is busy. Try again in a moment.");
return false;
}
if (_pending != null) return false;
_pending = f.Request with { Retry = true, AtMs = now };
_retryNotBeforeMs = now + RetryAfterMs;
Log?.Invoke($"[RynthDefective] {f.Request.Source}: the server answered 'too busy' to {f.What}; trying once more in {RetryAfterMs} ms");
Say?.Invoke($"{name}: the server said busy, trying again...");
return true;
}
// ── Casting (a spell slot) ──────────────────────────────────────────────
/// <summary>
/// A spell slot's cast: refused when the character doesn't know the spell or it needs a target
/// (SpellTargeting); else into Magic mode first (the client's stance for casting; RynthAi buffs the
/// same way), then cast once the stance has settled, answered by the server's UseDone like a use.
/// </summary>
private void SendSpell(IDefWorld w, UseRequest req, long now)
{
uint id = req.Spell;
SpellInfo? info = SpellTable.TryGet(id, out SpellInfo s) ? s : null;
string name = info?.Name ?? req.Label;
if (!w.CanCast)
{
Warn?.Invoke($"{name}: not cast, this RynthCore can't cast spells for a plugin.");
return;
}
if (w.KnowsSpell(id) == false)
{
Warn?.Invoke($"{name}: not cast, you don't know that spell.");
return;
}
if (SpellTargeting.Decide(info, w.SelectedId, w.PlayerId, out uint target, out string why) == CastAt.Refused)
{
Warn?.Invoke($"{name}: not cast, {why}.");
return;
}
var f = new Flight
{
Request = req,
Name = name,
What = $"spell {id} '{name}'",
Action = UseAction.Use,
SpellId = id,
Target = target,
SentMs = now,
StageMs = now,
ModeBefore = w.CombatMode,
Stage = Stage.Magic,
};
_flight = f;
if (w.CombatMode == Stance.Magic)
{
f.MagicSeenMs = now - MagicSettleMs; // already there and settled (nothing holds the character: WaitReason)
AdvanceMagic(w, f, now);
return;
}
f.ModeAsked = w.SetCombatMode(Stance.Magic);
Log?.Invoke($"[RynthDefective] {req.Source}: {f.What}: {Stance.Name(w.CombatMode)} -> magic first{(f.ModeAsked ? "" : " (the client turned it away; asking again)")}");
Say?.Invoke($"Magic mode for {name}...");
}
/// <summary>A cast waiting for Magic mode: cast once it has settled. True when finished (cast refused or failed).</summary>
private bool AdvanceMagic(IDefWorld w, Flight f, long now)
{
long age = now - f.StageMs;
if (w.CombatMode == Stance.Magic)
{
if (f.MagicSeenMs == 0) f.MagicSeenMs = now;
bool settling = now - f.MagicSeenMs < MagicSettleMs || CharacterHeld(now);
if (settling && age < WaitLimitMs) return false;
return Cast(w, f, now);
}
if (age >= StanceTimeoutMs)
{
Warn?.Invoke($"{f.Name}: not cast, the character didn't go into magic mode ({Stance.Name(w.CombatMode)} now). "
+ "A weapon in your hands? Wield a wand, or nothing, and try again.");
Finish(now);
return true;
}
if (!f.ModeAsked && !CharacterHeld(now)) f.ModeAsked = w.SetCombatMode(Stance.Magic);
return false;
}
private bool Cast(IDefWorld w, Flight f, long now)
{
f.UseDoneAtSend = w.UseDoneSeq;
f.RefusalAtSend = w.RefusalSeq;
if (!w.CastSpell(f.Target, f.SpellId))
{
Warn?.Invoke($"{f.Name}: the client didn't take the cast (nothing was sent).");
Finish(now);
return true;
}
_busy.NoteOwnSend(now);
f.Stage = Stage.Sent;
f.SentMs = now;
f.StageMs = now;
Log?.Invoke($"[RynthDefective] {f.Request.Source}: cast {f.What} on {(f.Target == w.PlayerId ? "you" : "0x" + f.Target.ToString("X8"))} (mode {Stance.Name(w.CombatMode)}{(f.Request.Retry ? ", the one more try" : "")})");
Say?.Invoke(f.Target == w.PlayerId ? $"Casting {f.Name}..." : $"Casting {f.Name} on the selection...");
return false;
}
// ── In flight ───────────────────────────────────────────────────────────
/// <summary>Steps the action in flight; true when it is finished (a new one may go out this tick).</summary>
@ -298,11 +504,12 @@ internal sealed class UseController
case Stage.Sent:
{
bool answered = w.UseDoneSeq != f.UseDoneAtSend;
bool quiet = age >= UseQuietMs && !w.ClientBusy && !w.Animating;
bool quiet = !answered && age >= UseQuietMs && !CharacterHeld(now);
if (answered || quiet || age >= UseTimeoutMs)
{
if (!answered && age >= UseTimeoutMs) Log?.Invoke($"[RynthDefective] no UseDone for {f.Item} after {age} ms; carrying on");
if (!answered && age >= UseTimeoutMs) Log?.Invoke($"[RynthDefective] no UseDone for {f.What} after {age} ms; carrying on");
Finish(now);
if (answered && w.UseDoneError(f.UseDoneAtSend) == TooBusyError) RetryTooBusy(f, now);
return true;
}
return false;
@ -332,6 +539,8 @@ internal sealed class UseController
}
return false;
}
case Stage.Magic:
return AdvanceMagic(w, f, now);
default:
return AdvanceStance(w, f, now);
}
@ -354,7 +563,7 @@ internal sealed class UseController
Finish(now);
return true;
}
if (since < StanceSettleMs || w.ClientBusy || w.Animating) return false;
if (since < StanceSettleMs || CharacterHeld(now)) return false;
if (w.SetCombatMode(want))
{
Log?.Invoke($"[RynthDefective] stance {Stance.Name(w.CombatMode)} -> {Stance.Name(want)} for {f.Item}");

View file

@ -59,7 +59,7 @@ internal sealed class BarSettingsView
if (st.IndependentBar && _s.CopyOffer > 0)
{
int n = _s.CopyOffer;
w.TextColored(SlotText.Waiting, $"The game's 18 slots hold {n} item{(n == 1 ? "" : "s")}. Copy {(n == 1 ? "it" : "them")} into this bar's slots 1-18?");
w.TextColored(SlotText.Waiting, $"The game's 18 slots hold {n} shortcut{(n == 1 ? "" : "s")} (items and spells). Copy {(n == 1 ? "it" : "them")} into this bar's slots 1-18?");
w.TextWrapped("Your own slots move after them, to 19 and on, with their keys, so the bar looks as before. "
+ "The game's toolbar and its keys stay as they are.");
w.SmallButton("Copy them", "set.copy", () => Tell(_s.CopyRetailSlots()));

View file

@ -121,6 +121,24 @@ internal sealed class BarView
color = SlotText.Plain;
bool icons = _s.Settings.ShowIcons && _s.IconsAvailable;
if (slot.IsSpell)
{
// A spell slot (set with /rdef spell or on the Shortcuts bar): its picture, or its initials.
string spell = slot.SpellLabel;
SpellInfo? info = SpellTable.TryGet(slot.SpellId, out SpellInfo si) ? si : null;
bool casting = _s.Use.InvolvesSpell(slot.SpellId);
if (icons) w.ImageButton(UiFormat.IconKindSpell, slot.SpellId, id, () => Press(number), size, size, 0xFFFFFFFFu, casting ? SlotText.Waiting : 0u);
else
{
if (casting) w.PushStyleColor(UiFormat.ColButton, SlotText.Waiting);
w.Button(SlotText.Abbreviation(spell), id, () => Press(number), size + 8f, size + 8f);
if (casting) w.PopStyleColor();
}
w.Tooltip($"Slot {number}: {spell}, a spell.\nClick or press the key: {SpellTargeting.Describe(info)} (Magic mode first)."
+ (keyFull != null ? "\nKey: " + keyFull : "\nNo key yet (Edit slots)."));
return;
}
if (slot.Item == null)
{
w.Button("+", id, () => Choose(number), size + 8f, size + 8f);

View file

@ -57,11 +57,12 @@ internal sealed class SlotEditor
DefSlot slot = _s.Data.Slots[n - 1];
int number = n;
string? key = _s.KeyOfSlot(n);
string name = slot.Item == null ? "(empty)" : slot.Item.FullName;
string name = slot.Empty ? "(empty)" : slot.Label;
if (icons)
{
CarriedItem? have = slot.Item == null ? null : ItemMatcher.Find(slot.Item, items, out _);
if (have != null) w.Image(UiFormat.IconKindObject, have.Id, RowIcon, RowIcon);
if (slot.IsSpell) w.Image(UiFormat.IconKindSpell, slot.SpellId, RowIcon, RowIcon);
else if (have != null) w.Image(UiFormat.IconKindObject, have.Id, RowIcon, RowIcon);
else if (slot.Item != null && slot.Item.Icon != 0) w.Image(UiFormat.IconKindIcon, slot.Item.Icon, RowIcon, RowIcon, UiFormat.Rgb(255, 255, 255, 90));
else w.Dummy(RowIcon, RowIcon);
w.SameLine();
@ -78,7 +79,7 @@ internal sealed class SlotEditor
{
int n = _selected;
DefSlot slot = _s.Data.Slots[n - 1];
w.TextColored(UiColors.Gold, $"Slot {n}: " + (slot.Item == null ? "(empty)" : slot.Item.FullName));
w.TextColored(UiColors.Gold, $"Slot {n}: " + (slot.Empty ? "(empty)" : slot.Label));
w.Button("Set from selected", "ed.set", () => Say(_s.SetFromSelected(n)));
w.Tooltip("Select an item in the game (click it in your pack), then press this: it goes in this slot.");
@ -99,6 +100,13 @@ internal sealed class SlotEditor
if (_picking) DrawPackPicker(w, items, n);
if (slot.IsSpell)
{
SpellInfo? info = SpellTable.TryGet(slot.SpellId, out SpellInfo si) ? si : null;
w.TextDisabled($"A spell: pressing the slot has it {SpellTargeting.Describe(info)} (Magic mode first). /rdef spell {n} <name> puts another in.");
DrawKey(w, n, slot);
return;
}
if (slot.Item == null) return;
int mode = (int)slot.Mode;

View file

@ -68,6 +68,7 @@ internal static class Program
MetaSchedulerTests.Register(runner);
NavEngineTests.Register(runner);
NavReachTests.Register(runner);
NavResumeTests.Register(runner);
PatrolDoorwayTests.Register(runner);
PatrolSettingsTests.Register(runner);
PatrolPocketTests.Register(runner);
@ -143,6 +144,7 @@ internal static class Program
HpFailsafeTests.Register(runner);
PluginFixTests.Register(runner);
BuffChainTests.Register(runner);
ShieldBuffTests.Register(runner);
LootPacingTests.Register(runner);
CorpseCloseTests.Register(runner);
VTankHotkeyTests.Register(runner);

View file

@ -29,7 +29,7 @@ internal static class NavEngineTests
r.Add("nav engine: walks to each waypoint, a Circular route wraps", CircularWraps);
r.Add("nav engine: a Linear route turns round at both ends", LinearBounces);
r.Add("nav engine: a Linear route keeps its direction through a pause", LinearDirectionSurvivesStop);
r.Add("nav engine: a Once route ends, turns nav off, and re-runs from [0]", OnceCompletes);
r.Add("nav engine: a Once route ends, turns nav off, stays finished, and the player can re-run it from [0]", OnceCompletes);
r.Add("nav engine: closest approach counts as arriving; a pause forgets it", SweepPass);
r.Add("nav engine: a pause point waits its time on the clock", PausePoint);
r.Add("nav engine: standing still through a pause, the stop is sent once and then once a second (not every tick)", PauseStopsOnce);
@ -223,10 +223,21 @@ internal static class NavEngineTests
Check.Eq(nav.Idx, 2, "the index is left past the end");
Check.False(FakeHost.AutoRun, "stopped");
nav.S.EnableNavigation = true; // re-run
// A meta or expression switching nav on (a macro start replays "/vt opt set enablenav true"):
// the route stays finished, as a finished VTank Once route does (2026-10-28; it re-ran from [0]).
nav.S.EnableNavigation = true;
nav.Tick();
Check.Eq(nav.Idx, 0, "re-enabled: the route restarts from [0]");
Check.Eq(LogCount("Once route re-armed"), 1, "logged");
Check.Eq(nav.Idx, 2, "nav switched on: still finished");
Check.False(nav.S.EnableNavigation, "and nav off again");
Check.Eq(LogCount("the Once route is finished"), 1, "logged");
// The player's Nav switch / Start Navigation (RearmFinishedNavRoute) re-runs it from [0].
Check.True(nav.S.RearmFinishedNavRoute(), "the player re-runs it");
nav.S.EnableNavigation = true;
nav.Tick();
Check.Eq(nav.Idx, 0, "re-run from [0]");
Check.True(nav.S.EnableNavigation, "nav on");
Check.False(nav.S.RearmFinishedNavRoute(), "a route that isn't finished is left alone");
}
private static void SweepPass()

View file

@ -0,0 +1,402 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.PluginCore;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
using A = RynthCore.Plugin.RynthAi.LegacyUi.MetaActionType;
using C = RynthCore.Plugin.RynthAi.LegacyUi.MetaConditionType;
using RT = RynthCore.Plugin.RynthAi.LegacyUi.NavRouteType;
namespace RynthCore.RynthAiHostTests.Tests;
// Stopping and starting the macro must not restart the nav (Tom, 2026-10-28: "anything that was a
// 'once' instead of linear or circular gets restarted"). Starting the macro re-arms the meta's rules,
// so a state's "Always -> Embedded Nav Route" fired again and loaded its route fresh: a Once route
// went back to [0], a finished one ran again, a Linear route turned round. Here the meta and the nav
// engine run on one settings object in the plugin's tick order (the macro-start closest-waypoint pick,
// then nav, then the meta), on a fake clock and a fake character that only moves when told.
internal static class NavResumeTests
{
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
private const double NS0 = 42.0, EW0 = 33.0;
private static long _now;
public static void Register(Runner r)
{
r.Add("nav resume: stop + start keeps a meta's Once route on its waypoint (no restart from [0])", OnceKeepsWaypoint);
r.Add("nav resume: stop + start keeps a Circular route's waypoint, also with Go To Closest Waypoint off", CircularKeepsWaypoint);
r.Add("nav resume: stop + start keeps a Linear route's waypoint and its direction", LinearKeepsDirection);
r.Add("nav resume: a finished Once route stays finished across stop + start (a replayed enablenav too)", FinishedOnceStaysFinished);
r.Add("nav resume: loading the route again starts it fresh (state entry, edited, another route loaded)", LoadAgainStartsFresh);
r.Add("nav resume: a rule that first fires after the start loads its route fresh", FirstFireAfterStartIsFresh);
r.Add("nav resume: a replayed /vt nav load or /ra nav load of the running .nav keeps its place; a replayed /ra nav restart is skipped", ChatNavLoadKept);
r.Add("nav resume: /ra nav restart runs the route from the top; the player's Nav switch re-runs a finished Once route", RestartCommand);
}
// ── Rig ───────────────────────────────────────────────────────────────────
private sealed class Bot
{
public readonly LegacyUiSettings S;
public readonly NavigationEngine E;
public readonly MetaManager M;
public readonly List<string> Ra = new();
public DateTime Now = new(2026, 10, 28, 12, 0, 0);
private bool _wasRunning;
/// <summary>Call FakeHost.Reset() and At(...) first. The first tick is a macro start (as at login).</summary>
public Bot(params MetaRule[] rules)
{
_now = 1_000_000;
NavigationEngine.Clock = static () => _now;
var host = FakeHost.Create();
S = new LegacyUiSettings { IsMacroRunning = true, EnableMeta = true, CurrentState = "Default" };
S.MetaRules = rules.ToList();
E = new NavigationEngine(host, S);
M = new MetaManager(S, host, new PlayerVitalsCache()) { Clock = () => Now };
M.SetRaCommandHandler(Ra.Add);
}
/// <summary>One plugin tick: the macro-start closest pick (RynthAiPlugin.OnTick), nav when the
/// arbiter would run it, then the meta. <paramref name="metaSeconds"/> moves only the meta's clock.</summary>
public void Tick(int ms = 100, double metaSeconds = 0)
{
_now += ms;
Now = Now.AddMilliseconds(ms).AddSeconds(metaSeconds);
if (!_wasRunning && S.IsMacroRunning) E.ResumeFromNearestWaypoint();
_wasRunning = S.IsMacroRunning;
if (S.IsMacroRunning && S.EnableNavigation && S.CurrentRoute.Points.Count > 0) E.Tick();
M.Think();
}
public void Ticks(int n) { for (int i = 0; i < n; i++) Tick(); }
/// <summary>/ra stop, a tick, /ra start, a few ticks.</summary>
public void StopStart()
{
S.IsMacroRunning = false;
E.Stop();
Ticks(3);
S.IsMacroRunning = true;
Ticks(3);
}
public int Idx => S.ActiveNavIndex;
public int Dir => E.GetStateSnapshot().LinearDir;
public string Var(string name) => M.Expressions.Variables.TryGetValue(name, out string? v) ? v : "(unset)";
}
private static void At(double north, double east)
=> FakeHost.SetNavPosition(NS0 + north / 240.0, EW0 + east / 240.0);
private static NavPoint Pt(double north, double east)
=> new() { Type = NavPointType.Point, NS = NS0 + north / 240.0, EW = EW0 + east / 240.0 };
/// <summary>Points every 20 yd due north of the origin, from 0 (or 10 for <paramref name="from10"/>).</summary>
private static NavRouteParser Line(RT type, int count, bool from10 = false)
{
var r = new NavRouteParser { RouteType = type };
for (int i = 0; i < count; i++) r.Points.Add(Pt((from10 ? 10 : 0) + i * 20, 0));
return r;
}
private static MetaRule Rule(string state, C cond, string condData, A act, string actData)
=> new() { State = state, Condition = cond, ConditionData = condData, Action = act, ActionData = actData };
private static MetaRule EmbedNav(string name, C cond = C.Always, string condData = "")
=> Rule("Default", cond, condData, A.EmbeddedNavRoute, name);
/// <summary>A bot whose meta loads <paramref name="route"/> as "R" with an Always rule; ticked until it runs.</summary>
private static Bot Running(NavRouteParser route, params MetaRule[] more)
{
var bot = new Bot(new[] { EmbedNav("R") }.Concat(more).ToArray());
bot.S.EmbeddedNavs["R"] = route.ToLines();
bot.Tick();
return bot;
}
// ── Stop + start keeps the place ──────────────────────────────────────────
private static void OnceKeepsWaypoint()
{
FakeHost.Reset(); At(0, 0);
var bot = Running(Line(RT.Once, 4, from10: true)); // [0] 10, [1] 30, [2] 50, [3] 70 yd north
Check.Eq(bot.Idx, 0, "the meta loaded the Once route at [0]");
var loaded = bot.S.CurrentRoute;
At(10, 0); bot.Tick();
At(30, 0); bot.Tick();
Check.Eq(bot.Idx, 2, "walked on to [2]");
At(40, 0); bot.Tick(); // on the leg to [2]
bot.StopStart();
Check.True(ReferenceEquals(bot.S.CurrentRoute, loaded), "the route was not loaded again");
Check.Eq(bot.Idx, 2, "still heading for [2] (it went back to [0] before)");
Check.True(bot.S.EnableNavigation, "nav on");
At(50, 0); bot.Tick();
Check.Eq(bot.Idx, 3, "and carries on to [3]");
}
private static void CircularKeepsWaypoint()
{
FakeHost.Reset(); At(0, 0);
var bot = Running(Line(RT.Circular, 4)); // [0] 0, [1] 20, [2] 40, [3] 60
bot.Tick();
Check.Eq(bot.Idx, 1, "loaded at the nearest point [0], arrived, on to [1]");
var loaded = bot.S.CurrentRoute;
At(20, 0); bot.Tick();
At(32, 0); bot.Tick(); // on the leg to [2]
Check.Eq(bot.Idx, 2, "heading for [2]");
bot.StopStart();
Check.True(ReferenceEquals(bot.S.CurrentRoute, loaded), "the route was not loaded again");
Check.Eq(bot.Idx, 2, "still heading for [2]");
// Go To Closest Waypoint off: a loaded Circular route starts at [0], so the old reload sent it
// back there; the waypoint is kept even after walking away from the route while stopped.
bot.S.NavResumeNearest = false;
bot.S.IsMacroRunning = false; bot.E.Stop(); bot.Ticks(2);
At(5, 0); bot.Tick();
bot.S.IsMacroRunning = true; bot.Ticks(3);
Check.Eq(bot.Idx, 2, "option off: kept exactly");
Check.True(ReferenceEquals(bot.S.CurrentRoute, loaded), "same route");
}
private static void LinearKeepsDirection()
{
FakeHost.Reset(); At(0, 0);
var bot = Running(Line(RT.Linear, 3)); // [0] 0, [1] 20, [2] 40
bot.Tick();
At(20, 0); bot.Tick();
At(40, 0); bot.Tick();
Check.Eq(bot.Idx, 1, "turned round at the end, heading back to [1]");
Check.Eq(bot.Dir, -1, "heading back");
At(33, 0); bot.Tick(); // on the way back, nearer [2] than [1]
bot.StopStart();
Check.Eq(bot.Idx, 1, "still heading back to [1] (the reload sent it to the nearest point, [2])");
Check.Eq(bot.Dir, -1, "direction kept (the reload turned it round)");
At(20, 0); bot.Tick();
Check.Eq(bot.Idx, 0, "carries on back to [0]");
}
private static void FinishedOnceStaysFinished()
{
FakeHost.Reset(); At(0, 0);
// As the CQ metas do: one Always rule switches nav on and loads the route.
var all = Rule("Default", C.Always, "", A.All, "");
all.ActionChildren.Add(new MetaRule { Action = A.ChatCommand, ActionData = "/vt opt set enablenav true" });
all.ActionChildren.Add(new MetaRule { Action = A.EmbeddedNavRoute, ActionData = "R" });
var done = Rule("Default", C.NavrouteEmpty, "", A.ExpressionAction, "setvar[done, getvar[done]+1]");
var bot = new Bot(all, done);
bot.S.EmbeddedNavs["R"] = Line(RT.Once, 2, from10: true).ToLines();
bot.Tick();
var loaded = bot.S.CurrentRoute;
At(10, 0); bot.Tick();
At(30, 0); bot.Tick();
bot.Tick();
Check.Eq(bot.Idx, 2, "finished: the index is past the end");
Check.False(bot.S.EnableNavigation, "the end of a Once route turns nav off");
Check.Eq(bot.Var("done"), "1", "Nav route empty fired");
At(0, 0); bot.Tick(); // walks back to the start
bot.StopStart();
bot.Ticks(5);
Check.True(ReferenceEquals(bot.S.CurrentRoute, loaded), "the route was not loaded again");
Check.Eq(bot.Idx, 2, "still finished (it ran again from [0] before)");
Check.False(bot.S.EnableNavigation, "nav off again after the replayed enablenav");
Check.False(FakeHost.AutoRun, "standing still");
Check.Eq(bot.Var("done"), "2", "Nav route empty is true straight away after the start");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("Once route re-armed")), 0, "never re-armed");
// The engine alone: the macro-start closest pick leaves a finished route alone.
bot.E.ResumeFromNearestWaypoint(always: true);
Check.Eq(bot.Idx, 2, "the closest-waypoint pick (death recall, hazard escape) keeps it finished");
// A meta or expression switching nav on: it stays finished.
bot.S.EnableNavigation = true;
bot.Ticks(2);
Check.Eq(bot.Idx, 2, "nav switched on by a meta: still finished");
Check.False(bot.S.EnableNavigation, "and nav off again");
}
// ── Loading again starts fresh ────────────────────────────────────────────
private static void LoadAgainStartsFresh()
{
FakeHost.Reset(); At(0, 0);
var bot = Running(Line(RT.Once, 4, from10: true));
At(10, 0); bot.Tick();
At(30, 0); bot.Tick();
Check.Eq(bot.Idx, 2, "on [2]");
// A real state entry (SetMetaState to the state it is in) loads it fresh, as before.
var first = bot.S.CurrentRoute;
bot.S.ForceStateReset = true;
bot.Tick();
Check.False(ReferenceEquals(bot.S.CurrentRoute, first), "state entry: loaded again");
Check.Eq(bot.Idx, 0, "state entry: a Once route starts at [0]");
// Edited while stopped: the replay loads the meta's copy fresh.
At(10, 0); bot.Tick();
At(30, 0); bot.Tick();
Check.Eq(bot.Idx, 2, "on [2] again");
bot.S.IsMacroRunning = false; bot.E.Stop(); bot.Ticks(2);
var edited = bot.S.CurrentRoute;
edited.Points.Add(Pt(90, 0));
bot.S.IsMacroRunning = true; bot.Ticks(2);
Check.False(ReferenceEquals(bot.S.CurrentRoute, edited), "edited: loaded again");
Check.Eq(bot.S.CurrentRoute.Points.Count, 4, "from the meta's copy");
Check.Eq(bot.Idx, 0, "edited: starts at [0]");
// Another route loaded while stopped: the meta puts its own back, fresh.
bot.S.IsMacroRunning = false; bot.E.Stop(); bot.Ticks(2);
bot.S.CurrentRoute = Line(RT.Circular, 2);
bot.S.CurrentNavPath = "<embedded:Other>";
bot.S.ActiveNavIndex = 1;
bot.S.IsMacroRunning = true; bot.Ticks(2);
Check.Eq(bot.S.CurrentNavPath, "<embedded:R>", "the meta's route is back");
Check.Eq(bot.S.CurrentRoute.RouteType, RT.Once, "Once");
Check.Eq(bot.Idx, 0, "at [0]");
}
private static void FirstFireAfterStartIsFresh()
{
FakeHost.Reset(); At(0, 0);
// Rule 2 reloads the same route after 30 s in the state; it hadn't fired when the macro stopped.
var bot = Running(Line(RT.Once, 4, from10: true), EmbedNav("R", C.SecondsInState_GE, "30"));
At(10, 0); bot.Tick();
At(30, 0); bot.Tick();
bot.StopStart();
Check.Eq(bot.Idx, 2, "the replayed Always rule kept [2]");
var kept = bot.S.CurrentRoute;
bot.Tick(metaSeconds: 31);
Check.False(ReferenceEquals(bot.S.CurrentRoute, kept), "the 30 s rule (a first fire, not a replay) loaded it again");
Check.Eq(bot.Idx, 0, "fresh: [0]");
}
private static void ChatNavLoadKept()
{
FakeHost.Reset(); At(0, 0);
string folder = Path.Combine(Program.TempRoot, "nav-resume", "NavProfiles");
Directory.CreateDirectory(folder);
string path = Path.Combine(folder, "Hive.nav");
Line(RT.Once, 4, from10: true).Save(path);
foreach (string cmd in new[] { "/vt nav load Hive", "/ra nav load Hive.nav" })
{
var bot = new Bot(Rule("Default", C.Always, "", A.ChatCommand, cmd));
bot.M.NavFolder = folder;
bot.Tick();
Check.Eq(bot.Ra.Count, 1, $"{cmd}: the first start loads it through /ra nav load");
// What /ra nav load did (LegacyDashboardRenderer.LoadSelectedNav), then walked to [2].
bot.S.CurrentNavPath = path;
bot.S.CurrentRoute = NavRouteParser.Load(path);
bot.S.ActiveNavIndex = 0;
bot.S.EnableNavigation = true;
var loaded = bot.S.CurrentRoute;
At(10, 0); bot.Tick();
At(30, 0); bot.Tick();
Check.Eq(bot.Idx, 2, $"{cmd}: on [2]");
bot.StopStart();
Check.Eq(bot.Ra.Count, 1, $"{cmd}: the replay did not load it again");
Check.True(ReferenceEquals(bot.S.CurrentRoute, loaded) && bot.Idx == 2, $"{cmd}: still on [2]");
// The file changed on disk: the replay loads it again, as before.
var changed = Line(RT.Once, 5, from10: true);
changed.Save(path);
bot.StopStart();
Check.Eq(bot.Ra.Count, 2, $"{cmd}: a changed file is loaded again");
Line(RT.Once, 4, from10: true).Save(path);
At(0, 0);
}
// A state that restarts its route on entry: not again for a macro start.
var restarter = new Bot(Rule("Default", C.Always, "", A.ChatCommand, "/ra nav restart"));
restarter.Tick();
Check.Eq(string.Join("|", restarter.Ra), "/ra nav restart", "on entering the state it runs");
restarter.StopStart();
Check.Eq(restarter.Ra.Count, 1, "a replayed /ra nav restart is not run again");
restarter.S.ForceStateReset = true;
restarter.Tick();
Check.Eq(restarter.Ra.Count, 2, "a real state entry runs it again");
}
// ── /ra nav restart and the player's Nav switch ───────────────────────────
private static void RestartCommand()
{
FakeHost.Reset(); At(0, 0);
var s = new LegacyUiSettings { IsMacroRunning = true };
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
void Set(string f, object v) => typeof(LegacyDashboardRenderer).GetField(f, Any)!.SetValue(dash, v);
Set("_settings", s);
Set("_host", FakeHost.Create());
Set("_navFiles", new List<string>());
Set("_metaFiles", new List<string>());
Set("_profileListsLock", new object());
// _settingsFilePath stays null: SaveSettings writes nothing.
var plugin = new RynthAiPlugin();
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi });
_now = 1_000_000;
NavigationEngine.Clock = static () => _now;
var engine = new NavigationEngine(FakeHost.Create(), s);
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(plugin, dash);
typeof(RynthAiPlugin).GetField("_navigationEngine", Any)!.SetValue(plugin, engine);
MethodInfo dispatch = typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!;
void Ra(string line)
{
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
dispatch.Invoke(plugin, new object[] { parts[1].ToLowerInvariant(), parts, 0 });
}
void Tick() { _now += 100; engine.Tick(); }
Ra("/ra nav restart");
Check.True(FakeHost.Chat.Exists(l => l.Contains("No nav route loaded to restart")), "nothing loaded: says so");
// A finished Once route.
s.CurrentRoute = Line(RT.Once, 2, from10: true);
s.ActiveNavIndex = 2;
s.EnableNavigation = false;
FakeHost.Chat.Clear();
Ra("/ra nav restart");
Check.Eq(s.ActiveNavIndex, 0, "restart: back to [0]");
Check.True(s.EnableNavigation, "restart: nav on");
Check.True(FakeHost.Chat.Exists(l => l.Contains("Nav route restarted from its first point (Once, 2 waypoints)")), "told: " + string.Join(" / ", FakeHost.Chat));
Tick();
Check.True(FakeHost.AutoRun, "and it walks");
// A Linear route heading back starts out again.
s.CurrentRoute = Line(RT.Linear, 3);
s.ActiveNavIndex = 0;
At(0, 0); Tick();
At(20, 0); Tick();
At(40, 0); Tick();
Check.Eq(engine.GetStateSnapshot().LinearDir, -1, "Linear heading back");
Ra("/ra nav restart");
Check.Eq(s.ActiveNavIndex, 0, "Linear restart: [0]");
Check.Eq(engine.GetStateSnapshot().LinearDir, 1, "Linear restart: heading out");
// The player's Nav switch (dashboard, mini remote, phone) re-runs a finished Once route.
s.CurrentRoute = Line(RT.Once, 2, from10: true);
s.ActiveNavIndex = 2;
s.EnableNavigation = false;
dash.SetSubsystemEnabled(2, true);
Check.Eq(s.ActiveNavIndex, 0, "Nav switch on: a finished Once route runs again from [0]");
s.ActiveNavIndex = 1;
dash.SetSubsystemEnabled(2, false);
dash.SetSubsystemEnabled(2, true);
Check.Eq(s.ActiveNavIndex, 1, "Nav switch off and on mid-route: the waypoint is kept");
FakeHost.Chat.Clear();
Ra("/ra nav");
Check.True(FakeHost.Chat.Exists(l => l.Contains("/ra nav restart")), "listed in the /ra nav usage");
}
}

View file

@ -0,0 +1,564 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The shield's armor spells (BuffManager.Shield.cs, 2026-10-28). Impenetrability and the Banes go
// on the player, and ACE puts them on worn armor and a worn shield; but buffing holds a wand, ACE
// won't wield one beside a shield, and the wand swap puts the shield into a pack first, so the
// listed shield was never buffed. Now: the listed shield in use (in the off hand, or put away for
// the wand) gets the armor's spells aimed at it, after the armor, on the armor's timers. Weapon
// enchantments never go on it; an unlisted shield or a listed one that was in a pack is left alone;
// a shield being moved waits; a refusal at the shield leaves the armor alone.
internal static class ShieldBuffTests
{
private const uint Player = 0x50000E01;
private const uint STypeItem = 32;
private const uint Sword = 0x80000701, Kite = 0x80000702, Round = 0x80000703;
private const int MeleeSlot = 0x00100000, ShieldSlot = 0x00200000;
private static readonly string[] Armor = { "Impenetrability VI", "Flame Bane VI", "Frost Bane VI" };
private const string Aura = "Aura of Blood Drinker Self VI";
public static void Register(Runner r)
{
r.Add("shield buffs: the armor spells, never a weapon enchantment", WhichSpells);
r.Add("shield buffs: the listed shield put away for the wand gets Impenetrability and the banes, aimed at it, after the armor", StowedShieldBuffed);
r.Add("shield buffs: a shield worn in the off hand (no wand) is buffed; a self-cast line naming it counts for it", WornShieldBuffed);
r.Add("shield buffs: no shield listed, an unlisted shield, a listed one already in a pack, or the switch off: nothing goes on a shield", NothingForOtherShields);
r.Add("shield buffs: put away for the wand, back in the off hand, then into a pack by combat: no longer the one in use", StowedForgottenWhenBackOn);
r.Add("shield buffs: a shield being moved is not cast at until the move settles", MidSwapWaits);
r.Add("shield buffs: renewed on the armor's timers (Rebuff With, Also Refresh Under, Force Rebuff)", RenewedLikeArmor);
r.Add("shield buffs: a fizzle, a refusal or a late armor line at the shield leaves the armor alone", RefusalsLeaveArmor);
r.Add("shield buffs: casts at the shield with no answer, or 'cannot be cast on', rest shield buffing; the armor carries on", NoAnswerParks);
r.Add("shield buffs: the shield's timers are saved and loaded with the others", TimersSaved);
r.Add("shield buffs: Buff the shield defaults on, loads, saves, copies, is in the settings map", Setting);
}
// ── Rig ───────────────────────────────────────────────────────────────────
private static readonly MethodInfo CastSelfBuffs =
typeof(BuffManager).GetMethod("CheckAndCastSelfBuffs", BindingFlags.NonPublic | BindingFlags.Instance)!;
private const BindingFlags F = BindingFlags.NonPublic | BindingFlags.Instance;
private static int Id(string name) => SpellTable.Named(name).Select(r => r.Id).FirstOrDefault();
private static string NameOf(int id) => SpellTable.ById(id)?.Name ?? $"#{id}";
private static int FamilyOf(string name) => SpellTableStub.GetById(Id(name))?.Family ?? 0;
private static T Fld<T>(BuffManager b, string name) => (T)typeof(BuffManager).GetField(name, F)!.GetValue(b)!;
private static void SetFld(BuffManager b, string name, object v) => typeof(BuffManager).GetField(name, F)!.SetValue(b, v);
private sealed class Rig
{
public readonly LegacyUiSettings S = new() { EnableBuffing = true };
public readonly BuffManager B;
public readonly SpellManager Sm;
public readonly RynthCoreHost Host;
public readonly WeaponSwapGate Gate = new();
public long GateMs;
public int Stowed;
/// <summary>Item Magic 300 (tier 6), in Magic stance, knowing Impenetrability, two banes and Blood Drinker.
/// A sword and the Kite Shield listed; <paramref name="worn"/>: the Kite Shield in the off hand.</summary>
public Rig(bool worn = false, bool listShield = true)
{
FakeHost.Reset();
foreach (string n in Armor.Append(Aura)) foreach (var row in SpellTable.Named(n)) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeItem)] = (300, 2);
FakeHost.WeaponCalls = true; // GetCurrentCombatMode answers CombatModeValue
FakeHost.CombatModeValue = CombatMode.Magic;
Item(Sword, "Long Sword", 0x1, MeleeSlot, combatUse: 1);
Item(Kite, "Kite Shield", 0x2, ShieldSlot, combatUse: 4);
Item(Round, "Round Shield", 0x2, ShieldSlot, combatUse: 4);
if (worn) Wear(Kite);
Host = FakeHost.Create(Player);
var cache = FakeHost.MakeCache(Host, Player, new[] { Sword, Kite, Round });
var skills = new CharacterSkills(Host);
skills.SetPlayerId(Player);
Sm = new SpellManager(Host, S);
Sm.InitializeNatively();
Sm.SetCharacterSkills(skills);
B = new BuffManager(Host, S, Sm, new PlayerVitalsCache());
B.SetCharacterSkills(skills);
B.SetWorldObjectCache(cache);
Gate.NowMs = () => GateMs;
B.SetWeaponSwapGate(Gate);
B.ShieldReadMs = 0;
B.OffhandStowed = id => Stowed = id;
FakeHost.ServerTime = 100_000;
List(listShield ? new[] { Sword, Kite } : new[] { Sword });
}
public void List(params uint[] ids) =>
S.ItemRules = ids.Select(i => new ItemRule
{
Id = unchecked((int)i), Name = FakeHost.Names[i], Element = "", ElementSource = "",
Action = i == Kite || i == Round ? WeaponList.ShieldAction : "Weapon",
}).ToList();
/// <summary>The wand swap put the Kite Shield into a pack (BuffManager's MoveToPack step).</summary>
public void PutAwayForWand()
{
B.OffhandPutAway(unchecked((int)Kite));
Unwear(Kite);
}
/// <summary>
/// The buff step until it casts nothing, every cast answered as the server would: a cast at the
/// player names the armor (and, with <paramref name="alsoOnShield"/>, the worn shield too), a cast
/// at a shield names it. Ends the run as the heartbeat does. Returns "spell@target" in order.
/// </summary>
public List<string> CastAll(Func<string, bool>? alsoOnShield = null, int max = 40)
{
var sent = new List<string>();
for (int i = 0; i < max; i++)
{
int before = FakeHost.Casts.Count;
CastSelfBuffs.Invoke(B, null);
if (FakeHost.Casts.Count == before) break;
var (target, id) = FakeHost.Casts.Last();
string name = NameOf(id);
sent.Add($"{name}@{Where(target)}");
Answer(target, name, alsoOnShield?.Invoke(name) == true);
}
EndRun();
return sent;
}
public void Answer(uint target, string name, bool alsoOnShield = false)
{
if (target == Player)
{
B.OnChatWindowText($"You cast {name} on {(BuffManager.IsItemEnchantment(name) ? "Rune Robe" : "yourself")}", 7);
if (alsoOnShield) B.OnChatWindowText($"You cast {name} on Kite Shield, refreshing {name}", 7);
}
else B.OnChatWindowText($"You cast {name} on {FakeHost.Names[target]}", 7);
}
public void EndRun()
{
if (!(bool)typeof(BuffManager).GetField("_isForceRebuffing", F)!.GetValue(B)!) return;
SetFld(B, "_isForceRebuffing", false);
SetFld(B, "_isAutoBatchRebuff", false);
typeof(BuffManager).GetMethod("ClearRunFamilies", F)!.Invoke(B, null);
}
public void SetShieldLeft(string spell, double seconds) =>
SetLeft(Record("_shieldSpellTimers", BuffManager.ShieldKey(unchecked((int)Kite), FamilyOf(spell))), seconds);
public void SetArmorLeft(string spell, double seconds) => SetLeft(Record("_itemSpellTimers", FamilyOf(spell)), seconds);
private static void SetLeft(object rec, double seconds) => rec.GetType().GetField("ExpiresAt")!.SetValue(rec, DateTime.Now.AddSeconds(seconds));
public object Record(string field, object key) => ((IDictionary)Fld<object>(B, field))[key]!;
public bool HasShield(string spell) => ((IDictionary)Fld<object>(B, "_shieldSpellTimers")).Contains(BuffManager.ShieldKey(unchecked((int)Kite), FamilyOf(spell)));
public bool HasArmor(string spell) => ((IDictionary)Fld<object>(B, "_itemSpellTimers")).Contains(FamilyOf(spell));
}
private static string Where(uint target) => target == Player ? "player" : FakeHost.Names.TryGetValue(target, out string? n) ? n : $"0x{target:X8}";
private static void Item(uint id, string name, uint itemType, int validSlots, int combatUse = 0)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = itemType;
FakeHost.Ints[(id, 9)] = validSlots;
if (combatUse != 0) FakeHost.Ints[(id, 51)] = combatUse;
}
private static void Wear(uint id) => FakeHost.Ints[(id, 10)] = ShieldSlot;
private static void Unwear(uint id) => FakeHost.Ints.Remove((id, 10));
private static IEnumerable<string> At(List<string> sent, string target) =>
sent.Where(s => s.EndsWith("@" + target, StringComparison.Ordinal)).Select(s => s.Substring(0, s.LastIndexOf('@')));
private static string ArmorAtPlayer => string.Join(", ", Armor);
// ── Tests ─────────────────────────────────────────────────────────────────
private static void WhichSpells()
{
foreach (string n in new[] { "Impenetrability VI", "Brogard's Defiance", "Incantation of Impenetrability", "Flame Bane VI",
"Swordsman's Bane", "Incantation of Bludgeon Bane", "Acid Bane", "Piercing Bane" })
Check.True(BuffManager.IsArmorItemSpell(n), $"an armor spell: {n}");
foreach (string n in new[] { "Blood Drinker Self", Aura, "Aura of Infected Caress", "Defender Self", "Aura of Cragstone's Will",
"Heart Seeker Self", "Spirit Drinker Self", "Armor Self", "Impregnability Self VI", "Strength Self VI" })
Check.False(BuffManager.IsArmorItemSpell(n), $"not an armor spell: {n}");
Check.Eq(BuffManager.CastTarget("Flame Bane VI on Kite Shield, refreshing Flame Bane V"), "Kite Shield", "the target, before the comma");
Check.Eq(BuffManager.CastTarget("Impenetrability VI on Kite Shield"), "Kite Shield", "the target alone");
Check.Eq(BuffManager.CastTarget("Strength Self VI"), "", "no target");
Check.True(BuffManager.ShieldKey(1, 2) != BuffManager.ShieldKey(2, 1), "the key keeps the shield and the family apart");
}
private static void StowedShieldBuffed()
{
var rig = new Rig(worn: true);
rig.PutAwayForWand(); // what the wand swap does before the first cast
Check.Eq(rig.Stowed, unchecked((int)Kite), "combat is still told, so it puts the shield back on");
Check.Eq(rig.B.ShieldToBuff(out string where), unchecked((int)Kite), "the shield to buff: " + where);
Check.True(rig.B.NeedsAnyBuff(), "nothing on: needs buffs");
var sent = rig.CastAll();
Check.Eq(string.Join(", ", At(sent, "player")), $"{Aura}, {ArmorAtPlayer}", "the character's buffs first, as before");
Check.Eq(string.Join(", ", At(sent, "Kite Shield")), ArmorAtPlayer, "then Impenetrability and both banes at the shield");
Check.True(sent.Last().EndsWith("@Kite Shield", StringComparison.Ordinal) && sent.FindIndex(s => s.EndsWith("@Kite Shield")) == 4,
"the shield's after every cast on the player: " + string.Join(", ", sent));
Check.False(FakeHost.Casts.Any(c => c.Target == Kite && NameOf(c.SpellId) == Aura), "Blood Drinker never at the shield");
Check.Eq(rig.B.ShieldSpellCount, 3, "three timers on the shield");
foreach (string a in Armor) Check.True(rig.HasArmor(a) && rig.HasShield(a), $"{a}: the armor's and the shield's timer");
Check.False(rig.B.NeedsAnyBuff(), "all on: nothing due");
Check.Eq(rig.CastAll().Count, 0, "and nothing more is cast");
// Force Rebuff: the armor and the shield again, still no weapon enchantment at it.
rig.B.ForceFullRebuff();
sent = rig.CastAll();
Check.Eq(string.Join(", ", At(sent, "Kite Shield")), ArmorAtPlayer, "Force Rebuff recasts the shield's too");
Check.False(FakeHost.Casts.Any(c => c.Target == Kite && !BuffManager.IsArmorItemSpell(NameOf(c.SpellId))), "only armor spells ever at the shield");
Check.True(FakeHost.Logs.Any(l => l.Contains("[Buff] shield: 0x") && l.Contains("put into a pack for the wand")), "the shield picked is logged");
}
private static void WornShieldBuffed()
{
// Magic without a wand: the shield stays on, the self-cast's lines don't name it.
var rig = new Rig(worn: true);
Check.Eq(rig.B.ShieldToBuff(out string where), unchecked((int)Kite), "the worn shield: " + where);
Check.Eq(where, "in the off hand", "in the off hand");
var sent = rig.CastAll();
Check.Eq(string.Join(", ", At(sent, "Kite Shield")), ArmorAtPlayer, "each armor spell aimed at the worn shield");
// The server's self-cast reached the worn shield: its line names it. Flame Bane's shield line
// comes after the armor's, Impenetrability's before (the self-cast still resolves by it).
var both = new Rig(worn: true);
sent = both.CastAll(alsoOnShield: n => n == "Flame Bane VI");
Check.Eq(string.Join(", ", At(sent, "Kite Shield")), "Impenetrability VI, Frost Bane VI", "Flame Bane's line named the shield: only the other two are cast at it");
Check.True(both.HasShield("Flame Bane VI") && both.HasArmor("Flame Bane VI"), "that line counts for the shield, and the armor's line for the armor");
var first = new Rig(worn: true);
first.B.ForceFullRebuff();
for (int i = 0; i < 10; i++)
{
int before = FakeHost.Casts.Count;
CastSelfBuffs.Invoke(first.B, null);
if (FakeHost.Casts.Count == before) break;
var (target, id) = FakeHost.Casts.Last();
string name = NameOf(id);
if (target == Player && name == "Impenetrability VI")
{
first.B.OnChatWindowText("You cast Impenetrability VI on Kite Shield", 7); // the shield's line first
Check.Eq(first.B.PendingSpellId, 0, "the self-cast is resolved by the shield's line too");
first.B.OnChatWindowText("You cast Impenetrability VI on Rune Robe", 7);
}
else first.Answer(target, name);
}
first.EndRun();
Check.True(first.HasShield("Impenetrability VI") && first.HasArmor("Impenetrability VI"), "both timers");
Check.False(FakeHost.Casts.Any(c => c.Target == Kite && NameOf(c.SpellId) == "Impenetrability VI"), "Impenetrability isn't cast at the shield again");
}
private static void NothingForOtherShields()
{
// The baseline: no shield listed (a worn one), exactly the casts there always were.
var none = new Rig(worn: true, listShield: false);
var sent = none.CastAll();
Check.Eq(string.Join(", ", sent), $"{Aura}@player, " + string.Join(", ", Armor.Select(a => a + "@player")), "no shield listed: the same casts as before");
Check.Eq(none.B.ShieldToBuff(out _), 0, "no shield to buff");
Check.False(none.B.NeedsAnyBuff(), "and nothing due");
Check.False(FakeHost.Logs.Any(l => l.Contains("[Buff] shield:")), "nothing logged about shields");
// An unlisted shield worn, the listed one in a pack and never put away by buffing.
var unlisted = new Rig();
Wear(Round);
sent = unlisted.CastAll();
Check.Eq(At(sent, "Round Shield").Count() + At(sent, "Kite Shield").Count(), 0, "nothing at the unlisted worn shield, nor the listed one in a pack");
Check.Eq(unlisted.B.ShieldToBuff(out string why), 0, "none to buff: " + why);
Check.True(why.Contains("in a pack"), "the reason says it is in a pack");
Check.False(unlisted.B.NeedsAnyBuff(), "nothing due: a shield in a pack doesn't hold Buffing");
// A shield filed with the Weapon action is still a listed shield.
var asWeapon = new Rig(worn: true);
asWeapon.S.ItemRules = new List<ItemRule>
{
new() { Id = unchecked((int)Sword), Name = "Long Sword", Action = "Weapon", Element = "", ElementSource = "" },
new() { Id = unchecked((int)Kite), Name = "Kite Shield", Action = "Weapon", Element = "", ElementSource = "" },
};
Check.Eq(asWeapon.B.ShieldToBuff(out _), unchecked((int)Kite), "a shield listed as a weapon is the listed shield");
// Buff the shield off.
var off = new Rig(worn: true);
off.S.BuffShield = false;
sent = off.CastAll();
Check.Eq(At(sent, "Kite Shield").Count(), 0, "switch off: nothing at the shield");
Check.Eq(string.Join(", ", At(sent, "player")), $"{Aura}, {ArmorAtPlayer}", "the armor as always");
Check.False(off.B.NeedsAnyBuff(), "and nothing due");
// Banes unticked for the armor are unticked for the shield.
var unticked = new Rig(worn: true);
unticked.S.SetBuffEnabled("Flame Bane", false);
sent = unticked.CastAll();
Check.Eq(string.Join(", ", At(sent, "Kite Shield")), "Impenetrability VI, Frost Bane VI", "an unticked bane goes on neither");
Check.False(At(sent, "player").Contains("Flame Bane VI"), "(nor the armor)");
}
private static void StowedForgottenWhenBackOn()
{
var rig = new Rig(worn: true);
rig.PutAwayForWand();
Wear(Kite); // combat put it back on
Check.Eq(rig.B.ShieldToBuff(out _), unchecked((int)Kite), "in the off hand");
Unwear(Kite); // still within the grace: a stow just sent
Check.Eq(rig.B.ShieldToBuff(out string where), unchecked((int)Kite), "a sighting right after the stow doesn't forget it: " + where);
Wear(Kite);
SetFld(rig.B, "_stowedShieldAt", DateTime.Now.AddSeconds(-30));
Check.Eq(rig.B.ShieldToBuff(out _), unchecked((int)Kite), "back in the off hand for a while");
Unwear(Kite); // combat took it off for a two-hander
Check.Eq(rig.B.ShieldToBuff(out where), 0, "then in a pack by combat's hand: not the one in use (" + where + ")");
rig.PutAwayForWand();
Check.Eq(rig.B.ShieldToBuff(out _), unchecked((int)Kite), "put away for the wand again: buffed again");
}
private static void MidSwapWaits()
{
var rig = new Rig(worn: true);
rig.PutAwayForWand();
// Combat's off-hand move of the shield, just claimed (the gate waits MinIntervalMs for it).
rig.GateMs = 1000;
Check.True(rig.Gate.TryBeginSwap("combat-offhand"), "a swap claimed");
rig.Gate.NoteMove(unchecked((int)Kite), wieldedNow: false);
var sent = rig.CastAll();
Check.Eq(At(sent, "Kite Shield").Count(), 0, "nothing at the shield while it moves");
Check.Eq(string.Join(", ", At(sent, "player")), $"{Aura}, {ArmorAtPlayer}", "the character's buffs don't wait");
Check.True((bool)CastSelfBuffs.Invoke(rig.B, null)!, "the step holds the tick (not done)");
Check.True(rig.B.LastBuffSkipReason.Contains("being moved"), "and says why: " + rig.B.LastBuffSkipReason);
rig.EndRun();
Check.True(rig.B.NeedsAnyBuff(), "the shield is still due");
rig.GateMs = 1000 + rig.Gate.MinIntervalMs + 1; // the move has settled
sent = rig.CastAll();
Check.Eq(string.Join(", ", At(sent, "Kite Shield")), ArmorAtPlayer, "settled: the shield's spells go");
// A multi-step swap holding the gate: wait; released: go.
var held = new Rig(worn: true);
held.PutAwayForWand();
held.Gate.Hold("combat-fight-swap", 60_000);
sent = held.CastAll();
Check.Eq(At(sent, "Kite Shield").Count(), 0, "a held swap: nothing at the shield");
held.Gate.Release("combat-fight-swap", 0);
sent = held.CastAll();
Check.Eq(string.Join(", ", At(sent, "Kite Shield")), ArmorAtPlayer, "released: the shield's spells go");
}
private static void RenewedLikeArmor()
{
var rig = new Rig(worn: true);
rig.PutAwayForWand();
rig.CastAll();
foreach (string a in Armor)
{
object s = rig.Record("_shieldSpellTimers", BuffManager.ShieldKey(unchecked((int)Kite), FamilyOf(a)));
object m = rig.Record("_itemSpellTimers", FamilyOf(a));
double Len(object rec) => ((DateTime)rec.GetType().GetField("ExpiresAt")!.GetValue(rec)! - (DateTime)rec.GetType().GetField("CastAt")!.GetValue(rec)!).TotalSeconds;
Check.Near(Len(s), Len(m), 0.5, $"{a}: the shield's timer is as long as the armor's");
Check.Near(Len(s), 2700, 0.5, $"{a}: 45 minutes at level 6");
}
Check.False(rig.B.NeedsAnyBuff(), "all on");
// The shield's Flame Bane under Rebuff With (300 s): due on its own, and only it is recast.
rig.SetShieldLeft("Flame Bane VI", 100);
Check.True(rig.B.NeedsAnyBuff(), "the shield's bane running out: due, like the armor's");
var sent = rig.CastAll();
Check.Eq(string.Join(", ", sent), "Flame Bane VI@Kite Shield", "only that one, at the shield");
// The armor's Frost Bane under Rebuff With, the shield's under Also Refresh Under (1200 s): they land together.
rig.SetArmorLeft("Frost Bane VI", 100);
rig.SetShieldLeft("Frost Bane VI", 1000);
sent = rig.CastAll();
Check.Eq(string.Join(", ", sent), "Frost Bane VI@player, Frost Bane VI@Kite Shield", "the batch tops off the shield's with the armor's");
// Under Also Refresh Under alone starts nothing, as for the armor.
rig.SetShieldLeft("Impenetrability VI", 1000);
Check.False(rig.B.NeedsAnyBuff(), "1000 s left is no reason to buff");
rig.S.RebuffSecondsRemaining = 1100;
Check.True(rig.B.NeedsAnyBuff(), "with Rebuff With 1100 it is");
rig.S.RebuffSecondsRemaining = 300;
// A death (the player's registry empties) forgets the shield's, as the armor's.
FakeHost.Enchantments.Clear();
FakeHost.Enchantments.Add(((uint)Id("Strength Self I"), FakeHost.ServerTime + 3000)); // something on, then nothing
rig.B.RefreshFromLiveMemory();
FakeHost.Enchantments.Clear();
rig.B.RefreshFromLiveMemory();
Check.Eq(rig.B.ShieldSpellCount, 0, "a death clears the shield's timers");
Check.True(rig.B.NeedsAnyBuff(), "and they are due again");
}
/// <summary>Runs the step until a cast at the Kite Shield is pending (everything else answered); its spell.</summary>
private static string ToFirstShieldCast(Rig rig)
{
for (int i = 0; i < 20; i++)
{
int before = FakeHost.Casts.Count;
CastSelfBuffs.Invoke(rig.B, null);
if (FakeHost.Casts.Count == before) return "";
var (target, id) = FakeHost.Casts.Last();
if (target == Kite) return NameOf(id);
rig.Answer(target, NameOf(id));
}
return "";
}
private static Dictionary<int, DateTime> ArmorParks(Rig rig) => Fld<Dictionary<int, DateTime>>(rig.B, "_buffFailCooldownUntil");
private static void RefusalsLeaveArmor()
{
var rig = new Rig(worn: true);
rig.PutAwayForWand();
rig.B.ForceFullRebuff();
string first = ToFirstShieldCast(rig);
Check.Eq(first, "Impenetrability VI", "the first cast at the shield");
// A late armor line of the same family while the shield's cast waits: the armor's, pending kept.
rig.B.OnChatWindowText("You cast Impenetrability VI on Rune Robe", 7);
Check.Eq(rig.B.PendingSpellId, Id("Impenetrability VI"), "the shield's cast still waits for its own line");
Check.False(rig.HasShield("Impenetrability VI"), "the armor's line doesn't count for the shield");
// A fizzle at the shield: the armor's timer stays, the shield's spell goes again.
rig.B.OnChatWindowText("Your spell fizzled.", 7);
Check.Eq(rig.B.PendingSpellId, 0, "the fizzle ends the cast");
Check.True(rig.HasArmor("Impenetrability VI"), "the armor's Impenetrability is still on");
Check.Eq(ToFirstShieldCast(rig), "Impenetrability VI", "and it is cast at the shield again");
// No components, at the shield: it rests on the shield only; the next bane goes at it.
rig.B.OnChatWindowText("You don't have all the components for this spell.", 7);
Check.True(rig.HasArmor("Impenetrability VI"), "the armor's timer stays");
Check.False(ArmorParks(rig).ContainsKey(FamilyOf("Impenetrability VI")), "the armor's family isn't parked");
Check.True(FakeHost.Chat.Any(l => l.Contains("Skipping Impenetrability VI on the shield")), "the chat line says on the shield");
Check.Eq(ToFirstShieldCast(rig), "Flame Bane VI", "the next spell goes at the shield");
rig.Answer(Kite, "Flame Bane VI");
// Not enough mana at the shield: the same, the armor's family untouched.
Check.Eq(ToFirstShieldCast(rig), "Frost Bane VI", "Frost Bane at the shield");
rig.B.OnChatWindowText("You don't have enough Mana to cast this spell.", 7);
Check.Eq(rig.B.PendingSpellId, 0, "the mana refusal ends it");
Check.True(rig.HasArmor("Frost Bane VI"), "the armor's Frost Bane stays");
Check.False(ArmorParks(rig).ContainsKey(FamilyOf("Frost Bane VI")), "nor is the armor's family rested");
// Too busy at the shield: the armor's timer stays.
var busy = new Rig(worn: true);
busy.PutAwayForWand();
Check.Eq(ToFirstShieldCast(busy), "Impenetrability VI", "a cast at the shield");
busy.B.OnChatWindowText("You're too busy!", 7);
Check.Eq(busy.B.PendingSpellId, 0, "too busy: no longer pending");
Check.True(busy.HasArmor("Impenetrability VI"), "the armor's timer stays");
}
private static void NoAnswerParks()
{
var rig = new Rig(worn: true);
rig.PutAwayForWand();
rig.S.IsMacroRunning = true;
rig.S.SpellCastIntervalMs = 0;
DateTime t0 = new DateTime(2026, 10, 28, 12, 0, 0), now = t0;
rig.B.Clock = () => now;
rig.B.MarkLiveBuffsReadyForTests();
FakeHost.Enchantments.Add(((uint)Id("Strength Self I"), FakeHost.ServerTime + 3000)); // a registry with something on
rig.B.RefreshFromLiveMemory();
// The heartbeat, every cast at the player answered, the shield's never.
int shieldSends = 0;
for (int i = 0; i < 80; i++)
{
now = now.AddSeconds(3);
int before = FakeHost.Casts.Count;
rig.B.OnHeartbeat();
if (FakeHost.Casts.Count == before)
{
if (rig.B.PendingSpellId != 0 && FakeHost.Casts.Count > 0 && FakeHost.Casts.Last().Target == Kite)
SetFld(rig.B, "_lastCastAttempt", DateTime.Now.AddSeconds(-6)); // its give-up reached
continue;
}
var (target, id) = FakeHost.Casts.Last();
if (target == Kite) { shieldSends++; continue; }
rig.Answer(target, NameOf(id));
}
Check.Eq(shieldSends, BuffManager.ShieldNoShowsToPark, $"{BuffManager.ShieldNoShowsToPark} casts at the shield, no more");
Check.True(FakeHost.Chat.Any(l => l.Contains("Not buffing the shield 'Kite Shield'")), "the rest is said in chat");
Check.False(rig.B.NeedsAnyBuff(), "parked: the shield doesn't hold Buffing");
Check.Eq(ArmorParks(rig).Count, 0, "no armor family parked");
Check.Eq(Fld<Dictionary<int, int>>(rig.B, "_silentNoShowCounts").Count, 0, "no armor no-show strikes");
Check.Eq(rig.Sm.UnresolvableSpellIds.Count, 0, "no spell blacklisted (it just went on the armor)");
Check.True(Armor.All(rig.HasArmor), "the armor got everything");
// "cannot be cast on" (ACE IsInvalidTarget) parks it at once.
var invalid = new Rig(worn: true);
invalid.PutAwayForWand();
Check.Eq(ToFirstShieldCast(invalid), "Impenetrability VI", "a cast at the shield");
invalid.B.OnChatWindowText("Impenetrability VI cannot be cast on Kite Shield.", 7);
Check.Eq(invalid.B.PendingSpellId, 0, "it ends the cast");
invalid.EndRun();
Check.False(invalid.B.NeedsAnyBuff(), "the shield rests");
Check.Eq(invalid.CastAll().Count, 0, "nothing more at it");
invalid.B.ForceFullRebuff();
Check.Eq(string.Join(", ", At(invalid.CastAll(), "Kite Shield")), ArmorAtPlayer, "Force Rebuff gives it a fresh try");
// The same line with nothing aimed at a shield changes nothing.
var other = new Rig(worn: true, listShield: false);
other.B.OnChatWindowText("Impenetrability VI cannot be cast on Kite Shield.", 7);
Check.True(other.B.NeedsAnyBuff(), "no shield cast pending: the line is not read");
}
private static void TimersSaved()
{
string folder = Path.Combine(Program.TempRoot, "shieldbuff");
Directory.CreateDirectory(folder);
var rig = new Rig(worn: true);
rig.B.SetTimerPath(folder);
rig.PutAwayForWand();
rig.CastAll();
string[] lines = File.ReadAllLines(Path.Combine(folder, "bufftimers.txt"));
Check.Eq(lines.Count(l => l.StartsWith("shield|", StringComparison.Ordinal)), 3, "three shield lines");
Check.Eq(lines.Count(l => l.StartsWith("item|", StringComparison.Ordinal)), 4, "and the four item lines (the armor's and the aura)");
var again = new Rig(worn: true);
again.PutAwayForWand();
again.B.SetTimerPath(folder);
Check.Eq(again.B.ShieldSpellCount, 3, "loaded back");
Check.True(Armor.All(again.HasArmor), "with the armor's");
Check.Eq(again.CastAll().Count, 0, "nothing due after the reload");
}
private static void Setting()
{
Check.True(new LegacyUiSettings().BuffShield, "a new profile: on");
var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true,\"RebuffSecondsRemaining\":300}", RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(old != null && old.BuffShield, "a profile saved before the setting: on");
var off = JsonSerializer.Deserialize(
JsonSerializer.Serialize(new LegacyUiSettings { BuffShield = false }, RynthAiJsonContext.Default.LegacyUiSettings),
RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(off != null && !off.BuffShield, "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 { BuffShield = false }, dst });
Check.False(dst.BuffShield, "a profile with it off loads off");
copy.Invoke(null, new object[] { old!, dst });
Check.True(dst.BuffShield, "an old profile loads on");
var live = new LegacyUiSettings();
var map = ExpressionTests.Engine(settings: live).BuildSettingsMapPublic();
Check.True(map.TryGetValue("BuffShield", out var entry), "BuffShield is in the settings map");
Check.Eq(entry.Get(), "1", "reads on");
entry.Set("0");
Check.False(live.BuffShield, "and sets off");
}
}

View file

@ -125,8 +125,8 @@ namespace RynthDefective.Tests
int saves = b.R.Saves;
string m = b.S.SetIndependent(true);
Check(b.S.Settings.IndependentBar && b.R.Saves > saves, "turned on, saved");
Eq(b.S.CopyOffer, 5, "the offer counts the game's slots with an item (not the spell)");
Check(m.Contains("independent") && m.Contains("5 items") && m.Contains("offers to copy"), "and says so: " + m);
Eq(b.S.CopyOffer, 6, "the offer counts the game's slots with an item or a spell");
Check(m.Contains("independent") && m.Contains("6 shortcuts") && m.Contains("offers to copy"), "and says so: " + m);
Check(b.S.Data.Slots[0].Item!.Id == own1.Id && b.S.Data.Slots[1].Item!.Id == own2.Id && b.S.Data.Slots[2].Empty,
"turning it on copies nothing by itself");
@ -135,7 +135,7 @@ namespace RynthDefective.Tests
List<DefSlot> s = b.S.Data.Slots;
Check(s[0].Item?.Id == kit.Id && s[1].Item?.Id == potion.Id && s[4].Item?.Id == sword.Id, "the game's items are in own 1, 2, 5");
Check(s[0].Mode == UseMode.Auto && s[0].Item!.Name == "Peerless Healing Kit" && s[0].Item!.Wcid == 628, "copied with their identity, automatic use");
Check(s[6].Empty, "a spell can't be copied: the slot stays empty");
Check(s[6].IsSpell && s[6].SpellId == 1234 && s[6].Item == null, "a spell goes in as a spell slot");
Check(s[8].Item?.Name == "Lucky Gold Letter" && s[8].Item!.Id == 0x7200_0099u, "an item the pack read missed goes by the name the client knows");
Check(s[9].Empty, "one nobody can name stays empty");
Check(s[2].Empty && s[3].Empty && s[17].Empty, "the game's empty slots stay empty");
@ -143,7 +143,7 @@ namespace RynthDefective.Tests
Check(s.Skip(20).All(x => x.Empty), "nothing past them");
Eq(s.Count, DefSettings.SlotsMax, "still 42 own slots");
Check(b.Bound.Count == 2 && b.Bound.Contains((19, "F9")) && b.Bound.Contains((19, "Ctrl+F9")), "own 1's keys follow it to 19: " + string.Join(";", b.Bound));
Check(m.Contains("Copied 4") && m.Contains("2 couldn't") && m.Contains("2 slots moved") && m.Contains("2 keys"), "and it says what it did: " + m);
Check(m.Contains("Copied 5") && m.Contains("1 couldn't") && m.Contains("2 slots moved") && m.Contains("2 keys"), "and it says what it did: " + m);
for (int n = 1; n <= 20; n++)
{
// The independent bar shows what the usual one did: bar N is own N.

View file

@ -65,6 +65,15 @@ namespace RynthDefective.Tests
Run("use: a kit on yourself, answered by UseDone", UseKit);
Run("use: one at a time, the newest wish wins, a held key queues once", UseQueue);
Run("use: busy, animating and RynthAi waiting hold a request, then it gives up", UseBusy);
Run("busy rule: a leftover count, our own use, animation, a count that just changed", BusyRuleDecisions);
Run("use: a busy count left by a death or a login doesn't hold the bar", UseStaleBusy);
Run("use: 'You're too busy' from the server: one more try", UseTooBusyRetry);
Run("spells: the table's names and flags, the name search", SpellTableAndSearch);
Run("spells: whom a cast goes to", SpellCastTarget);
Run("spells: a slot casts, Magic mode first, refusals", SpellUse);
Run("spells: putting a spell in a slot (by id, by name), the command", SpellSession);
Run("store: a spell slot saved and read; files from before read unchanged", SpellStore);
Run("window: a spell slot on the script-window bar and in its editor", SpellWindow);
Run("use: no UseDone, the quiet release and the time limit", UseUnanswered);
Run("use: a slot whose object is gone uses the next of its name", UseRebind);
Run("use: by name, missing items, target needed", UseByNameAndTargets);
@ -196,7 +205,9 @@ namespace RynthDefective.Tests
public bool InWorld { get; set; } = true;
public uint PlayerId => Me;
public uint SelectedId { get; set; }
public bool ClientBusy { get; set; }
public int BusyCount { get; set; }
/// <summary>The busy count above zero (1) or idle; set BusyCount for a count of its own.</summary>
public bool ClientBusy { get => BusyCount > 0; set => BusyCount = value ? Math.Max(1, BusyCount) : 0; }
public bool Animating { get; set; }
public bool? BotWaitingOnServer { get; set; }
public bool? BotMacroRunning { get; set; }
@ -204,11 +215,14 @@ namespace RynthDefective.Tests
public int CombatMode { get; set; } = Stance.NonCombat;
public int RefusalSeq { get; set; }
public uint RefusedObject;
/// <summary>The error of the newest UseDone (Answer sets it).</summary>
public uint LastUseDoneError;
public List<CarriedItem> Inventory = new();
public bool RefuseSends;
public readonly List<string> Sent = new();
public bool RefusalNamed(uint objectId) => RefusedObject == objectId;
public uint UseDoneError(int seqAtSend) => UseDoneSeq == seqAtSend + 1 ? LastUseDoneError : 0;
public IReadOnlyList<CarriedItem> Items() => Inventory;
public CarriedItem? Live(uint id) => Inventory.FirstOrDefault(i => i.Id == id);
@ -229,12 +243,30 @@ namespace RynthDefective.Tests
public bool SetCombatMode(int mode)
{
Sent.Add("mode " + mode);
CombatMode = mode;
if (!ModeRefused) CombatMode = mode;
return true;
}
/// <summary>The client asked for a mode but stays where it is (a weapon that can't cast in hand).</summary>
public bool ModeRefused;
public bool CanCast { get; set; } = true;
/// <summary>The spells the character knows; null = the spellbook can't be read.</summary>
public HashSet<uint>? Known;
public bool? KnowsSpell(uint spellId) => Known == null ? null : Known.Contains(spellId);
public bool CastSpell(uint target, uint spellId)
{
if (RefuseSends) return false;
Sent.Add($"cast {spellId} {(target == Me ? "me" : target.ToString("X"))}");
return true;
}
public void Advance(long ms) => NowMs += ms;
public void Answer() => UseDoneSeq++;
public void Answer(uint error = 0)
{
UseDoneSeq++;
LastUseDoneError = error;
}
}
private sealed class Harness

View file

@ -44,5 +44,9 @@
<Compile Include="..\..\Plugins\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthUi\RynthIcons.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
</ItemGroup>
<ItemGroup>
<!-- The plugin's spell table, under the name the plugin reads it by (spell slots). -->
<EmbeddedResource Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Combat\SpellData.txt" LogicalName="RynthDefective.SpellData.txt" Link="Shared\SpellData.txt" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,292 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Engine.UI.ScriptWindows;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Use;
namespace RynthDefective.Tests
{
// Spell slots (2026-10-28): the spell table and search, whom a cast goes to, a slot's cast through
// the use controller (Magic mode first, the refusals), putting a spell in a slot, the file.
internal static partial class Program
{
private const uint HealSelf = 6, HealOther = 5, FlameBolt = 27, FrostBolt = 28, LifestoneRecall = 1635;
private static void SpellTableAndSearch()
{
Check(SpellTable.Count > 5000, "the table is in the plugin: " + SpellTable.Count);
Check(SpellTable.TryGet(HealSelf, out SpellInfo hs) && hs.Name == "Heal Self I" && hs.SelfTargeted && !hs.Harmful, "Heal Self I: on yourself, not harmful");
Check(SpellTable.TryGet(HealOther, out SpellInfo ho) && ho.Name == "Heal Other I" && !ho.SelfTargeted && !ho.Harmful, "Heal Other I: targeted, helpful");
Check(SpellTable.TryGet(FlameBolt, out SpellInfo fb) && fb.Name == "Flame Bolt I" && fb.Harmful && !fb.SelfTargeted, "Flame Bolt I: harmful");
Check(SpellTable.TryGet(LifestoneRecall, out SpellInfo ls) && ls.SelfTargeted, "Lifestone Recall: on yourself");
Eq(SpellTable.Name(999_999), "Spell 999999", "a spell the table doesn't have goes by number");
Dictionary<uint, SpellInfo> parsed = SpellTable.Parse(new StringReader(
"x\ty\n0\tZero\n7\t \n12\tSome Spell\t1\t1\tw\t-1\t1\tFalse\tTrue\tTrue\n13\tShort\n"));
Check(parsed.Count == 2 && parsed[12].Harmful && parsed[12].SelfTargeted && !parsed[13].Harmful && !parsed[13].SelfTargeted,
"odd lines are skipped; a short line has no flags");
SpellInfo[] known = SpellTable.Known(new uint[] { FlameBolt, HealSelf, HealOther, HealSelf, 0, 999_999 });
Eq(string.Join("|", known.Select(k => k.Name)), "Flame Bolt I|Heal Other I|Heal Self I|Spell 999999", "the character's spells A-Z, once each");
SpellInfo[] list = SpellTable.Known(new uint[] { HealSelf, HealOther, FlameBolt, FrostBolt, LifestoneRecall });
List<SpellInfo> r = SpellTable.Search(list, "heal self i", 10, out int total);
Check(total == 1 && r[0].Id == HealSelf, "the exact name, any case");
r = SpellTable.Search(list, "Heal", 10, out total);
Eq(string.Join("|", r.Select(x => x.Name)), "Heal Other I|Heal Self I", "names starting with it");
r = SpellTable.Search(list, "bolt", 10, out total);
Eq(string.Join("|", r.Select(x => x.Name)), "Flame Bolt I|Frost Bolt I", "a word anywhere");
r = SpellTable.Search(list, "frost i", 10, out total);
Check(total == 1 && r[0].Id == FrostBolt, "every word of it");
r = SpellTable.Search(list, "", 3, out total);
Check(r.Count == 3 && total == 5, "blank: all of them, at most the limit");
SpellTable.Search(list, "zzz", 10, out total);
Eq(total, 0, "nothing matches");
}
private static void SpellCastTarget()
{
var self = new SpellInfo(HealSelf, "Heal Self I", true, false);
var helpful = new SpellInfo(HealOther, "Heal Other I", false, false);
var harmful = new SpellInfo(FlameBolt, "Flame Bolt I", false, true);
const uint mob = 0x8000_1234u;
Eq(SpellTargeting.Decide(self, mob, Me, out uint t, out _), CastAt.Yourself, "a self spell goes on you, whatever is selected");
Eq(t, Me, "on you");
Eq(SpellTargeting.Decide(helpful, mob, Me, out t, out _), CastAt.Selection, "a targeted spell goes on the selection");
Eq(t, mob, "the selected object");
Eq(SpellTargeting.Decide(helpful, 0, Me, out t, out _), CastAt.Yourself, "a helpful one with nothing selected: on you");
Eq(t, Me, "on you");
Eq(SpellTargeting.Decide(helpful, Me, Me, out t, out _), CastAt.Yourself, "with yourself selected: on you");
Eq(SpellTargeting.Decide(harmful, mob, Me, out t, out _), CastAt.Selection, "a harmful one on the selected monster");
Eq(t, mob, "the monster");
Eq(SpellTargeting.Decide(harmful, 0, Me, out t, out string why), CastAt.Refused, "a harmful one with nothing selected: refused");
Check(t == 0 && why.Contains("select a target"), "and says to select one: " + why);
Eq(SpellTargeting.Decide(harmful, Me, Me, out _, out why), CastAt.Refused, "a harmful one at yourself: refused");
Check(why.Contains("monster"), "says to select a monster: " + why);
Eq(SpellTargeting.Decide(null, mob, Me, out t, out _), CastAt.Selection, "a spell the table doesn't know: on the selection");
Eq(SpellTargeting.Decide(null, 0, Me, out t, out _), CastAt.Yourself, "else on you");
Eq(SpellTargeting.Decide(self, 0, 0, out _, out why), CastAt.Refused, "no character yet: refused");
Check(SpellTargeting.Describe(self) == "cast on you" && SpellTargeting.Describe(harmful).Contains("selected target")
&& SpellTargeting.Describe(helpful).Contains("or on you"), "the tooltip words");
}
private static Harness Caster(params uint[] known)
{
Harness h = With();
h.World.Known = new HashSet<uint>(known);
return h;
}
private static bool Cast(Harness h, uint spell, string name) =>
h.Use.Request(UseRequest.Cast(spell, name, "slot", h.World.NowMs));
private static void SpellUse()
{
// From peace: Magic mode first, the cast once the stance has settled, answered by UseDone.
Harness h = Caster(HealSelf, HealOther, FlameBolt);
Check(Cast(h, HealSelf, "Heal Self I"), "queued");
h.Tick();
Eq(string.Join("|", h.World.Sent), "mode 8", "at peace: Magic mode first");
Check(h.Use.InFlight && h.Said.Last().Contains("Magic mode"), "in flight, and says so: " + string.Join(";", h.Said));
h.Tick(500);
h.Tick(500);
Eq(h.World.Sent.Count, 1, "the stance settles first");
h.Tick(400);
Eq(string.Join("|", h.World.Sent), "mode 8|cast 6 me", "then the cast, on you");
Eq(h.Said.Last(), "Casting Heal Self I...", "status");
Check(h.Use.InFlight && h.Use.InvolvesSpell(HealSelf), "waiting for the server's answer");
Check(!Cast(h, HealSelf, "Heal Self I") || h.Use.HasPending, "pressed again during the cast: one more, once");
Check(!Cast(h, HealSelf, "Heal Self I"), "a held key queues once");
h.World.Answer();
h.Tick(100);
Check(!h.Use.InFlight, "answered");
h.Tick(300);
Eq(h.World.Sent.Last(), "cast 6 me", "the second press casts again, Magic mode already in place");
// Already in Magic: cast at once. A harmful spell on the selected monster.
h = Caster(FlameBolt);
h.World.CombatMode = Stance.Magic;
h.World.SelectedId = 0x1234;
Cast(h, FlameBolt, "Flame Bolt I");
h.Tick();
Eq(string.Join("|", h.World.Sent), "cast 27 1234", "in Magic already: cast on the selection at once");
Eq(h.Said.Last(), "Casting Flame Bolt I on the selection...", "status");
// Refusals: nothing selected for a harmful spell, a spell the character doesn't know, no casting at all.
h = Caster(FlameBolt);
h.World.CombatMode = Stance.Magic;
Cast(h, FlameBolt, "Flame Bolt I");
h.Tick();
Check(h.World.Sent.Count == 0 && !h.Use.InFlight && h.Warned.Count == 1 && h.Warned[0] == "Flame Bolt I: not cast, select a target first.",
"a war spell with nothing selected: refused, said: " + string.Join(";", h.Warned));
h = Caster(HealSelf);
Cast(h, FlameBolt, "Flame Bolt I");
h.Tick();
Check(h.World.Sent.Count == 0 && h.Warned.Count == 1 && h.Warned[0] == "Flame Bolt I: not cast, you don't know that spell.",
"a spell the character doesn't know: refused, no mode change: " + string.Join(";", h.Warned));
h = With();
h.World.Known = null; // the spellbook can't be read: the server decides
h.World.CombatMode = Stance.Magic;
Cast(h, HealSelf, "Heal Self I");
h.Tick();
Eq(string.Join("|", h.World.Sent), "cast 6 me", "spellbook unreadable: cast anyway");
h = Caster(HealSelf);
h.World.CanCast = false;
Cast(h, HealSelf, "Heal Self I");
h.Tick();
Check(h.World.Sent.Count == 0 && h.Warned.Count == 1 && h.Warned[0].Contains("can't cast"), "an engine that can't cast: said");
h = Caster(HealSelf);
h.World.CombatMode = Stance.Magic;
h.World.RefuseSends = true;
Cast(h, HealSelf, "Heal Self I");
h.Tick();
Check(!h.Use.InFlight && h.Warned.Count == 1 && h.Warned[0].Contains("didn't take the cast"), "the client turns the cast away: said, not waited on");
// Magic mode never comes (a sword in hand): asked once, then said, nothing cast.
h = Caster(HealSelf);
h.World.CombatMode = Stance.Melee;
h.World.ModeRefused = true;
Cast(h, HealSelf, "Heal Self I");
h.Tick();
h.Ticks(3, 1000);
Check(h.Use.InFlight && h.Warned.Count == 0, "still waiting for the stance");
h.Tick(1100);
Check(!h.Use.InFlight && h.Warned.Count == 1 && h.Warned[0].Contains("didn't go into magic mode (melee now)"), "the stance never came: said: " + string.Join(";", h.Warned));
Eq(string.Join("|", h.World.Sent), "mode 8", "asked once, never cast");
// The busy rules hold a cast like a use; "too busy" from the server gets one more try.
h = Caster(HealSelf);
h.World.CombatMode = Stance.Magic;
h.Tick();
h.World.BusyCount = 1;
Cast(h, HealSelf, "Heal Self I");
h.Ticks(2, 1000);
Eq(h.World.Sent.Count, 0, "a busy count that just rose holds the cast");
h.World.BusyCount = 0;
h.Tick(100);
Eq(string.Join("|", h.World.Sent), "cast 6 me", "and it goes once the character is free");
h.World.Answer(UseController.TooBusyError);
h.Tick(100);
h.Tick(1100);
Eq(string.Join("|", h.World.Sent), "cast 6 me|cast 6 me", "'too busy': cast once more a second later");
Check(h.Logged.Any(l => l.Contains("the one more try")), "logged as the retry");
h.World.Answer(UseController.TooBusyError);
h.Tick(100);
Check(h.Warned.Count == 1 && h.Warned[0].Contains("not cast, the server says the character is busy"), "twice: said: " + string.Join(";", h.Warned));
}
private static void SpellSession()
{
var rig = new Rig("spells");
IReadOnlyList<SpellInfo> known = SpellTable.Known(new uint[] { HealSelf, HealOther, FlameBolt, FrostBolt, LifestoneRecall });
rig.S.KnownSpells = () => known;
string m = rig.S.SetSpell(3, HealSelf);
DefSlot s3 = rig.S.Data.Slots[2];
Check(s3.IsSpell && s3.SpellId == HealSelf && s3.SpellName == "Heal Self I" && !s3.Empty && s3.Item == null, "slot 3 casts Heal Self I");
Check(m.Contains("Slot 3: Heal Self I") && m.Contains("cast on you"), "and says how: " + m);
Check(rig.Saves > 0, "saved");
Eq(s3.Label, "Heal Self I", "its label");
m = rig.S.SetSpell(4, 2000);
Check(rig.S.Data.Slots[3].Empty && m.Contains("don't know"), "a spell the character doesn't know: refused: " + m);
rig.S.KnownSpells = () => Array.Empty<SpellInfo>();
m = rig.S.SetSpell(4, 2000);
Check(rig.S.Data.Slots[3].SpellId == 2000, "the spellbook unreadable: taken (the cast is refused then if it must be): " + m);
rig.S.KnownSpells = () => known;
m = rig.S.SetSpellFromName(5, "frost bolt i");
Check(rig.S.Data.Slots[4].SpellId == FrostBolt, "by name, any case: " + m);
m = rig.S.SetSpellFromName(6, "bolt");
Check(rig.S.Data.Slots[5].Empty && m.Contains("2 of your spells match 'bolt'") && m.Contains("Flame Bolt I, Frost Bolt I"), "two match: says which: " + m);
m = rig.S.SetSpellFromName(6, "lifestone");
Check(rig.S.Data.Slots[5].SpellId == LifestoneRecall, "one starts with it: " + m);
m = rig.S.SetSpellFromName(7, "nothing like it");
Check(rig.S.Data.Slots[6].Empty && m.Contains("no spell named"), "none: " + m);
rig.S.KnownSpells = () => Array.Empty<SpellInfo>();
Check(rig.S.SetSpellFromName(7, "heal").Contains("can't be read"), "by name needs the spellbook");
rig.S.KnownSpells = () => known;
Check(rig.S.UseSlot(3) == null && rig.S.Use.Pending?.Spell == HealSelf && rig.S.Use.Pending.Label == "Heal Self I", "pressing a spell slot asks for its cast");
Check(rig.S.UseSlot(8)!.Contains("empty"), "an empty slot says so");
m = rig.S.BindKey(5, "F9", byName: true);
Check(m.Contains("holds a spell") && rig.Chat.Count == 0, "a spell slot binds by slot only: " + m);
rig.Inv = new List<CarriedItem> { Kit(10) };
rig.S.SetSlot(3, Kit(10));
Check(rig.S.Data.Slots[2].Item?.Id == 10 && rig.S.Data.Slots[2].SpellId == 0 && !rig.S.Data.Slots[2].IsSpell, "an item over a spell: the spell is gone");
DefSlot clone = rig.S.Data.Slots[4].Clone();
Check(clone.SpellId == FrostBolt && clone.SpellName == "Frost Bolt I", "a copy keeps the spell");
rig.S.ClearSlot(5);
Check(rig.S.Data.Slots[4].Empty, "cleared");
DefCommand c = DefCommandParser.Parse("spell 3 Heal Self VI");
Check(c.Verb == DefVerb.Spell && c.Slot == 3 && c.Text == "Heal Self VI", "/rdef spell 3 Heal Self VI");
Check(DefCommandParser.Parse("spell 3").Verb == DefVerb.Error && DefCommandParser.Parse("spell x Heal").Verb == DefVerb.Error
&& DefCommandParser.Parse("spell").Verb == DefVerb.Error, "a slot and a name are needed");
}
private static void SpellWindow()
{
// The script-window bar (engines without the Shortcuts bar): a spell slot is a picture, else its initials.
Windows w = Stocked("bar-spell");
w.S.Data.Slots[5] = new DefSlot { SpellId = HealSelf, SpellName = "Heal Self I" };
w.DrawBar();
ParsedWindow bar = ParseAll(w.Host, "bar with a spell", out _).First(p => p.Key == "RynthDefective/Bar");
Eq(CountOps(bar, ScriptOp.ImageButton), 5, "the four items and the spell drawn as pictures");
Eq(CountOps(bar, ScriptOp.Button), 3 + 3, "three empty slots and the toolbar");
Check(w.BarText.Contains("Heal Self I, a spell.") && w.BarText.Contains("cast on you"), "its tooltip says what it casts");
Windows t = Stocked("bar-spell-text", icons: false);
t.S.Data.Slots[5] = new DefSlot { SpellId = HealSelf, SpellName = "Heal Self I" };
t.DrawBar();
ParseAll(t.Host, "bar with a spell, no pictures", out _);
Check(t.BarText.Contains("HSI"), "no pictures: its initials");
// The editor on the spell slot.
w.Bar.EditOpen = true;
w.Bar.Editor.Select(6);
w.DrawBar();
ParseAll(w.Host, "editor on a spell slot", out _);
Check(w.BarText.Contains("Slot 6: Heal Self I") && w.BarText.Contains("6. Heal Self I") && w.BarText.Contains("A spell: pressing the slot has it cast on you"),
"the editor names the spell and how it is cast");
Check(!w.BarText.Contains("Pressing it") && w.BarText.Contains("Bind to this slot"), "no item use setting; the key controls stay");
}
private static void SpellStore()
{
var st = new DefStore(Path.Combine(_temp, "spells"));
var d = new DefData();
d.Slots[0].Item = ItemRef.From(Kit(0x7100_0001u));
d.Slots[1] = new DefSlot { SpellId = HealSelf, SpellName = "Heal Self I" };
d.Slots[2] = new DefSlot { SpellId = 987_654, SpellName = "A Server's Own Spell" };
Check(st.Save("S", "Spells", d) == null, "saved");
DefData r = st.Load("S", "Spells", out string? problem);
Check(problem == null, "read");
Check(r.Slots[1].IsSpell && r.Slots[1].SpellId == HealSelf && r.Slots[1].Label == "Heal Self I" && r.Slots[1].Mode == UseMode.Auto, "a spell slot comes back");
Check(r.Slots[2].SpellId == 987_654 && r.Slots[2].Label == "A Server's Own Spell", "a spell the table doesn't know keeps its saved name");
Check(r.Slots[0].Item?.Name == "Peerless Healing Kit" && r.Slots[0].SpellId == 0 && r.Slots[3].Empty, "the item slot and the empty ones as they were");
Eq(DefStore.ToJson(r), DefStore.ToJson(d), "writing what was read gives the same file");
// A file from before spell slots: read unchanged, written back the same.
const string old = "{\n \"version\": 1,\n \"slots\": [\n {\n \"item\": {\n \"id\": 5,\n \"name\": \"Kit\"\n },\n \"mode\": 2\n },\n {\n \"mode\": 0\n }\n ]\n}";
DefData o = DefStore.Parse(System.Text.Json.JsonDocument.Parse(old).RootElement);
Check(o.Slots[0].Item?.Name == "Kit" && o.Slots[0].Mode == UseMode.OnSelf && o.Slots[0].SpellId == 0 && o.Slots.Skip(1).All(x => x.Empty),
"an old file: the item, its mode, no spells");
Check(!DefStore.ToJson(o).Contains("\"spell\""), "and no spell is written for it");
// Hand-edited oddities: an item wins over a spell; a spell with no id, or not an object, is nothing.
const string odd = "{\"slots\":[{\"item\":{\"id\":5,\"name\":\"Kit\"},\"spell\":{\"id\":6,\"name\":\"Heal Self I\"}},"
+ "{\"spell\":{\"id\":0,\"name\":\"X\"}},{\"spell\":6},{\"spell\":{\"id\":6}},{\"spell\":{\"id\":-3,\"name\":\"Y\"}}]}";
DefData x = DefStore.Parse(System.Text.Json.JsonDocument.Parse(odd).RootElement);
Check(x.Slots[0].Item?.Name == "Kit" && x.Slots[0].SpellId == 0, "an item and a spell in one slot: the item");
Check(x.Slots[1].Empty && x.Slots[2].Empty && x.Slots[4].Empty, "no id, not an object, a negative id: empty");
Check(x.Slots[3].SpellId == HealSelf && x.Slots[3].Label == "Heal Self I", "an id with no name: named by the table");
}
}
}

View file

@ -75,19 +75,38 @@ namespace RynthDefective.Tests
{
Harness h = With(Kit(0x10));
ItemRef kit = ItemRef.From(Kit(0x10));
h.World.ClientBusy = true;
// A count that keeps moving is an action under way (the player's own, another plugin's): it holds.
h.Tick(); // the first look: idle
h.Slot(kit);
h.Ticks(5, 1000);
Eq(h.World.Sent.Count, 0, "the client's busy count holds it");
for (int i = 0; i < 5; i++)
{
h.World.BusyCount = 1 + (i % 2);
h.Tick(1000);
}
Eq(h.World.Sent.Count, 0, "a moving busy count holds it");
Check(h.Use.HasPending && h.Warned.Count == 0, "still waiting inside the limit");
h.Ticks(2, 1000);
h.World.BusyCount = 2;
h.Tick(1000);
Check(!h.Use.HasPending && h.Warned.Count == 1 && h.Warned[0] == "Peerless Healing Kit: not used, the character is busy.", "past the limit it gives up and says why: " + string.Join(";", h.Warned));
Eq(h.World.Sent.Count, 0, "and sent nothing");
h = With(Kit(0x10));
h.World.Animating = true;
h.Slot(kit);
h.Ticks(7, 1000);
Check(h.Warned.Count == 1 && h.Warned[0].Contains("an animation is playing"), "a gesture holds it: " + string.Join(";", h.Warned));
h.Ticks(3, 1000);
Eq(h.World.Sent.Count, 0, "a gesture holds it");
h.World.Animating = false;
h.Tick(100);
Eq(h.World.Sent.Count, 1, "and it goes when the gesture ends");
h = With(Kit(0x10));
h.World.Animating = true;
h.Slot(kit);
h.Ticks(4, 1000);
Eq(h.World.Sent.Count, 0, "a gesture 3 s long still holds it");
h.Tick(1000);
Check(h.World.Sent.Count == 1 && h.Warned.Count == 0, "one that never ends (a stuck motion queue) is let go after 4 s");
Eq(h.Logged.Count(l => l.Contains("'animating' for")), 1, "logged once");
h = With(Kit(0x10));
h.World.BotWaitingOnServer = true;
@ -115,6 +134,168 @@ namespace RynthDefective.Tests
Eq(h.World.Sent.Count, 1, "no RynthAi: nothing to wait for");
}
private static BusyFacts Facts(int count = 0, long steady = 0, int leftover = 0, long own = long.MaxValue / 4,
bool anim = false, long animMs = 0, bool? bot = null, long botMs = 0) =>
new(count, steady, leftover, own, anim, animMs, bot, botMs);
private static void BusyRuleDecisions()
{
Eq(BusyRule.Decide(Facts(), out BusyStale st), BusyHold.None, "idle: send");
Eq(st, BusyStale.None, "nothing ignored");
Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000), out st), BusyHold.None, "busy with nothing in flight for longer than the bound: send");
Eq(st, BusyStale.Count, "the count was ignored as a leftover");
Eq(BusyRule.Decide(Facts(count: 1, steady: BusyRule.CountTrustMs), out _), BusyHold.None, "exactly the bound: a leftover");
Eq(BusyRule.Decide(Facts(count: 1, steady: BusyRule.CountTrustMs - 1), out _), BusyHold.Busy, "just under it: still trusted");
Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, own: 500), out _), BusyHold.Busy, "busy just after our own use: wait");
Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, own: BusyRule.OwnTrustMs), out _), BusyHold.None, "our own use long enough ago: a leftover");
Eq(BusyRule.Decide(Facts(anim: true, animMs: 300), out _), BusyHold.Animation, "animating: wait");
Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, anim: true, animMs: 300), out _), BusyHold.Animation, "animating holds over a leftover count");
Eq(BusyRule.Decide(Facts(anim: true, animMs: BusyRule.AnimationMaxMs), out st), BusyHold.None, "a gesture past the bound is a stuck motion queue");
Eq(st, BusyStale.Animation, "and ignored as such");
Eq(BusyRule.Decide(Facts(count: 1, steady: 200, anim: true, animMs: 9000), out _), BusyHold.Busy, "a stuck gesture doesn't hide a fresh count");
Eq(BusyRule.Decide(Facts(count: 1, steady: 200), out _), BusyHold.Busy, "a count that just changed: wait");
Eq(BusyRule.Decide(Facts(count: 3, steady: 200, leftover: 2), out _), BusyHold.Busy, "a count that just rose above the leftover: wait");
Eq(BusyRule.Decide(Facts(count: 2, steady: 200, leftover: 2), out st), BusyHold.None, "back at the leftover (our use answered): holds nothing though it just moved");
Eq(st, BusyStale.Count, "the leftover is still a leftover");
Eq(BusyRule.Decide(Facts(count: 3, steady: 5000, leftover: 2), out st), BusyHold.None, "above the leftover but unchanged for longer than the bound: a bigger leftover");
Eq(st, BusyStale.Count, "ignored");
Eq(BusyRule.Decide(Facts(bot: true, botMs: 1000), out _), BusyHold.Bot, "RynthAi waiting on the server, fresh: wait");
Eq(BusyRule.Decide(Facts(bot: true, botMs: BusyRule.BotTrustMs), out st), BusyHold.None, "RynthAi's bit longer than its own action limits: send");
Eq(st, BusyStale.Bot, "ignored");
Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, bot: true, botMs: 10_000), out st), BusyHold.None, "RynthAi's copy of a leftover count (its macro off after a death)");
Eq(st, BusyStale.Count | BusyStale.Bot, "both ignored");
Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, bot: true, botMs: BusyRule.CountTrustMs), out _), BusyHold.None, "with a leftover count the bit gets the count's bound");
Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, bot: true, botMs: 1000), out _), BusyHold.Bot, "a bit that just came on holds even over a leftover (RynthAi just sent something)");
Eq(BusyRule.Decide(Facts(bot: false, botMs: 50), out _), BusyHold.None, "RynthAi idle");
}
private static void UseStaleBusy()
{
ItemRef kit = ItemRef.From(Kit(0x10));
// A login with a count the last session left: nothing moves it.
Harness h = With(Kit(0x10));
h.World.BusyCount = 2;
h.Tick(); // the first look
h.Slot(kit);
h.Ticks(3, 1000);
Eq(h.World.Sent.Count, 0, "right after the first look the count may be real: held");
h.Tick(1000);
Eq(string.Join("|", h.World.Sent), "useon 10 me", "unchanged for 4 s with nothing in flight: a leftover, the kit goes");
Eq(h.Warned.Count, 0, "no warning");
Eq(h.Logged.Count(l => l.Contains("busy count has read 2")), 1, "the leftover is logged once");
Check(h.Logged.Any(l => l.Contains("left alone")), "and the log says the count isn't touched");
Eq(h.Use.Busy.Leftover, 2, "2 is the leftover");
// Our own kit raises it; the answer brings it back to the leftover; the next kit goes at once.
h.World.BusyCount = 3;
h.Tick(100);
Check(h.Use.InFlight, "our kit is in flight");
h.World.BusyCount = 2;
h.World.Answer();
h.Tick(100);
Check(!h.Use.InFlight, "answered");
h.Slot(kit);
h.Tick(300);
Eq(h.World.Sent.Count, 2, "the next kit goes at once: the count is back at the leftover");
Eq(h.Logged.Count(l => l.Contains("busy count has read")), 1, "nothing new logged");
h.World.Answer();
h.Tick(100);
// Something else raises it above the leftover: real again, until it too sits unchanged.
h.World.BusyCount = 3;
h.Tick(300);
h.Slot(kit);
h.Ticks(3, 1000);
Eq(h.World.Sent.Count, 2, "a count above the leftover that just rose holds the kit");
h.Tick(1000);
Eq(h.World.Sent.Count, 3, "until it has sat unchanged for 4 s too");
Eq(h.Logged.Count(l => l.Contains("busy count has read 3")), 1, "a bigger leftover gets its own line");
h.World.Answer();
h.Tick(100);
h.World.BusyCount = 0;
h.Tick(100);
Eq(h.Use.Busy.Leftover, 0, "idle again: no leftover");
// A death: the count and RynthAi's copy of it sit through the death portal.
h = With(Kit(0x10));
h.World.BusyCount = 1;
h.World.BotWaitingOnServer = true;
h.Tick();
h.World.InWorld = false;
h.Ticks(8, 1000);
h.World.InWorld = true;
h.Slot(kit);
h.Tick(100);
Eq(string.Join("|", h.World.Sent), "useon 10 me", "landed: the count and RynthAi's bit that sat through the portal hold nothing");
Check(h.Logged.Any(l => l.Contains("RynthAi has read 'waiting on the server'")), "RynthAi's bit is logged as ignored too");
// A request made in the portal is dropped and said so.
h = With(Kit(0x10));
h.World.InWorld = false;
h.Slot(kit);
h.Tick();
Check(!h.Use.HasPending && h.World.Sent.Count == 0 && h.Warned.Count == 1 && h.Warned[0].Contains("portal space"), "a key in portal space: not used, and says why: " + string.Join(";", h.Warned));
// A login starts the clocks again (ResetSession), portal space doesn't.
h = With(Kit(0x10));
h.World.BusyCount = 1;
h.Tick();
h.Ticks(6, 1000);
h.Use.ResetSession();
h.Slot(kit);
h.Tick(100);
Eq(h.World.Sent.Count, 0, "after a login the count is new again: held for now");
}
private static void UseTooBusyRetry()
{
ItemRef kit = ItemRef.From(Kit(0x10));
Harness h = With(Kit(0x10));
h.Slot(kit);
h.Tick();
Eq(h.World.Sent.Count, 1, "sent");
h.World.Answer(UseController.TooBusyError);
h.Tick(100);
Check(!h.Use.InFlight && h.Use.HasPending, "answered 'too busy': queued once more");
h.Tick(500);
Eq(h.World.Sent.Count, 1, "not straight away");
h.Tick(600);
Eq(h.World.Sent.Count, 2, "a second later, sent again");
Check(h.Logged.Any(l => l.Contains("one more try")), "the log says it is the retry");
h.World.Answer(UseController.TooBusyError);
h.Tick(100);
Check(!h.Use.InFlight && !h.Use.HasPending && h.Warned.Count == 1 && h.Warned[0].Contains("the server says the character is busy"),
"busy again: said once, not retried again: " + string.Join(";", h.Warned));
h.Ticks(5, 1000);
Eq(h.World.Sent.Count, 2, "no loop");
// Another answer: no retry.
h = With(Kit(0x10));
h.Slot(kit);
h.Tick();
h.World.Answer(0x0402);
h.Tick(100);
h.Ticks(3, 1000);
Check(h.World.Sent.Count == 1 && !h.Use.HasPending, "another error is not retried");
// A newer request while the first was in flight wins over the retry.
h = With(Kit(0x10), Potion(0x20));
h.Slot(kit);
h.Tick();
h.Slot(ItemRef.From(Potion(0x20)));
h.World.Answer(UseController.TooBusyError);
h.Tick(100);
Check(h.Use.Pending?.Item?.Name == "Health Potion", "the newest wish wins over the retry");
h.Tick(1100);
Eq(string.Join("|", h.World.Sent), "useon 10 me|use 20", "the potion goes, the kit isn't sent again");
}
private static void UseUnanswered()
{
Harness h = With(Potion(0x20));