Snapshot for release 2026.10.31.2 (internal 4a0710c)

This commit is contained in:
Tom Bohar 2026-10-31 19:00:25 -04:00
commit d54613aa63
50 changed files with 5824 additions and 179 deletions

File diff suppressed because it is too large Load diff

View file

@ -58,6 +58,10 @@ internal static class Program
var runner = new Runner();
NativeLootTests.Register(runner);
VTankLootTests.Register(runner);
LootRuleMatchTests.Register(runner);
LootLateIdTests.Register(runner);
LootChatLineTests.Register(runner);
LootSurveyTests.Register(runner);
PropertyDumpTests.Register(runner);
T11LootTests.Register(runner);
MagItemDescriberTests.Register(runner);
@ -86,6 +90,8 @@ internal static class Program
LootSalvageTests.Register(runner);
LootCorpseTests.Register(runner);
LootRetryTimingTests.Register(runner);
LootClaimMismatchTests.Register(runner);
LootNothingLineTests.Register(runner);
ChestLootTests.Register(runner);
OwnCorpseTests.Register(runner);
UseRefusalTests.Register(runner);

View file

@ -124,6 +124,7 @@ internal static class CommandReplyTests
new(null, "/ra settings", K.Act),
new(null, "/ra settings loadchar", K.Act),
new(null, "/ra loot add banana", K.Act),
new(null, "/ra loot why", K.Act), // nothing selected: says so
new(null, "/ra lootparse", K.Act),
new(null, "/ra lootcheckinv", K.Act),
new(null, "/ra autotrade", K.Act),

View file

@ -0,0 +1,300 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.ItemInfo;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-10-31, a player asked for loot details in chat "like magtools does": the looter's "Looted"
// line of an item a loot rule took names the rule and the item's Mag-style details, in one line
// (Item Info's "Describe looted items in chat", on by default). Salvage stays short unless
// "Include salvage" is on, stackables (pyreals, notes, comps) keep the plain line, and the head stays
// "[RynthAi] Looted [<action>] <name>" for the self-test meta. One corpse: a crossbow (Keep rule),
// a helm (Salvage rule) and a stack of pyreals (Keep rule). The loot clock (CorpseClock) is moved by hand.
internal static class LootChatLineTests
{
private const uint Player = 0x50000E51;
private const uint Corpse = 0x80265100;
private const uint Xbow = 0x80265101, Helm = 0x80265102, Coins = 0x80265103;
private const uint ItemTypeContainer = 0x200, ItemTypeMissile = 0x100, ItemTypeArmor = 0x2, ItemTypeMoney = 0x40;
private const uint LongDescKey = 16;
private const string Me = "Loot Tester";
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
public static void Register(Runner r)
{
r.Add("loot chat: a looted keeper prints one line with its rule and its Mag-style details", KeeperDescribed);
r.Add("loot chat: salvage is quiet by default, and short (material, workmanship) with Include salvage", SalvageQuietByDefault);
r.Add("loot chat: pyreals, notes, comps and other stacks print the plain line only", StackablePlain);
r.Add("loot chat: Describe looted items off prints the plain lines", SettingOffPlain);
r.Add("loot chat: the settings survive a profile save and load, the settings map and /ra iteminfo loot", SettingsRoundTrip);
}
private static long _now;
private static void Clocked(Action body)
{
var old = RynthAiPlugin.CorpseClock;
_now = 70_000_000;
RynthAiPlugin.CorpseClock = () => _now;
try { body(); }
finally { RynthAiPlugin.CorpseClock = old; }
}
private static void World()
{
FakeHost.Reset();
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.Names[Player] = Me;
FakeHost.Positions[Player] = Me0;
FakeHost.PlayerPose = Me0;
FakeHost.Names[Corpse] = "Corpse of Olthoi Swarm Drone";
FakeHost.ItemTypes[Corpse] = ItemTypeContainer;
FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}.";
FakeHost.NotAttackable.Add(Corpse);
FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
// A gold crossbow, identified: workmanship 6, crossbow, pierce, +22, +162%, 15% melee defense,
// Legendary Blood Thirst.
Item(Xbow, "Blunt Crossbow", ItemTypeMissile, (19, 12000), (5, 600), (131, 60), (105, 6), (353, 9), (45, 2), (204, 22));
FakeHost.Doubles[(Xbow, 63)] = 2.62;
FakeHost.Doubles[(Xbow, 29)] = 1.15;
FakeHost.SpellIds[Xbow] = new[] { (uint)SpellDatabase.GetIdByName("Legendary Blood Thirst") };
FakeHost.Appraised.Add(Xbow);
// A steel helm for salvage, identified: workmanship 5, AL 300.
Item(Helm, "Helm", ItemTypeArmor, (19, 900), (5, 300), (131, 64), (105, 5), (28, 300));
FakeHost.Appraised.Add(Helm);
// A stack of 50 pyreals.
Item(Coins, "Pyreal", ItemTypeMoney, (19, 50), (11, 25000), (12, 50));
}
private static void Item(uint id, string name, uint itemType, params (uint Key, int Value)[] ints)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = itemType;
FakeHost.Containers[id] = Corpse;
FakeHost.Ints[(id, 1)] = unchecked((int)itemType);
foreach (var (k, v) in ints) FakeHost.Ints[(id, k)] = v;
}
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new()
{
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
LootAssessWindowMs = 200, LootCorpseTimeoutMs = 12_000,
};
public readonly WorldObjectCache Cache;
public Bot(RynthCoreHost host)
{
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
Set("_dashboard", dash);
Cache = new WorldObjectCache(host);
Cache.SetPlayerId(Player);
Set("_objectCache", Cache);
Set("_playerId", Player);
Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
var p = new VTankLootProfile();
p.Rules.Add(Rule("Keep bows", VTankLootAction.Keep, AcObjectClass.MissileWeapon));
p.Rules.Add(Rule("Salvage armor", VTankLootAction.Salvage, AcObjectClass.Armor));
p.Rules.Add(Rule("Coins", VTankLootAction.Keep, AcObjectClass.Money));
string path = Path.Combine(Program.TempRoot, "loot-chat-line.utl");
File.WriteAllText(path, VTankLootWriter.Serialize(p));
S.CurrentLootPath = path;
}
private static VTankLootRule Rule(string name, VTankLootAction action, AcObjectClass cls)
{
var rule = new VTankLootRule { Name = name, Action = action };
rule.Conditions.Add(new VTankLootCondition(VTankNodeTypes.ObjectClass, "0", new[] { ((int)cls).ToString() }));
return rule;
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
public void Tick()
{
Set("_activity", BotActivity.Looting);
typeof(RynthAiPlugin).GetMethod("TickCorpseOpening", Any)!.Invoke(P, null);
}
public bool Completed(uint corpse) =>
Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)corpse));
}
/// <summary>Opens the corpse and loots it, each item landing in the main pack as soon as its move goes out.</summary>
private static List<string> LootCorpse(Action<MagItemInfoSettings>? configure = null)
{
World();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
configure?.Invoke(bot.S.ItemInfoSettings);
bot.Cache.OnCreateObject(Corpse);
foreach (uint id in new[] { Xbow, Helm, Coins }) bot.Cache.OnCreateObject(id);
bot.Cache.Tick();
bot.Tick();
Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened");
FakeHost.UseDone(0);
bot.P.OnViewObjectContents(Corpse);
var landed = new HashSet<uint>();
for (int i = 0; i < 3000 && !(bot.Completed(Corpse) && landed.Count == 3); i++)
{
foreach (var m in FakeHost.ExternalMoves)
if (landed.Add(m.Id)) FakeHost.Containers[m.Id] = Player;
_now += 20;
bot.Tick();
}
List<string> looted = FakeHost.Chat.Where(c => c.StartsWith("[RynthAi] Looted [", StringComparison.Ordinal)).ToList();
Check.Eq(looted.Count, 3, "one Looted line per item: " + string.Join(" | ", looted));
Check.False(FakeHost.Chat.Any(c => c.StartsWith("[RynthAi Item]", StringComparison.Ordinal)), "no separate item info lines");
return looted;
}
private static string LineFor(List<string> looted, string name) =>
looted.SingleOrDefault(l => l.Contains("] " + name, StringComparison.Ordinal)) ?? "(none)";
private static void KeeperDescribed() => Clocked(() =>
{
List<string> looted = LootCorpse();
string line = LineFor(looted, "Blunt Crossbow");
Check.True(line.StartsWith("[RynthAi] Looted [Keep] Blunt Crossbow (rule \"Keep bows\"): Gold, Pierce Crossbow, ", StringComparison.Ordinal),
"the head, the rule, material and type: " + line);
foreach (string part in new[] { "+22", "+162%", "+15%md", "Legendary Blood Thirst", "Craft 6" })
Check.True(line.Contains(part, StringComparison.Ordinal), $"'{part}' in: {line}");
Check.False(line.Contains('\n'), "one line");
Check.False(line.Contains("not IDed"), "identified");
Check.Eq(FakeHost.Chat.Count(c => c.Contains("Looted [Keep] Blunt Crossbow")), 1, "said once");
// The Item Info field settings apply: spells hidden, no spells on the loot line either.
looted = LootCorpse(s => s.SetHidden(MagItemInfoField.Spells, true));
line = LineFor(looted, "Blunt Crossbow");
Check.False(line.Contains("Blood Thirst"), "a hidden field stays hidden: " + line);
Check.True(line.Contains("+22"), "the rest still shows: " + line);
});
private static void SalvageQuietByDefault() => Clocked(() =>
{
List<string> looted = LootCorpse();
Check.Eq(LineFor(looted, "Helm"), "[RynthAi] Looted [Salvage] Helm", "salvage keeps the short line by default");
looted = LootCorpse(s => s.LootChatSalvage = true);
Check.Eq(LineFor(looted, "Helm"), "[RynthAi] Looted [Salvage] Helm (rule \"Salvage armor\"): Steel, Craft 5",
"Include salvage: the rule, material and workmanship only (no AL)");
});
private static void StackablePlain() => Clocked(() =>
{
List<string> looted = LootCorpse(s => s.LootChatSalvage = true);
Check.Eq(LineFor(looted, "Pyreal"), "[RynthAi] Looted [Keep] Pyreal", "a pyreal stack keeps the plain line");
// Notes and comps by class, any other stack by its stack size; a single unstackable item is described.
var s = new MagItemInfoSettings { LootChatSalvage = true };
Check.Eq(LootChatLine.DetailFor(s, "Keep", false, false, AcObjectClass.TradeNote), LootChatLine.Detail.None, "trade note");
Check.Eq(LootChatLine.DetailFor(s, "Keep", false, false, AcObjectClass.SpellComponent), LootChatLine.Detail.None, "spell component");
Check.Eq(LootChatLine.DetailFor(s, "Keep", false, true, AcObjectClass.Gem), LootChatLine.Detail.None, "a stack of gems");
Check.Eq(LootChatLine.DetailFor(s, "KeepUpTo", false, false, AcObjectClass.Gem), LootChatLine.Detail.Full, "one gem (Keep #)");
Check.Eq(LootChatLine.DetailFor(s, "Recover", false, false, AcObjectClass.Armor), LootChatLine.Detail.None, "own corpse recovery: no rule, plain");
Check.Eq(LootChatLine.DetailFor(s, "ManaTap", false, false, AcObjectClass.Armor), LootChatLine.Detail.None, "mana tap built-in: plain");
});
private static void SettingOffPlain() => Clocked(() =>
{
List<string> looted = LootCorpse(s => { s.LootChat = false; s.LootChatSalvage = true; });
Check.Eq(LineFor(looted, "Blunt Crossbow"), "[RynthAi] Looted [Keep] Blunt Crossbow", "keeper: plain");
Check.Eq(LineFor(looted, "Helm"), "[RynthAi] Looted [Salvage] Helm", "salvage: plain");
Check.Eq(LineFor(looted, "Pyreal"), "[RynthAi] Looted [Keep] Pyreal", "pyreals: plain");
});
private static void SettingsRoundTrip()
{
var fresh = new MagItemInfoSettings();
Check.True(fresh.LootChat, "Describe looted items in chat is on by default");
Check.False(fresh.LootChatSalvage, "Include salvage is off by default");
Check.Eq(fresh.LootChatType, MagItemInfoSettings.SameAsHeader, "loot lines use the Item Info chat type by default");
Check.Eq(LootChatLine.ChatTypeOf(new MagItemInfoSettings { ChatType = 7 }), 7, "...which is ChatType");
// Profile: save, load (CopySettings), save again unchanged.
var saved = new LegacyUiSettings();
saved.ItemInfoSettings.LootChat = false;
saved.ItemInfoSettings.LootChatSalvage = true;
saved.ItemInfoSettings.LootChatType = 24;
string json = JsonSerializer.Serialize(saved, RynthAiJsonContext.Default.LegacyUiSettings);
var live = new LegacyUiSettings();
typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.Static | Any)!
.Invoke(null, new object[] { JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!, live });
Check.False(live.ItemInfoSettings.LootChat, "loot chat off survives");
Check.True(live.ItemInfoSettings.LootChatSalvage, "include salvage survives");
Check.Eq(live.ItemInfoSettings.LootChatType, 24, "loot chat type survives");
Check.Eq(JsonSerializer.Serialize(live, RynthAiJsonContext.Default.LegacyUiSettings), json, "and saves back unchanged");
// A profile from before the setting: on.
var doc = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject();
var infoKey = doc.Select(kv => kv.Key).Single(k => k.Equals("ItemInfoSettings", StringComparison.OrdinalIgnoreCase));
var info = doc[infoKey]!.AsObject();
var lootKey = info.Select(kv => kv.Key).SingleOrDefault(k => k.Equals("LootChat", StringComparison.OrdinalIgnoreCase));
Check.True(lootKey != null, "the field is in the profile JSON");
if (lootKey != null) info.Remove(lootKey);
string old = doc.ToJsonString();
var oldLoaded = JsonSerializer.Deserialize(old, RynthAiJsonContext.Default.LegacyUiSettings)!;
Check.True(oldLoaded.ItemInfoSettings.LootChat, "a profile without it loads it on");
// Reset all to defaults covers them; Sanitize clamps a hand-edited chat type.
saved.ItemInfoSettings.ResetToDefaults();
Check.True(saved.ItemInfoSettings.LootChat && !saved.ItemInfoSettings.LootChatSalvage
&& saved.ItemInfoSettings.LootChatType == MagItemInfoSettings.SameAsHeader, "reset restores the loot options");
saved.ItemInfoSettings.LootChatType = 99;
saved.ItemInfoSettings.Sanitize();
Check.Eq(saved.ItemInfoSettings.LootChatType, MagItemInfoSettings.SameAsHeader, "an out-of-range chat type is cleared");
// The settings map (metas: vtsetsetting / ragetsetting).
var mapSettings = new LegacyUiSettings();
var e = ExpressionTests.Engine(settings: mapSettings);
Check.Eq(e.Evaluate("ragetsetting[ItemInfoLootChat]"), "1", "map reads it");
Check.Eq(e.Evaluate("rasetsetting[ItemInfoLootChat, 0]"), "1", "map sets it");
Check.False(mapSettings.ItemInfoSettings.LootChat, "off through the map");
e.Evaluate("rasetsetting[ItemInfoLootSalvage, 1]");
Check.True(mapSettings.ItemInfoSettings.LootChatSalvage, "include salvage through the map");
// /ra iteminfo loot on|off answers, and changes the setting.
FakeHost.Reset();
var bot = new Bot(FakeHost.Create(Player));
void Cmd(params string[] words) => typeof(RynthAiPlugin).GetMethod("HandleItemInfoCommand", Any)!
.Invoke(bot.P, new object[] { new[] { "ra", "iteminfo" }.Concat(words).ToArray() });
Cmd("loot", "off");
Check.False(bot.S.ItemInfoSettings.LootChat, "/ra iteminfo loot off");
Check.True(FakeHost.Chat.Any(c => c == "[RynthAi] Item info on loot: OFF (salvage OFF)"), "replies: " + string.Join(" | ", FakeHost.Chat));
Cmd("loot", "on");
Check.True(bot.S.ItemInfoSettings.LootChat, "/ra iteminfo loot on");
Check.True(FakeHost.Chat.Any(c => c == "[RynthAi] Item info on loot: ON (salvage OFF)"), "replies on");
Cmd("loot", "salvage", "on");
Check.True(bot.S.ItemInfoSettings.LootChatSalvage, "/ra iteminfo loot salvage on");
Check.True(FakeHost.Chat.Any(c => c == "[RynthAi] Item info on loot, salvage: ON"), "replies salvage");
FakeHost.Chat.Clear();
Cmd("loot", "maybe");
Check.True(bot.S.ItemInfoSettings.LootChat, "a bad word changes nothing");
Check.True(FakeHost.Chat.Any(c => c.Contains("Usage: /ra iteminfo loot on|off")), "and gets the usage: " + string.Join(" | ", FakeHost.Chat));
}
}

View file

@ -0,0 +1,291 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// R-20261031-203155-cea0 (Conquest, indoors, RynthAi 2026.10.31.1): "Plugin says its looting but it
// doesn't." The arbiter logged Looting with want[loot=True] for 12 s after a kill, and not one
// "Corpse loot:" line followed (no [LootSettings] line the whole session either). Boost Nav Priority
// was on with no route to run: the arbiter's BoostNav clause is guarded by WantNav, so Looting won,
// while TickCorpseOpening's full stop took the flag alone and reset every claim. Owner's rule
// (2026-10-31): Boost Nav Priority means no looting at all, so HasLootWork offers nothing either. The kill's corpse
// ('Treasure of ...', no corpse name) was first filed as a no-position inventory Container and
// rescued to Corpse by its weenie flag 3 s later; it must be claimed and looted like any other.
// The loot clock (CorpseOpenController.CorpseClock) is moved by hand; the server answers at once.
internal static class LootClaimMismatchTests
{
private const uint Player = 0x50000D51;
private const uint Corpse = 0x80265100;
private const uint Gem = 0x80265101;
private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800;
private const uint BfCorpse = 0x2000;
private const uint LongDescKey = 16;
private const string Me = "Test Hunter";
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
private const long TickMs = 25;
private static (uint Cell, float X, float Y, float Z) Me0 => (0x482D0102u, 40f, 60f, 0f);
public static void Register(Runner r)
{
r.Add("loot claim (R-20261031-203155-cea0): a corpse first filed as a no-position inventory Container, then rescued, is claimed and looted", RescuedCorpseLooted);
r.Add("loot claim (R-20261031-203155-cea0): Boost Nav Priority with no route: no loot work, never in Looting; looted once the flag is off", BoostNavNoRouteLoots);
r.Add("loot claim (R-20261031-203155-cea0): Boost Nav Priority with a route, then none: nav has the tick, nothing claimed either way", BoostNavWithRouteYields);
r.Add("loot claim (R-20261031-203155-cea0): Looting with nothing claimed is logged with the reason after 3 s, then throttled", LootStallLogged);
}
// ── Clock and world ───────────────────────────────────────────────────────
private static long _now;
private static void Clocked(Action body)
{
var old = RynthAiPlugin.CorpseClock;
_now = 80_000_000;
RynthAiPlugin.CorpseClock = () => _now;
try { body(); }
finally { RynthAiPlugin.CorpseClock = old; }
}
/// <summary>The report's corpse: its name is no corpse name, and it is created before its
/// position and weenie flag read (the "nopos-item" branch files it as an inventory Container).</summary>
private static void World()
{
FakeHost.Reset();
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.Names[Player] = Me;
FakeHost.Positions[Player] = Me0;
FakeHost.PlayerPose = Me0;
FakeHost.Bitfields[Player] = 0; // installs GetObjectBitfield; the corpse's flag reads 0 for now
FakeHost.Names[Corpse] = "Treasure of Corrupted Dread";
FakeHost.ItemTypes[Corpse] = ItemTypeContainer;
FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}.";
FakeHost.NotAttackable.Add(Corpse);
FakeHost.Names[Gem] = "Black Opal";
FakeHost.ItemTypes[Gem] = ItemTypeGem;
FakeHost.Containers[Gem] = Corpse; // also installs GetObjectOwnershipInfo
FakeHost.Appraised.Add(Gem);
}
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new()
{
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
};
public readonly WorldObjectCache Cache;
private int _seenMoves;
public Bot(RynthCoreHost host)
{
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
Set("_dashboard", dash);
Cache = new WorldObjectCache(host);
Cache.SetPlayerId(Player);
Set("_objectCache", Cache);
Set("_playerId", Player);
Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
string profile = Path.Combine(Program.TempRoot, "loot-claim-mismatch.json");
var p = new LootProfile { Name = "gems" };
var rule = new LootRule { Name = "Gems", Action = LootAction.Keep };
rule.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
p.Rules.Add(rule);
p.Save(profile);
S.CurrentLootPath = profile;
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
public bool HasLootWork() => (bool)Call("HasLootWork", S, _now)!;
public bool NavWants() => (bool)Call("NavWantsTick", S)!;
/// <summary>The arbiter's decision from the real wants, as OnTick builds it (no buffing, no combat).</summary>
public BotActivity Decide()
{
var inputs = new ArbiterInputs(S.IsMacroRunning, false, false, HasLootWork(), false, NavWants(),
boostNav: S.BoostNavPriority, boostLoot: S.BoostLootPriority);
return ActivityArbiter.Decide(in inputs);
}
/// <summary>One plugin tick: the clock moves on, the arbiter decides, the looter runs, and
/// the server lands each move in the pack at once.</summary>
public BotActivity Tick()
{
_now += TickMs;
BotActivity act = Decide();
Set("_activity", act);
Call("TickCorpseOpening");
while (_seenMoves < FakeHost.ExternalMoves.Count)
{
var m = FakeHost.ExternalMoves[_seenMoves++];
FakeHost.Containers[m.Id] = m.Target;
}
return act;
}
public bool Completed => Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)Corpse));
public int Claimed => Get<int>("_targetCorpseId");
}
private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
private static int LoggedCount(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal));
/// <summary>The corpse created without a position or flag (filed as inventory), then its
/// position and flag land and the 2 s pass rescues it.</summary>
private static Bot RescuedCorpse()
{
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Cache.OnCreateObject(Corpse);
bot.Cache.OnCreateObject(Gem);
for (int i = 0; i < 20; i++) bot.Cache.Tick();
Check.Eq(bot.Cache[unchecked((int)Corpse)]?.ObjectClass, AcObjectClass.Container, "first filed as a Container (the report's state)");
Check.True(bot.Cache.GetInventory().Any(o => o.Id == unchecked((int)Corpse)), "in the inventory");
Check.False(bot.HasLootWork(), "no loot work while it sits in the inventory");
FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
FakeHost.Bitfields[Corpse] = BfCorpse;
typeof(WorldObjectCache).GetField("_lastReclassifyTime", Any)!.SetValue(bot.Cache, DateTime.MinValue);
bot.Cache.Tick();
Check.True(Logged("was filed as Container (inventory, no position when classified); now a Corpse"), "the rescue is logged as in the report");
Check.Eq(bot.Cache[unchecked((int)Corpse)]?.ObjectClass, AcObjectClass.Corpse, "rescued to Corpse");
Check.True(bot.Cache.GetLandscapeObjects().Any(o => o.Id == unchecked((int)Corpse)), "on the landscape");
return bot;
}
/// <summary>Ticks to the end of the corpse; the server opens it on the first use.</summary>
private static void LootToTheEnd(Bot bot)
{
long end = _now + 30_000;
bool opened = false;
while (_now < end && !bot.Completed)
{
bot.Tick();
if (!opened && FakeHost.Uses.Contains(Corpse))
{
opened = true;
FakeHost.UseDone(0);
bot.P.OnViewObjectContents(Corpse);
}
}
}
// ── 1. The rescued corpse ─────────────────────────────────────────────────
private static void RescuedCorpseLooted() => Clocked(() =>
{
World();
var bot = RescuedCorpse();
Check.True(bot.HasLootWork(), "the arbiter counts it as loot work");
Check.Eq(bot.Tick(), BotActivity.Looting, "Looting has the tick");
Check.Eq(bot.Claimed, unchecked((int)Corpse), "and the claim takes the rescued corpse");
Check.True(Logged("claimed corpse target 0x80265100"), "claim logged");
LootToTheEnd(bot);
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem && m.Target == Player), "the gem is moved into the pack");
Check.True(bot.Completed, "the corpse is finished");
Check.False(bot.HasLootWork(), "no loot work left: the bot leaves Looting");
});
// ── 2. The report: Boost Nav Priority on, nothing to navigate ─────────────
// Owner, 2026-10-31: Boost Nav Priority means no looting at all, route or not.
private static void BoostNavNoRouteLoots() => Clocked(() =>
{
World();
var bot = RescuedCorpse();
bot.S.BoostNavPriority = true;
bot.S.BoostLootPriority = true; // both on, as in the report: nav wins
bot.S.EnableNavigation = true; // on, but no route loaded (want[nav=False] in the report)
Check.False(bot.NavWants(), "nav has nothing to run");
Check.False(bot.HasLootWork(), "Boost Nav Priority: no loot work, the corpse is passed by");
Check.True(bot.Decide() != BotActivity.Looting, "the arbiter never gives Looting the tick");
for (int i = 0; i < 200; i++) Check.True(bot.Tick() != BotActivity.Looting, "never in Looting (5 s)");
Check.Eq(bot.Claimed, 0, "nothing claimed");
Check.False(FakeHost.Uses.Contains(Corpse), "nothing opened");
Check.False(Logged("Looting has held the tick"), "no stall: Looting never had the tick");
bot.S.BoostNavPriority = false; // the flag off: the corpse is looted as usual
Check.True(bot.HasLootWork(), "loot work again");
bot.Tick();
Check.Eq(bot.Claimed, unchecked((int)Corpse), "the corpse is claimed");
LootToTheEnd(bot);
Check.True(bot.Completed, "looted to the end");
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem && m.Target == Player), "the gem is in the pack");
});
// ── 3. Boost Nav Priority with a route still yields to nav ────────────────
private static void BoostNavWithRouteYields() => Clocked(() =>
{
World();
var bot = RescuedCorpse();
bot.S.BoostNavPriority = true;
bot.S.EnableNavigation = true;
var route = new NavRouteParser { RouteType = NavRouteType.Linear };
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 10.5, EW = -3.25 });
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 11.5, EW = -4.25 });
bot.S.CurrentRoute = route;
Check.True(bot.NavWants(), "nav has a route to run");
Check.False(bot.HasLootWork(), "no loot work to offer: the looter stands down for the route");
Check.Eq(bot.Decide(), BotActivity.Navigating, "nav has the tick");
for (int i = 0; i < 200; i++) bot.Tick(); // 5 s
Check.Eq(bot.Claimed, 0, "nothing claimed");
Check.False(FakeHost.Uses.Contains(Corpse), "nothing opened");
Check.False(Logged("Looting has held the tick"), "not a Looting stall: Looting never had the tick");
bot.S.CurrentRoute = null; // the route is unloaded: still no looting while the flag is on
Check.True(bot.Tick() != BotActivity.Looting, "no route, flag on: still no Looting");
Check.Eq(bot.Claimed, 0, "still nothing claimed");
});
// ── 4. A stall is never silent ────────────────────────────────────────────
private static void LootStallLogged() => Clocked(() =>
{
World();
var bot = RescuedCorpse();
bot.Set("_lootHaltUntil", _now + 60_000); // the loot-wedge halt: no claim while the corpse waits in range
const string Stall = "Looting has held the tick";
Check.Eq(bot.Tick(), BotActivity.Looting, "the corpse in range gives Looting the tick");
Check.Eq(bot.Claimed, 0, "nothing claimed");
for (int i = 0; i < (int)(RynthAiPlugin.LootStallLogMs / TickMs) - 10; i++) bot.Tick();
Check.False(Logged(Stall), "a short gap is not a stall");
for (int i = 0; i < 20; i++) bot.Tick();
Check.Eq(LoggedCount(Stall), 1, "past LootStallLogMs the stall is logged once");
string line = FakeHost.Logs.First(l => l.Contains(Stall, StringComparison.Ordinal));
Check.True(line.Contains("loot-wedge halt"), $"with the claim's skip reason ({line})");
Check.True(line.Contains("loot work: 1 lootable corpse(s) in range, e.g. 0x80265100"), $"and what the arbiter counted as loot work ({line})");
for (int i = 0; i < 200; i++) bot.Tick(); // 5 s more
Check.Eq(LoggedCount(Stall), 1, "throttled: not again within LootStallRepeatMs");
for (int i = 0; i < (int)(RynthAiPlugin.LootStallRepeatMs / TickMs); i++) bot.Tick();
Check.Eq(LoggedCount(Stall), 2, "logged again after LootStallRepeatMs");
bot.Set("_lootHaltUntil", 0L);
bot.Tick();
Check.Eq(bot.Claimed, unchecked((int)Corpse), "once the halt ends the corpse is claimed");
Check.True(Logged("the Looting stall is over"), "and the end of the stall is logged");
});
}

View file

@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-10-31, the corpse looter with LootSnob (Fixtures\lootsnob-excerpt.utl plus a Salvage rule
// on gold alone): a crossbow whose ID is late is held, asked for again, and in the end left on the
// corpse; it is never judged without its ID, where its stats read 0 and the gold rule took it
// ("best-effort" after the wait, until today). One whose ID comes in time is kept by its rule.
// The loot clock (CorpseClock) is moved by hand.
internal static class LootLateIdTests
{
private const uint Player = 0x50000D41;
private const uint Corpse = 0x80264100;
private const uint Xbow = 0x80264101;
private const uint ItemTypeContainer = 0x200, ItemTypeMissile = 0x100;
private const uint LongDescKey = 16;
private const string Me = "Ilsa Corvane";
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
public static void Register(Runner r)
{
r.Add("loot late ID: a crossbow whose ID never comes is held, asked again, then left - never the Salvage rule", IdNeverComes);
r.Add("loot late ID: a crossbow whose ID comes after the wait is kept by its LootSnob rule", IdComesLate);
}
private static long _now;
private static void Clocked(Action body)
{
var old = RynthAiPlugin.CorpseClock;
_now = 60_000_000;
RynthAiPlugin.CorpseClock = () => _now;
try { body(); }
finally { RynthAiPlugin.CorpseClock = old; }
}
private static void World()
{
FakeHost.Reset();
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.Names[Player] = Me;
FakeHost.Positions[Player] = Me0;
FakeHost.PlayerPose = Me0;
FakeHost.Names[Corpse] = "Corpse of Olthoi Swarm Drone";
FakeHost.ItemTypes[Corpse] = ItemTypeContainer;
FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}.";
FakeHost.NotAttackable.Add(Corpse);
FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
// What the CreateObject shows: name, type, slot, value, burden, material (gold).
FakeHost.Names[Xbow] = "Blunt Crossbow";
FakeHost.ItemTypes[Xbow] = ItemTypeMissile;
FakeHost.Containers[Xbow] = Corpse;
foreach (var (k, v) in new (uint, int)[] { (1, 0x100), (9, 0x00400000), (19, 12000), (5, 600), (131, 60) })
FakeHost.Ints[(Xbow, k)] = v;
}
/// <summary>The ID lands: workmanship, weapon type, wield, +22, damage mod 2.62, Legendary Blood Thirst.</summary>
private static void Identify()
{
foreach (var (k, v) in new (uint, int)[] { (105, 6), (353, 9), (158, 2), (159, 47), (160, 385), (204, 22), (45, 4), (48, 47) })
FakeHost.Ints[(Xbow, k)] = v;
FakeHost.Doubles[(Xbow, 63)] = 2.62;
FakeHost.Doubles[(Xbow, 29)] = 1.15;
FakeHost.SpellIds[Xbow] = new[] { (uint)SpellDatabase.GetIdByName("Legendary Blood Thirst") };
FakeHost.Appraised.Add(Xbow);
}
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new()
{
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
LootAssessWindowMs = 200, LootCorpseTimeoutMs = 12_000,
};
public readonly WorldObjectCache Cache;
public Bot(RynthCoreHost host)
{
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
Set("_dashboard", dash);
Cache = new WorldObjectCache(host);
Cache.SetPlayerId(Player);
Set("_objectCache", Cache);
Set("_playerId", Player);
Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
// LootSnob's excerpt and, last, a Salvage rule on gold alone (no workmanship), so the
// crossbow judged without its ID would be salvaged.
VTankLootProfile p = VTankLootParser.Load(Path.Combine(AppContext.BaseDirectory, "Fixtures", "lootsnob-excerpt.utl"));
var gold = new VTankLootRule { Name = "Gold any", Action = VTankLootAction.Salvage };
gold.Conditions.Add(new VTankLootCondition(VTankNodeTypes.LongValKeyE, "0", new[] { "60", "131" }));
p.Rules.Add(gold);
string path = Path.Combine(Program.TempRoot, "loot-late-id.utl");
File.WriteAllText(path, VTankLootWriter.Serialize(p));
S.CurrentLootPath = path;
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
public void Tick()
{
Set("_activity", BotActivity.Looting);
typeof(RynthAiPlugin).GetMethod("TickCorpseOpening", Any)!.Invoke(P, null);
}
public void TickFor(long ms)
{
long end = _now + ms;
while (_now < end) { _now += 20; Tick(); }
}
public bool Completed(uint corpse) =>
Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)corpse));
}
private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
private static bool Moved() => FakeHost.ExternalMoves.Any(m => m.Id == Xbow);
private static Bot OpenCorpse()
{
World();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Cache.OnCreateObject(Corpse);
bot.Cache.OnCreateObject(Xbow);
bot.Cache.Tick();
bot.Tick();
Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened");
FakeHost.UseDone(0);
bot.P.OnViewObjectContents(Corpse);
bot.TickFor(100);
Check.True(FakeHost.IdRequests.Contains(Xbow), "the crossbow's ID is asked for (a LootSnob rule that could take it needs it)");
return bot;
}
private static void IdNeverComes() => Clocked(() =>
{
var bot = OpenCorpse();
bot.TickFor(4_000); // past the assess window and AppraisalWaitMs
Check.False(Moved(), "not taken without its ID (the old best-effort took it for Gold salvage)");
Check.True(FakeHost.IdRequests.Count(id => id == Xbow) >= 2, "its ID is asked for again");
Check.True(Logged("no ID yet and a rule that decides it needs one"), "and that is logged");
for (int i = 0; i < 1000 && !bot.Completed(Corpse); i++) { _now += 20; bot.Tick(); }
Check.False(Moved(), "still not taken when the corpse is given up");
Check.True(Logged("left: no ID came, and a rule that decides it needs one"), "left on the corpse, and said why");
Check.True(bot.Completed(Corpse), "the corpse is finished");
Check.False(FakeHost.Chat.Any(c => c.Contains("Gold any")), "the Salvage rule never named");
});
private static void IdComesLate() => Clocked(() =>
{
var bot = OpenCorpse();
bot.TickFor(5_000); // later than the old wait gave it
Check.False(Moved(), "held while the ID is out");
Identify();
for (int i = 0; i < 200 && !Moved(); i++) { _now += 20; bot.Tick(); }
Check.True(Moved(), "taken once the ID is in");
Check.True(FakeHost.Chat.Any(c => c.Contains("Loot rule: Blunt Crossbow -> [Keep] (M) Xbow (OD +9)")),
"by LootSnob's Xbow (OD +9) (chat: " + string.Join(" | ", FakeHost.Chat.Where(c => c.Contains("Loot rule"))) + ")");
});
}

View file

@ -0,0 +1,249 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Owner, 2026-10-31: a corpse or chest whose only matching items were Keep # (or mana-stone)
// items already at their count ended with just "Keep # '<rule>': have N/N — leaving <item>." and
// never a "nothing to loot" line: "It should report nothing to loot as well." The end-of-container
// line now counts confirmed pickups, not matches (NothingLootedLine).
// The loot clock (CorpseOpenController.CorpseClock) is moved by hand; the server answers at once.
internal static class LootNothingLineTests
{
private const uint Player = 0x50000D61;
private const uint Corpse = 0x80266100;
private const uint Chest = 0x7A9B6001; // a landblock chest (static id)
private const uint Gem = 0x80266101;
private const uint PackGem = 0x80266102; // one already in the pack: the Keep # 1 is met
private const uint Stone = 0x80266103, PackStone = 0x80266104;
private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800, ItemTypeManaStone = 0x80000;
private const uint LongDescKey = 16;
private const string Me = "Test Hunter";
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
private const long TickMs = 25;
private const string Enough = "item(s) match, but you already have enough.";
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
public static void Register(Runner r)
{
r.Add("nothing to loot: a corpse whose only match is a Keep # at its count ends with 'you already have enough'", CappedCorpseSaysNothingToLoot);
r.Add("nothing to loot: a corpse with a looted item says no 'nothing to loot'", LootedCorpseSaysNothing);
r.Add("nothing to loot: a chest whose only match is a Keep # at its count ends with 'you already have enough'", CappedChestSaysNothingToLoot);
r.Add("nothing to loot: a corpse with no matching item keeps 'matches the loot profile'", NoMatchKeepsOldLine);
r.Add("nothing to loot: a corpse whose only match is a mana stone at its keep count ends with 'you already have enough'", CappedManaStoneSaysNothingToLoot);
}
// ── Clock and world ───────────────────────────────────────────────────────
private static long _now;
private static void Clocked(Action body)
{
var old = RynthAiPlugin.CorpseClock;
_now = 90_000_000;
RynthAiPlugin.CorpseClock = () => _now;
try { body(); }
finally { RynthAiPlugin.CorpseClock = old; }
}
private static void World(bool chest, bool gemInPack)
{
FakeHost.Reset();
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.CloseContainerCalls = true; // CloseContainer + GetGroundContainerId
FakeHost.ContentsCalls = true; // GetContainerContents: the Keep # count walks the pack
FakeHost.Names[Player] = Me;
FakeHost.Positions[Player] = Me0;
FakeHost.PlayerPose = Me0;
uint box = chest ? Chest : Corpse;
FakeHost.Names[box] = chest ? "Chest" : "Corpse of Brier Wasp";
FakeHost.ItemTypes[box] = ItemTypeContainer;
FakeHost.Positions[box] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
FakeHost.NotAttackable.Add(box);
if (chest) FakeHost.Containers[Chest] = 0; // lies in the world
else FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}.";
AddGem(Gem, "Black Opal", box);
if (gemInPack) AddGem(PackGem, "Black Opal", Player);
}
private static void AddGem(uint id, string name, uint container)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = ItemTypeGem;
FakeHost.Containers[id] = container;
FakeHost.Appraised.Add(id);
}
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new()
{
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
};
public readonly WorldObjectCache Cache;
public readonly RynthCoreHost Host;
private int _seenMoves;
/// <param name="keepOne">Gems are Keep # 1; otherwise the profile wants only armor.</param>
public Bot(RynthCoreHost host, bool keepOne)
{
Host = host;
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
Set("_dashboard", dash);
Cache = new WorldObjectCache(host);
Cache.SetPlayerId(Player);
Set("_objectCache", Cache);
Set("_playerId", Player);
Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
string profile = Path.Combine(Program.TempRoot, keepOne ? "loot-nothing-keep1.json" : "loot-nothing-armor.json");
var p = new LootProfile { Name = "nothing-line" };
var rule = keepOne
? new LootRule { Name = "Gems", Action = LootAction.KeepUpTo, KeepCount = 1 }
: new LootRule { Name = "Armor", Action = LootAction.Keep };
rule.Conditions.Add(new ObjectClassCondition { ObjectClass = keepOne ? AcObjectClass.Gem : AcObjectClass.Armor });
p.Rules.Add(rule);
p.Save(profile);
S.CurrentLootPath = profile;
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
/// <summary>One Looting tick; the server lands each move in the pack at once.</summary>
public void Tick()
{
_now += TickMs;
Set("_activity", BotActivity.Looting);
Call("TickCorpseOpening");
while (_seenMoves < FakeHost.ExternalMoves.Count)
{
var m = FakeHost.ExternalMoves[_seenMoves++];
FakeHost.Containers[m.Id] = m.Target;
}
}
public void Create(params uint[] ids)
{
foreach (uint id in ids) Cache.OnCreateObject(id);
for (int i = 0; i < 5; i++) Cache.Tick();
}
public bool CorpseDone => Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)Corpse));
}
private static bool Said(string part) => FakeHost.Chat.Any(l => l.Contains(part, StringComparison.Ordinal));
private static string ChatDump() => string.Join(" | ", FakeHost.Chat);
/// <summary>Claims, opens (the server's ViewContents) and loots the corpse to its end.</summary>
private static Bot LootCorpse(bool keepOne, bool gemInPack, Action<Bot>? setUp = null, params uint[] extra)
{
World(chest: false, gemInPack);
foreach (uint id in extra)
{
FakeHost.Names[id] = "Mana Stone";
FakeHost.ItemTypes[id] = ItemTypeManaStone;
FakeHost.Containers[id] = id == PackStone ? Player : Corpse;
FakeHost.Appraised.Add(id);
}
var host = FakeHost.Create(Player);
var bot = new Bot(host, keepOne);
setUp?.Invoke(bot);
var ids = new List<uint> { Corpse, Gem };
if (gemInPack) ids.Add(PackGem);
ids.AddRange(extra);
bot.Create(ids.ToArray());
long end = _now + 30_000;
bool opened = false;
while (_now < end && !bot.CorpseDone)
{
bot.Tick();
if (!opened && FakeHost.Uses.Contains(Corpse))
{
opened = true;
FakeHost.UseDone(0);
FakeHost.GroundContainer = Corpse;
bot.P.OnViewObjectContents(Corpse);
bot.P.OnUpdateObjectInventory(Corpse);
}
}
Check.True(opened, "the corpse is opened");
Check.True(bot.CorpseDone, "the corpse is finished");
return bot;
}
// ── Tests ─────────────────────────────────────────────────────────────────
private static void CappedCorpseSaysNothingToLoot() => Clocked(() =>
{
LootCorpse(keepOne: true, gemInPack: true);
Check.True(Said("Keep # 'Gems': have 1/1"), $"the Keep # leave is said as before ({ChatDump()})");
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "the gem is left");
Check.True(Said("[RynthAi] Nothing to loot on Corpse of Brier Wasp: 1 " + Enough), $"and the end says there was nothing to loot ({ChatDump()})");
Check.False(Said("matches the loot profile"), "not 'nothing matches': the gem did match");
});
private static void LootedCorpseSaysNothing() => Clocked(() =>
{
LootCorpse(keepOne: true, gemInPack: false);
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem && m.Target == Player), "the gem is looted (none in the pack yet)");
Check.True(Said("Looted [KeepUpTo] Black Opal"), $"and said ({ChatDump()})");
Check.False(Said("Nothing to loot"), "no 'nothing to loot' line");
Check.False(Said("matches the loot profile"), "nor 'nothing matches'");
});
private static void CappedChestSaysNothingToLoot() => Clocked(() =>
{
World(chest: true, gemInPack: true);
var host = FakeHost.Create(Player);
var bot = new Bot(host, keepOne: true);
bot.Create(Chest, Gem, PackGem);
FakeHost.GroundContainer = Chest; // the player opened it
bot.P.OnViewObjectContents(Chest);
bot.P.OnUpdateObjectInventory(Chest);
long end = _now + 30_000;
while (_now < end && !FakeHost.Closes.Contains(Chest)) bot.Tick();
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot: done with chest")), "the chest session ends");
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "the gem is left");
Check.True(Said("[RynthAi] Nothing to loot on Chest: 1 " + Enough), $"the end says there was nothing to loot ({ChatDump()})");
});
private static void NoMatchKeepsOldLine() => Clocked(() =>
{
LootCorpse(keepOne: false, gemInPack: false);
Check.True(Said("[RynthAi] Nothing on Corpse of Brier Wasp matches the loot profile."), $"the old line ({ChatDump()})");
Check.False(Said("Nothing to loot"), "and no second line");
});
private static void CappedManaStoneSaysNothingToLoot() => Clocked(() =>
{
// The profile wants armor only; the stone is the built-in mana-stone rule (tapping on, keep 1),
// which never counted as an evaluated item (alone on a corpse it ended with no line at all).
LootCorpse(keepOne: false, gemInPack: false, bot =>
{
bot.S.EnableManaTapping = true;
bot.S.ManaStoneKeepCount = 1;
bot.Set("_manaStoneManager", new ManaStoneManager(bot.Host, bot.S, bot.Cache));
}, Stone, PackStone);
Check.True(Said("Mana stone match: 'Mana Stone' (have 1/1)"), $"the stone is left at its keep count ({ChatDump()})");
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Stone), "the stone stays on the corpse");
Check.True(Said("[RynthAi] Nothing to loot on Corpse of Brier Wasp: 1 " + Enough), $"the end says there was nothing to loot ({ChatDump()})");
});
}

View file

@ -0,0 +1,271 @@
using System;
using System.IO;
using System.Linq;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
using N = RynthCore.Loot.VTank.VTankNodeTypes;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-10-31: "a +9 bludg xbow that rynth sees as gold salvage", with LootSnob, which VTank keeps.
// Fixtures\lootsnob-excerpt.utl is LootSnobV4's melee head, missile and void wand sections and six
// of its Salvage rules (switched on, as players have them), in the file's own order.
// Two causes:
// 1. "Calc'd Buffed Missile Damage" read max damage x the wand elemental modifier (152). A launcher
// has no max damage, so it was 0 and every one of LootSnob's 33 missile damage keeps failed; the
// crossbow fell to "(Salv) Gold". VTank: max damage + (mod - 1) x 100 / 3 + elemental bonus,
// buffed by the item's cantrips (Legendary Blood Thirst +10): 0 + 54 + 22 + 10 = 86, "Xbow (OD +9)".
// 2. An item whose ID was late was judged without it after the wait ("best-effort"): its stats read
// 0, the keep rules failed and a Salvage rule on its material took it. Now it waits, and is left.
internal static class LootRuleMatchTests
{
private const uint Player = 0x50000A01;
public static void Register(Runner r)
{
r.Add("loot rule match: a +9 crossbow (LootSnob 'Xbow (OD +9)') is kept, not Gold salvage", PlusNineCrossbow);
r.Add("loot rule match: without its ID the crossbow waits for it, never the Salvage rule", CrossbowWithoutId);
r.Add("loot rule match: missile damage of bows, crossbows and atlatls at LootSnob's thresholds", MissileDamageThresholds);
r.Add("loot rule match: buffed keys add the item's cantrips (Blood Thirst, Defender, Heart/Spirit Thirst, Impen, Hermetic)", BuffedCantrips);
r.Add("loot rule match: double keys compare as floats (1.20 + 0.09 >= 1.29)", FloatCompare);
r.Add("loot rule match: tinked damage and tinked target melee (VTank's worked examples)", TinkedNodes);
r.Add("loot rule match: which conditions need the ID", ConditionsNeedingId);
r.Add("loot rule match: Decide passes over a rule a known condition fails, in any order", DecideOrder);
r.Add("loot rule match: /ra loot why lists the rules above that came close, with the value read", LootWhyExplains);
}
private static VTankLootProfile Excerpt()
=> VTankLootParser.Load(Path.Combine(AppContext.BaseDirectory, "Fixtures", "lootsnob-excerpt.utl"));
private static int Spell(string name)
{
int id = SpellDatabase.GetIdByName(name);
if (id == 0) throw new InvalidOperationException($"spell '{name}' is not in SpellData.txt");
return id;
}
private static VTankLootContext Ctx() => new(FakeHost.Create(), Player);
private static void WithSpells(Item item, params string[] names)
=> FakeHost.SpellIds[unchecked((uint)item.Wo.Id)] = names.Select(n => (uint)Spell(n)).ToArray();
// A 385 crossbow as ACE's crossbow_elemental mutation makes it: +22, damage mod 2.62, gold,
// workmanship 6, Legendary Blood Thirst. No max damage (launchers have none).
private static Item PlusNineXbow(bool withId = true)
{
var x = new Item("Blunt Crossbow", AcObjectClass.MissileWeapon)
.Int(1, 0x100).Int(9, 0x00400000).Int(19, 12000).Int(5, 600).Int(131, 60);
if (withId)
{
x.Int(105, 6).Int(353, 9).Int(158, 2).Int(159, 47).Int(160, 385).Int(204, 22).Int(45, 4).Int(48, 47)
.Dbl(63, 2.62).Dbl(29, 1.15).Dbl(149, 1.0).Dbl(150, 1.0);
WithSpells(x, "Legendary Blood Thirst");
}
return x;
}
private static void PlusNineCrossbow()
{
FakeHost.Reset();
VTankLootProfile p = Excerpt();
var xbow = PlusNineXbow();
var ctx = Ctx();
VTankLootRule? rule = VTankLootEvaluator.FirstMatch(p, xbow, ctx, out int idx);
Check.NotNull(rule, "a rule takes it");
Check.Eq(rule?.Name.Trim(), "(M) Xbow (OD +9)", "LootSnob's Xbow (OD +9), as VTank");
Check.Eq(rule?.Action, VTankLootAction.Keep, "kept");
Check.Near(VTankLootEvaluator.BuffedMissileDamage(xbow, unchecked((uint)xbow.Wo.Id), ctx), 86.0, 1e-9, "0 + 162/3 + 22 + 10");
// Without the cantrip it's 76, under every crossbow damage keep, and its 1.15 melee defense is
// under the 20MD rules: VTank salvages that one too.
FakeHost.Reset();
var plain = PlusNineXbow();
FakeHost.SpellIds.Remove(unchecked((uint)plain.Wo.Id));
Check.Eq(VTankLootEvaluator.FirstMatch(p, plain, Ctx(), out _)?.Name.Trim(), "(Salv) Gold", "76 with no cantrip: Gold salvage, in VTank too");
}
private static void CrossbowWithoutId()
{
FakeHost.Reset();
VTankLootProfile p = Excerpt();
var bare = PlusNineXbow(withId: false); // only what the CreateObject shows: no workmanship, stats or spells
Check.Eq(VTankLootEvaluator.Decide(p, bare, Ctx(), hasIdData: false, out int idx), VTankLootVerdict.NeedsId, "waits for the ID");
Check.Eq(p.Rules[idx].Name.Trim(), "(M) Bow (OD +10)", "at the first missile rule: its weapon type needs the ID");
// Judged as if the ID were in (the old best-effort), it read 0s: no keep, and since the
// workmanship is ID data too it was left; with a Salvage rule on material only it was salvaged.
Check.Null(VTankLootEvaluator.FirstMatch(p, bare, Ctx(), out _), "judged with 0s nothing keeps it");
var materialOnly = new VTankLootProfile();
materialOnly.Rules.AddRange(p.Rules.Where(r => r.Action == VTankLootAction.Keep));
var salvGold = new VTankLootRule { Name = "Gold any", Action = VTankLootAction.Salvage };
salvGold.Conditions.Add(new VTankLootCondition(N.LongValKeyE, "0", new[] { "60", "131" }));
materialOnly.Rules.Add(salvGold);
Check.Eq(VTankLootEvaluator.FirstMatch(materialOnly, bare, Ctx(), out _)?.Name, "Gold any", "the old best-effort: the material rule took it");
Check.Eq(VTankLootEvaluator.Decide(materialOnly, bare, Ctx(), hasIdData: false, out _), VTankLootVerdict.NeedsId, "now it waits for the ID");
// A gem with no rule above that could want it is decided without an ID.
var gem = new Item("Opal", AcObjectClass.Gem).Int(1, 0x800).Int(19, 300);
Check.Eq(VTankLootEvaluator.Decide(p, gem, Ctx(), hasIdData: false, out _), VTankLootVerdict.NoMatch, "a gem needs no ID here");
}
private static Item Launcher(int weaponType, double mod, int elem)
=> new Item("Launcher", AcObjectClass.MissileWeapon).Int(353, weaponType).Int(159, 47).Int(204, elem).Dbl(63, mod).Dbl(29, 1.0);
private static string? First(VTankLootProfile p, Item item) => VTankLootEvaluator.FirstMatch(p, item, Ctx(), out _)?.Name.Trim();
private static void MissileDamageThresholds()
{
FakeHost.Reset();
VTankLootProfile p = Excerpt();
// LootSnob's maxima at wield 385: crossbow 77, bow 68.6, atlatl 75.3 (2.65 / 2.40 / 2.60 and +22).
Check.Eq(First(p, Launcher(9, 2.65, 22)), "(M) Xbow (Max 385)", "crossbow 165/3 + 22 = 77");
Check.Eq(First(p, Launcher(8, 2.40, 22)), "(M) Bow (Max 385)", "bow 140/3 + 22 = 68.67");
Check.Null(First(p, Launcher(10, 2.60, 22)), "atlatl 75.33: LootSnob's TW (Max 385) is switched off, OD +1 wants 76.3");
Check.Null(First(p, Launcher(9, 2.65, 21)), "a 76 crossbow (and no material to salvage): no rule");
Check.Eq(First(p, Launcher(9, 2.65, 22).Int(131, 60).Int(105, 5)), "(M) Xbow (Max 385)", "a gold one at 77 is kept, not salvaged");
Check.Eq(First(p, Launcher(9, 2.65, 21).Int(131, 60).Int(105, 5)), "(Salv) Gold", "a gold one at 76 is salvaged");
var epicAtlatl = Launcher(10, 2.60, 22);
WithSpells(epicAtlatl, "Epic Blood Thirst");
Check.Eq(First(p, epicAtlatl), "(M) TW (OD +7)", "atlatl 75.33 + Epic Blood Thirst 7 = 82.33");
}
private static void BuffedCantrips()
{
FakeHost.Reset();
static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
// A fresh context each time: one caches the spells it read for its evaluation pass.
static bool M(Item i, VTankLootCondition c) => VTankLootEvaluator.Match(new VTankLootRule { Conditions = { c } }, i, Ctx());
var axe = new Item("Axe").Int(44, 74);
Check.False(M(axe, C(N.BuffedLongValKeyGE, "84", "218103842")), "74 alone");
WithSpells(axe, "Legendary Blood Thirst");
Check.True(M(axe, C(N.BuffedLongValKeyGE, "84", "218103842")), "74 + Legendary Blood Thirst 10 (Decal MaxDamage key)");
Check.False(M(axe, C(N.BuffedLongValKeyGE, "85", "218103842")), "and no more");
Check.False(M(axe, C(N.LongValKeyGE, "75", "218103842")), "the plain key is not buffed");
var coat = new Item("Coat").Int(28, 500);
WithSpells(coat, "Epic Impenetrability", "Impenetrability VI");
Check.True(M(coat, C(N.BuffedLongValKeyGE, "560", "28")), "armor 500 + Epic Impen 60; Impen VI (castable) adds nothing");
Check.False(M(coat, C(N.BuffedLongValKeyGE, "561", "28")), "no more");
var bow = new Item("Bow").Dbl(29, 1.20);
WithSpells(bow, "Legendary Defender");
Check.True(M(bow, C(N.BuffedDoubleValKeyGE, "1.29", "29")), "melee defense 1.20 + Legendary Defender 0.09");
var sword = new Item("Sword").Dbl(62, 1.10);
WithSpells(sword, "Major Heart Thirst");
Check.True(M(sword, C(N.BuffedDoubleValKeyGE, "1.15", "167772172")), "attack (VTank AttackBonus key) 1.10 + Major Heart Thirst 0.05");
var wand = new Item("Nether Baton").Dbl(152, 1.18).Dbl(144, 0.10);
WithSpells(wand, "Legendary Spirit Thirst", "Legendary Hermetic Link");
Check.True(M(wand, C(N.BuffedDoubleValKeyGE, "1.25", "152")), "elemental vs monsters 1.18 + Legendary Spirit Thirst 0.07");
Check.True(M(wand, C(N.BuffedDoubleValKeyGE, "0.13", "144")), "mana conversion 0.10 x Legendary Hermetic Link 1.30");
Check.False(M(wand, C(N.BuffedDoubleValKeyGE, "0.131", "144")), "no more");
var noCtx = new Item("Axe").Int(44, 74);
Check.True(VTankLootEvaluator.Match(new VTankLootRule { Conditions = { C(N.BuffedLongValKeyGE, "74", "44") } }, noCtx, null), "no context: the plain value");
}
private static void FloatCompare()
{
var item = new Item("x").Dbl(29, 1.2 + 0.09); // 1.2899999999999998 as a double
static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
Check.True(VTankLootEvaluator.Match(new VTankLootRule { Conditions = { C(N.DoubleValKeyGE, "1.29", "29") } }, item), "GE as floats");
Check.True(VTankLootEvaluator.Match(new VTankLootRule { Conditions = { C(N.DoubleValKeyLE, "1.29", "29") } }, item), "LE as floats");
Check.False(VTankLootEvaluator.Match(new VTankLootRule { Conditions = { C(N.DoubleValKeyGE, "1.2901", "29") } }, item), "a real difference still counts");
}
private static void TinkedNodes()
{
FakeHost.Reset();
static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
// VTank's worked example: 50 max damage, variance 0.2, unimbued, untinkered: 9 tinks
// (2 granite, 7 iron) -> 84.4344.
var w = new Item("Sword", AcObjectClass.MeleeWeapon).Int(44, 50).Dbl(22, 0.2).Int(131, 61);
Check.Near(VTankLootEvaluator.BuffedTinkedDamage(w, unchecked((uint)w.Wo.Id), null), 84.4344, 1e-4, "tinked damage 84.4344");
Check.True(VTankLootEvaluator.Match(new VTankLootRule { Conditions = { C(N.CalcdBuffedTinkedDamageGE, "84.43") } }, w), "node 2006 at 84.43");
var imbued = new Item("Sword", AcObjectClass.MeleeWeapon).Int(44, 50).Dbl(22, 0.2).Int(131, 61).Int(179, 1).Int(171, 3);
Check.True(VTankLootEvaluator.BuffedTinkedDamage(imbued, unchecked((uint)imbued.Wo.Id), null) < 84.4344, "imbued with 3 tinks done: 7 left, less damage");
// Target melee: the same item with no bonuses spends its 9 tinks on melee defense to 0.05,
// attack to 0.04, and none on damage: 74.74 (= (50 + 24) x 1.01).
var noBonus = new Item("Sword", AcObjectClass.MeleeWeapon).Int(44, 50).Dbl(22, 0.2).Int(131, 61);
uint id = unchecked((uint)noBonus.Wo.Id);
Check.True(VTankLootEvaluator.MatchTinkedTargetMelee(noBonus, id, null, new[] { "74.74", "0.05", "0.04" }, out double dot), "reaches 0.05 / 0.04 / 74.74");
Check.Near(dot, 74.74, 1e-9, "damage with no tinks left");
Check.False(VTankLootEvaluator.MatchTinkedTargetMelee(noBonus, id, null, new[] { "1", "0.06", "0.04" }, out _), "melee 0.06 is out of reach");
Check.False(VTankLootEvaluator.MatchTinkedTargetMelee(noBonus, id, null, new[] { "1", "0.05", "0.05" }, out _), "attack 0.05 is out of reach");
// LootSnob's "(H) 430 Insane": 109 at 1.17 / 1.17.
var mace = new Item("Mace", AcObjectClass.MeleeWeapon).Int(44, 80).Dbl(22, 0.25).Dbl(29, 1.17).Dbl(62, 1.17).Int(131, 57);
Check.True(VTankLootEvaluator.Match(new VTankLootRule { Conditions = { C(N.CalcedBuffedTinkedTargetMeleeGE, "109", "1.17", "1.17") } }, mace), "an 80 mace at 1.17/1.17 reaches 109");
}
private static void ConditionsNeedingId()
{
static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.ObjectClass, "9")), "class");
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.StringValueMatch, "Bow", "1")), "name");
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.StringValueMatch, "x", "16")), "long description");
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyE, "60", "131")), "material");
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyGE, "1000", "19")), "value");
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyE, "27704", "218103849")), "icon overlay (Decal key)");
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyE, "104", "218103821")), "coverage (Decal key)");
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyGE, "3", "105")), "workmanship comes with the ID");
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyE, "9", "353")), "weapon type");
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyE, "47", "159")), "wield skill");
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyGE, "70", "218103842")), "max damage (Decal key)");
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.DoubleValKeyGE, "1.2", "29")), "melee defense");
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.BuffedMissileDamageGE, "77")), "missile damage");
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.SpellNameMatch, "Legendary")), "spells");
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.CharacterMainPackEmptySlotsGE, "7")), "pack slots");
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.DisabledRule, "true")), "disabled");
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.SlotExactPalette, "1", "1682")), "palette");
}
private static void DecideOrder()
{
static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
var bowRule = new VTankLootRule { Name = "bow keep", Action = VTankLootAction.Keep };
bowRule.Conditions.Add(C(N.LongValKeyE, "8", "353")); // ID first
bowRule.Conditions.Add(C(N.ObjectClass, "9")); // class after
var name = new VTankLootRule { Name = "trade note", Action = VTankLootAction.Keep };
name.Conditions.Add(C(N.StringValueMatch, "Trade Note", "1"));
var p = new VTankLootProfile();
p.Rules.AddRange(new[] { bowRule, name });
var note = new Item("Trade Note (250,000)", AcObjectClass.TradeNote);
Check.Eq(VTankLootEvaluator.Decide(p, note, null, hasIdData: false, out int i1), VTankLootVerdict.Match, "the bow rule's class rules a note out, though it comes second");
Check.Eq(i1, 1, "the name rule takes it with no ID");
var bow = new Item("Bow", AcObjectClass.MissileWeapon);
Check.Eq(VTankLootEvaluator.Decide(p, bow, null, hasIdData: false, out int i2), VTankLootVerdict.NeedsId, "a bow waits for the bow rule's ID");
Check.Eq(i2, 0, "at the bow rule");
Check.Eq(VTankLootEvaluator.Decide(p, bow, null, hasIdData: true, out _), VTankLootVerdict.NoMatch, "with the ID (no weapon type 8) nothing takes it");
Check.Eq(VTankLootEvaluator.Decide(new VTankLootProfile(), bow, null, hasIdData: false, out int i3), VTankLootVerdict.NoMatch, "empty profile");
Check.Eq(i3, -1, "index -1");
}
private static void LootWhyExplains()
{
FakeHost.Reset();
VTankLootProfile p = Excerpt();
var plain = PlusNineXbow();
FakeHost.SpellIds.Remove(unchecked((uint)plain.Wo.Id)); // 76: Gold salvage
LootWhy.Result why = LootWhy.Explain(p, plain, Ctx(), hasIdData: true);
Check.Eq(why.Verdict, VTankLootVerdict.Match, "matched");
Check.Eq(why.RuleName, "(Salv) Gold", "Gold salvage");
var max = why.NearMisses.FirstOrDefault(m => m.RuleName == "(M) Xbow (Max 385)");
Check.Eq(max.RuleName, "(M) Xbow (Max 385)", "Xbow (Max 385) came close");
Check.True(max.Failed.StartsWith("Buffed Missile Damage >= 77: read 76", StringComparison.Ordinal), $"its failed condition and the value read ({max.Failed})");
Check.True(max.Failed.Contains("mod 2.62") && max.Failed.Contains("elemental 22"), "and how it was made");
Check.False(why.NearMisses.Any(m => m.RuleName.StartsWith("(M) Bow", StringComparison.Ordinal)), "bow rules failed on their first condition: not listed");
Check.False(why.NearMisses.Any(m => m.RuleName.Contains("Max 375")), "switched-off rules are not listed");
Check.True(why.NearMisses.Any(m => m.RuleName == "(M) Xbow (20MD)" && m.Failed.Contains("read 1.15")), "the 20MD rules read its 1.15 melee defense");
var bare = PlusNineXbow(withId: false);
LootWhy.Result wait = LootWhy.Explain(p, bare, Ctx(), hasIdData: false);
Check.Eq(wait.Verdict, VTankLootVerdict.NeedsId, "no ID: waits");
Check.Eq(wait.RuleName, "(M) Bow (OD +10)", "names the rule that needs it");
}
}

View file

@ -0,0 +1,245 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// A survey, not a check of one rule: real item types (bows and crossbows by element, wands,
// melee weapons, armor, jewelry, salvage of each material), built the way ACE makes them, run
// through the LootSnob profiles players use, with and without their identify data. It prints
// the rule each one gets (and writes a TSV when RYNTH_LOOT_SURVEY_OUT names a file), so a change
// to the evaluator shows which items it moves. The profiles are read from the install
// (C:\Games\RynthSuite\RynthAi\LootProfiles, read only); without them only the excerpt runs.
// The checks that matter are in LootRuleMatchTests; this one only checks that it ran.
internal static class LootSurveyTests
{
private const uint Player = 0x50000A01;
private const string ProfileDir = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
public static void Register(Runner r)
{
r.Add("loot survey: LootSnob profiles x real item types, with and without ID (prints the rule each gets)", Survey);
}
// CreateObject ints: what an item shows before its ID (RynthCore PwdLayout.IntStypes).
private static readonly HashSet<uint> CreateInts = new() { 1, 4, 5, 6, 7, 9, 10, 11, 12, 16, 18, 19, 50, 51, 91, 92, 94, 95, 131, 133, 151, 152, 280 };
internal sealed record SurveyItem(string Label, string Name, AcObjectClass Cls, Dictionary<int, int> Ints, Dictionary<int, double> Dbls, string[] Spells);
private static int Spell(string name)
{
int id = SpellDatabase.GetIdByName(name);
if (id == 0) throw new InvalidOperationException($"spell '{name}' is not in SpellData.txt");
return id;
}
// ── ACE-like items ───────────────────────────────────────────────────────
private const int ItemType = 1, Burden = 5, ValidLoc = 9, Value = 19, Damage = 44, DamageType = 45, WeaponSkill = 48,
Workmanship = 105, Material = 131, WieldReq = 158, WieldSkill = 159, WieldDiff = 160, ElemBonus = 204,
EquipSet = 265, WeaponType = 353, ArmorLevel = 28, Priority = 4, Tinkered = 171, Imbued = 179;
private const int Variance = 22, DamageMod = 63, MeleeDef = 29, Offense = 62, MissileDef = 149, MagicDef = 150, ManaConv = 144, ElemVsMonster = 152;
private static SurveyItem Launcher(string label, string name, int weaponType, int wield, int elem, double mod, double def, int material, int work, int dmgType, params string[] spells)
=> new(label, name, AcObjectClass.MissileWeapon,
new() { [ItemType] = 0x100, [ValidLoc] = 0x00400000, [Value] = 9000, [Burden] = 500, [Material] = material, [Workmanship] = work,
[WeaponType] = weaponType, [WieldReq] = 2, [WieldSkill] = 47, [WieldDiff] = wield, [ElemBonus] = elem,
[DamageType] = dmgType, [WeaponSkill] = 47 },
new() { [DamageMod] = mod, [MeleeDef] = def, [MissileDef] = 1.0, [MagicDef] = 1.0 },
spells);
private static SurveyItem Melee(string label, string name, int weaponType, int skill, int damage, double variance, double def, double off, int material, int work, params string[] spells)
=> new(label, name, AcObjectClass.MeleeWeapon,
new() { [ItemType] = 0x1, [ValidLoc] = 0x00100000, [Value] = 9000, [Burden] = 400, [Material] = material, [Workmanship] = work,
[WeaponType] = weaponType, [WieldReq] = 2, [WieldSkill] = skill, [WieldDiff] = 430, [Damage] = damage, [DamageType] = 1, [WeaponSkill] = skill },
new() { [Variance] = variance, [MeleeDef] = def, [Offense] = off, [MissileDef] = 1.0, [MagicDef] = 1.0 },
spells);
private static SurveyItem Caster(string label, string name, int wield, double elemVsMonster, double def, double manaConv, int material, int work, params string[] spells)
=> new(label, name, AcObjectClass.WandStaffOrb,
new() { [ItemType] = 0x8000, [ValidLoc] = 0x01000000, [Value] = 9000, [Burden] = 50, [Material] = material, [Workmanship] = work,
[WieldReq] = 2, [WieldSkill] = 34, [WieldDiff] = wield },
new() { [ElemVsMonster] = elemVsMonster, [MeleeDef] = def, [ManaConv] = manaConv, [MagicDef] = 1.0 },
spells);
private static SurveyItem Armor(string label, string name, int al, int set, int material, int work, params string[] spells)
=> new(label, name, AcObjectClass.Armor,
new() { [ItemType] = 0x2, [ValidLoc] = 0x00000200, [Priority] = 0x400, [Value] = 9000, [Burden] = 700, [Material] = material,
[Workmanship] = work, [ArmorLevel] = al, [EquipSet] = set },
new(), spells);
private static SurveyItem Jewel(string label, string name, int material, int work, params string[] spells)
=> new(label, name, AcObjectClass.Jewelry,
new() { [ItemType] = 0x8, [ValidLoc] = 0x00040000, [Value] = 7000, [Burden] = 30, [Material] = material, [Workmanship] = work },
new(), spells);
internal static List<SurveyItem> Items()
{
const int Gold = 60, Iron = 61, Steel = 64, Silver = 63, Mahogany = 74, Oak = 75, Pine = 76, Ebony = 73, Teak = 77, Brass = 57,
Granite = 67, Satin = 5;
const int Slash = 1, Pierce = 2, Bludge = 4, Cold = 8, Fire = 16, Acid = 32, Elec = 64;
var items = new List<SurveyItem>
{
// Crossbows (WeaponType 9): LootSnob's missile damage = mod% / 3 + elemental + cantrip.
Launcher("xbow 385 +22 mod 2.62 Legendary Blood Thirst (OD +9)", "Blunt Crossbow", 9, 385, 22, 2.62, 1.15, Gold, 6, Bludge, "Legendary Blood Thirst"),
Launcher("xbow 385 +22 mod 2.65 (Max 385)", "Fire Crossbow", 9, 385, 22, 2.65, 1.12, Iron, 5, Fire),
Launcher("xbow 385 +22 mod 2.62 no cantrip (76, under Max 385)", "Blunt Crossbow", 9, 385, 22, 2.62, 1.15, Gold, 6, Bludge),
Launcher("xbow 385 +21 mod 2.65 Epic Blood Thirst (OD +6)", "Acid Compound Crossbow", 9, 385, 21, 2.65, 1.10, Mahogany, 7, Acid, "Epic Blood Thirst"),
Launcher("xbow 335 +9 mod 2.55 (a '+9' elemental)", "Electric Crossbow", 9, 335, 9, 2.55, 1.10, Gold, 5, Elec),
Launcher("xbow 375 +19 MD 1.20 Legendary Defender (29MD)", "Frost Crossbow", 9, 375, 19, 2.60, 1.20, Steel, 6, Cold, "Legendary Defender"),
Launcher("xbow 375 +19 MD 1.22 (22MD)", "Slashing Crossbow", 9, 375, 19, 2.60, 1.22, Silver, 6, Slash),
// Bows (8)
Launcher("bow 385 +22 mod 2.40 (Max 385)", "Fire Compound Bow", 8, 385, 22, 2.40, 1.10, Oak, 5, Fire),
Launcher("bow 385 +22 mod 2.40 Legendary Blood Thirst (OD +10)", "Piercing Bow", 8, 385, 22, 2.40, 1.10, Pine, 5, Pierce, "Legendary Blood Thirst"),
Launcher("bow 375 +19 mod 2.37 (64.7, rules off)", "Electric Bow", 8, 375, 19, 2.37, 1.10, Ebony, 6, Elec),
Launcher("bow 360 +16 mod 2.35 MD 1.21 (21MD)", "Blunt Bow", 8, 360, 16, 2.35, 1.21, Teak, 5, Bludge),
Launcher("bow 335 +9 mod 2.30 Iron", "Acid Bow", 8, 335, 9, 2.30, 1.05, Iron, 5, Acid),
// Atlatls (10)
Launcher("atlatl 385 +22 mod 2.60 Epic Blood Thirst (OD +7)", "Electric Atlatl", 10, 385, 22, 2.60, 1.10, Mahogany, 5, Elec, "Epic Blood Thirst"),
Launcher("atlatl 385 +22 mod 2.60 (75.3, Max 385 off)", "Fire Atlatl", 10, 385, 22, 2.60, 1.10, Mahogany, 5, Fire),
Launcher("atlatl 360 +16 MD 1.29 (29MD)", "Blunt Atlatl", 10, 360, 16, 2.45, 1.29, Gold, 6, Bludge),
// Wands
Caster("void wand 1.18 Legendary Spirit Thirst (OD +7)", "Nether Baton", 385, 1.18, 1.10, 0.05, Silver, 6, "Legendary Spirit Thirst"),
Caster("void wand 385 1.18 (Max 385)", "Nether Sceptre", 385, 1.18, 1.10, 0.05, Silver, 6),
Caster("war sceptre 1.18 MD 1.15 Major Defender (18pvm + 20md)", "Sceptre", 385, 1.18, 1.15, 0.05, Brass, 5, "Major Defender"),
Caster("war staff 1.15 MD 1.20 (no rule)", "Staff", 375, 1.12, 1.18, 0.05, Teak, 5),
Caster("orb no wield MD 1.21 Minor Defender (24MD)", "Orb", 0, 1.0, 1.21, 0.10, Granite, 5, "Minor Defender"),
// Melee (heavy axe 44, light sword 45, finesse dagger 46)
Melee("heavy axe 74 (Max 430)", "Silifi", 3, 44, 74, 0.45, 1.12, 1.12, Iron, 6),
Melee("heavy axe 74 Legendary Blood Thirst (OD +10)", "Lugian Axe", 3, 44, 74, 0.45, 1.12, 1.12, Iron, 6, "Legendary Blood Thirst"),
Melee("heavy axe 72 MD 1.26 Minor Defender (MD +8)", "War Axe", 3, 44, 66, 0.45, 1.26, 1.10, Steel, 6, "Minor Defender"),
Melee("heavy mace 80 var .25 def/atk 1.17 (430 Insane)", "Mace", 4, 44, 80, 0.25, 1.17, 1.17, Brass, 7),
Melee("light sword 68 (OD +10)", "Broad Sword", 2, 45, 68, 0.40, 1.10, 1.10, Steel, 5),
Melee("light sword 60 Epic Blood Thirst (67, OD +9)", "Shamshir", 2, 45, 60, 0.40, 1.10, 1.10, Steel, 5, "Epic Blood Thirst"),
Melee("finesse dagger 59 (OD >= +1)", "Poniard", 6, 46, 59, 0.40, 1.10, 1.10, Gold, 5),
Melee("2h spear 57 (OD +9)", "Assagai", 5, 41, 57, 0.40, 1.10, 1.10, Iron, 5),
// Armor and jewelry
Armor("Archer's set coat Legendary Missile Weapon + Epic Impen", "Amuli Coat", 600, 15, Satin, 6, "Legendary Missile Weapon Aptitude", "Epic Impenetrability"),
Armor("plain breastplate AL 400 Steel w5", "Breastplate", 400, 0, Steel, 5),
Armor("plain coat AL 300 Gold w4", "Chainmail Coat", 300, 0, Gold, 4),
Jewel("ring Legendary Strength", "Ring", Silver, 5, "Legendary Strength"),
Jewel("necklace no spells Gold w4", "Necklace", Gold, 4),
};
// Salvage of each material: a plain armor piece, workmanship 5.
(string Name, int Id)[] mats =
{
("Alabaster", 66), ("Armoredillo Hide", 53), ("Bronze", 58), ("Ceramic", 1), ("Marble", 68), ("Peridot", 34), ("Reed Shark Hide", 55),
("Steel", 64), ("Wool", 8), ("Yellow Topaz", 49), ("Zircon", 50), ("Amber", 11), ("Copper", 59), ("Diamond", 20), ("Ebony", 73),
("Gold", 60), ("Gromnie Hide", 54), ("Linen", 4), ("Moonstone", 31), ("Pine", 76), ("Porcelain", 2), ("Pyreal", 62), ("Ruby", 38),
("Sapphire", 39), ("Satin", 5), ("Silver", 63), ("Teak", 77), ("Agate", 10), ("Azurite", 14), ("Black Opal", 16), ("Bloodstone", 17),
("Carnelian", 18), ("Citrine", 19), ("Fire Opal", 22), ("Green Garnet", 23), ("Hematite", 25), ("Lapis Lazuli", 28), ("Lavender Jade", 29),
("Malachite", 30), ("Opal", 33), ("Red Jade", 36), ("Rose Quartz", 37), ("Smokey Quartz", 40), ("Sunstone", 41), ("Aquamarine", 13),
("Black Garnet", 15), ("Brass", 57), ("Emerald", 21), ("Granite", 67), ("Imperial Topaz", 26), ("Iron", 61), ("Jet", 27),
("Mahogany", 74), ("Oak", 75), ("Red Garnet", 35), ("Velvet", 7), ("White Sapphire", 47), ("Ivory", 51), ("Leather", 52),
("Sandstone", 70), ("Silk", 6), ("Amethyst", 12), ("Green Jade", 24), ("Obsidian", 69), ("Onyx", 32), ("Serpentine", 71),
("Tiger Eye", 42), ("Tourmaline", 43), ("Turquoise", 44), ("White Jade", 45), ("White Quartz", 46), ("Yellow Garnet", 48),
};
foreach (var (n, id) in mats)
items.Add(Armor($"salvage: {n} w5 (plain armor)", "Leather Leggings", 150, 0, id, 5));
return items;
}
// ── Running one item ─────────────────────────────────────────────────────
private static readonly MethodInfo? DecideMethod = typeof(VTankLootEvaluator).GetMethod("Decide");
/// <summary>The rule the looter gives the item: with its ID, or (hasId false) from what it shows before one.</summary>
internal static string Classify(VTankLootProfile profile, SurveyItem s, bool hasId)
{
var (item, ctx) = Build(s, hasId);
int index;
string verdict;
if (DecideMethod != null)
{
object?[] args = { profile, item.Wo, ctx, hasId, -1 };
verdict = DecideMethod.Invoke(null, args)!.ToString()!;
index = (int)args[4]!;
}
else
{
// Before 2026-10-31: no wait for the ID past the timeout, the rules judged what was there.
VTankLootRule? hit = VTankLootEvaluator.FirstMatch(profile, item.Wo, ctx, out index);
verdict = hit != null ? "Match" : "NoMatch";
}
if (verdict == "NoMatch" || index < 0) return "leave";
string name = profile.Rules[index].Name.Trim();
return verdict == "NeedsId" ? $"hold for ID ({name})" : $"{profile.Rules[index].Action}: {name}";
}
/// <summary>The survey item as a test item: with its ID, or only what the CreateObject shows.</summary>
private static (Item Item, VTankLootContext Ctx) Build(SurveyItem s, bool hasId)
{
var item = new Item(s.Name, s.Cls);
foreach (var (k, v) in s.Ints)
if (hasId || CreateInts.Contains(unchecked((uint)k))) item.Int(k, v);
if (hasId)
foreach (var (k, v) in s.Dbls) item.Dbl(k, v);
uint id = unchecked((uint)item.Wo.Id);
var spellIds = new List<uint>();
if (hasId) foreach (string sp in s.Spells) spellIds.Add((uint)Spell(sp));
FakeHost.SpellIds[id] = spellIds.ToArray();
return (item, new VTankLootContext(FakeHost.Create(), Player));
}
internal static VTankLootProfile WithSalvageOn(VTankLootProfile p)
{
foreach (var r in p.Rules)
if (r.Action == VTankLootAction.Salvage)
r.Conditions.RemoveAll(c => c.NodeType == VTankNodeTypes.DisabledRule);
return p;
}
private static void Survey()
{
FakeHost.Reset();
var profiles = new List<(string Name, VTankLootProfile Profile)>
{
("lootsnob-excerpt (fixture)", VTankLootParser.Load(Path.Combine(AppContext.BaseDirectory, "Fixtures", "lootsnob-excerpt.utl"))),
};
string snob = Path.Combine(ProfileDir, "LootSnobV4.utl"), cq = Path.Combine(ProfileDir, "CQ_Lootsnob_lite.utl");
if (File.Exists(snob))
{
profiles.Add(("LootSnobV4", VTankLootParser.Load(snob)));
profiles.Add(("LootSnobV4 salvage on", WithSalvageOn(VTankLootParser.Load(snob))));
}
if (File.Exists(cq))
{
profiles.Add(("CQ_Lootsnob_lite", VTankLootParser.Load(cq)));
profiles.Add(("CQ_Lootsnob_lite salvage on", WithSalvageOn(VTankLootParser.Load(cq))));
}
var tsv = new StringBuilder("profile\titem\tname\twith ID\twithout ID\n");
foreach (var (pname, profile) in profiles)
{
Console.WriteLine($" -- {pname} ({profile.Rules.Count} rules)");
foreach (SurveyItem s in Items())
{
string withId = Classify(profile, s, hasId: true);
string noId = Classify(profile, s, hasId: false);
tsv.Append(pname).Append('\t').Append(s.Label).Append('\t').Append(s.Name).Append('\t').Append(withId).Append('\t').Append(noId).Append('\n');
if (!s.Label.StartsWith("salvage:", StringComparison.Ordinal) || withId != "leave")
Console.WriteLine($" {s.Label,-62} ID: {withId,-40} no ID: {noId}");
}
}
// What /ra loot why says for the reported crossbow without its cantrip (76: Gold salvage).
var (whyProfileName, whyProfile) = profiles[profiles.Count > 2 ? 2 : 0];
SurveyItem plain = Items().Find(i => i.Label.StartsWith("xbow 385 +22 mod 2.62 no cantrip", StringComparison.Ordinal))!;
var (whyItem, whyCtx) = Build(plain, hasId: true);
LootWhy.Result why = LootWhy.Explain(whyProfile, whyItem.Wo, whyCtx, hasIdData: true);
Console.WriteLine($" -- /ra loot why, {whyProfileName}, '{plain.Label}': {why.Verdict} rule {why.Index + 1} '{why.RuleName}' [{why.Action}], {why.NearMisses.Count} came close:");
foreach (var m in why.NearMisses)
Console.WriteLine($" #{m.Index + 1} '{m.RuleName}': {m.Failed}");
string? outPath = Environment.GetEnvironmentVariable("RYNTH_LOOT_SURVEY_OUT");
if (!string.IsNullOrWhiteSpace(outPath)) File.WriteAllText(outPath, tsv.ToString());
Check.True(profiles[0].Profile.Rules.Count > 100, "the excerpt fixture loads");
}
}

View file

@ -143,6 +143,16 @@ internal static class ProfileLoadTests
Check.Eq(l.Layout, MagItemInfoSettings.LayoutOneLine, "layout");
Check.Eq(l.ChatType, 7, "chat type");
Check.Eq(l.Prefix, "[ii] ", "prefix");
// 2026-10-31: Describe items when selected is on by default; a saved "off" stays off.
Check.True(new MagItemInfoSettings().OnSelect, "Describe items when selected: on by default");
var off = new LegacyUiSettings();
off.ItemInfoSettings.OnSelect = false;
var offLoaded = JsonSerializer.Deserialize(JsonSerializer.Serialize(off, RynthAiJsonContext.Default.LegacyUiSettings),
RynthAiJsonContext.Default.LegacyUiSettings)!;
var offLive = new LegacyUiSettings();
CopySettings(offLoaded, offLive);
Check.False(offLive.ItemInfoSettings.OnSelect, "a saved 'off' stays off");
Check.True(live.EnableGroundLoot, "ground loot");
Check.False(live.PetAutoRefill, "pet auto refill");
Check.True(live.MonsterNameBlacklist.Contains("Drudge Skulker"), "monster blacklist");

View file

@ -33,6 +33,9 @@ internal static class TargetingTests
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);
r.Add("targeting: a higher priority out of sight is named as passed over, once per reason", PassedOverOutOfSight);
r.Add("targeting: a higher priority just past Monster Range is named on the lock line", PassedOverBeyondRange);
r.Add("targeting: nothing is named when no higher priority was left out", PassedOverNothingHigher);
}
// ── Schemes ───────────────────────────────────────────────────────────────
@ -235,6 +238,132 @@ internal static class TargetingTests
Check.Eq(s.TargetSelection, 3, "an out-of-range choice is clamped");
}
// ── Passed over (R-20261031-201214-8be7) ──────────────────────────────────
// A report said a Priority 5 monster was ignored for Priority 1 ones; the log showed only
// that some monsters in range were LOS-blocked, not which. The lock line now names the best
// higher-priority monster that wasn't a candidate, and why. Selection itself is unchanged.
private static void PassedOverOutOfSight()
{
var t = new ScanPick(monsterRange: 10);
t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 });
t.Place(A, "Mob A", north: 2);
t.Place(Boss, "Boss", east: 3);
t.Blocked.Add(Boss);
Check.Eq(t.Tick(), A, "the Boss is behind a wall: Mob A, the only candidate, is locked");
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] lock 0x80000401")
&& l.Contains("[passed over 0x80000404 'Boss' priority 5, 3.0 m: line of sight blocked]")),
"the lock line names the Boss and why it wasn't picked");
int lines = PassedLines();
t.Tick();
t.Tick();
Check.Eq(PassedLines(), lines, "still behind the wall: not logged again");
FakeHost.NotAttackable.Add(Boss);
t.Tick();
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] passed over 0x80000404 'Boss' priority 5, 3.0 m: not attackable")
&& l.Contains("the target stays 0x80000401 'Mob A' priority 1")),
"a new reason is one new line, with the target that stays");
int after = PassedLines();
t.Tick();
Check.Eq(PassedLines(), after, "and only once");
FakeHost.NotAttackable.Remove(Boss);
t.Blocked.Remove(Boss);
Check.Eq(t.Tick(), Boss, "in sight and attackable: the Boss takes over at once");
string sw = FakeHost.Logs.Last(l => l.Contains("[CombatTarget] switch"));
Check.True(sw.Contains("priority 1 < 5") && !sw.Contains("passed over"), "the switch says priority, with nothing passed over");
}
private static void PassedOverBeyondRange()
{
var t = new ScanPick(monsterRange: 10);
t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 });
t.Place(A, "Mob A", north: 2);
t.Place(Boss, "Boss", north: -12);
Check.Eq(t.Tick(), A, "the Boss at 12 m is past Monster Range 10: Mob A");
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] lock 0x80000401")
&& l.Contains("[passed over 0x80000404 'Boss' priority 5, 12.0 m: beyond Monster Range (10 m)]")),
"the lock line names the Boss past the range");
t = new ScanPick(monsterRange: 10);
t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 });
t.Place(A, "Mob A", north: 2);
t.Place(Boss, "Boss", north: -30);
t.Tick();
Check.False(FakeHost.Logs.Any(l => l.Contains("passed over")), "30 m out (more than 15 m past the range): not named");
}
private static void PassedOverNothingHigher()
{
var t = new ScanPick(monsterRange: 10);
t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 });
t.Place(A, "Mob A", north: 2);
t.Place(B, "Mob B", east: 3);
t.Place(C, "Mob C", north: -12);
t.Blocked.Add(B);
Check.Eq(t.Tick(), A, "Mob A is locked");
Check.False(FakeHost.Logs.Any(l => l.Contains("passed over")),
"a same-priority monster behind a wall or past the range isn't named");
t = new ScanPick(monsterRange: 10);
t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 });
t.Place(A, "Mob A", north: 2);
t.Place(Boss, "Boss", east: 3);
Check.Eq(t.Tick(), Boss, "the Boss in sight is the target");
t.Blocked.Add(Boss);
t.Tick();
Check.False(FakeHost.Logs.Any(l => l.Contains("passed over")), "the target itself out of sight isn't 'passed over'");
}
private static int PassedLines() => FakeHost.Logs.Count(l => l.Contains("[CombatTarget] passed over"));
/// <summary>The real scan (ScanNearbyTargets) over placed monsters, then the pick.</summary>
private sealed class ScanPick
{
public readonly LegacyUiSettings S;
public readonly HashSet<uint> Blocked = new();
private readonly List<uint> _ids = new();
private CombatManager? _c;
private static readonly FieldInfo LastScan =
typeof(CombatManager).GetField("_lastScanTime", BindingFlags.NonPublic | BindingFlags.Instance)!;
public ScanPick(int monsterRange)
{
FakeHost.Reset();
TargetingTests.Place(Player, "Me", 96, 96, creature: false);
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
S = new LegacyUiSettings { MonsterRange = monsterRange, TargetSelection = Closest, TargetLock = true };
}
/// <summary>A monster <paramref name="north"/>/<paramref name="east"/> m from the player.</summary>
public void Place(uint id, string name, double north = 0, double east = 0)
{
TargetingTests.Place(id, name, (float)(96 + east), (float)(96 + north));
if (!_ids.Contains(id)) _ids.Add(id);
}
/// <summary>One combat tick's selection: scan, pick, and the passed-over note.</summary>
public uint Tick()
{
if (_c == null)
{
var host = FakeHost.Create();
var cache = FakeHost.MakeCache(host, Player, _ids, null);
_c = new CombatManager(host, S, cache);
_c.SetPlayerId(Player);
_c.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
_c.LosBlockedOverride = id => Blocked.Contains(unchecked((uint)id));
}
LastScan.SetValue(_c, DateTime.MinValue);
_c.ScanNearbyTargets();
_c.HandleCombatTrigger();
_c.NotePassedOverWhileEngaged();
return unchecked((uint)_c.activeTargetId);
}
}
// ── Rig ───────────────────────────────────────────────────────────────────
private sealed class Rig

View file

@ -256,18 +256,26 @@ internal static class VTankLootTests
Check.False(M(sword, C(N.MinDamageGE, "20.5")), "min above");
Check.True(M(sword, C(N.BuffedMedianDamageGE, "30")), "median 30");
Check.False(M(sword, C(N.BuffedMedianDamageGE, "30.1")), "median above");
Check.True(M(sword, C(N.CalcdBuffedTinkedDamageGE, "40")), "tinked damage reads max damage");
// No material: it can't be tinked, so the damage over time is max + Blood Drinker's 24,
// 10% crits at double: (40 + 24) x (0.9 x 1.5 / 2 + 0.2) = 56
Check.True(M(sword, C(N.CalcdBuffedTinkedDamageGE, "56")), "tinked damage: no material, no tinks");
Check.False(M(sword, C(N.CalcdBuffedTinkedDamageGE, "56.01")), "tinked damage just above");
Check.False(M(sword, C(N.DamagePercentGE, "0")), "damage percent always fails (as VTank)");
var nodmg = new Item("Stick");
Check.False(M(nodmg, C(N.MinDamageGE, "0")), "no max damage: min damage fails even at 0");
Check.False(M(nodmg, C(N.BuffedMedianDamageGE, "0")), "no max damage: median fails");
Check.False(M(nodmg, C(N.BuffedMissileDamageGE, "0")), "no max damage: missile fails");
Check.False(M(nodmg, C(N.BuffedMissileDamageGE, "0")), "no damage modifier (not a launcher): missile fails");
var bow = new Item("Bow").Int(44, 50).Dbl(152, 1.2);
Check.True(M(bow, C(N.BuffedMissileDamageGE, "60")), "50 * elemental 1.2 = 60");
Check.False(M(bow, C(N.BuffedMissileDamageGE, "60.1")), "just above");
var weakBow = new Item("Bow").Int(44, 50).Dbl(152, 0.5);
Check.True(M(weakBow, C(N.BuffedMissileDamageGE, "50")), "an elemental bonus below 1 counts as 1");
// Missile damage = max damage + (damage mod - 1) x 100 / 3 + elemental bonus (204); a
// launcher has no max damage. VTank's own example: a 50 max damage bow with mod 1.15 is 55.
var bow = new Item("Bow").Int(44, 50).Dbl(63, 1.15);
Check.True(M(bow, C(N.BuffedMissileDamageGE, "55")), "50 + 15/3 = 55");
Check.False(M(bow, C(N.BuffedMissileDamageGE, "55.01")), "just above");
var xbow = new Item("Crossbow").Dbl(63, 2.65).Int(204, 22);
Check.True(M(xbow, C(N.BuffedMissileDamageGE, "77")), "a 385 crossbow: 165/3 + 22 = 77");
Check.False(M(xbow, C(N.BuffedMissileDamageGE, "77.01")), "and no more");
var noElem = new Item("Crossbow").Dbl(63, 2.2);
Check.True(M(noElem, C(N.BuffedMissileDamageGE, "40")), "no elemental bonus reads 0: 120/3 = 40");
}
private static void BuffedKeysAndRatings()
@ -288,7 +296,7 @@ internal static class VTankLootTests
Check.True(M(item, C(N.AnySimilarColor, "1", "2", "3", "4", "5")), "any similar colour passes");
Check.True(M(item, C(N.SimilarColorArmorType, "1", "2", "3", "4", "5", "6")), "armor-type colour passes");
Check.True(M(item, C(N.SlotSimilarColor, "1", "2", "3", "4", "5", "6")), "slot colour passes");
Check.False(M(item, C(N.CalcedBuffedTinkedTargetMeleeGE, "1", "1", "1")), "tinked target melee is not implemented: fails");
Check.False(M(item, C(N.CalcedBuffedTinkedTargetMeleeGE, "1", "1", "1")), "tinked target melee: no max damage, fails");
}
private static void SpellNodesNoContext()
@ -355,6 +363,7 @@ internal static class VTankLootTests
{
FakeHost.Reset();
FakeHost.Skills[(Player, 34)] = (Buffed: 400, Training: 3);
FakeHost.SkillLevels[(Player, 34, 1)] = 320; // base (no enchantments)
FakeHost.Ints[(Player, 25)] = 275; // LEVEL
var ctx = new VTankLootContext(FakeHost.Create(), Player);
var item = new Item("x");
@ -362,9 +371,11 @@ internal static class VTankLootTests
Check.True(MC(item, ctx, C(N.CharacterSkillGE, "400", "34")), "skill 400 >= 400");
Check.False(MC(item, ctx, C(N.CharacterSkillGE, "401", "34")), "skill 400 < 401");
Check.False(MC(item, ctx, C(N.CharacterSkillGE, "1", "33")), "a skill the host has no value for reads 0");
// "Base skill" is checked against the training class (2 trained, 3 specialized).
Check.True(MC(item, ctx, C(N.CharacterBaseSkill, "34", "3", "3")), "specialized in [3,3]");
Check.False(MC(item, ctx, C(N.CharacterBaseSkill, "34", "0", "2")), "not in [0,2]");
// "Base skill" is the unbuffed skill level (it was the training class, 2 or 3, until 2026-10-31,
// so LootSnob's "Heavy Weapon 300" = base heavy in [300, 999] never matched).
Check.True(MC(item, ctx, C(N.CharacterBaseSkill, "34", "300", "999")), "base 320 in [300,999]");
Check.False(MC(item, ctx, C(N.CharacterBaseSkill, "34", "330", "999")), "base 320 not in [330,999] (buffed is 400)");
Check.False(MC(item, ctx, C(N.CharacterBaseSkill, "34", "3", "3")), "not the training class any more");
Check.True(MC(item, ctx, C(N.CharacterLevelGE, "275")), "level GE at the value");
Check.False(MC(item, ctx, C(N.CharacterLevelGE, "276")), "level GE above");
Check.True(MC(item, ctx, C(N.CharacterLevelLE, "275")), "level LE at the value");

View file

@ -114,6 +114,8 @@ namespace RynthDefective.Tests
Run("quantity: give - the last player or NPC selected, all of it, refusals", QtyGive);
Run("quantity: buy - the selected item or by name, checks first, the vendor's answer", QtyBuy);
Run("quantity: /rdef qty and the Selection window's view", QtyBoxAndView);
Run("quantity: a server's bank - its values, pack + bank, one that can't be read, max", QtyBankRules);
Run("quantity: buy and max with no bank, a bank that covers it, one that doesn't, one that can't be read", QtyBankBuy);
Run("store: the quantity box setting; files from before read it on", QtyStore);
}
finally

View file

@ -48,6 +48,7 @@ namespace RynthDefective.Tests
public string? BuyRefusedWith;
public int FreeContainers = 3;
public long Burden = -1;
public VendorBank BankInfo = VendorBank.None;
public bool TryGetName(uint id, out string name)
{
@ -123,6 +124,7 @@ namespace RynthDefective.Tests
}
public int FreeContainerSlots() => FreeContainers;
public long FreeBurden() => Burden;
public VendorBank Bank() => BankInfo;
public void Advance(long ms) => NowMs += ms;
}
@ -779,6 +781,176 @@ namespace RynthDefective.Tests
Check(c.Into == 0 && !c.Busy && c.StatusAt(w.NowMs) == null, "logout forgets the action, the pack and the line");
}
// ── A server's bank (2026-10-31) ────────────────────────────────────
// A player report: on a server whose bank pays vendors, the box refused a buy the pack alone
// couldn't pay for. The server plugin's profile values say whether a bank pays and how much.
private static void QtyBankRules()
{
// The values, as the active server's plugin publishes them.
Eq(VendorBank.Read(null), VendorBank.None, "no profile: no bank");
Eq(VendorBank.Read("{\"values\":{}}"), VendorBank.None, "no bank values: no bank");
Eq(VendorBank.Read("{\"values\":{\"vendorBank\":0,\"vendorBankPyreals\":5000}}"), VendorBank.None, "vendorBank 0: no bank, whatever the balance");
Eq(VendorBank.Read("not json"), VendorBank.None, "unusable text: no bank");
VendorBank read = VendorBank.Read("{\"values\":{\"vendorBank\":1,\"vendorBankPyreals\":5000}}");
Check(read.Pays && read.Known && read.Pyreals == 5000, "a bank that pays, with its balance");
read = VendorBank.Read("{\"values\":{\"vendorBank\":1}}");
Check(read.Pays && !read.Known && read.Pyreals == -1, "a bank that pays, balance not said: unread");
Check(!VendorBank.Read("{\"values\":{\"vendorBank\":1,\"vendorBankPyreals\":-3}}").Known, "a negative balance: unread");
Eq(VendorBank.Read("{\"values\":{\"vendorBank\":1,\"vendorBankPyreals\":1e30}}").Pyreals, VendorBank.MaxPyreals, "a huge balance is capped");
Eq(VendorBank.Read("{\"values\":{\"vendorBank\":1,\"vendorBankPyreals\":12.9}}").Pyreals, 12L, "whole pyreals");
// No bank: today's check, word for word.
VendorQuote none = Scarabs(funds: 300);
Eq(none.Refusal(100), "Not enough pyreals: 100 Mana Scarab cost 1,200, you have 300 (you can buy 25).", "no bank: the pack's pyreals");
Eq(none.MaxBuy(), 25, "no bank: max is what the pack pays for");
Eq(none.PriceLine(25), "300 pyreals · you have 300", "no bank: the price line as before");
Eq(none.BankNote(100), null, "no bank: no note");
Eq(none.MaxNote, string.Empty, "no bank: max needs no note");
Eq(none.Spendable, 300L, "no bank: the pack");
// A bank that's read and covers it: pack + bank, said both ways.
VendorQuote covers = Scarabs(funds: 300) with { BankPays = true, BankFunds = 5000 };
Eq(covers.Refusal(100), null, "pack 300 + bank 5,000 pay 1,200");
Eq(covers.PriceLine(100), "price 1,200; pack 300 + bank 5,000", "the price line says both");
Eq(covers.BankNote(100), "The bank pays the 900 pyreals your pack is short.", "the bank's part");
Eq(covers.BankNote(25), null, "the pack alone pays 25: no note");
Eq(covers.MaxBuy(), 441, "max counts pack + bank: 441 (5,292), not 442 (5,304)");
Eq(covers.MaxNote, string.Empty, "a bank that's read: max needs no note");
// A bank that's read and doesn't cover it.
VendorQuote shortOf = Scarabs(funds: 300) with { BankPays = true, BankFunds = 500 };
Eq(shortOf.Refusal(100), "Not enough pyreals: 100 Mana Scarab cost 1,200, you have 300 in your pack + 500 in the bank (you can buy 66).",
"pack + bank short: both said, and how many they pay for");
Eq(shortOf.MaxBuy(), 66, "max: 800 at 12 is 66");
Eq(shortOf.BankNote(100), null, "no note for a buy that can't go");
// A bank that can't be read: money isn't held against a buy; max is stock, room and burden.
VendorQuote unread = Scarabs(funds: 300) with { BankPays = true, BankFunds = -1 };
Eq(unread.Refusal(100), null, "the server decides about the money");
Eq(unread.Spendable, -1L, "nothing to count against");
Eq(unread.BankNote(100), "Your pack has 300 of the 1,200 pyreals: the server's bank may cover it (the server decides).", "the one-line note");
Eq(unread.BankNote(25), null, "the pack alone pays: no note");
Eq(unread.PriceLine(100), "1,200 pyreals · pack 300 + the bank", "the price line");
Eq(unread.MaxBuy(), 5000, "max: 50 free slots of 100");
Eq((unread with { FreeBurden = 55 }).MaxBuy(), 11, "max: the burden");
Eq((unread with { FreeItemSlots = -1 }).MaxBuy(), 100, "max with nothing known: one stack");
Check(unread.MaxNote.Contains("can't be read", StringComparison.Ordinal), "max says what it counts");
string? why = unread.Refusal(6000);
Check(why != null && why.StartsWith("Not enough room in your packs", StringComparison.Ordinal) && why.Contains("you can buy 5,000", StringComparison.Ordinal),
$"room is still checked: {why}");
Check((unread with { Unlimited = false, Stock = 5, ListingValue = 50 }).Refusal(6)!.StartsWith("The vendor has only 5", StringComparison.Ordinal), "and the stock");
// The bank pays pyreal vendors only.
var altInfo = new VendorInfo { VendorId = QVendor, SellRate = 1f, AltCurrencyWcid = 1234, AltCurrencyName = "Ancient Coin", AltCurrencyHave = 3, PlayerCoins = 300 };
var relic = new VendorItem { ObjectId = QVScarab, Name = "Relic", UnitValue = 2, Value = 2, StackSize = 1, MaxStackSize = 0, Amount = -1, Unlimited = true };
VendorQuote alt = VendorQuote.From(altInfo, relic, 10, 2, -1, new VendorBank(true, 5000));
Check(!alt.BankPays && alt.Funds == 3 && alt.Refusal(2) != null, "the vendor's own currency: no bank");
var pyInfo = new VendorInfo { VendorId = QVendor, SellRate = 1f, AltCurrencyHave = -1, PlayerCoins = 300 };
VendorQuote py = VendorQuote.From(pyInfo, relic, 10, 2, -1, new VendorBank(true, 5000));
Check(py.BankKnown && py.BankFunds == 5000 && py.Spendable == 5300, "a pyreal vendor: pack + bank");
Check(!VendorQuote.From(pyInfo, relic, 10, 2, -1).BankPays, "and without a bank, none");
// The answers.
Eq(QtyReplies.BuyRefusal("costs 300 pyreals, you have 200", false), QtyReplies.VendorRefusal("costs 300 pyreals, you have 200"), "no bank: the engine's refusal as before");
Check(QtyReplies.BuyRefusal("costs 1200 pyreals, you have 300", true).StartsWith("RynthCore didn't send it: it costs 1200 pyreals, you have 300.", StringComparison.Ordinal),
"a bank was to pay: RynthCore's own money check said so");
Eq(QtyReplies.BuyRefusal("vendor window is closed", true), QtyReplies.VendorRefusal("vendor window is closed"), "other refusals as before");
Check(QtyReplies.NotSold(25, "Mana Scarab", true, 300, "pyreals").Contains("the bank may not cover 300 pyreals", StringComparison.Ordinal), "the server said no, with a bank");
Check(QtyReplies.NotSold(25, "Mana Scarab", false, 300, "pyreals").EndsWith("(money, room, or too busy).", StringComparison.Ordinal), "and without one, as before");
}
private static void QtyBankBuy()
{
// The controller: the box's max and Buy, from the window and from /rdef buy, in each case.
// The world: 66 free pack slots (52 + 14), burden unknown, 300 pyreals in the pack.
var w = QWorld();
var (c, said) = QController();
QVendorOpen(w, coins: 300);
w.SelectedId = QVScarab;
uint Last() => w.NextRequest - 1;
// No bank: refused before sending, as before; max 25.
int sent = w.Sent.Count;
c.Buy(w, QtyAmount.Of(100), "");
Eq(said.Last(), (false, "Not enough pyreals: 100 Mana Scarab cost 1,200, you have 300 (you can buy 25)."), "no bank: refused");
Eq(w.Sent.Count, sent, "nothing sent");
c.SetBox(w, QtyAmount.Max);
Eq(c.Value, 25, "no bank: the box's max");
c.Buy(w, QtyAmount.Max, "");
Eq(w.Sent.Last(), $"buy {QVScarab:X} from {QVendor:X} 25", "no bank: buy max sends 25");
w.Status = new VendorTradeStatus { RequestId = Last(), State = VendorTradeState.Done, Result = VendorTradeResult.Accepted, Estimate = 300, IsBuy = true };
c.Tick(w);
Eq(said.Last(), (true, "Bought 25 Mana Scarab for 300 pyreals."), "bought");
// A bank that's read and covers it.
w.BankInfo = new VendorBank(true, 5000);
c.SetBox(w, QtyAmount.Max);
Eq(c.Value, 441, "the box's max counts pack + bank");
Check(said.Last().Text.Contains("price 5,292; pack 300 + bank 5,000", StringComparison.Ordinal), $"/rdef qty says both: {said.Last().Text}");
Check(c.View(w)!.Subject.MaxBuy == 441, "the window's max too");
c.Buy(w, QtyAmount.Of(100), "");
Eq(w.Sent.Last(), $"buy {QVScarab:X} from {QVendor:X} 100", "100 for 1,200: sent");
w.Status = new VendorTradeStatus { RequestId = Last(), State = VendorTradeState.Done, Result = VendorTradeResult.Accepted, Estimate = 1200, IsBuy = true };
c.Tick(w);
Eq(said.Last(), (true, "Bought 100 Mana Scarab for 1,200 pyreals."), "bought with the bank's help");
DefCommand cmd = DefCommandParser.Parse("buy max Mana Scarab");
c.Buy(w, cmd.Amount, cmd.Text);
Eq(w.Sent.Last(), $"buy {QVScarab:X} from {QVendor:X} 441", "/rdef buy max: pack + bank");
w.Status = new VendorTradeStatus { RequestId = Last(), State = VendorTradeState.Refused, Message = "costs 5292 pyreals, you have 300" };
c.Tick(w);
Check(!said.Last().Ok && said.Last().Text.StartsWith("RynthCore didn't send it", StringComparison.Ordinal)
&& said.Last().Text.Contains("out of the bank", StringComparison.Ordinal), $"RynthCore's own money check, said: {said.Last().Text}");
// A bank that's read and doesn't cover it: refused before sending, both said.
w.BankInfo = new VendorBank(true, 500);
sent = w.Sent.Count;
c.Buy(w, QtyAmount.Of(100), "");
Eq(said.Last(), (false, "Not enough pyreals: 100 Mana Scarab cost 1,200, you have 300 in your pack + 500 in the bank (you can buy 66)."), "pack + bank short: refused");
Eq(w.Sent.Count, sent, "nothing sent");
c.SetBox(w, QtyAmount.Max);
Eq(c.Value, 66, "the box's max: 66");
cmd = DefCommandParser.Parse("buy 100 Mana Scarab");
c.Buy(w, cmd.Amount, cmd.Text);
Check(!said.Last().Ok && said.Last().Text.Contains("in the bank", StringComparison.Ordinal), "/rdef buy 100 replies the same");
// A bank that can't be read: sent, and the server decides.
w.BankInfo = new VendorBank(true);
c.SetBox(w, QtyAmount.Max);
Eq(c.Value, 6600, "the box's max: 66 free slots of 100 (money not counted)");
Check(said.Last().Ok && said.Last().Text.Contains("max counts the vendor's stock, your pack space and burden only", StringComparison.Ordinal),
$"with the note: {said.Last().Text}");
c.Buy(w, QtyAmount.Of(100), "");
Eq(w.Sent.Last(), $"buy {QVScarab:X} from {QVendor:X} 100", "100 for 1,200 with 300 in the pack: sent");
w.Status = new VendorTradeStatus { RequestId = Last(), State = VendorTradeState.Done, Result = VendorTradeResult.Accepted, Estimate = 1200, IsBuy = true };
c.Tick(w);
Eq(said.Last(), (true, "Bought 100 Mana Scarab for 1,200 pyreals."), "the server's bank covered it");
c.Buy(w, QtyAmount.Of(100), "");
w.Status = new VendorTradeStatus { RequestId = Last(), State = VendorTradeState.Done, Result = VendorTradeResult.AnsweredNoRefresh, IsBuy = true };
c.Tick(w);
Check(!said.Last().Ok && said.Last().Text.Contains("the bank may not cover 1,200 pyreals", StringComparison.Ordinal), $"the server's own no, reported: {said.Last().Text}");
c.Buy(w, QtyAmount.Of(100), "");
w.Status = new VendorTradeStatus { RequestId = Last(), State = VendorTradeState.Refused, Message = "costs 1200 pyreals, you have 300" };
c.Tick(w);
Check(!said.Last().Ok && said.Last().Text.StartsWith("RynthCore didn't send it", StringComparison.Ordinal), "RynthCore's own money check, said");
cmd = DefCommandParser.Parse("buy max Mana Scarab");
c.Buy(w, cmd.Amount, cmd.Text);
Eq(w.Sent.Last(), $"buy {QVScarab:X} from {QVendor:X} 6600", "/rdef buy max: room only");
w.Status = null;
w.Advance(QuantityController.BuyAnswerMs);
c.Tick(w);
Check(!said.Last().Ok && said.Last().Text.StartsWith("No answer about 6,600 Mana Scarab", StringComparison.Ordinal), "and it always answers");
c.Buy(w, QtyAmount.Of(7000), "");
Check(!said.Last().Ok && said.Last().Text.StartsWith("Not enough room in your packs", StringComparison.Ordinal), "room is still checked first");
// The pack alone pays: the same with any bank.
c.Buy(w, QtyAmount.Of(20), "");
Eq(w.Sent.Last(), $"buy {QVScarab:X} from {QVendor:X} 20", "20 for 240: sent");
w.Status = new VendorTradeStatus { RequestId = Last(), State = VendorTradeState.Done, Result = VendorTradeResult.AnsweredNoRefresh, IsBuy = true };
c.Tick(w);
Check(said.Last().Text.EndsWith("(money, room, or too busy).", StringComparison.Ordinal), "the pack paid: no bank in the answer");
}
private static void QtyStore()
{
var store = new DefStore(System.IO.Path.Combine(_temp, "qty"));

View file

@ -41,6 +41,10 @@
<Compile Include="..\..\Plugins\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
<!-- The server plugin's bank values for the quantity box's buys (2026-10-31). -->
<Compile Include="..\..\Plugins\Shared\EngineServerState.cs" Link="Shared\EngineServerState.cs" />
<Compile Include="..\..\Plugins\Shared\ServerStateClient.cs" Link="Shared\ServerStateClient.cs" />
<Compile Include="..\..\Plugins\Shared\RynthServerProfileApi.cs" Link="Shared\RynthServerProfileApi.cs" />
<!-- The shortcut bar, panel buttons and Selection windows (2026-10-22) draw with the shared ImGui look. -->
<Compile Include="..\..\Plugins\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<Compile Include="..\..\Plugins\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />

View file

@ -0,0 +1,166 @@
using System.Text.Json;
using RynthCore.Plugin.RynthNet;
using RynthCore.Plugin.RynthNet.Characters;
namespace RynthNet.Tests;
// The Characters window's two looks (2026-10-31): minimal (one line per character, frameless) and
// full (every column), the low-health colours, the status dot, the minimal line's layout, /rn view,
// the frameless manifest, and the choice kept per character in settings.json.
internal static partial class Program
{
private static void LookChecks()
{
HealthThresholds();
StatusDots();
MinimalLayout();
ViewNames();
ViewCommand();
FramelessManifest();
ViewPersistence();
}
private static CharacterRow Row(float hp, CharStateKind kind = CharStateKind.Idle, bool vitals = true) => new()
{
Name = "Char One", HasVitals = vitals, Hp = new CharVital(hp, "x"), StateKind = kind,
};
private static void HealthThresholds()
{
Check(CharactersLook.LowHp == 0.5f && CharactersLook.CriticalHp == 0.25f, "low at half health, critical at a quarter");
Check(CharactersLook.Hp(1f) == HpWarn.Ok && CharactersLook.Hp(0.51f) == HpWarn.Ok, "over half: fine (the text colour)");
Check(CharactersLook.Hp(0.5f) == HpWarn.Low && CharactersLook.Hp(0.26f) == HpWarn.Low, "half or less: low (amber)");
Check(CharactersLook.Hp(0.25f) == HpWarn.Critical && CharactersLook.Hp(0.01f) == HpWarn.Critical, "a quarter or less: critical (red)");
Check(CharactersLook.Hp(0f) == HpWarn.Dead, "no health: dead (red)");
Check(CharactersLook.Hp(Row(0.9f, CharStateKind.Dead)) == HpWarn.Dead, "a dead state is dead, whatever the last vitals said");
Check(CharactersLook.Hp(Row(0.3f)) == HpWarn.Low && CharactersLook.Hp(Row(0.2f)) == HpWarn.Critical, "a row's health share");
Check(CharactersLook.Hp(Row(0f, vitals: false)) == HpWarn.Unknown, "no vitals yet: unknown, not dead");
}
private static void StatusDots()
{
Check(CharactersLook.Dot(new CharacterRow { LoggedOut = true, StateKind = CharStateKind.LoggedOut }) == CharDot.Off, "logged out: an empty ring");
Check(CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.NoStatus }) == CharDot.Off, "no status yet: an empty ring");
Check(CharactersLook.Dot(new CharacterRow { IsSelf = true }) == CharDot.Self, "this client");
Check(CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.Dead, Stale = true }) == CharDot.Dead, "dead before stale");
Check(CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.Botting, Stale = true }) == CharDot.Stale, "stale before what the bot was doing");
Check(CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.Botting }) == CharDot.Botting, "botting");
Check(CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.Fighting }) == CharDot.Fighting, "botting: fighting");
Check(CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.Portal }) == CharDot.Portal, "portal space");
Check(CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.Idle }) == CharDot.Idle
&& CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.CombatMode }) == CharDot.Idle, "idle, in or out of a stance");
}
private static void MinimalLayout()
{
// dot 12, gap 6, bars 3 x 24 + 2 x 2 = 76, arrow 14: everything for an 80 px name and a 40 px distance is 234 px.
MinimalLine all = CharactersLook.Minimal(300, 80, 40);
Check(all.Bars && all.Distance && all.NameWidth == 80 && all.BarWidth == 24, "300 px: name, bars, arrow and distance");
Check(Math.Abs(all.Width(1f, 40) - 234) < 0.01f, $"the whole line is 234 px (got {all.Width(1f, 40)})");
Check(CharactersLook.Minimal(234, 80, 40).Distance && !CharactersLook.Minimal(233, 80, 40).Distance, "the distance needs the whole line");
MinimalLine noDist = CharactersLook.Minimal(200, 80, 40);
Check(noDist.Bars && !noDist.Distance && noDist.NameWidth == 80, "200 px: name and bars, no distance");
MinimalLine squeezed = CharactersLook.Minimal(150, 80, 40);
Check(squeezed.Bars && squeezed.NameWidth == 56 && squeezed.BarWidth == 24, $"150 px: the name gives way first ({squeezed.NameWidth})");
MinimalLine thin = CharactersLook.Minimal(100, 80, 40);
Check(thin.Bars && thin.NameWidth == 30 && thin.BarWidth == 16, $"100 px: the name at its least, then the bars narrow ({thin.BarWidth})");
MinimalLine none = CharactersLook.Minimal(60, 80, 40);
Check(!none.Bars && !none.Distance && none.NameWidth == 48, "60 px: just the dot and the name");
Check(!CharactersLook.Minimal(1000, 80, 0).Distance, "no row has a distance: no distance column");
MinimalLine big = CharactersLook.Minimal(600, 160, 80, k: 2f);
Check(big.Bars && big.Distance && big.BarWidth == 48, "the sizes grow with the text size");
Check(CharactersLook.MinimalHeight(0) == 20 && CharactersLook.MinimalHeight(3) == 52 && CharactersLook.MinimalHeight(3, 1.5f) == 78,
"the window asks for one line per character (one for the status when there are none)");
}
private static void ViewNames()
{
Check(CharactersLook.Name(CharactersViewMode.Minimal) == "minimal" && CharactersLook.Name(CharactersViewMode.Full) == "full", "names");
foreach (string s in new[] { "minimal", "MIN", "compact", "bare" })
Check(CharactersLook.TryParse(s, out CharactersViewMode m) && m == CharactersViewMode.Minimal, $"'{s}' is minimal");
foreach (string s in new[] { "full", "Edit", "framed" })
Check(CharactersLook.TryParse(s, out CharactersViewMode m) && m == CharactersViewMode.Full, $"'{s}' is full");
Check(!CharactersLook.TryParse("huge", out _) && !CharactersLook.TryParse(null, out _), "anything else isn't a view");
Check(CharactersLook.FromSetting(null) == CharactersViewMode.Minimal && CharactersLook.FromSetting("weird") == CharactersViewMode.Minimal
&& CharactersLook.FromSetting("full") == CharactersViewMode.Full, "the setting: minimal unless it says full");
}
private static void ViewCommand()
{
var (min, full) = (CharactersViewMode.Minimal, CharactersViewMode.Full);
ViewAnswer a = CharactersLook.Command("", min, loggedIn: false);
Check(a.Ok && !a.Changed && a.Next == min && a.Reply.StartsWith("the Characters window is in the minimal view", StringComparison.Ordinal),
"/rn view alone: the view now (logged in or not): " + a.Reply);
a = CharactersLook.Command("full", min, true);
Check(a.Ok && a.Changed && a.Next == full && a.Reply.StartsWith("the Characters window now shows the full view", StringComparison.Ordinal), "/rn view full: " + a.Reply);
a = CharactersLook.Command("FULL", full, true);
Check(a.Ok && !a.Changed && a.Reply.StartsWith("the Characters window is already in the full view", StringComparison.Ordinal), "already full: " + a.Reply);
Check(CharactersLook.Command("toggle", full, true).Next == min && CharactersLook.Command("toggle", min, true).Next == full, "toggle");
Check(CharactersLook.Command("minimal", full, true).Reply.Contains("/rn view full", StringComparison.Ordinal), "the minimal reply says how to get the full view back");
a = CharactersLook.Command("full", min, loggedIn: false);
Check(!a.Ok && a.Reply.StartsWith("log in first", StringComparison.Ordinal), "before login: why (it is kept per character)");
a = CharactersLook.Command("huge", min, true);
Check(!a.Ok && a.Reply == CharactersLook.Usage && a.Reply.StartsWith("usage: /rn view", StringComparison.Ordinal), "a wrong view: the usage");
}
private static void FramelessManifest()
{
Check(CharactersManifest.For(false) == CharactersManifest.Json && CharactersManifest.For(true) == CharactersManifest.FramelessJson,
"the engine framed manifest without frameless windows, the frameless one with them");
using JsonDocument doc = JsonDocument.Parse(CharactersManifest.FramelessJson);
JsonElement w = doc.RootElement.GetProperty("windows")[0];
Check(w.GetProperty("title").GetString() == CharactersManifest.Title && w.GetProperty("surface").GetString() == CharactersManifest.Surface,
"the same title (players' saved place) and surface");
Check(w.GetProperty("chrome").GetString() == "none" && w.GetProperty("fitHeight").GetBoolean(), "frameless, as tall as what it shows");
Check(w.GetProperty("bar").GetBoolean() && w.GetProperty("minWidth").GetInt32() <= 200, "a bar button; narrow enough for the minimal line");
using JsonDocument old = JsonDocument.Parse(CharactersManifest.Json);
Check(!old.RootElement.GetProperty("windows")[0].TryGetProperty("chrome", out _), "the framed one has no chrome key (older engines)");
}
private static void ViewPersistence()
{
string dir = Path.Combine(AppContext.BaseDirectory, "settings-test-" + Environment.ProcessId);
string? before = Environment.GetEnvironmentVariable("RYNTHNET_DIR");
Environment.SetEnvironmentVariable("RYNTHNET_DIR", dir);
try
{
Directory.CreateDirectory(dir);
if (File.Exists(RynthNetSettings.FilePath)) File.Delete(RynthNetSettings.FilePath);
Check(RynthNetSettings.FilePath.StartsWith(dir, StringComparison.OrdinalIgnoreCase), "the test's settings file is under its own bin folder");
RynthNetSettings fresh = RynthNetSettings.Load(out string? err);
Check(err == null && fresh.ViewFor("TestWorld|Char One") == CharactersViewMode.Minimal, "nothing saved: minimal (the default)");
const string a = "TestWorld|Char One", b = "TestWorld|Char Two";
Check(RynthNetSettings.Update(s => s.Character(a).View = CharactersLook.Name(CharactersViewMode.Full), out _, out err), "saved: " + err);
RynthNetSettings back = RynthNetSettings.Load(out err);
Check(back.ViewFor(a) == CharactersViewMode.Full, "the full view comes back for that character");
Check(back.ViewFor(b) == CharactersViewMode.Minimal, "another character keeps the default");
string text = File.ReadAllText(RynthNetSettings.FilePath);
Check(text.Contains("\"view\": \"full\"", StringComparison.Ordinal), "written as \"view\": \"full\" under the character");
// Another client's change (tags) on top keeps the view, and the view keeps the tags.
Check(RynthNetSettings.Update(s => s.Character(a).Tags.Add("heal"), out _, out _), "a tag saved alongside");
back = RynthNetSettings.Load(out _);
Check(back.ViewFor(a) == CharactersViewMode.Full && back.TagsFor(a).Contains("heal"), "the view and the tags live together");
// Back to minimal: saved as such; an entry with nothing left is dropped.
Check(RynthNetSettings.Update(s => { s.Character(b).View = "minimal"; s.Character(a).Tags.Clear(); s.Character(a).View = null; }, out _, out _), "minimal saved");
back = RynthNetSettings.Load(out _);
Check(back.ViewFor(b) == CharactersViewMode.Minimal && back.Characters.ContainsKey(b), "minimal is kept when chosen");
Check(!back.Characters.ContainsKey(a), "a character with no tags, policy or view isn't written");
// A hand-edited file with a view the plugin doesn't know: the default, not an error.
File.WriteAllText(RynthNetSettings.FilePath, "{\"characters\":{\"TestWorld|Char One\":{\"tags\":[],\"view\":\"sideways\"}}}");
back = RynthNetSettings.Load(out err);
Check(err == null && back.ViewFor(a) == CharactersViewMode.Minimal && back.Characters[a].View == null, "an unknown view: minimal");
File.WriteAllText(RynthNetSettings.FilePath, "{\"characters\":{\"TestWorld|Char One\":{\"view\":\"FULL\"}}}");
Check(RynthNetSettings.Load(out _).ViewFor(a) == CharactersViewMode.Full, "any case");
}
finally
{
Environment.SetEnvironmentVariable("RYNTHNET_DIR", before);
try { Directory.Delete(dir, recursive: true); } catch { } // the test's own output, under bin
}
}
}

View file

@ -29,6 +29,7 @@ internal static partial class Program
Vitals();
WindowChecks();
Replies();
LookChecks();
Console.WriteLine($"{_checks} checks, {_failed} failed");
return _failed == 0 ? 0 : 1;

View file

@ -7,7 +7,10 @@
built from a fake game (CharactersRows.cs), the Atlas names (AtlasNames.cs), the manifest
RynthCore hosts the window from (CharactersManifest.cs), and Shared\RynthUi\RynthIcons.cs
against the engine's baked icons (the sibling RynthCore's ImGui\PhosphorIcons.cs, when there).
The window itself draws with ImGui and isn't compiled here.
The window's looks (Characters\CharactersLook.cs, 2026-10-31): the minimal line's layout, the
low-health colours, the status dot, /rn view, and the choice kept per character in
settings.json (RynthNetSettings.cs, with RYNTHNET_DIR pointed at a folder under this program's
bin, never C:\Games). The window itself draws with ImGui and isn't compiled here.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
@ -25,6 +28,10 @@
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNet\Characters\AtlasNames.cs" Link="RynthNet\AtlasNames.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNet\Characters\CharactersManifest.cs" Link="RynthNet\CharactersManifest.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNet\CommandParser.cs" Link="RynthNet\CommandParser.cs" />
<!-- The window's two looks (minimal / full) and where the choice is kept (settings.json, under the test's own folder). -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNet\Characters\CharactersLook.cs" Link="RynthNet\CharactersLook.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNet\RynthNetSettings.cs" Link="RynthNet\RynthNetSettings.cs" />
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
<Compile Include="..\..\Plugins\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthIcons.cs" />
</ItemGroup>