Snapshot for release 2026.10.11.1 (internal d20160b)

This commit is contained in:
Tom Bohar 2026-10-11 15:00:56 -04:00
commit 504a6f080a
66 changed files with 7865 additions and 310 deletions

View file

@ -0,0 +1,73 @@
using System;
using System.Linq;
using RynthCore.Loot.VTank;
namespace RynthCore.LootSdkTests;
// Condition types the parser has no arity for (2009/2011/2016 from a third-party editor):
// their data must be bounded by the length code, not by guessing where the next rule
// starts. The fixture mirrors T10locky.utl on 2026-10-06, where a leading unknown node
// swallowed two following rules and a trailing one ate the SalvageCombine block.
internal static partial class Program
{
private const string UnknownNodeUtl =
"UTL\n1\n4\n" +
// Unknown node, a known LongValKeyGE, then another unknown node.
"Mixed\n\n0;1;2011;3;2011\n" +
"3\n0\n" +
"9\n15\n374\n" +
"3\n0\n" +
// Plain name rule right after it: was swallowed by the old heuristic.
"Coins\n\n0;1;1\n" +
"9\nCoin\n1\n" +
// Unknown node whose length code is not a number: heuristic fallback still applies.
"Bogus\n\n0;1;2010\n" +
"x\nabc\n" +
// Trailing unknown node directly before SalvageCombine.
"Spirit\n\n0;1;2016\n" +
"21\nEncapsulated Spirit\n" +
"SalvageCombine\n1\n1\n1-6, 7-8, 9, 10\n1\n25\n1-10\n";
private static void RunUnknownNodeTests()
{
Console.WriteLine("\n-- unknown VTank node types --");
VTankLootProfile p = VTankLootParser.LoadFromText(UnknownNodeUtl);
Eq(p.Rules.Count, 4, "unknown nodes: every rule parsed");
Eq(string.Join("|", p.Rules.Select(r => r.Name)), "Mixed|Coins|Bogus|Spirit", "unknown nodes: rule names in order");
VTankLootRule mixed = p.Rules[0];
Eq(mixed.Conditions.Count, 3, "unknown nodes: Mixed keeps three conditions");
Eq(string.Join(",", mixed.Conditions[0].DataLines), "0", "unknown nodes: leading 2011 reads only its own line");
Eq(mixed.Conditions[1].NodeType, VTankNodeTypes.LongValKeyGE, "unknown nodes: known node after an unknown one");
Eq(string.Join(",", mixed.Conditions[1].DataLines), "15,374", "unknown nodes: known node data aligned");
Eq(string.Join(",", mixed.Conditions[2].DataLines), "0", "unknown nodes: trailing 2011 reads only its own line");
Eq(string.Join(",", p.Rules[1].Conditions[0].DataLines), "Coin,1", "unknown nodes: following name rule intact");
Eq(string.Join(",", p.Rules[2].Conditions[0].DataLines), "abc", "unknown nodes: non-numeric length code falls back");
Eq(string.Join(",", p.Rules[3].Conditions[0].DataLines), "Encapsulated Spirit", "unknown nodes: 2016 reads one line");
Check(p.SalvageCombine != null, "unknown nodes: SalvageCombine block survives a trailing unknown node");
if (p.SalvageCombine != null)
{
Check(p.SalvageCombine.Enabled, "unknown nodes: SalvageCombine enabled");
Eq(p.SalvageCombine.PerMaterial.TryGetValue(25, out string? bands) ? bands : null, "1-10",
"unknown nodes: SalvageCombine per-material band");
}
// Unknown nodes keep their exact lines, so a re-save does not corrupt the profile.
VTankLootProfile back = VTankLootParser.LoadFromText(VTankLootWriter.Serialize(p));
Eq(string.Join("|", back.Rules.Select(r => r.Name)), "Mixed|Coins|Bogus|Spirit", "unknown nodes: round-trip rule names");
Eq(string.Join(",", back.Rules[0].Conditions[2].DataLines), "0", "unknown nodes: round-trip keeps unknown data");
Eq(p.DeclaredRuleCount, 4, "unknown nodes: declared count recorded");
// A header that undercounts: every rule present is still read, SalvageCombine too,
// and a re-save writes the true count.
string undercounted = UnknownNodeUtl.Replace("UTL\n1\n4\n", "UTL\n1\n2\n");
VTankLootProfile u = VTankLootParser.LoadFromText(undercounted);
Eq(u.DeclaredRuleCount, 2, "undercounted header: declared count");
Eq(string.Join("|", u.Rules.Select(r => r.Name)), "Mixed|Coins|Bogus|Spirit", "undercounted header: all rules read");
Check(u.SalvageCombine != null, "undercounted header: SalvageCombine still parsed");
Eq(VTankLootParser.LoadFromText(VTankLootWriter.Serialize(u)).DeclaredRuleCount, 4, "undercounted header: re-save fixes the count");
}
}

View file

@ -46,6 +46,7 @@ internal static partial class Program
RunLootAddTests(args);
RunT11Tests();
RunLootAddT11Tests();
RunUnknownNodeTests();
Console.WriteLine($"\nGolden tests: {_asserts} assertions, {_fails} failed.");

View file

@ -25,6 +25,7 @@ namespace RynthCore.PatrolProof;
//
// It also compares /ra dunnav paths between 40 random cell pairs. Extra words:
// verbose list the off-floor legs trace log every room crossing
// waypoints one line per patrol waypoint and the rule that laid it (Waypoints.cs)
// doors x y list the cells, openings and floor polygons within 20 m of world (x, y)
//
// Run: dotnet run -c Release [-- <landblock hex>] [-- <AC folder>] [-- dump <dir>] [-- verbose]
@ -33,6 +34,7 @@ internal static class Program
private static int Main(string[] args)
{
if (args.Length > 0 && args[0] == "clear") return Clearance.Run(args.Skip(1).ToArray());
if (args.Contains("waypoints")) return Waypoints.Run(args);
uint lb = 0x6346;
string acDir = @"C:\Turbine\Asheron's Call";
string dumpDir = null;

View file

@ -29,6 +29,8 @@
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonPathfinder.cs" Link="Linked\DungeonPathfinder.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonPathfinder.Rooms.cs" Link="Linked\DungeonPathfinder.Rooms.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonGeometry.cs" Link="Linked\DungeonGeometry.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonHazardSurfaces.cs" Link="Linked\DungeonHazardSurfaces.cs" />
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Linked\RynthInstallPaths.cs" />
</ItemGroup>
<ItemGroup>

View file

@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Raycasting;
namespace RynthCore.PatrolProof;
// "waypoints": the patrol the plugin builds from given start cells, one line per waypoint with
// the rule that laid it (DungeonPathfinder.DescribePatrol, the same lines BuildDunPatrol logs as
// "[RynthAi] DunNav-Patrol wp ..."), and the hazard set the game would use:
// dotnet run -c Release -- 6146 waypoints 61460100 61460325 [surface] [hzfile <file>] [hz 012E,0131] [summary] [tiny]
// surface add the Detector C cells (floor textures in HazardTextures.txt, as the game seeds them)
// hzfile f add the cells listed in a DungeonHazards/<lb>.txt file
// hz a,b,... add cells (low 16 bits hex, or full ids)
// compare for each start, the summary with none / surface / file+hz / all hazards
// summary summary lines only tiny only waypoints in rooms of <= 5 cells
// The start cell is handled as BuildDunPatrol does: a start in a hazard moves to NearestSafeCell.
internal static class Waypoints
{
public static int Run(string[] args)
{
uint lb = 0x6146;
string acDir = @"C:\Turbine\Asheron's Call";
var starts = new List<uint>();
bool surface = false, summaryOnly = false, tinyOnly = false, compare = false;
var extra = new HashSet<uint>();
var fileCells = new HashSet<uint>();
for (int i = 0; i < args.Length; i++)
{
string a = args[i];
if (a == "waypoints") continue;
if (a == "surface") surface = true;
else if (a == "summary") summaryOnly = true;
else if (a == "tiny") tinyOnly = true;
else if (a == "compare") compare = true;
else if (a == "hzfile" && i + 1 < args.Length)
{
foreach (string raw in File.ReadAllLines(args[++i]))
{
string l = raw.Trim();
if (l.Length == 0 || l[0] == '#') continue;
if (uint.TryParse(l.Replace("0x", ""), NumberStyles.HexNumber, null, out uint c)) fileCells.Add(c);
}
}
else if (a == "hz" && i + 1 < args.Length)
foreach (string t in args[++i].Split(',', StringSplitOptions.RemoveEmptyEntries))
extra.Add(uint.Parse(t.Replace("0x", ""), NumberStyles.HexNumber));
else if (a.Length <= 6 && uint.TryParse(a.Replace("0x", ""), NumberStyles.HexNumber, null, out uint v)) lb = v;
else if (a.Length == 8 && uint.TryParse(a, NumberStyles.HexNumber, null, out uint s)) starts.Add(s);
else acDir = a;
}
// Low-16 ids become full cell ids of this landblock.
extra = extra.Select(c => c <= 0xFFFF ? (lb << 16) | c : c).ToHashSet();
var loader = new GeometryLoader();
if (!loader.Initialize(acDir)) { Console.WriteLine("Geometry loader failed: " + loader.StatusMessage); return 1; }
var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat);
var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS);
var surfaceCells = DungeonHazardSurfaces.ComputeHazardCells(lb, loader.CellDat, loader.PortalDat);
Console.WriteLine($"Landblock 0x{lb:X4}: {graph.Count} cells; hazard textures {DungeonHazardSurfaces.HazardTextureCount} -> {surfaceCells.Count} Detector C cells: {Ids(surfaceCells)}");
if (fileCells.Count > 0) Console.WriteLine($" hzfile cells: {Ids(fileCells)}");
if (extra.Count > 0) Console.WriteLine($" hz cells: {Ids(extra)}");
if (starts.Count == 0) starts.Add(graph.Keys.Min());
var sets = new List<(string Name, HashSet<uint> Cells)>();
var given = new HashSet<uint>(fileCells.Concat(extra));
if (compare)
{
sets.Add(("none", new HashSet<uint>()));
sets.Add(("surface", new HashSet<uint>(surfaceCells)));
if (given.Count > 0) sets.Add(("file+hz", new HashSet<uint>(given)));
if (given.Count > 0) sets.Add(("all", new HashSet<uint>(surfaceCells.Concat(given))));
}
else
{
var cells = new HashSet<uint>(given);
if (surface) cells.UnionWith(surfaceCells);
sets.Add((surface ? (given.Count > 0 ? "all" : "surface") : given.Count > 0 ? "file+hz" : "none", cells));
}
foreach (uint s0 in starts)
foreach (var (name, cells) in sets)
{
uint start = s0;
IReadOnlySet<uint> hazards = cells.Count > 0 ? cells : null;
if (hazards != null && hazards.Contains(start))
{
uint safe = DungeonPathfinder.NearestSafeCell(graph, start, hazards);
if (safe != 0) start = safe;
}
var log = new Dictionary<NavPoint, DungeonPathfinder.PatrolPointInfo>(ReferenceEqualityComparer.Instance);
DungeonPathfinder.PointLog = log;
NavRouteParser route;
try { route = DungeonPathfinder.BuildPatrolRoute(graph, start, hazards, geo); }
finally { DungeonPathfinder.PointLog = null; }
var lines = DungeonPathfinder.DescribePatrol(route, graph, geo, hazards, log);
Console.WriteLine();
Console.WriteLine($"== start {s0:X8}{(start != s0 ? $" (moved to safe {start:X8})" : "")}, hazards {name} ({cells.Count})");
Console.WriteLine(" " + EnteredRooms(route, graph, geo, hazards, log));
foreach (string l in lines)
{
bool isSummary = l.StartsWith("wp summary", StringComparison.Ordinal) || l.StartsWith("wp main route", StringComparison.Ordinal);
if (summaryOnly && !isSummary) continue;
if (tinyOnly && !isSummary && !IsTiny(l)) continue;
Console.WriteLine(" " + l);
}
}
return 0;
}
// "room N (k cells)" with k <= 5.
private static bool IsTiny(string line)
{
int at = line.IndexOf(" room ", StringComparison.Ordinal);
if (at < 0) return false;
int open = line.IndexOf('(', at), sp = line.IndexOf(" cells)", at, StringComparison.Ordinal);
return open > 0 && sp > open && int.TryParse(line.AsSpan(open + 1, sp - open - 1), out int n) && n > 0 && n <= 5;
}
// Rooms with at least one waypoint not laid by a look-in, by size.
private static string EnteredRooms(NavRouteParser route, Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo,
IReadOnlySet<uint> hazards, Dictionary<NavPoint, DungeonPathfinder.PatrolPointInfo> log)
{
var rooms = DungeonPathfinder.BuildRooms(graph, geo, hazards);
var entered = new HashSet<int>();
var looked = new HashSet<int>();
foreach (var p in route.Points)
{
log.TryGetValue(p, out var info);
uint cell = info != null && info.Cell != 0 ? info.Cell : DungeonPathfinder.CellAt(graph, geo, p);
if (!rooms.RoomOf.TryGetValue(cell, out int r)) continue;
if (info != null && info.Why.StartsWith("look-in", StringComparison.Ordinal) && info.Room == r) looked.Add(r);
else entered.Add(r);
}
int tiny = entered.Count(r => rooms.Cells[r].Count <= 5);
var tinyList = entered.Where(r => rooms.Cells[r].Count <= 5).OrderBy(r => r)
.Select(r => $"{r}[{string.Join(",", rooms.Cells[r].Select(c => (c & 0xFFFF).ToString("X4")))}]");
return $"rooms entered {entered.Count} (of {rooms.Cells.Count}), of them <= 5 cells: {tiny}: {string.Join(" ", tinyList)}; looked into {looked.Count}";
}
private static string Ids(IEnumerable<uint> cells) => string.Join(",", cells.OrderBy(c => c).Select(c => (c & 0xFFFF).ToString("X4")));
}

View file

@ -63,6 +63,7 @@ internal static class Program
LootCorpseTests.Register(runner);
OwnCorpseTests.Register(runner);
UseRefusalTests.Register(runner);
CorpseKillerTests.Register(runner);
VitalsTests.Register(runner);
MultiTargetTests.Register(runner);
CastSafetyTests.Register(runner);
@ -73,6 +74,7 @@ internal static class Program
UseAtLoginTests.Register(runner);
LearnSpellsTests.Register(runner);
AttackLatencyTests.Register(runner);
TargetingTests.Register(runner);
LootAddItemTests.Register(runner);
GiveTests.Register(runner);
DungeonMapBakeTests.Register(runner);
@ -87,6 +89,7 @@ internal static class Program
ManaStoneChoiceTests.Register(runner);
CustomDebuffTests.Register(runner);
ProfileLoadTests.Register(runner);
ActivityInterfaceTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -0,0 +1,73 @@
using System;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// "RynthAi.Activity" v1 (2026-10-11): the read-only bits RynthSort reads so its pack moves stay
// out of RynthAi's way. The mapping from RynthAi's state is ActivityInterface.Compose; the table
// comes from ActivityInterface.Query (what the engine's GetPluginInterface hands other plugins).
internal static class ActivityInterfaceTests
{
public static void Register(Runner r)
{
r.Add("activity: each arbiter decision maps to its own bit", ArbiterBits);
r.Add("activity: corpse, salvage queue, server wait, crafting and AutoCram add their bits", ExtraBits);
r.Add("activity: the table answers only its own name and versions", QueryTable);
}
private static void ArbiterBits()
{
Check.Eq(ActivityInterface.Compose(BotActivity.Idle, false, false, false, false, false, false), RynthAiActivity.None, "idle, macro off");
Check.Eq(ActivityInterface.Compose(BotActivity.Idle, true, false, false, false, false, false), RynthAiActivity.MacroRunning, "idle, macro on");
Check.Eq(ActivityInterface.Compose(BotActivity.Buffing, true, false, false, false, false, false),
RynthAiActivity.MacroRunning | RynthAiActivity.Buffing, "buffing");
Check.Eq(ActivityInterface.Compose(BotActivity.Combat, true, false, false, false, false, false),
RynthAiActivity.MacroRunning | RynthAiActivity.Combat, "combat");
Check.Eq(ActivityInterface.Compose(BotActivity.Looting, true, false, false, false, false, false),
RynthAiActivity.MacroRunning | RynthAiActivity.Looting, "looting");
Check.Eq(ActivityInterface.Compose(BotActivity.Salvaging, true, false, false, false, false, false),
RynthAiActivity.MacroRunning | RynthAiActivity.Salvaging, "salvaging");
Check.Eq(ActivityInterface.Compose(BotActivity.Navigating, true, false, false, false, false, false),
RynthAiActivity.MacroRunning | RynthAiActivity.Navigating, "navigating");
}
private static void ExtraBits()
{
// A corpse RynthAi opened or claimed counts as looting whatever the tick's owner is.
RynthAiActivity f = ActivityInterface.Compose(BotActivity.Navigating, true, corpseInHand: true, false, false, false, false);
Check.True((f & RynthAiActivity.Looting) != 0 && (f & RynthAiActivity.Navigating) != 0, "corpse in hand while navigating -> looting too");
f = ActivityInterface.Compose(BotActivity.Combat, true, false, salvageBusy: true, false, false, false);
Check.True((f & RynthAiActivity.Salvaging) != 0, "salvage queue while fighting -> salvaging");
f = ActivityInterface.Compose(BotActivity.Idle, false, false, false, serverWait: true, false, false);
Check.Eq(f, RynthAiActivity.ServerAction, "a player's command waiting on the server, macro off");
f = ActivityInterface.Compose(BotActivity.Idle, true, false, false, false, crafting: true, autoCram: true);
Check.Eq(f, RynthAiActivity.MacroRunning | RynthAiActivity.Crafting | RynthAiActivity.AutoCram, "crafting + AutoCram");
}
private static unsafe void QueryTable()
{
try
{
Check.True(ActivityInterface.Query("RynthAi.Status", 1) == IntPtr.Zero, "another interface's name");
Check.True(ActivityInterface.Query(RynthAiActivityApiV1.InterfaceName, 0) == IntPtr.Zero, "version 0");
Check.True(ActivityInterface.Query(RynthAiActivityApiV1.InterfaceName, 2) == IntPtr.Zero, "a newer version than RynthAi has");
IntPtr p = ActivityInterface.Query(RynthAiActivityApiV1.InterfaceName, 1);
Check.True(p != IntPtr.Zero, "v1 answers");
var t = (RynthAiActivityApiV1*)p;
Check.Eq(t->Version, 1u, "table version");
Check.Eq(t->StructSize, (uint)sizeof(RynthAiActivityApiV1), "table size");
Check.True(t->GetActivityFlags != null, "function filled in");
Check.True(ActivityInterface.Query(RynthAiActivityApiV1.InterfaceName, 1) == p, "the same table on every call");
// No plugin instance (not logged in): not ready, flags cleared.
uint flags = 0xFFFFFFFF;
Check.Eq(t->GetActivityFlags(&flags), 0, "not ready without a logged-in plugin");
Check.Eq(flags, 0u, "flags cleared when not ready");
}
finally
{
ActivityInterface.Release();
}
}
}

View file

@ -0,0 +1,54 @@
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-10-06: Silentkelpie skipped its own kills unopened (Necrolytic Extract left behind). The
// corpse LongDesc had gained "Corpse will decay in 56s" under the "Killed by" line and the killer
// read as "Silentkelpie.\nCorpse will decay in 56s", which never matches the character name.
internal static class CorpseKillerTests
{
public static void Register(Runner r)
{
r.Add("corpse killer: plain 'Killed by X.'", Plain);
r.Add("corpse killer: decay line after the killer is ignored", DecayLineIgnored);
r.Add("corpse killer: CRLF and multi-word names", CrLfMultiWord);
r.Add("corpse killer: no 'Killed by' line reads as unknown", Missing);
r.Add("corpse killer: radar column reads the same name", RadarMatches);
}
private static void Plain()
{
Check.Eq(RynthAiPlugin.ExtractCorpseKillerName("Killed by Silentkelpie."), "Silentkelpie", "plain line");
Check.Eq(RynthAiPlugin.ExtractCorpseKillerName("Killed by Silentkelpie"), "Silentkelpie", "no trailing period");
}
private static void DecayLineIgnored()
{
Check.Eq(RynthAiPlugin.ExtractCorpseKillerName("Killed by Silentkelpie.\nCorpse will decay in 56s"),
"Silentkelpie", "LF decay line");
Check.Eq(RynthAiPlugin.ExtractCorpseKillerName("Killed by Silentkelpie.\n\nCorpse will decay in 4m 12s."),
"Silentkelpie", "blank line then decay line");
}
private static void CrLfMultiWord()
{
Check.Eq(RynthAiPlugin.ExtractCorpseKillerName("Killed by Moreck II.\r\nCorpse will decay in 3m 10s"),
"Moreck II", "CRLF and a roman-numeral suffix");
}
private static void Missing()
{
Check.Null(RynthAiPlugin.ExtractCorpseKillerName(""), "empty LongDesc");
Check.Null(RynthAiPlugin.ExtractCorpseKillerName(null), "null LongDesc");
Check.Null(RynthAiPlugin.ExtractCorpseKillerName("Corpse will decay in 56s"), "decay line only");
Check.Null(RynthAiPlugin.ExtractCorpseKillerName("Killed by .\nCorpse will decay in 56s"), "empty killer");
}
private static void RadarMatches()
{
Check.Eq(RynthRadarUi.ExtractKiller("Killed by Silentkelpie.\nCorpse will decay in 56s"), "Silentkelpie", "radar decay line");
Check.Eq(RynthRadarUi.ExtractKiller(null), "", "radar unknown is empty");
}
}

View file

@ -25,7 +25,7 @@ internal static class HazardEscapeTests
r.Add("hazard: the hotspot damage line is read (amount, source); other lines are not", Parse);
r.Add("hazard: a hit stops everything and walks back along the footsteps, then hands back", EscapeAlongFootsteps);
r.Add("hazard: hurt again where it stopped - it goes further back", FurtherBack);
r.Add("hazard: macro off - the cell is still learned, nothing moves", MacroOff);
r.Add("hazard: macro off - nothing moves, nothing learned", MacroOff);
r.Add("hazard: Escape Acid and Lava off - no escape and nothing learned (some walk through acid)", SettingOff);
}
@ -85,7 +85,7 @@ internal static class HazardEscapeTests
b.Hit();
Check.True(b.P.HazardEscaping, "the hit starts the escape");
Check.True(b.Cache.IsHazardCell(CellB), "the cell it was hurt in is a hazard now");
Check.False(b.Cache.IsHazardCell(CellB), "the cell it was hurt in is not a patrol hazard (patrol as before 10-07)");
Check.True(b.Hold(), "the escape owns the tick (nothing else runs)");
Check.True(FakeHost.AutoRun, "running");
@ -134,7 +134,7 @@ internal static class HazardEscapeTests
b.S.IsMacroRunning = false;
for (int i = 0; i <= 6; i++) b.At(CellA, 60f, -185f + i);
b.Hit();
Check.True(b.Cache.IsHazardCell(CellA), "the cell is learned");
Check.False(b.Cache.IsHazardCell(CellA), "the cell is not learned");
Check.False(b.P.HazardEscaping, "but nothing moves the character while you play it");
Check.False(b.Hold(), "and the tick is not held");
}

View file

@ -40,6 +40,7 @@ internal static class LootSalvageTests
r.Add("salvage: an item queued before it reaches the pack waits, then is salvaged", SalvageWaitsForArrival);
r.Add("salvage: a pickup whose confirm was lost is still salvaged (tracked + sweep)", SalvageLostConfirm);
r.Add("salvage: no UST keeps the items until one is in the pack", SalvageNoUstKeepsItems);
r.Add("salvage: no UST - HasUst false, no combine sweep; a UST in the pack turns both on", SalvageNoUstNoSweep);
r.Add("salvage: skipped items are logged with their reason, once per batch", SalvageSkipReasonsLogged);
r.Add("salvage: an item that keeps failing rests, retries, and is given up with a log line", SalvageGiveUpIsBounded);
}
@ -287,6 +288,24 @@ internal static class LootSalvageTests
Check.True(items.All(id => !w.InWorld(id)), "every item salvaged");
}
private static void SalvageNoUstNoSweep()
{
var w = new World(Items(0), withUst: false);
w.Settings.EnableCombineSalvage = true;
Check.False(w.Mgr.HasUst(), "no UST carried");
w.Run(65_000, step: 500);
Check.False(w.SalvageLogs.Any(l => l.Contains("Combine sweep", StringComparison.Ordinal)), "no combine sweep without a UST");
Check.Eq(FakeHost.Uses.Count, 0, "nothing used");
var ids = new List<uint>();
World.AddUst(ids);
_ = w.Cache[unchecked((int)Ust)];
w.Run(4_000, step: 500);
Check.True(w.Mgr.HasUst(), "a UST in the pack is seen (within the 3 s cache)");
w.Run(31_000, step: 500);
Check.True(w.SalvageLogs.Any(l => l.Contains("Combine sweep", StringComparison.Ordinal)), "the combine sweep runs again");
}
private static void SalvageSkipReasonsLogged()
{
uint good = ItemBase + 1, retained = ItemBase + 2, listed = ItemBase + 3;

View file

@ -1,3 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
@ -14,6 +17,149 @@ internal static class ManaStoneChoiceTests
{
r.Add("mana stones: only ordinary stones and charges are used; special stones only when a rule names them", OrdinaryOnly);
r.Add("mana stones: with tapping off, charged stones and Mana Charges still refill worn gear", RefillWithoutTapping);
r.Add("mana stones: a stone the server called charged refills worn gear though its charge can't be read", KnownChargedRefills);
r.Add("mana stones: a stone just drained refills worn gear though its read still says empty", DrainedStoneRefills);
r.Add("mana stones: a stone that gave its mana is not used again; 'fully charged' holds refills", GaveManaNotReused);
r.Add("mana stones: tapping off, a stone whose charge can't be read is identified, then used", UnreadableStoneIdentified);
}
// ── Refill rig (2026-10-11) ───────────────────────────────────────────
// A stone's charge is read from its last appraisal; the server never sends a change to it.
// 2026-10-10: five charged stones whose charge couldn't be read were tried as empty stones
// ("The Ring is already full of mana."), marked known-charged, and then never used on a worn
// Khanda-handled Mace at 0% for over an hour. 2026-10-08: a stone that had just given its mana
// still read charged and was used again, cancelled by the server, timed out and parked.
private const uint Player = 0x50000E01;
private const uint StoneA = 0x80400001, StoneB = 0x80400002, StoneC = 0x80400003;
private const uint Mace = 0x80400010, Ring = 0x80400020;
private const uint CurManaKey = 107, MaxManaKey = 108, WieldedSlotKey = 10;
private sealed class Rig : IDisposable
{
public long Now = 1_000_000;
public readonly LegacyUiSettings S;
public readonly ManaStoneManager M;
/// <param name="stones">Stone id and its charge read (null = can't be read).</param>
public Rig(bool tapping, (uint Id, int? Mana)[] stones, bool ringToDrain = false)
{
FakeHost.Reset();
FakeHost.UseOnCalls = true;
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.Names[Player] = "Stone Tester";
foreach (var (id, mana) in stones)
{
FakeHost.Names[id] = "Moderate Mana Stone";
FakeHost.Containers[id] = Player;
SetMana(id, mana);
}
FakeHost.Names[Mace] = "Khanda-handled Mace";
FakeHost.Wielders[Mace] = Player;
FakeHost.Ints[(Mace, WieldedSlotKey)] = 0x100000;
FakeHost.Ints[(Mace, MaxManaKey)] = 5000;
FakeHost.Ints[(Mace, CurManaKey)] = 0; // and it keeps reading 0: worn-item mana is an appraisal too
var ids = new List<uint>();
foreach (var st in stones) ids.Add(st.Id);
ids.Add(Mace);
if (ringToDrain)
{
FakeHost.Names[Ring] = "Ring";
FakeHost.Containers[Ring] = Player;
FakeHost.Ints[(Ring, MaxManaKey)] = 4000;
FakeHost.Ints[(Ring, CurManaKey)] = 4000;
ids.Add(Ring);
}
var host = FakeHost.Create(Player);
var cache = FakeHost.MakeCache(host, Player, ids);
S = new LegacyUiSettings { EnableManaTapping = tapping, ManaTapMinMana = 100 };
S.IsMacroRunning = true;
ManaStoneManager.Clock = () => Now;
M = new ManaStoneManager(host, S, cache);
if (ringToDrain) M.MarkLootedForTap(unchecked((int)Ring));
}
public static void SetMana(uint id, int? mana)
{
if (mana == null) FakeHost.Ints.Remove((id, CurManaKey));
else FakeHost.Ints[(id, CurManaKey)] = mana.Value;
}
public void Run(long ms)
{
for (long t = 0; t < ms; t += 100)
{
Now += 100;
M.OnHeartbeat(0);
}
}
public void Chat(string line) => M.OnChatWindowText(line);
public List<uint> OnPlayer => FakeHost.UsesOn.Where(u => u.Target == Player).Select(u => u.Source).ToList();
public List<uint> OnRing => FakeHost.UsesOn.Where(u => u.Target == Ring).Select(u => u.Source).ToList();
public void Dispose() => ManaStoneManager.Clock = static () => Environment.TickCount64;
}
private static void KnownChargedRefills()
{
using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null), (StoneB, null) }, ringToDrain: true);
rig.Run(1000);
Check.Eq(rig.OnRing.Count, 1, "an unreadable stone is tried as the empty stone for the looted ring");
rig.Chat("The Ring is already full of mana.");
rig.Run(1000);
Check.Eq(rig.OnRing.Count, 2, "the next unreadable stone is tried");
Check.True(rig.OnRing[0] != rig.OnRing[1], "a different stone");
rig.Chat("The Ring is already full of mana.");
rig.Run(1000);
Check.Eq(rig.OnRing.Count, 2, "no stone left to drain into");
Check.Eq(rig.OnPlayer.Count, 1, "a stone the server called charged refills the 0% mace");
}
private static void DrainedStoneRefills()
{
using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null) }, ringToDrain: true);
rig.Run(1000);
Check.Eq(rig.OnRing.Count, 1, "the empty stone drains the looted ring");
rig.Chat("The Mana Stone drains 3,600 points of mana from the Ring.\nThe Ring is destroyed.");
rig.Run(1000);
Check.Eq(rig.OnPlayer.Count, 1, "the stone it just charged refills the 0% mace");
Check.Eq(rig.OnPlayer.FirstOrDefault(), StoneA, "that stone");
}
private static void GaveManaNotReused()
{
using var rig = new Rig(tapping: false, new (uint, int?)[] { (StoneA, 3000), (StoneB, 2000), (StoneC, 1000) });
rig.Run(1000);
Check.Eq(rig.OnPlayer.Count, 1, "the fullest stone refills the mace");
Check.Eq(rig.OnPlayer[0], StoneA, "stone A (3000)");
rig.Chat("The Mana Stone gives 3,000 points of mana to the following items: Khanda-handled Mace.\nYou need 2,000 more mana to fully charge your items.");
rig.Run(1000);
Check.Eq(rig.OnPlayer.Count, 2, "the gear still needs mana: the next stone");
Check.Eq(rig.OnPlayer[1], StoneB, "stone B, not A again (A's read still says 3000)");
rig.Chat("The Mana Stone gives 2,000 points of mana to the following items: Khanda-handled Mace.\nYour items are fully charged.");
rig.Run(60_000);
Check.Eq(rig.OnPlayer.Count, 2, "fully charged: no stone for a while though the mace still reads 0%");
rig.Run(70_000);
Check.Eq(rig.OnPlayer.Count, 3, "after the hold the stale read is tried once more");
Check.Eq(rig.OnPlayer[2], StoneC, "with stone C");
rig.Chat("You have no items equipped that need mana.");
rig.Run(60_000);
Check.Eq(rig.OnPlayer.Count, 3, "the server says nothing needs mana: held again, C kept");
}
private static void UnreadableStoneIdentified()
{
using var rig = new Rig(tapping: false, new (uint, int?)[] { (StoneA, null) });
rig.Run(1000);
Check.True(FakeHost.IdRequests.Contains(StoneA), "the stone whose charge can't be read is identified");
Check.Eq(rig.OnPlayer.Count, 0, "not used before its charge is known");
Rig.SetMana(StoneA, 3000); // the appraisal lands
rig.Run(6000);
Check.Eq(rig.OnPlayer.Count, 1, "then it refills the mace");
Check.Eq(FakeHost.IdRequests.Count(i => i == StoneA), 1, "identified once");
}
private static void OrdinaryOnly()

View file

@ -26,6 +26,33 @@ namespace RynthCore.RynthAiHostTests.Tests;
// inside corner gets a corner.
internal static class PatrolDoorwayTests
{
// 2026-10-10, 0x6146: hazards cut the loops and the patrol fell back to every dead end. Now,
// in that case, only short spurs (closets) go: a junction J with a 1-cell closet, a 3-cell
// spur and a 5-cell branch hanging off a loop.
private static void TrimShortSpurs()
{
var g = new Dictionary<uint, DungeonNavNode>();
void Link(uint a, uint b)
{
foreach (uint c in new[] { a, b })
if (!g.ContainsKey(c)) g[c] = new DungeonNavNode { CellId = c, NS = (c & 0xFF) * 0.01, EW = (c >> 8 & 0xFF) * 0.01 };
g[a].Neighbors.Add(b); g[b].Neighbors.Add(a);
}
// Loop 1-2-3-4, J = 1.
Link(0x01, 0x02); Link(0x02, 0x03); Link(0x03, 0x04); Link(0x04, 0x01);
Link(0x01, 0x10); // closet
Link(0x01, 0x20); Link(0x20, 0x21); Link(0x21, 0x22); // 3-cell spur
Link(0x02, 0x30); Link(0x30, 0x31); Link(0x31, 0x32); Link(0x32, 0x33); Link(0x33, 0x34); // 5-cell branch
var all = new HashSet<uint>(g.Keys);
var kept = DungeonPathfinder.TrimShortSpurs(g, all, 0x03, DungeonPathfinder.PatrolMaxSpurCells);
Check.False(kept.Contains(0x10), "the 1-cell closet goes");
Check.False(kept.Overlaps(new uint[] { 0x20, 0x21, 0x22 }), "the 3-cell spur goes");
Check.True(kept.IsSupersetOf(new uint[] { 0x30, 0x31, 0x32, 0x33, 0x34 }), "the 5-cell branch stays whole");
Check.True(kept.IsSupersetOf(new uint[] { 1, 2, 3, 4 }), "the loop stays");
var keepStart = DungeonPathfinder.TrimShortSpurs(g, all, 0x10, DungeonPathfinder.PatrolMaxSpurCells);
Check.True(keepStart.Contains(0x10), "the start cell is never trimmed");
}
public static void Register(Runner r)
{
r.Add("dungeon doorways: an opening's centre, facing and width come from its portal polygons", DoorwayFromPortals);
@ -38,6 +65,7 @@ internal static class PatrolDoorwayTests
r.Add("dungeon patrol: a loop through a big room: no points inside it, every doorway taken", PatrolLoop);
r.Add("dungeon patrol: a big dead-end room is looked into, not skirted", PatrolLooksIntoDeadEndRoom);
r.Add("dungeon floors: a ceiling (facing down) is not a floor", CeilingIsNotFloor);
r.Add("dungeon patrol: spurs of up to 3 cells trimmed, a long branch kept whole", TrimShortSpurs);
r.Add("dungeon clearance: walls, floor edges and slopes too steep to stand on bound it; a face high above doesn't", ClearanceMeasure);
r.Add("dungeon clearance: a point next to a wall (or past the floor's edge) is pushed out to 1 m", PushedOffWall);
r.Add("dungeon clearance: a point in a corridor narrower than 2 m ends on its middle line", NarrowCorridorCentred);

View file

@ -0,0 +1,286 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Combat target selection (2026-10-10): the Targeting setting (lowest health, closest, farthest,
// least turning) and Target Lock. Combat used to switch targets mid-fight on a blended score; now
// a locked target is kept until it dies or goes, leaves Monster Range, or a higher-priority
// monster is in range, and with the lock off a switch needs a clear margin under the rule.
internal static class TargetingTests
{
private const uint Player = 0x50000E01;
private const uint Lb = 0xA9B40000;
private const uint A = 0x80000401, B = 0x80000402, C = 0x80000403, Boss = 0x80000404;
private const int LowestHealth = 0, Closest = 1, Farthest = 2, LeastTurning = 3;
public static void Register(Runner r)
{
r.Add("targeting: each scheme picks its monster", SchemesPick);
r.Add("targeting: unknown health counts as full; ties go to the closest, then the lower id", UnknownHealthAndTies);
r.Add("targeting: Target Lock keeps the target when a better one of its tier appears", LockKeeps);
r.Add("targeting: Target Lock lets go when the target goes (after the scan grace)", LockReleasesWhenGone);
r.Add("targeting: Target Lock lets go when the target leaves Monster Range", LockReleasesOutOfRange);
r.Add("targeting: a higher-priority monster in range takes over, lock or not", HigherPriorityWins);
r.Add("targeting: lock off switches only past each scheme's margin", LockOffMargins);
r.Add("targeting: lock off never switches with an attack at the target in flight", NoSwitchInFlight);
r.Add("targeting: settings default to lowest health with the lock on", Defaults);
}
// ── Schemes ───────────────────────────────────────────────────────────────
private static void SchemesPick()
{
// A: close, facing away, lightly wounded. B: mid, nearly ahead, badly wounded.
// C: far, health unknown.
var health = new Dictionary<uint, float> { [A] = 0.8f, [B] = 0.3f };
(uint, double, double)[] scan = { (A, 2, 90), (B, 4, 10), (C, 6, 50) };
Check.Eq(new Rig(LowestHealth, true, health).Pick(scan), B, "lowest health: B at 30%");
Check.Eq(new Rig(Closest, true, health).Pick(scan), A, "closest: A at 2 m");
Check.Eq(new Rig(Farthest, true, health).Pick(scan), C, "farthest: C at 6 m");
Check.Eq(new Rig(LeastTurning, true, health).Pick(scan), B, "least turning: B, 10 degrees off");
var t = new Rig(LeastTurning, true, health);
t.Pick((A, 2, 90), (B, 4, 60), (C, 6, 5));
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] lock 0x80000403") && l.Contains("least turning: turn 5 deg")),
"the lock line names the scheme and the deciding value");
}
private static void UnknownHealthAndTies()
{
// B is at 95%, A unknown: unknown counts as full, so B is the more wounded.
var t = new Rig(LowestHealth, true, new Dictionary<uint, float> { [B] = 0.95f });
Check.Eq(t.Pick((A, 2, 0), (B, 5, 0)), B, "a known 95% beats an unknown (full) health");
// Every health unknown: all tie at full, so the closest.
t = new Rig(LowestHealth, true);
Check.Eq(t.Pick((A, 3, 0), (B, 1.5, 0), (C, 2, 0)), B, "all unknown: the closest");
Check.True(FakeHost.Logs.Any(l => l.Contains("lowest health: health unknown (as full)")), "logged as unknown");
// Same distance: the lower id.
t = new Rig(Closest, true);
Check.Eq(t.Pick((B, 2, 0), (A, 2, 0)), A, "a tie in distance: the lower id");
// Lock off: an unknown-health monster never looks more wounded than the incumbent.
t = new Rig(LowestHealth, false, new Dictionary<uint, float> { [A] = 0.5f });
Check.Eq(t.Pick((A, 3, 0), (B, 1, 0)), A, "A at 50% is picked over an unknown B");
Check.Eq(t.Pick((A, 3, 0), (B, 1, 0), (C, 1, 0)), A, "unknown B and C don't take over");
}
// ── Target Lock ───────────────────────────────────────────────────────────
private static void LockKeeps()
{
var t = new Rig(Closest, true);
Check.Eq(t.Pick((A, 4, 0)), A, "A, alone, is locked");
int before = FakeHost.Logs.Count(l => l.Contains("[CombatTarget]"));
Check.Eq(t.Pick((A, 4, 0), (B, 1, 0)), A, "B walks up to 1 m: the lock keeps A");
Check.Eq(t.Pick((A, 4.5, 30), (B, 0.5, 0), (C, 0.8, 0)), A, "and keeps it with more around");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[CombatTarget]")), before, "nothing new is logged while the lock holds");
t = new Rig(LowestHealth, true, new Dictionary<uint, float> { [A] = 0.7f, [B] = 0.9f });
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "lowest health: A at 70%");
t.Health(B, 0.1f);
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "B drops to 10%: the lock keeps A");
}
private static void LockReleasesWhenGone()
{
var t = new Rig(Closest, true);
Check.Eq(t.Pick((A, 2, 0), (B, 3, 0)), A, "A is locked");
Check.Eq(t.Pick((B, 3, 0)), A, "A blinks out of the scan: kept within the scan grace");
t.Advance(1000);
Check.Eq(t.Pick((B, 3, 0)), A, "still within the 1.5 s grace");
t.Advance(1000);
Check.Eq(t.Pick((B, 3, 0)), B, "gone past the grace: B");
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] switch 0x80000401") && l.Contains("(gone,")),
"the switch says why: gone");
// A kill drops the target outright (DropTarget), and the next pick is fresh.
t = new Rig(Closest, true);
t.Pick((A, 2, 0), (B, 3, 0));
t.Combat.OnKillNotification("Mob A's perforated corpse falls before you!");
Check.Eq(t.Combat.activeTargetId, 0, "the kill drops A");
Check.Eq(t.Pick((B, 3, 0)), B, "and B is locked");
}
private static void LockReleasesOutOfRange()
{
var t = new Rig(Closest, true, monsterRange: 5);
Check.Eq(t.Pick((A, 4, 0), (B, 4.5, 0)), A, "A is locked at 4 m");
Check.Eq(t.Pick((A, 5.5, 0)), A, "A steps past Monster Range, nothing else in range: kept");
Check.Eq(t.Pick((A, 6.5, 0), (B, 4.8, 0)), B, "past Monster Range with B inside it: B");
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] switch 0x80000401") && l.Contains("out of Monster Range, 6.5 m")),
"the switch says why: out of Monster Range");
Check.Eq(t.Pick((A, 3, 0), (B, 4.8, 0)), B, "A coming back closer doesn't take it back (B is locked now)");
}
private static void HigherPriorityWins()
{
foreach (bool lockOn in new[] { true, false })
{
string mode = lockOn ? "lock on" : "lock off";
var t = new Rig(Closest, lockOn, monsterRange: 10);
t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 2 });
Check.Eq(t.Pick((A, 2, 0), (B, 3, 0)), A, $"{mode}: A is locked");
Check.Eq(t.Pick((A, 2, 0), (B, 3, 0), (Boss, 12, 0)), A, $"{mode}: a Boss outside Monster Range doesn't count");
Check.Eq(t.Pick((A, 2, 0), (B, 3, 0), (Boss, 9, 0)), Boss, $"{mode}: the Boss inside Monster Range takes over at once, farther or not");
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] switch 0x80000401") && l.Contains("priority 1 < 2")),
$"{mode}: the switch says why: priority");
Check.Eq(t.Pick((A, 1, 0), (Boss, 9, 0)), Boss, $"{mode}: the Boss is kept over a closer, lower-priority A");
}
}
// ── Lock off ──────────────────────────────────────────────────────────────
private static void LockOffMargins()
{
// Closest: 1.5 m.
var t = new Rig(Closest, false);
Check.Eq(t.Pick((A, 3, 0)), A, "closest: A at 3 m");
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "B 1 m closer: kept");
Check.Eq(t.Pick((A, 3, 0), (B, 1.2, 0)), B, "B 1.8 m closer: switch");
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] switch 0x80000401") && l.Contains("closest: 3.0 m, another is clearly better")
&& l.Contains("-> 0x80000402") && l.Contains("closest: 1.2 m")),
"the switch names the scheme and both values");
// Farthest: 1.5 m.
t = new Rig(Farthest, false, monsterRange: 10);
Check.Eq(t.Pick((A, 8, 0)), A, "farthest: A at 8 m");
Check.Eq(t.Pick((A, 8, 0), (B, 9, 0)), A, "B 1 m farther: kept");
Check.Eq(t.Pick((A, 8, 0), (B, 9.8, 0)), B, "B 1.8 m farther: switch");
// Lowest health: 5 percentage points.
t = new Rig(LowestHealth, false, new Dictionary<uint, float> { [A] = 0.5f, [B] = 0.9f });
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "lowest health: A at 50%");
t.Health(B, 0.47f);
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "B at 47% (3 points lower): kept");
t.Health(B, 0.40f);
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), B, "B at 40% (10 points lower): switch");
// Least turning: 20 degrees.
t = new Rig(LeastTurning, false);
Check.Eq(t.Pick((A, 3, 30)), A, "least turning: A");
Check.Eq(t.Pick((A, 3, 40), (B, 3, 25)), A, "B needs 15 degrees less: kept");
Check.Eq(t.Pick((A, 3, 40), (B, 3, 15)), B, "B needs 25 degrees less: switch");
}
private static void NoSwitchInFlight()
{
// An attack at A with no damage since: held for the flight window.
var t = new Rig(Closest, false);
Check.Eq(t.Pick((A, 3, 0)), A, "A is locked");
t.Combat.RecordOffensiveCast(unchecked((int)A));
Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), A, "a cast at A in flight: B (2.5 m closer) waits");
t.Advance(2000);
Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), A, "still in the 4 s window");
t.Advance(2500);
Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), B, "the window passed with nothing landed: switch");
// Damage landing ends the hold.
t = new Rig(Closest, false);
t.Pick((A, 3, 0));
t.Combat.RecordOffensiveCast(unchecked((int)A));
Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), A, "cast in flight: kept");
t.Combat.ReportDamageOnTarget(unchecked((int)A));
Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), B, "the cast landed: switch");
// A target that never takes damage can't hold it forever under continuous fire.
t = new Rig(Closest, false);
t.Pick((A, 3, 0));
t.Advance(16000);
t.Combat.RecordOffensiveCast(unchecked((int)A));
Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), B, "16 s locked without damage: a fresh cast doesn't hold it");
}
private static void Defaults()
{
var s = new LegacyUiSettings();
Check.Eq(s.TargetSelection, 0, "Targeting: lowest health");
Check.True(s.TargetLock, "Target Lock: on");
var loaded = System.Text.Json.JsonSerializer.Deserialize("{\"MonsterRange\":7}", RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(loaded != null && loaded.TargetLock, "a profile saved before the setting loads the lock as on");
// Profile switch/load copies them (CopySettings is the hand-written field list).
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
var dst = new LegacyUiSettings();
copy.Invoke(null, new object[] { new LegacyUiSettings { TargetSelection = 3, TargetLock = false }, dst });
Check.Eq(dst.TargetSelection, 3, "a profile's Targeting is copied");
Check.False(dst.TargetLock, "and its lock off");
copy.Invoke(null, new object[] { loaded!, dst });
Check.True(dst.TargetLock && dst.TargetSelection == 0, "an old profile loads the defaults");
// Engine Settings face: the payload carries them; an engine without the fields leaves them alone.
s = new LegacyUiSettings { TargetSelection = 2, TargetLock = false };
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)!
.SetValue(dash, new LegacyAdvancedSettingsUi(s)); // BuildSettingsJson reads its crafting state
var sent = System.Text.Json.JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
Check.True(sent != null && sent.TargetSelection == 2 && sent.TargetLock == false, "sent to the engine face");
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
Check.True(s.TargetSelection == 2 && !s.TargetLock, "a save without the fields leaves them alone");
dash.ApplySettingsJson("{\"TargetSelection\":1,\"TargetLock\":true}");
Check.True(s.TargetSelection == 1 && s.TargetLock, "a save with them sets them");
dash.ApplySettingsJson("{\"TargetSelection\":9}");
Check.Eq(s.TargetSelection, 3, "an out-of-range choice is clamped");
}
// ── Rig ───────────────────────────────────────────────────────────────────
private sealed class Rig
{
public readonly CombatManager Combat;
public readonly LegacyUiSettings S;
private readonly WorldObjectCache _cache;
private DateTime _now = DateTime.Now;
public Rig(int scheme, bool targetLock, Dictionary<uint, float>? health = null, int monsterRange = 20)
{
FakeHost.Reset();
Place(Player, "Me", 96, 96, creature: false);
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
Place(A, "Mob A", 96, 98);
Place(B, "Mob B", 96, 99);
Place(C, "Mob C", 96, 100);
Place(Boss, "Boss", 96, 101);
S = new LegacyUiSettings { MonsterRange = monsterRange, TargetSelection = scheme, TargetLock = targetLock };
var host = FakeHost.Create();
_cache = FakeHost.MakeCache(host, Player, new[] { A, B, C, Boss }, health);
Combat = new CombatManager(host, S, _cache);
Combat.SetPlayerId(Player);
Combat.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
Combat.TargetClock = () => _now;
}
public void Health(uint id, float ratio) => _cache.OnUpdateHealth(id, ratio);
public void Advance(double ms) => _now = _now.AddMilliseconds(ms);
/// <summary>One tick: the scan holds these (id, distance m, facing angle deg); returns the target.</summary>
public uint Pick(params (uint Id, double Dist, double Angle)[] scan)
{
Combat.SetScannedTargetsForTests(scan.Select(t => new CombatManager.ScannedTarget
{
Id = unchecked((int)t.Id), Distance = t.Dist, Angle = t.Angle, Bearing = double.NaN, Name = FakeHost.Names[t.Id],
}));
Combat.HandleCombatTrigger();
return unchecked((uint)Combat.activeTargetId);
}
}
private static void Place(uint id, string name, float x, float y, bool creature = true)
{
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f);
if (creature) FakeHost.ItemTypes[id] = 0x10;
}
}

View file

@ -24,6 +24,7 @@ internal static class VitalsTests
r.Add("vitals: profiles without the Stamina to Health keys load today's 30 / 20", StaminaToHealthDefaults);
r.Add("vitals: Re-stam To keeps a started recharge going to its line; off = one recharge as before", RestamTo);
r.Add("vitals: out of Magic stance a listed stamina potion goes before Revitalize; a caster casts first", StaminaPotionFirst);
r.Add("vitals: a listed potion whose stack ran out is drunk from the next stack of that name", ListedPotionNextStack);
r.Add("vitals: after a kit, nothing else heals until the kit's result line lands", KitResultWait);
r.Add("vitals: Heal Self known only above the tier Life Magic allows (vitae) is still cast", HealAboveAllowedTier);
r.Add("vitals: low health wins the arbiter even on a busy tick; backs off when nothing can heal", HealthWinsArbiter);
@ -290,6 +291,36 @@ internal static class VitalsTests
}
}
// Report 2026-10-10: 200+ Stamina Tinctures, and RynthAi stopped drinking them whenever the stack
// the rule was added from ran out, until the player added the next stack by hand.
private static void ListedPotionNextStack()
{
const uint Listed = 0x80001234, NextStack = 0x80005678;
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.CombatModeValue = CombatMode.Melee;
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
FakeHost.Names[NextStack] = "Stamina Tincture"; // the listed stack (Listed) is gone
var host = FakeHost.Create();
var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
GetManaAt = 0, TopOffMana = 0, RestamAt = 30, TopOffStam = 95, UsePotions = true, EnableBuffing = false };
s.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Listed), Name = "Stamina Tincture", Type = "Stamina" });
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, s);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 20, MaxMana = 100, CurrentMana = 100 };
var b = new BuffManager(host, s, sm, vitals);
b.SetCharacterSkills(skills);
b.SetWorldObjectCache(FakeHost.MakeCache(host, Player, new[] { NextStack }));
Check.True(b.CheckVitals(), "stamina 20% acts");
Check.True(FakeHost.Uses.Contains(NextStack), "the next stack of Stamina Tinctures is drunk");
Check.False(FakeHost.Uses.Contains(Listed), "not the stack that ran out");
Check.Eq(FakeHost.Casts.Count, 0, "no Revitalize while a tincture is carried");
}
// Tom, 2026-10-06: one Revitalize often doesn't recover enough stamina.
private static void RestamTo()
{

View file

@ -0,0 +1,252 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthILT.Bounty;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The RynthILT review of SilentKelpie's tracker (2026-10-09). Two promises, checked here on a
// fake clock:
// * rate: at most one "/bounty list" per MinRefreshSeconds (5 s floor, whatever asks: kills,
// award lines every kill, Refresh spam, opening and closing the window), and none while the
// window is closed;
// * hidden chat: only the reply to the tracker's own read is eaten. A /bounty the player types
// is shown, also when it overlaps a read of ours, and our own command coming back through the
// engine's chat bar dispatcher is not mistaken for the player's.
internal static class BountyReviewTests
{
public static void Register(Runner r)
{
r.Add("review: awards on every kill never read more than once per MinRefreshSeconds", AwardsEveryKill);
r.Add("review: Refresh spam and window open/close keep the 5 s floor", RefreshSpamAndToggling);
r.Add("review: a long mixed session: every read 5 s apart and only while the window is open", MixedSession);
r.Add("review: a /bounty list the player types is shown and stands in for the next read", TypedListShown);
r.Add("review: a /bounty the player types during our read: the rest of that read is shown", TypedDuringCapture);
r.Add("review: our own /bounty list coming back through the chat bar is not the player's", OwnEcho);
r.Add("review: command matching and long lines", Matching);
}
private const string Header = "Bounties:";
private const string Line = " Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills.";
private const string Footer = "Bounty: type /bounty to see the bounties where you stand.";
private sealed class Rig
{
public long Ms = 1_000_000;
public readonly List<long> SentAt = new();
public readonly List<bool> SentWhileOpen = new();
public BountyTracker T = null!;
public bool Open;
private long _lastPollMs;
public void Step(long ms)
{
for (long e = 0; e < ms; e += 250)
{
Ms += 250;
if (Open && Ms - _lastPollMs >= 1000) { T.BuildJson(); _lastPollMs = Ms; }
T.Tick();
}
}
/// <summary>The server answers our read at once (header, a line, footer).</summary>
public void Reply()
{
T.OnChat(Header);
T.OnChat(Line);
T.OnChat(Footer);
}
}
private static Rig New(int minRefreshSeconds = 5)
{
var rig = new Rig();
rig.T = new BountyTracker(cmd =>
{
if (cmd != BountyTracker.ListCommand) return;
rig.SentAt.Add(rig.Ms);
rig.SentWhileOpen.Add(rig.T.WindowOpen);
}, _ => { }, _ => { }, string.Empty, () => rig.Ms);
rig.T.Command($"set minrefreshseconds {minRefreshSeconds}");
return rig;
}
private static long MinGap(List<long> at)
{
long min = long.MaxValue;
for (int i = 1; i < at.Count; i++) min = Math.Min(min, at[i] - at[i - 1]);
return min;
}
private static void AwardsEveryKill()
{
var rig = New(minRefreshSeconds: 10);
rig.Open = true;
// A 1-kill bounty with no cooldown: every kill prints an award, for two minutes.
for (int s = 0; s < 120; s++)
{
rig.T.OnKill();
rig.T.OnChat("Bounty complete! +1 Ascension Coin gained.");
rig.T.OnChat("Next bounty requires 1 kill.");
rig.Step(1000);
if (rig.T.Reading) rig.Reply();
}
Check.True(rig.SentAt.Count >= 2, $"it still reads ({rig.SentAt.Count} reads)");
Check.True(rig.SentAt.Count <= 13, $"at most one read per 10 s over 120 s ({rig.SentAt.Count} reads)");
Check.True(MinGap(rig.SentAt) >= 10_000, $"reads at least MinRefreshSeconds apart (min gap {MinGap(rig.SentAt)} ms)");
}
private static void RefreshSpamAndToggling()
{
var rig = New(minRefreshSeconds: 30);
rig.Open = true;
rig.Step(500);
rig.Reply();
Check.Eq(rig.SentAt.Count, 1, "opening reads once");
// Refresh clicked every half second for 20 s: manual reads keep the 5 s floor.
for (int i = 0; i < 40; i++)
{
rig.T.Command("refresh");
rig.Step(500);
if (rig.T.Reading) rig.Reply();
}
Check.True(rig.SentAt.Count <= 5, $"20 s of Refresh spam: at most 4 more reads ({rig.SentAt.Count} in all)");
Check.True(MinGap(rig.SentAt) >= 5_000, $"manual reads at least 5 s apart (min gap {MinGap(rig.SentAt)} ms)");
// Kills while closed, then the window toggled open and shut every 4 s for a minute.
int before = rig.SentAt.Count;
for (int i = 0; i < 15; i++)
{
rig.Open = false;
rig.T.OnKill();
rig.Step(4000);
rig.Open = true;
rig.Step(1000);
if (rig.T.Reading) rig.Reply();
}
Check.True(rig.SentAt.Count - before <= 3, $"open/close every 5 s for 75 s with MinRefreshSeconds 30: at most 3 reads ({rig.SentAt.Count - before})");
Check.True(MinGap(rig.SentAt) >= 5_000, "and never two within 5 s");
Check.True(rig.SentWhileOpen.All(o => o), "every read went out with the window open");
}
private static void MixedSession()
{
var rig = New(minRefreshSeconds: 5);
var rnd = new Random(20261009);
for (int s = 0; s < 1800; s++) // 30 minutes
{
if (s % 120 == 0) rig.Open = !rig.Open;
int roll = rnd.Next(100);
if (roll < 30) rig.T.OnKill();
else if (roll < 35) rig.T.OnChat("Bounty complete! +1 Ascension Coin gained.");
else if (roll < 37) rig.T.Command("refresh");
else if (roll < 38) rig.T.OnChat("Bounty unlocked: Ascension Coin - 1 kill required.");
rig.Step(1000);
if (rig.T.Reading && rnd.Next(4) != 0) rig.Reply(); // now and then the server says nothing
}
Check.True(rig.SentAt.Count > 10, $"reads happened ({rig.SentAt.Count})");
Check.True(MinGap(rig.SentAt) >= 5_000, $"every read at least 5 s after the last (min gap {MinGap(rig.SentAt)} ms)");
Check.True(rig.SentWhileOpen.All(o => o), "every read went out with the window open");
}
private static void TypedListShown()
{
var rig = New(minRefreshSeconds: 5);
rig.Open = true;
rig.Step(500);
rig.Reply();
Check.Eq(rig.SentAt.Count, 1, "first read");
rig.Step(10_000);
// The player types /bounty list: the reply is shown (nothing eaten) and still applied.
rig.T.NoteTypedCommand("/bounty list");
Check.True(rig.T.Reading, "the typed list is captured (shown)");
Check.False(rig.T.OnChat(Header), "typed reply: the header stays in chat");
Check.False(rig.T.OnChat(" Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills."), "typed reply: the lines stay in chat");
Check.False(rig.T.OnChat(Footer), "typed reply: the footer stays in chat");
Check.False(rig.T.Reading, "and the footer ends it");
Check.Eq(rig.T.State.Entries.Count, 1, "the typed reply fills the list");
// It counts as the latest read: a kill right after waits the full interval.
rig.T.OnKill();
rig.Step(4000);
Check.Eq(rig.SentAt.Count, 1, "no read of ours on top of the player's");
rig.Step(2000);
Check.Eq(rig.SentAt.Count, 2, "the kill's read comes MinRefreshSeconds after the typed one");
Check.True(rig.T.OnChat(Header) && rig.T.OnChat(Line) && rig.T.OnChat(Footer), "our own read is eaten again");
// "/bounty" (where you stand) output is never eaten.
rig.T.NoteTypedCommand("/bounty");
Check.False(rig.T.OnChat("Bounty: 1 Ascension Coin - 0 of 1 kills."), "a /bounty line stays in chat");
Check.False(rig.T.OnChat("Bounty: there is no bounty here."), "'no bounty here' stays in chat");
}
private static void TypedDuringCapture()
{
var rig = New(minRefreshSeconds: 5);
rig.Open = true;
rig.Step(500);
Check.Eq(rig.SentAt.Count, 1, "our read went out");
rig.T.NoteTypedCommand(BountyTracker.ListCommand); // our own echo first (consumed)
Check.True(rig.T.OnChat(Header), "our reply's header is eaten");
// The player types /bounty list while our reply is still coming in.
rig.Step(250);
rig.T.NoteTypedCommand("/bounty list");
Check.False(rig.T.OnChat(Line), "after the player asked, reward lines are shown");
Check.False(rig.T.OnChat(Footer), "and so is the footer");
Check.False(rig.T.OnChat(Header), "the player's own reply: header shown");
Check.False(rig.T.OnChat(Line), "the player's own reply: line shown");
Check.False(rig.T.OnChat(Footer), "the player's own reply: footer shown");
Check.False(rig.T.OnChat("Bounty complete! +1 Ascension Coin gained."), "award lines are never eaten");
// On a server without /bounty, the player's typed /bounty during our read: the refusal shows.
var rig2 = New();
rig2.Open = true;
rig2.Step(500);
rig2.T.NoteTypedCommand("/bounty");
Check.False(rig2.T.OnChat("Unknown command: bounty"), "the refusal of the player's own /bounty stays in chat");
}
private static void OwnEcho()
{
var rig = New(minRefreshSeconds: 5);
rig.Open = true;
rig.Step(500);
Check.Eq(rig.SentAt.Count, 1, "our read went out");
rig.Step(250);
rig.T.NoteTypedCommand("/bounty list"); // the engine's dispatcher passing our own line back
Check.True(rig.T.OnChat(Header), "our echo is recognised: the reply is still eaten");
Check.True(rig.T.OnChat(Line), "reward lines eaten");
Check.True(rig.T.OnChat(Footer), "footer eaten");
// An echo that comes too late is taken for the player's: that read is shown, never eaten wrongly.
rig.Step(10_000);
Check.Eq(rig.SentAt.Count, 1, "no new read yet (nothing asked)");
rig.T.Command("refresh");
rig.Step(500);
Check.Eq(rig.SentAt.Count, 2, "refresh reads");
rig.Step(3000);
rig.T.NoteTypedCommand("/bounty list");
Check.False(rig.T.OnChat(Header), "a late echo errs on the shown side");
}
private static void Matching()
{
Check.True(BountyTracker.IsBountyCommand("/bounty"), "/bounty");
Check.True(BountyTracker.IsBountyCommand("/bounty list"), "/bounty list");
Check.True(BountyTracker.IsBountyCommand("@Bounty all"), "@bounty all");
Check.False(BountyTracker.IsBountyCommand("/bountyhunter"), "a longer command is not /bounty");
Check.False(BountyTracker.IsBountyCommand("/b hello"), "chat");
Check.True(BountyTracker.IsListCommand("/bounty list") && BountyTracker.IsListCommand("/BOUNTY ALL"), "list commands");
Check.False(BountyTracker.IsListCommand("/bounty") || BountyTracker.IsListCommand("/bounty list now"), "not list commands");
var rig = New();
rig.Open = true;
rig.Step(500);
string longLine = " Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills." + new string(' ', 600) + "x";
Check.False(rig.T.OnChat(longLine), "a line over 512 characters is never eaten or parsed");
}
}

View file

@ -0,0 +1,388 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using RynthCore.Plugin.RynthILT.Bounty;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// ACECustom bounty tracker (2026-10-09). The server keeps the kill counts (BountyProgress is a
// server-only property), so the engine's Bounties window has RynthILT read "/bounty list" quietly
// and parse it. The line formats below are copied from ACECustom BountyManager (ShowAllBounties /
// ShowBounty / Award / NextBountyLine). The tracker runs on a fake clock; the engine's 1 s poll
// of RynthPluginGetBountiesJson is simulated by calling BuildJson.
internal static class BountyTests
{
public static void Register(Runner r)
{
r.Add("bounty: /bounty list lines (counting, cooldown, QB, layers, commas)", ListLines);
r.Add("bounty: /bounty lines, waits and chat events", HereLinesAndEvents);
r.Add("bounty: a full read replaces the list, a partial one updates it", ApplyListRules);
r.Add("bounty: kills and awards stamp the row; an ended cooldown shows 0 kills; state survives a relog", ChangesAndCooldown);
r.Add("bounty: /bounty updates only the one reward it can mean", HereMatching);
r.Add("bounty: an open window reads the list quietly, kills and awards re-read it", WindowReadsAndKills);
r.Add("bounty: closed window sends nothing; unknown command stops reads; no reply times out", ClosedAndUnsupported);
r.Add("bounty: the window's JSON (options, QB filter, closest first) parses in the engine", BridgeJson);
}
// ── Parsing ────────────────────────────────────────────────────────────────
private static void ListLines()
{
Check.True(BountyParse.TryParseListLine(" Lugian Mines: 1 Ascension Coin every 100 kills (at most every 5 min) - you: 34 of 100 kills.", out var a),
"counting line parses (leading indentation)");
Check.Eq(a.Where, "Lugian Mines", "area");
Check.Eq(a.Amount, 1L, "amount");
Check.Eq(a.Item, "Ascension Coin", "item");
Check.Eq(a.KillsRequired, 100, "kills per award");
Check.Eq(a.CooldownSeconds, 300, "cooldown");
Check.Eq(a.Status.Status, BountyStatus.Counting, "status");
Check.Eq(a.Status.Kills, 34, "kills so far");
Check.True(BountyParse.TryParseListLine("All zones: 3 Pyreal Nugget every 1,000 kills (at most every 2 min 30 sec) - you: unlocks in 1 hr 15 sec, then 1,000 kills required.", out var b),
"cooldown line parses");
Check.Eq(b.Where, "All zones", "all-zones area");
Check.Eq(b.KillsRequired, 1000, "N0 kills");
Check.Eq(b.CooldownSeconds, 150, "2 min 30 sec");
Check.Eq(b.Status.Status, BountyStatus.Cooldown, "cooldown status");
Check.Eq(b.Status.WaitSeconds, 3615, "1 hr 15 sec");
Check.Eq(b.Status.KillsRequired, 1000, "kills after the cooldown");
Check.True(BountyParse.TryParseListLine("Valley of Death: 1,500 Trade Note - Large every 1 kill - you: needs 5,000 QB (you have 3,210).", out var c),
"QB line with no cooldown and a hyphenated item parses");
Check.Eq(c.Amount, 1500L, "N0 amount");
Check.Eq(c.Item, "Trade Note - Large", "item keeps its own ' - '");
Check.Eq(c.KillsRequired, 1, "one kill");
Check.Eq(c.CooldownSeconds, 0, "no cooldown");
Check.Eq(c.Status.Status, BountyStatus.NeedsQb, "QB status");
Check.Eq(c.Status.QbRequired, 5000L, "QB needed");
Check.Eq(c.Status.QbHave, 3210L, "QB had");
Check.True(BountyParse.TryParseListLine("Halls of Metos: Lower (layer 2): 2 Ascension Coin every 50 kills - you: 0 of 50 kills.", out var d),
"an area with ': ' and a layer parses");
Check.Eq(d.Where, "Halls of Metos: Lower (layer 2)", "area keeps its colon and layer");
Check.False(BountyParse.TryParseListLine("Bounties:", out _), "the header is not a reward");
Check.False(BountyParse.TryParseListLine("Bounty: type /bounty to see the bounties where you stand.", out _), "the footer is not a reward");
Check.False(BountyParse.TryParseListLine("Bob says, \"Lugian Mines: 1 coin every 100 kills\"", out _), "chat talk is not a reward");
Check.True(BountyParse.IsListTerminator("Bounty: type /bounty to see the bounties where you stand."), "footer ends the reply");
Check.True(BountyParse.IsListTerminator("Bounty: there are no bounties anywhere right now."), "'none anywhere' ends the reply");
Check.True(BountyParse.IsNoBountiesAnywhere("Bounty: there are no bounties anywhere right now."), "'none anywhere' is recognised");
Check.False(BountyParse.IsListTerminator("Bounty: there is no bounty here."), "/bounty's 'none here' is not the list's end");
Check.True(BountyParse.IsUnknownCommand("Unknown command: bounty"), "ACE's unknown-command reply is recognised");
Check.False(BountyParse.IsUnknownCommand("Unknown command: bank"), "another command's reply is not ours");
}
private static void HereLinesAndEvents()
{
Check.True(BountyParse.TryParseHereLine("Bounty: 1 Ascension Coin - 12 of 100 kills.", out var h1), "plain /bounty line");
Check.Eq(h1.Scope, "", "no scope");
Check.Eq(h1.Status.Kills, 12, "kills");
Check.True(BountyParse.TryParseHereLine("Bounty (all zones): 3 Pyreal Nugget - unlocks in 45 sec, then 1 kill required.", out var h2), "all-zones /bounty line");
Check.Eq(h2.Scope, "all zones", "all-zones scope");
Check.Eq(h2.Status.WaitSeconds, 45, "45 sec");
Check.True(BountyParse.TryParseHereLine("Bounty (Thaelaryn Island): 1 Ascension Coin - needs 500 QB (you have 20).", out var h3), "region /bounty line");
Check.Eq(h3.Scope, "Thaelaryn Island", "region scope");
Check.False(BountyParse.TryParseHereLine("Bounty: there is no bounty here.", out _), "'none here' is not a reward");
Check.False(BountyParse.TryParseHereLine("Bounty: +1 Ascension Coin will follow in a moment.", out _), "held notice is not a reward");
Check.Eq(BountyParse.ParseWaitSeconds("5 min"), 300, "5 min");
Check.Eq(BountyParse.ParseWaitSeconds("2 hr 3 min 4 sec"), 7384, "hr min sec");
Check.Eq(BountyParse.ParseWaitSeconds("soon"), 0, "unparseable wait");
Check.True(BountyParse.TryParseEvent("Bounty unlocked: Ascension Coin - 100 kills required.", out var k1, out string item1, out int n1, out _)
&& k1 == BountyEventKind.Unlocked && item1 == "Ascension Coin" && n1 == 100, "unlock event");
Check.True(BountyParse.TryParseEvent("Bounty complete! +3 Pyreal Nuggets gained.", out var k2, out string item2, out _, out _)
&& k2 == BountyEventKind.Complete && item2 == "Pyreal Nuggets", "award event");
Check.True(BountyParse.TryParseEvent("Next bounty unlocks in 2 min 30 sec - 1 kill required.", out var k3, out _, out int n3, out int w3)
&& k3 == BountyEventKind.NextCooldown && n3 == 1 && w3 == 150, "next-cooldown event");
Check.True(BountyParse.TryParseEvent("Next bounty requires 1,000 kills.", out var k4, out _, out int n4, out _)
&& k4 == BountyEventKind.NextReady && n4 == 1000, "next-ready event");
Check.True(BountyParse.TryParseEvent("Bounty: Your inventory is full. +1 Ascension Coin gained (3 total). They're safe until you make room.", out var k5, out _, out _, out _)
&& k5 == BountyEventKind.Held, "held event");
Check.False(BountyParse.TryParseEvent("Bounty: there is no bounty here.", out _, out _, out _, out _), "'none here' is not an event");
Check.False(BountyParse.TryParseEvent("Bounty: 1 Ascension Coin - 12 of 100 kills.", out _, out _, out _, out _), "a status line is not an event");
Check.False(BountyParse.TryParseEvent("Bounty: type /bounty to see the bounties where you stand.", out _, out _, out _, out _), "the footer is not an event");
}
// ── Applying reads ─────────────────────────────────────────────────────────
private static BountyListLine L(string line)
{
Check.True(BountyParse.TryParseListLine(line, out var l), "fixture parses: " + line);
return l;
}
private static void ApplyListRules()
{
var t = New(out _, out _, out _);
var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc);
t.ApplyList(new[]
{
L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."),
L("All zones: 3 Pyreal Nugget every 50 kills - you: 0 of 50 kills."),
}, complete: true, noneAnywhere: false, t0);
Check.Eq(t.State.Entries.Count, 2, "full read: two rewards");
Check.Eq(t.State.ListedUtc, t0, "read time stamped");
// A partial reply (no footer) only updates what it names; the other rows stay.
t.ApplyList(new[] { L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 11 of 100 kills.") },
complete: false, noneAnywhere: false, t0.AddSeconds(5));
Check.Eq(t.State.Entries.Count, 2, "partial read keeps the other row");
Check.Eq(t.State.Entries[0].Kills, 11, "partial read updates the named row in place");
// A full read drops areas that are gone and keeps the server's order.
t.ApplyList(new[]
{
L("Thaelaryn Island: 1 Ascension Coin every 20 kills - you: 4 of 20 kills."),
L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 12 of 100 kills."),
}, complete: true, noneAnywhere: false, t0.AddSeconds(10));
Check.Eq(string.Join(",", t.State.Entries.Select(e => e.Where)), "Thaelaryn Island,Lugian Mines", "server order, removed area gone");
t.ApplyList(Array.Empty<BountyListLine>(), complete: true, noneAnywhere: true, t0.AddSeconds(20));
Check.Eq(t.State.Entries.Count, 0, "'none anywhere' empties the list");
Check.True(t.State.NoneAnywhere, "and says so");
}
private static void ChangesAndCooldown()
{
string file = Path.Combine(Program.TempRoot, "bounty-changes", BountyTracker.FileName);
var t = New(out _, out _, out _, file);
var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc);
const string Head = "Lugian Mines: 1 Ascension Coin every 3 kills (at most every 5 min) - you: ";
t.ApplyList(new[] { L(Head + "1 of 3 kills.") }, true, false, t0);
Check.Eq(t.State.Entries[0].ChangedUtc, default(DateTime), "first sighting is not a change");
t.ApplyList(new[] { L(Head + "2 of 3 kills.") }, true, false, t0.AddSeconds(10));
Check.Eq(t.State.Entries[0].ChangedUtc, t0.AddSeconds(10), "a new kill stamps the row");
t.ApplyList(new[] { L(Head + "unlocks in 5 min, then 3 kills required.") }, true, false, t0.AddSeconds(20));
var e = t.State.Entries[0];
Check.Eq(e.ChangedUtc, t0.AddSeconds(20), "the award stamps the row");
Check.Eq(e.UnlockAtUtc, t0.AddSeconds(320), "unlock time = read time + wait");
Check.Eq(BountyTracker.Effective(e, t0.AddSeconds(100)).Status, BountyStatus.Cooldown, "still cooling down");
var after = BountyTracker.Effective(e, t0.AddSeconds(321));
Check.True(after.Status == BountyStatus.Counting && after.Kills == 0, "after the cooldown: 0 of N kills");
Check.True(BountyTracker.Describe(e, t0.AddSeconds(100)).Contains("unlocks in 3 min 40 sec"), "chat text counts the cooldown down");
// The state survives a relog (the window fills right after login).
t.Command("set hideqblocked 1");
t.Save();
var loaded = New(out _, out _, out _, file);
Check.Eq(loaded.State.Entries.Count, 1, "entries saved per character");
Check.Eq(loaded.State.Entries[0].UnlockAtUtc, t0.AddSeconds(320), "unlock time saved");
Check.True(loaded.State.HideQbLocked, "options saved");
}
private static void HereMatching()
{
var t = New(out _, out _, out _);
var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc);
t.ApplyList(new[]
{
L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."),
L("Halls of Metos: 1 Ascension Coin every 100 kills - you: 50 of 100 kills."),
L("Thaelaryn Island: 2 Ascension Coin every 20 kills - you: 4 of 20 kills."),
L("All zones: 1 Ascension Coin every 100 kills - you: 0 of 100 kills."),
}, true, false, t0);
Check.True(BountyParse.TryParseHereLine("Bounty (Thaelaryn Island): 2 Ascension Coin - 5 of 20 kills.", out var region), "fixture");
Check.True(t.ApplyHere(region, t0.AddSeconds(5)), "a region line names its area");
Check.Eq(t.State.Entries[2].Kills, 5, "region row updated");
Check.True(BountyParse.TryParseHereLine("Bounty (all zones): 1 Ascension Coin - 1 of 100 kills.", out var zones), "fixture");
Check.True(t.ApplyHere(zones, t0.AddSeconds(6)), "an all-zones line names its area");
Check.Eq(t.State.Entries[3].Kills, 1, "all-zones row updated");
Check.True(BountyParse.TryParseHereLine("Bounty: 1 Ascension Coin - 11 of 100 kills.", out var plain), "fixture");
Check.False(t.ApplyHere(plain, t0.AddSeconds(7)), "two dungeons pay the same reward: left alone");
Check.Eq(t.State.Entries[0].Kills, 10, "first dungeon untouched");
Check.Eq(t.State.Entries[1].Kills, 50, "second dungeon untouched");
}
// ── The read loop ──────────────────────────────────────────────────────────
private const string ListReplyCounting = " Lugian Mines: 1 Ascension Coin every 100 kills - you: 34 of 100 kills.";
private const string Footer = "Bounty: type /bounty to see the bounties where you stand.";
private static void WindowReadsAndKills()
{
var t = New(out var clock, out var sent, out _);
t.Command("set minrefreshseconds 5");
Run(t, clock, 500, windowOpen: true);
Check.Eq(Reads(sent), 1, "opening the window reads /bounty list");
Check.True(t.Reading, "a read is in progress");
Check.True(t.OnChat("Bounties:"), "the header is hidden from chat");
Check.True(t.OnChat(ListReplyCounting), "reward lines are hidden from chat");
Check.True(t.OnChat(Footer), "the footer is hidden and ends the read");
Check.False(t.Reading, "the read is over");
Check.Eq(t.State.Entries.Count, 1, "the read fills the list");
Check.Eq(t.State.Entries[0].Kills, 34, "with the player's kills");
// A kill re-reads after the debounce, but not sooner than MinRefreshSeconds after the last read.
t.OnKill();
Run(t, clock, 3000, windowOpen: true);
Check.Eq(Reads(sent), 1, "no re-read inside MinRefreshSeconds");
Run(t, clock, 3000, windowOpen: true);
Check.Eq(Reads(sent), 2, "a kill re-reads the list");
t.OnChat("Bounties:");
t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills - you: 35 of 100 kills.");
t.OnChat(Footer);
Check.Eq(t.State.Entries[0].Kills, 35, "the kill shows up");
Check.True(t.State.Entries[0].ChangedUtc != default, "and the row is highlighted");
// Award lines are shown to the player and also trigger a read, once MinRefreshSeconds
// have passed since the last one (review 2026-10-09: awards used to skip the interval).
Check.False(t.OnChat("Bounty complete! +1 Ascension Coin gained."), "award lines stay in chat");
Check.Eq(t.State.LastEvent, "Bounty complete! +1 Ascension Coin gained.", "the window shows the last event");
Run(t, clock, 2000, windowOpen: true);
Check.Eq(Reads(sent), 2, "the award's re-read waits for MinRefreshSeconds");
Run(t, clock, 3000, windowOpen: true);
Check.Eq(Reads(sent), 3, "an award re-reads the list");
// A reply whose footer never comes ends after a quiet moment, as a partial update.
t.OnChat("Bounties:");
t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills (at most every 5 min) - you: unlocks in 5 min, then 100 kills required.");
Run(t, clock, 2000, windowOpen: true);
Check.False(t.Reading, "a reply without its footer still ends");
Check.Eq(t.State.Entries[0].Status, (int)BountyStatus.Cooldown, "and is applied");
// Lines the player asks for themselves are not hidden but still update the list.
Check.False(t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills - you: 0 of 100 kills."), "a typed /bounty list line stays in chat");
Check.Eq(t.State.Entries[0].Status, (int)BountyStatus.Counting, "and updates the row");
// Closing the window (the engine stops polling; 3 s grace) stops the reads.
Run(t, clock, 5000, windowOpen: false);
int before = Reads(sent);
t.OnKill();
Run(t, clock, 20000, windowOpen: false);
Check.Eq(Reads(sent), before, "no reads once the window is closed");
}
private static void ClosedAndUnsupported()
{
var t = New(out var clock, out var sent, out var chat);
t.Command("set minrefreshseconds 5");
t.OnKill();
Run(t, clock, 10000, windowOpen: false);
Check.Eq(Reads(sent), 0, "closed window: kills send nothing");
Run(t, clock, 500, windowOpen: true);
Check.Eq(Reads(sent), 1, "opening the window reads the list");
Check.True(t.OnChat("Unknown command: bounty"), "the unknown-command reply to our read is hidden");
Check.True(t.Unsupported, "'Unknown command: bounty' marks the server unsupported");
t.OnKill();
Run(t, clock, 10 * 60_000, windowOpen: true);
Check.Eq(Reads(sent), 1, "no automatic reads on an unsupported server, periodic included");
t.HandleChatCommand(new[] { "/ilt", "bountys", "refresh" });
Check.False(t.Unsupported, "a manual refresh tries again");
Run(t, clock, 500, windowOpen: true);
Check.Eq(Reads(sent), 2, "and reads the list");
Check.True(chat.Any(c => c.Contains("Reading /bounty list")), "the command answers in chat");
Run(t, clock, 11000, windowOpen: true);
Check.False(t.Reading, "no reply: the read is abandoned");
Check.True(t.BuildJson().Contains("no reply to /bounty list"), "and the window says so");
// With the window closed a manual refresh sends nothing (review 2026-10-09: reads only
// while the window is open); the next open reads.
Run(t, clock, 5000, windowOpen: false);
Check.True(t.Command("refresh").Contains("window is open"), "a closed-window refresh says why it waits");
Check.Eq(Reads(sent), 2, "a closed-window refresh sends nothing");
Run(t, clock, 500, windowOpen: true);
Check.Eq(Reads(sent), 3, "the next open reads");
chat.Clear();
t.HandleChatCommand(new[] { "/ilt", "bounty" });
Check.True(chat.Any(c => c.Contains("/rc bounties")), "'/ilt bounty' points at the window");
}
private static void BridgeJson()
{
var t = New(out _, out _, out _);
var now = DateTime.UtcNow;
t.ApplyList(new[]
{
L("Valley of Death: 1,500 Trade Note - Large every 1 kill - you: needs 5,000 QB (you have 3,210)."),
L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."),
L("Thaelaryn Island: 2 Ascension Coin every 20 kills (at most every 5 min) - you: unlocks in 2 min, then 20 kills required."),
L("Halls of Metos: 1 Ascension Coin every 10 kills - you: 9 of 10 kills."),
}, true, false, now);
Check.Eq(t.Command("set minrefreshseconds 1"), "", "option accepted");
Check.Eq(t.State.MinRefreshSeconds, BountyTracker.MinRefreshFloorSeconds, "MinRefreshSeconds is clamped to the floor");
t.Command("set periodicminutes 999");
Check.Eq(t.State.PeriodicRefreshMinutes, BountyTracker.PeriodicCeilingMinutes, "PeriodicRefreshMinutes is clamped");
Check.True(t.Command("set nonsense 1").Contains("unknown"), "unknown option is reported");
using (var doc = JsonDocument.Parse(t.BuildJson()))
{
var root = doc.RootElement;
Check.Eq(root.GetProperty("rows").GetArrayLength(), 4, "all rows by default");
Check.Eq(root.GetProperty("rows")[0].GetProperty("where").GetString(), "Valley of Death", "server order by default");
Check.Eq(root.GetProperty("minRefreshSeconds").GetInt32(), 5, "camelCase option names");
}
t.Command("set hideqblocked 1");
t.Command("set sortbyprogress on");
string json = t.BuildJson();
using (var doc = JsonDocument.Parse(json))
{
var rows = doc.RootElement.GetProperty("rows");
Check.Eq(rows.GetArrayLength(), 3, "QB-locked row hidden");
Check.Eq(doc.RootElement.GetProperty("hiddenCount").GetInt32(), 1, "and counted");
Check.Eq(rows[0].GetProperty("where").GetString(), "Halls of Metos", "closest first: 9 of 10");
Check.Eq(rows[2].GetProperty("where").GetString(), "Thaelaryn Island", "cooldowns after counting rows");
}
#if ENGINE_BOUNTIES
var snap = RynthCore.Engine.UI.Data.BountiesSnapshot.Parse(json);
Check.NotNull(snap, "the engine parses the plugin's JSON");
Check.True(snap!.HideQbLocked && snap.SortByProgress, "engine sees the options");
Check.Eq(snap.MinRefreshSeconds, 5, "engine sees MinRefreshSeconds");
Check.Eq(snap.HiddenCount, 1, "engine sees the hidden count");
Check.Eq(snap.Rows.Count, 3, "engine sees the rows");
var cd = snap.Rows.Single(r => r.Where == "Thaelaryn Island");
Check.Eq(cd.Status, (int)RynthCore.Engine.UI.Data.BountyRowStatus.Cooldown, "engine status enum matches the plugin's");
Check.True(cd.UnlockInSec > 100 && cd.UnlockInSec <= 120, $"cooldown seconds left ({cd.UnlockInSec})");
Check.Eq(cd.CooldownSeconds, 300, "cooldown length");
var halls = snap.Rows[0];
Check.True(halls.Kills == 9 && halls.KillsRequired == 10 && halls.Amount == 1 && halls.Item == "Ascension Coin", "row fields");
#endif
}
// ── Helpers ────────────────────────────────────────────────────────────────
private sealed class Clock { public long Ms = 1_000_000; }
private static BountyTracker New(out Clock clock, out List<string> sent, out List<string> chat, string file = "")
{
var c = new Clock();
var s = new List<string>();
var ch = new List<string>();
if (file.Length > 0) Directory.CreateDirectory(Path.GetDirectoryName(file)!);
var t = new BountyTracker(s.Add, ch.Add, _ => { }, file, () => c.Ms);
clock = c;
sent = s;
chat = ch;
return t;
}
private static int Reads(List<string> sent) => sent.Count(x => x == BountyTracker.ListCommand);
/// <summary>Advances the clock in 250 ms steps, ticking; with the window open the engine polls every second.</summary>
private static void Run(BountyTracker t, Clock clock, long ms, bool windowOpen)
{
for (long elapsed = 0; elapsed < ms; elapsed += 250)
{
clock.Ms += 250;
if (windowOpen && elapsed % 1000 == 0) t.BuildJson();
t.Tick();
}
}
}

View file

@ -0,0 +1,28 @@
using System;
using System.IO;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// Offline tests for the RynthILT plugin: the ACECustom bounty tracker (parsing, merging, the
// quiet /bounty list read loop on a fake clock, persistence, the bridge JSON). Each test prints
// PASS / FAIL.
//
// Run: dotnet run -c Release (all tests)
// dotnet run -c Release -- window (tests whose name contains "window")
internal static class Program
{
/// <summary>Scratch folder next to the exe for files tests write. Emptied at start.</summary>
public static string TempRoot { get; } = Path.Combine(AppContext.BaseDirectory, "scratch");
private static int Main(string[] args)
{
if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true);
Directory.CreateDirectory(TempRoot);
var runner = new Runner();
BountyTests.Register(runner);
BountyReviewTests.Register(runner);
return runner.Run("RynthILT tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -0,0 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Tests for the RynthILT plugin's ACECustom bounty tracker (Bounty/BountyParse.cs and
Bounty/BountyTracker.cs, ported from SilentKelpie's rynth/RynthSuite PR #11 with his
BountyTests). The plugin is a NativeAOT x86 library, so its host-agnostic sources are
compiled in here directly instead of referencing the project. File tests use a scratch
folder next to the exe, never %APPDATA%\RynthCore.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail; an argument filters by test name)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>RynthILT.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthILT\Bounty\BountyParse.cs" Link="Plugin\BountyParse.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthILT\Bounty\BountyTracker.cs" Link="Plugin\BountyTracker.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthILT\RynthILTJsonContext.cs" Link="Plugin\RynthILTJsonContext.cs" />
<!-- The RynthAi test tools' check/runner harness (no plugin code in it). -->
<Compile Include="..\RynthCore.RynthAiTests\Harness\Check.cs" Link="Harness\Check.cs" />
<Compile Include="..\RynthCore.RynthAiTests\Harness\Runner.cs" Link="Harness\Runner.cs" />
</ItemGroup>
<!-- The engine's Bounties snapshot reader (self-contained DTOs), so BountyTests checks the plugin's
JSON against the engine's own reader. Optional, so this builds before the engine side is
merged: without the file the round-trip check is compiled out (ENGINE_BOUNTIES). -->
<PropertyGroup Condition="Exists('..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\BountiesSnapshotJson.cs')">
<DefineConstants>$(DefineConstants);ENGINE_BOUNTIES</DefineConstants>
</PropertyGroup>
<ItemGroup Condition="Exists('..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\BountiesSnapshotJson.cs')">
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\BountiesSnapshotJson.cs" Link="Engine\BountiesSnapshotJson.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,996 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using RynthCore.Engine.UI.ScriptWindows;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Ui;
using RynthCore.Plugin.RynthSort.Views;
using RynthCore.Plugin.Shared;
// The engine parser's only outside dependency: the registry's limits (the engine's values).
namespace RynthCore.Engine.UI.ScriptWindows
{
internal static class ScriptWindowRegistry
{
public const int MaxOpsPerWindow = 1500;
public const int MaxBytesPerWindow = 64 * 1024;
public const int MaxWindowsPerOwner = 32;
public const int MaxBytesPerSubmit = 256 * 1024;
}
}
namespace RynthSort.Tests
{
internal static partial class Program
{
private static int _pass, _fail;
private static string _temp = "";
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "Write")]
private static extern int Write(UiHost h);
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_submit")]
private static extern ref byte[] SubmitBuffer(UiHost h);
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "Apply")]
private static extern void Apply(UiHost h, ReadOnlySpan<byte> data);
private static int Main()
{
_temp = Path.Combine(Path.GetTempPath(), "RynthSort.Tests." + Environment.ProcessId);
Directory.CreateDirectory(_temp);
try
{
Run("rules: class and name matching, first match wins", RuleMatching);
Run("classify: item classes as RynthLua sees them", Classify);
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);
Run("plan: missing pack", PlanMissingPack);
Run("plan: tidy and clean", PlanTidyClean);
Run("plan: unpack", PlanUnpack);
Run("gate: stay out of the way", Gates);
Run("gate: RynthAi activity", GatesRynthAi);
Run("gate: quiet time after a pause", GateQuiet);
Run("gate: looting watch", LootWatching);
Run("gate: older RynthAi status JSON", StatusJsonFallback);
Run("moves: answers and back-off", MoveAnswers);
Run("loop: nothing is sent while paused", LoopPaused);
Run("loop: one move at a time, then the gap", LoopOneAtATime);
Run("loop: refusals block the item and back off", LoopRefusals);
Run("loop: too busy and no answer", LoopBusyAndTimeout);
Run("loop: jobs (sort now, tidy, clean, unpack)", LoopJobs);
Run("store: save and load", StoreRoundTrip);
Run("store: Lua script import", StoreLuaImport);
Run("store: odd files", StoreOddFiles);
Run("lua autostart warning", LuaAutostart);
Run("window: display lists parse in the engine", WindowParses);
Run("window: rule editing through events", WindowEvents);
}
finally
{
try { Directory.Delete(_temp, true); } catch { }
}
Console.WriteLine($"{_pass} passed, {_fail} failed");
if (_pass == 0) { Console.WriteLine("ABORT: zero assertions ran."); return 1; }
return _fail == 0 ? 0 : 1;
}
private static void Run(string name, Action test)
{
int before = _fail;
try { test(); }
catch (Exception ex) { _fail++; Console.WriteLine($"FAIL: {name} threw {ex}"); }
Console.WriteLine($" {(before == _fail ? "ok " : "FAIL")} {name}");
}
private static void Check(bool ok, string what)
{
if (ok) _pass++;
else { _fail++; Console.WriteLine("FAIL: " + what); }
}
private static void Eq<T>(T actual, T expected, string what) =>
Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{what}: expected {expected}, got {actual}");
// ── Sample data ─────────────────────────────────────────────────────
private const uint Me = 0x50000001;
private static SortInventory Inv(int packs, int cap = 24, int mainCap = 102)
{
var inv = new SortInventory();
inv.Main.Id = Me;
inv.Main.Name = "Main pack";
inv.Main.Capacity = mainCap;
for (int i = 1; i <= packs; i++)
inv.Packs.Add(new SortPack { Id = 0x40000000u + (uint)i, Name = "Pack " + i, Capacity = cap });
return inv;
}
private static SortItem It(uint id, string name, int cls, uint wcid = 0, int stack = 1, int max = 1) =>
new() { Id = id, Name = name, ObjectClass = cls, Wcid = wcid, Stack = stack, MaxStack = max };
private static void Fill(SortPack p, int count, uint firstId)
{
for (int i = 0; i < count; i++) p.Items.Add(It(firstId + (uint)i, "Junk " + i, ObjectClasses.Misc));
}
private static readonly List<SortRule> Defaults = SortRules.Defaults();
// ── Rules ───────────────────────────────────────────────────────────
private static void RuleMatching()
{
SortItem comp = It(1, "Prismatic Taper", ObjectClasses.SpellComponent);
SortItem salvage = It(2, "Salvaged Iron (100)", ObjectClasses.Salvage);
SortItem gem = It(3, "Black Opal", ObjectClasses.Gem);
SortItem misc = It(4, "Ashcoal", ObjectClasses.Misc);
Check(SortRules.Matches(SortRule.ForClass(ObjectClasses.SpellComponent, 1), comp), "class rule matches its class");
Check(!SortRules.Matches(SortRule.ForClass(ObjectClasses.SpellComponent, 1), salvage), "class rule ignores other classes");
Check(SortRules.Matches(SortRule.ForName("taper", 4), comp), "name rule: part of the name, any case");
Check(!SortRules.Matches(SortRule.ForName("", 4), comp), "an empty name rule matches nothing");
var off = SortRule.ForClass(ObjectClasses.Gem, 3);
off.On = false;
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)");
(rules[0], rules[1]) = (rules[1], rules[0]);
Eq(SortRules.RuleFor(rules, comp)?.Pack, 1, "reordered: the class rule wins");
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");
Eq(ObjectClasses.Label(ObjectClasses.ManaStone), "Mana Stone", "class label");
Eq(ObjectClasses.ChoiceLabels[ObjectClasses.ChoiceIndex(ObjectClasses.WandStaffOrb)], "Wand Staff Orb", "choice label");
Eq(SortRules.Describe(SortRule.ForName("Pyreal", 2)), "name has \"Pyreal\"", "describe name rule");
// The Lua script's numbers mean the same classes (saved rules stay right).
Eq(ObjectClasses.Names[12], "SpellComponent", "12 = SpellComponent");
Eq(ObjectClasses.Names[39], "Salvage", "39 = Salvage");
Eq(ObjectClasses.Names[29], "HealingKit", "29 = HealingKit");
}
private static void Classify()
{
Eq(InventoryReader.ClassifyFrom(0x40000000, 0, "Salvaged Iron", out bool c1), ObjectClasses.Salvage, "tinkering material = salvage");
Check(c1, "certain with a type");
Eq(InventoryReader.ClassifyFrom(0x00001000, 0, "Prismatic Taper", out _), ObjectClasses.SpellComponent, "spell component");
Eq(InventoryReader.ClassifyFrom(0x00080000 | 0x00000080, 0, "Mana Stone", out _), ObjectClasses.ManaStone, "mana stone before misc");
Eq(InventoryReader.ClassifyFrom(0x00000080, 0x10000, "Healing Kit", out _), ObjectClasses.HealingKit, "healer bit = healing kit");
Eq(InventoryReader.ClassifyFrom(0x00000080, 0x20000, "Lockpick", out _), ObjectClasses.Lockpick, "lockpick bit");
Eq(InventoryReader.ClassifyFrom(0x00002000, 0, "Scroll of Strength Self VII", out _), ObjectClasses.Scroll, "writable named Scroll = scroll");
Eq(InventoryReader.ClassifyFrom(0x00000200, 0, "Foci of Enchantment", out _), ObjectClasses.Foci, "foci by name");
Eq(InventoryReader.ClassifyFrom(0x00000080, 0x8000, "Apple", out _), ObjectClasses.Food, "misc with the food bit = food");
Eq(InventoryReader.ClassifyFrom(0, 0, "", out bool c2), ObjectClasses.Unknown, "no data");
Check(!c2, "not certain without data (read again later)");
}
// ── Planner ─────────────────────────────────────────────────────────
private static void PlanSettle()
{
var p = new SortPlanner();
SortInventory inv = Inv(3);
inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
List<SortMove> m = p.Plan(inv, Defaults, SortScope.Main, false, 1000, 5000);
Eq(m.Count, 0, "a new item waits for the settle time");
Eq(p.View.Waiting, 1, "it is counted as waiting");
m = p.Plan(inv, Defaults, SortScope.Main, false, 5999, 5000);
Eq(m.Count, 0, "still settling just before");
m = p.Plan(inv, Defaults, SortScope.Main, false, 6000, 5000);
Eq(m.Count, 1, "moves once settled");
Eq(m[0].DestIndex, 1, "to pack 1");
Eq(m[0].Dest.Id, inv.Packs[0].Id, "pack 1's id");
var q = new SortPlanner();
m = q.Plan(inv, Defaults, SortScope.Main, true, 1000, 5000);
Eq(m.Count, 1, "Sort now (force) skips the settle time");
// An item that left the main pack and came back starts its settle time again.
var r = new SortPlanner();
r.Plan(inv, Defaults, SortScope.Main, false, 0, 5000);
SortItem it = inv.Main.Items[0];
inv.Main.Items.Clear();
r.Plan(inv, Defaults, SortScope.Main, false, 3000, 5000);
inv.Main.Items.Add(it);
Eq(r.Plan(inv, Defaults, SortScope.Main, false, 6000, 5000).Count, 0, "re-seen item settles again");
Eq(r.Plan(inv, Defaults, SortScope.Main, false, 11000, 5000).Count, 1, "then moves");
// Settle 0: moves at once.
Eq(new SortPlanner().Plan(inv, Defaults, SortScope.Main, false, 0, 0).Count, 1, "settle 0 moves at once");
}
private static void PlanPackChoice()
{
// A full pack refuses an item that can't stack there.
SortInventory inv = Inv(3);
Fill(inv.Packs[1], 24, 1000);
inv.Main.Items.Add(It(10, "Salvaged Iron", ObjectClasses.Salvage, wcid: 20981, stack: 1, max: 1));
var p = new SortPlanner();
List<SortMove> m = p.Plan(inv, Defaults, SortScope.Main, true, 0, 5000);
Eq(m.Count, 0, "full pack, no stack: refused");
Check(p.View.Full.Contains(2), "pack 2 reported full");
Eq(p.View.Waiting, 1, "waiting");
// A full pack takes a stackable item when a stack of the same kind has room there.
inv = Inv(3);
Fill(inv.Packs[0], 23, 1000);
inv.Packs[0].Items.Add(It(50, "Prismatic Taper", ObjectClasses.SpellComponent, wcid: 8897, stack: 40, max: 100));
inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent, wcid: 8897, stack: 12, max: 100));
p = new SortPlanner();
m = p.Plan(inv, Defaults, SortScope.Main, true, 0, 5000);
Eq(m.Count, 1, "full pack, joins a stack: moves");
Eq(m.Count > 0 ? m[0].MergeInto : 0u, 50u, "merges into the stack there");
Check(p.View.Full.Count == 0, "not reported full");
// ... but not when that stack is itself full.
inv.Packs[0].Items[23].Stack = 100;
p = new SortPlanner();
m = p.Plan(inv, Defaults, SortScope.Main, true, 0, 5000);
Eq(m.Count, 0, "full pack whose stack is full: refused");
Check(p.View.Full.Contains(1), "pack 1 full");
// A different kind with the same name doesn't count when both have a class id (wcid).
inv.Packs[0].Items[23].Stack = 40;
inv.Packs[0].Items[23].Wcid = 9999;
Eq(new SortPlanner().Plan(inv, Defaults, SortScope.Main, true, 0, 5000).Count, 0, "same name, other wcid: no stack");
// Without wcids the name decides (the Lua script's rule).
inv.Packs[0].Items[23].Wcid = 0;
inv.Main.Items[0].Wcid = 0;
Eq(new SortPlanner().Plan(inv, Defaults, SortScope.Main, true, 0, 5000).Count, 1, "no wcid: same name stacks");
// Room for one: two items, only the first goes; the second waits as "full".
inv = Inv(3);
Fill(inv.Packs[2], 23, 1000);
inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
inv.Main.Items.Add(It(11, "Mana Stone", ObjectClasses.ManaStone));
p = new SortPlanner();
m = p.Plan(inv, Defaults, SortScope.Main, true, 0, 5000);
Eq(m.Count, 1, "one slot: one move planned");
Check(p.View.Full.Contains(3), "then pack 3 counts as full");
// A non-full pack merges into a stack with room when there is one (keeps stacks tidy).
inv = Inv(1);
inv.Packs[0].Items.Add(It(50, "Prismatic Taper", ObjectClasses.SpellComponent, wcid: 8897, stack: 40, max: 100));
inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent, wcid: 8897, stack: 12, max: 100));
m = new SortPlanner().Plan(inv, Defaults, SortScope.Main, true, 0, 5000);
Eq(m.Count == 1 ? m[0].MergeInto : 0u, 50u, "merges into an existing stack");
// Capacity unknown (0): a side pack holds 24.
inv = Inv(1, cap: 0);
Fill(inv.Packs[0], 24, 1000);
inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
Eq(new SortPlanner().Plan(inv, Defaults, SortScope.Main, true, 0, 5000).Count, 0, "unknown capacity = 24");
}
private static void PlanNeverMoves()
{
SortInventory inv = Inv(3);
var worn = It(10, "Prismatic Taper", ObjectClasses.SpellComponent);
worn.Wielded = true;
inv.Main.Items.Add(worn);
inv.Main.Items.Add(It(11, "Backpack", ObjectClasses.Container));
inv.Main.Items.Add(It(12, "Foci of Enchantment", ObjectClasses.Foci));
var rules = new List<SortRule>
{
SortRule.ForClass(ObjectClasses.SpellComponent, 1),
SortRule.ForClass(ObjectClasses.Container, 1),
SortRule.ForClass(ObjectClasses.Foci, 1),
};
var p = new SortPlanner();
Eq(p.Plan(inv, rules, SortScope.All, true, 0, 0).Count, 0, "worn item, pack and foci never move");
inv.Main.Items.Clear();
inv.Main.Items.Add(It(20, "Prismatic Taper", ObjectClasses.SpellComponent));
p.Block(20, 60_000);
Eq(p.Plan(inv, rules, SortScope.Main, true, 1000, 0).Count, 0, "a blocked item is left alone");
Eq(p.BlockedCount(1000), 1, "counted as blocked");
Eq(p.Plan(inv, rules, SortScope.Main, true, 60_000, 0).Count, 1, "after its minute it is tried again");
}
private static void PlanMissingPack()
{
SortInventory inv = Inv(2);
inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
var p = new SortPlanner();
Eq(p.Plan(inv, Defaults, SortScope.Main, true, 0, 0).Count, 0, "pack 3 doesn't exist: no move");
Check(p.View.Missing.Contains(3), "pack 3 reported missing");
Eq(p.View.Packs.Count, 2, "the view lists the two packs");
}
private static void PlanTidyClean()
{
SortInventory inv = Inv(3);
inv.Packs[0].Items.Add(It(10, "Salvaged Iron", ObjectClasses.Salvage)); // belongs in pack 2
inv.Packs[1].Items.Add(It(11, "Salvaged Gold", ObjectClasses.Salvage)); // right where it is
inv.Packs[2].Items.Add(It(12, "Ashcoal", ObjectClasses.Misc)); // no rule wants it
var p = new SortPlanner();
Eq(p.Plan(inv, Defaults, SortScope.Main, true, 0, 0).Count, 0, "Sort now leaves side packs alone");
List<SortMove> m = p.Plan(inv, Defaults, SortScope.All, false, 0, 5000);
Eq(m.Count, 1, "Tidy: one misplaced item");
Check(m.Count == 1 && m[0].Item.Id == 10 && m[0].DestIndex == 2, "Tidy moves it to pack 2 (no settle time)");
m = p.Plan(inv, Defaults, SortScope.Clean, false, 0, 5000);
Eq(m.Count, 2, "Clean: the misplaced one and the stray");
Check(m.Any(x => x.Item.Id == 12 && x.DestIndex == 0 && x.Dest.Id == Me), "the stray goes to the main pack");
// Main pack full: the stray stays, and Clean says so.
inv = Inv(1, mainCap: 2);
Fill(inv.Main, 2, 2000);
inv.Packs[0].Items.Add(It(12, "Ashcoal", ObjectClasses.Misc));
p = new SortPlanner();
Eq(p.Plan(inv, Defaults, SortScope.Clean, false, 0, 0).Count, 0, "main pack full: stray stays");
Check(p.View.MainFull, "main pack reported full");
// ... unless it joins a stack in the main pack.
inv.Main.Items[0] = It(2000, "Pyreal", ObjectClasses.Money, wcid: 273, stack: 10, max: 25000);
inv.Packs[0].Items[0] = It(12, "Pyreal", ObjectClasses.Money, wcid: 273, stack: 5, max: 25000);
Eq(new SortPlanner().Plan(inv, Defaults, SortScope.Clean, false, 0, 0).Count, 1, "joins a main-pack stack");
}
private static void PlanUnpack()
{
SortInventory inv = Inv(3);
inv.Packs[0].Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
inv.Packs[1].Items.Add(It(11, "Salvaged Iron", ObjectClasses.Salvage));
inv.Packs[2].Items.Add(It(12, "Black Opal", ObjectClasses.Gem));
var p = new SortPlanner();
List<SortMove> m = p.PlanUnpack(inv, null, 0);
Eq(m.Count, 3, "unpack all: every side-pack item");
Check(m.All(x => x.DestIndex == 0), "all to the main pack");
m = p.PlanUnpack(inv, 2, 0);
Check(m.Count == 1 && m[0].Item.Id == 11, "unpack 2: only pack 2");
inv = Inv(1, mainCap: 1);
Fill(inv.Main, 1, 2000);
inv.Packs[0].Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
m = p.PlanUnpack(inv, null, 0);
Eq(m.Count, 0, "main pack full: nothing");
Check(p.View.MainFull && p.View.Waiting == 1, "main full reported");
}
// ── Gates ───────────────────────────────────────────────────────────
private static void Gates()
{
Check(SortGate.Reason(new GateInputs()) == null, "nothing going on: fine");
Eq(SortGate.Reason(new GateInputs { InPortalSpace = true }), "portal space", "portal space");
Eq(SortGate.Reason(new GateInputs { Looting = true }), "looting", "looting a corpse or chest");
Eq(SortGate.Reason(new GateInputs { VendorOpen = true }), "vendor open", "vendor");
Eq(SortGate.Reason(new GateInputs { TradeOpen = true }), "trading", "trade window");
Eq(SortGate.Reason(new GateInputs { ClientBusy = true }), "busy", "busy (a use or a cast)");
Eq(SortGate.Reason(new GateInputs { Animating = true }), "busy", "animating");
Eq(SortGate.Reason(new GateInputs { InPortalSpace = true, Looting = true }), "portal space", "portal space comes first");
}
private static void GatesRynthAi()
{
RynthAiActivity run = RynthAiActivity.MacroRunning;
Check(SortGate.Reason(new GateInputs { Bot = run }) == null, "RynthAi idle: fine");
Check(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Navigating }) == null, "RynthAi walking a route: fine");
Eq(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Looting }), "RynthAi is looting", "looting");
Eq(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Salvaging }), "RynthAi is salvaging", "salvaging");
Eq(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Buffing }), "RynthAi is buffing", "buffing / healing");
Eq(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Crafting }), "RynthAi is making ammo", "crafting");
Eq(SortGate.Reason(new GateInputs { Bot = RynthAiActivity.ServerAction }), "RynthAi is waiting on the server", "an unanswered use/cast, macro off too");
Eq(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Combat }), "RynthAi is fighting", "fighting, Sort during fights off");
Check(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Combat, SortInCombat = true }) == null, "fighting, Sort during fights on");
Eq(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Combat | RynthAiActivity.ServerAction, SortInCombat = true }),
"RynthAi is waiting on the server", "fighting with a cast unanswered: still waits");
Eq(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Combat, SortInCombat = true, Animating = true }), "busy",
"fighting while animating: waits");
Check(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.AutoCram }) == null, "AutoCram alone doesn't pause (it's a warning)");
Check(SortGate.Reason(new GateInputs { Bot = null }) == null, "no RynthAi: the client's own signals only");
}
private static void GateQuiet()
{
var g = new SortGate();
Eq(g.Evaluate(new GateInputs { ClientBusy = true }, 10_000), "busy", "busy");
Eq(g.Evaluate(new GateInputs(), 10_100), "busy", "just cleared: still held");
Eq(g.Evaluate(new GateInputs(), 10_000 + SortGate.QuietMs - 1), "busy", "held until the quiet time ends");
Check(g.Evaluate(new GateInputs(), 10_000 + SortGate.QuietMs) == null, "then clear");
Check(new SortGate().Evaluate(new GateInputs(), 0) == null, "never paused: clear at once");
}
private static void LootWatching()
{
var w = new LootWatch();
Check(!w.Update(0, 0, 0), "nothing open");
Check(w.Update(0x7000_0001, 5, 1000), "a corpse just opened");
Check(w.Update(0x7000_0001, 4, 3000), "its contents changing");
Check(w.Update(0x7000_0001, 4, 6999), "within 4 s of the last change");
// 6999 was the last "looting" read: 1.5 s more from there, then a finished corpse the client
// still shows open doesn't count.
Check(w.Update(0x7000_0001, 4, 6999 + LootWatch.AfterMs - 1), "the 1.5 s after the last looting");
Check(!w.Update(0x7000_0001, 4, 6999 + LootWatch.AfterMs), "a finished corpse still shown open doesn't count");
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");
}
private static void StatusJsonFallback()
{
Eq(HostSortWorld.FromStatusJson("{\"macro\":true,\"action\":\"Looting\"}"), RynthAiActivity.MacroRunning | RynthAiActivity.Looting, "looting");
Eq(HostSortWorld.FromStatusJson("{\"macro\":true,\"action\":\"Healing\"}"), RynthAiActivity.MacroRunning | RynthAiActivity.Buffing, "healing = buffing slot");
Eq(HostSortWorld.FromStatusJson("{\"macro\":true,\"action\":\"Restoring mana\"}"), RynthAiActivity.MacroRunning | RynthAiActivity.Buffing, "restoring mana");
Eq(HostSortWorld.FromStatusJson("{\"macro\":true,\"action\":\"Following\"}"), RynthAiActivity.MacroRunning | RynthAiActivity.Navigating, "following");
Eq(HostSortWorld.FromStatusJson("{\"macro\":true,\"action\":\"Default\"}"), RynthAiActivity.MacroRunning, "default");
Eq(HostSortWorld.FromStatusJson("{\"macro\":false,\"action\":\"Combat\"}"), RynthAiActivity.None, "macro off: nothing");
Check(HostSortWorld.FromStatusJson("nope") == null && HostSortWorld.FromStatusJson(null) == null, "not JSON: null");
}
// ── Moves ───────────────────────────────────────────────────────────
private static MoveInFlight Flight(uint item, uint dest, uint merge = 0, int stack = 1, int seq = 7, long sent = 1000)
{
var it = It(item, "Thing", ObjectClasses.Misc, stack: stack);
var pack = new SortPack { Id = dest };
return new MoveInFlight { Move = new SortMove(it, pack, 1, merge), SentMs = sent, ErrorSeqAtSend = seq, StackAtSend = stack };
}
private static void MoveAnswers()
{
MoveInFlight m = Flight(10, 0x40000001);
Eq(MoveTracker.Observe(m, new MoveObservation { Exists = true, Container = Me, ErrorSeq = 7 }, 1500), MoveOutcome.Pending, "still in the main pack");
Eq(MoveTracker.Observe(m, new MoveObservation { Exists = true, Container = 0x40000001, ErrorSeq = 7 }, 1500), MoveOutcome.Done, "landed");
Eq(MoveTracker.Observe(m, new MoveObservation { Exists = false }, 1500), MoveOutcome.Done, "gone: merged on arrival");
Eq(MoveTracker.Observe(m, new MoveObservation { Exists = true, Container = Me, ErrorSeq = 8, ErrorEventType = 0xA0, ErrorObject = 10 }, 1500),
MoveOutcome.Refused, "InventoryServerSaveFailed for it");
Eq(MoveTracker.Observe(m, new MoveObservation { Exists = true, Container = Me, ErrorSeq = 8, Error = 0x1D, ErrorEventType = 0x28A }, 1500),
MoveOutcome.TooBusy, "You're too busy");
Eq(MoveTracker.Observe(m, new MoveObservation { Exists = true, Container = Me, ErrorSeq = 8, Error = 0x402, ErrorEventType = 0x28A, ErrorObject = 99 }, 1500),
MoveOutcome.Pending, "someone else's refusal (a fizzle) isn't ours");
Eq(MoveTracker.Observe(m, new MoveObservation { Exists = true, Container = Me, ErrorSeq = 7 }, 1000 + MoveTracker.TimeoutMs),
MoveOutcome.TimedOut, "no answer in 5 s");
MoveInFlight merge = Flight(10, 0x40000001, merge: 50, stack: 12);
Eq(MoveTracker.Observe(merge, new MoveObservation { Exists = true, Container = Me, Stack = 4, ErrorSeq = 7 }, 1500),
MoveOutcome.Done, "a merge that took part of the stack");
Eq(MoveTracker.BackoffMs(0), 0L, "no failures: no hold");
Eq(MoveTracker.BackoffMs(1), 2000L, "one: 2 s");
Eq(MoveTracker.BackoffMs(3), 8000L, "three: 8 s");
Eq(MoveTracker.BackoffMs(30), MoveTracker.MaxBackoffMs, "capped at 30 s");
}
// ── The loop ────────────────────────────────────────────────────────
/// <summary>A pretend game for the controller: packs, gate inputs and how the server answers.</summary>
private sealed class FakeWorld : ISortWorld
{
public SortInventory Inv = Inv(3);
public GateInputs Gate;
public readonly List<SortMove> Sent = new();
public bool EngineAccepts = true;
/// <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();
public SortInventory? ReadInventory() => Inv;
public GateInputs ReadGate(bool sortInCombat, long nowMs) { GateInputs g = Gate; g.SortInCombat = sortInCombat; return g; }
public int ErrorSeqNow() => ErrorSeq;
public bool SendMove(in SortMove move)
{
Sent.Add(move);
if (!EngineAccepts) return false;
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;
break;
case "refuse":
ErrorSeq++;
_refused = move.Item.Id;
break;
case "busy":
ErrorSeq++;
_busy = true;
break;
}
return true;
}
private uint _refused;
private bool _busy;
public MoveObservation Observe(uint itemId)
{
var o = new MoveObservation { Exists = true, Container = _where.TryGetValue(itemId, out uint c) ? c : Me, ErrorSeq = ErrorSeq };
if (_refused == itemId) { o.ErrorEventType = 0xA0; o.ErrorObject = itemId; }
if (_busy) { o.Error = 0x1D; o.ErrorEventType = 0x28A; }
return o;
}
}
private static SortController Controller(bool auto = true, int gapMs = 300, int settleSec = 0)
{
var c = new SortController();
c.Data.Settings.Auto = auto;
c.Data.Settings.GapMs = gapMs;
c.Data.Settings.SettleSec = settleSec;
return c;
}
/// <summary>Ticks every 16 ms from <paramref name="from"/> to <paramref name="to"/>.</summary>
private static void Ticks(SortController c, FakeWorld w, long from, long to)
{
for (long t = from; t <= to; t += 16) c.Tick(w, t);
}
private static void LoopPaused()
{
foreach (var (name, gate) in new (string, GateInputs)[]
{
("looting", new GateInputs { Looting = true }),
("vendor", new GateInputs { VendorOpen = true }),
("trade", new GateInputs { TradeOpen = true }),
("busy", new GateInputs { ClientBusy = true }),
("animating", new GateInputs { Animating = true }),
("portal", new GateInputs { InPortalSpace = true }),
("RynthAi looting", new GateInputs { Bot = RynthAiActivity.MacroRunning | RynthAiActivity.Looting }),
("RynthAi salvaging", new GateInputs { Bot = RynthAiActivity.MacroRunning | RynthAiActivity.Salvaging }),
("RynthAi buffing", new GateInputs { Bot = RynthAiActivity.MacroRunning | RynthAiActivity.Buffing }),
("RynthAi waiting on the server", new GateInputs { Bot = RynthAiActivity.ServerAction }),
("RynthAi fighting", new GateInputs { Bot = RynthAiActivity.MacroRunning | RynthAiActivity.Combat }),
})
{
var w = new FakeWorld { Gate = gate };
w.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
SortController c = Controller();
Ticks(c, w, 0, 10_000);
Eq(w.Sent.Count, 0, $"{name}: nothing sent");
Check(c.Paused, $"{name}: status says paused ({c.Status})");
c.StartJob(SortScope.All);
Ticks(c, w, 10_000, 12_000);
Eq(w.Sent.Count, 0, $"{name}: a job asked for waits too");
// Clear: after the quiet time it goes (counted from the last paused read, which is at
// most one poll before the clear).
w.Gate = new GateInputs();
long quietEnd = 12_000 + SortGate.QuietMs - SortController.PollMs - 50;
Ticks(c, w, 12_000, quietEnd);
Eq(w.Sent.Count, 0, $"{name}: not during the quiet time");
Ticks(c, w, quietEnd + 16, 16_000);
Eq(w.Sent.Count, 1, $"{name}: moves once clear");
}
}
private static void LoopOneAtATime()
{
var w = new FakeWorld { Server = "silent" };
for (uint i = 0; i < 3; i++) w.Inv.Main.Items.Add(It(10 + i, "Prismatic Taper " + i, ObjectClasses.SpellComponent));
SortController c = Controller(gapMs: 300);
Ticks(c, w, 0, 2000);
Eq(w.Sent.Count, 1, "one move out, unanswered: no second one");
Check(c.HasMoveOut, "the move is out");
// Answered: the next goes only after the gap.
w.Server = "land";
var w2 = new FakeWorld();
for (uint i = 0; i < 3; i++) w2.Inv.Main.Items.Add(It(10 + i, "Prismatic Taper " + i, ObjectClasses.SpellComponent));
SortController c2 = Controller(gapMs: 300);
c2.Tick(w2, 0);
Eq(w2.Sent.Count, 1, "first move");
c2.Tick(w2, 16); // answer seen (landed)
Check(!c2.HasMoveOut, "answered");
c2.Tick(w2, 16 + 299);
Eq(w2.Sent.Count, 1, "the gap holds the next one");
c2.Tick(w2, 16 + 300);
Eq(w2.Sent.Count, 2, "second move after the gap");
Ticks(c2, w2, 400, 3000);
Eq(w2.Sent.Count, 3, "all three moved");
Eq(w2.Inv.Packs[0].Items.Count, 3, "all in pack 1");
Eq(c2.Moved, 3, "three moved");
Eq(c2.Status, "watching", "then watching");
Check(c2.Log.Count == 3 && c2.Log[0].Contains("-> pack 1"), "moves logged, newest first");
// Settle time: nothing before it.
var w3 = new FakeWorld();
w3.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
SortController c3 = Controller(settleSec: 5);
Ticks(c3, w3, 0, 4900);
Eq(w3.Sent.Count, 0, "settling");
Ticks(c3, w3, 4900, 6000);
Eq(w3.Sent.Count, 1, "moved after the settle time");
// Auto-sort off: nothing, status off.
var w4 = new FakeWorld();
w4.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
SortController c4 = Controller(auto: false);
Ticks(c4, w4, 0, 3000);
Eq(w4.Sent.Count, 0, "auto-sort off: nothing moves");
Eq(c4.Status, "off", "status off");
}
private static void LoopRefusals()
{
var w = new FakeWorld { Server = "refuse" };
w.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
w.Inv.Main.Items.Add(It(11, "Salvaged Iron", ObjectClasses.Salvage));
SortController c = Controller(gapMs: 300);
c.Tick(w, 0);
Eq(w.Sent.Count, 1, "first move");
c.Tick(w, 16);
Check(!c.HasMoveOut, "refusal seen");
Check(c.Planner.IsBlocked(10, 17), "the refused item is left alone");
Check(c.Log[0].Contains("not moved"), "logged as not moved");
Ticks(c, w, 32, 16 + MoveTracker.BackoffMs(1) - 16);
Eq(w.Sent.Count, 1, "held for the back-off");
w.Server = "land";
Ticks(c, w, 16 + MoveTracker.BackoffMs(1), 6000);
Eq(w.Sent.Count, 2, "then the next item");
Eq(w.Sent[1].Item.Id, 11u, "it is the other item, not the refused one");
Ticks(c, w, 6000, 50_000);
Eq(w.Sent.Count, 2, "the refused one waits out its minute");
Ticks(c, w, 50_000, 62_000);
Eq(w.Sent.Count, 3, "tried again after a minute");
Eq(c.Failed, 1, "one failure counted");
// The engine refusing the call counts as a refusal too.
var w2 = new FakeWorld { EngineAccepts = false };
w2.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
SortController c2 = Controller();
c2.Tick(w2, 0);
Check(c2.Planner.IsBlocked(10, 1) && c2.Log[0].Contains("engine refused"), "engine refusal blocks the item");
// Failures in a row hold longer each time.
var w3 = new FakeWorld { Server = "refuse" };
for (uint i = 0; i < 4; i++) w3.Inv.Main.Items.Add(It(10 + i, "Taper " + i, ObjectClasses.SpellComponent));
SortController c3 = Controller();
var sentAt = new List<long>();
for (long t = 0; t < 40_000; t += 16)
{
int before = w3.Sent.Count;
c3.Tick(w3, t);
if (w3.Sent.Count > before) sentAt.Add(t);
}
Check(sentAt.Count == 4, $"four tries ({sentAt.Count})");
if (sentAt.Count == 4)
Check(sentAt[2] - sentAt[1] > sentAt[1] - sentAt[0] && sentAt[3] - sentAt[2] > sentAt[2] - sentAt[1], "each hold longer than the last");
}
private static void LoopBusyAndTimeout()
{
var w = new FakeWorld { Server = "busy" };
w.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
SortController c = Controller();
c.Tick(w, 0);
c.Tick(w, 16);
Check(!c.Planner.IsBlocked(10, 17), "too busy: the item isn't blocked");
Check(c.Log[0].Contains("busy"), "logged");
w.Server = "land";
Ticks(c, w, 32, 1900);
Eq(w.Sent.Count, 1, "held for the back-off");
Ticks(c, w, 1900, 3000);
Eq(w.Sent.Count, 2, "then tried again");
var w2 = new FakeWorld { Server = "silent" };
w2.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
SortController c2 = Controller();
Ticks(c2, w2, 0, MoveTracker.TimeoutMs - 16);
Check(c2.HasMoveOut, "waiting for the answer");
Ticks(c2, w2, MoveTracker.TimeoutMs, MoveTracker.TimeoutMs + 32);
Check(!c2.HasMoveOut && c2.Planner.IsBlocked(10, MoveTracker.TimeoutMs + 32), "no answer in 5 s: blocked");
Check(c2.Log[0].Contains("no answer"), "logged");
}
private static void LoopJobs()
{
// Tidy: misplaced side-pack items, as fast as the server answers (no auto gap).
var w = new FakeWorld();
w.Inv.Packs[0].Items.Add(It(10, "Salvaged Iron", ObjectClasses.Salvage));
w.Inv.Packs[0].Items.Add(It(11, "Salvaged Gold", ObjectClasses.Salvage));
SortController c = Controller(auto: false, gapMs: 3000);
c.StartJob(SortScope.All);
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");
// Unpack turns auto-sort off (and asks for a save) so nothing moves back.
var w2 = new FakeWorld();
w2.Inv.Packs[0].Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
w2.Inv.Packs[2].Items.Add(It(12, "Black Opal", ObjectClasses.Gem));
SortController c2 = Controller(auto: true);
int saves = 0;
c2.SettingsChanged = () => saves++;
c2.StartUnpack(null);
Check(!c2.Data.Settings.Auto && saves == 1, "unpack: auto-sort off, saved");
Ticks(c2, w2, 0, 1000);
Eq(w2.Inv.Main.Items.Count, 2, "both in the main pack");
Eq(c2.Log[0], "Side packs emptied", "noted");
Ticks(c2, w2, 1000, 20_000);
Eq(w2.Sent.Count, 2, "nothing moved back");
// Unpack one pack.
var w3 = new FakeWorld();
w3.Inv.Packs[0].Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
w3.Inv.Packs[2].Items.Add(It(12, "Black Opal", ObjectClasses.Gem));
SortController c3 = Controller();
c3.StartUnpack(3);
Ticks(c3, w3, 0, 1000);
Check(w3.Inv.Main.Items.Count == 1 && w3.Inv.Main.Items[0].Id == 12, "only pack 3 emptied");
// Clean: strays back to the main pack.
var w4 = new FakeWorld();
w4.Inv.Packs[1].Items.Add(It(12, "Ashcoal", ObjectClasses.Misc));
SortController c4 = Controller(auto: false);
c4.StartJob(SortScope.Clean);
Ticks(c4, w4, 0, 1000);
Check(w4.Inv.Main.Items.Count == 1 && c4.Log[0] == "Packs cleaned", "clean sent the stray home");
// Sort now ignores the settle time.
var w5 = new FakeWorld();
w5.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
SortController c5 = Controller(settleSec: 30);
c5.StartJob(SortScope.Main);
Ticks(c5, w5, 0, 200);
Eq(w5.Sent.Count, 1, "sort now: no settle time");
}
// ── Store ───────────────────────────────────────────────────────────
private static SortStore TempStore(string name)
{
string root = Path.Combine(_temp, name);
return new SortStore(Path.Combine(root, "RynthSort"), Path.Combine(root, "RynthLua", "Data", "RynthSort"));
}
private static void StoreRoundTrip()
{
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");
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;
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(SortStore.FileStem("Dream:Weave", "Con"), "Dream_Weave_Con", "unsafe characters replaced like RynthLua");
Eq(SortStore.SafeFileName("CON"), "_CON", "reserved names guarded");
}
// The Lua script's file for Drakkon, as it is on disk (2026-10-07).
private const string LuaFile = "{\n \"rules\": [{\"on\":true,\"kind\":\"class\",\"class\":12,\"text\":\"\",\"pack\":1},{\"on\":true,\"kind\":\"class\",\"class\":39,\"text\":\"\",\"pack\":2},{\"on\":true,\"kind\":\"class\",\"class\":11,\"text\":\"\",\"pack\":3},{\"on\":true,\"kind\":\"class\",\"class\":16,\"text\":\"\",\"pack\":3},{\"on\":true,\"kind\":\"class\",\"class\":13,\"text\":\"\",\"pack\":3},{\"on\":true,\"kind\":\"class\",\"class\":29,\"text\":\"\",\"pack\":4}],\n \"settings\": {\"auto\":false,\"settleSec\":5,\"gapMs\":600}\n}\n";
private static void StoreLuaImport()
{
SortStore st = TempStore("import");
string lua = st.LuaPathFor("DreamWeave", "Drakkon");
Directory.CreateDirectory(Path.GetDirectoryName(lua)!);
File.WriteAllText(lua, LuaFile);
CharacterSortData d = st.Load("DreamWeave", "Drakkon", out string? problem);
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.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");
// Once RynthSort has its own file, the Lua file is no longer read (and is left alone).
d.Rules.RemoveAt(0);
st.Save("DreamWeave", "Drakkon", d);
CharacterSortData again = st.Load("DreamWeave", "Drakkon", out _);
Eq(again.Rules.Count, 5, "own file wins over the Lua file");
Check(File.Exists(lua) && File.ReadAllText(lua) == LuaFile, "the Lua file is untouched");
// Another character with no Lua file: defaults.
Eq(st.Load("DreamWeave", "Someone", out _).ImportedFrom, "", "nothing to import: defaults");
}
private static void StoreOddFiles()
{
SortStore st = TempStore("odd");
string own = st.PathFor("S", "A");
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");
// 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}}");
d = st.Load("S", "A", out problem);
Check(problem == null && d.Rules.Count == 0, "{} = no rules");
Check(d.Settings.SettleSec == SortSettings.SettleMax && d.Settings.GapMs == SortSettings.GapMin, "clamped");
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");
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");
}
private static void LuaAutostart()
{
static bool Starts(string json, string key)
{
using var doc = System.Text.Json.JsonDocument.Parse(json);
return RynthSortPlugin.LuaScriptStarts(doc.RootElement, key);
}
Check(!Starts("{\"GlobalScripts\":[],\"CharacterScripts\":{\"DreamWeave|Drakkon\":[\"item-counter\"]}}", "DreamWeave|Drakkon"), "today's settings: not set to start");
Check(Starts("{\"GlobalScripts\":[\"RynthSort\"]}", "DreamWeave|Drakkon"), "global autostart");
Check(Starts("{\"CharacterScripts\":{\"DreamWeave|Drakkon\":[\"rynthsort\"]}}", "DreamWeave|Drakkon"), "this character's autostart");
Check(!Starts("{\"CharacterScripts\":{\"DreamWeave|Other\":[\"RynthSort\"]}}", "DreamWeave|Drakkon"), "another character's");
}
// ── Window ──────────────────────────────────────────────────────────
private static (SortController, SortPanel, UiHost, UiWindow) Window()
{
var c = new SortController();
var panel = new SortPanel(c, () => { }) { Character = () => "Drakkon" };
var host = new UiHost();
UiWindow w = host.Add(new UiWindow("RynthSort/Main", "RynthSort") { Visible = true });
var inv = Inv(4);
Fill(inv.Packs[0], 24, 1000);
inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
c.Planner.Plan(inv, c.Data.Rules, SortScope.Main, true, 0, 0);
return (c, panel, host, w);
}
private static void Draw(UiWindow w, SortPanel panel)
{
w.Begin();
panel.Draw(w);
w.End();
}
private static string BodyText(UiWindow w) => Encoding.UTF8.GetString(w.Body);
private static unsafe void ParseAll(UiHost host, string what, out int maxOps)
{
int n = Write(host);
byte[] buf = SubmitBuffer(host);
int rc;
List<ParsedWindow> windows;
string error;
fixed (byte* p = buf) rc = DisplayListParser.Parse(p, n, 4000f, out _, out windows, out error);
Check(rc == 0, $"{what}: engine parser refused the submit ({rc}): {error}");
maxOps = windows.Where(x => x.List != null).Select(x => x.List!.OpCount).DefaultIfEmpty(0).Max();
}
private static byte[] Event(ushort type, uint seq, uint window, uint key, byte[] payload)
{
var e = new byte[16 + payload.Length];
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(e, type);
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(e.AsSpan(2), (ushort)e.Length);
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(e.AsSpan(4), seq);
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(e.AsSpan(8), window);
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(e.AsSpan(12), key);
payload.CopyTo(e, 16);
return e;
}
private static byte[] Click => new byte[] { 1, 0 };
private static void WindowParses()
{
var (c, panel, host, w) = Window();
Draw(w, panel);
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");
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));
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 _);
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("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;
Draw(w, panel);
ParseAll(host, "rule editor (name)", out _);
Check(BodyText(w).Contains("Name has"), "name editor");
c.Data.Rules[0].Kind = RuleKind.Class;
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");
// Many rules still fit.
for (int i = 0; i < SortStore.MaxRules; i++) c.Data.Rules.Add(SortRule.ForName("x" + i, 1 + i % 8));
Draw(w, panel);
ParseAll(host, "64+ rules", out int many);
Check(many < 1500, $"many rules fit ({many} ops)");
// Logged out.
panel.Character = () => "";
Draw(w, panel);
ParseAll(host, "logged out", out _);
Check(BodyText(w).Contains("Log in"), "logged-out text");
}
private static void WindowEvents()
{
var (c, panel, host, w) = Window();
Draw(w, panel);
int rules = c.Data.Rules.Count;
Apply(host, Event(1, 1, w.Hash, w.KeyOf("rule.add"), Click));
Eq(c.Data.Rules.Count, rules + 1, "Add rule");
Eq(panel.Selected, rules, "the new rule is selected");
Draw(w, panel);
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);
// 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);
// 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);
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);
// 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");
// 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 }));
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 }));
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));
Check(c.Job == SortScope.Unpack && c.UnpackWhich == null, "Empty side packs button");
}
}
}

View file

@ -0,0 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
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
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
folder, never C:\Games.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>RynthSort.Tests</RootNamespace>
<NoWarn>$(NoWarn);CS0649;CS0169;CS0414;CS8618</NoWarn>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
<!-- The engine parser's whitelists use ImGui.NET's enums. -->
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthSort\**\*.cs" Exclude="..\..\Plugins\RynthCore.Plugin.RynthSort\obj\**;..\..\Plugins\RynthCore.Plugin.RynthSort\bin\**" Link="RynthSort\%(RecursiveDir)%(Filename)%(Extension)" />
<Compile Include="..\..\Plugins\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
</ItemGroup>
</Project>