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)");

View file

@ -0,0 +1,500 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthSort.Tests
{
// RynthSort v3: rules with several classes and names (and their migration), the order inside
// packs, the side packs' top-to-bottom order, stacks joined in place, and that auto-sort runs out
// of moves on a fixed inventory instead of moving items back and forth.
internal static partial class Program
{
// ── Rules with several entries ──────────────────────────────────────
private static void MultiRules()
{
var armor = It(1, "Gold Breastplate", ObjectClasses.Armor);
var shirt = It(2, "Flared Shirt", ObjectClasses.Clothing);
var sword = It(3, "Tachi", ObjectClasses.MeleeWeapon);
var shield = It(4, "Kite Shield", ObjectClasses.Armor);
var opal = It(5, "Black Opal", ObjectClasses.Gem);
var gear = SortRule.For(4, new[] { ObjectClasses.Armor, ObjectClasses.Clothing, ObjectClasses.MeleeWeapon });
Check(SortRules.Matches(gear, armor) && SortRules.Matches(gear, shirt) && SortRules.Matches(gear, sword), "one rule, three classes: any of them matches");
Check(!SortRules.Matches(gear, opal), "not the others");
var mixed = SortRule.For(5, new[] { ObjectClasses.Gem }, "Shield", "Pyreal");
Check(SortRules.Matches(mixed, shield) && SortRules.Matches(mixed, opal), "classes and names in one rule: either matches");
var rules = new List<SortRule> { gear, mixed };
Eq(SortRules.RuleFor(rules, shield)?.Pack, 5, "the shield's name beats the armor class");
Eq(SortRules.RuleFor(rules, armor)?.Pack, 4, "other armor by class");
Check(!gear.AddClass(ObjectClasses.Armor) && gear.Classes.Count == 3, "a class is in a rule once");
Check(mixed.AddName(" Mote ") && mixed.HasName("mote") && !mixed.AddName("MOTE") && !mixed.AddName(" "), "names trimmed, once in any case, never blank");
Check(mixed.RemoveName("PYREAL") && !mixed.HasName("Pyreal"), "removed in any case");
Check(SortRule.Clean(new string('x', 80)).Length == SortRule.MaxNameLength, "names cut to 64");
Eq(SortRules.Describe(gear), "Armor, Clothing, Melee Weapon", "described A-Z");
Eq(SortRules.Describe(mixed), "Gem, name has \"Mote\", name has \"Shield\"", "classes first, then names, A-Z");
Eq(SortRules.Describe(new SortRule()), "(empty: add a class or a name)", "an empty rule");
Check(!SortRules.Matches(new SortRule(), opal), "an empty rule matches nothing");
Check(gear.SameAs(SortRule.For(4, new[] { ObjectClasses.MeleeWeapon, ObjectClasses.Armor, ObjectClasses.Clothing })), "same entries in another order: the same rule");
Check(!gear.SameAs(SortRule.For(5, new[] { ObjectClasses.MeleeWeapon, ObjectClasses.Armor, ObjectClasses.Clothing })), "another pack: not the same");
SortRule copy = mixed.Clone();
copy.AddClass(ObjectClasses.Key);
Check(!mixed.HasClass(ObjectClasses.Key) && copy.Uid != mixed.Uid, "a clone is its own rule");
var list = new List<SortRule> { SortRule.ForName("Zircon", 1), new SortRule { Pack = 1 }, SortRule.ForClass(ObjectClasses.Armor, 1), SortRule.ForClass(ObjectClasses.Gem, 1) };
list.Sort(SortRules.CompareForList);
Check(SortRules.Describe(list[0]) == "Armor" && SortRules.Describe(list[1]) == "Gem" && list[2].HasName("Zircon") && list[3].IsEmpty, "listed A-Z under a pack, empty last");
Eq(SortRules.Defaults().Count, 3, "defaults: components, salvage, and gems/stones/keys as one rule");
Check(SortRules.Defaults()[2].Classes.Count == 3, "the third default rule holds three classes");
}
private static void RuleMigration()
{
SortStore st = TempStore("migration");
string own = st.PathFor("S", "Old");
Directory.CreateDirectory(Path.GetDirectoryName(own)!);
// A version 2 file (2026-10-11): one class or name per rule, ids, the fix done.
File.WriteAllText(own, "{\"version\":2,\"rules\":["
+ "{\"on\":true,\"kind\":\"class\",\"class\":12,\"text\":\"\",\"pack\":1,\"packId\":1073741825,\"packNote\":\"Sack - Components\"},"
+ "{\"on\":false,\"kind\":\"name\",\"class\":12,\"text\":\"Ink of\",\"pack\":2,\"packId\":1073741826},"
+ "{\"on\":true,\"kind\":\"name\",\"class\":12,\"text\":\"\",\"pack\":3}],"
+ "\"settings\":{\"auto\":true},\"packsFixed\":true}");
CharacterSortData d = st.Load("S", "Old", out string? problem);
Check(problem == null && d.Rules.Count == 3 && d.PacksFixed, "version 2 loads");
Check(d.Rules[0].Classes.SequenceEqual(new[] { ObjectClasses.SpellComponent }) && d.Rules[0].Names.Count == 0
&& d.Rules[0].PackId == 0x40000001 && d.Rules[0].PackNote == "Sack - Components", "a class rule: one class, its pack kept");
Check(d.Rules[1].Names.SequenceEqual(new[] { "Ink of" }) && d.Rules[1].Classes.Count == 0 && !d.Rules[1].On && d.Rules[1].PackId == 0x40000002,
"a name rule: one name (not its unused class), off stays off");
Check(d.Rules[2].IsEmpty, "a blank name rule matched nothing and still doesn't");
Check(d.Settings.OrderInPacks && !d.Settings.OrderKindFirst, "the order settings at their defaults");
// Saved as version 3, with the old fields too (an older RynthSort reads the first entry).
d.Rules[0].AddClass(ObjectClasses.Salvage);
d.Rules[0].AddName("Taper");
Check(st.Save("S", "Old", d) == null, "saved");
string json = File.ReadAllText(own);
Check(json.Contains("\"version\": 3") && json.Contains("\"classes\"") && json.Contains("\"names\""), "version 3 with lists");
using (var doc = System.Text.Json.JsonDocument.Parse(json))
{
var r0 = doc.RootElement.GetProperty("rules")[0];
Check(r0.GetProperty("kind").GetString() == "class" && r0.GetProperty("class").GetInt32() == ObjectClasses.SpellComponent, "old fields: the first class");
var r2 = doc.RootElement.GetProperty("rules")[2];
Check(r2.GetProperty("kind").GetString() == "name" && r2.GetProperty("text").GetString() == "", "an empty rule reads as a blank name rule to an older RynthSort");
var r1 = doc.RootElement.GetProperty("rules")[1];
Check(r1.GetProperty("kind").GetString() == "name" && r1.GetProperty("text").GetString() == "Ink of", "a name-only rule: its name the old way");
}
CharacterSortData back = st.Load("S", "Old", out problem);
Check(problem == null && back.Rules[0].Classes.Count == 2 && back.Rules[0].HasClass(ObjectClasses.Salvage) && back.Rules[0].HasName("taper"), "version 3 reads back whole");
// Odd lists: non-numbers and bad strings skipped, duplicates once, the old fields ignored when lists are there.
File.WriteAllText(own, "{\"version\":3,\"rules\":[{\"classes\":[11,\"x\",11,-3,13.0],\"names\":[\"Opal\",5,\"opal\",\" \"],\"kind\":\"class\",\"class\":39,\"pack\":2}]}");
CharacterSortData odd = st.Load("S", "Old", out _);
Check(odd.Rules[0].Classes.SequenceEqual(new[] { ObjectClasses.Gem, ObjectClasses.Key }) && odd.Rules[0].Names.SequenceEqual(new[] { "Opal" }), "lists cleaned; old fields ignored");
// The Lua script's rules read the same way (one entry each) and still compare as its own.
SortStore imp = TempStore("migration-lua");
string lua = imp.LuaPathFor("DreamWeave", "Drakkon");
Directory.CreateDirectory(Path.GetDirectoryName(lua)!);
File.WriteAllText(lua, LuaFile);
CharacterSortData fresh = imp.Load("DreamWeave", "Drakkon", out _);
Check(fresh.Rules.All(x => x.Classes.Count == 1 && x.Names.Count == 0) && fresh.Rules[0].SameAs(fresh.LuaRules![0]), "Lua rules: one class each, SameAs their file");
}
// ── Order inside a pack ─────────────────────────────────────────────
private static List<SortItem> Items(params string[] names)
{
var list = new List<SortItem>();
for (int i = 0; i < names.Length; i++) list.Add(It(100 + (uint)i, names[i], ObjectClasses.Misc));
return list;
}
private static string Names(IEnumerable<SortItem> items) => string.Join(",", items.Select(i => i.Name));
/// <summary>Runs NextMove (every item movable) until it stops; the moves it took.</summary>
private static int SortByMoves(List<SortItem> items, bool kindFirst, Dictionary<uint, int>? perItem = null, int limit = 1000)
{
int moves = 0;
while (moves < limit && PackOrder.NextMove(items, kindFirst, _ => true, out SortItem it, out int at))
{
PackOrder.Apply(items, it, at);
moves++;
if (perItem != null) perItem[it.Id] = perItem.TryGetValue(it.Id, out int n) ? n + 1 : 1;
}
return moves;
}
private static bool InOrder(IReadOnlyList<SortItem> items, bool kindFirst)
{
for (int i = 1; i < items.Count; i++)
if (PackOrder.Compare(items[i - 1], items[i], kindFirst) > 0) return false;
return true;
}
private static void InPackOrder()
{
// The order: A-Z any case; like names together; then the stack kind; then the id.
var a = It(5, "black opal", ObjectClasses.Gem, wcid: 2);
var b = It(4, "Black Opal", ObjectClasses.Gem, wcid: 2);
var c2 = It(3, "Black Opal", ObjectClasses.Gem, wcid: 1);
var d = It(9, "Amber", ObjectClasses.Misc);
var list = new List<SortItem> { a, b, c2, d };
list.Sort((x, y) => PackOrder.Compare(x, y, false));
Eq(string.Join(",", list.Select(i => i.Id)), "9,3,4,5", "Amber; then the Black Opals: same name together, by kind, by id");
var armor = It(20, "Zircon Plate", ObjectClasses.Armor);
var gem = It(21, "Agate", ObjectClasses.Gem);
Check(PackOrder.Compare(armor, gem, false) > 0 && PackOrder.Compare(armor, gem, true) < 0, "kind first: Armor before Gem whatever the names");
// One item that arrived at the end: one move puts it in its place.
var items = Items("Amber", "Bone", "Coal", "Dust", "Agate");
Check(PackOrder.NextMove(items, false, _ => true, out SortItem it, out int at) && it.Name == "Agate" && at == 0, "Agate to slot 0");
PackOrder.Apply(items, it, at);
Check(InOrder(items, false) && !PackOrder.NextMove(items, false, _ => true, out _, out _), "then in order: no move");
// One item at the top that belongs at the bottom: one move, not four.
items = Items("Zinc", "Amber", "Bone", "Coal", "Dust");
Eq(SortByMoves(items, false), 1, "Zinc to the end in one move");
Eq(Names(items), "Amber,Bone,Coal,Dust,Zinc", "in order");
// Reversed: n - 1 moves.
items = Items("E", "D", "C", "B", "A");
Eq(SortByMoves(items, false), 4, "reversed five: four moves");
Check(InOrder(items, false), "in order");
// A move "counted without it": moving down past others.
items = Items("B", "A", "C");
Check(PackOrder.NextMove(items, false, _ => true, out it, out at), "a move");
PackOrder.Apply(items, it, at);
Eq(Names(items), "A,B,C", $"{it.Name} to {at}");
// Where an arriving item goes.
items = Items("Amber", "Coal", "Dust");
Eq(PackOrder.InsertAt(items, It(1, "Bone", ObjectClasses.Misc), false), 1, "Bone between Amber and Coal");
Eq(PackOrder.InsertAt(items, It(1, "Zinc", ObjectClasses.Misc), false), 3, "Zinc at the end");
Eq(PackOrder.InsertAt(items, It(1, "Aaa", ObjectClasses.Misc), false), 0, "Aaa first");
Eq(PackOrder.InsertAt(new List<SortItem>(), It(1, "X", ObjectClasses.Misc), false), 0, "an empty pack");
// An item that can't move now isn't picked; another is.
items = Items("C", "B", "A");
Check(PackOrder.NextMove(items, false, x => x.Name != "A", out it, out _) && it.Name != "A", "a blocked item is skipped");
Check(!PackOrder.NextMove(Items("B", "A"), false, x => false, out _, out _), "nothing movable: no move");
Eq(PackOrder.OutOfPlace(Items("Zinc", "Amber", "Bone"), false), 1, "one out of place");
Eq(PackOrder.OutOfPlace(Items("Amber", "Bone"), false), 0, "in order");
Check(!PackOrder.AllNamed(new List<SortItem> { It(1, "", ObjectClasses.Misc) }), "an unnamed item: wait for its name");
// Every order of up to 7 items: in order after at most n - (longest run) moves, each item moved at most twice.
int worstPerItem = 0;
for (int n = 1; n <= 7; n++)
{
foreach (int[] perm in Permutations(n))
{
var p = perm.Select(i => It(100 + (uint)i, ((char)('A' + i)).ToString(), ObjectClasses.Misc)).ToList();
bool[] kept = PackOrder.Kept(PackOrder.Ranks(p, false));
int bound = kept.Count(x => !x);
var per = new Dictionary<uint, int>();
int moves = SortByMoves(p, false, per);
if (!InOrder(p, false) || moves > bound) { Check(false, $"order {string.Join("", perm)}: {moves} moves (bound {bound}), in order {InOrder(p, false)}"); goto done; }
worstPerItem = Math.Max(worstPerItem, per.Values.DefaultIfEmpty(0).Max());
}
}
Check(true, "every order of 1-7 items sorts within n - (longest run) moves");
done:
Check(worstPerItem <= 2, $"no item moved more than twice ({worstPerItem})");
// Bigger packs, shuffled the same way every run.
var rnd = new Random(1234);
for (int round = 0; round < 40; round++)
{
int n = 10 + rnd.Next(93);
var p = Enumerable.Range(0, n).Select(i => It(1000 + (uint)i, "Item " + rnd.Next(60).ToString("D2"), ObjectClasses.Misc, wcid: (uint)rnd.Next(3))).OrderBy(_ => rnd.Next()).ToList();
int bound = PackOrder.OutOfPlace(p, round % 2 == 0);
var per = new Dictionary<uint, int>();
int moves = SortByMoves(p, round % 2 == 0, per);
if (!InOrder(p, round % 2 == 0) || moves > bound || per.Values.DefaultIfEmpty(0).Max() >= SortPlanner.MaxReorders)
{
Check(false, $"round {round}: {n} items, {moves} moves (bound {bound}), most per item {per.Values.DefaultIfEmpty(0).Max()}");
break;
}
}
Check(true, "40 shuffled packs of 10-102 items sort within the bound, under the per-item backstop");
}
private static IEnumerable<int[]> Permutations(int n)
{
var a = Enumerable.Range(0, n).ToArray();
yield return (int[])a.Clone();
while (true)
{
int i = n - 2;
while (i >= 0 && a[i] >= a[i + 1]) i--;
if (i < 0) yield break;
int j = n - 1;
while (a[j] <= a[i]) j--;
(a[i], a[j]) = (a[j], a[i]);
Array.Reverse(a, i + 1, n - i - 1);
yield return (int[])a.Clone();
}
}
private static void SlotOrders()
{
var pack = new SortPack { Id = 0x40000001 };
pack.Items.AddRange(Items("A", "B", "C")); // ids 100, 101, 102 (id order)
Check(pack.ApplyOrder(new uint[] { 102, 100, 101 }, 3) && pack.OrderKnown, "a list naming exactly the items read");
Eq(string.Join(",", pack.Items.Select(i => i.Id)), "102,100,101", "items in slot order");
Check(!pack.ApplyOrder(new uint[] { 102, 100 }, 2) && !pack.OrderKnown, "one short (a move behind): not known");
Check(!pack.ApplyOrder(new uint[] { 102, 100, 999 }, 3) && !pack.OrderKnown, "an id not read: not known");
Check(!pack.ApplyOrder(new uint[] { 102, 102, 100 }, 3) && !pack.OrderKnown, "an id twice: not known");
Eq(pack.Items.Count, 3, "a refused list leaves the items");
Check(pack.ApplyOrder(new uint[] { 100, 101, 102, 7 }, 3), "only the count given is read");
// The side packs, top first; foci in the list are fine.
SortInventory inv = Inv(3); // ids ...01, 02, 03 (id order)
Check(inv.ApplyPackOrder(new uint[] { 0x40000003, 0x40000F01, 0x40000001, 0x40000002 }, 4) && inv.PackOrderKnown, "pack column order");
Eq(string.Join(",", inv.Packs.Select(p => p.Id & 0xF)), "3,1,2", "pack 1 is the top pack");
SortInventory inv2 = Inv(3);
Check(!inv2.ApplyPackOrder(new uint[] { 0x40000003, 0x40000001 }, 2) && !inv2.PackOrderKnown, "a pack missing from the list: not known");
Eq(string.Join(",", inv2.Packs.Select(p => p.Id & 0xF)), "1,2,3", "id order kept");
// A rule's number follows its pack to its new place; the Lua fix still reads id order.
var rule = SortRule.ForClass(ObjectClasses.Gem, 1);
rule.PackId = 0x40000003;
Check(PackFix.Sync(new List<SortRule> { rule }, inv) && rule.Pack == 1, "the top pack is now pack 1");
}
// ── The planner keeping every pack tidy ─────────────────────────────
private static void PlanInPack()
{
var rules = new List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 1) };
// A route into a pack whose order is known names the item's slot there.
SortInventory inv = Inv(1);
inv.Packs[0].Items.AddRange(new[] { It(50, "Agate", ObjectClasses.Gem), It(51, "Opal", ObjectClasses.Gem) });
inv.Packs[0].OrderKnown = true;
inv.Main.Items.Add(It(10, "Jet", ObjectClasses.Gem));
List<SortMove> m = new SortPlanner().Plan(inv, rules, SortScope.All, true, 0, 0, PlanOptions.Full);
Check(m.Count == 1 && m[0].Kind == MoveKind.Route && m[0].Placement == 1, "Jet goes between Agate and Opal");
inv.Packs[0].OrderKnown = false;
m = new SortPlanner().Plan(inv, rules, SortScope.All, true, 0, 0, PlanOptions.Full);
Check(m.Count == 1 && m[0].Placement == -1, "order unknown: the first empty slot");
m = new SortPlanner().Plan(inv, rules, SortScope.All, true, 0, 0);
Check(m.Count == 1 && m[0].Placement == -1, "without the options: as before");
// Nothing to route: stacks first, then order.
inv = Inv(1);
inv.Packs[0].OrderKnown = true;
inv.Packs[0].Items.AddRange(new[]
{
It(60, "Opal", ObjectClasses.Gem, wcid: 7, stack: 3, max: 10),
It(61, "Agate", ObjectClasses.Gem),
It(62, "Opal", ObjectClasses.Gem, wcid: 7, stack: 5, max: 10),
});
var p = new SortPlanner();
m = p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full);
Check(m.Count >= 1 && m[0].Kind == MoveKind.Stack && m[0].Item.Id == 60 && m[0].MergeInto == 62 && m[0].Dest.Id == inv.Packs[0].Id,
"the smaller Opal stack joins the larger, in its pack");
Check(m.Count == 1, "one tidy move per pack per pass");
inv.Packs[0].Items.RemoveAt(0);
inv.Packs[0].Items[1].Stack = 8;
m = p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full);
Check(m.Count == 0, "Agate, Opal: in order, one stack: nothing");
inv.Packs[0].Items.Reverse();
m = p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full);
Check(m.Count == 1 && m[0].Kind == MoveKind.Reorder && m[0].InPlace && m[0].Placement >= 0, "out of order: a reorder in place");
Eq(p.View.Packs[0].OutOfPlace, 1, "the view counts it");
Check(p.View.Ordering && p.View.Packs[0].OrderKnown, "the view knows ordering is on");
// Not without the options, not for Main or Unpack, not for an unknown order, not with an unnamed item.
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000).Count, 0, "no options: no tidying");
Eq(p.Plan(inv, rules, SortScope.Main, false, 0, 5000, PlanOptions.Full).Count, 0, "Main: routes only");
inv.Packs[0].OrderKnown = false;
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full).Count, 0, "order unknown: not reordered");
inv.Packs[0].OrderKnown = true;
inv.Packs[0].Items.Add(It(70, "", ObjectClasses.Gem));
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full).Count, 0, "an unnamed item: wait");
inv.Packs[0].Items.RemoveAt(2);
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000, new PlanOptions { Order = false, Merge = true }).Count, 0, "ordering off: no reorder");
// A route waits for nothing in place: routes first.
inv.Main.Items.Add(It(11, "Zircon", ObjectClasses.Gem));
m = p.Plan(inv, rules, SortScope.All, true, 0, 0, PlanOptions.Full);
Check(m.Count == 1 && m[0].Kind == MoveKind.Route, "a route goes before any tidying");
// The main pack is put in order only once nothing in it is new.
inv = Inv(0);
inv.Main.OrderKnown = true;
inv.Main.Items.AddRange(new[] { It(80, "Zinc", ObjectClasses.Misc), It(81, "Amber", ObjectClasses.Misc) });
p = new SortPlanner();
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full).Count, 0, "new items settling in the main pack: not yet");
m = p.Plan(inv, rules, SortScope.All, false, 5000, 5000, PlanOptions.Full);
Check(m.Count == 1 && m[0].Kind == MoveKind.Reorder && m[0].DestIndex == 0, "settled: the main pack is put in order");
Check(m[0].Done == "put in order in main pack", "logged as such");
// The backstop: an item put in order too often lately isn't again until the window passes.
for (int i = 0; i < SortPlanner.MaxReorders; i++) p.NoteReorder(80, 6000 + i);
Check(p.ReorderLimited(80, 7000), "limited after too many");
m = p.Plan(inv, rules, SortScope.All, false, 7000, 5000, PlanOptions.Full);
Check(m.All(x => x.Item.Id != 80), "not moved again");
Check(!p.ReorderLimited(80, 6000 + SortPlanner.ReorderWindowMs), "the window passes");
}
private static void MoveAnswersInPlace()
{
var item = It(10, "Opal", ObjectClasses.Gem, stack: 5);
var pack = new SortPack { Id = 0x40000001 };
var reorder = new MoveInFlight { Move = new SortMove(item, pack, 1, 0, 2, MoveKind.Reorder), SentMs = 1000, ErrorSeqAtSend = 7, StackAtSend = 5 };
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = pack.Id, Slot = 0, ErrorSeq = 7 }, 1500), MoveOutcome.Pending,
"in its pack but not at its slot yet: still waiting (its container says nothing)");
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = pack.Id, Slot = 2, ErrorSeq = 7 }, 1500), MoveOutcome.Done, "at its slot");
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = Me, Slot = 0, ErrorSeq = 7 }, 1500), MoveOutcome.Done, "moved away by someone: stop waiting");
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = pack.Id, Slot = -1, ErrorSeq = 7 }, 1000 + MoveTracker.TimeoutMs), MoveOutcome.TimedOut, "no answer");
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = pack.Id, Slot = 0, ErrorSeq = 8, ErrorEventType = 0xA0, ErrorObject = 10 }, 1500),
MoveOutcome.Refused, "refused");
var join = new MoveInFlight { Move = new SortMove(item, pack, 1, 50, -1, MoveKind.Stack), SentMs = 1000, ErrorSeqAtSend = 7, StackAtSend = 5 };
Eq(MoveTracker.Observe(join, new MoveObservation { Exists = true, Container = pack.Id, Stack = 5, ErrorSeq = 7 }, 1500), MoveOutcome.Pending, "a join: still whole");
Eq(MoveTracker.Observe(join, new MoveObservation { Exists = true, Container = pack.Id, Stack = 2, ErrorSeq = 7 }, 1500), MoveOutcome.Done, "part of it joined");
Eq(MoveTracker.Observe(join, new MoveObservation { Exists = false }, 1500), MoveOutcome.Done, "all of it joined");
}
// ── Convergence ─────────────────────────────────────────────────────
/// <summary>A messy character: loot in the main pack, items in the wrong packs, packs out of order, split stacks.</summary>
private static SortInventory Messy()
{
SortInventory inv = Inv(3, cap: 24);
foreach (SortPack p in inv.Packs) p.OrderKnown = true;
inv.Main.OrderKnown = true;
uint id = 1000;
SortItem Add(SortPack p, string name, int cls, uint wcid = 0, int stack = 1, int max = 1)
{
var it = It(id++, name, cls, wcid, stack, max);
p.Items.Add(it);
return it;
}
// Main pack: loot of every kind, and things no rule wants.
Add(inv.Main, "Lead Scarab", ObjectClasses.SpellComponent, 691, 3, 100);
Add(inv.Main, "Salvaged Iron", ObjectClasses.Salvage);
Add(inv.Main, "Black Opal", ObjectClasses.Gem, 2401, 1, 1);
Add(inv.Main, "Zircon Plate", ObjectClasses.Armor);
Add(inv.Main, "Ashcoal", ObjectClasses.Misc);
Add(inv.Main, "Healing Kit", ObjectClasses.HealingKit, 628, 1, 1);
Add(inv.Main, "Prismatic Taper", ObjectClasses.SpellComponent, 20631, 40, 100);
Add(inv.Main, "Amber Ring", ObjectClasses.Jewelry);
// Pack 1 (components): out of order, split stacks, a gem that belongs in pack 3.
Add(inv.Packs[0], "Prismatic Taper", ObjectClasses.SpellComponent, 20631, 70, 100);
Add(inv.Packs[0], "Hyssop", ObjectClasses.SpellComponent, 650, 5, 100);
Add(inv.Packs[0], "Agate", ObjectClasses.Gem, 2394, 1, 1);
Add(inv.Packs[0], "Prismatic Taper", ObjectClasses.SpellComponent, 20631, 90, 100);
Add(inv.Packs[0], "Copper Scarab", ObjectClasses.SpellComponent, 690, 1, 100);
Add(inv.Packs[0], "Lead Scarab", ObjectClasses.SpellComponent, 691, 99, 100);
Add(inv.Packs[0], "Birch", ObjectClasses.SpellComponent, 660, 10, 100);
// Pack 2 (salvage): reversed.
foreach (string s in new[] { "Salvaged Steel", "Salvaged Granite", "Salvaged Gold", "Salvaged Ebony", "Salvaged Copper" })
Add(inv.Packs[1], s, ObjectClasses.Salvage);
// Pack 3 (gems, stones, keys): a component that belongs in pack 1, and stray misc.
Add(inv.Packs[2], "Mana Stone", ObjectClasses.ManaStone);
Add(inv.Packs[2], "Legendary Key", ObjectClasses.Key);
Add(inv.Packs[2], "Gold Scarab", ObjectClasses.SpellComponent, 693, 2, 100);
Add(inv.Packs[2], "Pyreal Mote", ObjectClasses.Misc);
Add(inv.Packs[2], "Diamond", ObjectClasses.Gem);
return inv;
}
private static void Converges()
{
foreach (bool kindFirst in new[] { false, true })
foreach (SortScope scope in new[] { SortScope.All, SortScope.Clean })
{
string what = $"{scope}{(kindFirst ? ", kind first" : "")}";
SortInventory inv = Messy();
List<SortRule> rules = SortRules.Defaults();
var opt = PlanOptions.Full;
opt.KindFirst = kindFirst;
var planner = new SortPlanner();
var seen = new HashSet<string>();
int passes = 0, moved = 0;
bool repeated = false;
// The planner on the same inventory, each pass's first move done as the server does it.
for (; passes < 500; passes++)
{
List<SortMove> moves = planner.Plan(inv, rules, scope, false, 10_000 + passes, 0, opt);
if (moves.Count == 0) break;
SortMove m = moves[0];
string state = Snapshot(inv) + "|" + m.Item.Id + ">" + m.Dest.Id + "@" + m.Placement + "+" + m.MergeInto;
if (!seen.Add(state)) repeated = true;
ServerApply(inv, m);
if (m.Kind == MoveKind.Reorder) planner.NoteReorder(m.Item.Id, 10_000 + passes);
moved++;
}
Console.WriteLine($" {what}: {moved} moves to tidy the messy inventory");
Check(passes < 500, $"{what}: runs out of moves ({moved} moves)");
Check(!repeated, $"{what}: never the same move from the same state twice");
Check(moved <= 60, $"{what}: in a sensible number of moves ({moved})");
for (int i = 0; i < 50; i++)
if (planner.Plan(inv, rules, scope, false, 20_000 + i * 1000, 0, opt).Count != 0) { Check(false, $"{what}: stays still afterwards"); break; }
Check(true, $"{what}: 50 more passes, no move");
// And it is tidy: every item in its pack, packs in order, one stack with room per kind.
foreach (SortItem it in inv.Main.Items.Concat(inv.Packs.SelectMany(p => p.Items)))
{
SortRule? r = SortRules.RuleFor(rules, it);
SortPack where = inv.Packs.Prepend(inv.Main).First(p => p.Items.Contains(it));
if (r != null) Check(where.Id == inv.Packs[r.Pack - 1].Id, $"{what}: {it.Name} in its rule's pack");
else if (scope == SortScope.Clean) Check(where == inv.Main, $"{what}: {it.Name} (no rule) back in the main pack");
}
foreach (SortPack pk in inv.Packs.Prepend(inv.Main))
{
Check(InOrder(pk.Items, kindFirst), $"{what}: {pk.Name} in order ({Names(pk.Items)})");
Check(!SortPlanner.StackJoin(pk, _ => true, out _, out _), $"{what}: {pk.Name} has no two stacks to join");
}
Eq(inv.Packs[0].Items.Count(i => i.Name == "Prismatic Taper"), 2, $"{what}: tapers 200 = 100 + 100");
}
}
private static string Snapshot(SortInventory inv) =>
string.Join(";", inv.Packs.Prepend(inv.Main).Select(p => string.Join(",", p.Items.Select(i => i.Id + "x" + i.Stack))));
private static void ConvergesInTheLoop()
{
// The controller with auto-sort on, against a pretend server that does what ACE does.
var w = new FakeWorld { Inv = Messy(), Can = SortAbilities.All };
SortController c = Controller(auto: true, gapMs: 300, settleSec: 1);
Ticks(c, w, 0, 120_000);
int sent = w.Sent.Count;
if (Environment.GetEnvironmentVariable("RSORT_DEBUG") == "1") foreach (SortMove dm in w.Sent) Console.WriteLine($" {dm.Kind} {dm.Item.Name} x{dm.Item.Stack} -> {dm.DestLabel} @{dm.Placement} +{dm.MergeInto}");
Console.WriteLine($" auto-sort: {sent} moves ({w.Sent.Count(m => m.Kind == MoveKind.Route)} to packs, {w.Sent.Count(m => m.Kind == MoveKind.Stack)} stacks joined, {w.Sent.Count(m => m.Kind == MoveKind.Reorder)} reorders)");
Check(sent > 20 && sent < 80, $"auto-sort tidied everything ({sent} moves)");
Eq(c.Status, "watching", "then watching");
Eq(c.Failed, 0, "no move failed or timed out on the way");
Check(c.Log.Any(l => l.Contains("put in order")), $"reorders logged ({string.Join(" / ", c.Log)})");
Ticks(c, w, 120_000, 600_000);
Eq(w.Sent.Count, sent, "eight minutes more: not one move (nothing moves back and forth)");
foreach (SortPack pk in w.Inv.Packs.Prepend(w.Inv.Main)) Check(InOrder(pk.Items, false), $"{pk.Name} in order");
// New loot: routed into its place after the settle time, nothing else stirs.
w.Inv.Main.Items.Add(It(5000, "Cobalt Scarab", ObjectClasses.SpellComponent, 6000, 1, 100));
Ticks(c, w, 600_000, 700_000);
Eq(w.Sent.Count, sent + 1, "one new item: one move");
SortMove last = w.Sent[^1];
Check(last.Kind == MoveKind.Route && last.Placement >= 0 && last.Dest.Id == w.Inv.Packs[0].Id, "into pack 1 at its slot");
Check(InOrder(w.Inv.Packs[0].Items, false), "pack 1 still in order (it landed in its place)");
// An engine before API v80: items still go to their packs; nothing is reordered.
var old = new FakeWorld { Inv = Messy(), Can = new SortAbilities { Merge = true } };
SortController c2 = Controller(auto: true, settleSec: 0);
Ticks(c2, old, 0, 120_000);
Check(old.Sent.All(m => m.Kind != MoveKind.Reorder && m.Placement == -1), "no slots, no reorders");
Check(old.Inv.Packs[2].Items.All(i => i.ObjectClass != ObjectClasses.SpellComponent), "but the misplaced component left pack 3");
int oldSent = old.Sent.Count;
Ticks(c2, old, 120_000, 300_000);
Eq(old.Sent.Count, oldSent, "and it stays still too");
}
}
}

View file

@ -0,0 +1,343 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Views;
namespace RynthSort.Tests
{
// Rules tied to pack ids, the one-time fix of imported Lua pack numbers, the pack picker's labels
// and spell component classification.
internal static partial class Program
{
private const uint FocusA = 0x40000F01, FocusB = 0x40000F02;
/// <summary>
/// A main pack whose side slots are, in the client's list order: a focus, pack A, a focus,
/// pack B, pack C. The Lua script numbered those 1-5; RynthSort's packs are A, B, C (1-3).
/// </summary>
private static SortInventory WithFoci()
{
var inv = new SortInventory();
inv.Main.Id = Me;
inv.Main.Name = "Main pack";
inv.Main.Capacity = 102;
inv.Slots.Add(new SortSlot(FocusA, 0));
inv.Slots.Add(new SortSlot(0x40000001, 24));
inv.Slots.Add(new SortSlot(FocusB, 0));
inv.Slots.Add(new SortSlot(0x40000002, 24));
inv.Slots.Add(new SortSlot(0x40000003, 24));
foreach (SortSlot s in inv.Slots)
if (s.IsPack) inv.Packs.Add(new SortPack { Id = s.Id, Name = "Pack", Capacity = 24 });
inv.Packs[0].Items.Add(It(500, "Salvaged Iron", ObjectClasses.Salvage));
inv.Packs[1].Items.Add(It(501, "Black Opal", ObjectClasses.Gem));
inv.Packs[2].Items.Add(It(502, "Lead Scarab", ObjectClasses.SpellComponent));
return inv;
}
private static void ClassifyComponents()
{
// ItemType SpellComponents (0x1000) on ACE: the scarabs (Lead 691 .. Platinum 8897, Mana
// Scarab 37155) and Prismatic Taper (20631, weenie type SpellComponent) all have 4096.
foreach (string name in new[] { "Lead Scarab", "Platinum Scarab", "Mana Scarab", "Dark Scarab", "Prismatic Taper", "Red Taper", "Hyssop", "Ink of Formation" })
{
Eq(InventoryReader.ClassifyFrom(0x00001000, 0, name, out bool certain), ObjectClasses.SpellComponent, name);
Check(certain, name + ": certain");
// An item's ordinary bitfield bits (stuck, attackable) don't change it.
Eq(InventoryReader.ClassifyFrom(0x00001000, 0x00000014, name, out _), ObjectClasses.SpellComponent, name + " with bitfield bits");
}
var comps = SortRule.ForClass(ObjectClasses.SpellComponent, 1);
Check(SortRules.Matches(comps, It(1, "Platinum Scarab", InventoryReader.ClassifyFrom(0x1000, 0, "Platinum Scarab", out _))), "a component rule takes scarabs");
Check(SortRules.Matches(comps, It(2, "Prismatic Taper", InventoryReader.ClassifyFrom(0x1000, 0, "Prismatic Taper", out _))), "and tapers");
}
private static void ResolveById()
{
SortInventory inv = Inv(3);
var gem = SortRule.ForClass(ObjectClasses.Gem, 1);
gem.PackId = 0x40000003;
Eq(SortRules.Resolve(gem, inv, out bool fell), 3, "the pack its id names, not its number");
Check(!fell, "not a fallback");
inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
var p = new SortPlanner();
List<SortMove> m = p.Plan(inv, new List<SortRule> { gem }, SortScope.Main, true, 0, 0);
Check(m.Count == 1 && m[0].Dest.Id == 0x40000003 && m[0].DestIndex == 3, "moved to the pack with its id");
Eq(p.View.Issues.Count, 0, "no warning");
// A new pack shows up ahead of it in the list: the rule follows its pack.
inv.Packs.Insert(0, new SortPack { Id = 0x40000009, Name = "New", Capacity = 24 });
Eq(SortRules.Resolve(gem, inv, out _), 4, "its pack is now 4th: still the one used");
m = p.Plan(inv, new List<SortRule> { gem }, SortScope.Main, true, 0, 0);
Check(m.Count == 1 && m[0].Dest.Id == 0x40000003, "still moved to the same pack");
Check(PackFix.Sync(new List<SortRule> { gem }, inv) && gem.Pack == 4, "its number follows (for the window and the fallback)");
Check(!PackFix.Sync(new List<SortRule> { gem }, inv), "no change the second time");
// Already in its pack: Tidy leaves it there.
inv.Main.Items.Clear();
inv.Packs[3].Items.Add(It(11, "Black Opal", ObjectClasses.Gem));
Eq(p.Plan(inv, new List<SortRule> { gem }, SortScope.All, true, 0, 0).Count, 0, "in its pack: no move");
// Its pack isn't carried: the number decides, and the window says so.
SortInventory inv2 = Inv(3);
inv2.Main.Items.Add(It(12, "Black Opal", ObjectClasses.Gem));
var gone = SortRule.ForClass(ObjectClasses.Gem, 2);
gone.PackId = 0x4000FFFF;
gone.PackNote = "Sack - Gems";
Eq(SortRules.Resolve(gone, inv2, out fell), 2, "not carried: its number");
Check(fell, "a fallback");
m = p.Plan(inv2, new List<SortRule> { gone }, SortScope.Main, true, 0, 0);
Check(m.Count == 1 && m[0].DestIndex == 2, "moved by number");
Check(p.View.Issues.Count == 1 && p.View.Issues[0].UsedPack == 2 && p.View.Missing.Count == 0, "reported as a fallback, not missing");
// Not carried and no such number: nowhere.
gone.Pack = 5;
Eq(SortRules.Resolve(gone, inv2, out _), 0, "nowhere");
m = p.Plan(inv2, new List<SortRule> { gone }, SortScope.Main, true, 0, 0);
Check(m.Count == 0 && p.View.Missing.Contains(5) && p.View.Issues.Count == 1 && p.View.Issues[0].UsedPack == 0, "no move, reported missing");
Eq(p.View.Waiting, 1, "the item waits");
// A rule with no id is the number, as before; one that is off isn't reported.
Eq(SortRules.Resolve(SortRule.ForClass(ObjectClasses.Gem, 3), inv2, out fell), 3, "no id: the number");
Check(!fell, "no id: not a fallback");
gone.On = false;
p.Plan(inv2, new List<SortRule> { gone }, SortScope.Main, true, 0, 0);
Eq(p.View.Issues.Count, 0, "a rule that is off isn't reported");
}
private static List<SortRule> LuaRules() => new()
{
SortRule.ForClass(ObjectClasses.SpellComponent, 1), // a focus
SortRule.ForClass(ObjectClasses.Salvage, 2), // pack A
SortRule.ForClass(ObjectClasses.Gem, 3), // a focus
SortRule.ForClass(ObjectClasses.Key, 4), // pack B
SortRule.ForClass(ObjectClasses.HealingKit, 5), // pack C
SortRule.ForClass(ObjectClasses.TradeNote, 6), // nothing
};
private static void PackFixImported()
{
SortInventory inv = WithFoci();
List<SortRule> rules = LuaRules();
List<string> lines = PackFix.Apply(rules, inv, imported: true, LuaRules(), out int changed);
Eq(changed, 3, "three rules pointed at a pack");
Eq(lines.Count, 6, "a line for every rule");
Check(rules[0].PackId == 0 && rules[0].Pack == 1 && lines[0].Contains("a focus") && lines[0].Contains("left as pack 1"), "Lua pack 1 was a focus: left, and said so");
Check(rules[1].PackId == 0x40000001 && rules[1].Pack == 1, "Lua pack 2 = pack A = RynthSort's pack 1");
Check(lines[1].Contains("the Lua script's pack 2 -> pack 1") && lines[1].Contains("Pack - Salvage") && lines[1].Contains("0x40000001"), $"logged ({lines[1]})");
Check(rules[2].PackId == 0 && rules[2].Pack == 3 && lines[2].Contains("a focus"), "Lua pack 3 was a focus");
Check(rules[3].PackId == 0x40000002 && rules[3].Pack == 2, "Lua pack 4 = pack B = 2");
Check(rules[4].PackId == 0x40000003 && rules[4].Pack == 3 && rules[4].PackNote == "Pack - Components", "Lua pack 5 = pack C = 3, remembered with its contents");
Check(rules[5].PackId == 0 && rules[5].Pack == 6 && lines[5].Contains("doesn't exist") && lines[5].Contains("3 packs and 2 foci"), $"Lua pack 6 doesn't exist ({lines[5]})");
// Every rule with an id now: a second run changes nothing.
List<string> again = PackFix.Apply(rules, inv, true, LuaRules(), out int changed2);
Eq(changed2, 0, "rules with ids are skipped");
Eq(again.Count, 3, "only the three still without one are looked at");
// The Lua file unreadable (null): every rule is taken as the Lua script's.
List<SortRule> r2 = LuaRules();
PackFix.Apply(r2, inv, true, null, out int c3);
Check(c3 == 3 && r2[3].PackId == 0x40000002, "no Lua file to compare with: all as imported");
// No foci: Lua numbers and RynthSort's agree; the fix only adds the ids.
SortInventory plain = Inv(3);
foreach (SortPack pk in plain.Packs) plain.Slots.Add(new SortSlot(pk.Id, 24));
List<SortRule> r3 = SortRules.Defaults();
PackFix.Apply(r3, plain, true, SortRules.Defaults(), out int c4);
Check(c4 == 3 && r3[0].PackId == 0x40000001 && r3[0].Pack == 1 && r3[2].PackId == 0x40000003 && r3[2].Pack == 3, "no foci: same numbers, ids added");
// Rules RynthSort saved (not imported): each keeps its number and takes that pack's id.
List<SortRule> own = SortRules.Defaults();
List<string> ownLines = PackFix.Apply(own, inv, imported: false, null, out int c5);
Check(c5 == 3 && own[0].PackId == 0x40000001 && own[1].PackId == 0x40000002 && own[2].PackId == 0x40000003, "RynthSort's numbers count real packs: pinned as they are");
Check(ownLines[0].Contains("pack 1 kept"), $"logged ({ownLines[0]})");
Check(PackFix.Ready(inv), "every capacity read: ready");
inv.Slots[2] = new SortSlot(FocusB, -1);
Check(!PackFix.Ready(inv), "a capacity not readable yet: not ready (could be a pack)");
}
// Drakkon's rules as RynthSort's file had them on 2026-10-11 (imported, then edited in the
// window), against his Lua script's file (2026-10-07): only rules 5 and 6 are still the Lua
// script's (keys 3, kits 4); the rest were picked in RynthSort's window, in its numbers.
private static List<SortRule> DrakkonNow() => new()
{
SortRule.ForClass(ObjectClasses.SpellComponent, 4),
SortRule.ForClass(ObjectClasses.Salvage, 1),
SortRule.ForClass(ObjectClasses.Gem, 4),
SortRule.ForClass(ObjectClasses.ManaStone, 4),
SortRule.ForClass(ObjectClasses.Key, 3),
SortRule.ForClass(ObjectClasses.HealingKit, 4),
SortRule.ForClass(ObjectClasses.TradeNote, 4),
SortRule.ForName("Ink of", 2),
SortRule.ForName("Prismatic Taper", 4),
};
private static void PackFixDrakkon()
{
SortStore st = TempStore("drakkon");
string lua = st.LuaPathFor("DreamWeave", "Drakkon");
Directory.CreateDirectory(Path.GetDirectoryName(lua)!);
File.WriteAllText(lua, LuaFile);
var d = new CharacterSortData { Rules = DrakkonNow(), ImportedFrom = lua };
Check(st.Save("DreamWeave", "Drakkon", d) == null, "saved like the old file");
// The old file had no packsFixed and version 1.
string own = st.PathFor("DreamWeave", "Drakkon");
File.WriteAllText(own, File.ReadAllText(own).Replace("\"packsFixed\": false", "\"x\": 0").Replace("\"version\": 3", "\"version\": 1"));
CharacterSortData loaded = st.Load("DreamWeave", "Drakkon", out string? problem);
Check(problem == null && !loaded.PacksFixed && loaded.LuaRules != null && loaded.LuaRules.Count == 6, "imported, not fixed: the Lua file's rules read to compare with");
// A layout with one focus: slot 1 pack A, slot 2 a focus, slot 3 pack B, slot 4 pack C.
var inv = new SortInventory();
inv.Main.Id = Me;
inv.Slots.Add(new SortSlot(0x40000001, 24));
inv.Slots.Add(new SortSlot(FocusA, 0));
inv.Slots.Add(new SortSlot(0x40000002, 24));
inv.Slots.Add(new SortSlot(0x40000003, 24));
foreach (SortSlot s in inv.Slots)
if (s.IsPack) inv.Packs.Add(new SortPack { Id = s.Id, Name = "Pack", Capacity = 24 });
List<SortRule> r = loaded.Rules;
List<string> lines = PackFix.Apply(r, inv, true, loaded.LuaRules, out int changed);
Check(r[4].PackId == 0x40000002 && r[4].Pack == 2, "keys: the Lua script's pack 3 (after the focus) -> pack 2");
Check(r[5].PackId == 0x40000003 && r[5].Pack == 3, "kits: the Lua script's pack 4 -> pack 3");
Check(r[1].PackId == 0x40000001 && r[1].Pack == 1, "salvage (picked in RynthSort): pack 1 kept");
Check(r[7].PackId == 0x40000002 && r[7].Pack == 2, "Ink of (picked in RynthSort): pack 2 kept");
Check(r[0].PackId == 0 && r[0].Pack == 4 && lines[0].Contains("which you don't have"), "components to RynthSort's pack 4: there are only 3, left (and said)");
Check(r[8].PackId == 0 && r[8].Pack == 4, "Prismatic Taper to pack 4: the same");
Eq(changed, 4, "four rules tied to their packs");
Eq(lines.Count, 9, "a line per rule");
}
private static void PackFixLoop()
{
var w = new FakeWorld { Inv = WithFoci() };
w.Inv.Main.Items.Add(It(10, "Platinum Scarab", ObjectClasses.SpellComponent));
w.Inv.Main.Items.Add(It(11, "Healing Kit", ObjectClasses.HealingKit));
SortController c = Controller();
c.Data.Rules = LuaRules();
c.Data.ImportedFrom = "lua.json";
c.Data.LuaRules = LuaRules();
List<string>? fixLines = null;
int fixChanged = -1;
c.PacksFixed = (l, n) => { fixLines = l; fixChanged = n; };
Ticks(c, w, 0, SortController.FixSettleMs - 100);
Eq(w.Sent.Count, 0, "imported rules not fixed yet: nothing moves");
Eq(c.Status, "reading your packs", "status says why");
Check(!c.Data.PacksFixed && fixLines == null, "not before the packs have read the same for a while");
Ticks(c, w, SortController.FixSettleMs - 100 + 16, SortController.FixSettleMs + 1500);
Check(c.Data.PacksFixed && c.Data.LuaRules == null, "fixed once settled");
Check(fixLines != null && fixLines.Count == 6 && fixChanged == 3, "the plugin hears it (to log and save)");
Check(c.Log.Any(x => x.Contains("Imported pack numbers fixed: 3 of 6")), "noted in the window");
Check(w.Sent.Any(m => m.Item.Id == 11 && m.Dest.Id == 0x40000003), "kits (the Lua script's pack 5) go to pack C");
// Components named the Lua script's pack 1, a focus: left as it was, "pack 1", which is
// RynthSort's first real pack (the log line says so; Tom picks the right one).
Check(w.Sent.Any(m => m.Item.Id == 10 && m.Dest.Id == 0x40000001), "a rule left as it was keeps its number");
Check(c.Data.Rules[0].PackId == 0, "and has no id until one is picked");
}
private static void PackLabels()
{
var inv = new SortInventory();
inv.Main.Id = Me;
for (int i = 1; i <= 3; i++) inv.Packs.Add(new SortPack { Id = 0x40000000u + (uint)i, Name = "Pack", Capacity = 24 });
for (uint i = 0; i < 10; i++) inv.Packs[0].Items.Add(It(100 + i, "Salvaged Iron", ObjectClasses.Salvage));
for (uint i = 0; i < 5; i++) inv.Packs[0].Items.Add(It(200 + i, "Black Opal", ObjectClasses.Gem));
inv.Packs[0].Items.Add(It(300, "Legendary Key", ObjectClasses.Key));
inv.Packs[0].Items.Add(It(301, "Pyreal Mote", ObjectClasses.Misc));
inv.Packs[1].Items.Add(It(400, "Lead Scarab", ObjectClasses.SpellComponent));
inv.Packs[1].Items.Add(It(401, "Pyreal Mote", ObjectClasses.Misc));
inv.Packs[1].Items.Add(It(402, "Pyreal Mote", ObjectClasses.Misc));
Eq(inv.Packs[0].Summary(), "Salvage, Gems, Keys", "the three commonest kinds");
Eq(inv.Packs[1].Summary(), "Pyreal Mote, Components", "misc items by name");
Eq(inv.Packs[2].Summary(), "empty", "empty");
var p = new SortPlanner();
p.Plan(inv, SortRules.Defaults(), SortScope.Main, true, 0, 0);
List<string> choices = SortPanel.PackChoices(p.View, 1);
Eq(choices[0], "Pack 1: Pack (17/24) - Salvage, Gems, Keys", "picker label: number, name, room, contents");
Eq(choices[1], "Pack 2: Pack (3/24) - Pyreal Mote, Components", "bags with one name told apart by contents");
Eq(choices[2], "Pack 3: Pack (0/24) - empty", "an empty pack");
Eq(choices[3], "Pack 4 (none)", "then numbers you don't have");
// Picking stores the id; the row shows the pack it resolves to.
var rule = SortRule.ForClass(ObjectClasses.Gem, 1);
SortPanel.SetPack(rule, p.View, 2);
Check(rule.Pack == 2 && rule.PackId == 0x40000002 && rule.PackNote == "Pack - Pyreal Mote, Components", "picked: number, id and note");
Eq(SortPanel.ShownPack(p.View, rule), 2, "the rule is listed under pack 2");
SortPanel.SetPack(rule, p.View, 6);
Check(rule.Pack == 6 && rule.PackId == 0 && rule.PackNote == "", "a number you don't have: no id");
Check(!p.View.PackOrderKnown && SortPanel.PackTooltip(p.View).Contains("list order") && !SortPanel.PackTooltip(p.View).Contains("top of the pack column"),
"pack order unknown: the tooltip doesn't claim screen order");
inv.PackOrderKnown = true;
p.Plan(inv, SortRules.Defaults(), SortScope.Main, true, 0, 0);
Check(SortPanel.PackTooltip(p.View).Contains("top of the pack column"), "pack order known: numbered from the top");
// Warnings sit with their pack: a rule that fell back to a number is listed (and warned
// about) under the pack it uses; rules whose pack isn't carried are grouped by that pack.
var gems = SortRule.ForClass(ObjectClasses.Gem, 7);
gems.PackId = 0x4000AAAA; gems.PackNote = "Sack - Gems";
var keys = SortRule.ForClass(ObjectClasses.Key, 7);
keys.PackId = 0x4000AAAA; keys.PackNote = "Sack - Gems";
var salvage = SortRule.ForClass(ObjectClasses.Salvage, 1);
salvage.PackId = 0x4000BBBB; salvage.PackNote = "Bag - Salvage";
var rules = new List<SortRule> { SortRule.ForClass(ObjectClasses.SpellComponent, 1), gems, keys, SortRule.ForClass(ObjectClasses.ManaStone, 6), salvage };
inv.PackOrderKnown = false;
p.Plan(inv, rules, SortScope.Main, true, 0, 0);
Eq(SortPanel.FallbackWarnings(p.View, 1).Count, 1, "one fallback warning, under pack 1");
Eq(SortPanel.FallbackWarnings(p.View, 1)[0], "Salvage: its pack (Bag - Salvage) isn't carried, so this one is used", "with what the pack was");
Eq(SortPanel.FallbackWarnings(p.View, 2).Count, 0, "none under pack 2");
Dictionary<int, List<SortRule>> groups = SortPanel.Group(rules, p.View);
Check(groups[1].Count == 2 && groups[1].Contains(salvage), "pack 1 lists its own rule and the fallback");
Check(groups[0].Count == 3 && groups[0].Contains(gems) && groups[0].Contains(keys), "rules for packs you don't have, together");
}
private static void StorePackIds()
{
SortStore st = TempStore("packids");
CharacterSortData d = st.Load("S", "A", out _);
Check(!d.PacksFixed, "new character: the defaults get tied to packs on the first read");
d.Rules[0].PackId = 0x8000ABCD;
d.Rules[0].PackNote = "Sack - Components";
d.PacksFixed = true;
st.Save("S", "A", d);
string json = File.ReadAllText(st.PathFor("S", "A"));
Check(json.Contains("\"version\": 3") && json.Contains("\"packId\": 2147527629") && json.Contains("\"packsFixed\": true"), "version 2 with pack ids");
Check(!json.Contains("\"packId\": 0"), "no packId written for rules without one");
CharacterSortData back = st.Load("S", "A", out string? problem);
Check(problem == null && back.PacksFixed && back.Rules[0].PackId == 0x8000ABCD && back.Rules[0].PackNote == "Sack - Components" && back.Rules[1].PackId == 0, "read back");
Check(back.LuaRules == null, "not imported: nothing to compare with");
// A version 1 file: rules by number, not fixed.
File.WriteAllText(st.PathFor("S", "A"), "{\"version\":1,\"rules\":[{\"kind\":\"class\",\"class\":11,\"pack\":3}]}");
CharacterSortData v1 = st.Load("S", "A", out problem);
Check(problem == null && !v1.PacksFixed && v1.Rules[0].PackId == 0 && v1.Rules[0].Pack == 3, "version 1 loads: number only, fix pending");
File.WriteAllText(st.PathFor("S", "A"), "{\"rules\":[{\"pack\":3,\"packId\":-5},{\"pack\":2,\"packId\":3.5},{\"pack\":1,\"packId\":1073741825.0}]}");
CharacterSortData odd = st.Load("S", "A", out _);
Check(odd.Rules[0].PackId == 0 && odd.Rules[1].PackId == 0 && odd.Rules[2].PackId == 0x40000001, "odd ids read as none; a whole double is fine");
// A fresh import: the Lua rules kept to compare with, not fixed.
SortStore imp = TempStore("packids-import");
string lua = imp.LuaPathFor("DreamWeave", "Drakkon");
Directory.CreateDirectory(Path.GetDirectoryName(lua)!);
File.WriteAllText(lua, LuaFile);
CharacterSortData fresh = imp.Load("DreamWeave", "Drakkon", out _);
Check(!fresh.PacksFixed && fresh.LuaRules != null && fresh.LuaRules.Count == 6 && !ReferenceEquals(fresh.LuaRules[0], fresh.Rules[0]), "fresh import: Lua rules copied, fix pending");
// Saved with a backup: the old file kept beside it.
imp.Save("DreamWeave", "Drakkon", fresh);
string before = File.ReadAllText(imp.PathFor("DreamWeave", "Drakkon"));
fresh.PacksFixed = true;
Check(imp.Save("DreamWeave", "Drakkon", fresh, backup: true) == null, "saved with a backup");
string bak = imp.PathFor("DreamWeave", "Drakkon") + ".bak";
Check(File.Exists(bak) && File.ReadAllText(bak) == before, ".bak holds the file as it was");
CharacterSortData fixedNow = imp.Load("DreamWeave", "Drakkon", out _);
Check(fixedNow.PacksFixed && fixedNow.LuaRules == null, "once fixed, the Lua file isn't read again");
}
}
}

View file

@ -47,6 +47,12 @@ namespace RynthSort.Tests
{
Run("rules: class and name matching, first match wins", RuleMatching);
Run("classify: item classes as RynthLua sees them", Classify);
Run("classify: scarabs, tapers and other spell components", ClassifyComponents);
Run("rules: a rule's pack by id, else its number", ResolveById);
Run("pack fix: imported Lua numbers (foci counted)", PackFixImported);
Run("pack fix: Drakkon's rules (edited after the import)", PackFixDrakkon);
Run("pack fix: in the loop (held until the packs settle)", PackFixLoop);
Run("window: pack labels and warnings", PackLabels);
Run("plan: settle time, force", PlanSettle);
Run("plan: pack choice (full pack, stacks, capacity)", PlanPackChoice);
Run("plan: worn, packs, foci and blocked items never move", PlanNeverMoves);
@ -67,9 +73,19 @@ namespace RynthSort.Tests
Run("store: save and load", StoreRoundTrip);
Run("store: Lua script import", StoreLuaImport);
Run("store: odd files", StoreOddFiles);
Run("store: pack ids, the fix flag and the backup", StorePackIds);
Run("lua autostart warning", LuaAutostart);
Run("window: display lists parse in the engine", WindowParses);
Run("window: a bar button of its own", WindowBarButton);
Run("window: rule editing through events", WindowEvents);
Run("rules: several classes and names in one rule", MultiRules);
Run("store: old rules migrate to version 3", RuleMigration);
Run("order: inside a pack (A-Z, fewest moves, every order of up to 7)", InPackOrder);
Run("order: slot orders and the pack column", SlotOrders);
Run("plan: stacks and order inside packs", PlanInPack);
Run("moves: answers for moves within a pack", MoveAnswersInPlace);
Run("plan: a fixed inventory runs out of moves", Converges);
Run("loop: auto-sort tidies every pack, then stays still", ConvergesInTheLoop);
}
finally
{
@ -140,9 +156,11 @@ namespace RynthSort.Tests
Check(!SortRules.Matches(off, gem), "a rule that is off matches nothing");
var rules = new List<SortRule> { SortRule.ForName("taper", 5), SortRule.ForClass(ObjectClasses.SpellComponent, 1) };
Eq(SortRules.RuleFor(rules, comp)?.Pack, 5, "first match wins (name rule above the class rule)");
Eq(SortRules.RuleFor(rules, comp)?.Pack, 5, "a name match beats a class match");
(rules[0], rules[1]) = (rules[1], rules[0]);
Eq(SortRules.RuleFor(rules, comp)?.Pack, 1, "reordered: the class rule wins");
Eq(SortRules.RuleFor(rules, comp)?.Pack, 5, "whatever the order");
var twoClass = new List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 2), SortRule.ForClass(ObjectClasses.Gem, 4) };
Eq(SortRules.RuleFor(twoClass, gem)?.Pack, 2, "two class matches: the rule saved first");
Check(SortRules.RuleFor(Defaults, misc) == null, "no rule wants misc");
Eq(SortRules.RuleFor(Defaults, salvage)?.Pack, 2, "default: salvage to pack 2");
Eq(SortRules.RuleFor(Defaults, gem)?.Pack, 3, "default: gems to pack 3");
@ -411,6 +429,13 @@ namespace RynthSort.Tests
Check(w.Update(0x7000_0002, 7, 20_000), "the next corpse");
Check(w.Update(0, 0, 20_500), "closed: 1.5 s more (the next corpse is a moment away)");
Check(!w.Update(0, 0, 21_600), "then clear");
// An unreadable count (-1) between real reads is not a change (2026-10-11: paused for ever).
var f = new LootWatch();
Check(f.Update(0x7000_0003, 6, 30_000), "a corpse opened");
for (long t = 30_500; t < 40_000; t += 500)
f.Update(0x7000_0003, t % 1000 == 0 ? 6 : -1, t);
Check(!f.Update(0x7000_0003, 6, 40_000), "a flickering unreadable count doesn't keep it 'looting'");
}
private static void StatusJsonFallback()
@ -466,14 +491,17 @@ namespace RynthSort.Tests
public GateInputs Gate;
public readonly List<SortMove> Sent = new();
public bool EngineAccepts = true;
/// <summary>What the pretend engine can do (none: as an engine before API v80 without merges).</summary>
public SortAbilities Can;
/// <summary>"land" moves the item at once; "refuse" answers with InventoryServerSaveFailed; "busy" with You're too busy; "silent" never answers.</summary>
public string Server = "land";
public int ErrorSeq = 3;
private readonly Dictionary<uint, uint> _where = new();
private readonly HashSet<uint> _gone = new();
public SortInventory? ReadInventory() => Inv;
public GateInputs ReadGate(bool sortInCombat, long nowMs) { GateInputs g = Gate; g.SortInCombat = sortInCombat; return g; }
public int ErrorSeqNow() => ErrorSeq;
public SortAbilities Abilities => Can;
public bool SendMove(in SortMove move)
{
@ -482,12 +510,7 @@ namespace RynthSort.Tests
switch (Server)
{
case "land":
uint id = move.Item.Id;
foreach (SortPack p in Inv.Packs.Prepend(Inv.Main)) p.Items.RemoveAll(i => i.Id == id);
uint destId = move.Dest.Id;
SortPack dest = destId == Inv.Main.Id ? Inv.Main : Inv.Packs.First(p => p.Id == destId);
dest.Items.Add(move.Item);
_where[id] = dest.Id;
if (ServerApply(Inv, move)) _gone.Add(move.Item.Id);
break;
case "refuse":
ErrorSeq++;
@ -504,15 +527,58 @@ namespace RynthSort.Tests
private uint _refused;
private bool _busy;
public MoveObservation Observe(uint itemId)
public MoveObservation Observe(in SortMove move)
{
var o = new MoveObservation { Exists = true, Container = _where.TryGetValue(itemId, out uint c) ? c : Me, ErrorSeq = ErrorSeq };
uint itemId = move.Item.Id;
var o = new MoveObservation { Exists = !_gone.Contains(itemId), Container = Me, ErrorSeq = ErrorSeq, Slot = -1, Stack = move.Item.Stack };
foreach (SortPack p in Inv.Packs.Prepend(Inv.Main))
{
int at = p.Items.FindIndex(i => i.Id == itemId);
if (at < 0) continue;
o.Container = p.Id;
o.Slot = at;
o.Stack = p.Items[at].Stack;
}
if (_refused == itemId) { o.ErrorEventType = 0xA0; o.ErrorObject = itemId; }
if (_busy) { o.Error = 0x1D; o.ErrorEventType = 0x28A; }
return o;
}
}
/// <summary>
/// What ACE does with a move: a merge adds what fits to the other stack (the rest stays; a
/// stack emptied is gone: true); a move takes the item out and puts it in at its placement
/// (clamped), or at the end when it names none. Items keep their objects (the planner's
/// copies of stack sizes see the change, as a fresh read would).
/// </summary>
private static bool ServerApply(SortInventory inv, SortMove move)
{
uint id = move.Item.Id;
uint destId = move.Dest.Id;
SortPack? from = inv.Packs.Prepend(inv.Main).FirstOrDefault(p => p.Items.Any(i => i.Id == id));
if (from == null) return false;
SortItem item = from.Items.First(i => i.Id == id);
SortPack dest = destId == inv.Main.Id ? inv.Main : inv.Packs.First(p => p.Id == destId);
uint mergeInto = move.MergeInto;
if (mergeInto != 0)
{
SortItem? into = dest.Items.FirstOrDefault(i => i.Id == mergeInto);
if (into == null) return false;
int max = into.MaxStack > 1 ? into.MaxStack : item.MaxStack;
int amount = Math.Min(item.Stack, max - into.Stack);
if (amount <= 0) return false;
into.Stack += amount;
item.Stack -= amount;
if (item.Stack > 0) return false;
from.Items.Remove(item);
return true;
}
from.Items.Remove(item);
int at = move.Placement >= 0 ? Math.Clamp(move.Placement, 0, dest.Items.Count) : dest.Items.Count;
dest.Items.Insert(at, item);
return false;
}
private static SortController Controller(bool auto = true, int gapMs = 300, int settleSec = 0)
{
var c = new SortController();
@ -695,7 +761,7 @@ namespace RynthSort.Tests
Ticks(c, w, 0, 600);
Eq(w.Sent.Count, 2, "tidy moved both quickly (job gap, not the 3 s auto gap)");
Eq(w.Inv.Packs[1].Items.Count, 2, "both in pack 2");
Check(c.Job == null && c.Log[0] == "Packs tidied", "job ends with a note");
Check(c.Job == null && c.Log[0] == "Packs sorted", "job ends with a note");
// Unpack turns auto-sort off (and asks for a save) so nothing moves back.
var w2 = new FakeWorld();
@ -750,21 +816,23 @@ namespace RynthSort.Tests
{
SortStore st = TempStore("roundtrip");
CharacterSortData d = st.Load("DreamWeave", "Drakkon", out string? problem);
Check(problem == null && d.Rules.Count == 5 && d.ImportedFrom.Length == 0, "no file: the defaults");
Check(problem == null && d.Rules.Count == 3 && d.ImportedFrom.Length == 0, "no file: the defaults");
Check(!d.Settings.WindowOpen, "no file: the window starts closed (the bar button opens it)");
d.Rules.Add(SortRule.ForName("Pyreal \"Mote\"", 6));
d.Rules[0].On = false;
d.Settings.Auto = false;
d.Settings.SettleSec = 12;
d.Settings.GapMs = 900;
d.Settings.SortInCombat = true;
d.Settings.WindowOpen = false;
d.Settings.WindowOpen = true;
Check(st.Save("DreamWeave", "Drakkon", d) == null, "saved");
Check(File.Exists(Path.Combine(st.Root, "characters", "DreamWeave_Drakkon.json")), "file named server_character");
CharacterSortData back = st.Load("DreamWeave", "Drakkon", out problem);
Check(problem == null, "read back");
Eq(back.Rules.Count, 6, "rules");
Check(!back.Rules[0].On && back.Rules[5].Kind == RuleKind.Name && back.Rules[5].Text == "Pyreal \"Mote\"" && back.Rules[5].Pack == 6, "rule fields");
Check(!back.Settings.Auto && back.Settings.SettleSec == 12 && back.Settings.GapMs == 900 && back.Settings.SortInCombat && !back.Settings.WindowOpen, "settings");
Eq(back.Rules.Count, 4, "rules");
Check(!back.Rules[0].On && back.Rules[3].Classes.Count == 0 && back.Rules[3].Names.Count == 1 && back.Rules[3].Names[0] == "Pyreal \"Mote\"" && back.Rules[3].Pack == 6, "rule fields");
Check(back.Rules[2].SameAs(SortRules.Defaults()[2]), "a rule with three classes comes back whole");
Check(!back.Settings.Auto && back.Settings.SettleSec == 12 && back.Settings.GapMs == 900 && back.Settings.SortInCombat && back.Settings.WindowOpen, "settings");
Eq(SortStore.FileStem("Dream:Weave", "Con"), "Dream_Weave_Con", "unsafe characters replaced like RynthLua");
Eq(SortStore.SafeFileName("CON"), "_CON", "reserved names guarded");
}
@ -782,9 +850,10 @@ namespace RynthSort.Tests
Check(problem == null, "Lua file read");
Eq(d.ImportedFrom, lua, "marked as imported");
Eq(d.Rules.Count, 6, "six rules");
Check(d.Rules[5].Kind == RuleKind.Class && d.Rules[5].Class == ObjectClasses.HealingKit && d.Rules[5].Pack == 4, "healing kits to pack 4");
Check(d.Rules[5].Names.Count == 0 && d.Rules[5].Classes.Count == 1 && d.Rules[5].Classes[0] == ObjectClasses.HealingKit && d.Rules[5].Pack == 4, "healing kits to pack 4 (one class)");
Check(!d.Settings.Auto && d.Settings.SettleSec == 5 && d.Settings.GapMs == 600, "settings taken over");
Check(d.Settings.WindowOpen && !d.Settings.SortInCombat, "plugin-only settings at their defaults");
Check(!d.Settings.SortInCombat, "plugin-only settings at their defaults");
Check(d.Settings.WindowOpen, "taken over from the Lua script: the window opens once to show the rules");
// Once RynthSort has its own file, the Lua file is no longer read (and is left alone).
d.Rules.RemoveAt(0);
@ -804,7 +873,7 @@ namespace RynthSort.Tests
Directory.CreateDirectory(Path.GetDirectoryName(own)!);
File.WriteAllText(own, "{ not json");
CharacterSortData d = st.Load("S", "A", out string? problem);
Check(problem != null && d.Rules.Count == 5, "broken file: defaults, problem reported");
Check(problem != null && d.Rules.Count == 3, "broken file: defaults, problem reported");
// The Lua script saved an empty rule list as {}; numbers as doubles; out-of-range values clamped.
File.WriteAllText(own, "{\"rules\":{},\"settings\":{\"auto\":true,\"settleSec\":99.0,\"gapMs\":5,\"x\":1}}");
@ -815,9 +884,9 @@ namespace RynthSort.Tests
File.WriteAllText(own, "{\"rules\":[{\"kind\":\"name\",\"text\":\"Key\",\"pack\":2.0},{\"class\":11,\"pack\":-4},7,{\"on\":false}]}");
d = st.Load("S", "A", out _);
Eq(d.Rules.Count, 3, "a non-object entry is skipped");
Check(d.Rules[0].Kind == RuleKind.Name && d.Rules[0].Pack == 2 && d.Rules[0].On, "missing 'on' = on; 2.0 = 2");
Check(d.Rules[0].Names.Count == 1 && d.Rules[0].Names[0] == "Key" && d.Rules[0].Classes.Count == 0 && d.Rules[0].Pack == 2 && d.Rules[0].On, "missing 'on' = on; 2.0 = 2");
Eq(d.Rules[1].Pack, 1, "pack clamped to 1");
Check(!d.Rules[2].On && d.Rules[2].Class == ObjectClasses.SpellComponent, "defaults for missing fields");
Check(!d.Rules[2].On && d.Rules[2].Classes.Count == 1 && d.Rules[2].Classes[0] == ObjectClasses.SpellComponent, "defaults for missing fields");
}
private static void LuaAutostart()
@ -869,6 +938,32 @@ namespace RynthSort.Tests
maxOps = windows.Where(x => x.List != null).Select(x => x.List!.OpCount).DefaultIfEmpty(0).Max();
}
private static unsafe List<ParsedWindow> ParseWindows(UiHost host)
{
int n = Write(host);
byte[] buf = SubmitBuffer(host);
List<ParsedWindow> windows;
fixed (byte* p = buf) DisplayListParser.Parse(p, n, 4000f, out _, out windows, out _);
return windows;
}
private static void WindowBarButton()
{
Eq(UiFormat.FlagBarButton, WindowFlags.BarButton, "the plugin's bit is the engine's");
var (_, panel, host, w) = Window();
Draw(w, panel);
List<ParsedWindow> windows = ParseWindows(host);
Check(windows.Count == 1 && windows[0].Title == "RynthSort", "one window, titled RynthSort (the button's tooltip)");
uint f = windows.Count == 1 ? windows[0].Flags : 0;
Check((f & WindowFlags.ShowInBar) != 0 && (f & WindowFlags.BarButton) != 0, "ShowInBar + BarButton survive the engine's parse");
w.MarkSubmitted(true);
w.ShowInBar = false;
windows = ParseWindows(host);
f = windows.Count == 1 ? windows[0].Flags : ~0u;
Check((f & (WindowFlags.ShowInBar | WindowFlags.BarButton)) == 0, "not in the bar: no button either");
}
private static byte[] Event(ushort type, uint seq, uint window, uint key, byte[] payload)
{
var e = new byte[16 + payload.Length];
@ -890,37 +985,65 @@ namespace RynthSort.Tests
ParseAll(host, "default rules", out int ops);
Check(ops > 10 && ops < 1500, $"ops in range ({ops})");
string body = BodyText(w);
Check(body.Contains("Auto-sort") && body.Contains("Sort main pack") && body.Contains("Tidy all packs")
&& body.Contains("Empty side packs") && body.Contains("Clean packs"), "buttons and toggle");
Check(body.Contains("Rules (first match wins)") && body.Contains("1. Spell Component -> pack 1 (Pack 1)"), "rule list");
Check(body.Contains("Auto-sort") && body.Contains("Sort now") && body.Contains("Clean packs") && body.Contains("Empty side packs"), "buttons and toggle");
Check(body.Contains("Main pack (1/102)"), "the main pack's line");
Check(body.Contains("Pack 1: Pack 1 (24/24) - Junk 0, Junk 1, Junk 2"), "a section per pack, named with its room and contents");
Check(body.Contains("Pack 3: Pack 3 (0/24) - empty") && body.Contains("Gem, Key, Mana Stone"), "a rule with three classes as one row under its pack");
Check(body.Contains("Pack 4: Pack 4 (0/24) - empty") && body.Contains("No rules send items here."), "a pack without rules says so");
Check(body.IndexOf("Pack 1: ", StringComparison.Ordinal) < body.IndexOf("Spell Component", StringComparison.Ordinal)
&& body.IndexOf("Spell Component", StringComparison.Ordinal) < body.IndexOf("Pack 2: ", StringComparison.Ordinal), "a rule sits under its pack");
Check(!body.Contains("Classes:"), "no editor until a rule is picked");
w.MarkSubmitted(true);
// A selected rule's editor (class, then name), the settings open, warnings and a log.
Apply(host, Event(1, 1, w.Hash, w.KeyOf("row.0"), Click));
// The gem rule's editor, the settings open, warnings and a log.
SortRule gemRule = c.Data.Rules[2];
Apply(host, Event(1, 1, w.Hash, w.KeyOf($"r{gemRule.Uid}.row"), Click));
Apply(host, Event(6, 2, w.Hash, w.KeyOf("settings"), new byte[] { 1 }));
c.Note("Prismatic Taper -> pack 1");
panel.Warnings = () => new[] { "The RynthSort Lua script is set to start too" };
Draw(w, panel);
ParseAll(host, "rule editor (class)", out _);
ParseAll(host, "rule editor", out _);
body = BodyText(w);
Check(body.Contains("Rule 1") && body.Contains("Mana Stone") && body.Contains("Pack 1: Pack 1 (24/24)") && body.Contains("Pack 7 (none)"), "editor with class and pack choices");
Check(body.Contains("Settle (s)") && body.Contains("Gap (ms)") && body.Contains("Sort during fights"), "settings shown");
Check(body.Contains("Classes:") && body.Contains("Gem x") && body.Contains("Key x") && body.Contains("Mana Stone x"), "the rule's classes as chips");
Check(body.Contains("Add a class...") && body.Contains("Name has") && body.Contains("Remove rule"), "add a class, add a name, remove");
Check(body.Contains("Pack 3: Pack 3 (0/24) - empty") && body.Contains("Pack 7 (none)"), "the pack picker");
Check(body.Contains("Settle (s)") && body.Contains("Gap (ms)") && body.Contains("Sort during fights")
&& body.Contains("Put items in order inside packs") && body.Contains("Group by kind first"), "settings shown");
Check(body.Contains("plugin API 80"), "an engine that can't read orders: said in the settings");
Check(body.Contains("Lua script is set to start"), "warning shown");
w.MarkSubmitted(true);
c.Data.Rules[0].Kind = RuleKind.Name;
c.Data.Rules[0].Text = "Taper";
c.Data.Rules[0].Class = 999;
gemRule.AddName("Opal");
gemRule.AddName("a##b");
Draw(w, panel);
ParseAll(host, "rule editor (name)", out _);
Check(BodyText(w).Contains("Name has"), "name editor");
c.Data.Rules[0].Kind = RuleKind.Class;
ParseAll(host, "rule editor with names", out _);
body = BodyText(w);
Check(body.Contains("Names:") && body.Contains("\"Opal\" x"), "names as chips");
Check(body.Contains("Gem, Key, Mana Stone, name has \"a# #b\", name has \"Opal\""), "the row: classes, then names, A-Z (## shown apart)");
// A rule whose pack isn't carried: its own section, grouped by what the pack was.
var gone = SortRule.ForClass(ObjectClasses.Lockpick, 9);
gone.PackId = 0x4000AAAA;
gone.PackNote = "Sack - Gems";
c.Data.Rules.Add(gone);
var inv = Inv(4);
Fill(inv.Packs[0], 24, 1000);
inv.Packs[0].OrderKnown = true;
c.Planner.Plan(inv, c.Data.Rules, SortScope.All, true, 0, 0, PlanOptions.Full);
Draw(w, panel);
ParseAll(host, "rule editor (class the editor doesn't offer)", out _);
Check(BodyText(w).Contains("class 999"), "an unknown class stays shown");
ParseAll(host, "missing pack", out _);
body = BodyText(w);
Check(body.Contains("Rules for packs you don't have (1)") && body.Contains("A pack you don't have (it was Sack - Gems):") && body.Contains("Lockpick"), "missing-pack section");
Check(body.Contains("Pack 1: Pack 1 (24/24)") && body.Contains("in order"), "a pack in order says so");
// Two rules naming the same class for different packs: the losing pack says so.
c.Data.Rules.Add(SortRule.ForClass(ObjectClasses.Gem, 4));
Draw(w, panel);
ParseAll(host, "conflict", out _);
Check(BodyText(w).Contains("Gem: also in a rule for pack 3, which wins"), "conflict shown under the losing pack");
// Many rules still fit.
for (int i = 0; i < SortStore.MaxRules; i++) c.Data.Rules.Add(SortRule.ForName("x" + i, 1 + i % 8));
for (int i = 0; i < SortStore.MaxRules; i++) c.Data.Rules.Add(SortRule.For(1 + i % 8, new[] { ObjectClasses.Armor, ObjectClasses.Food }, "x" + i, "y" + i));
Draw(w, panel);
ParseAll(host, "64+ rules", out int many);
Check(many < 1500, $"many rules fit ({many} ops)");
@ -932,64 +1055,107 @@ namespace RynthSort.Tests
Check(BodyText(w).Contains("Log in"), "logged-out text");
}
private static byte[] TextEvent(string text, bool submitted)
{
byte[] t = Encoding.UTF8.GetBytes(text);
var payload = new byte[3 + t.Length];
payload[0] = submitted ? (byte)1 : (byte)0;
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(1), (ushort)t.Length);
t.CopyTo(payload, 3);
return payload;
}
private static void WindowEvents()
{
var (c, panel, host, w) = Window();
Draw(w, panel);
int rules = c.Data.Rules.Count;
uint seq = 0;
void Send(ushort type, string id, byte[] payload)
{
Apply(host, Event(type, ++seq, w.Hash, w.KeyOf(id), payload));
Draw(w, panel);
}
Apply(host, Event(1, 1, w.Hash, w.KeyOf("rule.add"), Click));
// "+ Add rule" in pack 4's section: a new, empty rule for pack 4, its editor open.
Send(1, "add.40000004", Click);
Eq(c.Data.Rules.Count, rules + 1, "Add rule");
Eq(panel.Selected, rules, "the new rule is selected");
Draw(w, panel);
SortRule r = panel.Selected!;
Check(r != null && r.IsEmpty && r.PackId == 0x40000004 && r.Pack == 4, "the new rule is selected, empty, for that pack");
Check(BodyText(w).Contains("(empty: add a class or a name)"), "an empty rule says what to do");
string k = "r" + r!.Uid;
Apply(host, Event(1, 2, w.Hash, w.KeyOf("rule.up"), Click));
Eq(panel.Selected, rules - 1, "Up moves the selection with the rule");
Draw(w, panel);
// Classes through the picker (its first line is "Add a class...").
Send(3, k + ".addclass", BitConverter.GetBytes(ObjectClasses.ChoiceIndex(ObjectClasses.Armor) + 1));
Check(r.Classes.Count == 1 && r.HasClass(ObjectClasses.Armor), "picker adds Armor");
int clothing = ObjectClasses.Choices.Where(x => x != ObjectClasses.Armor).ToList().IndexOf(ObjectClasses.Clothing) + 1;
Send(3, k + ".addclass", BitConverter.GetBytes(clothing));
Check(r.HasClass(ObjectClasses.Clothing) && r.Classes.Count == 2, "and Clothing (the picker leaves out what the rule has)");
Send(3, k + ".addclass", BitConverter.GetBytes(0));
Eq(r.Classes.Count, 2, "the picker's first line adds nothing");
// The new rule: make it a name rule for "opal" to pack 4.
Apply(host, Event(3, 3, w.Hash, w.KeyOf("rule.kind"), BitConverter.GetBytes(1)));
Draw(w, panel);
byte[] text = Encoding.UTF8.GetBytes("opal");
var payload = new byte[3 + text.Length];
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(1), (ushort)text.Length);
text.CopyTo(payload, 3);
Apply(host, Event(5, 4, w.Hash, w.KeyOf("rule.text"), payload));
Apply(host, Event(3, 5, w.Hash, w.KeyOf("rule.pack"), BitConverter.GetBytes(3)));
SortRule r = c.Data.Rules[rules - 1];
Check(r.Kind == RuleKind.Name && r.Text == "opal" && r.Pack == 4, "edited through the combo, text box and pack combo");
Draw(w, panel);
// Names: typed and Enter, or typed and Add.
Send(5, k + ".draft", TextEvent("Shield", true));
Check(r.Names.Count == 1 && r.HasName("Shield"), "Enter adds the name");
Send(5, k + ".draft", TextEvent("Buckler", false));
Eq(r.Names.Count, 1, "typing alone adds nothing");
Send(1, k + ".addname", Click);
Check(r.HasName("Buckler") && r.Names.Count == 2, "Add adds it");
Send(5, k + ".draft", TextEvent("shield", true));
Eq(r.Names.Count, 2, "the same name in another case isn't added twice");
Check(BodyText(w).Contains("Armor, Clothing, name has \"Buckler\", name has \"Shield\""), "the row lists them");
// Its checkbox turns it off.
Apply(host, Event(2, 6, w.Hash, w.KeyOf("on." + (rules - 1)), new byte[] { 0 }));
Check(!r.On, "checkbox turns the rule off");
Draw(w, panel);
// Chips take entries out.
Send(1, $"{k}.c{ObjectClasses.Clothing}", Click);
Check(!r.HasClass(ObjectClasses.Clothing) && r.HasClass(ObjectClasses.Armor), "a class chip removes its class");
Send(1, k + ".n0", Click);
Check(!r.HasName("Buckler") && r.HasName("Shield"), "a name chip removes its name (A-Z: Buckler first)");
Apply(host, Event(1, 7, w.Hash, w.KeyOf("rule.down"), Click));
Eq(c.Data.Rules.IndexOf(r), rules, "Down");
Draw(w, panel);
Apply(host, Event(1, 8, w.Hash, w.KeyOf("rule.remove"), Click));
Check(!c.Data.Rules.Contains(r) && c.Data.Rules.Count == rules, "Remove");
Draw(w, panel);
// Another pack through the picker.
Send(3, k + ".pack", BitConverter.GetBytes(1));
Check(r.Pack == 2 && r.PackId == 0x40000002 && r.PackNote.StartsWith("Pack 2 - "), $"moved to pack 2, kept by its id ({r.PackNote})");
string body = BodyText(w);
Check(body.IndexOf("Pack 2: ", StringComparison.Ordinal) < body.IndexOf("Armor, name has", StringComparison.Ordinal)
&& body.IndexOf("Armor, name has", StringComparison.Ordinal) < body.IndexOf("Pack 3: ", StringComparison.Ordinal), "now listed under pack 2");
// Class combo on rule 1.
Apply(host, Event(1, 9, w.Hash, w.KeyOf("row.0"), Click));
Draw(w, panel);
Apply(host, Event(3, 10, w.Hash, w.KeyOf("rule.class"), BitConverter.GetBytes(ObjectClasses.ChoiceIndex(ObjectClasses.HealingKit))));
Eq(c.Data.Rules[0].Class, ObjectClasses.HealingKit, "class combo");
// On and off.
Send(2, k + ".on", new byte[] { 0 });
Check(!r.On, "the box turns the rule off");
Send(2, k + ".on", new byte[] { 1 });
Check(r.On, "and on");
// Merge rules: a second rule for pack 3 joins the first.
Send(1, "add.40000003", Click);
SortRule second = panel.Selected!;
Send(3, "r" + second.Uid + ".addclass", BitConverter.GetBytes(ObjectClasses.ChoiceIndex(ObjectClasses.Lockpick) + 1));
Check(BodyText(w).Contains("Merge rules"), "two rules in a pack: Merge rules offered");
int before = c.Data.Rules.Count;
Send(1, "merge.40000003", Click);
Eq(c.Data.Rules.Count, before - 1, "two rules became one");
SortRule merged = c.Data.Rules.Single(x => x.PackId == 0x40000003 || x.Pack == 3);
Check(merged.HasClass(ObjectClasses.Gem) && merged.HasClass(ObjectClasses.Key) && merged.HasClass(ObjectClasses.ManaStone) && merged.HasClass(ObjectClasses.Lockpick),
"the merged rule has every class");
// Remove.
Send(1, k + ".row", Click);
Check(ReferenceEquals(panel.Selected, r), "picked again");
Send(1, k + ".remove", Click);
Check(!c.Data.Rules.Contains(r) && panel.Selected == null, "Remove");
// Settings and buttons.
Apply(host, Event(6, 11, w.Hash, w.KeyOf("settings"), new byte[] { 1 }));
Draw(w, panel);
Apply(host, Event(3, 12, w.Hash, w.KeyOf("settle"), BitConverter.GetBytes(12)));
Apply(host, Event(3, 13, w.Hash, w.KeyOf("gap"), BitConverter.GetBytes(50_000)));
Apply(host, Event(2, 14, w.Hash, w.KeyOf("combat"), new byte[] { 1 }));
Send(6, "settings", new byte[] { 1 });
Send(3, "settle", BitConverter.GetBytes(12));
Send(3, "gap", BitConverter.GetBytes(50_000));
Send(2, "combat", new byte[] { 1 });
Check(c.Data.Settings.SettleSec == 12 && c.Data.Settings.GapMs == SortSettings.GapMax && c.Data.Settings.SortInCombat, "sliders (clamped) and the fights box");
Apply(host, Event(2, 15, w.Hash, w.KeyOf("auto"), new byte[] { 0 }));
Send(2, "order", new byte[] { 0 });
Send(2, "orderkind", new byte[] { 1 });
Check(!c.Data.Settings.OrderInPacks && c.Data.Settings.OrderKindFirst, "the order boxes");
Send(2, "auto", new byte[] { 0 });
Check(!c.Data.Settings.Auto, "auto-sort box");
Apply(host, Event(1, 16, w.Hash, w.KeyOf("job.all"), Click));
Eq(c.Job, SortScope.All, "Tidy button");
Apply(host, Event(1, 17, w.Hash, w.KeyOf("job.unpack"), Click));
Send(1, "job.all", Click);
Eq(c.Job, SortScope.All, "Sort now button");
Send(1, "job.unpack", Click);
Check(c.Job == SortScope.Unpack && c.UnpackWhich == null, "Empty side packs button");
}
}

View file

@ -4,7 +4,12 @@
Offline checks for RynthSort: rule matching, pack choice (a full pack only takes an item that
joins a stack there), Tidy / Clean / Unpack planning, the "stay out of the way" gates (looting,
vendor, trade, busy, portal space and RynthAi's activity bits), one move at a time with the
gap and the back-off after refusals, the per-character file and the Lua script import, and that
gap and the back-off after refusals, the per-character file and the Lua script import, rules
tied to pack ids (and the one-time fix of the Lua script's pack numbers, which counted foci),
rules with several classes and names (and old files migrating to them), the order inside
packs (every order of up to 7 items, shuffled packs to 102), slot orders and the pack column,
stacks joined in place, that a fixed inventory runs out of moves (planner and loop),
the pack picker's labels, spell component classification, and that
the window's display list is accepted by the engine's own parser (RynthCore
src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs, compiled in from the sibling
RynthCore checkout). Nothing native is loaded: no AC, no ImGui context. Files go to a temp