Snapshot for release 2026.10.12.1 (internal 8d252bd)

This commit is contained in:
Tom Bohar 2026-10-12 00:33:13 -04:00
commit 3c4f093e3d
60 changed files with 5748 additions and 602 deletions

View file

@ -41,6 +41,9 @@ internal static unsafe class FakeHost
public static readonly Dictionary<uint, uint[]> SpellIds = new();
/// <summary>Data id properties (STypeDID): (object, key) -> value, e.g. a scroll's Spell 28.</summary>
public static readonly Dictionary<(uint Id, uint Key), uint> DataIds = new();
/// <summary>Instance id properties (STypeIID): (object, key) -> object id, e.g. a pet's PetOwner 44.
/// When it has entries at Create() time the host also gets GetObjectInstanceIdProperty (opt-in).</summary>
public static readonly Dictionary<(uint Id, uint Key), uint> InstanceIds = new();
public static readonly Dictionary<uint, uint[]> Palettes = new();
public static readonly HashSet<uint> KnownSpells = new();
public static readonly HashSet<uint> NotAttackable = new();
@ -98,6 +101,13 @@ internal static unsafe class FakeHost
public static bool StopCalls;
/// <summary>StopCompletely calls (opt-in with <see cref="StopCalls"/>).</summary>
public static int Stops;
/// <summary>Opt-in: wires SetMotion; calls land in <see cref="MotionCalls"/>.</summary>
public static bool SetMotionCalls;
/// <summary>Every SetMotion (motion, on), in order (opt-in with <see cref="SetMotionCalls"/>).</summary>
public static readonly List<(uint Motion, bool On)> MotionCalls = new();
/// <summary>Movement and cast calls in the order they reached the engine ("autorun on/off", "stop",
/// "motion 0x.. on/off", "cast N").</summary>
public static readonly List<string> Sent = new();
/// <summary>Every UseObject (a wield, a use) and RequestId (an identify), in order.</summary>
public static readonly List<uint> Uses = new();
public static readonly List<uint> IdRequests = new();
@ -193,16 +203,19 @@ internal static unsafe class FakeHost
Names.Clear(); Positions.Clear(); ItemTypes.Clear();
Ints.Clear(); Doubles.Clear(); Quads.Clear(); Bools.Clear(); Strings.Clear();
Skills.Clear(); SkillLevels.Clear(); Attributes.Clear();
SpellIds.Clear(); DataIds.Clear(); Palettes.Clear(); KnownSpells.Clear(); NotAttackable.Clear(); Enchantments.Clear();
SpellIds.Clear(); DataIds.Clear(); InstanceIds.Clear(); Palettes.Clear(); KnownSpells.Clear(); NotAttackable.Clear(); Enchantments.Clear();
Containers.Clear(); Wielders.Clear(); Bitfields.Clear();
ServerTime = 0; Vitae = 1.0f; Portaling = false; PlayerPose = default; HasPose = true;
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
Logs.Clear(); Chat.Clear(); ChatCommands.Clear();
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear(); GiveLands = true;
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true;
Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1;
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false;
// Spell mana costs "unknown" (no reserve beyond Get Mana At, no cost gate), so a portal.dat on
// the PC doesn't change results; the mana reserve tests set their own costs.
RynthCore.Plugin.RynthAi.BuffManager.ManaCostOverride = _ => 0;
WieldCalls = false; Wields.Clear();
SalvageCalls = false; ExternalMoves.Clear(); SalvageAdds.Clear(); SalvageExecutes.Clear();
RefuseSalvageAdd.Clear(); OnSalvageExecute = null; Wielded.Clear(); _panelItems.Clear();
@ -248,6 +261,8 @@ internal static unsafe class FakeHost
api.GetObjectOwnershipInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, uint*, int>)&GetObjectOwnershipInfo;
if (Bitfields.Count > 0)
api.GetObjectBitfieldFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint>)&GetObjectBitfield;
if (InstanceIds.Count > 0)
api.GetObjectInstanceIdPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)&GetObjectInstanceIdProperty;
api.SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&SetAutoRun;
api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&TurnToHeading;
api.JumpNonAutonomousFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&JumpNonAutonomous;
@ -256,6 +271,8 @@ internal static unsafe class FakeHost
api.CastSpellFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int>)&CastSpell;
if (StopCalls)
api.StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&StopCompletely;
if (SetMotionCalls)
api.SetMotionFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int>)&SetMotion;
if (Nav3DCalls)
{
api.Nav3DClearFn = (IntPtr)(delegate* unmanaged[Cdecl]<void>)&Nav3DClear;
@ -530,6 +547,14 @@ internal static unsafe class FakeHost
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetObjectInstanceIdProperty(uint id, uint key, uint* v)
{
if (!InstanceIds.TryGetValue((id, key), out uint x)) return 0;
*v = x;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetObjectDataIdProperty(uint id, uint key, uint* v)
{
@ -613,7 +638,10 @@ internal static unsafe class FakeHost
private static uint GetSelectedItemId() => SelectedItem;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetAutoRun(int on) { AutoRun = on != 0; AutoRunCalls.Add(AutoRun); return 1; }
private static int SetAutoRun(int on) { AutoRun = on != 0; AutoRunCalls.Add(AutoRun); Sent.Add(AutoRun ? "autorun on" : "autorun off"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetMotion(uint motion, int on) { MotionCalls.Add((motion, on != 0)); Sent.Add($"motion 0x{motion:X8} {(on != 0 ? "on" : "off")}"); return 1; }
// The fake character turns instantly.
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
@ -626,9 +654,9 @@ internal static unsafe class FakeHost
private static int TapJump() { TapJumps++; return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); return 1; }
private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); Sent.Add($"cast {spellId}"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int StopCompletely() { Stops++; return 1; }
private static int StopCompletely() { Stops++; Sent.Add("stop"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void ForceResetBusyCount() { ForceResets++; BusyStateValue = 0; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]

View file

@ -20,6 +20,9 @@ internal static class Program
/// <summary>DungeonHazardStore's folder before Main pointed it at the scratch folder.</summary>
public static string LiveHazardFolder { get; private set; } = "";
/// <summary>CreatureProfileStore's folder before Main pointed it at the scratch folder.</summary>
public static string LiveCreatureFolder { get; private set; } = "";
private static int Main(string[] args)
{
if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true);
@ -36,6 +39,9 @@ internal static class Program
// A sighted lava/acid hotspot is persisted under C:\Games\RynthSuite\RynthAi\DungeonHazards.
LiveHazardFolder = RynthCore.Plugin.RynthAi.DungeonHazardStore.Folder;
RynthCore.Plugin.RynthAi.DungeonHazardStore.Folder = Path.Combine(TempRoot, "DungeonHazards");
// Appraised creatures are saved to C:\Games\RynthSuite\RynthAi\CreatureData\creatures.json.
LiveCreatureFolder = RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder;
RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder = Path.Combine(TempRoot, "CreatureData");
// Spell names (item spells, spell expiry by name) come from the plugin's embedded table.
SpellDatabase.Load();
@ -90,6 +96,9 @@ internal static class Program
CustomDebuffTests.Register(runner);
ProfileLoadTests.Register(runner);
ActivityInterfaceTests.Register(runner);
CastNoDamageTests.Register(runner);
ManaReserveTests.Register(runner);
DamageRowsTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -47,7 +47,10 @@ internal static class ActionPacingTests
{
r.Add("pacing: a use is the server action until its UseDone; a refusal answers it too; a wield answers by wielding", UseAnswers);
r.Add("pacing: the stall onset replayed - the idle peace swap waits for the corpse use's answer, then goes; no swap to the mode you're in", OnsetModeChangeHeld);
r.Add("pacing: moves, turns and redundant stops wait while the server answers; a real stop and the cast nudge go through", MovesHeld);
r.Add("pacing: moves and turns wait while the server answers; a stop with nothing of ours moving waits too, is never dropped; a real stop and the cast nudge go through", MovesHeld);
r.Add("pacing (stop burst, flight 63260): a held stop goes out once the server answers, before the next start", HeldStopSentAfterAnswer);
r.Add("pacing (stop burst): no cast goes out while a stop is held - the stop is sent first", CastWaitsForHeldStop);
r.Add("pacing (stop burst): a stop for our own autorun goes through however long ago it was turned on", OldAutorunStopGoesThrough);
r.Add("pacing: no answer - each kind's time limit lets the next action go, logged, and nothing is force-cleared", TimeLimits);
r.Add("pacing: heals (a plain heal waits for a corpse use's answer, 300 ms at Emergency, one behind a cast's result, 300 ms after the stance reads)", HealRules);
r.Add("pacing (vitals): Drakkon 07:03 - a cast whose result is in waits for its UseDone: one cast, not a too-busy flood", CastWaitsForUseDone);
@ -201,14 +204,17 @@ internal static class ActionPacingTests
Check.False(host.SetAutoRunBy("Nav", true), "nav can't start running");
Check.False(host.TurnToHeadingBy("Nav", 90f), "nor turn");
Check.False(host.SetMotionBy("Combat", 0x6500000D, true), "nor start a turn motion");
Check.False(host.StopCompletelyBy("Arbiter"), "a stop with nothing of ours moving is a redundant movement packet: held");
Check.False(host.SetMotionBy("Combat", 0x6500000D, false), "Combat's turn-off with no turn on: held");
Check.False(host.StopCompletelyBy("Arbiter"), "a stop with nothing of ours moving waits for the answer");
Check.False(host.SetMotionBy("Combat", 0x6500000D, false), "Combat's turn-off with no turn on: waits too");
Check.True(MoveAudit.HasPendingStop, "the stops are kept, not dropped");
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "no autorun reached the client");
Check.Eq(FakeHost.Stops, 0, "no stop either");
Check.Eq(FakeHost.Stops, 0, "no stop yet either");
Check.True(Logged("held (move/turn): the server is still answering the use of"), "the hold is logged");
Check.True(Logged("StopCompletely() waits (nothing of ours is moving; sent once the server has answered, before any cast)"), "the wait is logged");
Check.True(host.SetAutoRunBy("Buff/Nudge", true) && host.SetAutoRunBy("Buff/Nudge", false), "the held-cast nudge is deliberate: it goes through");
Check.True(host.StopCompletelyBy("MacroStop"), "a macro stop goes through");
Check.False(MoveAudit.HasPendingStop, "the macro StopCompletely covered the held ones");
FakeHost.UseDone(0);
Check.True(host.SetAutoRunBy("Nav", true), "answered: nav runs again");
@ -218,6 +224,55 @@ internal static class ActionPacingTests
Check.False(MoveAudit.OwnMovementActive, "and we are not moving any more");
});
private static void HeldStopSentAfterAnswer() => Paced(() =>
{
World();
FakeHost.SetMotionCalls = true;
var host = FakeHost.Create(Player);
host.UseFor(Corpse, "Loot", "open the claimed corpse");
Check.False(host.SetAutoRunBy("Nav", false), "nav's stop with nothing of ours moving waits");
Check.False(host.SetMotionBy("Nav", 0x6500000D, false), "and its turn-off");
Check.False(MoveAudit.FlushPendingStops(host, "test"), "nothing is sent while the use is unanswered");
Check.Eq(FakeHost.Sent.Count, 0, "nothing reached the client");
FakeHost.UseDone(0);
Check.True(MoveAudit.FlushPendingStops(host, "once the server answered"), "answered: the held stops go out (RynthAi's tick)");
Check.True(FakeHost.Sent.SequenceEqual(new[] { "autorun off", "motion 0x6500000D off" }), $"autorun off, then the turn-off ({string.Join(", ", FakeHost.Sent)})");
Check.True(Logged("held stop(s) sent once the server answered"), "logged");
Check.False(MoveAudit.HasPendingStop, "nothing left");
// A start that goes through sends any held stop first, so the order is kept.
host.UseFor(CorpseB, "Loot", "open");
FakeHost.Names[CorpseB] = "Corpse of Olthoi Swarm Drone";
host.StopCompletelyBy("Arbiter");
FakeHost.UseDone(0);
FakeHost.Sent.Clear();
Check.True(host.SetAutoRunBy("Nav", true), "nav runs again");
Check.True(FakeHost.Sent.SequenceEqual(new[] { "stop", "autorun on" }), $"the held stop, then the start ({string.Join(", ", FakeHost.Sent)})");
});
private static void CastWaitsForHeldStop() => Paced(() =>
{
var host = World();
host.UseFor(Corpse, "Loot", "open the claimed corpse");
Check.False(host.StopCompletelyBy("Arbiter"), "held while the use is unanswered");
// A player command (asked) casts over the unanswered use: the stop still goes first.
host.CastSpellFor(Corpse, 5367, "Command", "spell 5367 (/ra cast)", asked: true);
Check.True(FakeHost.Sent.SequenceEqual(new[] { "stop", "cast 5367" }), $"stop, then the cast ({string.Join(", ", FakeHost.Sent)})");
Check.False(MoveAudit.HasPendingStop, "nothing held after the cast");
Check.True(Logged("held stop(s) sent before a cast"), "logged");
});
private static void OldAutorunStopGoesThrough() => Paced(() =>
{
var host = World();
Check.True(host.SetAutoRunBy("Nav", true), "nav runs");
_t += 10_000; // nav's later autorun re-sends were held, or it simply ran on: well past the 3 s "fresh" window
host.UseFor(Corpse, "Loot", "open the claimed corpse");
Check.True(host.SetAutoRunBy("Nav", false), "our autorun is still on in AC: the stop goes through at once");
Check.True(FakeHost.AutoRunCalls.SequenceEqual(new[] { true, false }), "on, then off reached the client");
Check.False(MoveAudit.HasPendingStop, "nothing held");
});
private static void TimeLimits() => Paced(() =>
{
var host = World();

View file

@ -0,0 +1,200 @@
using System;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.CreatureData;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Casts that land nothing (player log, 2026-10-11): two Rampagers side by side, every Nether Arc
// VII a "predicted kill" on cast #1 (the learned casts-to-kill was 1), so the bot swapped to the
// other one and back for 30 minutes and the no-damage judge, which every swap resets, never ran.
// A monster swapped off as a predicted kill and then fought again is alive: no more predicted
// swaps off it. And each combat cast logs what the server said in the next few seconds.
internal static class CastNoDamageTests
{
private const uint Player = 0x50000D01;
private const uint Lb = 0x5B480000;
private const uint RampagerWcid = 16916;
private const uint Wand = 0x8008AB76;
private const int NetherArc7 = 5367;
public static void Register(Runner r)
{
r.Add("no-damage casts: a monster that survives a predicted kill is not predicted again", SurvivorNotPredictedAgain);
r.Add("no-damage casts: other monsters still get predicted kills; the memory lapses after 10 min", OthersStillPredicted);
r.Add("no-damage casts: the chat after a combat cast is logged, swings at us left out, capped, 4 s", CastChatTrace);
r.Add("no-damage casts (flight 63260): 3 magic casts landing nothing -> one short real sidestep, no cast meanwhile; a hit resets; 30 s apart", ResyncSidestep);
}
private sealed class Rig
{
public readonly LegacyUiSettings S = new() { MonsterRange = 30 };
public readonly MonsterDamageStore Store = new();
public readonly CombatManager C;
public readonly uint A = 0x80165DA5, B = 0x80165DA6, D = 0x80165DA7, E = 0x801753EC;
public DateTime Now = new(2026, 10, 11, 10, 55, 34);
public Rig()
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
FakeHost.Names[Player] = "Me";
FakeHost.Positions[Player] = (Lb | 0x018D, 96f, 96f, 0f);
FakeHost.PlayerPose = (Lb | 0x018D, 96f, 96f, 0f);
uint[] mobs = { A, B, D, E };
for (int i = 0; i < mobs.Length; i++)
{
FakeHost.Names[mobs[i]] = "Rampager";
FakeHost.Positions[mobs[i]] = (Lb | 0x018D, 96f + i, 98.7f, 0f);
FakeHost.ItemTypes[mobs[i]] = 0x10;
FakeHost.Wcids[mobs[i]] = RampagerWcid;
}
var host = FakeHost.Create();
var cache = FakeHost.MakeCache(host, Player, mobs, null);
C = new CombatManager(host, S, cache);
C.SetPlayerId(Player);
C.SetDamageStores(null, Store);
C.TargetClock = () => Now;
// What the player's store had learned: one Nether Arc VII kills a Rampager.
for (int i = 0; i < 3; i++)
Store.RecordKill(Wand, RampagerWcid, "Rampager", "Nether", 7, 1, 435);
Scan(mobs);
}
public void Scan(params uint[] ids) => C.SetScannedTargetsForTests(ids.Select(id => new CombatManager.ScannedTarget
{
Id = unchecked((int)id), Distance = 2.7, Angle = 0, Bearing = double.NaN, Name = "Rampager",
}));
public void Engage(uint id) => C.EngageForTest(unchecked((int)id));
public bool Cast() => C.CastAndPredictForTest(Wand, "Nether", 7);
public void Advance(double seconds) => Now = Now.AddSeconds(seconds);
public int LogCount(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal));
}
private static void ResyncSidestep()
{
var rig = new Rig();
FakeHost.SetMotionCalls = true;
var host = FakeHost.Create();
var c = new CombatManager(host, rig.S, FakeHost.MakeCache(host, Player, new[] { rig.A, rig.B }, null));
c.SetPlayerId(Player);
c.TargetClock = () => rig.Now;
MoveAudit.Reset();
c.MagicMissForTest(unchecked((int)rig.A));
c.MagicMissForTest(unchecked((int)rig.B)); // a swap to the other monster doesn't reset the count
Check.False(c.ResyncActive, "two misses: nothing yet");
c.ReportDamageOnTarget(unchecked((int)rig.A));
c.MagicMissForTest(unchecked((int)rig.A));
c.MagicMissForTest(unchecked((int)rig.A));
Check.False(c.ResyncActive, "a hit reset the count");
c.MagicMissForTest(unchecked((int)rig.A));
Check.True(c.ResyncActive, "three in a row: a re-sync is wanted");
Check.Eq(rig.LogCount("one short sidestep to re-sync"), 1, "said once");
Check.True(c.TickResyncStep(), "first tick: the step starts, no cast");
Check.True(FakeHost.MotionCalls.SequenceEqual(new[] { (0x6500000Fu, true) }), "sidestep right key down");
rig.Advance(0.2);
Check.True(c.TickResyncStep(), "still stepping at 200 ms");
rig.Advance(0.1);
Check.True(c.TickResyncStep(), "300 ms: key up, settling");
Check.True(FakeHost.MotionCalls.SequenceEqual(new[] { (0x6500000Fu, true), (0x6500000Fu, false) }), "key up");
rig.Advance(0.4);
Check.False(c.TickResyncStep(), "settled: casting may go on");
Check.Eq(c.ResyncSteps, 1, "one step");
for (int i = 0; i < 3; i++) c.MagicMissForTest(unchecked((int)rig.A));
Check.False(c.ResyncActive, "within 30 s: no second step");
rig.Advance(30);
for (int i = 0; i < 3; i++) c.MagicMissForTest(unchecked((int)rig.A));
Check.True(c.ResyncActive, "30 s later: another one");
c.TickResyncStep();
Check.True(FakeHost.MotionCalls[2] == (0x65000010u, true), "the other side this time");
}
private static void SurvivorNotPredictedAgain()
{
var r = new Rig();
// The ping-pong as it ran: A predicted dead and swapped off, then B.
r.Engage(r.A);
Check.True(r.Cast(), "cast #1 at A: predicted kill (learned casts-to-kill 1)");
r.C.PredictedSwapForTest();
Check.Eq(r.LogCount("Predicted kill shot 0x80165DA5"), 1, "the swap off A is logged");
r.Advance(6.3);
r.Engage(r.B);
Check.True(r.Cast(), "cast #1 at B: predicted kill");
r.C.PredictedSwapForTest();
// A is fought again 13 s later: it didn't die.
r.Advance(6.3);
r.Engage(r.A);
Check.False(r.Cast(), "A survived its predicted kill: no predicted swap off it this time");
Check.Eq(r.LogCount("Predicted kill of 0x80165DA5 'Rampager' didn't happen"), 1, "said once, naming A");
Check.True(r.LogCount("No more predicted swaps off it") == 1, "the line says what changes");
Check.False(r.Cast(), "cast #2 at A: still no predicted swap");
Check.False(r.Cast(), "cast #3 at A: still none");
Check.Eq(r.LogCount("didn't happen"), 1, "the line is not repeated per cast");
// B the same when it comes round.
r.Engage(r.B);
Check.False(r.Cast(), "B survived too: no predicted swap off it");
Check.Eq(r.LogCount("Predicted kill of 0x80165DA6 'Rampager' didn't happen"), 1, "said once for B");
}
private static void OthersStillPredicted()
{
var r = new Rig();
r.Engage(r.A);
r.Cast();
r.C.PredictedSwapForTest();
r.Advance(6);
r.Engage(r.A);
Check.False(r.Cast(), "A survived: not predicted");
// D was never swapped off: its cast #1 is a predicted kill as before (E is there to swap to).
r.Engage(r.D);
Check.True(r.Cast(), "a monster that never survived a prediction still gets one");
Check.Eq(r.LogCount("Predicted kill of 0x80165DA7"), 0, "nothing said about D");
// Ten minutes on, A is forgotten (a respawn can reuse the id).
r.Advance(11 * 60);
r.Engage(r.A);
Check.True(r.Cast(), "after 10 min A gets predicted kills again");
}
private static void CastChatTrace()
{
var r = new Rig();
r.C.StartCastChatTrace(NetherArc7, unchecked((int)r.A));
r.Advance(0.25);
r.C.TraceCastChat("You say, \"Zhavik Malar\"", 17);
r.C.TraceCastChat("You evaded Rampager!", 21);
r.C.TraceCastChat("Rampager grazes your lower leg for 9 points of bludgeoning damage!", 21);
r.Advance(1.0);
r.C.TraceCastChat("Rampager resists your spell", 7);
Check.Eq(r.LogCount("[CombatChat]"), 2, "the incantation and the resist are logged, the swing and the evade are not");
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatChat] +250 ms after", StringComparison.Ordinal)
&& l.Contains("at 0x80165DA5: type=17", StringComparison.Ordinal)),
"the line has the time since the send, the target and the chat type");
Check.True(FakeHost.Logs.Any(l => l.Contains("+1250 ms", StringComparison.Ordinal) && l.Contains("'Rampager resists your spell'", StringComparison.Ordinal)),
"the server's answer is quoted");
for (int i = 0; i < 20; i++) r.C.TraceCastChat($"line {i}", 0);
Check.Eq(r.LogCount("[CombatChat]"), 8, "at most 8 lines per cast");
// A new cast starts a new trace; nothing is logged once its 4 s are up.
r.C.StartCastChatTrace(NetherArc7, unchecked((int)r.B));
r.Advance(4.1);
r.C.TraceCastChat("Your spell fizzled.", 7);
Check.Eq(r.LogCount("[CombatChat]"), 8, "a line 4.1 s after the send is not logged");
r.C.TraceCastChat("You cast Corruption VII on Rampager", 7);
Check.Eq(r.LogCount("[CombatChat]"), 8, "nor any later one until the next cast");
}
}

View file

@ -0,0 +1,272 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.CreatureData;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The Damage tab's monster rows (2026-10-11, a player's screenshot):
// * the player's own character was a row (no HP, no "weak to", 0 kills). The object cache files
// any creature whose type reads first as a Monster - other players, and the character itself
// once something looked it up through the cache - and players are attackable, so the class
// and attackable checks let them into the nearby rows and the appraisal store;
// * two "Rampager" rows, one with the kills and one without: retail has five Rampager weenies
// (10810, 10811, 16916, 21526, 22599), and each wcid was a row. Now one row per name.
internal static class DamageRowsTests
{
private const uint Player = 0x50000C01, OtherPlayer = 0x50000C02, AdminPlayer = 0x50000C03;
private const uint Pet = 0x80001003, MonsterA = 0x80001001, MonsterB = 0x80001002;
private const uint RampagerA = 10810, RampagerB = 10811, PetWcid = 48000;
private const uint ItemTypeCreature = 0x10, BfPlayer = 0x8, BfAttackable = 0x10;
private const uint Wand = 0x80000401;
private static readonly BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("damage rows: no player (you, another player, an admin, a pet) is listed or recorded", NoPlayerRows);
r.Add("damage rows: player rows already saved are dropped when the stores load", StoredPlayerRowsDropped);
r.Add("damage rows: two wcids sharing a name are one row, and an edit on it applies to both", SameNameOneRow);
r.Add("damage rows: one wcid from every source and difficulty tier is one row", OneWcidOneRow);
}
// ── Fixture ──────────────────────────────────────────────────────────────
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly MonsterDamageStore Store = new();
public readonly CreatureProfileStore Creatures = new();
public Bot(RynthCoreHost host, string name)
{
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var cache = new WorldObjectCache(host);
cache.SetPlayerId(Player);
Set("_objectCache", cache);
Set("_playerId", Player);
string folder = Path.Combine(Program.TempRoot, "damage-rows", name);
if (Directory.Exists(folder)) Directory.Delete(folder, true);
Directory.CreateDirectory(folder);
Store.SetCharacter(folder);
Set("_damageStore", Store);
Set("_creatureStore", Creatures);
foreach (uint id in new[] { OtherPlayer, AdminPlayer, Pet, MonsterA, MonsterB })
cache.OnCreateObject(id);
cache.Tick();
// What put the character in the table: a lookup of it through the cache files it as
// a landscape Monster (the indexer's lazy classification doesn't skip the player).
_ = cache[unchecked((int)Player)];
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public HashSet<uint> Seen => (HashSet<uint>)typeof(RynthAiPlugin).GetField("_seenMonstersThisSession", Any)!.GetValue(P)!;
/// <summary>The monster rows of the Damage tab (the Default line left out).</summary>
public List<JsonElement> Rows()
{
using var doc = JsonDocument.Parse(P.BuildMonsterDamageJson());
return doc.RootElement.EnumerateArray()
.Where(e => !(e.TryGetProperty("isDefault", out var d) && d.GetBoolean()))
.Select(e => e.Clone()).ToList();
}
}
private static void World(bool withPet = true)
{
FakeHost.Reset();
var here = (Cell: 0xA9B40001u, X: 10f, Y: 10f, Z: 0f);
FakeHost.PlayerPose = here;
void Creature(uint id, string name, uint wcid, uint bitfield, float dx)
{
FakeHost.Names[id] = name;
FakeHost.Wcids[id] = wcid;
FakeHost.ItemTypes[id] = ItemTypeCreature;
FakeHost.Bitfields[id] = bitfield;
FakeHost.Positions[id] = (here.Cell, here.X + dx, here.Y, here.Z);
}
Creature(Player, "Drakkon", PlayerWeenies.Human, BfPlayer | BfAttackable, 0f);
Creature(OtherPlayer, "Lucy McJuicy", PlayerWeenies.Human, BfPlayer | BfAttackable, 2f);
Creature(AdminPlayer, "+Buffy", PlayerWeenies.Admin, BfPlayer | BfAttackable, 3f);
Creature(MonsterA, "Rampager", RampagerA, BfAttackable, 5f);
Creature(MonsterB, "Rampager", RampagerB, BfAttackable, 6f);
if (withPet)
{
Creature(Pet, "Fire Spirit", PetWcid, BfAttackable, 1f);
FakeHost.InstanceIds[(Pet, 44)] = Player; // PetOwner
}
}
private static uint[] Wcids(JsonElement row)
=> row.TryGetProperty("wcids", out var w) ? w.EnumerateArray().Select(x => (uint)x.GetInt64()).ToArray()
: new[] { (uint)row.GetProperty("wcid").GetInt64() };
// ── Tests ────────────────────────────────────────────────────────────────
private static void NoPlayerRows()
{
World();
var host = FakeHost.Create(Player);
var bot = new Bot(host, "no-player");
// Appraise everyone: each answer carries max health, which is what records a creature.
foreach (uint id in new[] { Player, OtherPlayer, AdminPlayer, Pet, MonsterA })
bot.P.OnUpdateHealth(id, 1f, 400, 435);
var rows = bot.Rows();
string[] names = rows.Select(r => r.GetProperty("name").GetString() ?? "").ToArray();
foreach (string who in new[] { "Drakkon", "Lucy McJuicy", "+Buffy", "Fire Spirit" })
Check.False(names.Contains(who), $"'{who}' is not a Damage-tab row (rows: {string.Join(", ", names)})");
Check.False(rows.SelectMany(Wcids).Any(PlayerWeenies.IsPlayerWcid), "no row under a player weenie (1, 4)");
Check.True(names.Contains("Rampager"), "the monsters nearby are rows");
Check.False(bot.Creatures.TryGetByWcid(PlayerWeenies.Human, out _), "no player in creatures.json (wcid 1)");
Check.False(bot.Creatures.TryGetByWcid(PlayerWeenies.Admin, out _), "no admin in creatures.json (wcid 4)");
Check.False(bot.Creatures.TryGetByName("Fire Spirit", out _), "no pet in creatures.json");
Check.True(bot.Creatures.TryGetByWcid(RampagerA, out _), "the monster is recorded");
Check.False(bot.Seen.Contains(PlayerWeenies.Human) || bot.Seen.Contains(PetWcid), "nor in this session's appraised list");
// The learned store refuses a player weenie whatever records it.
bot.Store.RecordHit(Wand, PlayerWeenies.Human, "Lucy McJuicy", "Fire", 7, 120, false);
bot.Store.RecordKill(Wand, PlayerWeenies.Human, "Lucy McJuicy", "Fire", 7, 3, 400);
bot.Store.RecordTaken(PlayerWeenies.Human, "Lucy McJuicy", "Fire", 50);
bot.Store.SetManualHp(PlayerWeenies.Admin, 999);
bot.Store.NoteCast(PlayerWeenies.Human, 7, "Lucy McJuicy");
Check.False(bot.Store.Snapshot().Any(r => PlayerWeenies.IsPlayerWcid(r.Wcid)), "monster_damage.txt never records a player");
Check.Eq(bot.Store.GetManualHp(PlayerWeenies.Admin), 0.0, "nor a setting on one");
}
private static void StoredPlayerRowsDropped()
{
World(withPet: false);
var host = FakeHost.Create(Player);
// monster_damage.txt with the character's own row and a monster's.
string folder = Path.Combine(Program.TempRoot, "damage-rows", "stored");
Directory.CreateDirectory(folder);
string file = Path.Combine(folder, "monster_damage.txt");
File.WriteAllLines(file, new[]
{
"# RynthAi per-character monster damage learning (auto-generated).",
"M|1|Drakkon|0",
"D|1|Drakkon|0|Fire|0|0|0|1|2|0|0|0|0",
"T|4|+Buffy|Fire|3|20|30",
"H|10810|Rampager|420|4",
"D|10810|Rampager|2147487513|Fire|7|120|20|3.5|4|200|4|100|16",
});
var store = new MonsterDamageStore();
store.SetCharacter(folder);
Check.Eq(string.Join(",", store.Snapshot().Select(r => r.Wcid).Distinct()), "10810", "only the monster loads");
store.SaveIfDirty();
string saved = File.ReadAllText(file);
Check.False(saved.Contains("Drakkon") || saved.Contains("+Buffy"), "the file is saved without the player rows");
Check.True(saved.Contains("Rampager"), "and with the monster");
// creatures.json (Program points CreatureProfileStore.Folder at the scratch folder).
string cfile = Path.Combine(CreatureProfileStore.Folder, "creatures.json");
Directory.CreateDirectory(CreatureProfileStore.Folder);
File.WriteAllText(cfile,
"{\"Lucy McJuicy|1\":{\"Name\":\"Lucy McJuicy\",\"Wcid\":1,\"CreatureType\":31,\"MaxHealth\":340,\"KnownSpellIds\":[]},"
+ "\"+Buffy|4\":{\"Name\":\"+Buffy\",\"Wcid\":4,\"CreatureType\":31,\"MaxHealth\":335,\"KnownSpellIds\":[]},"
+ "\"Rampager|10810\":{\"Name\":\"Rampager\",\"Wcid\":10810,\"CreatureType\":0,\"MaxHealth\":280,\"KnownSpellIds\":[]}}");
var creatures = new CreatureProfileStore();
creatures.Load();
Check.False(creatures.TryGetByWcid(1, out _) || creatures.TryGetByWcid(4, out _), "players are not loaded as creatures");
Check.True(creatures.TryGetByWcid(RampagerA, out _), "the monster is");
creatures.SaveIfDirty();
string csaved = File.ReadAllText(cfile);
Check.False(csaved.Contains("Lucy McJuicy") || csaved.Contains("+Buffy"), "creatures.json is saved without them");
Check.True(csaved.Contains("Rampager"), "and keeps the monster");
File.Delete(cfile);
// And a bot that has them in memory lists none of them.
var bot = new Bot(host, "stored-bot");
bot.Set("_damageStore", store);
Check.False(bot.Rows().Any(r => Wcids(r).Any(PlayerWeenies.IsPlayerWcid)), "no player row in the Damage tab");
}
private static void SameNameOneRow()
{
World(withPet: false);
var host = FakeHost.Create(Player);
var bot = new Bot(host, "same-name");
// Rampager 10810: four kills. Rampager 10811: appraised and standing next to it, never killed.
// Both had a manual HP of 435 (the screenshot), set one row at a time.
for (int i = 0; i < 4; i++)
{
bot.Store.RecordHit(Wand, RampagerA, "Rampager", "Fire", 7, 145, false);
bot.Store.RecordKill(Wand, RampagerA, "Rampager", "Fire", 7, 3, 435);
}
bot.Store.SetManualHp(RampagerA, 435);
bot.Store.SetManualHp(RampagerB, 435);
bot.P.OnUpdateHealth(MonsterB, 1f, 435, 435);
var rows = bot.Rows().Where(r => r.GetProperty("name").GetString() == "Rampager").ToList();
Check.Eq(rows.Count, 1, "one Rampager row");
var row = rows[0];
Check.Eq(string.Join(",", Wcids(row)), "10810,10811", "listing both kinds");
Check.Eq((uint)row.GetProperty("wcid").GetInt64(), RampagerA, "the row is the kind with the kills");
Check.Eq(row.GetProperty("kills").GetInt32(), 4, "with its kills");
Check.Eq(row.GetProperty("hp").GetInt32(), 435, "and the HP");
Check.True(row.GetProperty("hpManual").GetBoolean(), "set by hand");
Check.True(row.GetProperty("nearby").GetBoolean(), "nearby: both stand here");
// Edits on the row reach every kind.
bot.P.SetMonsterHp(RampagerA, 500);
Check.Eq(bot.Store.GetManualHp(RampagerB), 500.0, "an HP set on the row applies to the other kind");
bot.P.SetMonsterWeapon(RampagerA, Wand);
Check.Eq(bot.Store.GetManualWeapon(RampagerB), Wand, "so does a weapon");
bot.P.SetMonsterOffhand(RampagerA, 77);
Check.Eq(bot.Store.GetManualOffhand(RampagerB), 77u, "and an offhand");
bot.P.SetMonsterPet(RampagerA, "E:Fire");
Check.Eq(bot.Store.GetManualPet(RampagerB), "E:Fire", "and a pet");
Check.Eq(bot.Store.GetManualHp(RampagerA), 500.0, "the row's own kind too");
// Two kinds both fought: the kills add up, one drawer line per weapon/spell.
bot.Store.RecordKill(Wand, RampagerB, "Rampager", "Fire", 7, 5, 435);
row = bot.Rows().Single(r => r.GetProperty("name").GetString() == "Rampager");
Check.Eq(row.GetProperty("kills").GetInt32(), 5, "kills of both kinds");
var tiers = row.GetProperty("tiers").EnumerateArray().ToList();
Check.Eq(tiers.Count, 1, "one drawer line for the shared weapon and spell");
Check.Eq(tiers[0].GetProperty("kills").GetInt32(), 5, "with both kinds' kills");
Check.Eq(tiers[0].GetProperty("casts").GetDouble(), 3.4, "casts to kill weighted by kills ((4*3+5)/5)");
// Removing the row removes every kind.
Check.True(bot.P.DeleteMonsterRow(RampagerA.ToString()), "the row is removed");
Check.False(bot.Store.Snapshot().Any(r => r.Wcid == RampagerA || r.Wcid == RampagerB), "both kinds' learned data went");
Check.False(bot.Seen.Contains(RampagerB), "and the appraised kind with it");
}
private static void OneWcidOneRow()
{
World(withPet: false);
FakeHost.Positions.Remove(MonsterB); // only Rampager 10810 here
FakeHost.Names.Remove(MonsterB);
var host = FakeHost.Create(Player);
var bot = new Bot(host, "one-wcid");
// The same Rampager from every source: learned at real Dereth and at an Aelrynth
// difficulty tier (kept per (wcid, tier)), appraised this session, standing nearby,
// and in creatures.json under a differently cased name.
bot.Store.RecordKill(Wand, RampagerA, "Rampager", "Fire", 7, 3, 435);
bot.Store.Difficulty = 2;
bot.Store.RecordKill(Wand, RampagerA, "Rampager", "Fire", 7, 4, 480);
bot.Store.Difficulty = 0;
bot.Creatures.Upsert(new CreatureProfile { Name = "rampager", Wcid = RampagerA, MaxHealth = 280 });
bot.P.OnUpdateHealth(MonsterA, 1f, 435, 435);
var rows = bot.Rows();
Check.Eq(rows.Count, 1, $"one row (rows: {string.Join(", ", rows.Select(r => r.GetProperty("name").GetString() + "/" + r.GetProperty("wcid")))})");
Check.Eq((uint)rows[0].GetProperty("wcid").GetInt64(), RampagerA, "the Rampager");
Check.False(rows[0].TryGetProperty("wcids", out _), "of one kind");
Check.Eq(rows[0].GetProperty("kills").GetInt32(), 1, "real Dereth's kill (the tier's are its own)");
}
}

View file

@ -57,6 +57,21 @@ internal static class ExpressionTests
r.Add("expr: list text saved before escaping reads the same", OldListTextReadsTheSame);
r.Add("expr: # takes a regex pattern without backticks, as documented", RegexOperatorUnquoted); // was a known failure; fixed by c34b39c
r.Add("expr: vitae[] reports no penalty when it cannot read vitae", VitaeWithoutHost); // was a known failure; fixed by 33f23f7
// UtilityBelt expression reference audit (2026-10-11): each test pins a documented
// behaviour we got wrong. The doc is Expressions.html (utilitybelt.gitlab.io/docs/expressions).
r.Add("expr doc: ; runs each expression in turn", DocSemicolon);
r.Add("expr doc: && and || skip the side that can't change the answer", DocShortCircuit);
r.Add("expr doc: unquoted text keeps its spaces, backslash escapes a character", DocStrings);
r.Add("expr doc: true and false are 1 and 0", DocTrueFalse);
r.Add("expr doc: @name and &name read pvars and gvars, $ takes an expression", DocVarShorthand);
r.Add("expr doc: {index}, {key} and slices on lists, dicts and text", DocIndexAndSlice);
r.Add("expr: $x = value assigns (UB syntax real metas use)", AssignmentSyntax);
r.Add("expr doc: listadd, listpop and friends change the list in its variable", DocListsChangeInPlace);
r.Add("expr doc: a dictionary kept in a variable lives on", DocDictsPersist);
r.Add("expr doc: iif, istrue, isfalse and getobjectinternaltype", DocLogicAndTypes);
r.Add("expr doc: name, regex, state and setting arguments may be expressions", DocTextArguments);
r.Add("expr doc: getheadingto across landblocks, casts of unknown spells, getknownspells", DocLiveState);
}
// ── Helpers ───────────────────────────────────────────────────────────────
@ -205,7 +220,7 @@ internal static class ExpressionTests
Is(e, "", "");
Is(e, " ", "");
Is(e, "1 2", "1"); // text after a complete expression is ignored
Is(e, "hello world", "hello"); // so a bare two-word value keeps only the first word
Is(e, "hello world", "hello world"); // text of letters and spaces is one value (reference)
Is(e, "@", "");
Is(e, "!1", ""); // there is no logical not; use ==0 or isfalse[]
Is(e, "a.b_c9", "a.b_c9"); // identifiers keep dots and underscores
@ -262,7 +277,7 @@ internal static class ExpressionTests
Is(e, "testvar[a]+testvar[b]", "0");
Is(e, "setvar[s, `two words`]", "two words");
Is(e, "$s", "two words");
Is(e, "setvar[t, two words]", "two"); // unquoted: only the first word
Is(e, "setvar[t, two words]", "two words"); // unquoted text keeps all its words
e.SetVariable("host_set", "7");
Is(e, "$host_set", "7");
}
@ -346,15 +361,18 @@ internal static class ExpressionTests
Is(e, "listgetitem[$l,3]", "b");
Is(e, "listgetitem[$l,4]", "");
Is(e, "listgetitem[$l,-1]", "");
Is(e, "listadd[$l,d]", "[a,b,c,b,d]");
Is(e, "$l", "[a,b,c,b]"); // lists are values: listadd returns a new one
Is(e, "listinsert[$l,z,0]", "[z,a,b,c,b]");
Is(e, "listinsert[$l,z,4]", "[a,b,c,b,z]");
Is(e, "listinsert[$l,z,5]", "0");
Is(e, "listremove[$l,b]", "[a,c,b]"); // first match only
Is(e, "listremove[$l,q]", "[a,b,c,b]");
Is(e, "listremoveat[$l,1]", "[a,c,b]");
Is(e, "listremoveat[$l,9]", "0");
// listcopy[...] is not a variable, so these give a changed copy and $l stays.
Is(e, "listadd[listcopy[$l],d]", "[a,b,c,b,d]");
Is(e, "$l", "[a,b,c,b]");
Is(e, "listinsert[listcopy[$l],z,0]", "[z,a,b,c,b]");
Is(e, "listinsert[listcopy[$l],z,4]", "[a,b,c,b,z]");
Is(e, "listinsert[listcopy[$l],z,5]", "0");
Is(e, "listremove[listcopy[$l],b]", "[a,c,b]"); // first match only
Is(e, "listremove[listcopy[$l],q]", "[a,b,c,b]");
Is(e, "listremoveat[listcopy[$l],1]", "[a,c,b]");
Is(e, "listremoveat[listcopy[$l],9]", "0");
Is(e, "listinsert[$l,z,5]", "0"); // a failed change leaves $l alone
Is(e, "$l", "[a,b,c,b]");
Is(e, "listcontains[$l,C]", "1"); // ignores case
Is(e, "listcontains[$l,q]", "0");
Is(e, "listindexof[$l,b]", "1");
@ -364,11 +382,11 @@ internal static class ExpressionTests
Is(e, "listcopy[$l]", "[a,b,c,b]");
Is(e, "listcopy[x]", "[]");
Is(e, "listreverse[$l]", "[b,c,b,a]");
Is(e, "listpop[$l]", "b");
Is(e, "listpop[$l,0]", "a");
Is(e, "listpop[$l,-5]", "b"); // any negative index means the last item
Is(e, "listpop[listcopy[$l]]", "b");
Is(e, "listpop[listcopy[$l],0]", "a");
Is(e, "listpop[listcopy[$l],-5]", "b"); // any negative index means the last item
Is(e, "listpop[listcreate[]]", "");
Is(e, "listclear[$l]", "[]");
Is(e, "listclear[listcopy[$l]]", "[]");
Is(e, "listfromrange[1,3]", "[1,2,3]");
Is(e, "listfromrange[3,1]", "[3,2,1]");
Is(e, "listfromrange[2,2]", "[2]");
@ -404,10 +422,10 @@ internal static class ExpressionTests
var e = Engine();
Is(e, "dictcreate[a,1,b,2]", "D:0");
Is(e, "dictgetitem[dictcreate[a,1,b,2],b]", "2");
Is(e, "setvar[d, dictcreate[a,1]] && dictadditem[$d,a,9]", "1"); // one evaluation: the handle is live
// Dicts last for one top-level evaluation; a handle kept in a variable goes dead.
Is(e, "dictgetitem[$d,a]", "");
Is(e, "dictsize[$d]", "0");
Is(e, "setvar[d, dictcreate[a,1]] && dictadditem[$d,a,9]", "1");
// A handle kept in a variable stays live in later evaluations (reference audit).
Is(e, "dictgetitem[$d,a]", "9");
Is(e, "dictsize[$d]", "1");
Is(e, "setvar[d, dictcreate[k,v]] && dictadditem[$d,n,1]==0 && dicthaskey[$d,n] && dictsize[$d]==2", "1");
Is(e, "setvar[d, dictcreate[k,v]] && dictremovekey[$d,k] && dictremovekey[$d,k]==0 && dictsize[$d]==0", "1");
Is(e, "listcount[dictkeys[dictcreate[a,1,b,2,c,3]]]", "3");
@ -415,7 +433,7 @@ internal static class ExpressionTests
Is(e, "dicthaskey[dictcreate[Key,1],key]", "0"); // dict keys are case-sensitive
Is(e, "setvar[d, dictcreate[a,1]] && setvar[c, dictcopy[$d]] && dictadditem[$c,z,1]==0 && dicthaskey[$d,z]==0", "1");
Is(e, "dictsize[dictclear[dictcreate[a,1]]]", "0");
Is(e, "dictcreate[a]", "D:0"); // odd argument count: the last key is dropped
Check.True(e.Evaluate("dictcreate[a]").StartsWith("D:"), "odd argument count: still a dict"); // the last key is dropped
Is(e, "dictsize[dictcreate[a]]", "0");
Is(e, "dictgetitem[D:99,a]", "");
}
@ -453,7 +471,8 @@ internal static class ExpressionTests
Is(e, "atan2[0,1]", "0");
Is(e, "cos[0]", "1");
Is(e, "isfalse[0]", "1");
Is(e, "istrue[2]", "1");
Is(e, "istrue[2]", "0"); // "equal to true (1)" (reference)
Is(e, "istrue[1]", "1");
Is(e, "istrue[abc]", "0"); // text is not a true number here, though ToBool says true
Is(e, "spellname[1332]", "Strength Self VI");
Is(e, "spellname[99999999]", "Unknown Spell (99999999)");
@ -473,8 +492,8 @@ internal static class ExpressionTests
Is(e, "testvar[b]", "0"); // the other branch never ran
Is(e, "iif[0, x]", "");
Is(e, "iif[1]", "");
Is(e, "iif[abc, yes, no]", "yes"); // lazy iif uses ToBool: text is true
Is(e, "iif[0.0, yes, no]", "yes"); // "0.0" is not "0"
Is(e, "iif[abc, yes, no]", "no"); // "false or not a number" takes the third (reference)
Is(e, "iif[0.0, yes, no]", "no"); // 0.0 is the number 0
Is(e, "if[1, setvar[c,1]]", "1");
Is(e, "if[0, setvar[d,1]]", "");
Is(e, "testvar[d]", "0");
@ -544,7 +563,7 @@ internal static class ExpressionTests
Is(e, "getobjectinternaltype[stopwatchcreate[]]", "7");
Is(e, "getobjectinternaltype[dictcreate[]]", "7");
Is(e, "getobjectinternaltype[`[WorldObject] 0x50000001: Sword`]", "7");
Is(e, "getobjectinternaltype[listcreate[1,2]]", "3"); // lists are text
Is(e, "getobjectinternaltype[listcreate[1,2]]", "7"); // a list is an object (reference audit)
Is(e, "raoptget[nope]", "0");
Is(e, "raoptset[mode, hunt]", "1");
@ -748,7 +767,7 @@ internal static class ExpressionTests
Is(e, "getgameticks[]", "27435600");
Is(e, "getgameyear[]", "10");
Is(e, "getgamemonth[]", "0");
Is(e, "getgameday[]", "0");
Is(e, "getgameday[]", "1"); // days are 1-30 (reference)
Is(e, "getgamehour[]", "7");
Is(e, "getisday[]", "1");
Is(e, "getisnight[]", "0");
@ -756,6 +775,9 @@ internal static class ExpressionTests
Is(e, "getminutesuntilday[]", "0");
Is(e, "getgamemonthname[0]", "Morningthaw");
Is(e, "getgamemonthname[11]", "Wintersebb");
Is(e, "getgamemonthname[6]", "Harvestgain"); // spelled as the reference lists it
Is(e, "getmonthname[1]", "Solclaim"); // the reference example's name
Is(e, "getgamehourname[1]", "Darktide-and-Half");
Is(e, "getgamemonthname[12]", "");
Is(e, "getgamemonthname[x]", "");
Is(e, "getgamehourname[0]", "Darktide");
@ -966,6 +988,324 @@ internal static class ExpressionTests
Check.Eq(e.Evaluate("getvar[lastchat] # killed.*olthoi"), "1", "getvar[lastchat] # killed.*olthoi");
}
// ── UtilityBelt reference audit ──────────────────────────────────────────
private static void DocSemicolon()
{
var e = Engine();
// The doc's own example (with listcreate, its createlist is a typo).
Is(e, "setvar[myList,listcreate[1,2,3]]; setvar[n,4]", "4");
Is(e, "$myList", "[1,2,3]");
Is(e, "getvar[n]", "4");
// The stopwatch pattern real metas use: the second half used to be dropped.
Is(e, "setvar[T, stopwatchcreate[]];stopwatchstart[getvar[T]]", "SW:0");
Is(e, "setvar[a,1];;setvar[b,2];", "2"); // empty parts are skipped
Is(e, "testvar[a]+testvar[b]", "2");
Is(e, "1+1; 2+2", "4"); // the value is the last expression's
// Inside a template, as in the doc's listsort example.
Is(e, "listmap[listcreate[1,2], `setvar[t,$1*10];$t+1`]", "[11,21]");
Is(e, "getvar[a] # 1;setvar[c,3]", "3"); // an unquoted # pattern ends at ;
}
private static void DocShortCircuit()
{
var e = Engine();
Is(e, "0 && setvar[x,1]", "0");
Is(e, "testvar[x]", "0"); // the right side never ran
Is(e, "1 || setvar[y,1]", "1");
Is(e, "testvar[y]", "0");
Is(e, "1 && setvar[z,1]", "1");
Is(e, "testvar[z]", "1");
Is(e, "0 || setvar[w,5]", "1");
Is(e, "getvar[w]", "5");
// Real meta idiom: cond && action, with nested calls and backticks in the skipped part.
Is(e, "setvar[debug,0]; $debug>=2&&setvar[said, `[x], y`]", "0");
Is(e, "testvar[said]", "0");
Is(e, "0 && (setvar[p,1] || setvar[q,1]) || setvar[r,1]", "1");
Is(e, "testvar[p]+testvar[q]", "0");
Is(e, "getvar[r]", "1");
Is(e, "0 && 1 || 1", "1"); // results are as before
Is(e, "1 && 0", "0");
}
private static void DocStrings()
{
var e = Engine();
// The reference's examples: "123 test" escaped as \1\2\3 test, "p@cMan$)" as p\@cMan\$\).
Is(e, "setvar[a, \\1\\2\\3 test]", "123 test");
Is(e, "setvar[b, p\\@cMan\\$\\)]", "p@cMan$)");
Is(e, "setvar[c, some example string]", "some example string");
Is(e, "strlen[some example string]", "19");
// Real meta text: an escaped '!' and comma, a chat command joined with +.
Is(e, "setvar[m, Not in a fellowship\\!]", "Not in a fellowship!");
Is(e, "listcount[listcreate[a\\,b, c]]", "2"); // \, is a comma, not a separator
e.Evaluate("setvar[nav, Hunt Loop]");
Is(e, "\\/vt nav load +getvar[nav]", "/vt nav load Hunt Loop");
Is(e, "\\/t +getvar[nav]+\\, Removed as bell user\\.", "/t Hunt Loop, Removed as bell user.");
Is(e, "\\/ub jumpw 180 +cstr[750-5]", "/ub jumpw 180 745");
Is(e, "getvar[nav] == Hunt Loop && 1", "1"); // compared as the whole text
Is(e, "setvar[d, ILT Mega.met]", "ILT Mega.met");
Is(e, "1 2", "1"); // a number is one word
Is(e, "abc def[] ghi", "abc"); // a function name is not text
Is(e, "listcount[listcreate[`a]`, b]]", "2"); // a ']' inside backticks is text
Is(e, "echo[`x`, 1] ; strlen[`a\\`b`]", "3"); // \` inside backticks still works
// Inside backticks \\ is one backslash (real metas nest templates this way); any other
// \x stays, as in the reference's getregexmatch[`test 123`,`\d+`].
Is(e, "getregexmatch[`test 123`,`\\d+`]", "123");
Is(e, "getregexmatch[`test 123`,`\\\\d+`]", "123"); // `\\d+` is the regex \d+
Is(e, "exec[`setvar[cmd, \\\\/vt forcebuff]`]", "/vt forcebuff");
Is(e, "strlen[`a\\\\b`]", "3");
}
private static void DocTrueFalse()
{
var e = Engine();
Is(e, "true", "1");
Is(e, "false", "0");
Is(e, "True == 1", "1");
Is(e, "FALSE == 0", "1");
Is(e, "setvar[flag, False]", "0");
Is(e, "iif[true, yes, no]", "yes");
Is(e, "true story", "true story"); // only the word on its own
Is(e, "`true`", "true"); // and not in backticks
}
private static void DocVarShorthand()
{
FakeHost.Reset();
FakeHost.Names[Player] = "Sunnuj";
var e = Engine(FakeHost.Create(), playerId: Player);
Is(e, "setpvar[myPersistentVariable, 5]", "5");
Is(e, "@myPersistentVariable", "5");
Is(e, "@myPersistentVariable * 2", "10");
Is(e, "@unsetPvar", "0");
Is(e, "setgvar[myGlobalVariable, hi]", "hi");
Is(e, "&myGlobalVariable", "hi");
Is(e, "&unsetGvar", "0");
Is(e, "7&3", "3"); // & between values is still bitwise
Is(e, "6 & 3", "2");
Is(e, "1 && &myGlobalVariable == hi", "1");
// "$wobjectgetname[wobjectgetplayer[]]" is getvar[wobjectgetname[wobjectgetplayer[]]].
Is(e, "setvar[Sunnuj, mine]", "mine");
Is(e, "$wobjectgetname[0x50000A01]", "mine");
Is(e, "setvar[which, Sunnuj]", "Sunnuj");
Is(e, "$getvar[which]", "mine");
Is(e, "@", ""); // a stray sigil reads nothing, as before
}
private static void DocIndexAndSlice()
{
var e = Engine();
e.Evaluate("setvar[list, listcreate[a,b,c,d]]");
Is(e, "$list{0}", "a");
Is(e, "$list{3}", "d");
Is(e, "$list{-1}", "d");
Is(e, "$list{9}", "");
Is(e, "$list{:-1}", "[a,b,c]"); // the reference's slice example
Is(e, "$list{1:3}", "[b,c]");
Is(e, "$list[1:3]", "[b,c]"); // its other spelling
Is(e, "$list{2:}", "[c,d]");
Is(e, "$list{3:1}", "[]");
Is(e, "listcount[$list{1:}]", "3");
Is(e, "test[1:]", "est"); // "Strings support slices like arrays"
Is(e, "test[:-1]", "tes");
Is(e, "`hello`{1}", "e");
Is(e, "setvar[i, 2]; $list{$i}", "c"); // the index is an expression
Is(e, "listcreate[x,y]{1}", "y");
// A dict by key, in one evaluation (keeping dicts across evaluations is a separate test).
Is(e, "setvar[d, dictcreate[a,2,params,p]]; $d{a}+$d{params}", "2p");
Is(e, "setvar[d, dictcreate[c, dictcreate[name,Bob]]]; $d{c}{name}", "Bob");
Is(e, "nosuchfn[1]", ""); // no ':' : still an unknown function
}
private static void AssignmentSyntax()
{
FakeHost.Reset();
var e = Engine(FakeHost.Create());
Is(e, "$x=5", "5");
Is(e, "$x", "5");
Is(e, "$x == 5", "1"); // == is still a comparison
Is(e, "$x = $x + 1", "6");
Is(e, "@TotalWins=@TotalWins+1", "1");
Is(e, "@TotalWins=@TotalWins+1", "2");
Is(e, "&g = hello", "hello");
Is(e, "getgvar[g]", "hello");
// Real meta: the value stops at &&, so the list is stored and then counted.
Is(e, "$found=listcreate[a,b] && listcount[$found]>0", "1");
Is(e, "$found", "[a,b]");
Is(e, "1 && $later=7", "1");
Is(e, "$later", "7");
Is(e, "0 && $never=1", "0");
Is(e, "testvar[never]", "0");
Is(e, "$a=1;$b=$a+1;$b", "2");
}
private static void DocListsChangeInPlace()
{
FakeHost.Reset();
FakeHost.Names[Player] = "List Toon";
var e = Engine(FakeHost.Create(), playerId: Player);
// The reference's overview example.
Is(e, "setvar[myList,listcreate[1,2,3]]; listadd[$myList,4]", "[1,2,3,4]");
Is(e, "$myList", "[1,2,3,4]");
// Real meta: no setvar around it.
e.Evaluate("setvar[CharList, listcreate[]]");
e.Evaluate("listadd[getvar[CharList], Drakkon]");
e.Evaluate("listadd[getvar[CharList], Lucy McJuicy]");
Is(e, "$CharList", "[Drakkon,Lucy McJuicy]");
Is(e, "listinsert[getvar[CharList], Zed, 0]", "[Zed,Drakkon,Lucy McJuicy]");
Is(e, "listremove[$CharList, Drakkon]", "[Zed,Lucy McJuicy]");
Is(e, "listremoveat[$CharList, 0]", "[Lucy McJuicy]");
Is(e, "$CharList", "[Lucy McJuicy]");
// listpop removes and returns; with no index, the last item.
e.Evaluate("setvar[q, listcreate[a,b,c]]");
Is(e, "listpop[$q]", "c");
Is(e, "listpop[getvar[q],0]", "a");
Is(e, "$q", "[b]");
Is(e, "listclear[$q]", "[]");
Is(e, "$q", "[]");
Is(e, "listpop[$q]", ""); // empty: nothing to pop
// pvars and gvars too, and setvar around it still works.
e.Evaluate("setpvar[pl, listcreate[x]]");
e.Evaluate("listadd[@pl, y]");
Is(e, "getpvar[pl]", "[x,y]");
e.Evaluate("setgvar[gl, listcreate[1]]");
e.Evaluate("listadd[getgvar[gl], 2]");
Is(e, "&gl", "[1,2]");
Is(e, "setvar[s, listadd[$myList, 5]]", "[1,2,3,4,5]");
Is(e, "$s", "[1,2,3,4,5]");
// Not a variable, or not a list: nothing is written.
Is(e, "setvar[n, 7]; listadd[$n, 1]", "0");
Is(e, "$n", "7");
Is(e, "listadd[getvar[q]+x, 1]", "0");
}
private static void DocDictsPersist()
{
var e = Engine();
Is(e, "setvar[myDict,dictcreate[]]", "D:0");
Is(e, "dictadditem[getvar[myDict],foo,1]", "0");
Is(e, "dictadditem[getvar[myDict],foo,2]", "1"); // overwrote
Is(e, "dictgetitem[getvar[myDict],foo]", "2");
Is(e, "$myDict{foo}", "2");
Is(e, "dictsize[dictcreate[a,b,c,d]]", "2"); // the reference's example
Is(e, "dicthaskey[$myDict,foo]", "1");
// A new dict never takes a stored dict's id (they used to restart at D:0 each time).
string other = e.Evaluate("dictcreate[x,1]");
Check.True(other != "D:0", $"new dict {other} is not D:0");
Is(e, "dictsize[$myDict]", "1");
Is(e, "setvar[cfg, dictcreate[inner, dictcreate[name,Bob]]]; 1", "1");
Is(e, "$cfg{inner}{name}", "Bob");
Is(e, "setvar[copy, dictcopy[$myDict]]; dictadditem[$copy,bar,1]; dictsize[$myDict]", "1");
Is(e, "dictsize[$copy]", "2");
// Unreferenced dicts are swept once there are many; referenced ones (also nested) stay.
for (int i = 0; i < 400; i++) e.Evaluate("dictcreate[t,1]");
e.Evaluate("1");
Is(e, "dictgetitem[$myDict,foo]", "2");
Is(e, "$cfg{inner}{name}", "Bob");
Is(e, "dictsize[$copy]", "2");
Check.True(e.Evaluate("dictgetitem[D:5,t]") == "", "an unreferenced dict was swept");
}
private static void DocLogicAndTypes()
{
var e = Engine();
Is(e, "iif[1,2,3]", "2"); // the reference's example
Is(e, "iif[0,2,3]", "3");
Is(e, "iif[abc,2,3]", "3"); // not a number: the third
Is(e, "iif[``,2,3]", "3");
Is(e, "iif[-1,2,3]", "2");
Is(e, "isfalse[0]", "1"); // the reference's examples
Is(e, "istrue[1]", "1");
Is(e, "isfalse[abc]", "0"); // text is not false (0)...
Is(e, "istrue[abc]", "0"); // ...nor true (1)
Is(e, "istrue[2]", "0");
Is(e, "isfalse[1]", "0");
Is(e, "istrue[3<10]", "1");
Is(e, "getobjectinternaltype[``]", "0"); // 0=none, 1=number, 3=string, 7=object
Is(e, "getobjectinternaltype[5]", "1");
Is(e, "getobjectinternaltype[test]", "3");
Is(e, "getobjectinternaltype[listcreate[]]", "7");
Is(e, "getobjectinternaltype[coordinateparse[`1.2N, 3.4E`]]", "7");
Is(e, "getobjectinternaltype[dictcreate[]]", "7");
Is(e, "getobjectinternaltype[`1|2`]", "3");
}
private static void DocTextArguments()
{
FakeHost.Reset();
const uint kit = 0x60000001, key = 0x60000002, token = 0x60000003, essence = 0x60000004;
FakeHost.Names[kit] = "Healing Kit";
FakeHost.Names[key] = "The Baron's Key";
FakeHost.Names[token] = "High-Stakes Gambling Token";
FakeHost.Names[essence] = "Wisp Essence";
FakeHost.Ints[(kit, 12)] = 5;
var host = FakeHost.Create();
var cache = FakeHost.MakeCache(host, Player, new[] { kit, key, token, essence }, new Dictionary<uint, float>());
var e = Engine(host, playerId: Player, settings: new LegacyUiSettings { EnableCombat = true });
e.SetObjectCache(cache);
// Expressions are evaluated (they used to be searched for as typed).
e.Evaluate("setvar[itemname, Healing Kit]");
Is(e, "wobjectfindininventorybyname[$itemname]", "[WorldObject] 0x60000001: Healing Kit");
Is(e, "wobjectfindininventorybyname[getvar[itemname]]", "[WorldObject] 0x60000001: Healing Kit");
Is(e, "getitemcountininventorybyname[$itemname]", "5");
Is(e, "getitemcountininventorybynamerx[`^`+$itemname+`$`]", "5");
Is(e, "wobjectfindininventorybynamerx[\\(Knight\\|Wisp\\)\\.\\+Essence]", "[WorldObject] 0x60000004: Wisp Essence");
Is(e, "listcount[wobjectfindallinventorybynamerx[getvar[itemname]]]", "1");
// Plain text with punctuation is still taken as typed.
Is(e, "wobjectfindininventorybyname[The Baron's Key]", "[WorldObject] 0x60000002: The Baron's Key");
Is(e, "wobjectfindininventorybyname[High-Stakes Gambling Token]", "[WorldObject] 0x60000003: High-Stakes Gambling Token");
Is(e, "wobjectfindininventorybynamerx[(Essence)]", "[WorldObject] 0x60000004: Wisp Essence");
Is(e, "listcount[wobjectfindallinventorybynamerx[Wis[p]]]", "1"); // a regex that looks like a call
Check.False(FakeHost.Logs.Exists(l => l.Contains("unknown expression function 'wis'")), "and isn't logged as an unknown function");
Is(e, "getitemcountininventorybyname[Healing Kit]", "5");
// Meta state and setting names, and the cstrf format.
e.Evaluate("setvar[next, Turn In]");
Is(e, "vtsetmetastate[getvar[next]]", "1");
Is(e, "vtgetmetastate[]", "Turn In");
Is(e, "vtsetmetastate[Hunt - Phase 2]", "1"); // typed text with a '-'
Is(e, "vtgetmetastate[]", "Hunt - Phase 2");
e.Evaluate("setvar[opt, EnableCombat]");
Is(e, "vtgetsetting[$opt]", "1");
Is(e, "vtsetsetting[$opt, 0]", "1");
Is(e, "vtgetsetting[EnableCombat]", "0");
e.Evaluate("setvar[fmt, N3]");
Is(e, "cstrf[3.14159,$fmt]", "3.142");
Is(e, "cstrf[3.14159,`N3`]", "3.142"); // the reference's example
}
private static void DocLiveState()
{
FakeHost.Reset();
const uint north = 0x80000021, east = 0x80000022, near = 0x80000023;
FakeHost.PlayerPose = (0xA9B4001Cu, 96f, 96f, 0f);
FakeHost.Positions[north] = (0xA9B50001u, 96f, 10f, 0f); // the landblock to the north, low y
FakeHost.Positions[east] = (0xAAB40001u, 10f, 96f, 0f); // the landblock to the east, low x
FakeHost.Positions[near] = (0xA9B4001Cu, 96f, 150f, 0f);
FakeHost.KnownSpells.Add(2931);
FakeHost.Spellbook.AddRange(new uint[] { 2931, 1 });
var e = Engine(FakeHost.Create(), playerId: Player);
// "heading in degrees (0-360 clockwise, 0 is north) from your player to the target"
Is(e, "getheadingto[0x80000021]", "0"); // was 180: the local y alone is south
Is(e, "getheadingto[0x80000022]", "90"); // was 270
Is(e, "getheadingto[0x80000023]", "0");
Is(e, "getheadingto[0]", "0");
// "2 if the attempt is impossible": a spell the character doesn't know.
Is(e, "actiontrycastbyid[1]", "2");
Is(e, "actiontrycastbyidontarget[1, 0x80000023]", "2");
Check.Eq(FakeHost.Casts.Count, 0, "nothing cast for an unknown spell");
Is(e, "actiontrycastbyid[2931]", "0"); // known: not in magic mode yet, one step taken
Is(e, "getknownspells[]", "[2931,1]");
Is(e, "listcontains[getknownspells[], 2931]", "1");
Is(Engine(), "getknownspells[]", "[]"); // no host
}
private static void VitaeWithoutHost()
{
Check.Eq(Engine().Evaluate("vitae[]"), "0", "no host: no known penalty");

View file

@ -194,7 +194,9 @@ internal static class HealLatencyTests
Check.Eq(FakeHost.Casts.Count, 2, "...but Stamina to Mana, so the mana comes back");
Check.Eq(r.B.BuffingLabel, "Restoring mana", "and the slot reads Restoring mana");
r.B.OnChatWindowText("You don't have enough Mana to cast this spell.", 0);
Check.True(r.Logged("not enough mana; resting the family 15s"), "a non-heal still rests 15 s");
// Stamina to Mana is a vital too (the mana reserve, 2026-10-11): 2 s, not the 15 s a buff rests.
Check.Eq(FakeHost.Logs.Count(l => l.Contains("not enough mana; resting the family 2s", StringComparison.Ordinal)), 2,
"Stamina to Mana rests 2 s as well, not 15 s");
System.Threading.Thread.Sleep(2100);
r.V.CurrentMana = 60;
Check.True(r.B.CheckVitals(), "2 s later, mana back");

View file

@ -114,11 +114,11 @@ internal static class InstallPathsTests
Check.Eq(RynthCore.Plugin.RynthAi.Loot.LootEditorBridge.LootFolder, @"C:\Games\RynthSuite\RynthAi\LootProfiles", "loot profiles");
Check.Eq(RynthCore.Plugin.RynthAi.Vendor.AutoVendorManager.MainProfileDir, @"C:\Games\RynthSuite\RynthAi\AutoVendor", "AutoVendor");
Check.Eq(RynthCore.Plugin.RynthAi.Trade.AutoTradeManager.MainProfileDir, @"C:\Games\RynthSuite\RynthAi\AutoTrade", "AutoTrade");
Check.Eq(RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder, @"C:\Games\RynthSuite\RynthAi\CreatureData", "creature data");
Check.Eq(RynthCore.Plugin.RynthAi.CreatureData.CreatureWeakness.WeaknessFile, @"C:\Games\RynthSuite\RynthAi\Data\creature_weakness.json", "weakness file");
Check.Eq(PrivateStatic(typeof(RynthCore.Plugin.RynthAi.RadarWallRenderer), "ExploredDir"), @"C:\Games\RynthSuite\RynthAi\ExploredDungeons", "explored dungeons");
// The tests point the store at their scratch folder (Program.Main); this is its value before that.
Check.Eq(Program.LiveHazardFolder, @"C:\Games\RynthSuite\RynthAi\DungeonHazards", "dungeon hazards");
Check.Eq(Program.LiveCreatureFolder, @"C:\Games\RynthSuite\RynthAi\CreatureData", "creature data");
}
private static string? PrivateStatic(Type type, string field)

View file

@ -0,0 +1,273 @@
using System;
using System.Linq;
using System.Reflection;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The mana reserve (2026-10-11). A void mage, Life Magic 304, at 1/383 mana and 289/383 stamina
// against Rampagers: "You don't have enough Mana to cast this spell", and RynthAi kept casting
// Corruption instead of Stamina to Mana. Combat had drained mana under what Stamina to Mana costs,
// its refusal parked it 15 s, and with no mana potion nothing held the arbiter for vitals. Now a
// caster keeps ManaReserveFactor x Stamina to Mana's cost: under it Stamina to Mana goes first and
// combat holds its casts; under the cost, the highest level it can pay for goes, or mana
// regenerates while attacks wait, and a mana refusal rests the vital only briefly.
internal static class ManaReserveTests
{
private const uint Player = 0x50000B21;
private const uint STypeLife = 33;
private const uint STypeVoid = 43;
private const int Target = 0x7000A021;
private const string NotEnoughMana = "You don't have enough Mana to cast this spell.";
public static void Register(Runner r)
{
r.Add("mana reserve: under 1.5x Stamina to Mana's cost, Stamina to Mana is chosen over an attack", ReserveChoosesStaminaToMana);
r.Add("mana reserve: under Stamina to Mana's cost, no attack spam and no 15 s park on 'not enough Mana'", StarvedNoSpamNoPark);
r.Add("mana reserve: as mana regenerates, the level it can pay for goes, then attacks resume", RecoversAsManaRegenerates);
r.Add("mana reserve: stamina too low for Stamina to Mana - stamina is refilled first", StaminaFirst);
r.Add("mana reserve: combat holds an attack it can't pay for, and casts once mana is back", CombatHoldsCast);
r.Add("mana reserve: a melee fighter's attacks aren't held; Get Mana At off means no reserve", MeleeAndOff);
r.Add("mana reserve: the dat's BaseMana is read (when this PC has a portal.dat)", DatBaseMana);
}
private static int Family(string name) => SpellTableStub.GetById(SpellTable.Named(name).First().Id)!.Family;
private static int Id(string name) => SpellTable.Named(name).First().Id;
private static string NameOf(int id) => SpellTableStub.GetById(id)?.Name ?? $"#{id}";
private static int CostByLevel(int id) => (SpellTableStub.GetById(id)?.Level ?? 0) * 10;
private static int FamilyOfCast(int i) => SpellTableStub.GetById(FakeHost.Casts[i].SpellId)?.Family ?? 0;
private sealed class Rig
{
public readonly BuffManager B;
public readonly LegacyUiSettings S;
public readonly PlayerVitalsCache V;
public bool InCombat = true;
public Rig(uint mana, uint stamina = 289, int getManaAt = 20, int combatMode = 0)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.CombatModeValue = combatMode == 0 ? CombatMode.Magic : combatMode;
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (304, 2);
FakeHost.Skills[(Player, STypeVoid)] = (400, 3);
BuffManager.ManaCostOverride = CostByLevel; // level x 10: I 10 ... VII 70, VIII 80
var host = FakeHost.Create();
S = new LegacyUiSettings
{
IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
GetManaAt = getManaAt, TopOffMana = getManaAt, RestamAt = 0, TopOffStam = 0, UsePotions = false,
EnableBuffing = false,
};
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, S);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
V = new PlayerVitalsCache { MaxHealth = 400, CurrentHealth = 400, MaxStamina = 383, CurrentStamina = stamina, MaxMana = 383, CurrentMana = mana };
B = new BuffManager(host, S, sm, V);
B.SetCharacterSkills(skills);
B.InCombatOverride = () => InCombat;
}
public int LogCount(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal));
}
private static BotActivity Arbiter(BuffManager b)
{
var inputs = new ArbiterInputs(true, b.PendingSpellId != 0 || b.WantsVitalRecharge, wantCombat: true,
wantLooting: false, wantSalvaging: false, wantNav: true, combatEngaged: true);
return ActivityArbiter.Decide(in inputs);
}
private static void ReserveChoosesStaminaToMana()
{
// Over Get Mana At 20% (77 of 383), but under 1.5x the top Stamina to Mana's cost.
var r = new Rig(mana: 300);
int corruption = Id("Corruption VII");
int reserve = r.B.ManaReserve();
Check.True(reserve > 77, $"the reserve ({reserve}) is over Get Mana At's 77 points");
r.V.CurrentMana = (uint)(reserve - 5);
Check.True(r.V.ManaPct >= 20, $"{r.V.CurrentMana}/383 is over Get Mana At");
Check.True(r.B.WantsManaNow(), "under the reserve, in combat: vitals want the tick");
Check.True(r.B.WantsVitalRecharge, "...which is what the arbiter reads");
Check.Eq(Arbiter(r.B), BotActivity.Buffing, "the arbiter gives vitals the tick over combat");
string? hold = r.B.OffensiveCastHold(corruption);
Check.True(hold != null && hold.Contains("reserve"), $"combat's Corruption VII waits ({hold})");
Check.True(r.B.CheckVitals(), "vitals act");
Check.Eq(FakeHost.Casts.Count, 1, "one cast");
Check.Eq(FamilyOfCast(0), Family("Stamina to Mana Self I"), $"it is Stamina to Mana ({NameOf(FakeHost.Casts[0].SpellId)})");
int cost = CostByLevel(FakeHost.Casts[0].SpellId);
Check.Eq(r.B.ManaReserve(), (int)Math.Ceiling(cost * BuffManager.ManaReserveFactor), "the reserve is 1.5x that level's cost");
// Plenty of mana: nothing held.
r.V.CurrentMana = 300;
Check.False(r.B.WantsManaNow(), "300/383: no hold");
Check.Null(r.B.OffensiveCastHold(corruption), "300/383: combat casts");
}
private static void StarvedNoSpamNoPark()
{
// The report: 1/383 mana. No Stamina to Mana level costs 1 or less.
var r = new Rig(mana: 1);
int corruption = Id("Corruption VII");
for (int i = 0; i < 5; i++)
Check.True(r.B.CheckVitals(), $"check {i}: vitals hold the tick (mana regenerating)");
Check.Eq(FakeHost.Casts.Count, 0, "no Stamina to Mana sent that the server would refuse");
Check.Eq(r.LogCount("is under"), 1, "logged once");
Check.True(r.LogCount("attacks wait, regenerating") == 1, "the log says attacks wait");
Check.True(r.B.WantsManaNow(), "vitals keep the tick while it regenerates");
Check.Eq(Arbiter(r.B), BotActivity.Buffing, "combat doesn't get it");
string? hold = r.B.OffensiveCastHold(corruption);
Check.True(hold != null && hold.Contains("Corruption VII's cost"), $"an attack under its own cost waits ({hold})");
Check.Eq(r.B.BuffingLabel, BuffManager.LabelMana, "the slot reads Restoring mana");
// Costs unknown (no dat): Stamina to Mana is tried; refused for mana it rests 2 s, not 15 s,
// and mana regenerates meanwhile with attacks still held.
var u = new Rig(mana: 50);
BuffManager.ManaCostOverride = _ => 0;
Check.True(u.B.CheckVitals(), "50/383 under Get Mana At: Stamina to Mana goes");
Check.Eq(FakeHost.Casts.Count, 1, "one cast");
u.B.OnChatWindowText(NotEnoughMana, 0);
Check.True(FakeHost.Logs.Any(l => l.Contains("not enough mana; resting the family 2s", StringComparison.Ordinal)), "rested 2 s, not 15 s");
Check.True(u.B.CheckVitals(), "inside the rest: vitals still hold (regenerating)");
Check.Eq(FakeHost.Casts.Count, 1, "no re-cast inside the rest");
Check.True(u.B.WantsManaNow(), "the short rest doesn't let combat in");
System.Threading.Thread.Sleep(2100);
u.V.CurrentMana = 70;
Check.True(u.B.CheckVitals(), "2 s later");
Check.Eq(FakeHost.Casts.Count, 2, "Stamina to Mana is cast again");
Check.Eq(FamilyOfCast(1), Family("Stamina to Mana Self I"), "Stamina to Mana");
}
private static void RecoversAsManaRegenerates()
{
var r = new Rig(mana: 1);
Check.True(r.B.CheckVitals(), "1 mana: waiting");
Check.Eq(FakeHost.Casts.Count, 0, "nothing cast");
r.V.CurrentMana = 15; // pays for level I (10), nothing higher
Check.True(r.B.CheckVitals(), "15 mana");
Check.Eq(FakeHost.Casts.Count, 1, "a Stamina to Mana goes");
Check.True(CostByLevel(FakeHost.Casts[0].SpellId) <= 15, $"the level it can pay for ({NameOf(FakeHost.Casts[0].SpellId)})");
r.V.CurrentMana = (uint)(r.B.ManaReserve() - 1); // the top level is payable again; still under the reserve
Check.True(r.B.CheckVitals(), "just under the reserve");
Check.Eq(FakeHost.Casts.Count, 2, "Stamina to Mana again");
int top = r.B.ManaReserve();
Check.True(CostByLevel(FakeHost.Casts[1].SpellId) * BuffManager.ManaReserveFactor >= top - 1,
$"the top level this time ({NameOf(FakeHost.Casts[1].SpellId)})");
r.V.CurrentMana = 300;
Check.False(r.B.WantsManaNow(), "300 mana: vitals let go");
Check.Null(r.B.OffensiveCastHold(Id("Corruption VII")), "attacks resume");
Check.False(r.B.CheckVitals(), "nothing for vitals to do");
}
private static void StaminaFirst()
{
// 50 mana (under Get Mana At 20% = 77) and 10% stamina: Stamina to Mana can't go (stamina
// under 15%), so Revitalize first - at a level 50 mana pays for.
var r = new Rig(mana: 50, stamina: 38);
Check.True(r.B.CheckVitals(), "vitals act");
Check.Eq(FakeHost.Casts.Count, 1, "one cast");
Check.Eq(FamilyOfCast(0), Family("Revitalize Self I"), $"Revitalize ({NameOf(FakeHost.Casts[0].SpellId)})");
Check.True(CostByLevel(FakeHost.Casts[0].SpellId) <= 50, "a level the mana pays for");
Check.Eq(r.B.BuffingLabel, BuffManager.LabelStamina, "Restoring stamina");
Check.False(r.B.WantsManaNow(), "with no stamina kit or potion, attacks aren't held for mana (Revitalize costs mana too)");
// Re-stam At off and Stamina to Mana unaffordable doesn't matter: stamina goes first all the same.
var off = new Rig(mana: 50, stamina: 38);
off.S.RestamAt = 0;
Check.True(off.B.CheckVitals(), "Re-stam At 0: still refilled for Stamina to Mana");
Check.Eq(FamilyOfCast(0), Family("Revitalize Self I"), "Revitalize");
}
private static void CombatHoldsCast()
{
FakeHost.Reset();
foreach (string n in new[] { "Flame Bolt VI" })
foreach (var row in SpellTable.Named(n)) FakeHost.Spellbook.Add((uint)row.Id);
var s = new LegacyUiSettings { IsMacroRunning = true, GetManaAt = 20, TopOffMana = 20, UsePotions = false, RingRange = 0 };
s.MinSkillLevelTier1 = 0; s.MinSkillLevelTier2 = 0; s.MinSkillLevelTier3 = 0; s.MinSkillLevelTier4 = 0;
s.MinSkillLevelTier5 = 0; s.MinSkillLevelTier6 = 0; s.MinSkillLevelTier7 = 10000; s.MinSkillLevelTier8 = 10000;
s.MonsterRules.Add(new MonsterRule { Name = "Rampager", DamageType = "Fire", UseBolt = true });
FakeHost.PlayerPose = (0x0101001Bu, 0f, 0f, 0f);
FakeHost.Positions[Player] = FakeHost.PlayerPose;
FakeHost.Positions[(uint)Target] = (0x0101001Bu, 0f, 10f, 0f);
FakeHost.Names[(uint)Target] = "Rampager";
FakeHost.CombatModeValue = CombatMode.Magic;
BuffManager.ManaCostOverride = CostByLevel;
var host = FakeHost.Create(Player);
var cache = FakeHost.MakeCache(host, Player, new[] { (uint)Target });
var c = new CombatManager(host, s, cache);
c.SetPlayerId(Player);
var sm = new SpellManager(host, s);
sm.InitializeNatively();
sm.RefreshKnownSpells();
c.SetSpellManager(sm);
var v = new PlayerVitalsCache { MaxHealth = 400, CurrentHealth = 400, MaxStamina = 383, CurrentStamina = 289, MaxMana = 383, CurrentMana = 1 };
var b = new BuffManager(host, s, sm, v);
b.InCombatOverride = () => true;
c.ManaReserveHold = id => b.OffensiveCastHold(id);
c.activeTargetId = Target;
var target = new WorldObject(Target, "Rampager");
MethodInfo attack = typeof(CombatManager).GetMethod("AttackWithMagic", BindingFlags.NonPublic | BindingFlags.Instance)!;
FieldInfo held = typeof(CombatManager).GetField("_manaCastHeld", BindingFlags.NonPublic | BindingFlags.Instance)!;
for (int i = 0; i < 3; i++) attack.Invoke(c, new object[] { target });
Check.Eq(FakeHost.Casts.Count, 0, "1 mana: Flame Bolt VI (60) isn't sent");
Check.True((bool)held.GetValue(c)!, "held for mana");
Check.Eq(c.LastCombatSkipReason, "mana-reserve", "the skip reason says so");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[CombatCast] attacks wait: mana 1/383 is under Flame Bolt VI's cost (60)", StringComparison.Ordinal)), 1, "logged once");
v.CurrentMana = 300;
attack.Invoke(c, new object[] { target });
Check.Eq(FakeHost.Casts.Count, 1, "mana back: the bolt goes");
Check.Eq(NameOf(FakeHost.Casts[0].SpellId), "Flame Bolt VI", "Flame Bolt VI");
Check.False((bool)held.GetValue(c)!, "not held");
Check.True(FakeHost.Logs.Any(l => l.Contains("attacks resume", StringComparison.Ordinal)), "and says attacks resume");
}
private static void MeleeAndOff()
{
// A melee fighter (no combat manager: the stance decides) at low mana: no reserve, no hold.
var melee = new Rig(mana: 1, combatMode: CombatMode.Melee);
Check.False(melee.B.WantsManaNow(), "melee: vitals don't hold the fight for mana");
melee.V.CurrentMana = 85; // 22%: over Get Mana At 20%, under a caster's reserve (90)
Check.False(melee.B.ManaUnderLine(true, out int line), $"melee: only Get Mana At ({line})");
// Get Mana At 0 (mana recharge off in combat): no reserve, nothing held.
var off = new Rig(mana: 100, getManaAt: 0);
Check.False(off.B.WantsManaNow(), "Get Mana At 0: no hold");
Check.Null(off.B.OffensiveCastHold(Id("Corruption VII")), "Get Mana At 0: combat casts (it can pay)");
Check.False(off.B.CheckVitals(), "and vitals do nothing for mana");
}
private static void DatBaseMana()
{
var saved = BuffManager.ManaCostOverride;
BuffManager.ManaCostOverride = null;
try
{
int s2m1 = Id("Stamina to Mana Self I");
if (!ComponentDatabase.TryGetSpellBaseMana(s2m1, out int m1))
{
Console.WriteLine(" (no portal.dat on this PC: BaseMana not checked)");
return;
}
string[] names = { "Stamina to Mana Self I", "Stamina to Mana Self IV", "Stamina to Mana Self VI",
"Revitalize Self VI", "Heal Self VI", "Corruption VII", "Flame Bolt VI" };
string line = string.Join(", ", names.Select(n => $"{n} {BuffManager.SpellManaCost(Id(n))}"));
Console.WriteLine(" dat BaseMana: " + line);
Check.True(m1 > 0, $"Stamina to Mana Self I costs something ({m1})");
Check.True(BuffManager.SpellManaCost(Id("Stamina to Mana Self VI")) > m1, "level VI costs more than level I");
}
finally { BuffManager.ManaCostOverride = saved; }
}
}

View file

@ -62,6 +62,8 @@ internal static class MetaTests
r.Add("meta edit: a saved rule keeps CallState's return state and ChatCapture's colours", EditKeepsHiddenFields);
r.Add("meta edit: the editor's Set current text matches the landblock / landcell", SetCurrentMatches);
r.Add("meta edit: a new state's Never -> None rule keeps it through a save and reload", NewStateSurvivesReload);
r.Add("meta: rule names survive a save and reload (.af \"~~ @name\")", RuleNamesRoundTrip);
r.Add("meta edit: an update without a name (an engine without rule names) keeps the rule's name", UpdateKeepsName);
}
private static void SetCurrentMatches()
@ -109,6 +111,71 @@ internal static class MetaTests
Check.False(rig.Has("x"), "its Never rule never fires");
}
private static void RuleNamesRoundTrip()
{
var named = Rule("Hunt", C.Always, "", A.ChatCommand, "/vt start");
named.Name = "Start hunting";
var both = Rule("Hunt", C.Never, "", A.None, "");
both.Name = " Parked " + "\r\n" + " rule "; // trimmed, kept on one line
both.Enabled = false;
var plain = Rule("Hunt", C.Always, "", A.None, "");
var rules = new List<MetaRule> { named, both, plain };
string text = AfFileWriter.SaveToString(rules, new Dictionary<string, List<string>>());
Check.True(text.Contains("~~ @name Start hunting"), "written as a ~~ @name line");
var back = AfFileParser.LoadFromText(text);
Check.Eq(back.Rules.Count, 3, "every rule back");
Check.Eq(back.Warnings.Count, 0, "no warnings");
if (back.Rules.Count == 3)
{
Check.Eq(back.Rules[0].Name, "Start hunting", "the name");
Check.Eq(back.Rules[1].Name, "Parked rule", "one line, trimmed");
Check.False(back.Rules[1].Enabled, "a name and @disabled together");
Check.Eq(back.Rules[2].Name, "", "a name belongs to one rule only");
}
// Hand-written: either marker order; "@names" and an empty "@name" are just comments.
var hand = AfFileParser.LoadFromText(string.Join("\n", new[]
{
"STATE: {Default} ~~ {",
"\t~~ @disabled",
"\t~~ @name Second",
"\tIF:\tAlways",
"\t\tDO:\tNone",
"\t~~ @names are just a comment",
"\tIF:\tNever",
"\t\tDO:\tNone",
"\t~~ @name",
"\tIF:\tNever",
"\t\tDO:\tNone",
"~~ }",
}));
Check.Eq(hand.Rules.Count, 3, "three rules");
if (hand.Rules.Count == 3)
{
Check.Eq(hand.Rules[0].Name, "Second", "name after @disabled");
Check.False(hand.Rules[0].Enabled, "still disabled");
Check.Eq(hand.Rules[1].Name, "", "@names is a comment");
Check.Eq(hand.Rules[2].Name, "", "an empty @name is a comment");
}
}
private static void UpdateKeepsName()
{
var rule = Rule("Default", C.Always, "", A.None, "");
rule.Name = "Keep me";
var rules = new List<MetaRule> { rule };
MetaRuleEdits.Replace(rules, 0, Rule("Default", C.Never, "", A.None, ""), keepName: true);
Check.Eq(rules[0].Name, "Keep me", "an engine without names doesn't wipe it");
Check.Eq(rules[0].Condition, C.Never, "the edit applied");
var renamed = Rule("Default", C.Never, "", A.None, "");
renamed.Name = "New name";
MetaRuleEdits.Replace(rules, 0, renamed);
Check.Eq(rules[0].Name, "New name", "a sent name replaces it");
MetaRuleEdits.Replace(rules, 0, Rule("Default", C.Never, "", A.None, ""));
Check.Eq(rules[0].Name, "", "a sent empty name clears it");
}
// ── Panel edits on a running meta (MetaRuleEdits, update_rule; 2026-10-05 autosave) ─────
private static void EditKeepsRunningMeta()
@ -936,6 +1003,21 @@ internal static class MetaTests
RunAction(rig, A.EmbeddedNavRoute, "__rynthai_offline_test_no_such_route__");
Check.Eq(rig.S.CurrentRoute.Points.Count, 0, "unknown route: nothing loaded");
Check.True(FakeHost.Chat.Exists(c => c.Contains("Route missing")), "unknown route reported");
// "Patrol" (the Meta panel's first route choice): the dungeon patrol, as /ra dunnav-patrol.
rig.Ra.Clear();
RunAction(rig, A.EmbeddedNavRoute, "Patrol");
Check.Eq(string.Join("|", rig.Ra), "/ra dunnav-patrol", "Patrol starts the dungeon patrol");
Check.Eq(rig.S.CurrentRoute.Points.Count, 0, "...and loads no route itself");
rig.Ra.Clear();
RunAction(rig, A.EmbeddedNavRoute, "patrol");
Check.Eq(rig.Ra.Count, 1, "any case");
// A meta's own route called Patrol wins.
rig.Ra.Clear();
rig.S.EmbeddedNavs["Patrol"] = once;
RunAction(rig, A.EmbeddedNavRoute, "Patrol");
Check.Eq(rig.Ra.Count, 0, "an embedded route named Patrol is used instead");
Check.Eq(rig.S.CurrentNavPath, "<embedded:Patrol>", "...and loaded");
}
private static void Watchdog()

View file

@ -49,6 +49,7 @@ internal static class WeaponTests
r.Add("slayer: the element follows the chosen weapon", SlayerElement);
r.Add("slayer: read through the host (int 166, float 138, monster int 2), cached by wcid", SlayerFromHost);
r.Add("weapon choice: an unlisted wand is never picked (Damage tab, learned, pack, name)", UnlistedNeverPicked);
r.Add("Items list: a listed item no longer carried is reported missing (pack, hand, unknown)", MissingFromPack);
r.Add("weapon swap: one in flight, confirmed, retry cap, then what's in hand", SwapOneInFlight);
r.Add("weapon swap: no flip-flop between two weapons", SwapNoFlipFlop);
r.Add("weapon swap: a server refusal counts as a failed try", SwapRefused);
@ -666,6 +667,37 @@ internal static class WeaponTests
}
}
private static void MissingFromPack()
{
// 2026-10-11: Drakkon's buff wand left his pack and the Items slot still just said "Wand".
const int InPack = 0x7000A001, InHand = 0x7000A002, Gone = 0x7000A003, Unknown = 0x7000A004;
var known = new Dictionary<int, WorldObject>
{
[InPack] = new WorldObject(InPack, "Silver Wand", AcObjectClass.WandStaffOrb),
[InHand] = new WorldObject(InHand, "Ken", AcObjectClass.MeleeWeapon),
[Gone] = new WorldObject(Gone, "Wand", AcObjectClass.WandStaffOrb), // the client still knows it
};
WorldObject? Look(int id) => known.TryGetValue(id, out var wo) ? wo : null;
var rules = new List<ItemRule>
{
new() { Id = InPack, Name = "Silver Wand" },
new() { Id = InHand, Name = "Ken" },
new() { Id = Gone, Name = "Wand" },
new() { Id = Unknown, Name = "Old Bow" },
new() { Id = 0, Name = "never resolved" },
};
var pack = new[] { known[InPack], new WorldObject(0x7000A0FF, "Pyreal", AcObjectClass.Money) };
var missing = WeaponList.MissingIds(rules, pack, Look, wo => wo.Id == InHand);
Check.True(!missing.Contains(InPack), "in the pack: carried");
Check.True(!missing.Contains(InHand), "wielded (not in the pack list): carried");
Check.True(missing.Contains(Gone), "left the pack, the client still knows it: missing");
Check.True(missing.Contains(Unknown), "the client doesn't know it at all: missing");
Check.Eq(missing.Count, 2, "only those two (id 0 is never reported)");
missing = WeaponList.MissingIds(rules, Array.Empty<WorldObject>(), Look, _ => false);
Check.Eq(missing.Count, 0, "inventory not known yet (empty, logging in): nothing reported missing");
}
private static void UnlistedNeverPicked()
{
var rig = new Rig(1535, "Ethereal Wisp");
@ -683,10 +715,23 @@ internal static class WeaponTests
var cache = FakeHost.MakeCache(FakeHost.Create(), Player, new[] { ListedWand, FireWand, NamedJunk });
WorldObject? Look(int id) => cache[id];
var inv = new[] { cache[unchecked((int)FireWand)]!, cache[unchecked((int)NamedJunk)]! };
int got = WeaponList.FindWand(rig.S.ItemRules, Look, _ => false, inv, allowUnlisted: true, out bool unlisted);
Check.Eq(unchecked((uint)got), ListedWand, "a wand is listed: that one, never the pack's");
var invWithListed = new[] { cache[unchecked((int)ListedWand)]!, cache[unchecked((int)FireWand)]!, cache[unchecked((int)NamedJunk)]! };
int got = WeaponList.FindWand(rig.S.ItemRules, Look, _ => false, invWithListed, allowUnlisted: true, out bool unlisted);
Check.Eq(unchecked((uint)got), ListedWand, "a wand is listed and carried: that one, never another from the pack");
Check.False(unlisted, "not from the pack");
// 2026-10-11: the listed wand left the pack (the client still knows the object). It is
// not returned - the server ignores a wield of it and every buff was parked.
got = WeaponList.FindWand(rig.S.ItemRules, Look, _ => false, inv, allowUnlisted: false, out _);
Check.Eq(got, 0, "listed wand not carried, setting off: no wand (buffs go bare-handed), not the gone one");
got = WeaponList.FindWand(rig.S.ItemRules, Look, _ => false, inv, allowUnlisted: true, out unlisted);
Check.Eq(unchecked((uint)got), FireWand, "listed wand not carried, setting on: a caster from the pack");
got = WeaponList.FindWand(rig.S.ItemRules, Look, wo => wo.Id == unchecked((int)ListedWand), inv, allowUnlisted: false, out _);
Check.Eq(unchecked((uint)got), ListedWand, "a listed wand in hand counts as carried");
var sameName = new WorldObject(0x7000ABCD, cache[unchecked((int)ListedWand)]!.Name, AcObjectClass.WandStaffOrb);
got = WeaponList.FindWand(rig.S.ItemRules, Look, _ => false, new[] { sameName }, allowUnlisted: false, out _);
Check.Eq(got, 0x7000ABCD, "listed wand gone: another of the same name in the pack stands in");
var none = new List<ItemRule>();
got = WeaponList.FindWand(none, Look, _ => false, new[] { cache[unchecked((int)NamedJunk)]! }, allowUnlisted: true, out _);
Check.Eq(got, 0, "no wand listed: a jewel named 'Fire Wand' is never taken (no name match)");