Snapshot for release 2026.10.13.1 (internal d2b5fb3)

This commit is contained in:
Tom Bohar 2026-10-13 14:25:49 -04:00
commit 319740ff5d
291 changed files with 58505 additions and 2107 deletions

View file

@ -0,0 +1,54 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Builds RynthAi's embedded spell catalog (Combat\SpellCatalog.tsv) from ACECustom's
Reports\SpellCatalog-Full.csv.
.DESCRIPTION
The Spells window and buff profiles list spells from this catalog. ACECustom's report
is the source of truth for level, school, Self/Other/Item target, effect type and spell
family on the ILT server. The full CSV is ~13 MB because of its Supersedes columns;
this keeps only the columns RynthAi reads, one spell per line, tab separated:
Id Name Level Effect Target FamilyId FamilyName Power DurationSec School Mana Description
Re-run after ACECustom regenerates its catalog (Scripts\export_spell_catalog.py).
.PARAMETER Source
ACECustom SpellCatalog-Full.csv.
.PARAMETER Out
Output TSV (UTF-8, no BOM).
#>
param(
[string]$Source = (Join-Path $PSScriptRoot '..\..\ACECustom\Reports\SpellCatalog-Full.csv'),
[string]$Out = (Join-Path $PSScriptRoot '..\Plugins\RynthCore.Plugin.RynthAi\Combat\SpellCatalog.tsv')
)
$ErrorActionPreference = 'Stop'
if (-not (Test-Path $Source)) { throw "ACECustom spell catalog not found: $Source" }
# Tabs and line breaks would break the one-row-per-line format.
function Clean([string]$s) {
if ($null -eq $s) { return '' }
return ($s -replace "[`t`r`n]+", ' ').Trim()
}
$rows = Import-Csv -Path $Source
$lines = New-Object System.Collections.Generic.List[string]
$lines.Add('# RynthAi spell catalog generated from ACECustom Reports\SpellCatalog-Full.csv by Tools\Generate-SpellCatalog.ps1. Do not edit by hand.')
$lines.Add("# Id`tName`tLevel`tEffect`tTarget`tFamilyId`tFamilyName`tPower`tDurationSec`tSchool`tMana`tDescription")
foreach ($r in ($rows | Sort-Object { [int]$_.SpellId })) {
$fields = @(
(Clean $r.SpellId), (Clean $r.Name), (Clean $r.Level), (Clean $r.EffectType), (Clean $r.Target),
(Clean $r.FamilyId), (Clean $r.FamilyName), (Clean $r.Power), (Clean $r.DurationSec),
(Clean $r.School), (Clean $r.Mana), (Clean $r.Description)
)
$lines.Add($fields -join "`t")
}
$outFull = [System.IO.Path]::GetFullPath($Out)
[System.IO.File]::WriteAllLines($outFull, $lines, (New-Object System.Text.UTF8Encoding($false)))
Write-Host ("Wrote {0} spells to {1} ({2:N0} bytes)" -f ($lines.Count - 2), $outFull, (Get-Item $outFull).Length)

View file

@ -18,6 +18,34 @@ internal static partial class Program
TestAddT11Weapon();
TestAddT11Armor();
TestAddT11EdgeCases();
TestAddT11GradedGear();
}
private static void TestAddT11GradedGear()
{
// Graded armor with a stamped tier: exact tier, gear grade, modifiers; no slots or Tainted.
LootItemFacts f = T11Facts("T11 - Celdon Breastplate", AcObjectClass.Armor, null, T11GradedArmorUse);
f.T11 = T11ItemInfo.Parse(f.Name, null, T11GradedArmorUse, new T11ServerProps(18, 0, -1));
LootItemRuleDraft? d = LootItemRules.Build(f, new LootItemRuleOptions { IncludeT11 = true }, out _);
Check(d != null, "add t11 graded: armor builds");
if (d == null) return;
List<string> t = T11Conds(d.Rule);
Check(t.Contains(GE(T11Keys.EstimatedTier, 18)), "add t11 graded: stamped tier");
Check(t.Contains(GE(T11Keys.GearGrade, 12)), "add t11 graded: gear grade B+");
Check(t.Contains(GE(T11Keys.ForModifier(50), 60)) && t.Contains(GE(T11Keys.ForModifier(19), 50)), "add t11 graded: modifiers");
Check(!t.Any(c => c.EndsWith("," + T11Keys.Tainted) || c.EndsWith("," + T11Keys.PropertySlots)
|| c.EndsWith("," + T11Keys.FreePropertySlots)), "add t11 graded: no bag state");
Eq(d.Notes.Count, 0, "add t11 graded: no notes");
Check(LootItemRules.PreviewLines(d.Rule).Any(l => l.Contains("T11: Gear Grade")), "add t11 graded: preview names Gear Grade");
// Jewelry: the key-54 Cast on Strike is catalogued now, so it gets a condition instead of a note.
LootItemFacts ring = T11Facts("T11 - Ring", AcObjectClass.Jewelry, null, T11JewelryUse);
LootItemRuleDraft? r = LootItemRules.Build(ring, new LootItemRuleOptions { IncludeT11 = true }, out _);
List<string> rt = r == null ? new List<string>() : T11Conds(r.Rule);
Check(rt.Contains(GE(T11Keys.ForModifier(54), 75)), "add t11 graded: jewelry Cast on Strike power");
Check(rt.Contains(GE(T11Keys.CastOnStrikeCount, 1)), "add t11 graded: jewelry proc counted");
Check(rt.Contains(GE(T11Keys.GearGrade, 14)), "add t11 graded: jewelry gear grade A");
Check(r != null && r.Notes.Count == 0, "add t11 graded: jewelry has no unknown-modifier note");
}
/// <summary>A condition as "type:line,line" for order-sensitive comparisons.</summary>

View file

@ -38,6 +38,26 @@ internal static partial class Program
"- Max Health Pct +2% [1-4]\n" +
"- Modifier 60 +3 [1-5]\n";
// Armor as ACECustom appraises it since #543 (2026-10-06): zone lock, Gear Grade and Properties lead
// the block; markers follow a line's band; Tainted closes it.
private const string T11GradedArmorUse =
"Modifiers:\n" +
"- Zone Locked (Power Reduced)\n" +
"- Gear Grade: B+ (average of 4 rolled lines)\n" +
"- Properties: 3 of 5\n" +
"- Damage Resist +60 [35-69] (Built-in)\n" +
"- Max Health +50 [14-69] (+20 tinkered) (Locked)\n" +
"- Fortify Vitals +15% vitals (Built-in)\n" +
"- Tainted: bags no longer work on this item\n";
// Jewelry with the key-54 Cast on Strike line.
private const string T11JewelryUse =
"Modifiers:\n" +
"- Gear Grade: A (average of 1 rolled line)\n" +
"- Properties: 2\n" +
"- Cast on Strike 75% power [50-100] - Force Arc, 13% per hit\n" +
"- Life on Hit 2% HP per hit [1-3]\n";
private static void RunT11Tests()
{
Console.WriteLine("\n-- T11 loot --");
@ -48,6 +68,86 @@ internal static partial class Program
TestT11AugReport();
TestT11Keys();
TestT11Editor();
TestT11GearGradeAndSlots();
TestT11JewelryProc();
TestT11ServerProps();
}
private static void TestT11GearGradeAndSlots()
{
T11ItemInfo a = T11ItemInfo.Parse("T11 - Celdon Breastplate", null, T11GradedArmorUse);
Eq(a.Modifiers.Count, 3, "graded: grade / properties / tainted / zone lock are not modifiers");
Eq(a.GearGrade, "B+", "graded: gear grade label");
Eq(a.GearGradeRank, 12, "graded: gear grade rank");
Eq(a.GearGradeLines, 4, "graded: gear grade line count");
Eq(a.Grade, null, "graded: no weapon grade on armor");
Eq((a.PropertySlots, a.PropertySlotCap, a.FreePropertySlots), (3, 5, 2), "graded: properties 3 of 5");
Check(a.Tainted && a.ZoneLocked, "graded: tainted and zone locked");
T11Modifier dr = a.Modifiers.First(m => m.Key == 50);
Check(dr.BuiltIn && !dr.Locked && dr.Tinkered == 0, "graded: Damage Resist built-in");
Eq(dr.RollPercent, 74, "graded: band read before the marker");
T11Modifier mh = a.Modifiers.First(m => m.Key == 19);
Eq((mh.Value, mh.Tinkered, mh.Locked), (50, 20, true), "graded: Max Health value, tinker, lock");
Eq(mh.RollPercent, 65, "graded: Max Health roll (50-14)/(69-14)");
Check(a.Modifiers.Any(m => m.Key == 41 && m.IsSlotSpecial && m.Value == 15), "graded: slot special with a marker");
int V(int key) => T11Keys.TryGetValue(a, key, null, out int v) ? v : int.MinValue;
Eq(V(T11Keys.GearGrade), 12, "graded key: gear grade");
Eq(V(T11Keys.PropertySlots), 3, "graded key: slots used");
Eq(V(T11Keys.PropertySlotCap), 5, "graded key: slot limit");
Eq(V(T11Keys.FreePropertySlots), 2, "graded key: free slots");
Eq(V(T11Keys.Tainted), 1, "graded key: tainted");
Eq(V(T11Keys.ModifierCount), 3, "graded key: modifier count");
// A weapon shows its slot count in Property Details, without a Modifiers block.
T11ItemInfo w = T11ItemInfo.Parse("Tachi",
"Property Details:\n- Weapon Grade: A (95% of max damage)\n- Properties: 2 of 5\n", null);
Check(w.IsT11, "graded: weapon grade marks T11");
Eq((w.PropertySlots, w.PropertySlotCap), (2, 5), "graded: weapon properties line");
Eq(w.Modifiers.Count, 0, "graded: weapon properties line is not a modifier");
Check(T11ItemInfo.Parse("Robe", null, "Modifiers:\n- Properties: 1 of 4\n").IsT11, "graded: a Properties line marks T11");
Check(!T11ItemInfo.Parse("Robe", null, "Modifiers:\n- Tainted: bags no longer work on this item\n").IsT11, "graded: Tainted alone doesn't mark T11");
Eq(T11ItemInfo.None.PropertySlots, -1, "graded: no properties line = -1");
}
private static void TestT11JewelryProc()
{
T11ItemInfo r = T11ItemInfo.Parse("T11 - Ring", null, T11JewelryUse);
Eq(r.Modifiers.Count, 2, "jewel: two modifiers");
T11Modifier cos = r.Modifiers.First(m => m.Key == 54);
Eq((cos.Name, cos.Value, cos.RollPercent), ("Cast on Strike", 75, 50), "jewel: Cast on Strike power and roll");
Eq(r.Procs.Count, 1, "jewel: proc from the modifier line");
Eq(r.Procs.Count > 0 ? r.Procs[0] : default, ("Force Arc", 13.0), "jewel: proc spell and chance");
Eq((r.PropertySlots, r.PropertySlotCap), (2, 0), "jewel: unlimited properties line");
Eq(r.GearGradeLines, 1, "jewel: singular rolled line");
Check(r.Modifiers.Any(m => m.Key == 48 && m.Value == 2 && m.RollPercent == 50), "jewel: Life on Hit");
Eq(T11Keys.TryGetValue(r, T11Keys.ForModifier(54), null, out int p) ? p : -1, 75, "jewel: per-modifier key for 54");
Check(LootRuleText.LongKeys.Any(k => k.Id == T11Keys.ForModifier(54) && k.Name == "T11 Mod: Cast on Strike"), "jewel: editor names key 54");
}
private static void TestT11ServerProps()
{
// No name prefix and no text: the stamped tier alone marks T11 and is exact.
T11ItemInfo z = T11ItemInfo.Parse("Celdon Breastplate", null, null, new T11ServerProps(18, 0, -1));
Check(z.IsT11 && z.TierIsExact, "server: ZcTier 18 marks T11, exact");
Eq(z.Tier, 18, "server: tier from ZcTier");
Eq(T11Keys.TryGetValue(z, T11Keys.EstimatedTier, null, out int t) ? t : 0, 18, "server: tier key reads ZcTier");
Eq(T11Keys.TryGetValue(z, T11Keys.TierIsExact, null, out int x) ? x : 0, 1, "server: Tier Is Exact");
// The weapon tier beats the gate estimate (3,000 item augs = T13), and the quality comes along.
T11ItemInfo w = T11ItemInfo.Parse("T11 - Tachi", T11WeaponLongDesc, null, new T11ServerProps(0, 14, 873));
Eq((w.EstimatedTier, w.Tier, w.WeaponQuality), (13, 14, 873), "server: weapon tier and quality");
Eq(T11ItemInfo.Parse("T11 - Tachi", T11WeaponLongDesc, null).TierIsExact, false, "server: no props = estimate");
Eq(T11ItemInfo.Parse("T11 - Tachi", T11WeaponLongDesc, null).WeaponQuality, -1, "server: no props = no quality");
Eq(T11ServerProps.None.WeaponQuality, -1, "server: None has no quality");
// A low stamped tier on a plain item doesn't make it T11.
Check(!T11ItemInfo.Parse("Celdon Breastplate", null, null, new T11ServerProps(7, 0, -1)).IsT11, "server: tier 7 is not T11");
Check(LootRuleText.LongKeys.Any(k => k.Id == T11Catalog.PropZcTier && k.Name == "ZcTier"), "server: editor names ZcTier");
Check(LootRuleText.LongKeys.Any(k => k.Id == T11Catalog.PropWeaponAugScaleQuality), "server: editor lists WeaponAugScaleQuality");
Check(LootRuleText.LongKeys.Any(k => k.Id == T11Catalog.PropWeaponAugScaleTier), "server: editor lists WeaponAugScaleTier");
Eq(LootRuleText.ValueName(T11Keys.GearGrade, "16"), "S", "server: gear grade value table");
}
private static void TestT11WeaponParse()

View file

@ -5,6 +5,8 @@ namespace RynthCore.MonsterEditor;
[JsonSerializable(typeof(List<MonsterRule>))]
[JsonSerializable(typeof(EditorSettings))]
// UB damage-insights seed written for the RynthAi plugin (see UbMobSeedImport).
[JsonSerializable(typeof(RynthCore.CreatureSeed.UbMobSeedFile))]
// Case-insensitive like the plugin's RynthAiJsonContext, which reads the same files.
[JsonSourceGenerationOptions(WriteIndented = true, IncludeFields = true, PropertyNameCaseInsensitive = true)]
internal partial class EditorJsonContext : JsonSerializerContext { }

View file

@ -169,14 +169,19 @@
</DataGridTemplateColumn>
<!-- Priority -->
<DataGridTemplateColumn Header="P" Width="32" MinWidth="30">
<DataGridTemplateColumn Width="40" MinWidth="36">
<DataGridTemplateColumn.Header>
<TextBlock Text="P" ToolTip.Tip="Priority: higher is fought first. 0 = IGNORE: never attacked, even if it attacks you, and it does not hold up nav, looting or buffs."/>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate><DataTemplate>
<TextBlock Text="{Binding Priority}"
<TextBlock Text="{Binding PriorityText}"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
VerticalAlignment="Center"
ToolTip.Tip="Priority: higher is fought first. 0 = IGNORE: never attacked, even if it attacks you, and it does not hold up nav, looting or buffs."/>
</DataTemplate></DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate><DataTemplate>
<TextBox Text="{Binding Priority, Mode=TwoWay}" Padding="3,1"/>
<TextBox Text="{Binding Priority, Mode=TwoWay}" Padding="3,1"
ToolTip.Tip="Priority: higher is fought first. 0 = IGNORE: never attacked, even if it attacks you, and it does not hold up nav, looting or buffs."/>
</DataTemplate></DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

View file

@ -21,6 +21,7 @@ public class MonsterRule : INotifyPropertyChanged
private bool _useArc, _useBolt = true, _useRing, _useStreak, _useBlast, _useWall;
private string _exVuln = "None";
private int _offhandId;
private int _preferredAmmoItemId;
private string _petDamage = "PAuto";
public string Name { get => _name; set { _name = value; OnPropertyChanged(); } }
@ -32,7 +33,12 @@ public class MonsterRule : INotifyPropertyChanged
/// Empty = match by name only. Kept and editable here (before 2026-10-05 an editor save
/// dropped it, so expression rules fell back to name-only).</summary>
public string MatchExpression { get => _matchExpression; set { _matchExpression = value ?? ""; OnPropertyChanged(); } }
public int Priority { get => _priority; set { _priority = value; OnPropertyChanged(); } }
/// <summary>Target order: a higher Priority is fought first. 0 (or less) means IGNORE: RynthAi never targets the
/// monster, even one attacking the player, and does not wait on it.</summary>
public int Priority { get => _priority; set { _priority = value; OnPropertyChanged(); OnPropertyChanged(nameof(PriorityText)); } }
/// <summary>What the Priority column shows: the number, or "ign" for Priority 0 (ignore).</summary>
[JsonIgnore]
public string PriorityText => _priority <= 0 ? "ign" : _priority.ToString();
public string DamageType { get => _damageType; set { _damageType = value; OnPropertyChanged(); } }
public int WeaponId { get => _weaponId; set { _weaponId = value; OnPropertyChanged(); } }
public bool Fester { get => _fester; set { _fester = value; OnPropertyChanged(); } }
@ -49,6 +55,8 @@ public class MonsterRule : INotifyPropertyChanged
public bool UseWall { get => _useWall; set { _useWall = value; OnPropertyChanged(); } }
public string ExVuln { get => _exVuln; set { _exVuln = value; OnPropertyChanged(); } }
public int OffhandId { get => _offhandId; set { _offhandId = value; OnPropertyChanged(); } }
/// <summary>Optional loose ammo stack id for missile combat while this rule matches (0 = auto).</summary>
public int PreferredAmmoItemId { get => _preferredAmmoItemId; set { _preferredAmmoItemId = value; OnPropertyChanged(); } }
public string PetDamage { get => _petDamage; set { _petDamage = value; OnPropertyChanged(); } }
/// <summary>Every field in the file this class doesn't know (e.g. the plugin's CustomDebuffs,
@ -57,8 +65,65 @@ public class MonsterRule : INotifyPropertyChanged
public Dictionary<string, JsonElement>? ExtraFields { get; set; }
[JsonIgnore]
/// <summary>True for the special row named "Default" — the catch-all when no other rule matches.</summary>
public bool IsDefault => string.Equals(_name, "Default", System.StringComparison.OrdinalIgnoreCase);
/// <summary>Full copy (for import merge). Copies every rule field, UseBlast included.</summary>
public MonsterRule Clone()
{
return new MonsterRule
{
Name = _name,
Category = _category,
MatchExpression = _matchExpression,
Priority = _priority,
DamageType = _damageType,
WeaponId = _weaponId,
Fester = _fester,
Broadside = _broadside,
GravityWell = _gravityWell,
Imperil = _imperil,
Yield = _yield,
Vuln = _vuln,
UseArc = _useArc,
UseBolt = _useBolt,
UseRing = _useRing,
UseStreak = _useStreak,
UseBlast = _useBlast,
ExVuln = _exVuln,
OffhandId = _offhandId,
PreferredAmmoItemId = _preferredAmmoItemId,
PetDamage = _petDamage,
};
}
/// <summary>Overwrites combat fields (used to merge a VT Default row into the Rynth Default row).</summary>
public void CopyCombatSettingsFrom(MonsterRule? src)
{
if (src == null) return;
// Keep Name: must stay "Default". Use public setters so the grid updates.
Category = src.Category;
MatchExpression = src.MatchExpression;
Priority = src.Priority;
DamageType = src.DamageType;
WeaponId = src.WeaponId;
Fester = src.Fester;
Broadside = src.Broadside;
GravityWell = src.GravityWell;
Imperil = src.Imperil;
Yield = src.Yield;
Vuln = src.Vuln;
UseArc = src.UseArc;
UseBolt = src.UseBolt;
UseRing = src.UseRing;
UseStreak = src.UseStreak;
UseBlast = src.UseBlast;
ExVuln = src.ExVuln;
OffhandId = src.OffhandId;
PreferredAmmoItemId = src.PreferredAmmoItemId;
PetDamage = src.PetDamage;
}
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string? name = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

View file

@ -16,6 +16,18 @@
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" />
<PackageReference Include="Avalonia.Controls.DataGrid" Version="11.2.3" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="9.0.0" />
<!-- Reads UtilityBelt's mob_damage_insights.ldb (same LiteDB version UB writes with). -->
<PackageReference Include="LiteDB" Version="5.0.21" />
<!-- Direct reference overrides Avalonia's transitive 0.20.x (NU1903 / GHSA-xrw6-gwf8-vvr9). -->
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
</ItemGroup>
<ItemGroup>
<!-- Install-location resolver (installer-chosen RynthCore / RynthSuite folders). -->
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- UB damage-insights seed schema, shared with the RynthAi plugin. -->
<Compile Include="..\..\Shared\UbMobSeed.cs" Link="Shared\UbMobSeed.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,318 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using LiteDB;
using RynthCore.CreatureSeed;
// LiteDB ships its own JsonSerializer; the seed is written with System.Text.Json (source-generated).
using StjSerializer = System.Text.Json.JsonSerializer;
namespace RynthCore.MonsterEditor;
/// <summary>
/// Converts UtilityBelt's <c>mob_damage_insights.ldb</c> (LiteDB 5) into the RynthAi
/// damage-type seed (<see cref="UbMobSeedFile"/>). Runs here rather than in the plugin
/// because LiteDB is reflection-heavy and the RynthAi plugin is NativeAOT.
/// <para>
/// UB rows record damage players dealt TO each monster, per damage type. The
/// per-character databases are pushed into the shared server database every 12 hours,
/// so they are mostly a subset of it: for each monster the single row with the most hits
/// wins (summing would double-count).
/// </para>
/// </summary>
internal static class UbMobSeedImport
{
/// <summary>Hits a damage type needs before it is ranked.</summary>
public const int DefaultMinHitsPerType = 20;
private const string DbFileName = "mob_damage_insights.ldb";
private const string WcidCollection = "mob_damage_agg";
private const string MagCollection = "mob_mag_name_agg";
/// <summary>UB damage-type flags (ACE <c>DamageType</c>) mapped to RynthAi element names.
/// Normal (0) and combined flags are not castable choices and are skipped.</summary>
private static readonly Dictionary<string, string> FlagToElement = new()
{
["1"] = "Slash",
["2"] = "Pierce",
["4"] = "Bludgeon",
["8"] = "Cold",
["16"] = "Fire",
["32"] = "Acid",
["64"] = "Lightning",
["1024"] = "Nether",
};
/// <summary>Outcome of an import run.</summary>
public sealed record Result(bool Ok, string Message, UbMobSeedFile? Seed);
/// <summary>UB's per-world folder for InfiniteLeaftide (holds the shared server database).</summary>
public static string DefaultServerFolder => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"Decal Plugins", "UtilityBelt", "InfiniteLeaftide");
/// <summary>Where the plugin reads the seed: <c>&lt;SuiteDir&gt;\RynthAi\CreatureData\ub-mob-seed.json</c>.</summary>
public static string DefaultOutputPath => Path.Combine(
RynthCore.Install.RynthInstallPaths.RynthAiDir, "CreatureData", UbMobSeedFile.FileName);
/// <summary>
/// Lists the shared server database (first) and every per-character database
/// one level below it.
/// </summary>
public static List<string> FindDatabases(string serverFolder)
{
var list = new List<string>();
if (!Directory.Exists(serverFolder)) return list;
string shared = Path.Combine(serverFolder, DbFileName);
if (File.Exists(shared)) list.Add(shared);
foreach (string dir in Directory.GetDirectories(serverFolder).OrderBy(d => d, StringComparer.OrdinalIgnoreCase))
{
string perChar = Path.Combine(dir, DbFileName);
if (File.Exists(perChar)) list.Add(perChar);
}
return list;
}
/// <summary>
/// Reads every database under <paramref name="serverFolder"/>, ranks damage types per
/// monster and writes the seed to <paramref name="outputPath"/> atomically.
/// </summary>
public static Result Run(string serverFolder, string outputPath, int minHitsPerType = DefaultMinHitsPerType)
{
List<string> dbs = FindDatabases(serverFolder);
if (dbs.Count == 0)
return new Result(false, $"No {DbFileName} found in {serverFolder}.", null);
// Best row per wcid / per normalized Mag-Tools name, across all sources.
var bestWcid = new Dictionary<uint, BsonDocument>();
var bestMag = new Dictionary<string, BsonDocument>(StringComparer.OrdinalIgnoreCase);
var used = new List<string>();
var errors = new List<string>();
foreach (string db in dbs)
{
try
{
ReadDatabase(db, bestWcid, bestMag);
used.Add(db);
}
catch (Exception ex)
{
errors.Add($"{Path.GetFileName(Path.GetDirectoryName(db))}: {ex.Message}");
}
}
if (used.Count == 0)
return new Result(false, "Could not read any UB database: " + string.Join("; ", errors), null);
var seed = new UbMobSeedFile
{
GeneratedUtc = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture),
MinHitsPerType = minHitsPerType,
Sources = used,
World = MostCommonWorld(bestWcid.Values),
};
// Live UB rows keyed by wcid.
var wcidNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var (wcid, doc) in bestWcid.OrderBy(kv => kv.Key))
{
string name = Str(doc, "LastSeenName");
if (name.Length > 0) wcidNames.Add(name);
var elements = RankElements(doc, minHitsPerType, hasPeaks: true);
if (elements.Count < 2) continue; // one type alone says nothing about weakness
seed.Entries.Add(new UbMobSeedEntry
{
Wcid = wcid,
Name = name,
Source = "ub",
TotalHits = Num(doc, "TotalHits"),
Elements = elements,
});
}
// Mag-Tools name-only rows, skipped when a wcid row already covers the name.
foreach (var doc in bestMag.Values)
{
string name = Str(doc, "LastSeenDisplayName");
if (name.Length == 0) name = Str(doc, "NormalizedMobName");
if (name.Length == 0 || wcidNames.Contains(name)) continue;
var elements = RankElements(doc, minHitsPerType, hasPeaks: false);
if (elements.Count < 2) continue;
seed.Entries.Add(new UbMobSeedEntry
{
Wcid = 0,
Name = name,
Source = "magtools",
TotalHits = elements.Sum(e => (long)e.Hits),
Elements = elements,
});
}
WriteAtomic(outputPath, StjSerializer.Serialize(seed, EditorJsonContext.Default.UbMobSeedFile));
int ub = seed.Entries.Count(e => e.Source == "ub");
int mag = seed.Entries.Count - ub;
string msg = $"UB seed written: {ub} monster(s) by wcid + {mag} by name (Mag-Tools) from {used.Count} database(s) → {outputPath}";
if (errors.Count > 0) msg += $" Skipped: {string.Join("; ", errors)}";
return new Result(true, msg, seed);
}
/// <summary>
/// Opens a snapshot copy of <paramref name="dbPath"/> (UB may have the live file open)
/// and folds its rows into the best-row maps.
/// </summary>
private static void ReadDatabase(string dbPath, Dictionary<uint, BsonDocument> bestWcid,
Dictionary<string, BsonDocument> bestMag)
{
string tempDir = Path.Combine(Path.GetTempPath(), "RynthUbSeed-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
try
{
string copy = Path.Combine(tempDir, DbFileName);
CopyShared(dbPath, copy);
// LiteDB 5 keeps uncommitted pages in "<name>-log.ldb"; copy it so recent hits are included.
string log = Path.Combine(Path.GetDirectoryName(dbPath)!, Path.GetFileNameWithoutExtension(dbPath) + "-log.ldb");
if (File.Exists(log))
CopyShared(log, Path.Combine(tempDir, Path.GetFileNameWithoutExtension(DbFileName) + "-log.ldb"));
// Writable connection on the private copy so LiteDB can replay the log; the original is untouched.
using var db = new LiteDatabase(new ConnectionString { Filename = copy, Connection = ConnectionType.Direct });
if (db.CollectionExists(WcidCollection))
{
foreach (var doc in db.GetCollection(WcidCollection).FindAll())
{
long wcid = Num(doc, "Wcid");
// wcid 1 is the player weenie (self/PvP lines), not a monster.
if (wcid <= 1 || wcid > uint.MaxValue) continue;
KeepBest(bestWcid, (uint)wcid, doc, Num(doc, "TotalHits"));
}
}
if (db.CollectionExists(MagCollection))
{
foreach (var doc in db.GetCollection(MagCollection).FindAll())
{
string key = Str(doc, "NormalizedMobName");
if (key.Length == 0) continue;
KeepBest(bestMag, key, doc, SumValues(doc, "HitsByType"));
}
}
}
finally
{
try { Directory.Delete(tempDir, recursive: true); } catch { /* temp cleanup is best-effort */ }
}
}
/// <summary>Keeps the row with the most hits per key (sources overlap; see class remarks).</summary>
private static void KeepBest<TKey>(Dictionary<TKey, BsonDocument> map, TKey key, BsonDocument doc, long hits)
where TKey : notnull
{
if (!map.TryGetValue(key, out var existing) || hits > HitsOf(existing))
map[key] = doc;
}
/// <summary>Total hits of a row in either collection's shape.</summary>
private static long HitsOf(BsonDocument doc)
{
long total = Num(doc, "TotalHits");
return total > 0 ? total : SumValues(doc, "HitsByType");
}
/// <summary>
/// Ranks the castable damage types with at least <paramref name="minHits"/> hits.
/// Score blends average damage (vs the best average) with UB's own effectiveness
/// measure, peak hit vs the best peak, when peaks are recorded.
/// </summary>
private static List<UbMobSeedElement> RankElements(BsonDocument doc, int minHits, bool hasPeaks)
{
var hits = Doc(doc, "HitsByType");
var sums = Doc(doc, "SumDamageByType");
var peaks = hasPeaks ? Doc(doc, "MaxDamageByType") : null;
if (hits == null || sums == null) return new List<UbMobSeedElement>();
var list = new List<UbMobSeedElement>();
foreach (string flag in hits.Keys)
{
if (!FlagToElement.TryGetValue(flag, out string? element)) continue;
int n = (int)Math.Min(int.MaxValue, Num(hits, flag));
if (n < minHits || !sums.ContainsKey(flag)) continue;
list.Add(new UbMobSeedElement
{
Element = element,
Hits = n,
AvgDamage = Math.Round(Num(sums, flag) / (double)n, 2),
MaxHit = peaks != null && peaks.ContainsKey(flag) ? Num(peaks, flag) : 0,
});
}
if (list.Count == 0) return list;
double bestAvg = list.Max(e => e.AvgDamage);
long bestPeak = list.Max(e => e.MaxHit);
foreach (var e in list)
{
double avgRatio = bestAvg > 0 ? e.AvgDamage / bestAvg : 0;
double score = bestPeak > 0
? 0.5 * avgRatio + 0.5 * (e.MaxHit / (double)bestPeak)
: avgRatio;
e.Score = Math.Round(score, 4);
}
return list.OrderByDescending(e => e.Score).ThenByDescending(e => e.Hits).ToList();
}
/// <summary>Most frequent <c>WorldName</c> among the rows (empty when none recorded).</summary>
private static string MostCommonWorld(IEnumerable<BsonDocument> rows) =>
rows.Select(r => Str(r, "WorldName"))
.Where(w => w.Length > 0)
.GroupBy(w => w, StringComparer.OrdinalIgnoreCase)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.FirstOrDefault() ?? string.Empty;
/// <summary>Copies a file another process may hold open for writing.</summary>
private static void CopyShared(string source, string dest)
{
using var src = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
using var dst = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None);
src.CopyTo(dst);
}
/// <summary>Writes via a temp file so the plugin never reads a half-written seed.</summary>
private static void WriteAtomic(string path, string contents)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + ".tmp";
File.WriteAllText(tmp, contents);
File.Move(tmp, path, overwrite: true);
}
// ── BSON helpers (schema-tolerant: UB may store numbers as Int32, Int64 or Double) ──
private static BsonDocument? Doc(BsonDocument doc, string field) =>
doc.TryGetValue(field, out var v) && v.IsDocument ? v.AsDocument : null;
private static string Str(BsonDocument doc, string field) =>
doc.TryGetValue(field, out var v) && v.IsString ? v.AsString.Trim() : string.Empty;
private static long Num(BsonDocument doc, string field) =>
doc.TryGetValue(field, out var v) && v.IsNumber ? Convert.ToInt64(v.RawValue, CultureInfo.InvariantCulture) : 0;
private static long SumValues(BsonDocument doc, string field)
{
var d = Doc(doc, field);
if (d == null) return 0;
long total = 0;
foreach (string k in d.Keys) total += Num(d, k);
return total;
}
}

View file

@ -0,0 +1,548 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Data.Sqlite;
namespace RynthCore.MonsterEditor;
/// <summary>
/// Best-effort import of VirindiTank "user" macro profiles (typically <c>.usd</c>) into RynthAi
/// <see cref="MonsterRule"/> rows. Tries, in order: (1) line-oriented SCF <c>MyMonsters</c> (classic
/// uTank2 <c>*.usd</c> in <c>VirindiPlugins\VirindiTank</c>); (2) SQLite; (3) binary scan for
/// vTank-style match expressions.
/// </summary>
public static class VirindiTankUsdImport
{
public sealed class Result
{
public bool Ok { get; set; }
public List<MonsterRule> Rules { get; } = new();
/// <summary>Human-readable summary: counts, method used, warnings.</summary>
public string Message { get; set; } = string.Empty;
}
public static Result TryImport(string filePath)
{
var r = new Result();
if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath))
{
r.Message = "File not found.";
return r;
}
string? allText;
try
{
// VT text profiles are UTF-8; invalid sequences become replacement chars, still OK for SCF.
allText = File.ReadAllText(filePath, Encoding.UTF8);
}
catch (Exception ex)
{
r.Message = $"Read failed: {ex.Message}";
return r;
}
// Primary path: SCF <c>MyMonsters</c> block (see VirindiPlugins\VirindiTank\*.usd, format 8+).
if (VirindiTankUsdTextScfParser.TryParseMyMonsters(allText, r.Rules, out string? scfNote) && r.Rules.Count > 0)
{
r.Ok = true;
r.Message = BuildMessage("MyMonsters (VT SCF / line format)", r.Rules.Count, scfNote);
return r;
}
r.Rules.Clear();
byte[] bytes;
try
{
bytes = File.ReadAllBytes(filePath);
}
catch (Exception ex2)
{
r.Message = $"Read as bytes failed: {ex2.Message}";
return r;
}
if (IsSqliteDatabase(bytes))
{
try
{
if (TryImportFromSqlite(filePath, r.Rules, out int count, out string? sqlNote))
{
r.Ok = true;
r.Message = BuildMessage("SQLite (Virindi uTank settings database)", count, sqlNote);
return r;
}
}
catch (Exception ex)
{
const string pfx = "SQLite read error: ";
string errMsg = pfx + ex.Message;
if (TryImportFromStringScan(bytes, r.Rules, out int exprCount, out string? scanNote))
{
r.Ok = exprCount > 0;
r.Message = BuildMessage("Text scan (after SQLite exception)", exprCount, errMsg + " " + scanNote);
}
else
r.Message = errMsg;
return r;
}
}
string? fallNote;
if (TryImportFromStringScan(bytes, r.Rules, out int n, out fallNote))
{
r.Ok = n > 0;
r.Message = n > 0
? BuildMessage("Expression scan (non-SQLite or unreadable table)", n, fallNote)
: "Could not import: no vTank-style match expressions in file. " + (fallNote ?? string.Empty) +
" If this is a Virindi Tank user profile, ensure the file is a .usd from your VirindiPlugins\\VirindiTank folder (SQLite based).";
}
else
{
r.Message = fallNote ?? "Import failed.";
}
return r;
}
private static string BuildMessage(string method, int count, string? extra)
{
var sb = new StringBuilder();
sb.Append(CultureInfo.InvariantCulture, $"Imported {count} rule(s) using {method}.");
if (!string.IsNullOrWhiteSpace(extra))
{
sb.Append(' ');
sb.Append(extra);
}
return sb.ToString();
}
private static bool IsSqliteDatabase(byte[] header)
{
const string sig = "SQLite format 3\0";
if (header.Length < sig.Length) return false;
for (int i = 0; i < sig.Length; i++)
{
if (header[i] != sig[i]) return false;
}
return true;
}
private static bool TryImportFromSqlite(string filePath, List<MonsterRule> outList, out int count, out string? note)
{
count = 0;
note = null;
outList.Clear();
var csb = new SqliteConnectionStringBuilder
{
DataSource = filePath,
Mode = SqliteOpenMode.ReadOnly,
};
using var con = new SqliteConnection(csb.ToString());
con.Open();
// Discover tables and their columns; pick the best "monster list" table.
var tableScores = new List<(string name, int score)>();
using (var listCmd = con.CreateCommand())
{
listCmd.CommandText = "SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'";
using var r = listCmd.ExecuteReader();
while (r.Read())
{
string t = r.GetString(0);
if (!IsSafeTableName(t)) continue;
int s = ScoreTableIntent(con, t);
if (s > 0) tableScores.Add((t, s));
}
}
if (tableScores.Count == 0)
{
// Unknown schema — try every user table; ReadMonsterTable skips unsuitable ones.
using (var listCmd2 = con.CreateCommand())
{
listCmd2.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'";
using var r2 = listCmd2.ExecuteReader();
while (r2.Read())
{
string t = r2.GetString(0);
if (IsSafeTableName(t)) tableScores.Add((t, 1));
}
}
}
if (tableScores.Count == 0)
{
note = "No user tables in SQLite file.";
return false;
}
tableScores.Sort((a, b) => b.score.CompareTo(a.score));
var best = tableScores[0].name;
if (!ReadMonsterTable(con, best, outList, out int readCount, out string? readErr))
{
note = readErr;
return false;
}
count = readCount;
note = $"Table \"{best}\" (score {tableScores[0].score}). {readErr ?? string.Empty}".Trim();
return count > 0;
}
private static bool IsSafeTableName(string t)
{
foreach (char c in t)
{
if (char.IsLetterOrDigit(c) || c is '_' or '-') continue;
return false;
}
return t.Length is > 0 and < 200;
}
private static int ScoreTableIntent(SqliteConnection con, string table)
{
int s = 0;
if (table.IndexOf("monster", StringComparison.OrdinalIgnoreCase) >= 0) s += 15;
if (table.IndexOf("mob", StringComparison.OrdinalIgnoreCase) >= 0) s += 8;
if (table.IndexOf("attack", StringComparison.OrdinalIgnoreCase) >= 0) s += 4;
using var c = con.CreateCommand();
c.CommandText = $"PRAGMA table_info(\"{table}\")";
using var r = c.ExecuteReader();
while (r.Read())
{
string col = r.GetString(1);
s += ColumnScore(col);
}
return s;
}
private static int ColumnScore(string col)
{
string c = col.ToLowerInvariant();
if (c.Contains("fester", StringComparison.Ordinal) || c is "f") return 4;
if (c.Contains("broad", StringComparison.Ordinal) || c is "b" or "broadside") return 4;
if (c.Contains("gravity", StringComparison.Ordinal) || c is "g") return 2;
if (c.Contains("imperil", StringComparison.Ordinal) || c is "i") return 2;
if (c.Contains("yield", StringComparison.Ordinal) || c is "y") return 2;
if (c.Contains("vuln", StringComparison.Ordinal) && c.Contains("ex", StringComparison.Ordinal) == false) return 2;
if (c is "v") return 2;
if (c.Contains("expression", StringComparison.Ordinal) || c is "matchexpr" or "matchexpression" or "match" or "expr" or "e")
return 8;
if (c is "name" or "mname" or "monstername" or "n")
return 6;
if (c.Contains("damag", StringComparison.Ordinal) || c.Contains("element", StringComparison.Ordinal) || c is "dmg" or "dt")
return 4;
if (c.Contains("priority", StringComparison.Ordinal) || c is "p" or "pri" or "sort" or "idx" or "ordinal")
return 2;
if (c.Contains("weapon", StringComparison.Ordinal) || c.Contains("wand", StringComparison.Ordinal)) return 2;
if (c is "a" or "r" or "s" or "w" or "u") return 1; // A/R/S are ambiguous; low weight
return 0;
}
private static bool ReadMonsterTable(SqliteConnection con, string table, List<MonsterRule> outList, out int count, out string? err)
{
count = 0;
err = null;
// Prefer stable ordering when a dedicated column exists (ROWID is the SQLite insert order for many VT exports).
string orderBy = "ROWID";
if (TableHasColumn(con, table, "Order")) orderBy = "CAST([Order] AS INTEGER)";
else if (TableHasColumn(con, table, "SortIndex")) orderBy = "SortIndex";
else if (TableHasColumn(con, table, "Index")) orderBy = "[Index]";
using var cmd = con.CreateCommand();
cmd.CommandText = $"SELECT * FROM \"{table}\" ORDER BY {orderBy} ASC";
using var r = cmd.ExecuteReader();
int ordName = FindOrdinalByHints(r, "name", "monstername", "mname", "entry", "n", "text0");
int ordExpr = FindOrdinalByHints(r, "matchexpression", "match", "expression", "expr", "e", "ed");
if (ordExpr < 0) ordExpr = FindExpressionColumn(r);
int ordDmg = FindOrdinalByHints(r, "damagetype", "element", "dmg", "de", "delement");
int ordPri = FindOrdinalByHints(r, "priority", "p", "pri", "importance", "ipriority");
int ordEx = FindOrdinalByHints(r, "exvuln", "exvul", "extravuln", "vulnextra");
int ordWep = FindOrdinalByHints(r, "weaponid", "weapon", "windex", "weaponindex");
int ordOff = FindOrdinalByHints(r, "offhand", "offhandid", "shield");
int ordF = FindOrdinalByHints(r, "fester", "f", "b_fester", "bisfester", "festerb");
int ordB = FindOrdinalByHints(r, "broadside", "b", "broad", "broadb");
int ordG = FindOrdinalByHints(r, "gravity", "g", "grav");
int ordI = FindOrdinalByHints(r, "imperil", "i", "imprl");
int ordY = FindOrdinalByHints(r, "yield", "y", "yld");
int ordV = FindOrdinalByHints(r, "vulnerability", "v", "vuln", "b_vuln", "bisfestervuln", "bisfesterv"); // be careful: skip ex vuln
// VT often: UseArc, UseRing, Streak, Bolt
int ordA = FindOrdinalByHints(r, "usearc", "arc", "a");
int ordR = FindOrdinalByHints(r, "usering", "ring", "r", "b_ring");
int ordS = FindOrdinalByHints(r, "streak", "s", "usestreak", "b_streak", "bisfeststreak", "bisfstreak", "bisfstreak2");
int ordBl= FindOrdinalByHints(r, "usebolt", "bolt", "bl", "b_bolt", "bisfstreakbolt", "bisfstreakbol", "bisfb");
if (ordName < 0 && ordExpr < 0)
{
err = "Table has no recognizable name/expression column.";
return false;
}
while (r.Read())
{
var m = new MonsterRule();
string? name = GetStr(r, ordName);
string? expr = GetStr(r, ordExpr);
if (!string.IsNullOrWhiteSpace(name) && name.Trim().Equals("default", StringComparison.OrdinalIgnoreCase))
{
m.Name = "Default";
m.MatchExpression = string.Empty;
}
else
{
m.Name = name?.Trim() ?? string.Empty;
m.MatchExpression = expr?.Trim() ?? string.Empty;
}
m.Priority = 1;
if (ordPri >= 0) m.Priority = Math.Clamp(ToInt32(r, ordPri, 1), -100, 10000);
m.DamageType = string.IsNullOrEmpty(GetStr(r, ordDmg)) ? "Auto" : MapDamageType(GetStr(r, ordDmg) ?? "Auto");
m.ExVuln = string.IsNullOrEmpty(GetStr(r, ordEx)) ? "None" : (GetStr(r, ordEx) ?? "None");
m.WeaponId = ordWep >= 0 ? Math.Max(0, ToInt32(r, ordWep, 0)) : 0;
m.OffhandId = ordOff >= 0 ? Math.Max(0, ToInt32(r, ordOff, 0)) : 0;
m.Fester = GetBoolish(r, ordF);
m.Broadside = GetBoolish(r, ordB);
m.GravityWell= GetBoolish(r, ordG);
m.Imperil = GetBoolish(r, ordI);
m.Yield = GetBoolish(r, ordY);
m.Vuln = GetBoolish(r, ordV);
m.UseArc = GetBoolish(r, ordA);
m.UseRing = GetBoolish(r, ordR);
m.UseStreak = GetBoolish(r, ordS);
m.UseBolt = ordBl >= 0 ? GetBoolish(r, ordBl) : m.UseBolt;
// If row is empty, skip
if (string.IsNullOrEmpty(m.Name) && string.IsNullOrEmpty(m.MatchExpression))
{
bool anyToggle = m.Fester || m.Broadside || m.GravityWell || m.Imperil || m.Yield || m.Vuln
|| m.UseArc || m.UseRing || m.UseStreak;
if (!anyToggle) continue;
}
if (m.Name.Length == 0 && m.MatchExpression.Length == 0)
continue;
outList.Add(m);
}
count = outList.Count;
if (count == 0) err = "No mappable rows.";
return true;
}
private static bool TableHasColumn(SqliteConnection con, string table, string col)
{
using var c = con.CreateCommand();
c.CommandText = $"PRAGMA table_info(\"{table}\")";
using var r = c.ExecuteReader();
while (r.Read())
{
if (r.GetString(1).Equals(col, StringComparison.OrdinalIgnoreCase)) return true;
}
return false;
}
/// <summary>Column whose name is exactly <paramref name="hints"/> (lowercase) or a short exact code (P, V, etc.).</summary>
private static int FindOrdinalByHints(SqliteDataReader r, params string[] hints)
{
for (int i = 0; i < r.FieldCount; i++)
{
string n = r.GetName(i);
string nl = n.ToLowerInvariant();
foreach (string h in hints)
{
if (h.Equals("p", StringComparison.Ordinal) && nl is "p" or "ipriority")
return i;
if (h.Equals("v", StringComparison.Ordinal) && (nl is "v" or "b_v" or "b_vuln" or "vuln")
&& !nl.Contains("exvul", StringComparison.Ordinal) && !nl.Contains("ex_vul", StringComparison.Ordinal))
return i;
if (nl == h.ToLowerInvariant()) return i;
}
}
return -1;
}
private static int FindExpressionColumn(SqliteDataReader r)
{
for (int i = 0; i < r.FieldCount; i++)
{
string nl = r.GetName(i).ToLowerInvariant();
if (nl.Contains("matchexpr", StringComparison.Ordinal)
|| (nl.Contains("match", StringComparison.Ordinal) && nl.Contains("exp", StringComparison.Ordinal)))
return i;
}
return -1;
}
private static string? GetStr(SqliteDataReader r, int ord) => ord < 0 || r.IsDBNull(ord) ? null : r.GetValue(ord)?.ToString();
private static int ToInt32(SqliteDataReader r, int ord, int dft)
{
try
{
if (r.IsDBNull(ord)) return dft;
return Convert.ToInt32(r.GetValue(ord), CultureInfo.InvariantCulture);
}
catch
{
if (int.TryParse(r.GetValue(ord)?.ToString(), out int p)) return p;
return dft;
}
}
private static bool GetBoolish(SqliteDataReader r, int ord)
{
if (ord < 0 || r.IsDBNull(ord)) return false;
var v = r.GetValue(ord);
if (v is long l) return l != 0;
if (v is int i) return i != 0;
if (v is bool b) return b;
string? s = v?.ToString()?.Trim();
if (string.IsNullOrEmpty(s)) return false;
if (s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1" || s.Equals("yes", StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
private static string MapDamageType(string raw)
{
string t = raw.Trim();
if (t.Length == 0) return "Auto";
if (t.Contains('<', StringComparison.Ordinal) && t.Contains('>', StringComparison.Ordinal)) // <auto>
{
if (t.Contains("auto", StringComparison.OrdinalIgnoreCase)) return "Auto";
}
// VT uses words like "Slash" — normalize first letter
if (t.Equals("Auto", StringComparison.OrdinalIgnoreCase)) return "Auto";
foreach (string s in new[] { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" })
{
if (s.Equals(t, StringComparison.OrdinalIgnoreCase)) return s;
}
// Unknown — keep for display, Rynth will treat oddly if not in list; still better than Data loss
return t;
}
// ── Binary / UTF-16 / UTF-8 string scan: expression fallbacks ────────────
private static bool TryImportFromStringScan(byte[] data, List<MonsterRule> outList, out int count, out string? note)
{
count = 0;
note = null;
outList.Clear();
var strs = new HashSet<string>(StringComparer.Ordinal);
foreach (string s in ExtractAllStrings(data, minLen: 8, maxLen: 480))
{
if (LooksLikeVtExpression(s))
strs.Add(s.Trim());
}
if (strs.Count == 0)
{
count = 0;
return false;
}
// Prefer longer expressions (often more specific)
foreach (string s in strs.OrderByDescending(x => x.Length))
{
outList.Add(new MonsterRule
{
Name = string.Empty,
MatchExpression = s,
DamageType = "Auto",
UseBolt = true,
});
}
count = outList.Count;
note = "Binary mode only recovers vTank **match expression** rows (name-only entries must be added by hand, or re-export from a SQLite .usd).";
return true;
}
/// <summary>Pull printable ASCII/UTF-8 (single-byte) and UTF-16-LE "wide string" runs from a blob.</summary>
private static IEnumerable<string> ExtractAllStrings(byte[] data, int minLen, int maxLen)
{
// 7-bit runs (covers most human-readable .usd contents outside SQLite BLOBs)
int start = -1;
for (int i = 0; i < data.Length; i++)
{
byte b = data[i];
if ((b >= 0x20 && b <= 0x7E) || b == 0x09) // printables + tab
{
if (start < 0) start = i;
}
else
{
if (start >= 0)
{
int len = i - start;
if (len >= minLen)
yield return Encoding.UTF8.GetString(data, start, len > maxLen ? maxLen : len);
}
start = -1;
}
}
if (start >= 0)
{
int len2 = data.Length - start;
if (len2 >= minLen)
yield return Encoding.UTF8.GetString(data, start, len2 > maxLen ? maxLen : len2);
}
// UTF-16-LE ASCII: [char][0][char][0] (common in Windows/.NET-originated data)
for (int i = 0; i < data.Length - 1;)
{
if (data[i + 1] != 0) { i++; continue; }
if (data[i] < 0x20) { i++; continue; }
{
char ch = (char)data[i];
if (!char.IsLetter(ch) && !char.IsDigit(ch) && ch is not ( '<' or '=' or '(' or '!' or 'f' or 't')) { i++; continue; }
}
int p = i;
var sb = new StringBuilder();
while (p + 1 < data.Length)
{
if (data[p + 1] != 0) break;
int c = data[p];
if (c < 0x20) break;
if (c > 0x7E) break;
sb.Append((char)c);
p += 2;
if (sb.Length >= maxLen) break;
}
if (sb.Length >= minLen) yield return sb.ToString();
if (p > i) { i = p; }
else { i++; }
}
}
private static bool LooksLikeVtExpression(string s)
{
s = s.Trim();
if (s.Length < 6) return false;
if (s.Equals("DEFAULT", StringComparison.OrdinalIgnoreCase)) return false;
if (s.Contains("SQLite format", StringComparison.Ordinal)) return false;
if (s.Contains("&&", StringComparison.Ordinal) || s.Contains("||", StringComparison.Ordinal)) return true;
if (s.Contains("==", StringComparison.Ordinal) && (
s.Contains("range", StringComparison.Ordinal)
|| s.Contains("species", StringComparison.Ordinal)
|| s.Contains("typeid", StringComparison.Ordinal)
|| s.Contains("name", StringComparison.Ordinal)
|| s.Contains("maxhp", StringComparison.Ordinal)
|| s.Contains("hasshield", StringComparison.Ordinal)
|| s.Contains("metastate", StringComparison.Ordinal)))
return true;
// e.g. range>5 && !foo
if (Regex.IsMatch(s, @"(?i)range\s*[<>=!]+")) return true;
return false;
}
}

View file

@ -0,0 +1,189 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace RynthCore.MonsterEditor;
// In-game VirindiTank import uses the same MyMonsters layout in Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankUsdMyMonstersScfParser.cs — keep in sync.
/// <summary>
/// Line-oriented uTank2 SCF <c>.usd</c> (e.g. format 8) — the common format under
/// <c>C:\Games\VirindiPlugins\VirindiTank\*.usd</c>, with a <c>MyMonsters</c> table using <c>s</c>/<c>i</c>/<c>b</c> value lines.
/// Reference: <c>--Silentkelpie_InfiniteLeaftide.usd</c> (MyMonsters 21 columns, 110+ rows in sample file).
/// </summary>
public static class VirindiTankUsdTextScfParser
{
public static bool TryParseMyMonsters(string allText, List<MonsterRule> outList, out string? note)
{
outList.Clear();
note = null;
if (string.IsNullOrWhiteSpace(allText) || allText.IndexOf("MyMonsters", StringComparison.Ordinal) < 0)
return false;
string[] L = allText
.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None)
.Select(s => s.Trim())
.ToArray();
if (L.Length < 8) { note = "File too short."; return false; }
int idx = 0;
for (; idx < L.Length; idx++) if (L[idx] == "MyMonsters") break;
if (idx >= L.Length) { note = "MyMonsters not found."; return false; }
idx++;
if (!int.TryParse(L[idx], out int colCount) || colCount < 1) { note = "MyMonsters: bad column count."; return false; }
idx += 1 + colCount * 2; // names + y/n
if (idx >= L.Length) { note = "MyMonsters: truncated after header."; return false; }
if (!int.TryParse(L[idx], out int rowCount) || rowCount < 0) { note = "MyMonsters: bad row count."; return false; }
idx++;
// Empty table: treat as "no data" so the importer can fall back to SQLite / byte scan.
if (rowCount == 0) { note = "MyMonsters has no rows."; return false; }
if (colCount < 4 + 3) { note = "MyMonsters: column count too small."; return false; }
int nBool = colCount - 4 - 3;
for (int r = 0; r < rowCount; r++)
{
if (idx + 1 >= L.Length) { note = $"No data for row {r + 1} (early EOF)."; return outList.Count > 0; }
if (!T(L, "s", ref idx)) { note = RowErr(r, "s"); return outList.Count > 0; }
if (!ValStr(L, ref idx, out string raw)) { note = RowErr(r, "name"); return outList.Count > 0; }
if (!T(L, "i", ref idx)) { note = RowErr(r, "i ap"); return outList.Count > 0; }
if (!ValInt(L, ref idx, out int ap, out int err) || err != 0) { note = RowErr(r, "ap int"); return outList.Count > 0; }
if (!T(L, "i", ref idx)) { note = RowErr(r, "i dt"); return outList.Count > 0; }
if (!ValInt(L, ref idx, out int vtDmg, out err) || err != 0) { note = RowErr(r, "dt int"); return outList.Count > 0; }
if (!T(L, "i", ref idx)) { note = RowErr(r, "i wep"); return outList.Count > 0; }
if (!ValInt(L, ref idx, out int wep, out err) || err != 0) { note = RowErr(r, "wep int"); return outList.Count > 0; }
if (nBool < 14) { note = "Expected at least 14 bool columns in mob row."; return outList.Count > 0; }
if (nBool < 1) { note = "nBool<1."; return false; }
var b = new bool[nBool];
for (int k = 0; k < nBool; k++)
{
if (!T(L, "b", ref idx) || !ValBool(L, ref idx, out b[k])) { note = RowErr(r, $"b{k}"); return outList.Count > 0; }
}
if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int sev, out err) || err != 0) { note = RowErr(r, "sec vuln int"); return outList.Count > 0; }
if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int ofh, out err) || err != 0) { note = RowErr(r, "offh int"); return outList.Count > 0; }
if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int pet, out err) || err != 0) { note = RowErr(r, "pet int"); return outList.Count > 0; }
outList.Add(MakeRule(raw, ap, vtDmg, wep, b, sev, ofh, pet));
}
if (outList.Count == 0) { note = "No rows were parsed from MyMonsters."; return false; }
return true;
}
private static string RowErr(int r, string what) => $"MyMonsters row {r + 1} ({what}).";
private static bool T(string[] L, string t, ref int i)
{
if (i >= L.Length || L[i] != t) return false;
i++;
return true;
}
private static bool ValStr(string[] L, ref int i, out string s)
{
s = "";
if (i >= L.Length) return false;
s = L[i++]; return true;
}
private static bool ValInt(string[] L, ref int i, out int v, out int err)
{
err = 0;
v = 0;
if (i >= L.Length) { err = 1; return false; }
if (!int.TryParse(L[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out v) &&
!int.TryParse(L[i], out v))
{
err = 1; return false;
}
i++;
return true;
}
private static bool ValBool(string[] L, ref int i, out bool b)
{
b = false;
if (i >= L.Length) return false;
string t = L[i++];
if (string.Equals(t, "True", StringComparison.OrdinalIgnoreCase)) { b = true; return true; }
if (string.Equals(t, "False", StringComparison.OrdinalIgnoreCase)) { b = false; return true; }
return false;
}
/// b[0] Imperil, [1] Vuln, [2] Yield, [3] GravityW, [4] Attack, [5] Ring, [6] Broad, [7] Fester, [8..12] WC/FC/Cp/DC/Cs, [13] Streak.
private static MonsterRule MakeRule(
string raw, int ap, int vtDmg, int wep, bool[] b, int sev, int ofh, int pet)
{
string n = Nm(raw);
if (b.Length < 14) b = Pad(b, 14);
bool i = b[0], v = b[1], y = b[2], gW = b[3];
bool useBolt = b[4], useRing = b[5], broad = b[6], fest = b[7];
bool strk = b[13];
return new MonsterRule
{
Name = n,
Priority = ap,
DamageType = MapDmg(vtDmg),
WeaponId = WepId(wep),
Imperil = i,
Vuln = v,
Yield = y,
GravityWell = gW,
UseBolt = useBolt,
UseRing = useRing,
Broadside = broad,
Fester = fest,
UseStreak = strk,
// VT extra curses (b[8]..b[12]) — no Rynth match
ExVuln = "None", // sev = spell/element code; Rynth list is by name; leave None; user can tune
OffhandId = WepId(ofh),
PetDamage = MapPet(pet, sev),
};
}
private static bool[] Pad(bool[] b, int min)
{
if (b.Length >= min) return b;
var r = new bool[min];
for (int i = 0; i < b.Length; i++) r[i] = b[i];
return r;
}
private static string Nm(string s)
{
s = s.Trim();
if (s.Length > 1 && s[0] == '<' && s[^1] == '>')
{
string t = s.Substring(1, s.Length - 2);
if (t.Equals("DEFAULT", StringComparison.OrdinalIgnoreCase)) return "Default";
return t;
}
return s;
}
private static int WepId(int w) => w; // Rynth keeps AC-style ids (often large negatives); editor shows &lt;ID:…&gt; if not in list
/// <summary>uTank2 damage int — 8 and negatives typically mean "Auto" in exports.</summary>
private static string MapDmg(int c) => c switch
{
8 => "Auto",
1 => "Slash", 2 => "Pierce", 3 => "Bludgeon", 4 => "Acid", 5 => "Fire", 6 => "Cold", 7 => "Lightning", 0 => "Nether",
_ => "Auto",
};
private static string MapPet(int pdt, int _ /* secondary vuln int from VT; ExVuln string not derived */)
{
if (pdt is 0 or 101) return "PAuto";
if (pdt is >= 1 and <= 8)
{
// Narrowed 1..8: pet damage type codes in VT SCF.
return pdt switch
{
1 => "Slash", 2 => "Pierce", 3 => "Bludgeon", 4 => "Fire", 5 => "Cold", 6 => "Lightning", 7 => "Acid", 8 => "Nether",
_ => "PAuto",
};
}
return "PAuto";
}
}

View file

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

View file

@ -0,0 +1,12 @@
// The linked geometry sources trace through the plugin's RynthLog (Diagnostics/RynthLog.cs),
// which needs the whole plugin (its JSON context, the host). Offline there is nothing to trace
// to: this stands in for the one call they make.
namespace RynthCore.Plugin.RynthAi;
internal enum LogCat { Raycast }
internal static class RynthLog
{
public static void Trace(LogCat cat, string message) { }
}

View file

@ -18,6 +18,15 @@ namespace RynthCore.PatrolProof;
// hz a,b,... add cells (low 16 bits hex, or full ids)
// compare for each start, the summary with none / surface / file+hz / all hazards
// summary summary lines only tiny only waypoints in rooms of <= 5 cells
// The patrol settings (Settings > Navigation > Dungeon Patrol; DungeonPatrolOptions), default
// as in the game:
// coverage whole|loops|all spurs N (0-30: dead-end areas of <= N cells skipped) floors on|off walls M (0.5-2) lookin M (3-40)
// floors off keeps the surface cells out of the hazards unless hzfile/hz also list them, as
// BuildDunPatrol does with the cells in DungeonHazards/<lb>.txt.
// modes for each start, one line per setting variant (coverage modes, dead-end limits,
// floors off, wall distances, look-in sizes): patrol cells, waypoints, lap length
// pockets for each start, the dead-end areas off the reachable cells (largest first, the
// ones hanging off the trunk), their rooms and the smaller areas inside them
// The start cell is handled as BuildDunPatrol does: a start in a hazard moves to NearestSafeCell.
internal static class Waypoints
{
@ -26,7 +35,9 @@ internal static class Waypoints
uint lb = 0x6146;
string acDir = @"C:\Turbine\Asheron's Call";
var starts = new List<uint>();
bool surface = false, summaryOnly = false, tinyOnly = false, compare = false;
bool surface = false, summaryOnly = false, tinyOnly = false, compare = false, modes = false, pocketList = false;
var opt = DungeonPatrolOptions.Default;
var inv = CultureInfo.InvariantCulture;
var extra = new HashSet<uint>();
var fileCells = new HashSet<uint>();
for (int i = 0; i < args.Length; i++)
@ -37,6 +48,14 @@ internal static class Waypoints
else if (a == "summary") summaryOnly = true;
else if (a == "tiny") tinyOnly = true;
else if (a == "compare") compare = true;
else if (a == "modes") modes = true;
else if (a == "pockets") pocketList = true;
else if (a == "coverage" && i + 1 < args.Length)
opt = opt with { Coverage = args[++i] switch { "loops" => PatrolCoverage.LoopsOnly, "all" or "everything" => PatrolCoverage.Everything, _ => PatrolCoverage.WholeDungeon } };
else if (a == "spurs" && i + 1 < args.Length) opt = opt with { MaxDeadEndCells = int.Parse(args[++i], inv) };
else if (a == "floors" && i + 1 < args.Length) opt = opt with { AvoidHazardFloors = args[++i] != "off" };
else if (a == "walls" && i + 1 < args.Length) opt = opt with { WallClearance = double.Parse(args[++i], inv) };
else if (a == "lookin" && i + 1 < args.Length) opt = opt with { LookInRoomMeters = double.Parse(args[++i], inv) };
else if (a == "hzfile" && i + 1 < args.Length)
{
foreach (string raw in File.ReadAllLines(args[++i]))
@ -65,6 +84,10 @@ internal static class Waypoints
if (fileCells.Count > 0) Console.WriteLine($" hzfile cells: {Ids(fileCells)}");
if (extra.Count > 0) Console.WriteLine($" hz cells: {Ids(extra)}");
if (starts.Count == 0) starts.Add(graph.Keys.Min());
opt = opt.Clamped();
Console.WriteLine("Patrol settings: " + opt.Describe());
if (pocketList) return Pockets(graph, geo, starts, surface ? surfaceCells : new HashSet<uint>(), new HashSet<uint>(fileCells.Concat(extra)), opt);
if (modes) return Modes(graph, geo, starts, surface ? surfaceCells : new HashSet<uint>(), new HashSet<uint>(fileCells.Concat(extra)), opt);
var sets = new List<(string Name, HashSet<uint> Cells)>();
var given = new HashSet<uint>(fileCells.Concat(extra));
@ -83,9 +106,10 @@ internal static class Waypoints
}
foreach (uint s0 in starts)
foreach (var (name, cells) in sets)
foreach (var (name, cells0) in sets)
{
uint start = s0;
var cells = new HashSet<uint>(DungeonPathfinder.PatrolHazards(cells0, surfaceCells, given, opt) ?? cells0);
IReadOnlySet<uint> hazards = cells.Count > 0 ? cells : null;
if (hazards != null && hazards.Contains(start))
{
@ -95,7 +119,7 @@ internal static class Waypoints
var log = new Dictionary<NavPoint, DungeonPathfinder.PatrolPointInfo>(ReferenceEqualityComparer.Instance);
DungeonPathfinder.PointLog = log;
NavRouteParser route;
try { route = DungeonPathfinder.BuildPatrolRoute(graph, start, hazards, geo); }
try { route = DungeonPathfinder.BuildPatrolRoute(graph, start, hazards, geo, opt); }
finally { DungeonPathfinder.PointLog = null; }
var lines = DungeonPathfinder.DescribePatrol(route, graph, geo, hazards, log);
Console.WriteLine();
@ -112,6 +136,154 @@ internal static class Waypoints
return 0;
}
// One line per setting variant: what each Settings > Dungeon Patrol choice does to the patrol.
// cells patrol cells (GetMainRouteNodes) rooms<=5 small rooms (<= 5 cells) entered
// off-loop of those, rooms with no cell on the loops (the hazard-aware 2-core): dead-end rooms
// skipped reachable rooms left out whole, and the biggest of them (cells, metres across)
private static int Modes(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, List<uint> starts,
HashSet<uint> surfaceCells, HashSet<uint> given, DungeonPatrolOptions baseOpt)
{
var d = baseOpt;
var variants = new List<(string Name, DungeonPatrolOptions O)>
{
($"whole dungeon, dead ends {d.MaxDeadEndCells} (given)", d),
};
foreach (int n in new[] { 0, 3, 6, 8, 10, 12, 15, 20 })
if (n != d.MaxDeadEndCells) variants.Add(($"whole dungeon, dead ends {n}", d with { MaxDeadEndCells = n }));
variants.Add(("loops only", d with { Coverage = PatrolCoverage.LoopsOnly }));
variants.Add(("everything", d with { Coverage = PatrolCoverage.Everything }));
variants.Add(("lava/acid floors walked", d with { AvoidHazardFloors = false }));
variants.Add(("walls 0.5 m", d with { WallClearance = 0.5 }));
variants.Add(("look into rooms >= 20 m", d with { LookInRoomMeters = 20 }));
var all = new HashSet<uint>(surfaceCells.Concat(given));
foreach (uint s0 in starts)
{
Console.WriteLine();
Console.WriteLine($"== start {s0:X8}, hazards {all.Count} ({surfaceCells.Count} floor, {given.Count} given)");
Console.WriteLine(" setting | hazards | cells | waypoints (doorway) | lap yd | look-ins | rooms<=5 (off-loop) | skipped rooms (biggest)");
foreach (var (name, o) in variants)
{
var hz = DungeonPathfinder.PatrolHazards(all, surfaceCells, given, o);
IReadOnlySet<uint> hazards = hz is { Count: > 0 } ? hz : null;
uint start = s0;
if (hazards != null && hazards.Contains(start))
{
uint safe = DungeonPathfinder.NearestSafeCell(graph, start, hazards);
if (safe != 0) start = safe;
}
var rooms = DungeonPathfinder.BuildRooms(graph, geo, hazards);
var cellSet = DungeonPathfinder.GetMainRouteNodes(graph, start, hazards, o, geo.DoorwayCount > 0 ? rooms : null);
var everything = DungeonPathfinder.GetMainRouteNodes(graph, start, hazards, o with { Coverage = PatrolCoverage.Everything });
var loops = DungeonPathfinder.GetMainRouteNodes(graph, start, hazards, o with { Coverage = PatrolCoverage.LoopsOnly });
var log = new Dictionary<NavPoint, DungeonPathfinder.PatrolPointInfo>(ReferenceEqualityComparer.Instance);
DungeonPathfinder.PointLog = log;
NavRouteParser route;
try { route = DungeonPathfinder.BuildPatrolRoute(graph, start, hazards, geo, o); }
finally { DungeonPathfinder.PointLog = null; }
int n = route.Points.Count, door = route.Points.Count(p => p.Doorway);
double len = 0;
for (int i = 0; i < n; i++)
{
var a = route.Points[i]; var b = route.Points[(i + 1) % n];
len += Math.Sqrt((a.NS - b.NS) * (a.NS - b.NS) + (a.EW - b.EW) * (a.EW - b.EW)) * 240.0;
}
int lookIns = log.Values.Where(v => v.Why.StartsWith("look-in", StringComparison.Ordinal)).Select(v => v.Room).Distinct().Count();
var entered = Entered(route, graph, geo, rooms, log);
var small = entered.Where(r => rooms.Cells[r].Count <= 5).ToList();
int offLoop = small.Count(r => !rooms.Cells[r].Any(loops.Contains));
var skipped = Enumerable.Range(0, rooms.Cells.Count)
.Where(r => rooms.Cells[r].Any(everything.Contains) && !rooms.Cells[r].Any(cellSet.Contains)).ToList();
string biggest = skipped.Count == 0 ? "-" : skipped.Select(r => (Cells: rooms.Cells[r].Count, M: Across(graph, rooms.Cells[r])))
.OrderByDescending(t => t.Cells).ThenByDescending(t => t.M).Select(t => $"{t.Cells}c {t.M:F0}m").First();
Console.WriteLine($" {name,-34} | {hazards?.Count ?? 0,7} | {cellSet.Count,5} | {n,9} ({door,5}) | {len,6:F0} | {lookIns,8} | {small.Count,8} ({offLoop,7}) | {skipped.Count,5} ({biggest})");
}
}
return 0;
}
// The dead-end areas (DungeonPathfinder.FindDeadEndPockets) of the reachable rooms, as the
// patrol finds them: those hanging off the loops (rooms with a 2-core cell), largest first, with
// their rooms and the sizes of the pockets nested in them; then how many pockets of each size.
private static int Pockets(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, List<uint> starts,
HashSet<uint> surfaceCells, HashSet<uint> given, DungeonPatrolOptions opt)
{
var all = new HashSet<uint>(surfaceCells.Concat(given));
foreach (uint s0 in starts)
{
var hz = DungeonPathfinder.PatrolHazards(all, surfaceCells, given, opt);
IReadOnlySet<uint> hazards = hz is { Count: > 0 } ? hz : null;
uint start = s0;
if (hazards != null && hazards.Contains(start))
{
uint safe = DungeonPathfinder.NearestSafeCell(graph, start, hazards);
if (safe != 0) start = safe;
}
var reach = DungeonPathfinder.GetMainRouteNodes(graph, start, hazards, opt with { Coverage = PatrolCoverage.Everything });
var rooms = DungeonPathfinder.BuildRooms(graph, geo, hazards);
var (adj, weight) = DungeonPathfinder.RoomAdjacency(graph, reach, rooms);
// Weighted as the patrol weighs them: a big room (look-in size) as 1000.
bool Big(uint r) => DungeonPathfinder.RoomSpreadMeters(graph, rooms.Cells[(int)r]) >= opt.LookInRoomMeters;
var p = DungeonPathfinder.FindDeadEndPockets(adj, r => Big(r) ? 1000 : weight[r], (uint)rooms.RoomOf[start]);
// The trunk: the loops (2-core). Pockets off it are the branches; a pocket the start is
// in turns the rest of the dungeon into one big pocket, so the trunk isn't "no pocket".
var core = DungeonPathfinder.GetMainRouteNodes(graph, start, hazards, opt with { Coverage = PatrolCoverage.LoopsOnly })
.Select(c => (uint)rooms.RoomOf[c]).ToHashSet();
var top = p.All.Where(q => core.Contains(q.Attach) && !core.Contains(q.Root)).OrderByDescending(q => q.Size).ToList();
string Room(uint r) => (rooms.Cells[(int)r][0] & 0xFFFF).ToString("X4");
Console.WriteLine();
Console.WriteLine($"== start {s0:X8}: {reach.Count} reachable cells in {adj.Count} rooms, {core.Count} rooms on the loops, "
+ $"{p.All.Count} pockets ({top.Count} off the loops)");
foreach (var q in top)
{
var inside = p.NodesOf(q).ToHashSet();
var rs = inside.Select(r => Big(r) ? $"{weight[r]}big" : $"{weight[r]}").GroupBy(n => n).OrderByDescending(g => g.Key.Length).ThenByDescending(g => g.Key)
.Select(g => g.Count() == 1 ? g.Key : $"{g.Key}x{g.Count()}");
var nested = p.All.Where(n => n.Root != q.Root && inside.Contains(n.Root)).Select(n => n.Size).OrderByDescending(n => n).Take(12);
Console.WriteLine($" off room {Room(q.Attach)} at {Room(q.Root)}: {q.Size,3} cells, rooms [{string.Join(",", rs)}], nested [{string.Join(",", nested)}]");
}
var bins = new[] { 1, 2, 3, 5, 8, 10, 12, 15, 20, 30, 50, int.MaxValue };
int lo = 1;
var hist = new List<string>();
foreach (int b in bins)
{
int c = p.All.Count(q => q.Size >= lo && q.Size <= b);
hist.Add($"{lo}{(b == lo ? "" : b == int.MaxValue ? "+" : "-" + b)}: {c}");
lo = b + 1;
}
Console.WriteLine(" all pockets by size: " + string.Join(", ", hist));
}
return 0;
}
// Rooms with at least one waypoint not laid by a look-in.
private static HashSet<int> Entered(NavRouteParser route, Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo,
DungeonRooms rooms, Dictionary<NavPoint, DungeonPathfinder.PatrolPointInfo> log)
{
var entered = new HashSet<int>();
foreach (var p in route.Points)
{
log.TryGetValue(p, out var info);
uint cell = info != null && info.Cell != 0 ? info.Cell : DungeonPathfinder.CellAt(graph, geo, p);
if (!rooms.RoomOf.TryGetValue(cell, out int r)) continue;
if (info != null && info.Why.StartsWith("look-in", StringComparison.Ordinal) && info.Room == r) continue;
entered.Add(r);
}
return entered;
}
// Metres across a room's cell centres.
private static double Across(Dictionary<uint, DungeonNavNode> graph, List<uint> cells)
{
double best = 0;
foreach (uint a in cells)
foreach (uint b in cells)
{
var x = graph[a]; var y = graph[b];
best = Math.Max(best, Math.Sqrt((x.NS - y.NS) * (x.NS - y.NS) + (x.EW - y.EW) * (x.EW - y.EW)) * 240.0);
}
return best;
}
// "room N (k cells)" with k <= 5.
private static bool IsTiny(string line)
{

View file

@ -85,11 +85,19 @@ internal static unsafe class FakeHost
public static readonly List<bool> AutoRunCalls = new();
public static bool AutoRun;
public static int Jumps;
/// <summary>Runs inside CastSpell, after the cast is recorded (a UseDone that lands during the send).</summary>
public static Action? AfterCastSpell;
/// <summary>Opt-in: wires TapJump (the keyboard jump, 0xF61B); calls land in <see cref="TapJumps"/>.</summary>
public static bool TapJumpCalls;
public static int TapJumps;
/// <summary>TapJump returns 0 (the client refused the jump); the call still counts in TapJumps.</summary>
public static bool TapJumpRefuse;
public static int Turns;
public static readonly List<(uint Target, int SpellId)> Casts = new();
/// <summary>True: CastSpell returns false (the client refused it; nothing is recorded in <see cref="Casts"/>).</summary>
public static bool CastRefused;
/// <summary>CastSpell calls refused while <see cref="CastRefused"/> was set.</summary>
public static int CastsRefused;
/// <summary>Opt-in: wires GiveObjectTo (AC's give action); every call lands in <see cref="Gives"/>.</summary>
public static bool GiveCalls;
/// <summary>Every GiveObjectTo (item, target, amount; 0 = the whole object), in order.</summary>
@ -111,14 +119,25 @@ internal static unsafe class FakeHost
/// <summary>Every UseObject (a wield, a use) and RequestId (an identify), in order.</summary>
public static readonly List<uint> Uses = new();
public static readonly List<uint> IdRequests = new();
/// <summary>Opt-in (set before Create): QueryHealth (counted in <see cref="HealthQueries"/>) and GetLastIdTime (answering <see cref="IdTimes"/>, 0 = never).</summary>
public static bool TargetCalls;
public static readonly List<uint> HealthQueries = new();
public static readonly Dictionary<uint, long> IdTimes = new();
/// <summary>Every MoveItemInternal (an item into a pack), in order (opt-in with <see cref="WeaponCalls"/>).</summary>
public static readonly List<(uint Id, uint Pack, int Amount)> Moves = new();
/// <summary>Objects the fake says have appraisal data (HasAppraisalData).</summary>
public static readonly HashSet<uint> Appraised = new();
/// <summary>False = RequestId refuses (as the engine does around a teleport or a death): returns 0
/// and is counted in <see cref="RefusedIdRequests"/>, not in <see cref="IdRequests"/>.</summary>
public static bool RequestIdAccepts = true;
public static int RefusedIdRequests;
/// <summary>Opt-in (set before Create): UseObject, RequestId, HasAppraisalData and
/// GetCurrentCombatMode (answering <see cref="CombatModeValue"/>). Tests written without
/// them keep seeing those calls as absent.</summary>
public static bool WeaponCalls;
/// <summary>Opt-in GetContainerContents answering from <see cref="Containers"/> (item -> container),
/// in insertion order. Off by default: see the class note.</summary>
public static bool ContentsCalls;
/// <summary>The engine's VTank signal (API v74 GetVTankState flags: 1 = watching, 2 = running);
/// -1 = not installed (an engine before v74). Opt-in: set before Create().</summary>
public static int VTankFlags = -1;
@ -135,11 +154,22 @@ internal static unsafe class FakeHost
public static void UseDone(uint error) { UseDoneSeq++; LastUseDoneError = error; }
/// <summary>1 while a cast gesture animates (GetCastBusyState), else 0.</summary>
public static int CastBusy;
/// <summary>Opt-in (set before Create): GetLastWeenieError, answering the fields below.</summary>
public static bool WeenieErrorCalls;
public static int WeenieErrSeq;
public static uint WeenieErrCode, WeenieErrEvent, WeenieErrObject;
/// <summary>The server refused something: 0x028A WeenieError, or 0x00A0 InventoryServerSaveFailed (obj = the item).</summary>
public static void WeenieError(uint code, uint evt = 0x028A, uint obj = 0)
{ WeenieErrSeq++; WeenieErrCode = code; WeenieErrEvent = evt; WeenieErrObject = obj; }
public static int VTankSeq;
public static int CombatModeValue = 1;
/// <summary>Opt-in (set before Create): ChangeCombatMode, recorded in <see cref="CombatModeRequests"/>.</summary>
public static bool CombatModeCalls;
public static readonly List<int> CombatModeRequests = new();
/// <summary>True: ChangeCombatMode returns 0 (the engine refused, e.g. around a teleport) and records nothing in <see cref="CombatModeRequests"/>.</summary>
public static bool CombatModeRefuse;
/// <summary>ChangeCombatMode calls refused while <see cref="CombatModeRefuse"/> was set.</summary>
public static int CombatModeRefusals;
/// <summary>Opt-in (set before Create): WieldItem (a wield into a named slot, API v70+). The
/// host then reports API version 73, so only tests that ask for it see the newer calls.</summary>
public static bool WieldCalls;
@ -161,6 +191,14 @@ internal static unsafe class FakeHost
public static Action<List<uint>>? OnSalvageExecute;
/// <summary>Item id -> wielded location: GetObjectWielderInfo says the player wields it there.</summary>
public static readonly Dictionary<uint, uint> Wielded = new();
/// <summary>Opt-in (set before Create): SalvageDirect (API v82, salvage without the panel).</summary>
public static bool SalvageDirectCalls;
/// <summary>Every SalvageDirect (UST, ids), in order (opt-in with <see cref="SalvageDirectCalls"/>).</summary>
public static readonly List<(uint Tool, List<uint> Ids)> SalvageDirects = new();
/// <summary>What SalvageDirect answers; null = the count of ids (sent). -1 = sender not bound.</summary>
public static int? SalvageDirectAnswer;
/// <summary>Called on a sent SalvageDirect with (UST, ids) (the test plays the server here).</summary>
public static Action<uint, List<uint>>? OnSalvageDirect;
private static readonly List<uint> _panelItems = new();
/// <summary>Opt-in (set before Create): CloseContainer (API v76; the host then reports at
/// least v76) and GetGroundContainerId (answering <see cref="GroundContainer"/>).</summary>
@ -208,22 +246,25 @@ internal static unsafe class FakeHost
ServerTime = 0; Vitae = 1.0f; Portaling = false; PlayerPose = default; HasPose = true;
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
Logs.Clear(); Chat.Clear(); ChatCommands.Clear();
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true;
Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1;
Logs.Clear(); Chat.Clear(); ChatCommands.Clear(); AfterCastSpell = null;
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true;
Uses.Clear(); IdRequests.Clear(); TargetCalls = false; HealthQueries.Clear(); IdTimes.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; ContentsCalls = false; CombatModeValue = 1;
RequestIdAccepts = true; RefusedIdRequests = 0;
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false;
WeenieErrorCalls = false; WeenieErrSeq = 0; WeenieErrCode = WeenieErrEvent = WeenieErrObject = 0;
// Spell mana costs "unknown" (no reserve beyond Get Mana At, no cost gate), so a portal.dat on
// the PC doesn't change results; the mana reserve tests set their own costs.
RynthCore.Plugin.RynthAi.BuffManager.ManaCostOverride = _ => 0;
WieldCalls = false; Wields.Clear();
SalvageCalls = false; ExternalMoves.Clear(); SalvageAdds.Clear(); SalvageExecutes.Clear();
RefuseSalvageAdd.Clear(); OnSalvageExecute = null; Wielded.Clear(); _panelItems.Clear();
SalvageDirectCalls = false; SalvageDirects.Clear(); SalvageDirectAnswer = null; OnSalvageDirect = null;
CloseContainerCalls = false; Closes.Clear(); GroundContainer = 0;
SelectedItem = 0;
UseOnCalls = false; UsesOn.Clear();
PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear();
CombatModeCalls = false; CombatModeRequests.Clear();
CombatModeCalls = false; CombatModeRequests.Clear(); CombatModeRefuse = false; CombatModeRefusals = 0;
BusyCalls = false; ForceResets = 0; BusyStateValue = 0;
}
@ -259,6 +300,8 @@ internal static unsafe class FakeHost
api.GetPlayerIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetPlayerId;
if (Containers.Count > 0 || Wielders.Count > 0)
api.GetObjectOwnershipInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, uint*, int>)&GetObjectOwnershipInfo;
if (ContentsCalls)
api.GetContainerContentsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int, int>)&GetContainerContents;
if (Bitfields.Count > 0)
api.GetObjectBitfieldFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint>)&GetObjectBitfield;
if (InstanceIds.Count > 0)
@ -290,6 +333,11 @@ internal static unsafe class FakeHost
api.GetCurrentCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetCurrentCombatMode;
api.MoveItemInternalFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int, int>)&MoveItemInternal;
}
if (TargetCalls)
{
api.QueryHealthFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&QueryHealth;
api.GetLastIdTimeFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, long>)&GetLastIdTime;
}
if (SalvageCalls)
{
api.UseObjectFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&UseObject;
@ -299,6 +347,11 @@ internal static unsafe class FakeHost
api.SalvagePanelExecuteFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&SalvagePanelExecute;
api.GetObjectWielderInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, int>)&GetObjectWielderInfo;
}
if (SalvageDirectCalls)
{
api.Version = Math.Max(api.Version, 82u);
api.SalvageDirectFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int, int>)&SalvageDirect;
}
if (CombatModeCalls)
api.ChangeCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&ChangeCombatMode;
if (BusyCalls)
@ -351,6 +404,8 @@ internal static unsafe class FakeHost
if (LastUseDoneCalls)
api.GetLastUseDoneFn = (IntPtr)(delegate* unmanaged[Cdecl]<int*, uint*, int>)&GetLastUseDone;
}
if (WeenieErrorCalls)
api.GetLastWeenieErrorFn = (IntPtr)(delegate* unmanaged[Cdecl]<int*, uint*, uint*, uint*, int>)&GetLastWeenieError;
if (VTankFlags >= 0)
{
api.Version = Math.Max(api.Version, 74u);
@ -426,6 +481,13 @@ internal static unsafe class FakeHost
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetCastBusyState() => CastBusy;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetLastWeenieError(int* seq, uint* error, uint* eventType, uint* objectId)
{
*seq = WeenieErrSeq; *error = WeenieErrCode; *eventType = WeenieErrEvent; *objectId = WeenieErrObject;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetLastUseDone(int* seq, uint* error)
{
@ -478,6 +540,15 @@ internal static unsafe class FakeHost
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetContainerContents(uint container, uint* output, int max)
{
int n = 0;
foreach (var kv in Containers)
if (kv.Value == container && n < max) output[n++] = kv.Key;
return n;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint GetObjectBitfield(uint id) => Bitfields.TryGetValue(id, out uint b) ? b : 0u;
@ -651,10 +722,10 @@ internal static unsafe class FakeHost
private static int JumpNonAutonomous(float extent) { Jumps++; return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TapJump() { TapJumps++; return 1; }
private static int TapJump() { TapJumps++; return TapJumpRefuse ? 0 : 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); Sent.Add($"cast {spellId}"); return 1; }
private static int CastSpell(uint target, int spellId) { if (CastRefused) { CastsRefused++; return 0; } Casts.Add((target, spellId)); Sent.Add($"cast {spellId}"); AfterCastSpell?.Invoke(); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int StopCompletely() { Stops++; Sent.Add("stop"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
@ -672,7 +743,7 @@ internal static unsafe class FakeHost
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetCurrentCombatMode() => CombatModeValue;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ChangeCombatMode(int mode) { CombatModeRequests.Add(mode); return 1; }
private static int ChangeCombatMode(int mode) { if (CombatModeRefuse) { CombatModeRefusals++; return 0; } CombatModeRequests.Add(mode); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int UseObject(uint id) { Uses.Add(id); return 1; }
@ -714,6 +785,17 @@ internal static unsafe class FakeHost
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SalvageDirect(uint tool, uint* ids, int count)
{
var list = new List<uint>();
for (int i = 0; i < count; i++) list.Add(ids[i]);
SalvageDirects.Add((tool, list));
int answer = SalvageDirectAnswer ?? count;
if (answer > 0) OnSalvageDirect?.Invoke(tool, list);
return answer;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetObjectWielderInfo(uint id, uint* wielder, uint* location)
{
@ -724,7 +806,18 @@ internal static unsafe class FakeHost
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int RequestId(uint id) { IdRequests.Add(id); return 1; }
private static int RequestId(uint id)
{
if (!RequestIdAccepts) { RefusedIdRequests++; return 0; }
IdRequests.Add(id);
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int QueryHealth(uint id) { HealthQueries.Add(id); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static long GetLastIdTime(uint id) => IdTimes.TryGetValue(id, out long t) ? t : 0L;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int HasAppraisalData(uint id) => Appraised.Contains(id) ? 1 : 0;

View file

@ -36,6 +36,7 @@ internal static class Program
ExpressionEngine.ItemGiverDir = Path.Combine(TempRoot, "ItemGiver");
// The dungeon map bake writes floor plans under C:\Games\RynthSuite\RynthAi\Maps.
RynthCore.Plugin.RynthAi.Maps.DungeonMapBake.CacheDir = Path.Combine(TempRoot, "Maps");
RynthCore.Plugin.RynthAi.IltHub.IltAugCosts.FilePath = Path.Combine(TempRoot, "ilt-aug-costs.json");
// A sighted lava/acid hotspot is persisted under C:\Games\RynthSuite\RynthAi\DungeonHazards.
LiveHazardFolder = RynthCore.Plugin.RynthAi.DungeonHazardStore.Folder;
RynthCore.Plugin.RynthAi.DungeonHazardStore.Folder = Path.Combine(TempRoot, "DungeonHazards");
@ -45,11 +46,14 @@ internal static class Program
// Spell names (item spells, spell expiry by name) come from the plugin's embedded table.
SpellDatabase.Load();
// ACECustom spell catalog (Spells window, buff profiles), also embedded in the plugin.
SpellCatalog.EnsureLoaded(Console.WriteLine);
var runner = new Runner();
NativeLootTests.Register(runner);
VTankLootTests.Register(runner);
T11LootTests.Register(runner);
MagItemDescriberTests.Register(runner);
ExpressionTests.Register(runner);
MetaTests.Register(runner);
NoKillTests.Register(runner);
@ -57,7 +61,10 @@ internal static class Program
NavEngineTests.Register(runner);
NavReachTests.Register(runner);
PatrolDoorwayTests.Register(runner);
PatrolSettingsTests.Register(runner);
PatrolPocketTests.Register(runner);
BuffTests.Register(runner);
SpellCatalogTests.Register(runner);
CombatMathTests.Register(runner);
WeaponTests.Register(runner);
RadarSnapshotTests.Register(runner);
@ -67,6 +74,7 @@ internal static class Program
FloodPerfTests.Register(runner);
LootSalvageTests.Register(runner);
LootCorpseTests.Register(runner);
ChestLootTests.Register(runner);
OwnCorpseTests.Register(runner);
UseRefusalTests.Register(runner);
CorpseKillerTests.Register(runner);
@ -77,6 +85,7 @@ internal static class Program
BlastTests.Register(runner);
ArcWhenClearTests.Register(runner);
WallTests.Register(runner);
CombatHookTests.Register(runner);
UseAtLoginTests.Register(runner);
LearnSpellsTests.Register(runner);
AttackLatencyTests.Register(runner);
@ -87,8 +96,8 @@ internal static class Program
MonsterEditorTests.Register(runner);
InstallPathsTests.Register(runner);
PetRefillTests.Register(runner);
IgnoreMonsterTests.Register(runner);
WorldCacheTypedTests.Register(runner);
ItemInfoTests.Register(runner);
NavOverlayTests.Register(runner);
ActionPacingTests.Register(runner);
HazardEscapeTests.Register(runner);
@ -99,6 +108,26 @@ internal static class Program
CastNoDamageTests.Register(runner);
ManaReserveTests.Register(runner);
DamageRowsTests.Register(runner);
NavMapEditTests.Register(runner);
LootSpeedTests.Register(runner);
MeleeStallTests.Register(runner);
AttributeRaiserTests.Register(runner);
SigilChainTests.Register(runner);
ServerMenuTests.Register(runner);
ItemsCleanTests.Register(runner);
DeathRecallTests.Register(runner);
BankCommandTests.Register(runner);
InventoryAttributeFilterTests.Register(runner);
StuckCastTests.Register(runner);
PacerEdgeTests.Register(runner);
RecoveryRetryTests.Register(runner);
HpFailsafeTests.Register(runner);
PluginFixTests.Register(runner);
BuffChainTests.Register(runner);
LootPacingTests.Register(runner);
CorpseCloseTests.Register(runner);
VTankHotkeyTests.Register(runner);
SaveFailureTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -53,6 +53,8 @@
<!-- The Meta editor's "Set current" landblock / landcell text (self-contained), so MetaTests
check that MetaManager matches what the editor writes (engine 2026-10-05). -->
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\MetaLocation.cs" Link="Engine\MetaLocation.cs" />
<!-- The Inventory panel's attribute filter rules and matching (pure; engine 2026-10-11). -->
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Compatibility\InventoryAttributeFilter.cs" Link="Engine\InventoryAttributeFilter.cs" />
</ItemGroup>
<ItemGroup>

View file

@ -54,6 +54,21 @@ internal static class ActionPacingTests
r.Add("pacing: no answer - each kind's time limit lets the next action go, logged, and nothing is force-cleared", TimeLimits);
r.Add("pacing: heals (a plain heal waits for a corpse use's answer, 300 ms at Emergency, one behind a cast's result, 300 ms after the stance reads)", HealRules);
r.Add("pacing (vitals): Drakkon 07:03 - a cast whose result is in waits for its UseDone: one cast, not a too-busy flood", CastWaitsForUseDone);
r.Add("refusal: a refused mode change begins no paced action, and the next one is not held by it", RefusedBeginsNothing);
r.Add("refusal: the engine refusing for 5 s burns nothing; a streak past 30 s counts as a failure again, with one log line each end", RefusalStreakFailsOpen);
r.Add("refusal: 20 s of refusals with no wand never reach _magicModeBlocked; past 30 s the failure counting resumes and the vitals fall to the potion path", NoWandRefusalLoop);
r.Add("refusal: wand wielded, 9 s of refused stance changes - no re-equip UseObject, no burnt re-equip; the first accepted request starts the clock", WandWieldedRefusalNoReEquip);
r.Add("refusal: a refused peace-before-open is asked again inside the 2.5 s ceiling; exactly one accepted request goes out before the open", PeaceBeforeOpenRefusedRetried);
r.Add("refusal: a streak that went quiet for 10 s+ (a death, a logout) is over - 600 s later a refusal starts a fresh streak, and Forget ends one", RefusalStreakExpires);
r.Add("refusal: wand wielded, a request accepted then dropped (a teleport), 9 s of refusals - the stuck clock restarts, no re-equip UseObject", StuckClockRestartsOnRefusal);
r.Add("refusal: the stall watchdog's refused mode toggle spends no ladder step (Unfire) and is asked again next tick", StallToggleRefusedSpendsNoStep);
r.Add("refusal: missile crafting asks for peace until accepted, and combines after the 2.5 s ceiling; already in peace it combines on the first tick with no mode request", CraftingPeaceRefusal);
r.Add("pacing (stance): a refused ChangeCombatMode burns no try and no backoff step, and the next tick asks again (pacing on and off)", RefusedStanceBurnsNothing);
r.Add("corpse id: a refused RequestId is not recorded as asked - the next evaluation asks again and the accepted one goes out", CorpseIdRefusedRetried);
r.Add("corpse id: an accepted request with no data is asked again after 3 s (not before), once per 3 s, with no give-up cap", CorpseIdReaskedWithoutData);
r.Add("corpse id: two corpses in range, no data for either - only the targeted one re-asks; the other stays at one accepted request (a refused one is still retried)", CorpseIdOnlyCandidateReasks);
r.Add("corpse id: 20 uncached corpses, a refusal window, then accept - at most 2 requests in the first accepted tick, the target among them; refused retries are 250 ms apart", CorpseIdBurstCapped);
r.Add("corpse id: the open container is a candidate and re-asks; delete and the >200 prune clear every id map", CorpseIdOpenContainerAndCleanup);
r.Add("pacing (vitals): a heal waits for an unanswered corpse use's answer, then goes at once; the emergency stance settle is unchanged", HealLatencyKept);
r.Add("pacing (looting): one open per server answer, never re-sent on top of an unanswered one", LootOneOpenPerAnswer);
r.Add("pacing (looting): Drakkon's stall is still found and said once with pacing on", LootStallStillDetected);
@ -468,6 +483,484 @@ internal static class ActionPacingTests
finally { PaceOff(); }
}
private static void RefusedStanceBurnsNothing()
{
foreach (bool pacing in new[] { true, false })
{
PaceOff();
if (pacing) PaceOn();
try
{
var r = new BuffRig(CombatMode.NonCombat);
r.S.EmergencyHealAt = 30; r.S.HealAt = 60; r.S.TopOffHP = 60; r.S.GetManaAt = 0; r.S.TopOffMana = 0;
r.V.CurrentHealth = 20; r.V.CurrentMana = 100;
var fails = typeof(BuffManager).GetField("_buffStanceConsecutiveFails", Any)!;
var last = typeof(BuffManager).GetField("_lastBuffStanceAttempt", Any)!;
DateTime lastBefore = (DateTime)last.GetValue(r.B)!;
FakeHost.CombatModeRefuse = true; // the engine turns the stance change away (a teleport, a death)
for (int i = 0; i < 6; i++) { r.At(i * 0.2); r.B.OnHeartbeat(); }
Check.Eq(FakeHost.CombatModeRefusals, 6, $"pacing={pacing}: every tick asks again - a refusal is no try and sets no backoff");
Check.Eq((int)fails.GetValue(r.B)!, 0, $"pacing={pacing}: _buffStanceConsecutiveFails unchanged");
Check.True((DateTime)last.GetValue(r.B)! == lastBefore, $"pacing={pacing}: _lastBuffStanceAttempt unchanged");
Check.Eq(FakeHost.CombatModeRequests.Count, 0, $"pacing={pacing}: nothing reached the server");
FakeHost.CombatModeRefuse = false;
r.At(1.4); r.B.OnHeartbeat();
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", $"pacing={pacing}: the engine accepts again and the very next tick sends Magic");
Check.Eq((int)fails.GetValue(r.B)!, 1, $"pacing={pacing}: only a sent request counts as a try");
}
finally { PaceOff(); }
}
}
private static void RefusedBeginsNothing() => Paced(() =>
{
var host = World(combatMode: 2);
FakeHost.CombatModeRefuse = true;
Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "refused"), "the engine refused: false");
Check.True(ActionPacer.Current(host) == null, "no paced action was begun");
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "so nothing is held behind it");
FakeHost.CombatModeRefuse = false;
Check.True(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "accepted"), "accepted: true");
Check.True(ActionPacer.Current(host)?.Kind == PacedKind.CombatMode, "and now the stance change is outstanding");
});
private static void RefusalStreakFailsOpen() => Paced(() =>
{
var host = World(combatMode: 2);
FakeHost.CombatModeRefuse = true;
for (int s = 0; s <= 5; s++) { _t = 10_000_000 + s * 1000; Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), $"{s} s into a refusal streak: false"); }
Check.Eq(FakeHost.Logs.Count(l => l.Contains("the engine refused the change")), 1, "one line when the streak starts");
FakeHost.CombatModeRefuse = false;
_t = 10_000_000 + 6_000;
Check.True(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), "accepted");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("the engine accepts mode changes again")), 1, "one line when it ends");
FakeHost.UseDone(0); ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => _t;
FakeHost.CombatModeRefuse = true;
long start = _t + 1000;
bool sawOpen = false;
for (int s = 0; s <= 40; s++)
{
_t = start + s * 1000L;
bool r = host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x");
if (s <= 30) Check.False(r, $"{s} s into the streak: still false");
else sawOpen |= r;
}
Check.True(sawOpen, "past 30 s a refusal counts as a failure again (true)");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("the engine refused the change")), 2, "the second streak logged once");
FakeHost.CombatModeRefuse = false;
_t += 1000;
Check.True(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), "any accepted call ends the streak");
FakeHost.CombatModeRefuse = true;
_t += 5000; ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => _t;
Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), "a fresh streak starts at false again");
});
private static readonly BindingFlags Priv = BindingFlags.Instance | BindingFlags.NonPublic;
private static void SetupBuffRigVitals(BuffRig r)
{
r.S.EmergencyHealAt = 30; r.S.HealAt = 60; r.S.TopOffHP = 60; r.S.GetManaAt = 0; r.S.TopOffMana = 0;
r.V.CurrentHealth = 20; r.V.CurrentMana = 100;
}
private static void NoWandRefusalLoop()
{
PaceOff();
try
{
var r = new BuffRig(CombatMode.NonCombat);
SetupBuffRigVitals(r);
var blocked = typeof(BuffManager).GetField("_magicModeBlocked", Priv)!;
var fails = typeof(BuffManager).GetField("_buffStanceConsecutiveFails", Priv)!;
var swapUntil = typeof(BuffManager).GetField("_vitalSwapBlockedUntil", Priv)!;
FakeHost.CombatModeRefuse = true;
bool everBlocked = false;
int ticks = 0;
for (double s = 0; s <= 20; s += 0.5) { r.At(s); r.B.OnHeartbeat(); ticks++; everBlocked |= (bool)blocked.GetValue(r.B)!; }
Check.True(FakeHost.CombatModeRefusals >= ticks / 2, $"20 s: the stance is asked again throughout ({FakeHost.CombatModeRefusals} refusals in {ticks} heartbeats; other vitals gates skip some ticks)");
Check.False(everBlocked, "_magicModeBlocked never set by refusals");
Check.Eq((int)fails.GetValue(r.B)!, 0, "no failure counted");
Check.True((DateTime)swapUntil.GetValue(r.B)! < DateTime.Now, "and the vitals did not fall through to the potion path");
// Past 30 s of refusals the call counts again. The backoff gates run on the real clock, so
// stand in for three earlier counted tries: the very next counted try (the first past 30 s)
// is the fourth, and the one after it finds the flip blocked and hands over to the potion.
fails.SetValue(r.B, 3);
for (double s = 20.5; s <= 40; s += 0.5) { r.At(s); r.B.OnHeartbeat(); everBlocked |= (bool)blocked.GetValue(r.B)!; }
Check.True(everBlocked, "40 s: the failure counting resumed and _magicModeBlocked was reached");
Check.True((DateTime)swapUntil.GetValue(r.B)! > DateTime.Now, "the vitals chain reached the potion/kit fallback (swap blocked, retry later)");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("the engine refused the change")), 1, "one streak, one line");
}
finally { PaceOff(); }
}
private static void WandWieldedRefusalNoReEquip()
{
PaceOff();
try
{
var r = new BuffRig(CombatMode.NonCombat);
SetupBuffRigVitals(r);
FakeHost.Names[Wand] = "Academy Wand";
FakeHost.ItemTypes[Wand] = 0x8000;
FakeHost.Ints[(Wand, 10)] = 0x01000000; // CurrentWieldedLocation: in hand
r.S.WieldUnlistedWandWhenNoneListed = true;
r.B.SetWorldObjectCache(FakeHost.MakeCache(r.Host, Player, new[] { Wand }));
var reEquips = typeof(BuffManager).GetField("_buffStanceReEquips", Priv)!;
var since = typeof(BuffManager).GetField("_buffStanceStuckSince", Priv)!;
FakeHost.CombatModeRefuse = true;
r.At(0); r.B.OnHeartbeat();
Check.True(FakeHost.CombatModeRefusals >= 1, "set-up: the wielded-wand branch asked for the stance and was refused");
Check.True((DateTime)since.GetValue(r.B)! == DateTime.MinValue, "the stuck clock has not started");
System.Threading.Thread.Sleep(9_000); // BuffStanceStuckRecoverMs (8 s) runs on the real clock
r.At(9); r.B.OnHeartbeat();
r.At(9.3); r.B.OnHeartbeat();
Check.Eq((int)reEquips.GetValue(r.B)!, 0, "9 s of refusals: _buffStanceReEquips stays 0");
Check.False(FakeHost.Uses.Contains(Wand), "and no UseObject(wand) - a MOVE on a wielded wand - went out");
Check.True((DateTime)since.GetValue(r.B)! == DateTime.MinValue, "the clock still has not started");
FakeHost.CombatModeRefuse = false;
r.At(9.6); r.B.OnHeartbeat();
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", "accepted: the Magic request goes out");
Check.True((DateTime)since.GetValue(r.B)! != DateTime.MinValue, "and only now the stuck clock starts");
Check.Eq((int)reEquips.GetValue(r.B)!, 0, "still no re-equip");
Check.False(FakeHost.Uses.Contains(Wand), "still no UseObject(wand)");
}
finally { PaceOff(); }
}
private static void PeaceBeforeOpenRefusedRetried()
{
LootWorld();
FakeHost.CombatModeCalls = true;
FakeHost.CombatModeValue = CombatMode.Melee;
var host = FakeHost.Create(Player);
var bot = new Bot(host);
var cache = bot.Get<WorldObjectCache>("_objectCache");
var cm = new CombatManager(host, bot.S, cache);
cm.SetPlayerId(Player);
bot.Set("_combatManager", cm);
bot.Set("_targetCorpseId", unchecked((int)Corpse));
bot.S.PeaceModeWhenIdle = true;
bool Wants(long now) => (bool)bot.Call("WantsPeaceBeforeOpen", bot.S, now)!;
FakeHost.CombatModeRefuse = true;
Check.True(Wants(1_000), "first ask (refused): the open waits");
Check.True(Wants(1_500), "asked again (refused): still waiting");
Check.Eq(FakeHost.CombatModeRefusals, 2, "both asks reached the engine: the refusal did not use up the one shot");
FakeHost.CombatModeRefuse = false;
Check.True(Wants(2_000), "accepted within the ceiling: waiting for the swap");
Check.True(Wants(2_300), "waiting");
Check.True(Wants(3_000), "waiting");
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "exactly one peace request went out");
Check.False(Wants(3_600), "the ceiling counts from the FIRST ask (1000 + 2500): the open goes on");
Check.Eq(FakeHost.CombatModeRequests.Count, 1, "and still exactly one");
}
private static void RefusalStreakExpires() => Paced(() =>
{
var host = World(combatMode: 2);
FakeHost.CombatModeRefuse = true;
Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), "t0: a refusal opens a streak (false)");
_t += 600_000; // a death, a logout: ten minutes of nothing, no accepted call in between
Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), "a refusal 600 s later is a NEW streak (false), not a 600 s streak failing open");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("the engine refused the change")), 2, "and it logged its own start line");
// Refusals closer than the gap are one streak: it still fails open at 30 s.
ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => _t;
long start = _t;
bool open = false;
for (int s = 0; s <= 40; s += 5) { _t = start + s * 1000L; open |= host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"); }
Check.True(open, "refusals 5 s apart stay one streak and fail open past 30 s");
// Forget (portal / death / logout) ends the streak too.
ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => _t;
// Refusals 9 s apart are one streak (the gap is 10 s). Without the Forget the refusal at +36 s would be 36 s into it and fail open.
Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), "streak begins");
_t += 9_000; Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), "+9 s: same streak");
ActionPacer.Forget("death");
for (int s = 0; s < 3; s++) { _t += 9_000; Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), $"after Forget a fresh streak, refusal {s + 1} (false)"); }
Check.True(ActionPacer.LastEngineRefusalMs > 0, "LastEngineRefusalMs records the newest refusal");
ActionPacer.Reset();
Check.Eq(ActionPacer.LastEngineRefusalMs, 0L, "Reset clears LastEngineRefusalMs");
});
private static void StuckClockRestartsOnRefusal()
{
PaceOff();
try
{
var r = new BuffRig(CombatMode.NonCombat);
SetupBuffRigVitals(r);
FakeHost.Names[Wand] = "Academy Wand";
FakeHost.ItemTypes[Wand] = 0x8000;
FakeHost.Ints[(Wand, 10)] = 0x01000000; // in hand
r.S.WieldUnlistedWandWhenNoneListed = true;
r.B.SetWorldObjectCache(FakeHost.MakeCache(r.Host, Player, new[] { Wand }));
var reEquips = typeof(BuffManager).GetField("_buffStanceReEquips", Priv)!;
var since = typeof(BuffManager).GetField("_buffStanceStuckSince", Priv)!;
var lastTry = typeof(BuffManager).GetField("_lastBuffStanceAttempt", Priv)!;
r.At(0); r.B.OnHeartbeat();
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", "set-up: the first request is accepted and starts the stuck clock");
Check.True((DateTime)since.GetValue(r.B)! != DateTime.MinValue, "set-up: the clock is running");
// The request was dropped by a teleport; the engine now refuses. The backoff gate (real clock) is opened by back-dating.
lastTry.SetValue(r.B, DateTime.Now.AddSeconds(-3));
FakeHost.CombatModeRefuse = true;
r.At(2); r.B.OnHeartbeat();
Check.True(FakeHost.CombatModeRefusals >= 1, "set-up: a later request was refused");
// 9 s of that: back-date the clock as if the real time had passed (the re-equip rule reads the real clock).
since.SetValue(r.B, DateTime.Now.AddSeconds(-9));
r.At(9); r.B.OnHeartbeat();
r.At(9.3); r.B.OnHeartbeat();
Check.Eq((int)reEquips.GetValue(r.B)!, 0, "a refusal newer than the clock's start restarted it: _buffStanceReEquips stays 0");
Check.False(FakeHost.Uses.Contains(Wand), "and no UseObject(wand) - a MOVE on a wielded wand - went out");
Check.True((DateTime.Now - (DateTime)since.GetValue(r.B)!).TotalSeconds < 3, "the clock was restarted at now");
FakeHost.CombatModeRefuse = false;
r.At(9.6); r.B.OnHeartbeat();
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8,8", "accepted again");
Check.Eq((int)reEquips.GetValue(r.B)!, 0, "still no re-equip");
Check.False(FakeHost.Uses.Contains(Wand), "still no UseObject(wand)");
}
finally { PaceOff(); }
}
private static void StallToggleRefusedSpendsNoStep()
{
PaceOff();
var host = World(combatMode: 2);
var s = new LegacyUiSettings { BotAction = "Combat" };
var cm = new CombatManager(host, s, new WorldObjectCache(host));
cm.SetPlayerId(Player);
const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic;
typeof(CombatManager).GetField("_activeTargetId", F)!.SetValue(cm, unchecked((int)Corpse));
var watch = typeof(CombatManager).GetField("_stallWatch", F)!.GetValue(cm)!;
var wt = watch.GetType();
DateTime now = DateTime.Now;
// The ladder stands at step 2 (re-select done 4 s ago); the next step due is the mode toggle.
wt.GetField("_eligibleSince", F)!.SetValue(watch, now.AddSeconds(-12));
wt.GetField("_lastTick", F)!.SetValue(watch, now.AddMilliseconds(-100));
wt.GetField("_step", F)!.SetValue(watch, 2);
wt.GetField("_lastStepAt", F)!.SetValue(watch, now.AddSeconds(-4));
wt.GetField("_stallRef", F)!.SetValue(watch, now.AddSeconds(-12));
int Step() => (int)wt.GetProperty("CurrentStep")!.GetValue(watch)!;
var run = typeof(CombatManager).GetMethod("RunStallWatchdog", F)!;
var lastAttack = typeof(CombatManager).GetField("lastAttackCmd", F)!;
lastAttack.SetValue(cm, DateTime.MinValue);
FakeHost.CombatModeRefuse = true;
Check.True((bool)run.Invoke(cm, new object?[] { null, 1.0 })!, "the toggle step holds the tick");
Check.Eq(FakeHost.CombatModeRefusals, 1, "the toggle reached the engine and was refused");
Check.Eq(Step(), 2, "a refusal spends no ladder step: still at step 2");
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "nothing was sent");
Check.True((DateTime)lastAttack.GetValue(cm)! == DateTime.MinValue, "a refusal does not stamp the attack clock");
FakeHost.CombatModeRefuse = false;
Check.True((bool)run.Invoke(cm, new object?[] { null, 1.0 })!, "next tick: the toggle step is due again at once (not 3 s later)");
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "and the accepted toggle sent Peace");
Check.Eq(Step(), 3, "now the ladder is at step 3");
Check.True((DateTime)lastAttack.GetValue(cm)! != DateTime.MinValue, "the accepted toggle stamps the attack clock");
}
private static void CraftingPeaceRefusal()
{
PaceOff();
const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic;
MissileCraftingManager Rig(int mode, bool refuse, out Action<double> backdateAsk)
{
var host = World(combatMode: mode);
FakeHost.CombatModeRefuse = refuse;
var cm = new MissileCraftingManager(host, new LegacyUiSettings { EnableMissileCrafting = true });
var t = typeof(MissileCraftingManager);
t.GetField("_currentRecipe", F)!.SetValue(cm, AmmoRecipes.All[0]);
t.GetField("_headBundleId", F)!.SetValue(cm, 0x5001);
t.GetField("_shaftBundleId", F)!.SetValue(cm, 0x5002);
t.GetField("_peaceSent", F)!.SetValue(cm, false);
t.GetField("_peaceAskedAt", F)!.SetValue(cm, DateTime.Now);
t.GetMethod("TryPeaceForCrafting", F)!.Invoke(cm, null); // StartCrafting's first step
t.GetMethod("SetState", F)!.Invoke(cm, new object[] { MissileCraftingManager.CraftState.Combining });
backdateAsk = sec => t.GetField("_peaceAskedAt", F)!.SetValue(cm, DateTime.Now.AddSeconds(-sec));
return cm;
}
// (a) the engine always refuses: no combine inside the ceiling, the combine after it.
var a = Rig(CombatMode.Melee, true, out var backdate);
a.ProcessCrafting();
Check.Eq(FakeHost.UsesOn.Count, 0, "(a) refused, inside 2.5 s: the combine waits");
a.ProcessCrafting();
Check.Eq(FakeHost.UsesOn.Count, 0, "(a) still waiting");
Check.True(FakeHost.CombatModeRefusals >= 2, $"(a) peace was asked again each tick ({FakeHost.CombatModeRefusals} refusals)");
backdate(2.6);
a.ProcessCrafting();
Check.Eq(FakeHost.UsesOn.Count, 1, "(a) past the 2.5 s ceiling the combine goes out anyway");
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "(a) no mode request ever reached the server");
// (b) already in Peace: no request at all, the combine on the first tick.
var b = Rig(CombatMode.NonCombat, true, out _);
b.ProcessCrafting();
Check.Eq(FakeHost.UsesOn.Count, 1, "(b) already in Peace: the combine goes out on the first tick");
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "(b) and no mode request was made");
Check.Eq(FakeHost.CombatModeRefusals, 0, "(b) nor asked");
}
private static (Bot Bot, WorldObject Corpse) CorpseIdRig()
{
LootWorld();
FakeHost.Strings.Remove((Corpse, LongDescKey)); // nothing appraised yet: no killer name
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Set("_targetCorpseId", unchecked((int)Corpse)); // the corpse the bot is going for: the only one that re-asks
var obj = bot.Get<WorldObjectCache>("_objectCache")[unchecked((int)Corpse)]!;
return (bot, obj);
}
private static void CorpseIdRefusedRetried() => Paced(() =>
{
var (bot, obj) = CorpseIdRig();
FakeHost.RequestIdAccepts = false;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(FakeHost.RefusedIdRequests, 1, "the engine refused the first RequestId");
Check.Eq(FakeHost.IdRequests.Count(i => i == Corpse), 0, "so nothing went out");
_t += 250;
FakeHost.RequestIdAccepts = true;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(FakeHost.IdRequests.Count(i => i == Corpse), 1, "the next evaluation asked again and it was accepted");
_t += 100;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(FakeHost.IdRequests.Count(i => i == Corpse), 1, "an accepted request is not repeated at once");
});
private static void CorpseIdReaskedWithoutData() => Paced(() =>
{
var (bot, obj) = CorpseIdRig();
int Asked() => FakeHost.IdRequests.Count(i => i == Corpse);
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 1, "t=0: the first request goes out");
_t += 2_999;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 1, "2.999 s, no data: not yet");
_t += 1;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 2, "3 s, no data: asked again");
_t += 1_000;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 2, "1 s after the re-ask: waits");
_t += 2_000;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 3, "one re-ask per 3 s, and no cap");
for (int i = 0; i < 10; i++) { _t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj); }
Check.Eq(Asked(), 13, "ten more 3 s periods, ten more asks");
FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}.";
_t += 3_000;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 13, "once the data has arrived nothing more is asked");
});
private static void CorpseIdOnlyCandidateReasks() => Paced(() =>
{
LootWorld();
FakeHost.Strings.Remove((Corpse, LongDescKey));
FakeHost.Strings.Remove((CorpseB, LongDescKey));
var host = FakeHost.Create(Player);
var bot = new Bot(host);
var cache = bot.Get<WorldObjectCache>("_objectCache");
var a = cache[unchecked((int)Corpse)]!;
var b = cache[unchecked((int)CorpseB)]!;
bot.Set("_targetCorpseId", unchecked((int)Corpse));
int Asked(uint id) => FakeHost.IdRequests.Count(i => i == id);
void Both() { bot.Call("EvaluateCorpseLootDecision", a); bot.Call("EvaluateCorpseLootDecision", b); }
FakeHost.RequestIdAccepts = false;
Both();
FakeHost.RequestIdAccepts = true;
_t += 250; Both();
Check.Eq(Asked(Corpse), 1, "the candidate: refused once, then one accepted request");
Check.Eq(Asked(CorpseB), 1, "the other corpse: a refused request is retried, one accepted request");
for (int i = 0; i < 4; i++) { _t += 3_000; Both(); }
Check.Eq(Asked(Corpse), 5, "no data: the candidate re-asks once per 3 s");
Check.Eq(Asked(CorpseB), 1, "the other corpse never asks a second time");
bot.Set("_targetCorpseId", unchecked((int)CorpseB));
_t += 3_000; Both();
Check.Eq(Asked(CorpseB), 2, "once it becomes the candidate it re-asks");
});
private static void CorpseIdBurstCapped() => Paced(() =>
{
LootWorld();
FakeHost.Strings.Remove((Corpse, LongDescKey));
FakeHost.Strings.Remove((CorpseB, LongDescKey));
var host = FakeHost.Create(Player);
var bot = new Bot(host);
var cache = bot.Get<WorldObjectCache>("_objectCache");
var ids = new System.Collections.Generic.List<uint> { Corpse, CorpseB };
for (uint i = 0; i < 18; i++)
{
uint id = 0x80090000 + i;
FakeHost.Names[id] = "Corpse of Olthoi Swarm Worker";
FakeHost.ItemTypes[id] = ItemTypeContainer;
FakeHost.NotAttackable.Add(id);
FakeHost.Positions[id] = (Me0.Cell, Me0.X + 2.0f + i * 0.1f, Me0.Y, Me0.Z);
cache.OnCreateObject(id);
ids.Add(id);
}
cache.Tick();
uint target = ids[^1]; // created last: the scan reaches it last, so only the candidate-first rule puts it among the first two
bot.Set("_targetCorpseId", unchecked((int)target));
void Scan() => bot.Call("HasUnlootedCorpsesInRange", 30.0);
FakeHost.RequestIdAccepts = false;
for (int k = 0; k < 3; k++) { _t += 300; Scan(); }
Check.Eq(FakeHost.IdRequests.Count, 0, "the refusal window: nothing accepted");
Check.True(FakeHost.RefusedIdRequests >= 20, $"every corpse was tried ({FakeHost.RefusedIdRequests} refusals)");
int refusals = FakeHost.RefusedIdRequests;
_t += 100; Scan();
Check.Eq(FakeHost.RefusedIdRequests, refusals, "100 ms later: refused corpses are not retried yet (250 ms apart)");
FakeHost.RequestIdAccepts = true;
_t += 300; Scan();
Check.True(FakeHost.IdRequests.Count <= 2, $"the first accepted tick sends at most 2 ({FakeHost.IdRequests.Count})");
Check.True(FakeHost.IdRequests.Contains(target), "and the candidate is among them");
for (int k = 0; k < 12; k++)
{
int before = FakeHost.IdRequests.Count;
_t += 200; Scan();
Check.True(FakeHost.IdRequests.Count - before <= 2, $"tick {k + 2}: at most 2 new requests");
}
Check.Eq(FakeHost.IdRequests.Distinct().Count(), 20, "within a few ticks every corpse has been asked once");
});
private static void CorpseIdOpenContainerAndCleanup() => Paced(() =>
{
const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic;
var (bot, obj) = CorpseIdRig();
bot.Set("_targetCorpseId", 0);
bot.Set("_openedContainerId", unchecked((int)Corpse));
int Asked() => FakeHost.IdRequests.Count(i => i == Corpse);
bot.Call("EvaluateCorpseLootDecision", obj);
_t += 3_000;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 2, "the open container is a candidate: it re-asks after 3 s");
var asked = bot.Get<System.Collections.Generic.Dictionary<int, long>>("_corpseIdAskedAt");
var refused = bot.Get<System.Collections.Generic.Dictionary<int, long>>("_corpseIdRefusedAt");
var requested = bot.Get<System.Collections.Generic.HashSet<int>>("_corpseIdRequested");
int sid = unchecked((int)Corpse);
refused[sid] = _t;
Check.True(asked.ContainsKey(sid) && requested.Contains(sid), "set-up: the corpse is recorded");
bot.Call("HandleCorpseObjectDeleted", Corpse);
Check.False(asked.ContainsKey(sid), "delete clears _corpseIdAskedAt");
Check.False(refused.ContainsKey(sid), "delete clears _corpseIdRefusedAt");
Check.False(requested.Contains(sid), "delete clears _corpseIdRequested");
for (int i = 0; i < 201; i++) { requested.Add(i + 1); asked[i + 1] = _t; refused[i + 1] = _t; }
bot.Set("_lastCorpsePruneAt", 0L);
bot.Call("PruneCorpseCollections");
Check.Eq(requested.Count, 0, "the >200 prune clears _corpseIdRequested");
Check.Eq(asked.Count, 0, "the >200 prune clears _corpseIdAskedAt");
Check.Eq(refused.Count, 0, "the >200 prune clears _corpseIdRefusedAt");
});
// ── Looting ──────────────────────────────────────────────────────────────────
private static void LootWorld()
@ -703,7 +1196,7 @@ internal static class ActionPacingTests
_t += 110;
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out string why), "the wand waits: the swing hasn't animated yet");
Check.True(why.Contains("swing"), "why: " + why);
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "the next attack isn't held");
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true), "the next attack isn't held");
_t += 200;
FakeHost.CastBusy = 1;
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "swinging: still waits");
@ -830,10 +1323,10 @@ internal static class ActionPacingTests
{
var host = World(combatMode: 2);
FakeHost.CastBusy = 1; // the last swing still plays
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "a melee attack repeat is not held by the animation");
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true), "a melee attack repeat is not held by the animation");
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "anything gated is");
host.UseFor(Corpse, "Loot", "open");
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "but an attack still waits for an unanswered corpse use (the server's turn)");
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true), "but an attack still waits for an unanswered corpse use (the server's turn)");
FakeHost.UseDone(0);
Check.True(ActionPacer.Current(host) == null, "the use is answered");
ActionPacer.Enabled = false;

View file

@ -83,8 +83,9 @@ internal static class AttackLatencyTests
private static void NewTargetInterval()
{
const int Magic = CombatMode.Magic, Melee = CombatMode.Melee, Missile = CombatMode.Missile;
Check.Eq(CombatManager.AttackIntervalMs(Melee, 1500, true, true), 1000.0, "melee: 1000 ms, new target or not");
Check.Eq(CombatManager.AttackIntervalMs(Missile, 1500, true, true), 1000.0, "missile: 1000 ms");
Check.Eq(CombatManager.AttackIntervalMs(Melee, 1500, true, false), 1000.0, "melee, same target: 1000 ms");
Check.Eq(CombatManager.AttackIntervalMs(Melee, 1500, true, true), CombatManager.NewTargetPhysicalFloorMs, "melee, new target: the short floor (2026-10-12)");
Check.Eq(CombatManager.AttackIntervalMs(Missile, 1500, true, false), 1000.0, "missile, same target: 1000 ms");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 1500, true, false), 1500.0, "magic, same target: the setting");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 2500, true, false), 2500.0, "magic, same target: a slower setting is kept");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 0, true, false), 0.0, "magic, setting 0: no delay of its own (the server gates hold the cast)");

View file

@ -0,0 +1,455 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using RynthCore.Plugin.RynthAi.IltHub;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Server Features gate + the infinite-attribute raiser (2026-10-06). The gate decides from
// Settings > Misc (world-name patterns, manual override) whether the ILT features ask the
// server at all; the raiser reads "/xp all" costs and spends unassigned XP with "/attr <abbr> 1"
// on the ticked stats, in the chosen order, never below the reserve.
internal static class AttributeRaiserTests
{
private const uint Player = 0x50000C01;
public static void Register(Runner r)
{
r.Add("server features: name patterns (exact, wildcards, case)", Patterns);
r.Add("server features: list parsing and the override", ListAndOverride);
r.Add("attr raiser: pick by mode (priority, round robin, cheapest)", PickModes);
r.Add("attr raiser: pick respects ticks, reserve and unknown costs", PickLimits);
r.Add("attr raiser: order repair and stat names from server lines", OrderAndNames);
r.Add("attr raiser: a run reads costs, raises in order, stops when nothing is affordable", FullRun);
r.Add("attr raiser: off when the world is not in the Server Features list", GatedOff);
r.Add("attr raiser: safety (stale costs, another stat's reply, gate off mid-run, held off)", Safety);
r.Add("attr raiser: by-hand +1 / +10 priced like UB, refused when unaffordable, costs read on tab open", ByHandPriced);
r.Add("aug planner: /aug pulled on tab open, totals, reset targets, copy texts", AugPlanner);
r.Add("aug costs: UB's ILT model (tier starts at its S level) in closed form", AugCostModel);
r.Add("aug costs: per-server multipliers and rules, saved and reset", AugCostSettings);
}
/// <summary>UB Augs.cs GetCumulativeCost difference, level by level (the reference the closed form must match).</summary>
private static decimal UbLoop(IltAugCostRow r, double[] m, int cur, int tgt)
{
decimal step = r.Base * (decimal)r.LinearPercent / 100m, total = 0;
for (int i = cur + 1; i <= tgt; i++)
{
decimal b = r.Base + (i - 1) * step;
double mult = i < r.S1 ? m[0] : i < r.S2 ? m[1] : i < r.S3 ? m[2] : i < r.S4 ? m[3] : m[4];
total += b * (decimal)mult;
}
return total;
}
private static void AugCostModel()
{
var rows = IltAugCosts.DefaultRows().ToDictionary(x => x.Key);
var m = IltAugCosts.DefaultMultipliers;
var creature = rows["creature"];
Check.Eq(IltAugCosts.LumCost(creature, m, 2748, 2749), 750_000m + 2748 * 975_000m, "level 2749 (S1 - 1) is the last x1 level");
Check.Eq(IltAugCosts.LumCost(creature, m, 2749, 2750), (750_000m + 2749 * 975_000m) * 4, "level 2750 (S1) is the first x4 level");
Check.Eq(rows["specialization"].S2, 2500, "Specialization uses UB's 1750/2500/3000/3750");
Check.Eq(rows["summon"].S1, 1750, "Summon uses UB's 1750/2500/3000/3750");
Check.Eq(creature.Cap, 0, "no target cap by default (UB has none)");
foreach (var (key, cur, tgt) in new[] { ("creature", 0, 6000), ("item", 1200, 3600), ("specialization", 1700, 3800),
("duration", 999, 1001), ("summon", 3749, 3751), ("life", 10, 10) })
Check.Eq(IltAugCosts.LumCost(rows[key], m, cur, tgt), UbLoop(rows[key], m, cur, tgt), $"{key} {cur}->{tgt} matches UB's loop");
var odd = new double[] { 1.5, 2, 3.25, 10, 0 };
Check.Eq(IltAugCosts.LumCost(rows["war"], odd, 1500, 4000), UbLoop(rows["war"], odd, 1500, 4000), "custom multipliers match the loop");
Check.Eq(IltAugCosts.LumCost(creature, m, 50, 40), 0m, "a target below current costs nothing");
Check.True(IltAugCosts.LumCost(creature, m, 0, IltAugCosts.NoCapLimit) > 0, "the largest uncapped target is priced without overflow");
}
private static void AugCostSettings()
{
string file = IltAugCosts.FilePath;
if (File.Exists(file)) File.Delete(file);
var settings = new LegacyUiSettings();
var hub = NewHub("InfiniteLeaftide", settings, "aug-costs", out _);
var prog = hub.Progression;
prog.ApplyAugLines(new List<string> { "War: 1700" });
hub.State.Character.AugTargets["war"] = 1800;
string Snapshot()
{
var sb = new System.Text.StringBuilder();
prog.AppendSnapshotJson(sb);
return "{" + sb + "}";
}
System.Text.Json.JsonElement Aug(string json) => System.Text.Json.JsonDocument.Parse(json).RootElement.GetProperty("aug");
var before = Aug(Snapshot());
Check.False(before.GetProperty("cfg").GetProperty("custom").GetBoolean(), "a world starts on the defaults");
Check.Eq(before.GetProperty("cfg").GetProperty("mults").GetArrayLength(), 5, "five tier multipliers in the snapshot");
string lumBefore = before.GetProperty("totLum").GetString() ?? "";
prog.HandleRemote(new[] { "augmult", "1", "2" });
var after = Aug(Snapshot());
Check.True(after.GetProperty("cfg").GetProperty("custom").GetBoolean(), "an edit gives the world its own rules");
Check.Eq(after.GetProperty("cfg").GetProperty("mults")[1].GetDouble(), 2.0, "multiplier saved");
Check.True((after.GetProperty("totLum").GetString() ?? "") != lumBefore, "the plan re-prices with the new multiplier");
prog.HandleRemote(new[] { "augcfg", "war", "s1", "1800" });
prog.HandleRemote(new[] { "augcfg", "war", "base", "1m" });
prog.HandleRemote(new[] { "augcfg", "war", "s2", "100" });
var war = prog.AugCosts.For("InfiniteLeaftide").Augs.First(x => x.Key == "war");
Check.Eq(war.S1, 1800, "S1 edited");
Check.Eq(war.Base, 1_000_000L, "base accepts k/m/b suffixes");
Check.Eq(war.S2, 1800, "S2 can't go below S1");
Check.Eq(prog.AugCosts.For("Aelrynth").Multipliers[1], 4.0, "another world keeps the defaults");
var reloaded = new IltAugCosts();
Check.Eq(reloaded.For("infiniteleaftide").Multipliers[1], 2.0, "rules are saved per world (name ignores case)");
prog.HandleRemote(new[] { "augcfgreset" });
Check.False(prog.AugCosts.IsCustom("InfiniteLeaftide"), "reset drops the world's rules");
Check.Eq(new IltAugCosts().For("InfiniteLeaftide").Multipliers[1], 4.0, "and the reset is saved");
}
private static void ByHandPriced()
{
Check.Eq(IltAttributeRaiser.ProjectCost(1_000, 1), 1_000L, "one level costs the reported cost");
// 1000 * (1.077^10 - 1) / 0.077 = 14,281.7 (UB's EstimateMultiLevelCost).
Check.Eq(IltAttributeRaiser.ProjectCost(1_000, 10), 14_281L, "ten levels grow 7.7% each");
Check.Eq(IltAttributeRaiser.ProjectCost(0, 10), 0L, "unknown cost projects nothing");
Check.Eq(IltAttributeRaiser.ProjectCost(long.MaxValue / 2, 10), long.MaxValue, "saturates instead of overflowing");
var settings = new LegacyUiSettings();
var hub = NewHub("InfiniteLeaftide", settings, "attr-byhand", out _);
var raiser = hub.Progression.Attributes;
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 5_000;
// Levels already known (as after the login probe), so the tab doesn't queue /aug ahead of /xp all.
hub.Progression.ApplyAugLines(new List<string> { "Creature: 1" });
// Opening the tab (a snapshot poll) reads the costs once per login.
var sb = new System.Text.StringBuilder();
hub.Progression.AppendSnapshotJson(sb);
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "the first snapshot reads the costs");
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 1,000",
"[XP] Your XP cost for next 1 Strength level is: 4,000");
TickUntil(hub, () => false, 400);
int reads = FakeHost.ChatCommands.Count(x => x == "/xp all");
hub.Progression.AppendSnapshotJson(new System.Text.StringBuilder());
TickUntil(hub, () => false, 400);
Check.Eq(FakeHost.ChatCommands.Count(x => x == "/xp all"), reads, "later snapshots don't read again");
sb.Clear();
raiser.AppendJson(sb);
string json = sb.ToString();
System.Text.Json.JsonDocument.Parse("{" + json + "}").Dispose();
Check.True(json.Contains("\"key\":\"coo\"") && json.Contains("\"afford1\":true") && json.Contains("\"cost10\":\"~14.3K\""),
$"Coordination: +1 affordable, +10 projected (got {json})");
Check.True(json.Contains("\"updated\":\"") && !json.Contains("\"updated\":\"-\""), "the last-updated time is set");
// +10 Coordination (~14.3K of 5K) is refused; +1 Strength (4K of 5K) goes out.
raiser.RaiseManual("coo", 10);
var status = new System.Text.StringBuilder();
raiser.AppendJson(status);
Check.True(status.ToString().Contains("Not enough unassigned XP"), "an unaffordable +10 is refused with the reason");
raiser.RaiseManual("str", 1);
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr str 1")), "an affordable +1 is sent");
Check.False(FakeHost.ChatCommands.Contains("/attr coo 10"), "the refused +10 was never sent");
}
private static void AugPlanner()
{
var settings = new LegacyUiSettings();
var hub = NewHub("InfiniteLeaftide", settings, "aug-planner", out _);
var prog = hub.Progression;
prog.AppendSnapshotJson(new System.Text.StringBuilder());
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "opening the tab pulls /aug once");
prog.ApplyAugLines(new List<string> { "Creature: 100", "Specialize: 2", "Summon: 0" });
prog.HandleRemote(new[] { "augtarget", "creature", "110" });
var sb = new System.Text.StringBuilder();
prog.AppendSnapshotJson(sb);
string json = sb.ToString();
using (var doc = System.Text.Json.JsonDocument.Parse("{" + json + "}"))
{
var aug = doc.RootElement.GetProperty("aug");
Check.Eq(aug.GetProperty("totCur").GetInt64(), 102L, "totals: current");
Check.Eq(aug.GetProperty("totTgt").GetInt64(), 112L, "totals: target");
Check.Eq(aug.GetProperty("totInc").GetInt64(), 10L, "totals: increase");
Check.Eq(aug.GetProperty("totCoins").GetInt64(), 30L, "Creature costs 3 coins a level");
var creature = aug.GetProperty("rows").EnumerateArray().First(x => x.GetProperty("key").GetString() == "creature");
Check.Eq(creature.GetProperty("inc").GetInt32(), 10, "row: increase");
string discord = aug.GetProperty("copyDiscord").GetString() ?? "";
Check.True(discord.StartsWith("```", StringComparison.Ordinal) && discord.Contains("TOTALS:") && discord.Contains("Creature"),
"Discord copy is a code-block table with totals");
Check.True(discord.All(ch => ch < 128), "copy text is ASCII (the engine reads the snapshot as ANSI)");
string ingame = aug.GetProperty("copyIngame").GetString() ?? "";
Check.True(ingame.Contains("Crit: 100") && ingame.Contains("Spec: 2") && !ingame.Contains("Sum:"),
$"in-game copy lists current levels with short names (got '{ingame}')");
}
prog.HandleRemote(new[] { "augreset" });
Check.Eq(hub.State.Character.AugTargets["creature"], 100, "reset targets: back to current");
Check.Eq(hub.State.Character.AugTargets["summon"], 0, "reset targets: unloaded augs go to 0");
Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 1, "levels loaded: no second automatic /aug");
}
private static void Patterns()
{
Check.True(ServerFeatureGate.Matches("InfiniteLeaftide", "InfiniteLeaftide"), "exact");
Check.True(ServerFeatureGate.Matches("infiniteleaftide", "InfiniteLeaftide"), "exact ignores case");
Check.False(ServerFeatureGate.Matches("InfiniteLeaftide2", "InfiniteLeaftide"), "exact means the whole name");
Check.True(ServerFeatureGate.Matches("Leaftide Test", "*Leaftide*"), "contains");
Check.True(ServerFeatureGate.Matches("MyLeaftide", "*tide"), "ends with");
Check.True(ServerFeatureGate.Matches("Leaftide-PTR", "Leaf*"), "starts with");
Check.True(ServerFeatureGate.Matches("Aelrynth Infinite", "Ael*Inf*"), "two wildcards");
Check.False(ServerFeatureGate.Matches("Aelrynth", "*Leaftide*"), "no match");
Check.False(ServerFeatureGate.Matches("ab", "a*bb"), "the end part must fit after the start");
Check.True(ServerFeatureGate.NameMatches("Aelrynth", new[] { "", "InfiniteLeaftide", "aelrynth" }, out string m) && m == "aelrynth",
"NameMatches reports the pattern that matched");
Check.False(ServerFeatureGate.NameMatches("", ServerFeatureGate.DefaultServerNames, out _), "an unknown world never matches");
}
private static void ListAndOverride()
{
var list = ServerFeatureGate.ParseList(" InfiniteLeaftide , *Leaftide*;Aelrynth,,aelrynth ");
Check.Eq(string.Join("|", list), "InfiniteLeaftide|*Leaftide*|Aelrynth", "trimmed, split on , and ;, de-duplicated ignoring case");
Check.Eq(ServerFeatureGate.FormatList(list), "InfiniteLeaftide, *Leaftide*, Aelrynth", "formatted back for the text box");
var s = new LegacyUiSettings();
Check.True(s.FeatureServerNames.Contains("InfiniteLeaftide"), "a fresh profile starts with the defaults");
Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s), "the default list covers InfiniteLeaftide");
Check.False(ServerFeatureGate.IsEnabled("Aelrynth", s), "another world is off by default");
s.ForceServerFeatures = true;
Check.True(ServerFeatureGate.IsEnabled("Aelrynth", s), "the manual override turns it on anywhere");
s.ForceServerFeatures = false;
s.FeatureServerNames = new List<string> { "Aelrynth" };
Check.True(ServerFeatureGate.IsEnabled("aelrynth", s), "a world added to the list is on");
Check.False(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s), "a world removed from the list is off");
Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", null), "no profile yet: the defaults apply");
}
private static readonly string[] Order = { "coo", "qui", "str", "end", "foc", "sel", "hea", "sta", "man" };
private static void PickModes()
{
var cost = new Dictionary<string, long> { ["coo"] = 500, ["qui"] = 300, ["str"] = 100 };
var ticked = new HashSet<string> { "coo", "qui", "str" };
int rr = 0;
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, ticked, cost, 1000, ref rr), "coo",
"priority: the first affordable stat in the order");
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, ticked, cost, 400, ref rr), "qui",
"priority: skips a stat it can't afford");
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, ticked, cost, 1000, ref rr), "str",
"cheapest: the lowest next-level cost");
var tie = new Dictionary<string, long> { ["coo"] = 100, ["str"] = 100 };
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, ticked, tie, 1000, ref rr), "coo",
"cheapest: a tie goes to the higher-priority stat");
rr = 0;
var picks = new List<string?>();
for (int i = 0; i < 4; i++) picks.Add(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 1000, ref rr));
Check.Eq(string.Join(",", picks), "coo,qui,str,coo", "round robin: one each in order, then around again");
rr = 0;
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 400, ref rr), "qui",
"round robin: an unaffordable stat is passed over");
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 400, ref rr), "str",
"round robin: carries on from the last pick");
}
private static void PickLimits()
{
var cost = new Dictionary<string, long> { ["coo"] = 500, ["qui"] = 300 };
int rr = 0;
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string>(), cost, 10_000, ref rr),
"nothing ticked: nothing raised");
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string> { "qui" }, cost, 10_000, ref rr), "qui",
"an unticked stat is never spent on, even at the top of the order");
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string> { "coo", "qui" }, cost, 0, ref rr),
"no budget (XP at or below the reserve): nothing raised");
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string> { "str" }, cost, 10_000, ref rr),
"a stat whose cost wasn't read is not raised blind");
var zero = new Dictionary<string, long> { ["coo"] = 0 };
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, new HashSet<string> { "coo" }, zero, 10_000, ref rr),
"a zero cost (unparsed) is not raised");
}
private static void OrderAndNames()
{
var repaired = IltAttributeRaiser.RepairOrder(new List<string> { "sel", "bogus", "Self", "Strength", "hea" });
Check.Eq(string.Join(",", repaired), "sel,str,hea,coo,qui,end,foc,sta,man",
"saved order kept, duplicates/junk dropped, missing stats appended in the default order");
Check.Eq(IltAttributeRaiser.RepairOrder(null).Count, 9, "a missing order becomes the default");
Check.Eq(string.Join(",", IltAttributeRaiser.RepairSelection(new List<string> { "Coordination", "coo", "x" })), "coo",
"selection: names map to abbreviations, duplicates and junk dropped");
Check.Eq(IltAttributeRaiser.Find("MaxHealth")?.Abbr, "hea", "cost line 'MaxHealth'");
Check.Eq(IltAttributeRaiser.Find("Maximum Stamina")?.Abbr, "sta", "'Maximum Stamina'");
Check.Eq(IltAttributeRaiser.Find("Self")?.Abbr, "sel", "Self");
Check.Eq(IltAttributeRaiser.Find("qui")?.Abbr, "qui", "abbreviation");
Check.Null(IltAttributeRaiser.Find("Luck"), "unknown names are rejected");
var cost = IltParse.XpCost.Match("[XP] Your XP cost for next 1 Coordination level is: 12,345,678");
Check.True(cost.Success && cost.Groups[1].Value == "Coordination" && IltParse.ParseLeadingLong(cost.Groups[2].Value) == 12_345_678,
"the /xp all cost line parses");
var raised = IltParse.AttrRaised.Match("[ATTR] Quickness attribute raised by 1, costing 9,876!");
Check.True(raised.Success && raised.Groups[1].Value == "Quickness" && raised.Groups[2].Value == "1"
&& IltParse.ParseLeadingLong(raised.Groups[3].Value) == 9876, "the /attr success line parses");
}
// ── The loop on the fake host ─────────────────────────────────────────────
private static IltHubController NewHub(string world, LegacyUiSettings settings, string folder, out RynthCoreHost host)
{
FakeHost.Reset();
FakeHost.WorldName = world;
host = FakeHost.Create(Player);
string dir = Path.Combine(Program.TempRoot, folder);
Directory.CreateDirectory(dir);
return new IltHubController(host, dir, () => null, () => settings, () => null, () => { });
}
/// <summary>Ticks the hub until <paramref name="done"/> or the timeout (the chat queue spaces sends by real time).</summary>
private static bool TickUntil(IltHubController hub, Func<bool> done, int timeoutMs = 6000)
{
var until = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (DateTime.UtcNow < until)
{
hub.Tick();
if (done()) return true;
Thread.Sleep(25);
}
return false;
}
private static void Reply(IltHubController hub, params string[] lines)
{
foreach (string l in lines) hub.OnChat(l);
}
private static void FullRun()
{
var settings = new LegacyUiSettings();
var hub = NewHub("InfiniteLeaftide", settings, "attr-run", out _);
var c = hub.State.Character;
c.AttrRaiseStats = new List<string> { "coo", "qui" };
c.AttrRaiseMode = (int)IltAttributeRaiser.Mode.Priority;
c.AttrKeepXp = 200;
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 2_500;
var raiser = hub.Progression.Attributes;
Check.Null(raiser.Blocker(), "an ILT world with /xp not reported off: the raiser can run");
raiser.Start(auto: false);
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "a run starts by reading the costs");
Reply(hub, "[XP] Your XP cost for next 1 Strength level is: 50",
"[XP] Your XP cost for next 1 Coordination level is: 1,000",
"[XP] Your XP cost for next 1 Quickness level is: 1,200");
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr coo 1")),
"priority: Coordination first (Strength is cheaper but not ticked)");
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 1_500;
Reply(hub, "[ATTR] Coordination attribute raised by 1, costing 1,000!");
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Count(x => x == "/xp all") >= 2), "costs are read again after each raise");
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 2,000",
"[XP] Your XP cost for next 1 Quickness level is: 1,200");
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr qui 1")),
"Coordination now costs more than the spendable 1,300: Quickness next");
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 300;
Reply(hub, "[ATTR] Quickness attribute raised by 1, costing 1,200!");
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Count(x => x == "/xp all") >= 3), "third cost read");
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 2,000",
"[XP] Your XP cost for next 1 Quickness level is: 1,500");
Check.True(TickUntil(hub, () => !raiser.Running), "nothing affordable above the reserve: the run ends");
Check.Eq(FakeHost.ChatCommands.Count(x => x.StartsWith("/attr", StringComparison.Ordinal)), 2, "exactly two raises sent");
string summary = FakeHost.Chat.LastOrDefault(x => x.Contains("Attribute raise")) ?? "";
Check.True(summary.Contains("Coordination +1") && summary.Contains("Quickness +1") && summary.Contains("2.2K"),
$"the run reports what it raised and spent (got '{summary}')");
var sb = new System.Text.StringBuilder();
raiser.AppendJson(sb);
string json = sb.ToString();
Check.True(json.StartsWith("\"attr\":{\"off\":false", StringComparison.Ordinal), "the Progression snapshot carries the raiser");
Check.True(json.Contains("\"key\":\"coo\"") && json.Contains("\"cost\":\"2.0K\""), "rows carry the last read costs");
System.Text.Json.JsonDocument.Parse("{" + json + "}").Dispose(); // throws if the JSON is malformed
// Panel commands: order, ticks, mode, reserve, a manual +10.
raiser.HandleRemote("attrmove", new[] { "attrmove", "qui", "up" });
Check.Eq(c.AttrOrder[0], "qui", "attrmove up");
raiser.HandleRemote("attron", new[] { "attron", "str", "on" });
Check.True(c.AttrRaiseStats.Contains("str"), "attron");
raiser.HandleRemote("attrmode", new[] { "attrmode", "2" });
Check.Eq(c.AttrRaiseMode, 2, "attrmode");
raiser.HandleRemote("attrkeep", new[] { "attrkeep", "1.5b" });
Check.Eq(c.AttrKeepXp, 1_500_000_000L, "attrkeep takes k/m/b suffixes");
raiser.HandleRemote("attrraise", new[] { "attrraise", "foc", "10" });
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr foc 10")), "a manual +10 sends /attr foc 10");
}
private static void Safety()
{
var settings = new LegacyUiSettings();
var hub = NewHub("InfiniteLeaftide", settings, "attr-safety", out _);
var c = hub.State.Character;
var raiser = hub.Progression.Attributes;
c.AttrRaiseStats = new List<string> { "coo", "qui" };
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 10_000;
// A cost seen earlier (passively, here by a hand-typed /xp all) is not trusted by a run:
// only the costs in the run's own read count.
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 100");
raiser.Start(auto: false);
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "run reads costs");
Reply(hub, "[XP] Your XP cost for next 1 Quickness level is: 500"); // Coordination missing this time
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Any(x => x.StartsWith("/attr", StringComparison.Ordinal))), "a raise is sent");
Check.Eq(FakeHost.ChatCommands.First(x => x.StartsWith("/attr", StringComparison.Ordinal)), "/attr qui 1",
"Coordination's older cost is not used when this read left it out");
// A reply about another stat (some other /attr sender) is not taken as our success.
Reply(hub, "[ATTR] Strength attribute raised by 1, costing 50!");
Check.True(TickUntil(hub, () => !raiser.Running), "a reply about another stat ends the run");
Check.Eq(FakeHost.ChatCommands.Count(x => x.StartsWith("/attr", StringComparison.Ordinal)), 1, "and nothing more is raised");
Check.False(FakeHost.Chat.Any(x => x.Contains("Attribute raise")), "and no raise is reported");
// The world leaves Server Features mid-run: the next step stops.
FakeHost.ChatCommands.Clear();
raiser.Start(auto: false);
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "second run reads costs");
settings.FeatureServerNames = new List<string> { "SomewhereElse" };
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 100");
Check.True(TickUntil(hub, () => !raiser.Running), "the run stops once the world is off");
Check.False(FakeHost.ChatCommands.Any(x => x.StartsWith("/attr", StringComparison.Ordinal)), "no raise after the gate closed");
settings.FeatureServerNames = new List<string>(ServerFeatureGate.DefaultServerNames);
// Another XP spender running: neither Raise now nor +N starts.
bool spending = true;
raiser.HoldOff = () => spending;
FakeHost.ChatCommands.Clear();
raiser.Start(auto: false);
raiser.RaiseManual("coo", 1);
TickUntil(hub, () => false, 600);
Check.False(raiser.Running, "held off: Raise now doesn't start");
Check.False(FakeHost.ChatCommands.Any(), "held off: nothing is sent");
}
private static void GatedOff()
{
var settings = new LegacyUiSettings();
var hub = NewHub("Aelrynth", settings, "attr-gated", out _);
var raiser = hub.Progression.Attributes;
hub.State.Character.AttrRaiseStats = new List<string> { "coo" };
Check.NotNull(raiser.Blocker(), "a world not in the list: blocked");
raiser.Start(auto: false);
TickUntil(hub, () => false, 600);
Check.False(FakeHost.ChatCommands.Any(), "nothing is sent off a feature world");
settings.FeatureServerNames.Add("Aelrynth");
Check.Null(raiser.Blocker(), "adding the world to Server Features unblocks it");
settings.FeatureServerNames.Remove("Aelrynth");
settings.ForceServerFeatures = true;
Check.Null(raiser.Blocker(), "so does the manual override");
}
}

View file

@ -0,0 +1,66 @@
using RynthCore.Plugin.RynthAi.IltHub;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Banking tab (IltBankCommands): the deposit / withdraw commands match ACECustom's /bank handler
// (upstream 2026-10-11), and only the bank's own reply lines count as a deposit / withdraw result.
internal static class BankCommandTests
{
public static void Register(Runner r)
{
r.Add("bank: deposit commands (everything, one kind, luminance tokens)", Deposits);
r.Add("bank: withdraw commands, trade notes by denomination and count", Withdrawals);
r.Add("bank: withdraw input is checked before anything is sent", WithdrawRefusals);
r.Add("bank: reply lines are recognised, balance and chat lines are not", Replies);
}
private static int DepositIndex(string args) =>
System.Array.FindIndex(IltBankCommands.Deposits, d => d.Args == args);
private static int WithdrawIndex(string code) =>
System.Array.FindIndex(IltBankCommands.Withdrawals, w => w.Code == code);
private static void Deposits()
{
Check.Eq(IltBankCommands.Deposit(0), "/b d", "Everything is a plain deposit");
Check.Eq(IltBankCommands.Deposit(DepositIndex("p")), "/b d p", "pyreals");
Check.Eq(IltBankCommands.Deposit(DepositIndex("pc")), "/b d pc", "prestige coins");
Check.Eq(IltBankCommands.Deposit(DepositIndex("lum")), "/b lum", "luminance tokens use /b lum");
Check.Eq(IltBankCommands.Deposit(-1), "", "unknown index sends nothing");
Check.Eq(IltBankCommands.Deposit(IltBankCommands.Deposits.Length), "", "past the end sends nothing");
}
private static void Withdrawals()
{
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("p"), 1_500_000, 0, out _), "/b w p 1500000", "pyreals");
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("pc"), 3, 0, out _), "/b w pc 3", "prestige coins");
int mmd = System.Array.FindIndex(IltBankCommands.NoteDenominations, n => n.Code == "mmd");
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), 5, mmd, out _), "/b w n mmd 5", "five 250K notes");
}
private static void WithdrawRefusals()
{
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("p"), 0, 0, out string e1), "", "zero refused");
Check.True(e1.Length > 0, "zero says why");
Check.Eq(IltBankCommands.Withdraw(-1, 10, 0, out _), "", "no currency refused");
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), 10, 99, out _), "", "bad denomination refused");
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), IltBankCommands.MaxNoteCount + 1, 0, out string e2), "",
"more notes than the server allows refused");
Check.True(e2.Contains("50,000"), "says the limit");
}
private static void Replies()
{
Check.True(IltBankCommands.IsActionReply("Deposited 12,345 pyreals"), "deposit");
Check.True(IltBankCommands.IsActionReply("No pyreal peas found to deposit"), "nothing to deposit");
Check.True(IltBankCommands.IsActionReply("Withdrew 2 prestige coins"), "withdraw");
Check.True(IltBankCommands.IsActionReply("Starting Banked Lum: 5B (5,000,000,000)"), "token deposit start");
Check.True(IltBankCommands.IsActionReply("[Withdraw] This command may only be run once every 5 seconds."), "throttled");
Check.True(IltBankCommands.IsActionReply("You don't have enough luminance banked. Need 10 but only have 5."), "short");
Check.False(IltBankCommands.IsActionReply("[BANK] Pyreals: 1,000"), "a balance line is not an action reply");
Check.False(IltBankCommands.IsActionReply("No one is near."), "other 'No ...' lines are not");
Check.False(IltBankCommands.IsActionReply("Bob tells you, \"Deposited 5 pyreals\""), "a tell is not");
Check.False(IltBankCommands.IsActionReply(""), "empty");
}
}

View file

@ -0,0 +1,363 @@
using System;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Buff cast chaining (Combat/BuffCastChain.cs). In a buff pass the next buff waited
// ~550 ms after the server's UseDone for the last one, held by the animation gate while the client
// played the recoil ("[Pace] Buff waits: the character is still animating"). On ACE the server
// takes the next cast right after that UseDone. The fast path skips the animation gate only, only
// right after our own buff's UseDone(0), and a refusal turns it off for the rest of the pass.
// FakeHost.CastBusy = 1 stands for "the client is still animating the recoil".
internal static class BuffChainTests
{
private const uint Player = 0x50000C01;
private const uint Corpse = 0x80068ACF;
private const uint STypeLife = 33;
private const uint TooBusy = 0x1D;
public static void Register(Runner r)
{
r.Add("buff chain: the next buff goes on the last buff's UseDone(0) while the recoil animates; setting off = waits", NextBuffOnUseDone);
r.Add("buff chain: the animation gate is kept after a non-cast action, after a UseDone error, and past the window", GateKept);
r.Add("buff chain: a refused fast-path cast turns it off for the rest of the pass; refusals counted and summed up", RefusalFallsBack);
r.Add("buff chain: FastBuffChain defaults on, loads on from an old profile and copies", SettingDefaults);
r.Add("buff chain: no Stamina to Mana for the mana reserve on the fast path; it waits for the animation, then goes", ManaReserveWaitsForAnimation);
r.Add("buff chain: a stop or turn after the last buff sends the next one through the animation gate (no buff 50 ms after a nav stop); no movement = fast path", MovementWaitsForAnimation);
}
// A buff went out 50 ms after StopCompletelyBy("Nav"): the stop starts a motion the client
// still has to play, so a movement call after the last buff turns the fast path off for the
// next buff, which then waits on the animation gate like any other.
private static void MovementWaitsForAnimation() => Paced(() =>
{
// Control: the same sequence with no movement in between takes the fast path.
var c = FirstBuffOut();
c.ServerRuns(0);
c.Tick(1.55);
Check.Eq(FakeHost.Casts.Count, 2, "no movement: the next buff goes on the UseDone(0)");
Check.Eq(c.B.Chain.FastCasts, 1, "no movement: on the fast path");
Check.Eq(c.B.Chain.MovementWaits, 0, "no movement: no movement wait");
var r = FirstBuffOut();
r.ServerRuns(0);
r.At(1.5);
Check.True(r.Host.StopCompletelyBy("Nav"), "nav's stop goes out");
r.Tick(1.55);
Check.Eq(FakeHost.Casts.Count, 1, "50 ms after the stop: the next buff waits for the animation");
Check.Eq(r.B.Chain.FastCasts, 0, "not on the fast path");
Check.Eq(r.B.Chain.MovementWaits, 1, "one movement wait counted");
// Held by the animation gate, or first by the movement settle (ActionPacer/MoveAudit, PR #14:
// 150 ms after a movement change and until the motion queue is clear), which covers the same
// 50 ms window. Either way the fast path does not skip it.
Check.True(Logged("[Pace] Buff waits: the character is still animating") || Logged("[Pace] Buff waits: the movement change StopCompletely()"),
"held by the animation gate or the movement settle");
r.Tick(1.65);
Check.Eq(r.B.Chain.MovementWaits, 1, "counted once per buff, not per tick");
FakeHost.CastBusy = 0;
r.Tick(1.75);
Check.Eq(FakeHost.Casts.Count, 2, "the animation over: the buff goes through the normal gate");
Check.Eq(r.B.Chain.FastCasts, 0, "still nothing on the fast path");
// A turn counts the same as a stop.
var t = FirstBuffOut();
t.ServerRuns(0);
t.At(1.5);
Check.True(t.Host.TurnToHeadingBy("Nav", 90f), "nav's turn goes out");
t.Tick(1.55);
Check.Eq(FakeHost.Casts.Count, 1, "50 ms after a turn: the next buff waits for the animation");
Check.Eq(t.B.Chain.MovementWaits, 1, "a movement wait");
// Stops sent while the buff is still unanswered are held (MoveAudit pending stops), not sent:
// no movement is counted yet, and the next cast would flush them inside itself. A held stop
// keeps the fast path off; the buff waits for the animation.
var h = FirstBuffOut();
h.At(0.5);
for (int i = 0; i < 5; i++) h.Host.StopCompletelyBy("Nav");
Check.True(MoveAudit.HasPendingStop, "the stops are held while the buff is unanswered");
h.ServerRuns(0);
h.Tick(1.55);
Check.Eq(FakeHost.Casts.Count, 1, "a held stop: the next buff waits for the animation");
Check.Eq(h.B.Chain.FastCasts, 0, "a held stop: not on the fast path");
FakeHost.CastBusy = 0;
h.Tick(1.75);
Check.Eq(FakeHost.Casts.Count, 2, "the animation over: the buff goes");
Check.Eq(h.B.Chain.FastCasts, 0, "and not on the fast path");
});
// The fast path skips the animation gate, so only the buff may ride it. Mana spent by the last
// buff can leave the next one under the mana reserve (BuffWaitsForMana): Stamina to Mana is then
// cast first, and it must wait for the recoil like any vital cast.
// 50/300: under the reserve itself (the vitals check keeps the fast path off);
// 120/300: over the reserve, but under it once the next buff's 60 is paid (the cast site drops
// the fast path for that buff).
private static void ManaReserveWaitsForAnimation() => Paced(() =>
{
foreach (uint after in new uint[] { 50, 120 })
{
var r = new Rig(staminaToMana: true);
BuffManager.ManaCostOverride = id => (SpellTableStub.GetById(id)?.Level ?? 0) * 10; // after Reset: level x 10
r.S.GetManaAt = 10; r.S.TopOffMana = 10;
r.V.MaxMana = 300; r.V.CurrentMana = 300;
int reserve = r.B.ManaReserve();
Check.Eq(reserve, 90, "the reserve (1.5 x Stamina to Mana VI's 60)");
r.Tick(0);
Check.Eq(FakeHost.Casts.Count, 1, $"{after}: the first buff goes at 300/300");
Check.True(!r.LastCast.StartsWith("Stamina to Mana", StringComparison.Ordinal), $"{after}: and it is a buff ({r.LastCast})");
r.V.CurrentMana = after; // what the buffs so far left
r.ServerRuns(0); // CastBusy = 1: the recoil still animating
r.Tick(1.55);
Check.Eq(FakeHost.Casts.Count, 1, $"{after}/300, 50 ms after the UseDone: nothing goes during the recoil");
Check.Eq(r.B.Chain.FastCasts, 0, $"{after}: nothing on the fast path");
r.Tick(1.65);
Check.Eq(FakeHost.Casts.Count, 1, $"{after}: still nothing while it animates");
FakeHost.CastBusy = 0;
r.Tick(1.75);
Check.Eq(FakeHost.Casts.Count, 2, $"{after}: the animation over, one cast");
Check.True(r.LastCast.StartsWith("Stamina to Mana", StringComparison.Ordinal), $"{after}: it is Stamina to Mana ({r.LastCast})");
}
});
private static long _t;
private sealed class Rig
{
public DateTime T0 = new(2026, 10, 10, 14, 0, 0);
public DateTime NowAt;
public readonly BuffManager B;
public readonly LegacyUiSettings S;
public readonly RynthCoreHost Host;
public readonly PlayerVitalsCache V;
public Rig(bool fast = true, bool staminaToMana = false)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.SalvageCalls = true;
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.UseOnCalls = true;
FakeHost.CombatModeCalls = true;
FakeHost.StopCalls = true;
FakeHost.BusyCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
FakeHost.Names[Corpse] = "Corpse of Drudge Skulker";
FakeHost.Bitfields[Corpse] = 0x2000;
foreach (string n in new[] { "Fire Protection Self VI", "Cold Protection Self VI", "Acid Protection Self VI" })
foreach (var row in SpellTable.Named(n)) FakeHost.Spellbook.Add((uint)row.Id);
if (staminaToMana)
foreach (var row in SpellTable.Rows.Where(x => x.Name.StartsWith("Stamina to Mana Self", StringComparison.Ordinal)))
FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (300, 2);
Host = FakeHost.Create(Player);
S = new LegacyUiSettings
{
IsMacroRunning = true, EnableBuffing = true, FastBuffChain = fast, SpellCastIntervalMs = 0,
};
var skills = new CharacterSkills(Host);
skills.SetPlayerId(Player);
var sm = new SpellManager(Host, S);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
V = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
B = new BuffManager(Host, S, sm, V);
B.SetCharacterSkills(skills);
NowAt = T0;
B.Clock = () => NowAt;
B.MarkLiveBuffsReadyForTests();
FakeHost.ServerTime = 100_000;
_t = 10_000_000;
ActionPacer.NowMs = () => _t + (long)(NowAt - T0).TotalMilliseconds;
MoveAudit.NowMs = ActionPacer.NowMs;
// Each rig restarts the clock at T0: the previous rig's movement (MoveAudit's settle,
// PR #14) and pacer state would otherwise sit in this rig's future and hold it.
MoveAudit.Reset();
ActionPacer.Reset();
}
public void At(double seconds) => NowAt = T0.AddSeconds(seconds);
public void Tick(double seconds) { At(seconds); B.OnHeartbeat(); }
public string LastCast => SpellTable.ById(FakeHost.Casts.Last().SpellId)?.Name ?? "";
/// <summary>The server runs the last cast: incantation, result line, then (on ACE) the
/// recoil, then UseDone(err). The client is still animating when the UseDone arrives.</summary>
public void ServerRuns(double sentAt, uint err = 0)
{
string name = LastCast;
At(sentAt + 0.1); B.OnChatWindowText("You say, \"Zojak Tugeth\"", 17);
FakeHost.CastBusy = 1;
At(sentAt + 1.0); B.OnChatWindowText($"You cast {name} on yourself", 7);
At(sentAt + 1.5);
FakeHost.UseDone(err);
}
}
private static void PaceOn()
{
ActionPacer.Reset();
ActionPacer.Enabled = true;
UseAudit.Reset("RynthAi", () => true);
MoveAudit.Reset();
var rec = typeof(RynthAiPlugin).GetMethod("RecordUseForPacing",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)!;
UseAudit.AfterSend = (h, u) => rec.Invoke(null, new object[] { h, u });
}
private static void PaceOff()
{
ActionPacer.Enabled = false;
ActionPacer.Reset();
ActionPacer.NowMs = () => Environment.TickCount64;
UseAudit.Reset("?", null);
UseAudit.NowMs = () => Environment.TickCount64;
MoveAudit.Reset();
MoveAudit.NowMs = () => Environment.TickCount64;
}
private static void Paced(Action body)
{
PaceOn();
try { body(); }
finally { PaceOff(); }
}
private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
/// <summary>First buff of a pass on a quiet client: it goes on the first tick.</summary>
private static Rig FirstBuffOut(bool fast = true)
{
var r = new Rig(fast);
r.Tick(0);
Check.Eq(FakeHost.Casts.Count, 1, "the first buff of the pass goes out");
return r;
}
private static void NextBuffOnUseDone() => Paced(() =>
{
var r = FirstBuffOut();
string first = r.LastCast;
r.ServerRuns(0);
r.Tick(1.55); // 50 ms after the UseDone, the recoil still animating
Check.Eq(FakeHost.Casts.Count, 2, "the next buff goes on the UseDone(0), the recoil still animating");
Check.True(r.LastCast != first, $"and it is the next buff ({first} then {r.LastCast})");
Check.True(Logged("[BuffChain] '" + r.LastCast + "' goes without waiting for the animation"), "the fast path is logged");
Check.Eq(r.B.Chain.FastCasts, 1, "one buff on the fast path");
// The same sequence with the setting off: the buff waits for the animation, as before.
var q = FirstBuffOut(fast: false);
q.ServerRuns(0);
for (double s = 1.55; s < 2.05; s += 0.1) q.Tick(s);
Check.Eq(FakeHost.Casts.Count, 1, "setting off: no buff while the recoil animates");
Check.True(Logged("[Pace] Buff waits: the character is still animating"), "held by the animation gate, as in the log");
FakeHost.CastBusy = 0;
q.Tick(2.1);
Check.Eq(FakeHost.Casts.Count, 2, "setting off: the buff goes once the animation is over");
Check.Eq(q.B.Chain.FastCasts, 0, "nothing on the fast path");
});
private static void GateKept() => Paced(() =>
{
// A corpse use went out after the buff (a non-cast action) and was answered: the next buff
// is the first after a non-cast action, so it waits for the animation.
// The buff's UseDone(0) is read on a tick the busy count holds (nothing goes), then the corpse
// use goes out and is answered.
var r = FirstBuffOut();
r.ServerRuns(0);
r.B.BusyCount = 1;
r.Tick(1.52);
Check.Eq(FakeHost.Casts.Count, 1, "the busy count holds this tick");
r.B.BusyCount = 0;
Check.True(r.Host.UseFor(Corpse, "Loot", "open the claimed corpse"), "a corpse use goes out");
FakeHost.UseDone(0);
for (double s = 1.6; s < 2.1; s += 0.1) r.Tick(s);
Check.Eq(FakeHost.Casts.Count, 1, "after a non-cast action: the buff waits for the animation");
FakeHost.CastBusy = 0;
r.Tick(2.2);
Check.Eq(FakeHost.Casts.Count, 2, "and goes when the animation is over");
// A swing went out after the buff's UseDone(0) (no UseDone of its own): the gate is kept.
var a = FirstBuffOut();
a.ServerRuns(0);
a.B.BusyCount = 1;
a.Tick(1.52);
a.B.BusyCount = 0;
ActionPacer.NoteAttackSent();
for (double s = 1.6; s < 2.1; s += 0.1) a.Tick(s);
Check.Eq(FakeHost.Casts.Count, 1, "after a swing: the buff waits for the animation");
// A UseDone with an error for the buff: no fast path (and a server refusal counted).
var e = FirstBuffOut();
e.ServerRuns(0, err: TooBusy);
for (double s = 1.55; s < 2.05; s += 0.1) e.Tick(s);
Check.Eq(FakeHost.Casts.Count, 1, "after a UseDone error: the buff waits for the animation");
Check.Eq(e.B.Chain.ServerRefusals, 1, "the error is counted as a server refusal");
Check.True(Logged("[BuffChain] refusal (server): UseDone error 0x1D"), "and logged");
// The UseDone(0) was read, but the client still reads busy past the window: not the recoil.
var w = FirstBuffOut();
w.ServerRuns(0);
w.B.BusyCount = 1; // something else holds the busy count meanwhile: the busy gate holds
w.Tick(1.52);
Check.Eq(FakeHost.Casts.Count, 1, "the busy gate is kept on the fast path");
w.B.BusyCount = 0;
w.Tick(1.52 + BuffCastChain.WindowMs / 1000.0 + 0.1);
Check.Eq(FakeHost.Casts.Count, 1, "past the window after the UseDone: the animation gate again");
});
private static void RefusalFallsBack() => Paced(() =>
{
var r = FirstBuffOut();
r.ServerRuns(0);
// The client refuses the fast-path cast: nothing goes out.
FakeHost.CastRefused = true;
r.Tick(1.55);
Check.Eq(FakeHost.CastsRefused, 1, "the fast-path cast was tried and the client refused it");
Check.Eq(r.B.Chain.ClientRefusals, 1, "counted as a client refusal");
Check.True(Logged("[BuffChain] refusal (client): CastSpell refused"), "logged");
Check.True(r.B.Chain.OffThisPass, "the fast path is off for the rest of the pass");
Check.True(Logged("the next buffs of this pass wait for the animation again"), "and that is logged");
FakeHost.CastRefused = false;
// The next buff waits for the animation, even right after a buff's UseDone(0).
FakeHost.CastBusy = 0;
r.Tick(1.7);
Check.Eq(FakeHost.Casts.Count, 2, "gate open: the buff goes");
double sent = 1.7;
r.ServerRuns(sent);
for (double s = sent + 1.55; s < sent + 2.05; s += 0.1) r.Tick(s);
Check.Eq(FakeHost.Casts.Count, 2, "after the refusal: the next buff waits for the animation");
FakeHost.CastBusy = 0;
r.Tick(sent + 2.1);
Check.Eq(FakeHost.Casts.Count, 3, "and goes when it ends");
// The pass ends: one summary line with this pass's refusals.
r.ServerRuns(sent + 2.1);
FakeHost.CastBusy = 0;
for (double s = sent + 3.7; s < sent + 6; s += 0.2) r.Tick(s);
Check.True(Logged("[BuffChain] buff pass complete:"), "a summary line at the end of the pass");
Check.True(Logged("refusals this pass: client 1, server 0"), "with its refusals: " +
(FakeHost.Logs.LastOrDefault(l => l.Contains("[BuffChain] buff pass")) ?? "(none)"));
});
private static void SettingDefaults()
{
Check.True(new LegacyUiSettings().FastBuffChain, "a new profile: on");
var old = System.Text.Json.JsonSerializer.Deserialize("{\"EnableBuffing\":true}", RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(old != null && old.FastBuffChain, "a profile saved before the setting: on");
var off = System.Text.Json.JsonSerializer.Deserialize(
System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings { FastBuffChain = false }, RynthAiJsonContext.Default.LegacyUiSettings),
RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(off != null && !off.FastBuffChain, "off is saved and loaded");
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)!;
var dst = new LegacyUiSettings();
copy.Invoke(null, new object[] { new LegacyUiSettings { FastBuffChain = false }, dst });
Check.False(dst.FastBuffChain, "a profile with it off loads off");
}
}

File diff suppressed because it is too large Load diff

View file

@ -39,6 +39,230 @@ internal static class CastSafetyTests
r.Add("cast safety: any held cast is nudged early while health is under a heal line; not when health is fine", UrgentNudgeForLowHealth);
r.Add("cast safety: no kit or potion while a cast is held open until its nudge, then one try per 3 s", HeldCastItemGate);
r.Add("move audit: one line per call, repeats counted, subsystem in the line", MoveAuditLines);
r.Add("cast safety: a script heal's 'due to casting' result closes the cast, so no early nudge steps the character forward", TransferResultClosesCast);
r.Add("cast safety: a script heal takes no early nudge: a 2.75 s result or a 3.8 s UseDone sees no autorun before 6 s", ScriptHealNoEarlyNudge);
r.Add("cast safety: a script heal's 'resists your spell' closes its cast", ScriptHealResisted);
r.Add("cast safety: another caster's transfer and the drain line leave the script heal pending", TransferLinesNotOurs);
r.Add("cast safety: extra 'due to casting' lines after the cast closed resolve nothing and record no timer", ExtraTransferLines);
r.Add("cast safety: a 'due to casting' line for no open cast is read only when it names the pending spell", StrayTransferLine);
}
// 2026-10-10 log (RynthCore.40732.log): the BloodMage script's Vitality Siphon reports
// "You gain N points of health due to casting Vitality Siphon on <monster>". The result
// matcher only read "ou cast ", so the heal stayed held and the early heal nudge (autorun on,
// off) went out 2.8 s after the incantation, mid-cast: 13 of the session's 14 nudges.
private static void TransferResultClosesCast()
{
foreach (bool withResult in new[] { false, true })
{
string what = withResult ? "result line read" : "control, no result line";
try
{
var r = StartScriptSiphon(what);
r.At(0.2); r.Incantation();
if (withResult)
{
r.At(2.5); r.Chat("You gain 51 points of health due to casting Vitality Siphon on Doorheld Surveyor", 7);
Check.Eq(r.B.PendingSpellId, 0, "result line read: the pending heal is resolved");
Check.True(r.Logged("via due-to-casting match"), "result line read: the CLEARED line names the branch that matched");
}
r.At(3.1); r.B.OnHeartbeat();
Check.Eq(FakeHost.AutoRunCalls.Count, 0, $"{what}: a script heal takes no early nudge");
// Held past 6 s while AC refuses: the normal nudge, unless the result closed the cast.
r.At(7.0); r.Chat("You're too busy!");
if (withResult)
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "result line read: the cast is closed, nothing moves the character");
else
Check.True(FakeHost.AutoRunCalls.SequenceEqual(new[] { true, false }), "control: the unanswered heal is still held at 6.8 s and nudged on the refusal");
}
finally { CombatHook.Reset(); }
}
}
private static int SiphonId => SpellTable.Named("Vitality Siphon").Select(x => x.Id).First();
/// <summary>A rig at 50% health (heal line 60) whose script hook chose Vitality Siphon, sent at 0 s.
/// The caller resets CombatHook.</summary>
private static Rig StartScriptSiphon(string what)
{
var r = new Rig();
MoveAudit.Reset();
CombatHook.Reset();
r.S.HealAt = 60; r.S.TopOffHP = 60;
r.V.CurrentHealth = 50; r.V.CurrentMana = 100;
// The script seam checks the known-spell snapshot (this rig never refreshed it).
((SpellManager)typeof(BuffManager).GetField("_spellManager", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!
.GetValue(r.B)!).RefreshKnownSpells();
CombatHook.Claim(RynthAiCombat.KindHeal, 0, 0, 0, "test");
r.At(0);
Check.True(r.B.CheckVitals(), $"{what}: waiting for the script's heal");
Check.True(CombatHook.Poll(RynthAiCombat.KindHeal, out var req), $"{what}: a heal request is open");
CombatHook.Decide(req.Seq, RynthAiCombat.KindHeal, (uint)SiphonId, 0, 0);
r.B.CheckVitals();
Check.Eq(r.CastName, "Vitality Siphon", $"{what}: the script's Vitality Siphon is cast");
return r;
}
/// <summary>Heartbeats every 100 ms over [from, to] seconds.</summary>
private static void Tick(Rig r, double from, double to)
{
for (int i = 0; from + i * 0.1 <= to + 1e-9; i++) { r.At(from + i * 0.1); r.B.OnHeartbeat(); }
}
// 2026-10-10 log: real Vitality Siphon results came 2.75, 2.45 and 2.42 s after the incantation,
// against the 2.8 s early heal nudge. A script-chosen heal waits the normal 6 s instead.
private static void ScriptHealNoEarlyNudge()
{
try
{
// Incantation lag (1.0 s after the send), result line 2.75 s after the incantation.
var r = StartScriptSiphon("late result");
r.At(1.0); r.Incantation();
Tick(r, 1.1, 3.7);
r.At(3.75); r.Chat("You gain 51 points of health due to casting Vitality Siphon on Doorheld Surveyor", 7);
Check.Eq(r.B.PendingSpellId, 0, "late result: read at 2.75 s");
Tick(r, 3.8, 6.9);
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "late result: no AutoRun call before 6 s after the incantation");
// No result line at all; the server's UseDone(0) 3.8 s after the incantation ends it.
var q = StartScriptSiphon("UseDone only");
q.At(1.0); q.Incantation();
Tick(q, 1.1, 4.7);
q.At(4.8); FakeHost.UseDone(0);
Tick(q, 4.8, 6.9);
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "UseDone only: no AutoRun call before 6 s after the incantation");
Check.True(q.Logged("'Vitality Siphon': UseDone #"), "UseDone only: the UseDone closed the cast");
}
finally { CombatHook.Reset(); }
// Control: RynthAi's own Heal Self with no result is still nudged at 2.8 s.
var h = new Rig();
MoveAudit.Reset();
h.S.HealAt = 60; h.S.TopOffHP = 60;
h.V.CurrentHealth = 50; h.V.CurrentMana = 100;
h.At(0); h.B.CheckVitals();
Check.True(CastIs("Heal Self"), "control: Heal Self is cast");
h.At(0.2); h.Incantation();
Tick(h, 0.3, 2.9);
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "control: no nudge 2.7 s after the incantation");
h.At(3.1); h.B.OnHeartbeat();
Check.True(FakeHost.AutoRunCalls.SequenceEqual(new[] { true, false }), "control: RynthAi's own heal is nudged at 2.8 s");
}
// A resisted transfer prints "<monster> resists your spell" and no "due to casting" line.
private static void ScriptHealResisted()
{
try
{
int resolves = 0;
var r = StartScriptSiphon("resisted");
r.B.SetCastResolvedCallback(_ => resolves++);
r.At(0.2); r.Incantation();
r.At(2.5); r.Chat("Doorheld Surveyor resists your spell", 7);
Check.Eq(r.B.PendingSpellId, 0, "resisted: the pending heal is resolved");
Check.Eq(resolves, 1, "resisted: resolved once");
Check.True(r.Logged("'Vitality Siphon': resisted"), "resisted: [CastTime] closes the cast as resisted");
r.At(7.0); r.Chat("You're too busy!");
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "resisted: the cast is closed, so a later refusal sends no nudge");
}
finally { CombatHook.Reset(); }
// RynthAi's own cast is not closed by a resist line (it can't be one of its transfers).
var h = new Rig();
h.S.HealAt = 60; h.S.TopOffHP = 60;
h.V.CurrentHealth = 50; h.V.CurrentMana = 100;
h.At(0); h.B.CheckVitals();
int pending = h.B.PendingSpellId;
h.At(0.2); h.Incantation();
h.At(1.0); h.Chat("Doorheld Surveyor resists your spell", 7);
Check.Eq(h.B.PendingSpellId, pending, "own Heal Self: a resist line leaves it pending");
}
// Lines that name a transfer but are not the result of our cast.
private static void TransferLinesNotOurs()
{
try
{
var r = StartScriptSiphon("not ours");
int pending = r.B.PendingSpellId;
Check.True(pending != 0, "the Siphon is pending");
r.At(0.2); r.Incantation();
foreach (string line in new[]
{
"You lose 12 points of mana due to Zofrit Zefir casting Drain Mana Other II on you",
// ACE WorldObject_Magic.cs:1370, a fellow's transfer shared with us.
"You gain 51 points of health due to Zofrit Zefir casting Vitality Siphon on Doorheld Surveyor",
"With Vitality Siphon you drain 51 points of Health from Doorheld Surveyor.",
})
{
r.At(1.0); r.Chat(line, 7);
Check.Eq(r.B.PendingSpellId, pending, $"'{line}': pending unchanged");
}
r.At(2.5); r.Chat("You gain 51 points of health due to casting Vitality Siphon on Doorheld Surveyor", 7);
Check.Eq(r.B.PendingSpellId, 0, "our own line still resolves it");
}
finally { CombatHook.Reset(); }
}
// Crimson Harvest prints several "due to casting" lines for one cast: only the first is its result.
private static void ExtraTransferLines()
{
try
{
int resolves = 0;
var r = StartScriptSiphon("extra lines");
r.B.SetCastResolvedCallback(_ => resolves++);
r.At(0.2); r.Incantation();
r.At(2.5); r.Chat("You gain 51 points of health due to casting Vitality Siphon on Doorheld Surveyor", 7);
Check.Eq(resolves, 1, "the first line resolves the cast");
var timers = (System.Collections.IDictionary)typeof(BuffManager)
.GetField("_ramBuffTimers", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.GetValue(r.B)!;
timers.Clear();
r.At(2.6); r.Chat("You gain 20 points of health due to casting Vitality Siphon on Doorheld Surveyor", 7);
Check.Eq(resolves, 1, "the second line resolves nothing");
Check.Eq(timers.Count, 0, "the second line records no timer");
}
finally { CombatHook.Reset(); }
}
private static System.Collections.IDictionary RamTimers(Rig r) => (System.Collections.IDictionary)typeof(BuffManager)
.GetField("_ramBuffTimers", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.GetValue(r.B)!;
// A "due to casting" line for no open cast is read only when it names the pending spell.
private static void StrayTransferLine()
{
// Another spell pending (RynthAi's Stamina to Mana); a stray line from a drain attack
// CombatManager cast (never tracked by BuffManager).
var r = new Rig();
int resolves = 0;
r.B.SetCastResolvedCallback(_ => resolves++);
r.At(0); r.B.CheckVitals();
int pending = r.B.PendingSpellId;
Check.True(pending != 0, "Stamina to Mana is pending");
r.At(0.3); r.Incantation();
var timers = RamTimers(r);
timers.Clear();
r.At(1.0); r.Chat("You gain 52 points of health due to casting Drain Health Other I on Olthoi Warrior", 7);
Check.Eq(r.B.PendingSpellId, pending, "stray drain line: pending unchanged");
Check.Eq(timers.Count, 0, "stray drain line: no timer recorded");
Check.Eq(resolves, 0, "stray drain line: nothing resolved");
// The pending spell's own line after its cast already closed (a UseDone came first).
try
{
var q = StartScriptSiphon("closed first");
int qResolves = 0;
q.B.SetCastResolvedCallback(_ => qResolves++);
q.At(0.2); q.Incantation();
q.At(2.0); FakeHost.UseDone(0); q.B.OnHeartbeat();
Check.True(q.Logged("'Vitality Siphon': UseDone #"), "closed first: the UseDone closed the cast");
int qPending = q.B.PendingSpellId;
Check.True(qPending != 0, "closed first: the Siphon is still pending");
q.At(2.4); q.Chat("You gain 51 points of health due to casting Vitality Siphon on Doorheld Surveyor", 7);
Check.Eq(q.B.PendingSpellId, 0, "closed first: the line naming the pending spell still resolves it");
Check.Eq(qResolves, 1, "closed first: resolved once");
}
finally { CombatHook.Reset(); }
}
private sealed class Rig

View file

@ -0,0 +1,408 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-10-12: with Looting on, a chest the player or a meta opened is looted by the corpse
// looter (RynthAiPlugin.ChestLoot.cs): matching items picked up, the rest left, no walk and no
// open, closed when done, never marked done for good (chests regenerate). Not the player's own
// packs, not house storage, nothing with Looting off.
internal static class ChestLootTests
{
private const uint Player = 0x50000D01;
private const uint Chest = 0x7A9B4001; // a landblock chest (static id)
private const uint Gem = 0x80263101;
private const uint Spoon = 0x80263102;
private const uint Gem2 = 0x80263103;
private const uint Cap = 0x80263104;
private const uint SidePack = 0x80263200;
private const uint PackGem = 0x80263201;
private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800, ItemTypeMisc = 0x80, ItemTypeArmor = 0x2;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("chest loot: an opened chest's matching items are picked up, the rest left; no walk, no open, closed when done", OpenedChestLooted);
r.Add("chest loot: your own side pack opened -> nothing taken", OwnSidePackNotLooted);
r.Add("chest loot: house storage (HouseOwner set) -> nothing taken", HouseStorageNotLooted);
r.Add("chest loot: house storage by name (engine without the HouseOwner read) -> nothing taken", HouseStorageByNameNotLooted);
r.Add("chest loot: Looting off -> nothing taken, the loot check still runs", LootingOffNothing);
r.Add("chest loot: reopening the chest loots it again (never marked done)", ReopenLootsAgain);
r.Add("chest loot: a salvage-only item is left when no UST is carried, as on corpses", SalvageWithoutUstLeft);
r.Add("chest loot: opened mid-fight it waits for combat, then is looted if still open", ChestWaitsForCombat);
r.Add("chest loot: closed by the player mid-loot -> session ends, chest not reopened", ClosedMidLootNotReopened);
r.Add("chest loot: a chest gets 2 minutes (not the 12 s corpse timeout), restarted by each pickup", ChestTimeoutLongAndRestarted);
}
// ── World set-up ──────────────────────────────────────────────────────────
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
private static void BaseWorld(string chestName = "Chest")
{
FakeHost.Reset();
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.CloseContainerCalls = true; // CloseContainer + GetGroundContainerId
FakeHost.Names[Player] = "Dargoth Hera";
FakeHost.Positions[Player] = Me0;
FakeHost.PlayerPose = Me0;
FakeHost.Names[Chest] = chestName;
FakeHost.ItemTypes[Chest] = ItemTypeContainer;
FakeHost.Positions[Chest] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
FakeHost.NotAttackable.Add(Chest);
FakeHost.Containers[Chest] = 0; // lies in the world (ownership readable, nobody holds it)
AddItem(Gem, "Black Opal", ItemTypeGem, Chest);
AddItem(Spoon, "Rusty Spoon", ItemTypeMisc, Chest);
}
private static void AddItem(uint id, string name, uint type, uint container)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = type;
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 Bot(RynthCoreHost host, bool salvageRule = false)
{
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);
string profile = Path.Combine(Program.TempRoot, salvageRule ? "loot-chest-salvage.json" : "loot-chest-test.json");
var p = new LootProfile { Name = "chest" };
var gems = new LootRule { Name = "Gems", Action = LootAction.Keep };
gems.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
p.Rules.Add(gems);
if (salvageRule)
{
var armor = new LootRule { Name = "Salvage armor", Action = LootAction.Salvage };
armor.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Armor });
p.Rules.Add(armor);
}
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, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())!;
public void Tick(BotActivity act = BotActivity.Looting)
{
Set("_activity", act);
Call("TickCorpseOpening");
}
public void Create(params uint[] ids)
{
foreach (uint id in ids) Cache.OnCreateObject(id);
Cache.Tick();
}
/// <summary>The server opens <paramref name="container"/> for the player (ViewContents, then the inventory update).</summary>
public void ServerOpens(uint container)
{
FakeHost.GroundContainer = container;
P.OnViewObjectContents(container);
P.OnUpdateObjectInventory(container);
}
/// <summary>The server's answer to a close: the window goes.</summary>
public void ServerCloses(uint container)
{
if (FakeHost.GroundContainer == container) FakeHost.GroundContainer = 0;
P.OnStopViewingObjectContents(container);
}
public void TickUntil(Func<bool> done, int max = 200)
{
for (int i = 0; i < max && !done(); i++)
{
Tick();
Thread.Sleep(10);
}
}
public void TickFor(int ms, BotActivity act = BotActivity.Looting)
{
long end = Environment.TickCount64 + ms;
while (Environment.TickCount64 < end)
{
Tick(act);
Thread.Sleep(10);
}
}
public bool Moved(uint id) => FakeHost.ExternalMoves.Any(m => m.Id == id);
public bool Marked(uint id) => Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)id));
}
private static string Moves() => string.Join(",", FakeHost.ExternalMoves.Select(m => $"{m.Id:X8}->{m.Target:X8}"));
/// <summary>Loots the chest's gem: picked up, lands in the pack, the chest is closed. Returns the bot.</summary>
private static void LootGemAndFinish(Bot bot, uint gem)
{
bot.TickUntil(() => bot.Moved(gem));
Check.True(FakeHost.ExternalMoves.Contains((gem, Player, 0)), $"the gem 0x{gem:X8} is moved into the main pack (moves: {Moves()})");
int closesBefore = FakeHost.Closes.Count;
FakeHost.Containers[gem] = Player; // it lands in the pack
bot.TickUntil(() => FakeHost.Closes.Count > closesBefore);
}
// ── Tests ─────────────────────────────────────────────────────────────────
private static void OpenedChestLooted()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
Check.False(bot.HasLootWork(), "a closed chest is no loot work");
bot.ServerOpens(Chest);
Check.True(bot.HasLootWork(), "an open chest is loot work (the arbiter gives Looting the tick, nav stops)");
LootGemAndFinish(bot, Gem);
Check.False(bot.Moved(Spoon), "the spoon matches nothing and stays in the chest");
Check.False(FakeHost.Uses.Contains(Chest), "no open sent: the chest was open already");
Check.False(FakeHost.AutoRunCalls.Any(on => on), "no walk toward it");
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{Chest:X8}", "closed once when done, as a finished corpse is");
Check.False(bot.Marked(Chest), "never put in the completed-corpse set");
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "the looter lets go of it");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot: looting open chest")), "the start is logged as Chest loot");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot: picking up") && l.Contains($"{Gem:X8}")), "the pickup is logged as Chest loot");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot: done with chest")), "the finish is logged");
// The server's answer to the close; nothing more happens.
bot.ServerCloses(Chest);
bot.TickFor(100);
Check.Eq(FakeHost.Closes.Count, 1, "still one close");
Check.False(bot.HasLootWork(), "no loot work left");
}
private static void ChestTimeoutLongAndRestarted()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.LootCorpseTimeoutMs = 12000;
// A corpse keeps the setting.
bot.Set("_targetCorpseId", 0x7A9B4002);
Check.Eq((int)bot.Call("GetCorpseTimeoutMs", bot.S)!, 12000, "a corpse: the Corpse Timeout setting");
// A chest: 2 minutes, or the setting when that is longer.
bot.Set("_targetCorpseId", unchecked((int)Chest));
bot.Set("_lootChestId", unchecked((int)Chest));
Check.Eq((int)bot.Call("GetCorpseTimeoutMs", bot.S)!, RynthAiPlugin.ChestLootTimeoutMs, "a chest: ChestLootTimeoutMs");
Check.Eq(RynthAiPlugin.ChestLootTimeoutMs, 120_000, "2 minutes");
bot.S.LootCorpseTimeoutMs = 300_000;
Check.Eq((int)bot.Call("GetCorpseTimeoutMs", bot.S)!, 300_000, "a longer Corpse Timeout still wins");
bot.S.LootCorpseTimeoutMs = 12000;
// 100 s into the session, a pickup: the clock restarts, so the session isn't timed out.
long now = 1_000_000;
bot.Set("_corpseTargetSince", now - 100_000);
bot.Set("_currentLootItemId", unchecked((int)Gem));
bot.Call("ConfirmCurrentLootItemMoved", now, "test");
Check.Eq(bot.Get<long>("_corpseTargetSince"), now, "a confirmed pickup restarts the chest's clock");
Check.False((bool)bot.Call("HasCorpseTimedOut", bot.S, now + 119_000)!, "119 s after the last pickup: still going");
Check.True((bool)bot.Call("HasCorpseTimedOut", bot.S, now + 120_000)!, "120 s with no pickup: timed out");
// A corpse pickup doesn't touch the corpse clock.
bot.Set("_lootChestId", 0);
bot.Set("_targetCorpseId", 0x7A9B4002);
bot.Set("_corpseTargetSince", now - 5_000);
bot.Set("_currentLootItemId", unchecked((int)Gem2));
bot.Call("ConfirmCurrentLootItemMoved", now, "test");
Check.Eq(bot.Get<long>("_corpseTargetSince"), now - 5_000, "a corpse keeps one timeout for the whole corpse");
}
private static void OwnSidePackNotLooted()
{
BaseWorld();
FakeHost.Names[SidePack] = "Pack";
FakeHost.ItemTypes[SidePack] = ItemTypeContainer;
FakeHost.Containers[SidePack] = Player; // in the main pack
AddItem(PackGem, "Black Opal", ItemTypeGem, SidePack);
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(SidePack, PackGem);
bot.ServerOpens(SidePack); // ACE sends ViewContents for side packs at login
Check.False(bot.HasLootWork(), "your own side pack is no loot work");
bot.TickFor(300);
Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing moved out of your own pack");
Check.Eq(FakeHost.Closes.Count, 0, "and it is not closed");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot: not looting") && l.Contains("in your inventory")), "the reason is logged");
// The main pack itself never counts either.
bot.ServerOpens(Player);
Check.False(bot.HasLootWork(), "the main pack is no loot work");
}
private static void HouseStorageNotLooted()
{
BaseWorld();
FakeHost.InstanceIds[(Chest, 32)] = 0x50000ABC; // HouseOwner: a house-linked object of an owned house
var host = FakeHost.Create(Player);
Check.True(host.HasGetObjectInstanceIdProperty, "the host reads STypeIID properties");
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
Check.False(bot.HasLootWork(), "house storage is no loot work");
bot.TickFor(300);
Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing taken out of house storage");
Check.Eq(FakeHost.Closes.Count, 0, "and it is left open for the player");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot: not looting") && l.Contains("house storage")), "the reason is logged");
}
private static void HouseStorageByNameNotLooted()
{
BaseWorld(chestName: "Storage");
var host = FakeHost.Create(Player);
Check.False(host.HasGetObjectInstanceIdProperty, "no STypeIID read here");
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
Check.False(bot.HasLootWork(), "a container named Storage is no loot work");
bot.TickFor(300);
Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing taken");
Check.True(RynthAiPlugin.IsHouseStorageName("Wall Hook"), "hooks are house objects too");
Check.False(RynthAiPlugin.IsHouseStorageName("Ornate Chest"), "a treasure chest is not");
}
private static void LootingOffNothing()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.EnableLooting = false;
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
Check.False(bot.HasLootWork(), "no loot work with Looting off");
bot.TickFor(300, BotActivity.Navigating);
Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing taken");
Check.Eq(FakeHost.Closes.Count, 0, "and it is not closed");
Check.False(FakeHost.Logs.Any(l => l.Contains("Chest loot:")), "no chest-loot lines at all");
Check.True(FakeHost.Chat.Any(c => c.Contains("Black Opal") || c.Contains("Rusty Spoon") || c.Contains("loot profile")),
"the old loot check of a natively opened container still runs (chat: " + string.Join(" | ", FakeHost.Chat) + ")");
}
private static void ReopenLootsAgain()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
LootGemAndFinish(bot, Gem);
bot.ServerCloses(Chest);
Check.Eq(FakeHost.Closes.Count, 1, "the first open ends with one close");
// The chest regenerates: a new gem; a meta uses it again.
AddItem(Gem2, "Fire Opal", ItemTypeGem, Chest);
bot.Create(Gem2);
bot.ServerOpens(Chest);
Check.True(bot.HasLootWork(), "the reopened chest is loot work again");
LootGemAndFinish(bot, Gem2);
Check.Eq(FakeHost.Closes.Count, 2, "and is closed again when done");
Check.False(bot.Moved(Spoon), "the spoon is still left");
}
private static void SalvageWithoutUstLeft()
{
BaseWorld();
AddItem(Cap, "Leather Cap", ItemTypeArmor, Chest);
var host = FakeHost.Create(Player);
var bot = new Bot(host, salvageRule: true);
bot.Set("_salvageManager", new SalvageManager(host, bot.S, bot.Cache));
bot.Create(Chest, Gem, Spoon, Cap);
bot.ServerOpens(Chest);
LootGemAndFinish(bot, Gem);
Check.False(bot.Moved(Cap), "the salvage-only cap stays in the chest: no UST to salvage it with");
Check.True(FakeHost.Logs.Any(l => l.Contains("Leather Cap") && l.Contains("no UST carried")), "logged as for corpses");
Check.True(FakeHost.Chat.Any(c => c.Contains("No UST in your pack")), "and said once in chat");
}
private static void ChestWaitsForCombat()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
Check.True(bot.HasLootWork(), "the chest wants the tick");
// Combat owns the tick: nothing taken, the chest waits.
bot.TickFor(300, BotActivity.Combat);
Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing taken while combat holds the tick");
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "the chest isn't taken as the loot container yet");
// The fight ends, the chest is still open: looted.
LootGemAndFinish(bot, Gem);
Check.Eq(FakeHost.Closes.Count, 1, "looted and closed after the fight");
}
private static void ClosedMidLootNotReopened()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
bot.TickUntil(() => bot.Moved(Gem));
Check.True(bot.Moved(Gem), "the gem's move is sent");
// The player closes it before the gem arrives.
bot.ServerCloses(Chest);
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "the session ends");
bot.TickFor(300);
Check.False(FakeHost.Uses.Contains(Chest), "the chest is never reopened by the looter");
Check.Eq(FakeHost.Closes.Count, 0, "nothing to close: it is closed already");
Check.False(bot.Marked(Chest), "and not marked: opening it again loots it");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("before looting finished")), "logged");
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,273 @@
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;
// Corpse looting speed:
// - the finished corpse is not closed when another one is next (ACE closes it when the next
// one is used); the late close of the old corpse must not disturb the new open.
// - a pickup that merges into a stack already in the pack is confirmed when that stack grows
// (it never arrives as an object in the pack: it waited out PickupArriveMaxMs, 4 s).
// The loot clock (CorpseOpenController.CorpseClock) is moved by hand here.
internal static class CorpseCloseTests
{
private const uint Player = 0x50000D21;
private const uint CorpseA = 0x80262100;
private const uint CorpseB = 0x80262200;
private const uint GemA = 0x80262101;
private const uint GemA2 = 0x80262102;
private const uint GemB = 0x80262201;
private const uint PackStack = 0x80262301;
private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800;
private const uint LongDescKey = 16;
private const uint StackSizeKey = 12;
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("corpse close: the next corpse is opened without closing the finished one; its late close doesn't disturb the new open", NextCorpseWithoutClose);
r.Add("corpse close: a held-back close is sent when no other corpse is opened in time, and when the macro stops", DeferredCloseFallback);
r.Add("loot pickup: a pickup that merges into a pack stack is confirmed when the stack grows, not after 4 s", StackMergeConfirmed);
}
private static long _now;
private static void Clocked(Action body)
{
var old = RynthAiPlugin.CorpseClock;
_now = 50_000_000;
RynthAiPlugin.CorpseClock = () => _now;
try { body(); }
finally { RynthAiPlugin.CorpseClock = old; }
}
private static void Corpse(uint id, float dx)
{
FakeHost.Names[id] = "Corpse of Olthoi Swarm Drone";
FakeHost.ItemTypes[id] = ItemTypeContainer;
FakeHost.Strings[(id, LongDescKey)] = $"Killed by {Me}.";
FakeHost.NotAttackable.Add(id);
FakeHost.Positions[id] = (Me0.Cell, Me0.X + dx, Me0.Y, Me0.Z);
}
private static void Gem(uint id, uint container)
{
FakeHost.Names[id] = "Black Opal";
FakeHost.ItemTypes[id] = ItemTypeGem;
FakeHost.Containers[id] = container;
FakeHost.Appraised.Add(id);
}
private static void World(bool twoCorpses, bool secondGem = false)
{
FakeHost.Reset();
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.CloseContainerCalls = true; // CloseContainer + GetGroundContainerId
FakeHost.Names[Player] = Me;
FakeHost.Positions[Player] = Me0;
FakeHost.PlayerPose = Me0;
Corpse(CorpseA, 1.0f);
Gem(GemA, CorpseA);
if (secondGem) Gem(GemA2, CorpseA);
if (twoCorpses)
{
Corpse(CorpseB, 1.5f);
Gem(GemB, CorpseB);
}
}
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 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, "corpse-close-test.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 void Tick(BotActivity act = BotActivity.Looting)
{
Set("_activity", act);
typeof(RynthAiPlugin).GetMethod("TickCorpseOpening", Any)!.Invoke(P, null);
}
public void TickFor(long ms, BotActivity act = BotActivity.Looting)
{
long end = _now + ms;
while (_now < end) { _now += 20; Tick(act); }
}
public void Create(params uint[] ids)
{
foreach (uint id in ids) Cache.OnCreateObject(id);
Cache.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));
/// <summary>Opens corpse A (the server's ViewContents) and loots its gem into the pack until A completes.</summary>
private static void LootCorpseA(Bot bot)
{
bot.Tick();
Check.True(FakeHost.Uses.Contains(CorpseA), "corpse A is opened");
FakeHost.UseDone(0);
FakeHost.GroundContainer = CorpseA;
bot.P.OnViewObjectContents(CorpseA);
for (int i = 0; i < 200 && !FakeHost.ExternalMoves.Any(m => m.Id == GemA); i++) { _now += 20; bot.Tick(); }
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == GemA), "the gem's move is sent");
FakeHost.Containers[GemA] = Player;
for (int i = 0; i < 200 && !bot.Completed(CorpseA); i++) { _now += 20; bot.Tick(); }
Check.True(bot.Completed(CorpseA), "corpse A is completed");
}
private static void NextCorpseWithoutClose() => Clocked(() =>
{
World(twoCorpses: true);
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(CorpseA, CorpseB, GemA, GemB);
LootCorpseA(bot);
Check.Eq(FakeHost.Closes.Count, 0, "corpse B is next: no close is sent for A");
Check.True(Logged("no close sent (the server closes it when the next corpse is used)"), "and that is logged");
// The next corpse's open goes out at once: nothing waits for a close answer.
long doneAt = _now;
for (int i = 0; i < 10 && !FakeHost.Uses.Contains(CorpseB); i++) { _now += 20; bot.Tick(); }
Check.True(FakeHost.Uses.Contains(CorpseB), "corpse B is opened");
Check.True(_now - doneAt < 200, $"within {_now - doneAt} ms of A completing (the close answer wait was 500 ms)");
Check.Eq(FakeHost.Closes.Count, 0, "still no close for A");
Check.True(Logged($"0x{CorpseA:X8} is left for the server to close with this open"), "the open of B leaves A to the server");
// The server opens B; the client still shows A for a moment (its close not in yet).
FakeHost.UseDone(0);
bot.P.OnViewObjectContents(CorpseB);
for (int i = 0; i < 5; i++) { _now += 20; bot.Tick(); }
Check.Eq(bot.Get<int>("_openedContainerId"), unchecked((int)CorpseB), "B stays the open corpse while the client still shows A");
// A's close lands (CloseGroundContainer A), then the client shows B.
bot.P.OnStopViewingObjectContents(CorpseA);
FakeHost.GroundContainer = CorpseB;
for (int i = 0; i < 5; i++) { _now += 20; bot.Tick(); }
Check.Eq(bot.Get<int>("_openedContainerId"), unchecked((int)CorpseB), "A's close doesn't touch B");
Check.False(Logged($"container 0x{CorpseB:X8} closed before completion"), "B is not taken as closed");
Check.Eq(FakeHost.Uses.Count(u => u == CorpseB), 1, "B is opened once (a second use would close it on ACE)");
Check.Eq(FakeHost.Closes.Count, 0, "and A was never closed by RynthAi");
});
private static void DeferredCloseFallback() => Clocked(() =>
{
// Corpse B in range, but combat holds the tick: no open of B, so A's close goes after the hold limit.
World(twoCorpses: true);
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(CorpseA, CorpseB, GemA, GemB);
LootCorpseA(bot);
Check.Eq(FakeHost.Closes.Count, 0, "held back at first");
bot.TickFor(RynthAiPlugin.DeferredCloseMaxMs - 200, BotActivity.Combat);
Check.Eq(FakeHost.Closes.Count, 0, "still held just under the limit");
bot.TickFor(400, BotActivity.Combat);
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{CorpseA:X8}", "no other corpse opened in time: A is closed, once");
// The macro stops while a close is held back: it goes at once.
World(twoCorpses: true);
var host2 = FakeHost.Create(Player);
var bot2 = new Bot(host2);
bot2.Create(CorpseA, CorpseB, GemA, GemB);
LootCorpseA(bot2);
Check.Eq(FakeHost.Closes.Count, 0, "held back");
bot2.S.IsMacroRunning = false;
_now += 20; bot2.Tick(BotActivity.Idle);
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{CorpseA:X8}", "macro stopped: A is closed");
// Only corpse A: closed at once on completion, as before.
World(twoCorpses: false);
var host3 = FakeHost.Create(Player);
var bot3 = new Bot(host3);
bot3.Create(CorpseA, GemA);
LootCorpseA(bot3);
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{CorpseA:X8}", "the last corpse is closed at once");
});
private static void StackMergeConfirmed() => Clocked(() =>
{
World(twoCorpses: false);
Gem(PackStack, Player);
FakeHost.Ints[(PackStack, StackSizeKey)] = 3;
FakeHost.Ints[(GemA, StackSizeKey)] = 1;
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(CorpseA, GemA, PackStack);
bot.Tick();
FakeHost.UseDone(0);
FakeHost.GroundContainer = CorpseA;
bot.P.OnViewObjectContents(CorpseA);
for (int i = 0; i < 200 && !FakeHost.ExternalMoves.Any(m => m.Id == GemA); i++) { _now += 20; bot.Tick(); }
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == GemA), "the gem's move is sent");
long sentAt = _now;
// The server merges it: the corpse item is removed (still known to the client's cache, in no
// container), and the pack stack grows from 3 to 4.
FakeHost.Containers[GemA] = 0;
FakeHost.Ints[(PackStack, StackSizeKey)] = 4;
for (int i = 0; i < 400 && !Logged("pickup confirmed for"); i++) { _now += 20; bot.Tick(); }
Check.True(Logged($"pickup confirmed for 0x{GemA:X8}; merged into the stack 0x{PackStack:X8} in the pack"),
"confirmed as a merge into the pack stack: " + (FakeHost.Logs.LastOrDefault(l => l.Contains("pickup confirmed")) ?? "(none)"));
Check.True(_now - sentAt < RynthAiPlugin.PickupArriveMaxMs, $"confirmed {_now - sentAt} ms after the send, under the 4 s limit");
// A same-name stack that did not grow: not a merge, waits for the limit as before.
World(twoCorpses: false);
Gem(PackStack, Player);
FakeHost.Ints[(PackStack, StackSizeKey)] = 3;
var host2 = FakeHost.Create(Player);
var bot2 = new Bot(host2);
bot2.Create(CorpseA, GemA, PackStack);
bot2.Tick();
FakeHost.UseDone(0);
FakeHost.GroundContainer = CorpseA;
bot2.P.OnViewObjectContents(CorpseA);
for (int i = 0; i < 200 && !FakeHost.ExternalMoves.Any(m => m.Id == GemA); i++) { _now += 20; bot2.Tick(); }
long sent2 = _now;
FakeHost.Containers[GemA] = 0; // gone from the corpse, the pack stack unchanged
for (int i = 0; i < 400 && !Logged("pickup confirmed for"); i++) { _now += 20; bot2.Tick(); }
Check.True(_now - sent2 >= RynthAiPlugin.PickupArriveMaxMs, $"no stack grew: confirmed only at the limit ({_now - sent2} ms)");
});
}

View file

@ -0,0 +1,76 @@
using RynthCore.Plugin.RynthAi;
using RynthCore.RynthAiTests.Harness;
using Step = RynthCore.Plugin.RynthAi.DeathRecallRun.Step;
namespace RynthCore.RynthAiHostTests.Tests;
// Recall On Death (DeathRecallRun): fires at once, retries a fizzle on its own clock (4 s spells,
// 6 s items), stops firing once portal space or a landblock change shows the teleport, finishes
// 3 s after landing, and gives up after 5 tries or 60 s. Not ready (no wand / not in magic mode)
// never fires.
internal static class DeathRecallTests
{
private const uint Lifestone = 0xA9B4;
public static void Register(Runner r)
{
r.Add("death recall: fires at once, then retries a fizzle every 4 s", RetriesSpell);
r.Add("death recall: portal space stops the firing, done 3 s after landing", PortalThenDone);
r.Add("death recall: a landblock change also counts as the teleport", LandblockChange);
r.Add("death recall: gives up after 5 tries without a teleport; an item retries every 6 s", GivesUp);
r.Add("death recall: not ready never fires, and times out after 60 s", NotReadyTimesOut);
}
private static void RetriesSpell()
{
var run = new DeathRecallRun(useItem: false, 0, Lifestone);
Check.Eq(run.Tick(0, false, Lifestone, true), Step.Fire, "first tick fires");
Check.Eq(run.Tick(3_999, false, Lifestone, true), Step.Wait, "no second cast before 4 s");
Check.Eq(run.Tick(4_000, false, Lifestone, true), Step.Fire, "a fizzle is retried at 4 s");
Check.Eq(run.Fires, 2, "two casts");
}
private static void PortalThenDone()
{
var run = new DeathRecallRun(useItem: false, 0, Lifestone);
run.Tick(0, false, Lifestone, true);
Check.Eq(run.Tick(2_000, true, 0, true), Step.Wait, "in portal space: wait");
Check.Eq(run.Tick(9_000, true, 0, true), Step.Wait, "still in portal space: no recast");
Check.Eq(run.Tick(10_000, false, Lifestone, true), Step.Wait, "landed: settle (same landblock is fine after portal space)");
Check.Eq(run.Tick(12_999, false, Lifestone, true), Step.Wait, "still settling");
Check.Eq(run.Tick(13_000, false, Lifestone, true), Step.Done, "done 3 s after landing");
Check.Eq(run.Fires, 1, "cast once");
}
private static void LandblockChange()
{
var run = new DeathRecallRun(useItem: true, 0, Lifestone);
run.Tick(0, false, Lifestone, true);
Check.Eq(run.Tick(4_000, false, 0x7D64, true), Step.Wait, "moved landblock: settling, no second use");
Check.Eq(run.Tick(7_000, false, 0x7D64, true), Step.Done, "done 3 s later");
Check.True(run.Teleported, "teleported");
}
private static void GivesUp()
{
var run = new DeathRecallRun(useItem: true, 0, Lifestone);
long t = 0;
int fires = 0;
for (int i = 0; i < 5; i++, t += 6_000)
if (run.Tick(t, false, Lifestone, true) == Step.Fire) fires++;
Check.Eq(fires, 5, "five uses, 6 s apart");
Check.Eq(run.Tick(29_000, false, Lifestone, true), Step.Wait, "waits out the last try");
Check.Eq(run.Tick(30_000, false, Lifestone, true), Step.Failed, "then gives up");
Check.True(run.FailReason.Contains("5 tries"), "says why");
}
private static void NotReadyTimesOut()
{
var run = new DeathRecallRun(useItem: false, 0, Lifestone);
Check.Eq(run.Tick(0, false, Lifestone, false), Step.Wait, "not ready: no cast");
Check.Eq(run.Tick(30_000, false, Lifestone, false), Step.Wait, "still not ready");
Check.Eq(run.Tick(60_001, false, Lifestone, false), Step.Failed, "60 s: gives up");
Check.Eq(run.Fires, 0, "never cast");
Check.True(run.FailReason.Contains("60 s"), "says why");
}
}

View file

@ -407,6 +407,13 @@ internal static class ExpressionTests
Is(e, "listsort[listcreate[10,9,100], `$1 - $2`]", "[9,10,100]"); // comparator
Is(e, "listfilter[$l, ``]", "[]");
// The inner expression can quote text with escaped backticks (CQ_DragonIsle_Water.met:
// listfilter[...,`chatbox[\`/t \`+wobjectgetname[$1]+\`, xp\`]`] sent "0Name`").
e.Evaluate("setvar[names, listcreate[Lotus,Oak]]");
Is(e, @"listmap[$names, `\`/t \`+$1+\`, xp\``]", "[/t Lotus\\, xp,/t Oak\\, xp]");
Is(e, @"listfilter[$names, `$1==\`Oak\``]", "[Oak]");
Is(e, @"listmap[$names, `\`a\\\\b\``]", "[a\\\\b,a\\\\b]");
// The loop variables are put back afterwards.
e.Evaluate("setvar[1, mine]");
e.Evaluate("listmap[$l, `$1`]");

View file

@ -184,6 +184,9 @@ internal static class HealLatencyTests
{
var r = new Rig(healthPct: 40, manaPct: 2);
r.S.GetManaAt = 50; r.S.TopOffMana = 50;
// Mana Conversion untrained: the rests below. Trained, a recovery vital retries in 200 ms
// instead (RecoveryRetryTests).
FakeHost.Skills[(Player, 16)] = (10, 1);
Check.True(r.B.CheckVitals(), "40% health: Heal Self is cast");
Check.Eq(HealSelfCasts(), 1, "one Heal Self");
r.B.OnChatWindowText("You don't have enough Mana to cast this spell.", 0);

View file

@ -0,0 +1,363 @@
using System;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// HP failsafe: under Emergency Heal At with heals failing (here: every heal sent and never answered,
// as in a client log's hung casts), the character must not sit and die. 3 rounds of 2.5 s with no
// rise: a forced jump (ActionPacer.ForceBreak), then healing again; 3 more: the macro stops and
// "/lifestone" goes out (HpFailsafeRecall, default on).
internal static class HpFailsafeTests
{
private const uint Player = 0x50000B31;
private const uint STypeLife = 33;
public static void Register(Runner r)
{
r.Add("hp failsafe: 7.5 s at Emergency Heal At with no heal landing -> one jump; 7.5 s more -> macro stop and /lifestone", BreakThenRecall);
r.Add("hp failsafe: a heal landing (+3%) restarts the count; health over the line ends it", HealLandingResets);
r.Add("hp failsafe: HP Failsafe Recall off -> the jump still, no recall; no recall line -> 3 sends, then it gives up", RecallOffAndResends);
r.Add("hp failsafe: a recall that never starts turns the macro back on and re-arms; the next recall after 30 s", FailedRecallResumes);
r.Add("hp failsafe: another player's recall line is not ours; ours with its first letter dropped is", RecallLineIsOurs);
r.Add("hp failsafe: Emergency Heal At 100 at full health is not an emergency", FullHealthAtHundred);
r.Add("hp failsafe: nothing counts in portal space", NothingInPortalSpace);
r.Add("hp failsafe: a death drops the pending recall (0 health, and the plugin's death hold): no /lifestone, the macro stays off", DeathDropsRecall);
r.Add("hp failsafe: a failed recall does not switch the macro back on past a VTank yield", VTankYieldRespected);
r.Add("hp failsafe: our name unreadable: the recall line is taken as ours, and that is logged once", RecallNameUnreadable);
r.Add("vitals (L8):a heal the server leaves unanswered is not re-sent at the 2.5 s give-up after a 'too busy' answer", VitalResendObeysLatch);
}
// No re-send into a busy server: a client log re-sent a heal every 2.5 s (the vitals give-up) into a server
// answering 0x1D. Through the whole vitals step (BuffManager heartbeats, pacer on, the pacer's
// breaker off to isolate the latch): a heal goes out, the server never answers it, and another
// send is refused 0x1D. No heal is re-sent while that heal is unanswered.
private static void VitalResendObeysLatch()
{
try
{
var r = new Rig(healthPct: 40);
r.S.EmergencyHealAt = 0; // the failsafe out of it
r.S.SpellCastIntervalMs = 100;
r.Run(0, 0);
Check.Eq(FakeHost.Casts.Count, 1, "the heal goes out (and is never answered)");
r.Run(0.1, 0.5);
int heal = FakeHost.Casts[0].SpellId;
// Another send goes out over the open heal (as when a cast hangs) and is refused 'too busy'.
Check.True(r.Host.CastSpellFor(0x80000AAAu, 1237, "Combat", "Drain Health Other I"), "the other send");
FakeHost.UseDone(ActionPacer.TooBusyErr);
// Real time too: BuffManager's own retry limits run on the real clock.
for (int ms = 600; ms <= 6000; ms += 200) { System.Threading.Thread.Sleep(200); r.At(ms / 1000.0); r.B.OnHeartbeat(); }
Check.Eq(FakeHost.Casts.Count(c => c.SpellId == heal), 1, "no heal re-sent in 6 s (the 2.5 s give-up re-sent one before): " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("[Pace]") || l.Contains("[Buff")).Take(20)));
Check.True(r.Logged("Buff waits:") && r.Logged("nothing goes until the server answers"), "the hold is logged: " + string.Join(" | ", FakeHost.Logs.Take(30)));
}
finally { Done(); }
}
private sealed class Rig
{
public DateTime T0 = new(2026, 10, 10, 19, 0, 0);
public DateTime NowAt;
public readonly BuffManager B;
public readonly LegacyUiSettings S;
public readonly PlayerVitalsCache V;
public readonly RynthCore.PluginSdk.RynthCoreHost Host;
public int MacroStops;
public Rig(int healthPct = 20)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.TapJumpCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
FakeHost.Names[Player] = "Mira";
FakeHost.PlayerPose = (0x6347028Au, 100f, 100f, 0f);
FakeHost.Positions[Player] = FakeHost.PlayerPose;
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
var host = Host = FakeHost.Create(Player);
S = new LegacyUiSettings
{
IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 30, StaminaToHealthAt = 0,
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false,
EnableBuffing = false, SpellCastIntervalMs = 100,
};
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, S);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
V = new PlayerVitalsCache
{
MaxHealth = 100, CurrentHealth = (uint)healthPct, MaxStamina = 100, CurrentStamina = 100,
MaxMana = 100, CurrentMana = 100,
};
B = new BuffManager(host, S, sm, V);
B.SetCharacterSkills(skills);
B.MacroStopForRecall = () => MacroStops++;
NowAt = T0;
B.Clock = () => NowAt;
B.MarkLiveBuffsReadyForTests();
ActionPacer.Reset();
ActionPacer.Enabled = true;
ActionPacer.StuckCastMs = 0; // the pacer's own breaker off: only the failsafe jumps here
ActionPacer.NowMs = () => 50_000_000 + (long)(NowAt - T0).TotalMilliseconds;
MoveAudit.Reset();
MoveAudit.NowMs = ActionPacer.NowMs;
FakeHost.UseDone(0);
}
public void At(double seconds) => NowAt = T0.AddMilliseconds(Math.Round(seconds * 1000));
public bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
/// <summary>Heartbeats every 100 ms from <paramref name="from"/> up to and including <paramref name="to"/>.</summary>
public void Run(double from, double to)
{
for (int ms = (int)Math.Round(from * 1000); ms <= (int)Math.Round(to * 1000); ms += 100)
{
At(ms / 1000.0);
B.OnHeartbeat();
}
}
}
private static void Done()
{
ActionPacer.Enabled = false;
ActionPacer.Reset();
ActionPacer.NowMs = () => Environment.TickCount64;
ActionPacer.StuckCastMs = 8000;
MoveAudit.Reset();
MoveAudit.NowMs = () => Environment.TickCount64;
}
private static void BreakThenRecall()
{
try
{
var r = new Rig(healthPct: 20);
r.Run(0, 7.4);
Check.True(FakeHost.Casts.Count > 0, "a heal went out (and is never answered)");
Check.Eq(FakeHost.TapJumps, 0, "7.4 s: no jump yet");
r.Run(7.5, 7.5);
Check.Eq(FakeHost.TapJumps, 1, "7.5 s (3 rounds, no rise): one jump");
Check.Eq(r.B.HpFailsafeBreaks, 1, "counted");
Check.True(r.Logged("HP failsafe: health 20% at or under Emergency Heal At 30%, no heal landed in 7.5 s: breaking the cast with a jump"),
"the break is logged");
r.Run(7.6, 14.9);
Check.Eq(FakeHost.TapJumps, 1, "only one jump");
Check.True(r.S.IsMacroRunning, "14.9 s: still running");
r.Run(15.0, 15.0);
Check.False(r.S.IsMacroRunning, "15 s (3 more rounds): the macro is stopped");
Check.Eq(r.MacroStops, 1, "with the rest of a /ra stop");
Check.Eq(r.B.HpFailsafeRecalls, 1, "counted");
Check.True(FakeHost.Chat.Any(c => c.Contains("recalling to the lifestone")), "and said in chat");
Check.Eq(FakeHost.ChatCommands.Count, 0, "the recall waits for the stop to take effect");
r.Run(15.1, 15.5);
Check.Eq(FakeHost.ChatCommands.Count, 0, "500 ms later: still waiting for the stop to take effect");
r.Run(15.6, 15.6);
Check.Eq(FakeHost.ChatCommands.Count, 1, "600 ms later: one recall");
Check.Eq(FakeHost.ChatCommands[0], BuffManager.RecallCommand, "/lifestone");
r.B.OnChatWindowText("Mira is recalling to the lifestone.", 0);
r.Run(15.7, 20);
Check.Eq(FakeHost.ChatCommands.Count, 1, "the recall line: no resend");
Check.True(r.Logged("HP failsafe: the recall started"), "logged");
}
finally { Done(); }
}
private static void HealLandingResets()
{
try
{
var r = new Rig(healthPct: 20);
r.Run(0, 5.0);
r.V.CurrentHealth = 22; // +2: regeneration, not a heal
r.Run(5.1, 7.5);
Check.Eq(FakeHost.TapJumps, 1, "+2% is not a heal landing: the jump at 7.5 s");
var h = new Rig(healthPct: 20);
h.Run(0, 5.0);
h.V.CurrentHealth = 23; // +3: a heal landed
h.Run(5.1, 12.4);
Check.Eq(FakeHost.TapJumps, 0, "a heal landed at 5 s: no jump at 7.5 s, none by 12.4 s");
h.Run(12.5, 12.6);
Check.Eq(FakeHost.TapJumps, 1, "7.5 s after the heal with no other: the jump");
var o = new Rig(healthPct: 20);
o.Run(0, 5.0);
o.V.CurrentHealth = 31; // over Emergency Heal At 30
o.Run(5.1, 5.1);
o.V.CurrentHealth = 20;
o.Run(5.2, 12.6);
Check.Eq(FakeHost.TapJumps, 0, "over the line at 5.1 s: the count started again at 5.2 s");
Check.True(o.Logged("HP failsafe: health back to 31%"), "the end is logged");
}
finally { Done(); }
}
private static void RecallOffAndResends()
{
try
{
var r = new Rig(healthPct: 20);
r.S.HpFailsafeRecall = false;
r.Run(0, 20);
Check.Eq(FakeHost.TapJumps, 1, "recall off: the jump still");
Check.True(r.S.IsMacroRunning, "recall off: the macro keeps running");
Check.Eq(FakeHost.ChatCommands.Count, 0, "no recall");
Check.True(r.Logged("HP Failsafe Recall is off"), "said once in the log");
var n = new Rig(healthPct: 20);
n.Run(0, 15.0);
Check.False(n.S.IsMacroRunning, "recall: macro stopped");
n.Run(15.1, 25);
Check.Eq(FakeHost.ChatCommands.Count, 3, "no recall line: sent 3 times, 1.5 s apart, then stopped");
Check.True(n.Logged("no recall seen after 3 tries"), "and logged");
}
finally { Done(); }
}
// A recall that never starts must not leave the macro stopped at low health.
private static void FailedRecallResumes()
{
try
{
var n = new Rig(healthPct: 20);
n.Run(0, 15.0);
Check.False(n.S.IsMacroRunning, "recall: macro stopped");
n.Run(15.1, 21.0);
Check.Eq(FakeHost.ChatCommands.Count, 3, "3 tries, no recall line");
Check.True(n.S.IsMacroRunning, "the macro is back on (the heals and kits run again)");
Check.Eq(n.B.HpFailsafeRecallsFailed, 1, "a failed recall counted");
Check.True(FakeHost.Chat.Any(c => c.Contains("macro back on to keep healing")), "said in chat");
n.Run(21.1, 49.0);
Check.Eq(FakeHost.ChatCommands.Count, 3, "inside the 30 s cooldown: no recall");
Check.True(n.S.IsMacroRunning, "and the macro keeps running");
int breaks = FakeHost.Logs.Count(l => l.Contains("HP failsafe: health 20% at or under Emergency Heal At 30%, no heal landed in"));
Check.True(breaks >= 2, $"the failsafe re-armed: it reached the break stage again ({breaks})");
n.Run(49.1, 75.0);
Check.Eq(n.B.HpFailsafeRecalls, 2, "after the cooldown: the next recall");
Check.True(FakeHost.ChatCommands.Count > 3, "sent");
}
finally { Done(); }
}
// Only our own recall line ends the wait.
private static void RecallLineIsOurs()
{
try
{
var r = new Rig(healthPct: 20);
r.Run(0, 15.6);
Check.Eq(FakeHost.ChatCommands.Count, 1, "the first recall");
r.B.OnChatWindowText("Bob is recalling to the lifestone.", 0);
r.Run(15.7, 17.1);
Check.Eq(FakeHost.ChatCommands.Count, 2, "another player's recall line: sent again");
Check.False(r.Logged("HP failsafe: the recall started"), "not taken as ours");
r.B.OnChatWindowText("ira is recalling to the lifestone.", 0); // the first letter dropped by the chat layer
r.Run(17.2, 22);
Check.Eq(FakeHost.ChatCommands.Count, 2, "ours (first letter dropped): no more sends");
Check.True(r.Logged("HP failsafe: the recall started"), "logged");
}
finally { Done(); }
}
// Emergency Heal At 100 at full health is not an emergency.
private static void FullHealthAtHundred()
{
try
{
var r = new Rig(healthPct: 100);
r.S.EmergencyHealAt = 100;
r.Run(0, 20);
Check.Eq(FakeHost.TapJumps, 0, "100% at Emergency Heal At 100: no break");
Check.True(r.S.IsMacroRunning, "no recall");
}
finally { Done(); }
}
// A pending recall is dropped on death: after the respawn it must not send /lifestone or switch
// the macro on, against Stop Macro On Death.
private static void DeathDropsRecall()
{
try
{
var r = new Rig(healthPct: 20);
r.Run(0, 15.0);
Check.False(r.S.IsMacroRunning, "recall pending: macro stopped");
r.V.CurrentHealth = 0; // dead before the first send
r.Run(15.1, 30);
Check.Eq(FakeHost.ChatCommands.Count, 0, "0 health: no /lifestone");
Check.False(r.S.IsMacroRunning, "the macro stays off");
Check.True(r.Logged("the pending recall is dropped (dead)"), "logged");
// The plugin's death hold drops it too (the vitals cache still reads the old health).
var p = new Rig(healthPct: 20);
p.Run(0, 15.0);
var plugin = new RynthAiPlugin();
PacerEdgeTests.SetHost(plugin, p.Host);
typeof(RynthAiPlugin).GetField("_buffManager", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.SetValue(plugin, p.B);
FakeHost.Vitals = (0, 100, 0, 100, 0, 100);
typeof(RynthAiPlugin).GetMethod("HoldForDeath", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.Invoke(plugin, null);
p.Run(15.1, 30);
Check.Eq(FakeHost.ChatCommands.Count, 0, "death hold: no /lifestone after the respawn");
Check.False(p.S.IsMacroRunning, "death hold: the macro stays off");
Check.True(p.Logged("the pending recall is dropped (death)"), "logged");
}
finally { Done(); }
}
// The failsafe's restart is a macro start like any other.
private static void VTankYieldRespected()
{
try
{
var r = new Rig(healthPct: 20);
r.B.MayRestartMacro = () => false; // VTank runs and yield is on
r.Run(0, 21.0);
Check.Eq(FakeHost.ChatCommands.Count, 3, "3 tries, no recall line");
Check.False(r.S.IsMacroRunning, "VTank yield: the macro stays off");
Check.True(FakeHost.Chat.Any(c => c.Contains("the macro stays off (VTank yield)")), "said in chat");
}
finally { Done(); }
}
private static void RecallNameUnreadable()
{
try
{
var r = new Rig(healthPct: 20);
FakeHost.Names.Remove(Player);
r.Run(0, 15.6);
Check.Eq(FakeHost.ChatCommands.Count, 1, "the first recall");
r.B.OnChatWindowText("Bob is recalling to the lifestone.", 0);
r.Run(15.7, 20);
Check.Eq(FakeHost.ChatCommands.Count, 1, "no name to compare: taken as ours, no resend");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("our name could not be read")), 1, "logged once");
}
finally { Done(); }
}
// Nothing counts in portal space.
private static void NothingInPortalSpace()
{
try
{
var r = new Rig(healthPct: 20);
FakeHost.Portaling = true;
r.Run(0, 20);
Check.Eq(FakeHost.TapJumps, 0, "portal space: no failsafe jump");
Check.True(r.S.IsMacroRunning, "no recall");
Check.Eq(r.B.HpFailsafeBreaks, 0, "nothing counted");
}
finally { FakeHost.Portaling = false; Done(); }
}
}

View file

@ -0,0 +1,215 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Monster rule Priority 0 = IGNORE: never a target, not "a monster
// nearby" for nav / combat / loot / stance, with no exception: an ignored monster attacking the
// player is still never attacked.
internal static class IgnoreMonsterTests
{
private const uint Player = 0x50000F01;
private const uint Lb = 0xA9B40000;
private const string Grub = "Olthoi Grub", Soldier = "Olthoi Soldier";
private static readonly BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
public static void Register(Runner r)
{
r.Add("monster ignore: a Priority 0 monster is never targeted", NotTargeted);
r.Add("monster ignore: a Priority 0 monster holds nothing up (nav, combat, close-threat gates)", HoldsNothingUp);
r.Add("monster ignore: the kill-shot swap does not count a Priority 0 monster as an alternate", KillShotAlternate);
r.Add("monster ignore: a Priority 0 monster hitting the player is still never targeted", NotTargetedWhenAttackingUs);
r.Add("monster ignore: Priority 1, no rule and the Default row behave as before", UnchangedForOtherPriorities);
}
private static uint _next;
private static void Place(uint id, string name, float north)
{
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (Lb | 0x1C, 96f, 96f + north, 0f);
FakeHost.ItemTypes[id] = 0x10;
}
/// <summary>A combat manager with the given monsters (name, metres north) and rules.</summary>
private static CombatManager World(List<MonsterRule>? rules, out List<uint> ids, params (string Name, float North)[] mobs)
{
FakeHost.Reset();
FakeHost.Names[Player] = "Me";
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
ids = new List<uint>();
foreach (var (name, north) in mobs)
{
uint id = 0x80000401 + _next++;
Place(id, name, north);
ids.Add(id);
}
var s = new LegacyUiSettings { MonsterRange = 30 };
if (rules != null) s.MonsterRules = rules;
var host = FakeHost.Create();
var cache = FakeHost.MakeCache(host, Player, ids);
var c = new CombatManager(host, s, cache);
c.SetPlayerId(Player);
c.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
Scan(c);
return c;
}
private static void Scan(CombatManager c)
{
typeof(CombatManager).GetField("_lastScanTime", Any)?.SetValue(c, DateTime.MinValue);
c.ScanNearbyTargets();
}
private static List<MonsterRule> GrubIgnored(int defaultPriority = 1) => new()
{
new MonsterRule { Name = "Default", Priority = defaultPriority },
new MonsterRule { Name = Grub, Priority = 0 },
};
private static bool Scanned(CombatManager c, uint id) => c.ScannedTargets.Any(t => (uint)t.Id == id);
// -- 1. not targeted -------------------------------------------------------
private static void NotTargeted()
{
// The grub is closer (3 m) than the soldier (8 m): without the rule it would be picked.
var c = World(GrubIgnored(), out var ids, (Grub, 3f), (Soldier, 8f));
uint grub = ids[0], soldier = ids[1];
Check.False(Scanned(c, grub), "the ignored grub is not in the scan list");
Check.True(Scanned(c, soldier), "the soldier is");
c.HandleCombatTrigger();
Check.Eq((uint)c.activeTargetId, soldier, "the soldier is locked, not the nearer grub");
// Alone, the grub is not acquired at all.
var lone = World(GrubIgnored(), out var ids2, (Grub, 3f));
lone.HandleCombatTrigger();
Check.Eq(lone.activeTargetId, 0, "a lone ignored grub is never locked");
Check.Eq(lone.ScannedTargets.Count, 0, "and the scan list is empty");
// A re-lock: the soldier dies (kill suppression), the next pick must not fall to the grub.
var c2 = World(GrubIgnored(), out var ids3, (Grub, 3f), (Soldier, 8f));
c2.HandleCombatTrigger();
Check.Eq((uint)c2.activeTargetId, ids3[1], "locked the soldier");
c2.OnKillNotification("Olthoi Soldier's perforated corpse falls before you!");
Scan(c2);
c2.HandleCombatTrigger();
Check.Eq(c2.activeTargetId, 0, "after the soldier dies the next pick is nothing, not the grub");
}
// -- 2. holds nothing up ---------------------------------------------------
private static void HoldsNothingUp()
{
var c = World(GrubIgnored(), out _, (Grub, 2f));
Check.False(c.HasTargets, "HasTargets (corpse combat-urgent gates, nav hold)");
Check.False(c.HasNearbyMonsters, "HasNearbyMonsters (nav hold, clear-the-room gating)");
Check.False(c.HasEngageableTarget, "HasEngageableTarget (enter/stay in combat, stance switching, arbiter)");
Check.False(c.IsUnderCloseAttack, "IsUnderCloseAttack");
Check.False(c.HasCloseThreat(50), "HasCloseThreat (buff and rest gating, loot starvation)");
Check.False(c.HasCloseThreat(5), "HasCloseThreat at the loot-starve radius");
// The control: the same grub with no rule is exactly what held everything up.
var held = World(null, out _, (Grub, 2f));
Check.True(held.HasTargets && held.HasNearbyMonsters && held.HasEngageableTarget && held.HasCloseThreat(5),
"without the rule the same grub holds all of them");
}
// -- 3. kill-shot alternate ------------------------------------------------
private static void KillShotAlternate()
{
var c = World(GrubIgnored(), out var ids, (Soldier, 5f), (Grub, 3f));
c.EngageForTest(unchecked((int)ids[0]));
var alt = typeof(CombatManager).GetMethod("HasAlternateTarget", Any)!;
bool HasAlt() => (bool)alt.Invoke(c, new object[] { unchecked((int)ids[0]) })!;
Check.False(HasAlt(), "the only other monster is an ignored grub: no alternate, keep casting at the soldier");
var open = World(null, out var ids2, (Soldier, 5f), (Grub, 3f));
open.EngageForTest(unchecked((int)ids2[0]));
Check.True((bool)alt.Invoke(open, new object[] { unchecked((int)ids2[0]) })!, "control: an unruled grub is an alternate");
}
// -- 4. attacking us: still ignored ----------------------------------------
private static void NotTargetedWhenAttackingUs()
{
var c = World(GrubIgnored(), out var ids, (Grub, 3f), (Soldier, 8f));
foreach (string line in new[]
{
"Olthoi Grub bites you for 3 points of piercing damage!",
"You evaded Olthoi Grub!",
"Olthoi Grub bites you for 4 points of piercing damage!",
})
{
c.HandleChatForDamage(line);
Scan(c);
c.HandleCombatTrigger();
Check.False(Scanned(c, ids[0]), $"after '{line}' the grub is still not a candidate");
Check.Eq((uint)c.activeTargetId, ids[1], $"after '{line}' the soldier (farther) stays the target");
}
// Alone and hitting us: never locked, holds nothing.
var lone = World(GrubIgnored(), out _, (Grub, 2f));
for (int i = 0; i < 5; i++)
{
lone.HandleChatForDamage("Olthoi Grub bites you for 3 points of piercing damage!");
Scan(lone);
lone.HandleCombatTrigger();
}
Check.Eq(lone.activeTargetId, 0, "a lone ignored grub hitting us is never locked");
Check.False(lone.HasEngageableTarget || lone.HasTargets, "and holds nothing up");
// Control: the same lines with no rule, the grub (nearer) is the target.
var open = World(null, out var ids2, (Grub, 3f), (Soldier, 8f));
open.HandleChatForDamage("Olthoi Grub bites you for 3 points of piercing damage!");
Scan(open);
open.HandleCombatTrigger();
Check.Eq((uint)open.activeTargetId, ids2[0], "control: an unruled grub is locked");
}
// -- 5. unchanged ----------------------------------------------------------
private static void UnchangedForOtherPriorities()
{
// Priority 1 rule and Default row: targeted, nearest first.
var rules = new List<MonsterRule>
{
new MonsterRule { Name = "Default", Priority = 1 },
new MonsterRule { Name = Grub, Priority = 1 },
};
var c = World(rules, out var ids, (Soldier, 6f), (Grub, 3f));
Check.True(Scanned(c, ids[0]) && Scanned(c, ids[1]), "Priority 1 rule and the Default row: both scanned");
c.HandleCombatTrigger();
Check.Eq((uint)c.activeTargetId, ids[1], "nearest first, as before");
// No rules at all.
var none = World(null, out var ids2, (Soldier, 6f), (Grub, 3f));
none.HandleCombatTrigger();
Check.Eq((uint)none.activeTargetId, ids2[1], "no rules: nearest first");
// Strict tiers still hold: a Priority 2 soldier beats a nearer Priority 1 grub, which is still a target alone.
var tiers = World(new List<MonsterRule>
{
new MonsterRule { Name = "Default", Priority = 1 },
new MonsterRule { Name = Soldier, Priority = 2 },
}, out var ids3, (Soldier, 9f), (Grub, 3f));
tiers.HandleCombatTrigger();
Check.Eq((uint)tiers.activeTargetId, ids3[0], "Priority 2 outranks a nearer Priority 1");
// A Default row at 0 ignores monsters no row names, and only those.
var d0 = World(new List<MonsterRule>
{
new MonsterRule { Name = "Default", Priority = 0 },
new MonsterRule { Name = Soldier, Priority = 1 },
}, out var ids4, (Soldier, 9f), (Grub, 3f));
Check.True(Scanned(d0, ids4[0]), "a named Priority 1 monster is scanned under a Default of 0");
Check.False(Scanned(d0, ids4[1]), "an unnamed monster takes the Default row: ignored");
}
}

View file

@ -0,0 +1,167 @@
using RynthCore.Engine.Compatibility;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The engine Inventory panel's attribute filter (RynthCore Compatibility/InventoryAttributeFilter.cs,
// linked): rule matching, unidentified items, all / any, the value conversions and the saved line.
internal static class InventoryAttributeFilterTests
{
public static void Register(Runner r)
{
r.Add("inv filter: number, flag, text and slot rules", RuleKinds);
r.Add("inv filter: appraised rules on an unidentified item are unknown", Unknowns);
r.Add("inv filter: match all vs match any, off and empty filters", Modes);
r.Add("inv filter: percents, wield level, material and set names", Conversions);
r.Add("inv filter: saved line round-trips and skips broken rules", Persistence);
}
/// <summary>Hand-filled facts: absent values are 0 / false / "", as in the engine.</summary>
private sealed class Facts : IInventoryFilterFacts
{
public bool Identified { get; set; } = true;
public uint SlotMask { get; set; }
public readonly System.Collections.Generic.Dictionary<FilterAttr, double> Numbers = new();
public readonly System.Collections.Generic.Dictionary<FilterAttr, bool> Flags = new();
public readonly System.Collections.Generic.Dictionary<FilterAttr, string> Texts = new();
public double Number(FilterAttrInfo a) => Numbers.TryGetValue(a.Id, out double v) ? v : 0;
public bool Flag(FilterAttrInfo a) => Flags.TryGetValue(a.Id, out bool v) && v;
public string Text(FilterAttrInfo a) => Texts.TryGetValue(a.Id, out string? v) ? v : "";
}
private static InventoryFilterRule Rule(FilterAttr a, FilterOp op, double n = 0, string text = "", int choice = 0) =>
new() { Attr = a, Op = op, Number = n, Text = text, Choice = choice };
private static FilterVerdict One(InventoryFilterRule rule, Facts f) => InventoryAttributeFilter.EvaluateRule(rule, f);
private static void RuleKinds()
{
var f = new Facts { SlotMask = 0x00008000 }; // neck
f.Numbers[FilterAttr.ArmorLevel] = 300;
f.Flags[FilterAttr.Imbued] = true;
f.Texts[FilterAttr.Spells] = "Legendary Strength\nEpic Endurance";
Check.Eq(One(Rule(FilterAttr.ArmorLevel, FilterOp.AtLeast, 300), f), FilterVerdict.Match, "300 >= 300");
Check.Eq(One(Rule(FilterAttr.ArmorLevel, FilterOp.AtLeast, 301), f), FilterVerdict.NoMatch, "300 >= 301");
Check.Eq(One(Rule(FilterAttr.ArmorLevel, FilterOp.AtMost, 300), f), FilterVerdict.Match, "300 <= 300");
Check.Eq(One(Rule(FilterAttr.ArmorLevel, FilterOp.Equal, 300), f), FilterVerdict.Match, "300 = 300");
Check.Eq(One(Rule(FilterAttr.ArmorLevel, FilterOp.NotEqual, 300), f), FilterVerdict.NoMatch, "300 != 300");
Check.Eq(One(Rule(FilterAttr.MaxDamage, FilterOp.AtMost, 10), f), FilterVerdict.Match, "absent number is 0");
Check.Eq(One(Rule(FilterAttr.Imbued, FilterOp.Yes), f), FilterVerdict.Match, "imbued yes");
Check.Eq(One(Rule(FilterAttr.Imbued, FilterOp.No), f), FilterVerdict.NoMatch, "imbued no");
Check.Eq(One(Rule(FilterAttr.Retained, FilterOp.No), f), FilterVerdict.Match, "absent flag is no");
Check.Eq(One(Rule(FilterAttr.Spells, FilterOp.Contains, text: "legendary str"), f), FilterVerdict.Match, "case-insensitive contains");
Check.Eq(One(Rule(FilterAttr.Spells, FilterOp.NotContains, text: "Legendary"), f), FilterVerdict.NoMatch, "doesn't contain");
Check.Eq(One(Rule(FilterAttr.Spells, FilterOp.Contains, text: "strength epic"), f), FilterVerdict.NoMatch,
"text can't span two spells");
Check.Eq(One(Rule(FilterAttr.Spells, FilterOp.NotContains, text: ""), f), FilterVerdict.Match, "empty text tests nothing");
int neck = System.Array.IndexOf(InventoryAttributeFilter.SlotNames, "Neck");
int finger = System.Array.IndexOf(InventoryAttributeFilter.SlotNames, "Finger");
Check.Eq(One(Rule(FilterAttr.Slot, FilterOp.Is, choice: neck), f), FilterVerdict.Match, "fits neck");
Check.Eq(One(Rule(FilterAttr.Slot, FilterOp.Is, choice: finger), f), FilterVerdict.NoMatch, "not a ring");
Check.Eq(One(Rule(FilterAttr.Slot, FilterOp.IsNot, choice: finger), f), FilterVerdict.Match, "is not a ring");
Check.True(InventoryAttributeFilter.FitsSlot(0x00000200, System.Array.IndexOf(InventoryAttributeFilter.SlotNames, "Chest")),
"chest underclothes count as chest");
Check.Eq(InventoryAttributeFilter.SlotNames.Length, InventoryAttributeFilter.SlotMasks.Length, "a mask per slot name");
}
private static void Unknowns()
{
var f = new Facts { Identified = false };
f.Numbers[FilterAttr.Value] = 5000;
Check.Eq(One(Rule(FilterAttr.ArmorLevel, FilterOp.AtLeast, 1), f), FilterVerdict.Unknown, "appraised rule needs an identify");
Check.Eq(One(Rule(FilterAttr.Value, FilterOp.AtLeast, 1000), f), FilterVerdict.Match, "public rule works without one");
Check.Eq(One(Rule(FilterAttr.Spells, FilterOp.Contains, text: ""), f), FilterVerdict.Match, "an empty text rule never hides");
Check.False(InventoryAttributeFilter.Info(FilterAttr.Value).NeedsId, "value is public");
Check.True(InventoryAttributeFilter.Info(FilterAttr.WieldLevel).NeedsId, "level to wield is appraised");
}
private static void Modes()
{
var f = new Facts { Identified = false };
f.Numbers[FilterAttr.Value] = 5000;
var filter = new InventoryAttributeFilter { Enabled = true };
filter.Rules.Add(Rule(FilterAttr.Value, FilterOp.AtLeast, 1000));
filter.Rules.Add(Rule(FilterAttr.ArmorLevel, FilterOp.AtLeast, 300));
Check.Eq(filter.Evaluate(f), FilterVerdict.Unknown, "all: one match + one unknown is unknown");
filter.Rules[0].Number = 10_000;
Check.Eq(filter.Evaluate(f), FilterVerdict.NoMatch, "all: a no-match wins over unknown");
filter.MatchAny = true;
Check.Eq(filter.Evaluate(f), FilterVerdict.Unknown, "any: no-match + unknown is unknown");
filter.Rules[0].Number = 1000;
Check.Eq(filter.Evaluate(f), FilterVerdict.Match, "any: a match wins over unknown");
f.Identified = true;
filter.Rules[0].Number = 10_000;
Check.Eq(filter.Evaluate(f), FilterVerdict.NoMatch, "any: nothing matches");
filter.Enabled = false;
Check.Eq(filter.Evaluate(f), FilterVerdict.Match, "off keeps everything");
Check.False(filter.Active, "off is not active");
Check.True(filter.NeedsIdentify, "an armor level rule needs identifies");
var empty = new InventoryAttributeFilter { Enabled = true };
Check.False(empty.Active, "no rules is not active");
Check.Eq(empty.Evaluate(f), FilterVerdict.Match, "no rules keeps everything");
}
private static void Conversions()
{
Check.Near(InventoryAttributeFilter.Scale(FilterSource.FloatModPercent, 1.15), 15, 1e-9, "attack mod 1.15 is 15%");
Check.Near(InventoryAttributeFilter.Scale(FilterSource.FloatModPercent, 0), 0, 1e-9, "absent mod is 0%");
Check.Near(InventoryAttributeFilter.Scale(FilterSource.FloatPercent, 0.05), 5, 1e-9, "mana conversion 0.05 is 5%");
Check.True(InventoryAttributeFilter.CompareNumber(InventoryAttributeFilter.Scale(FilterSource.FloatModPercent, 1.15), FilterOp.Equal, 15),
"float rounding still equals the typed percent");
Check.Eq(InventoryAttributeFilter.WieldLevel(7, 150, 0, 0), 150, "level in the first requirement");
Check.Eq(InventoryAttributeFilter.WieldLevel(2, 300, 7, 180), 180, "level in the second requirement");
Check.Eq(InventoryAttributeFilter.WieldLevel(2, 300, 0, 0), 0, "a skill requirement isn't a level");
Check.Eq(InventoryAttributeFilter.MaterialName(15), "Black Garnet", "MaterialType 15");
Check.Eq(InventoryAttributeFilter.MaterialName(77), "Teak", "the last material");
Check.Eq(InventoryAttributeFilter.MaterialName(0), "", "no material");
Check.Eq(InventoryAttributeFilter.MaterialName(78), "", "past the list");
Check.Eq(InventoryAttributeFilter.SetName(13), "Soldiers", "set 13");
Check.Eq(InventoryAttributeFilter.SetName(81), "Cloak War Magic", "set 81");
Check.Eq(InventoryAttributeFilter.SetName(43), "Olthoi Armor C Rat", "a run of capitals splits before the next word");
Check.Eq(InventoryAttributeFilter.SetName(89), "Ninja New", "underscore");
Check.Eq(InventoryAttributeFilter.SetName(140), "Paragon Melee", "the last set");
Check.Eq(InventoryAttributeFilter.SetName(200), "Set 200", "a custom set id");
Check.Eq(InventoryAttributeFilter.SetName(0), "", "no set");
}
private static void Persistence()
{
var f = new InventoryAttributeFilter { Enabled = true, MatchAny = true };
f.Rules.Add(Rule(FilterAttr.ArmorLevel, FilterOp.AtLeast, 300));
f.Rules.Add(Rule(FilterAttr.Spells, FilterOp.Contains, text: "Legendary; Epic, 100%"));
f.Rules.Add(Rule(FilterAttr.Slot, FilterOp.IsNot, choice: 3));
f.Rules.Add(Rule(FilterAttr.AttackBonus, FilterOp.Equal, 12.5));
string line = f.Serialize();
Check.False(line.Contains('\n'), "one line");
InventoryAttributeFilter back = InventoryAttributeFilter.Parse(line);
Check.True(back.Enabled && back.MatchAny, "on, any");
Check.Eq(back.Rules.Count, 4, "four rules");
Check.Eq(back.Rules[0].Attr, FilterAttr.ArmorLevel, "rule 1 attribute");
Check.Eq(back.Rules[0].Op, FilterOp.AtLeast, "rule 1 operator");
Check.Near(back.Rules[0].Number, 300, 1e-9, "rule 1 number");
Check.Eq(back.Rules[1].Text, "Legendary; Epic, 100%", "separators in text survive");
Check.Eq(back.Rules[2].Choice, 3, "slot choice");
Check.Near(back.Rules[3].Number, 12.5, 1e-9, "fractional number");
Check.Eq(back.Serialize(), line, "stable");
InventoryAttributeFilter broken = InventoryAttributeFilter.Parse("v1;on;all;nosuch,ge,1,0,;al,has,1,0,;al,le,abc,0,;dmg,ge,40,0,");
Check.Eq(broken.Rules.Count, 2, "unknown attribute and wrong operator skipped");
Check.Near(broken.Rules[0].Number, 0, 1e-9, "a bad number reads as 0");
Check.Eq(broken.Rules[1].Attr, FilterAttr.MaxDamage, "later good rule kept");
Check.Eq(InventoryAttributeFilter.Parse("").Rules.Count, 0, "empty line");
Check.Eq(InventoryAttributeFilter.Parse("v9;on;all;al,ge,1,0,").Rules.Count, 0, "unknown version ignored");
Check.Eq(InventoryAttributeFilter.Parse("v1;on;all;slot,is,0,99,").Rules[0].Choice,
InventoryAttributeFilter.SlotNames.Length - 1, "slot choice clamped");
}
}

View file

@ -1,375 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.ItemInfo;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginCore;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// /ra iteminfo (Silentkelpie's rynth PR #1 idea, re-implemented): a Mag-Tools style one-line
// description of the selected or named item, identified first when the client hasn't
// appraised it. The formatter is checked on fake appraisal data; the command end to end on
// FakeHost (selection, ID request, the print when the ID lands, the timeout, name lookup).
internal static class ItemInfoTests
{
private const uint Player = 0x50000F21;
private const uint Sword = 0x80300001, Ring = 0x80300002, Scarab = 0x80300003, Scarab2 = 0x80300004;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
public static void Register(Runner r)
{
r.Add("iteminfo: a weapon's damage, mods, imbue, slayer, spells and wield line", WeaponLine);
r.Add("iteminfo: Crushing Blow as the dealt crit multiplier, Biting Strike as a crit chance", CritStats);
r.Add("iteminfo: armor's set, AL, ratings, tinks and wield level", ArmorLine);
r.Add("iteminfo: jewelry with mana, diff and craft; a bare item stays short", JewelryAndBareItem);
r.Add("iteminfo: a selected item already appraised prints at once, no ID", SelectedAppraised);
r.Add("iteminfo: an unappraised item is identified, then printed when the ID lands", IdentifiesThenPrints);
r.Add("iteminfo: no reply prints what the client has after the timeout", TimeoutPrints);
r.Add("iteminfo: a name picks the inventory item, exact before partial", NameLookup);
r.Add("iteminfo: nothing selected or no such item says so", NothingSelected);
r.Add("iteminfo on select: the player's pick prints quietly; the bot's own picks and the setting off do not", OnSelect);
}
// ── Fake appraisal data ─────────────────────────────────────────────
private sealed class Fake : IItemInfoSource
{
public string Name { get; init; } = "";
public Dictionary<uint, int> Ints { get; } = new();
public Dictionary<uint, double> Floats { get; } = new();
public List<int> Spells { get; } = new();
public IReadOnlyList<int> SpellIds => Spells;
public bool TryInt(uint key, out int value) => Ints.TryGetValue(key, out value);
public bool TryFloat(uint key, out double value) => Floats.TryGetValue(key, out value);
}
private static string Spell(int id) => SpellDatabase.GetSpellName(id);
/// <summary>Each part appears, in this order.</summary>
private static void InOrder(string text, string[] parts, string what)
{
int at = 0;
foreach (string p in parts)
{
int i = text.IndexOf(p, at, StringComparison.Ordinal);
Check.True(i >= 0, $"{what}: has \"{p}\" after position {at} in: {text}");
if (i >= 0) at = i + p.Length;
}
}
private static void WeaponLine()
{
var w = new Fake { Name = "Ornate Katar" };
w.Ints[ItemInfoText.IntItemType] = 0x1;
w.Ints[ItemInfoText.IntMaterial] = 61; // Iron
w.Ints[ItemInfoText.IntWeaponSkill] = 44; // Heavy Weapons
w.Ints[ItemInfoText.IntDamage] = 77;
w.Floats[ItemInfoText.FloatDamageVariance] = 0.4;
w.Ints[ItemInfoText.IntDamageType] = 16; // Fire
w.Ints[ItemInfoText.IntWeaponTime] = 30;
w.Floats[ItemInfoText.FloatWeaponOffense] = 1.18;
w.Floats[ItemInfoText.FloatMeleeDefense] = 1.20;
w.Floats[ItemInfoText.FloatMagicDefense] = 1.0; // +0%: left out
w.Ints[ItemInfoText.IntImbued] = 0x2 | 0x200; // Crippling Blow, Fire Rending
w.Ints[ItemInfoText.IntSlayerType] = 14; // Undead
w.Ints[ItemInfoText.IntTinks] = 2;
w.Spells.AddRange(new[] { 2531, 6107, 2531 }); // a repeat is named once
w.Ints[ItemInfoText.IntWieldReq] = 1;
w.Ints[ItemInfoText.IntWieldSkill] = 44;
w.Ints[ItemInfoText.IntWieldDiff] = 375;
w.Ints[ItemInfoText.IntWieldReq2] = 7;
w.Ints[ItemInfoText.IntWieldDiff2] = 150;
w.Ints[ItemInfoText.IntItemDifficulty] = 300;
w.Ints[ItemInfoText.IntWorkmanship] = 9;
w.Ints[ItemInfoText.IntValue] = 12345;
w.Ints[ItemInfoText.IntEncumbrance] = 350;
w.Ints[ItemInfoText.Ratings[0].Key] = 2; // D2
string s = ItemInfoText.Describe(w, Spell);
InOrder(s, new[]
{
"Iron Ornate Katar (Melee Weapon)", "[D2]", "Heavy Weapons", "Dmg 46-77 Fire", "Speed 30",
"(+18% atk, +20% md)", "Crippling Blow, Fire Rending", "Undead Slayer", "Tinks 2",
"Spells: Major Heavy Weapon Aptitude, Legendary Strength", "Heavy Weapons 375 to wield",
"Wield Lvl 150", "Diff 300", "Craft 9", "Mat Iron", "Value 12,345", "BU 350",
}, "weapon");
Check.False(s.Contains("mgd"), "a +0% mod is left out");
Check.Eq(s.Split("Major Heavy Weapon Aptitude").Length, 2, "each spell named once");
Check.False(s.Contains("not identified"), "identified: no note");
}
private static void CritStats()
{
var w = new Fake { Name = "Ornate Katar" };
w.Ints[ItemInfoText.IntItemType] = 0x1;
w.Ints[ItemInfoText.IntDamage] = 77;
w.Ints[ItemInfoText.IntWeaponTime] = 30;
w.Floats[ItemInfoText.FloatCriticalMultiplier] = 2.66;
w.Floats[ItemInfoText.FloatCriticalFrequency] = 0.15;
w.Floats[ItemInfoText.FloatWeaponOffense] = 1.18;
string s = ItemInfoText.Describe(w, Spell);
InOrder(s, new[] { "Dmg 77", "Speed 30", "Crushing Blow 3.66x", "Biting Strike 15%", "(+18% atk)" }, "crit stats");
w.Floats[ItemInfoText.FloatCriticalMultiplier] = 1.0; // an ordinary crit
w.Floats[ItemInfoText.FloatCriticalFrequency] = 0.125;
s = ItemInfoText.Describe(w, Spell);
Check.False(s.Contains("Crushing Blow"), "a 1.0 multiplier is an ordinary crit: not shown");
Check.True(s.Contains("Biting Strike 12.5%"), "a fractional crit chance keeps one decimal");
var a = new Fake { Name = "Chainmail Tassets" };
a.Ints[ItemInfoText.IntItemType] = 0x2;
a.Floats[ItemInfoText.FloatCriticalMultiplier] = 3.0;
Check.False(ItemInfoText.Describe(a, Spell).Contains("Crushing Blow"), "only weapons show crit stats");
}
private static void ArmorLine()
{
var a = new Fake { Name = "Chainmail Tassets" };
a.Ints[ItemInfoText.IntItemType] = 0x2;
a.Ints[ItemInfoText.IntSetId] = 16; // Defender's
a.Ints[ItemInfoText.IntArmorLevel] = 584;
a.Ints[371] = 1; // DR1
a.Ints[375] = 2; // CDR2
a.Ints[ItemInfoText.IntTinks] = 3;
a.Ints[ItemInfoText.IntWieldReq] = 7;
a.Ints[ItemInfoText.IntWieldDiff] = 180;
a.Ints[ItemInfoText.IntMaterial] = 64; // Steel
string s = ItemInfoText.Describe(a, Spell);
InOrder(s, new[] { "Steel Chainmail Tassets (Armor)", "Defender's Set", "AL 584", "[DR1 CDR2]", "Tinks 3", "Wield Lvl 180", "Mat Steel" }, "armor");
Check.False(s.Contains("Dmg"), "armor shows no damage");
Check.False(s.Contains("Speed"), "or speed");
}
private static void JewelryAndBareItem()
{
var j = new Fake { Name = "Gold Ring" };
j.Ints[ItemInfoText.IntItemType] = 0x8;
j.Ints[ItemInfoText.IntMaterial] = 60; // Gold: already in the name
j.Ints[ItemInfoText.IntCurMana] = 1200;
j.Ints[ItemInfoText.IntMaxMana] = 1500;
j.Ints[ItemInfoText.IntItemDifficulty] = 285;
j.Ints[ItemInfoText.IntWorkmanship] = 7;
j.Ints[ItemInfoText.IntAttuned] = 1;
j.Spells.Add(3964);
string s = ItemInfoText.Describe(j, Spell);
InOrder(s, new[] { "Gold Ring (Jewelry)", "Spells: Epic Focus", "Diff 285", "Mana 1200/1500", "Craft 7", "Mat Gold", "Attuned" }, "jewelry");
Check.False(s.Contains("Gold Gold"), "the material isn't doubled");
Check.False(s.Contains("AL "), "jewelry with no armor shows no AL");
var bare = new Fake { Name = "Mana Scarab" };
bare.Ints[ItemInfoText.IntStackSize] = 25;
string b = ItemInfoText.Describe(bare, Spell, identified: false);
Check.True(b.StartsWith("Mana Scarab x25", StringComparison.Ordinal), $"a stack shows its size: {b}");
Check.True(b.EndsWith("(not identified: no reply from the server)", StringComparison.Ordinal), "unidentified note last");
Check.Eq(b.Split(", ").Length, 2, "nothing else is made up");
}
// ── The command on FakeHost ─────────────────────────────────────────
private sealed class World
{
public readonly RynthAiPlugin P = new();
public readonly WorldObjectCache Cache;
public long Now = 1_000_000;
public World()
{
FakeHost.Reset();
FakeHost.Names[Player] = "Reader";
FakeHost.PlayerIdValue = Player;
FakeHost.Positions[Player] = (0x1048002Au, 100f, 100f, 0f);
FakeHost.PlayerPose = (0x1048002Au, 100f, 100f, 0f);
Item(Sword, "Ornate Katar", 0x1);
Item(Ring, "Gold Ring", 0x8);
Item(Scarab, "Mana Scarab", 0x80);
Item(Scarab2, "Platinum Scarab", 0x80);
FakeHost.Ints[(Sword, ItemInfoText.IntDamage)] = 77;
FakeHost.Ints[(Sword, ItemInfoText.IntWorkmanship)] = 9;
FakeHost.Ints[(Ring, ItemInfoText.IntWorkmanship)] = 7;
FakeHost.SpellIds[Ring] = new uint[] { 3964 };
FakeHost.WeaponCalls = true; // RequestId + HasAppraisalData
var host = FakeHost.Create(playerId: Player);
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, new LegacyUiSettings());
Set("_dashboard", dash);
Cache = new WorldObjectCache(host);
Cache.SetPlayerId(Player);
Set("_objectCache", Cache);
Set("_playerId", Player);
Set("_initialized", true);
Set("_loginComplete", true);
foreach (uint id in new[] { Sword, Ring, Scarab, Scarab2 }) Cache.OnCreateObject(id);
Cache.Tick();
RynthAiPlugin.ItemInfoClock = () => Now;
}
private static void Item(uint id, string name, uint type)
{
FakeHost.Names[id] = name;
FakeHost.Containers[id] = Player;
FakeHost.ItemTypes[id] = type;
FakeHost.Ints[(id, ItemInfoText.IntItemType)] = (int)type;
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public void Command(string text)
{
string[] parts = text.Split(' ', StringSplitOptions.RemoveEmptyEntries);
typeof(RynthAiPlugin).GetMethod("HandleItemInfoCommand", Any)!.Invoke(P, new object[] { parts });
}
public void Tick() => typeof(RynthAiPlugin).GetMethod("TickItemInfo", Any)!.Invoke(P, null);
public string[] InfoLines => FakeHost.Chat.Where(c => c.StartsWith("[RynthAi] ", StringComparison.Ordinal)
|| c.StartsWith(RynthAiPlugin.ItemPrefix, StringComparison.Ordinal)).ToArray();
}
private static void Done() => RynthAiPlugin.ItemInfoClock = () => Environment.TickCount64;
private static void OnSelect()
{
var w = new World();
try
{
void Select(uint id) => typeof(RynthAiPlugin).GetMethod("QueueItemInfoOnSelect", Any)!
.Invoke(w.P, new object?[] { id, w.Cache[unchecked((int)id)] });
FakeHost.Appraised.Add(Ring);
Select(Ring);
w.Tick();
Check.Eq(w.InfoLines.Length, 1, "the player's pick prints once");
Check.True(w.InfoLines[0].Contains("Gold Ring (Jewelry)"), $"the ring's line: {w.InfoLines.FirstOrDefault()}");
Select(Sword);
w.Tick();
Check.Eq(w.InfoLines.Length, 1, "unappraised: no 'identifying' chatter on select");
Check.True(FakeHost.IdRequests.Contains(Sword), "but the ID is asked for");
FakeHost.Appraised.Add(Sword);
w.Tick();
Check.Eq(w.InfoLines.Length, 2, "printed when the appraisal lands");
SelfSelect.Mark(Ring);
Select(Ring);
w.Tick();
Check.Eq(w.InfoLines.Length, 2, "an item RynthAi selected itself (the looter, a meta) prints nothing");
var dash = (LegacyDashboardRenderer)typeof(RynthAiPlugin).GetField("_dashboard", Any)!.GetValue(w.P)!;
dash.Settings.ItemInfoOnSelect = false;
Select(Scarab);
w.Tick();
Check.Eq(w.InfoLines.Length, 2, "setting off: nothing");
}
finally { Done(); }
}
private static void SelectedAppraised()
{
var w = new World();
try
{
FakeHost.SelectedItem = Ring;
FakeHost.Appraised.Add(Ring);
w.Command("/ra iteminfo");
Check.Eq(FakeHost.Chat.Count, 0, "the command only queues (the tick prints)");
w.Tick();
Check.Eq(FakeHost.IdRequests.Count, 0, "appraised: no ID request");
Check.Eq(w.InfoLines.Length, 1, "one line");
Check.True(w.InfoLines[0].Contains("Gold Ring (Jewelry)") && w.InfoLines[0].Contains("Spells: Epic Focus") && w.InfoLines[0].Contains("Craft 7"),
$"the ring's line: {w.InfoLines.FirstOrDefault()}");
}
finally { Done(); }
}
private static void IdentifiesThenPrints()
{
var w = new World();
try
{
FakeHost.SelectedItem = Sword;
w.Command("/ra iteminfo");
w.Tick();
Check.True(FakeHost.IdRequests.SequenceEqual(new[] { Sword }), "one ID request for the sword");
Check.Eq(w.InfoLines.Length, 1, "just the 'identifying' line so far");
Check.True(w.InfoLines[0].Contains("identifying Ornate Katar"), "says it is identifying");
w.Now += 1000;
w.Tick();
Check.Eq(w.InfoLines.Length, 1, "still waiting a second later");
FakeHost.Appraised.Add(Sword);
w.Tick();
Check.Eq(w.InfoLines.Length, 2, "printed when the appraisal arrives");
Check.True(w.InfoLines[1].Contains("Ornate Katar (Melee Weapon)") && w.InfoLines[1].Contains("Dmg 77") && !w.InfoLines[1].Contains("not identified"),
$"the sword's line: {w.InfoLines[1]}");
w.Now += 10_000;
w.Tick();
Check.Eq(w.InfoLines.Length, 2, "printed once");
Check.Eq(FakeHost.IdRequests.Count, 1, "never asked twice");
}
finally { Done(); }
}
private static void TimeoutPrints()
{
var w = new World();
try
{
FakeHost.SelectedItem = Sword;
w.Command("/ra iteminfo");
w.Tick();
w.Now += RynthAiPlugin.ItemInfoTimeoutMs - 1;
w.Tick();
Check.Eq(w.InfoLines.Length, 1, "not before the timeout");
w.Now += 1;
w.Tick();
Check.Eq(w.InfoLines.Length, 2, "printed at the timeout");
Check.True(w.InfoLines[1].Contains("Ornate Katar") && w.InfoLines[1].EndsWith("(not identified: no reply from the server)", StringComparison.Ordinal),
$"with what the client has and the note: {w.InfoLines[1]}");
}
finally { Done(); }
}
private static void NameLookup()
{
var w = new World();
try
{
FakeHost.Appraised.Add(Scarab);
FakeHost.Appraised.Add(Scarab2);
FakeHost.Appraised.Add(Ring);
w.Command("/ra iteminfo mana scarab");
w.Tick();
Check.True(w.InfoLines.Last().StartsWith("[RynthAi Item] Mana Scarab", StringComparison.Ordinal), $"exact name, any case: {w.InfoLines.Last()}");
w.Command("/ra iteminfo Scarab");
w.Tick();
Check.True(w.InfoLines.Last().Contains("Scarab") && !w.InfoLines.Last().Contains("not in your"), "a partial name finds a scarab");
w.Command("/ra iteminfo ring");
w.Tick();
Check.True(w.InfoLines.Last().StartsWith("[RynthAi Item] Gold Ring", StringComparison.Ordinal), "partial: Gold Ring");
Check.Eq(FakeHost.SelectedItem, 0u, "a named lookup doesn't need a selection");
}
finally { Done(); }
}
private static void NothingSelected()
{
var w = new World();
try
{
w.Command("/ra iteminfo");
w.Tick();
Check.True(w.InfoLines.Length == 1 && w.InfoLines[0].Contains("nothing selected"), "nothing selected says so");
w.Command("/ra iteminfo Shield of Nowhere");
w.Tick();
Check.True(w.InfoLines.Last().Contains("no \"Shield of Nowhere\" in your inventory"), $"unknown name says so: {w.InfoLines.Last()}");
Check.Eq(FakeHost.IdRequests.Count, 0, "and nothing is identified");
}
finally { Done(); }
}
}

View file

@ -0,0 +1,77 @@
using System.Collections.Generic;
using System.Linq;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Items "Remove Missing" (/ra items clean, LegacyWeaponsUi.CleanMissing): weapons and consumables
// whose item is no longer owned are removed, unless an unlisted item of the same name is in the
// pack, in which case the entry is re-pointed at it. Live entries are never touched.
internal static class ItemsCleanTests
{
public static void Register(Runner r)
{
r.Add("items clean: entries for items no longer owned are removed, owned ones kept", RemovesGone);
r.Add("items clean: a gone entry moves to an unlisted item of the same name", RelinksSameName);
r.Add("items clean: a gone duplicate of an already-listed item is removed, not re-pointed", DuplicateRemoved);
}
private static (LegacyUiSettings S, LegacyWeaponsUi W) Rig()
{
var s = new LegacyUiSettings();
return (s, new LegacyWeaponsUi(s, FakeHost.Create()));
}
private static WorldObject Wo(int id, string name) => new(id, name, AcObjectClass.MeleeWeapon);
private static void RemovesGone()
{
var (s, w) = Rig();
s.ItemRules.Add(new ItemRule { Id = 1, Name = "Gold Epee", Element = "Slash", Action = "Weapon" });
s.ItemRules.Add(new ItemRule { Id = 2, Name = "War Axe", Element = "Slash", Action = "Weapon" });
s.ConsumableRules.Add(new ConsumableRule { Id = 3, Name = "Peerless Healing Kit", Type = "HealthKit" });
s.ConsumableRules.Add(new ConsumableRule { Id = 4, Name = "Intricate Lockpick", Type = "Lockpick" });
var (removed, relinked) = w.CleanMissing(new List<WorldObject> { Wo(1, "Gold Epee"), Wo(3, "Peerless Healing Kit") });
Check.Eq(s.ItemRules.Count, 1, "one weapon left");
Check.Eq(s.ItemRules[0].Id, 1, "the owned weapon stays");
Check.Eq(s.ConsumableRules.Count, 1, "one consumable left");
Check.Eq(s.ConsumableRules[0].Id, 3, "the owned consumable stays");
Check.True(removed.SequenceEqual(new[] { "War Axe", "Intricate Lockpick" }), "the gone ones are reported");
Check.Eq(relinked.Count, 0, "nothing re-pointed");
}
private static void RelinksSameName()
{
var (s, w) = Rig();
s.ItemRules.Add(new ItemRule { Id = 10, Name = "Silver Acid Rapier", Element = "Acid", Action = "Weapon" });
s.ConsumableRules.Add(new ConsumableRule { Id = 20, Name = "Peerless Healing Kit", Type = "HealthKit" });
var (removed, relinked) = w.CleanMissing(new List<WorldObject> { Wo(11, "Silver Acid Rapier"), Wo(21, "peerless healing kit") });
Check.Eq(removed.Count, 0, "nothing removed");
Check.Eq(relinked.Count, 2, "both re-pointed");
Check.Eq(s.ItemRules[0].Id, 11, "weapon now points at the replacement");
Check.Eq(s.ItemRules[0].Element, "Acid", "its element is kept");
Check.Eq(s.ConsumableRules[0].Id, 21, "kits point at the new stack (name match ignores case)");
}
private static void DuplicateRemoved()
{
var (s, w) = Rig();
s.ItemRules.Add(new ItemRule { Id = 30, Name = "Ebony Jo", Element = "Bludgeon", Action = "Weapon" });
s.ItemRules.Add(new ItemRule { Id = 31, Name = "Ebony Jo", Element = "Bludgeon", Action = "Weapon" });
var (removed, relinked) = w.CleanMissing(new List<WorldObject> { Wo(30, "Ebony Jo") });
Check.Eq(s.ItemRules.Count, 1, "the gone copy is removed");
Check.Eq(s.ItemRules[0].Id, 30, "the live entry stays");
Check.Eq(relinked.Count, 0, "not re-pointed at the item already listed");
Check.Eq(removed.Count, 1, "one removal reported");
}
}

View file

@ -56,7 +56,19 @@ internal static class LearnSpellsTests
r.Add("learn: with the setting off nothing is looted or read", SettingOffDoesNothing);
r.Add("learn: a scroll already in the pack is read, only at a safe moment", PackScrollAtSafeMoment);
r.Add("learn: a read with no answer is retried once, then given up", ReadTimeoutBounded);
r.Add("learn: a combat stance from before a read is requested once after it", StanceRestoredAfterRead);
r.Add("learn: no restore from Peace, with Peace Mode When Idle, or once the mode changed", StanceNotRestoredWhenNotWanted);
r.Add("learn: scrolls back to back restore the stance once, after the last", StanceRestoredOnceAfterSeries);
r.Add("learn: a fight during the read window is not fought over", StanceNotRestoredIntoAFight);
r.Add("learn: a restore that would come minutes late (no ticks, or busy for ever) is dropped", StanceTooLate);
r.Add("learn: a changed weapon in hand cancels the restore", StanceWeaponChanged);
r.Add("learn: pacing holds do not use up the restore budget", StancePacerHold);
r.Add("learn: Peace Mode When Idle switched on mid-window cancels the restore", StancePeaceIdleToggled);
r.Add("learn: a restore that never lands is tried 3 times, then given up", StanceNeverLands);
r.Add("learn: Reset and the macro stopping close the series", StanceResetAndMacroStop);
r.Add("learn: settings - on by default, old files keep it on, /vt opt and metas reach ReadUnknownScrolls", Settings);
r.Add("learn: the gap to the next read counts from the last read's UseDone (no UseDone: 1.5 s from its end)", ReadGapFromUseDone);
r.Add("learn: the stance goes back at the last read's UseDone when no scroll is pending; a pending scroll waits", StanceRestoredAtLastUseDone);
}
// ── World ─────────────────────────────────────────────────────────────────
@ -225,6 +237,331 @@ internal static class LearnSpellsTests
}
}
// ── Stance restore ────────────────────────────────────────────────────────
private static ScrollLearner StanceRig(int modeBefore, bool peaceIdle, int scrolls, out Clock clock, out LegacyUiSettings s,
Action? setup = null, params uint[] extraIds)
{
BaseWorld();
setup?.Invoke();
FakeHost.CombatModeCalls = true;
FakeHost.CombatModeValue = modeBefore;
AddScroll(PackScroll, FlameBoltIII, "Scroll of Flame Bolt III", Player);
var ids = new List<uint> { PackScroll };
ids.AddRange(extraIds);
if (scrolls > 1) { AddScroll(Scroll2, FrostBoltI, "Scroll of Frost Bolt I", Player); ids.Add(Scroll2); }
var host = FakeHost.Create(Player);
var cache = FakeHost.MakeCache(host, Player, ids);
clock = new Clock();
s = Settings0();
s.PeaceModeWhenIdle = peaceIdle;
return Learner(host, s, cache, clock);
}
/// <summary>The read starts (the server then puts us in Peace), and ends with the scroll destroyed.</summary>
private static void FinishARead(ScrollLearner l, Clock c)
{
TickUntilRead(l, c);
Check.True(l.IsReading, "a read started");
FakeHost.CombatModeValue = CombatMode.NonCombat;
Learned();
l.OnChat("The scroll is destroyed.");
c.Now += 100;
l.Tick(true, 0);
Check.False(l.IsReading, "the read is over");
}
/// <summary>The scroll taught its spell (the fake server never deletes it, so mark it known).</summary>
private static void Learned() =>
FakeHost.Spellbook.Add((uint)(FakeHost.Uses.Last() == PackScroll ? FlameBoltIII : FrostBoltI));
private static void Quiet(ScrollLearner l, Clock c, long ms, bool safe = true, int busy = 0)
{
for (long t = 0; t < ms; t += 250) { c.Now += 250; l.Tick(safe, busy); }
}
private static void StanceRestoredAfterRead()
{
var l = StanceRig(CombatMode.Magic, false, 1, out var c, out _);
FinishARead(l, c);
Quiet(l, c, 1_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "not at once: a next scroll may follow");
Quiet(l, c, 3_000);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), CombatMode.Magic.ToString(), "Magic requested once after the read");
FakeHost.CombatModeValue = CombatMode.Magic; // the client switched
Quiet(l, c, 6_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 1, "and not again");
// The client is busy: the request waits, then goes out.
var b = StanceRig(CombatMode.Melee, false, 1, out var cb, out _);
FinishARead(b, cb);
Quiet(b, cb, 5_000, busy: 2);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "busy: held");
Quiet(b, cb, 500);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), CombatMode.Melee.ToString(), "free again: Melee requested");
Done();
}
private static void StanceNotRestoredWhenNotWanted()
{
var peace = StanceRig(CombatMode.NonCombat, false, 1, out var c1, out _);
FinishARead(peace, c1);
Quiet(peace, c1, 8_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "Peace before the read: nothing");
var idle = StanceRig(CombatMode.Magic, true, 1, out var c2, out _);
FinishARead(idle, c2);
Quiet(idle, c2, 8_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "Peace Mode When Idle on: nothing");
var moved = StanceRig(CombatMode.Magic, false, 1, out var c3, out _);
FinishARead(moved, c3);
FakeHost.CombatModeValue = CombatMode.Melee; // something else chose a mode
Quiet(moved, c3, 8_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "another subsystem set a mode: left alone");
Done();
}
private static void StanceRestoredOnceAfterSeries()
{
var l = StanceRig(CombatMode.Magic, false, 2, out var c, out _);
FinishARead(l, c);
Quiet(l, c, 2_000); // the second scroll starts inside the settle time
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no restore between reads");
if (!l.IsReading) TickUntilRead(l, c);
Check.True(l.IsReading, "the second scroll is being read");
FakeHost.CombatModeValue = CombatMode.NonCombat;
Learned();
l.OnChat("The scroll is destroyed.");
c.Now += 100;
l.Tick(true, 0);
Check.False(l.IsReading, "second read over");
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "still none");
Quiet(l, c, 3_750);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), CombatMode.Magic.ToString(), "one restore, after the last: ");
Done();
}
private static void StanceNotRestoredIntoAFight()
{
// The fight starts in the settle window and combat sets its own stance.
var l = StanceRig(CombatMode.Magic, false, 1, out var c, out _);
FinishARead(l, c);
Quiet(l, c, 1_000, safe: false);
FakeHost.CombatModeValue = CombatMode.Missile;
Quiet(l, c, 8_000, safe: false);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "combat owns the mode: no restore");
// Still in Peace when the settle time ends but a fight holds the tick: dropped, not queued behind it.
var f = StanceRig(CombatMode.Magic, false, 1, out var c2, out _);
FinishARead(f, c2);
Quiet(f, c2, 4_000, safe: false);
Quiet(f, c2, 4_000, safe: true);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "not safe at restore time: dropped");
Check.True(Logged("stance not restored"), "and logged: " + LearnLogs());
Done();
}
private const uint SwordW = 0x80000601, DaggerW = 0x80000602;
private static void Weapons()
{
foreach (var (id, name) in new[] { (SwordW, "Long Sword"), (DaggerW, "Dagger") })
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = 0x1;
FakeHost.Ints[(id, 9)] = 0x00100000;
}
FakeHost.Ints[(SwordW, 10)] = 0x00100000; // the sword is in hand
}
private static void StanceTooLate()
{
// No learner tick for 20 minutes (a death hold, a vendor hold): not Melee from a past life.
var l = StanceRig(CombatMode.Melee, false, 1, out var c, out _);
FinishARead(l, c);
c.Now += 1_200_000;
l.Tick(true, 0);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "20 minutes later: no request");
Check.True(Logged("stance not restored (too late)"), "and logged: " + LearnLogs());
Quiet(l, c, 4_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "and the series is closed");
// The client stays busy for ten minutes: dropped at the limit, not sent when it frees up.
var b = StanceRig(CombatMode.Magic, false, 1, out var cb, out _);
FinishARead(b, cb);
Quiet(b, cb, 600_000, busy: 1);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "busy for 10 minutes: nothing sent");
Quiet(b, cb, 2_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "and not when it frees up");
Check.True(Logged("stance not restored (too late)"), "logged: " + LearnLogs());
Done();
}
private static void StanceWeaponChanged()
{
// ACE reverts a mode the wielded weapon doesn't fit: a different weapon in hand cancels the restore.
var l = StanceRig(CombatMode.Melee, false, 1, out var c, out _, Weapons, SwordW, DaggerW);
FinishARead(l, c);
FakeHost.Ints.Remove((SwordW, 10));
FakeHost.Ints[(DaggerW, 10)] = 0x00100000;
Quiet(l, c, 6_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "another weapon in hand: no request");
Check.True(Logged("stance not restored (the weapon changed)"), "logged: " + LearnLogs());
// Same weapon: restored.
var s = StanceRig(CombatMode.Melee, false, 1, out var c2, out _, Weapons, SwordW, DaggerW);
FinishARead(s, c2);
Quiet(s, c2, 4_000);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), CombatMode.Melee.ToString(), "the same weapon: Melee requested");
Check.True(Logged("restoring Melee mode"), "the log names the mode: " + LearnLogs());
Done();
}
private static void StancePacerHold()
{
var l = StanceRig(CombatMode.Magic, false, 1, out var c, out _);
long t = 50_000_000;
ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => t;
try
{
FinishARead(l, c);
var host = FakeHost.Create(Player);
// Another subsystem's action has no answer yet, so a mode change is held for the whole window.
for (long ms = 0; ms < 8_000; ms += 250)
{
c.Now += 250; t += 250;
if (ActionPacer.Current(host) == null) ActionPacer.Begin(host, PacedKind.ItemUse, 1, "x", "Other", 0);
l.Tick(true, 0);
}
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "held by the pacer: nothing sent");
Check.False(Logged("did not change mode"), "and no false give-up: " + LearnLogs());
// The action is answered: exactly one request.
ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => t;
Quiet(l, c, 500);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), CombatMode.Magic.ToString(), "answered: exactly one request");
}
finally { ActionPacer.Enabled = false; ActionPacer.Reset(); ActionPacer.NowMs = () => Environment.TickCount64; Done(); }
}
private static void StancePeaceIdleToggled()
{
var l = StanceRig(CombatMode.Magic, false, 1, out var c, out var s);
FinishARead(l, c);
Quiet(l, c, 1_000);
s.PeaceModeWhenIdle = true;
Quiet(l, c, 8_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "switched on mid-window: no request");
Check.False(Logged("stance not restored"), "and silently: " + LearnLogs());
Done();
}
private static void StanceNeverLands()
{
var l = StanceRig(CombatMode.Magic, false, 1, out var c, out _);
FinishARead(l, c);
Quiet(l, c, 12_000); // the client never reads Magic
Check.Eq(FakeHost.CombatModeRequests.Count, ScrollLearner.RestoreMaxRequests, "exactly the cap");
Check.True(Logged("stance not restored (the client did not change mode)"), "then the give-up line: " + LearnLogs());
Quiet(l, c, 8_000);
Check.Eq(FakeHost.CombatModeRequests.Count, ScrollLearner.RestoreMaxRequests, "and no more");
Done();
}
private static void StanceResetAndMacroStop()
{
var l = StanceRig(CombatMode.Magic, false, 1, out var c, out _);
FinishARead(l, c);
l.Reset();
Quiet(l, c, 8_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "Reset closes the series");
// The macro stops while in Peace: no request, and it says why.
var m = StanceRig(CombatMode.Magic, false, 1, out var c2, out var s2);
FinishARead(m, c2);
s2.IsMacroRunning = false;
c2.Now += 500; m.Tick(true, 0);
Quiet(m, c2, 6_000);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "macro stopped: no request");
Check.True(Logged("stance not restored (the macro stopped)"), "logged when it was in Peace: " + LearnLogs());
// Still in stance (the read never took it out): closes without a log.
var n = StanceRig(CombatMode.Magic, false, 1, out var c3, out var s3);
FinishARead(n, c3);
FakeHost.CombatModeValue = CombatMode.Magic;
FakeHost.Logs.Clear();
s3.IsMacroRunning = false;
c3.Now += 500; n.Tick(true, 0);
Check.False(Logged("stance not restored"), "still in stance: closed silently: " + LearnLogs());
Done();
}
// ── Read pacing from UseDone (UseDone ~0.7 s after "The scroll is destroyed.") ──
/// <summary>As FinishARead, with the read taking ~2 s like ACE's (stance, read motion, 1 s read).</summary>
private static void FinishARealRead(ScrollLearner l, Clock c)
{
TickUntilRead(l, c);
Check.True(l.IsReading, "a read started");
FakeHost.CombatModeValue = CombatMode.NonCombat;
c.Now += 1_900;
Learned();
l.OnChat("The scroll is destroyed.");
c.Now += 100;
l.Tick(true, 0);
Check.False(l.IsReading, "the read is over");
}
private static void ReadGapFromUseDone()
{
// UseDone seen: the next read goes 250 ms after it, well inside the old 1.5 s from the chat.
var l = StanceRig(CombatMode.NonCombat, false, 2, out var c, out _, () => FakeHost.ServerGates = true);
FinishARealRead(l, c); // chat answer at t, ticked at t+100
c.Now += 600; FakeHost.UseDone(0); // the server's UseDone ~0.7 s after the chat
l.Tick(true, 0);
Check.False(l.IsReading, "not at the UseDone itself");
c.Now += ScrollLearner.ReadGapAfterUseDoneMs;
l.Tick(true, 0);
Check.True(l.IsReading, "the next read starts 250 ms after the UseDone (950 ms after the chat)");
Check.Eq(FakeHost.Uses.Count, 2, "two reads sent");
Done();
// No UseDone (an older engine or a lost one): 1.5 s from the read's end, as before.
var n = StanceRig(CombatMode.NonCombat, false, 2, out var cn, out _, () => FakeHost.ServerGates = true);
FinishARealRead(n, cn);
cn.Now += 850; n.Tick(true, 0);
Check.False(n.IsReading, "no UseDone: not at 950 ms");
cn.Now += 700; n.Tick(true, 0);
Check.True(n.IsReading, "no UseDone: 1.55 s after the read ended (its chat, seen on the next tick)");
// A UseDone that came before the read's send does not count for it.
var o = StanceRig(CombatMode.NonCombat, false, 2, out var co, out _, () => FakeHost.ServerGates = true);
FakeHost.UseDone(0); // an older action's answer
FinishARealRead(o, co);
co.Now += 850; o.Tick(true, 0);
Check.False(o.IsReading, "an earlier UseDone is not this read's");
Done();
}
private static void StanceRestoredAtLastUseDone()
{
// The last scroll: the stance goes back at its UseDone, not 3.5 s after the chat.
var l = StanceRig(CombatMode.Magic, false, 1, out var c, out _, () => FakeHost.ServerGates = true);
FinishARealRead(l, c);
l.Tick(true, 0);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "not before the UseDone");
c.Now += 600; FakeHost.UseDone(0);
l.Tick(true, 0);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), CombatMode.Magic.ToString(), "Magic requested at the UseDone");
Done();
// Another scroll is pending: no restore at the first read's UseDone; that read comes next.
var s = StanceRig(CombatMode.Magic, false, 2, out var cs, out _, () => FakeHost.ServerGates = true);
FinishARealRead(s, cs);
cs.Now += 600; FakeHost.UseDone(0);
s.Tick(true, 0);
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "a scroll is pending: no restore at the UseDone");
Done();
}
// ── Tests ─────────────────────────────────────────────────────────────────
private static void AceRule()

View file

@ -8,6 +8,7 @@ using System.Threading;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
@ -44,14 +45,20 @@ internal static class LootCorpseTests
r.Add("corpse: a corpse named late (stored nameless) becomes a Corpse on access", CorpseNamedLateOnAccess);
r.Add("loot chain: own corpse appears -> claimed -> opened -> item moved into the pack", FullLootChain);
r.Add("loot chain: 'My Kills Only' loots your kill and skips another player's", OwnershipModes);
r.Add("loot chain: an item the cache never saw created is found in the corpse's contents and looted", UnseenItemRescued);
r.Add("loot chain: without GetContainerContents an unseen item stays unseen (no crash)", UnseenItemOldEngine);
r.Add("loot starvation: a corpse waiting behind far-off combat gets a turn, a close monster keeps combat", LootStarvation);
r.Add("loot logging: a corpse held by combat is logged once, with the reason", HeldByCombatLoggedOnce);
r.Add("monster ignore: a close Priority 0 monster neither holds combat nor starves the corpse", IgnoredMonsterDoesNotHoldLoot);
r.Add("corpse close: a finished corpse is closed once (CloseContainer, API v76)", FinishedCorpseClosedOnce);
r.Add("corpse close: an engine without CloseContainer leaves it to the next open (no close)", FinishedCorpseNotClosedOnOldEngine);
r.Add("corpse close: an abandoned open corpse is closed once", AbandonedCorpseClosed);
r.Add("corpse close: stopping the macro mid-loot closes the open corpse, not marked completed", MacroStopClosesCorpse);
r.Add("loot pacing: a pickup waits for the last bend-down, and no retry is timed while it plays", PickupWaitsForAnimation);
r.Add("loot pacing: no pickup (first or retry) while the server owes an answer to a cast; it goes on the UseDone", PickupWaitsForCastAnswer);
r.Add("corpse close: not while the last item is between the corpse and the pack - it closes once the item is in the inventory", CloseWaitsForInventory);
r.Add("loot pacing: an item merged into a stack in the pack is confirmed without the 4 s arrival wait", MergedPickupConfirmedQuickly);
r.Add("loot pacing: each item taken restarts the corpse timeout, so a corpse with many keeps is looted to the end", ManyKeepsBeatTheTimeout);
}
// ── World set-up ──────────────────────────────────────────────────────────
@ -243,6 +250,48 @@ internal static class LootCorpseTests
Check.False(FakeHost.Uses.Contains(Gem), "never used (a use can wield)");
}
// 2026-10-11, Silentkelpie: a Necrolytic Extract on his own kill, a Keep rule for it, left on
// the corpse with no [LootEval] line. The cache never processed a create for it, so it was
// in neither the inventory nor the landscape set and GetContainedItems never returned it.
private static void UnseenItemRescued()
{
BaseWorld(corpsePositioned: true);
FakeHost.ContentsCalls = true;
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Cache.OnCreateObject(Corpse);
bot.Cache.Tick();
Check.True(bot.HasLootWork(), "looting wants the tick");
bot.Tick(BotActivity.Looting);
Check.Eq(bot.Get<int>("_targetCorpseId"), unchecked((int)Corpse), "the corpse is claimed");
// The gem is in the corpse but its create never reaches the cache.
bot.P.OnViewObjectContents(Corpse);
Check.False(bot.Cache.GetContainedItems(unchecked((int)Corpse)).Any(), "the cache has nothing for the corpse (the bug's state)");
for (int i = 0; i < 100 && !FakeHost.ExternalMoves.Any(m => m.Id == Gem); i++)
{
bot.Tick(BotActivity.Looting);
Thread.Sleep(10);
}
Check.True(FakeHost.Logs.Any(l => l.Contains("the object cache had missed") && l.Contains("Black Opal")), "the rescue is logged with the item");
Check.True(FakeHost.ExternalMoves.Contains((Gem, Player, 0)), "the unseen gem is looted");
}
private static void UnseenItemOldEngine()
{
BaseWorld(corpsePositioned: true);
var host = FakeHost.Create(Player); // no GetContainerContents
var bot = new Bot(host);
bot.Cache.OnCreateObject(Corpse);
bot.Cache.Tick();
bot.Tick(BotActivity.Looting);
bot.P.OnViewObjectContents(Corpse);
for (int i = 0; i < 20; i++) { bot.Tick(BotActivity.Looting); Thread.Sleep(5); }
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "nothing to find it with: not looted");
Check.False(FakeHost.Logs.Any(l => l.Contains("the object cache had missed")), "no rescue line");
}
private static void OwnershipModes()
{
BaseWorld(corpsePositioned: true);
@ -264,7 +313,7 @@ internal static class LootCorpseTests
Check.True(Loot(Other), "All Corpses: anyone's kill is looted");
}
private static Bot StarvationWorld(float monsterMeters, out CombatManager combat)
private static Bot StarvationWorld(float monsterMeters, out CombatManager combat, Action<LegacyUiSettings>? configure = null)
{
BaseWorld(corpsePositioned: true);
FakeHost.Names[Monster] = "Ancient Water Elemental";
@ -274,6 +323,7 @@ internal static class LootCorpseTests
var bot = new Bot(host);
bot.S.EnableCombat = true;
bot.S.MonsterRange = 50;
configure?.Invoke(bot.S);
bot.Cache.OnCreateObject(Corpse);
_ = bot.Cache[unchecked((int)Monster)];
bot.Cache.OnUpdateHealth(Monster, 1f);
@ -328,6 +378,24 @@ internal static class LootCorpseTests
Check.Eq(ActivityArbiter.Decide(in buffing), BotActivity.Buffing, "buffing still outranks a starved corpse");
}
private static void IgnoredMonsterDoesNotHoldLoot()
{
// The same close (2 m) Water Elemental that keeps combat in charge above, with its rule at Priority 0.
var bot = StarvationWorld(2f, out var combat, s => s.MonsterRules = new List<MonsterRule>
{
new MonsterRule { Name = "Default", Priority = 1 },
new MonsterRule { Name = "Water Elemental", Priority = 0 },
});
Check.False(combat.HasTargets, "an ignored monster is not a target");
Check.False(combat.HasNearbyMonsters, "and not a monster nearby");
Check.False(combat.HasCloseThreat(RynthAiPlugin.LootStarveCloseYards), "nor a close threat that keeps the starved corpse waiting");
Check.False(combat.HasEngageableTarget, "combat does not want the tick");
AgeCorpse(bot, RynthAiPlugin.LootStarveMs + 1000);
Check.True(bot.HasLootWork(), "the corpse is lootable");
var inputs = new ArbiterInputs(true, false, combat.HasEngageableTarget, true, false, true, combatEngaged: combat.HasEngageableTarget);
Check.Eq(ActivityArbiter.Decide(in inputs), BotActivity.Looting, "so looting has the tick without needing a starved turn");
}
private static void HeldByCombatLoggedOnce()
{
var bot = StarvationWorld(15f, out _);
@ -487,6 +555,47 @@ internal static class LootCorpseTests
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 2, "then one retry");
}
// A pickup sent while Bloodstone Bolt VII was unanswered came back
// "too busy" (ACE refuses a pickup while IsBusy); the assess-timeout path skips the busy gate.
private static void PickupWaitsForCastAnswer()
{
BaseWorld(corpsePositioned: true);
FakeHost.ServerGates = true; // GetCastBusyState, GetUseDoneSeq
var host = FakeHost.Create(Player);
var bot = new Bot(host);
long t = 80_000_000;
ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => t;
try
{
bot.Cache.OnCreateObject(Corpse);
bot.Cache.Tick();
bot.Tick(BotActivity.Looting);
Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened");
ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => t; // the open is answered
// A cast goes out (Combat) and has no answer yet when the contents arrive.
ActionPacer.Begin(host, PacedKind.Cast, 0, "Bloodstone Bolt VII", "Combat", FakeHost.UseDoneSeq);
bot.Cache.OnCreateObject(Gem);
bot.Cache.Tick();
bot.P.OnViewObjectContents(Corpse);
for (int i = 0; i < 10; i++) { t += 50; bot.Tick(BotActivity.Looting); Thread.Sleep(10); }
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "no pickup while the cast is unanswered");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("pickup waits - the server still owes an answer")), 1, "the hold is logged once");
FakeHost.UseDone(0); // the cast's answer
for (int i = 0; i < 100 && !FakeHost.ExternalMoves.Any(m => m.Id == Gem); i++) { t += 50; bot.Tick(BotActivity.Looting); Thread.Sleep(10); }
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "the pickup goes on the cast's UseDone");
// The item stays on the corpse (refused); the next cast is unanswered when a retry is due.
ActionPacer.Begin(host, PacedKind.Cast, 0, "Bloodstone Bolt I", "Combat", FakeHost.UseDoneSeq);
TickFor(bot, 1_500);
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "no retry while a cast is unanswered");
FakeHost.UseDone(0);
TickFor(bot, 300);
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 2, "the retry goes once it is answered");
}
finally { ActionPacer.Enabled = false; ActionPacer.Reset(); ActionPacer.NowMs = () => Environment.TickCount64; }
}
// 2026-10-07: the client takes an item off the corpse list as soon as the move is sent; the
// corpse was closed then, and the character picked the item up after the corpse closed.
private static void CloseWaitsForInventory()
@ -507,6 +616,83 @@ internal static class LootCorpseTests
Check.True(FakeHost.Logs.Any(l => l.Contains("pickup confirmed")), "and the pickup confirmed");
}
// 2026-10-11, Silentkelpie: Necrolytic Extracts and Coalesced Aetheria merge into stacks
// already in the pack (StackableMerge). The server removes the picked object and the client
// keeps no container for it, so it never "arrived" in the inventory and every such item
// waited out PickupArriveMaxMs (4 s) before the next pickup. With the 12 s corpse timeout,
// a corpse with three or four keeps was closed part way through.
private const uint Gem2 = 0x80261102, Gem3 = 0x80261103;
private static Bot ThreeGemCorpse(int corpseTimeoutMs)
{
BaseWorld(corpsePositioned: true);
foreach (uint g in new[] { Gem2, Gem3 })
{
FakeHost.Names[g] = "Black Opal";
FakeHost.ItemTypes[g] = ItemTypeGem;
FakeHost.Containers[g] = Corpse;
FakeHost.Appraised.Add(g);
}
// Stackable, as the real merging items are: only a stack that ends up with no container
// counts as merged (an unknown item off the corpse with no container is still on its way).
foreach (uint g in new[] { Gem, Gem2, Gem3 })
{
FakeHost.Ints[(g, 11)] = 100; // MaxStackSize
FakeHost.Ints[(g, 12)] = 1; // StackCount
}
FakeHost.CloseContainerCalls = true;
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.LootCorpseTimeoutMs = corpseTimeoutMs;
bot.Cache.OnCreateObject(Corpse);
bot.Cache.Tick();
bot.Tick(BotActivity.Looting);
Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened");
foreach (uint g in new[] { Gem, Gem2, Gem3 })
bot.Cache.OnCreateObject(g);
bot.Cache.Tick();
FakeHost.GroundContainer = Corpse;
bot.P.OnViewObjectContents(Corpse);
return bot;
}
/// <summary>Ticks for up to <paramref name="ms"/>; every item whose move went out merges at once.</summary>
private static long LootWithMerges(Bot bot, int ms, int wantMoves)
{
long start = Environment.TickCount64, end = start + ms;
while (Environment.TickCount64 < end && FakeHost.ExternalMoves.Select(m => m.Id).Distinct().Count() < wantMoves)
{
foreach (var m in FakeHost.ExternalMoves)
FakeHost.Containers[m.Id] = 0; // merged: gone from the corpse, no container
bot.Tick(BotActivity.Looting);
Thread.Sleep(10);
}
foreach (var m in FakeHost.ExternalMoves)
FakeHost.Containers[m.Id] = 0;
return Environment.TickCount64 - start;
}
private static void MergedPickupConfirmedQuickly()
{
var bot = ThreeGemCorpse(corpseTimeoutMs: 60_000);
long took = LootWithMerges(bot, 6000, wantMoves: 2);
Check.Eq(FakeHost.ExternalMoves.Select(m => m.Id).Distinct().Count(), 2, "the second pickup goes out");
Check.True(took < 2800, $"the second pickup follows the first merge in about the settle time, not 4 s more (took {took} ms)");
Check.True(FakeHost.Logs.Any(l => l.Contains("merged into a stack in the pack")), "the confirm says why");
}
private static void ManyKeepsBeatTheTimeout()
{
// Each merged item takes about PickupSettleMs (1 s) to confirm; three in a row take longer
// than this corpse timeout, which only an idle corpse should hit.
var bot = ThreeGemCorpse(corpseTimeoutMs: 2200);
LootWithMerges(bot, 8000, wantMoves: 3);
TickFor(bot, 1500);
var moved = FakeHost.ExternalMoves.Select(m => m.Id).Distinct().ToList();
Check.Eq(moved.Count, 3, "all three gems are taken (moved: " + string.Join(",", moved.Select(i => $"{i:X8}")) + ")");
Check.False(FakeHost.Logs.Any(l => l.Contains("abandoning corpse")), "the corpse is not abandoned on the timeout");
}
private static void TickFor(Bot bot, int ms)
{
long end = Environment.TickCount64 + ms;

View file

@ -0,0 +1,176 @@
using System;
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.Plugin.RynthAi.Loot;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Loot findings:
// H. A corpse use sent between the salvage UST use and the salvage execute is swallowed by the
// client (the salvage panel open wins), and the corpse loop then waits for an open that never
// comes. Corpse opens (and every automatic door/corpse use, via UseAudit.WorldUseHold) wait
// while the salvage panel is pending; the corpse claim's timeout is not charged meanwhile.
internal static class LootPacingTests
{
private const uint Player = 0x50000E01;
private const uint CorpseA = 0x80069ACE;
private const uint CorpseB = 0x80073023;
private const uint Ust = 0x80000E11;
private const uint Junk = 0x80000E12;
private const uint UstWcid = 20646;
private const uint ItemTypeContainer = 0x200, ItemTypeArmor = 0x2;
private const uint LongDescKey = 16;
private const string Me = "Drakkon";
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
private static (uint Cell, float X, float Y, float Z) Me0 => (0x6347028Au, 100f, 100f, 0f);
public static void Register(Runner r)
{
r.Add("salvage/loot: no corpse open (or auto door/corpse use) while the salvage panel is pending; the claim is kept and opened after the execute", CorpseOpenWaitsForSalvagePanel);
}
private static void World()
{
FakeHost.Reset();
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal + salvage panel
FakeHost.WeaponCalls = true;
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.StopCalls = true;
FakeHost.Names[Player] = Me;
FakeHost.Positions[Player] = Me0;
FakeHost.PlayerPose = Me0;
foreach ((uint id, float dx) in new[] { (CorpseA, 1.0f), (CorpseB, 1.5f) })
{
FakeHost.Names[id] = "Corpse of Olthoi Swarm Worker";
FakeHost.ItemTypes[id] = ItemTypeContainer;
FakeHost.Strings[(id, LongDescKey)] = $"Killed by {Me}.";
FakeHost.NotAttackable.Add(id);
FakeHost.Positions[id] = (Me0.Cell, Me0.X + dx, Me0.Y, Me0.Z);
}
FakeHost.Names[Ust] = "Salvaging Ust";
FakeHost.Wcids[Ust] = UstWcid;
FakeHost.Names[Junk] = "Iron Breastplate";
FakeHost.ItemTypes[Junk] = ItemTypeArmor;
FakeHost.Ints[(Junk, 131)] = 64; // MaterialType
}
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,
EnableCombineSalvage = false,
SalvageOpenDelayFirstMs = 400, SalvageOpenDelayFastMs = 50,
SalvageAddDelayFirstMs = 600, SalvageAddDelayFastMs = 50,
SalvageSalvageDelayMs = 50,
SalvageResultDelayFirstMs = 1000, SalvageResultDelayFastMs = 250,
};
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);
Cache.OnCreateObject(CorpseA);
Cache.OnCreateObject(CorpseB);
_ = Cache[unchecked((int)Ust)]; // filed as the indexer does (FakeHost.MakeCache)
_ = Cache[unchecked((int)Junk)];
Cache.Tick();
string profile = Path.Combine(Program.TempRoot, "loot-pacing-test.json");
var p = new LootProfile { Name = "nothing" };
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 void Tick()
{
Set("_activity", BotActivity.Looting);
Call("TickCorpseOpening");
}
}
private static int CorpseUses() => FakeHost.Uses.Count(u => u == CorpseA || u == CorpseB);
private static void CorpseOpenWaitsForSalvagePanel()
{
World();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
long now = 60_000_000;
var savedClock = RynthAiPlugin.CorpseClock;
RynthAiPlugin.CorpseClock = () => now;
try
{
UseAudit.Reset("RynthAi", () => true);
// As RynthAiPlugin's init wires it.
UseAudit.WorldUseHold = (Func<string?>)Delegate.CreateDelegate(typeof(Func<string?>), bot.P,
typeof(RynthAiPlugin).GetMethod("SalvagePanelHold", Any)!);
var mgr = new SalvageManager(host, bot.S, bot.Cache) { Clock = () => now };
bot.Set("_salvageManager", mgr);
FakeHost.OnSalvageExecute = added =>
{
foreach (uint id in added) { FakeHost.Names.Remove(id); bot.Cache.OnDeleteObject(id); }
};
mgr.EnqueueItem(Junk);
// The salvage cycle starts: UST used, panel not executed yet.
for (int i = 0; i < 200 && !FakeHost.Uses.Contains(Ust); i++) { now += 50; mgr.OnTick(0); }
Check.True(FakeHost.Uses.Contains(Ust), "the UST is used");
FakeHost.UseDone(0); // the server answers the UST use (the panel opens)
Check.True(mgr.PanelPending, "the salvage panel is pending (UST used, no execute yet)");
// 20 s with the panel pending (longer than the 12 s claim timeout): looting ticks on.
for (int i = 0; i < 200; i++) { bot.Tick(); now += 100; }
Check.Eq(CorpseUses(), 0, "no corpse use while the salvage panel is pending");
Check.Eq(bot.Get<int>("_targetCorpseId"), unchecked((int)CorpseA), "the claim is kept, not abandoned on timeout");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("waits for the salvage panel")), 1, "the wait is logged once");
// Any other automatic door/corpse use is held too (nav doors, the use check's probes).
Check.False(host.UseFor(CorpseB, "Nav", "test: an automatic world use"), "an automatic world use is held");
Check.Eq(CorpseUses(), 0, "and not sent");
Check.True(FakeHost.Logs.Any(l => l.Contains("HELD 0x80073023")), "the hold is logged");
// The panel executes; the corpse opens on the next looting tick.
for (int i = 0; i < 200 && FakeHost.SalvageExecutes.Count == 0; i++) { now += 50; mgr.OnTick(0); }
Check.Eq(FakeHost.SalvageExecutes.Count, 1, "the salvage goes out");
Check.False(mgr.PanelPending, "the panel is no longer pending once the execute is sent");
for (int i = 0; i < 5 && CorpseUses() == 0; i++) { bot.Tick(); now += 100; }
Check.Eq(CorpseUses(), 1, "the corpse is opened after the execute");
Check.True(FakeHost.Uses.Contains(CorpseA), "the claimed corpse");
}
finally
{
RynthAiPlugin.CorpseClock = savedClock;
UseAudit.Reset("?", null);
}
}
}

View file

@ -28,6 +28,8 @@ internal static class LootSalvageTests
private const uint ItemBase = 0x80000B00;
private const uint UstWcid = 20646;
private const uint ItemTypeJewelry = 0x8, ItemTypeGem = 0x800, ItemTypeContainer = 0x200, ItemTypeArmor = 0x2;
private static readonly string TestLogDirectory =
System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthAiHostTests", "Diagnostics");
public static void Register(Runner r)
{
@ -43,6 +45,19 @@ internal static class LootSalvageTests
r.Add("salvage: no UST - HasUst false, no combine sweep; a UST in the pack turns both on", SalvageNoUstNoSweep);
r.Add("salvage: skipped items are logged with their reason, once per batch", SalvageSkipReasonsLogged);
r.Add("salvage: an item that keeps failing rests, retries, and is given up with a log line", SalvageGiveUpIsBounded);
// Salvage without the panel (engine API v82 SalvageDirect, 2026-10-12).
r.Add("salvage without the panel: one request with every item, the panel never opens", DirectOneRequest);
r.Add("salvage without the panel: setting off, or an engine without it -> the panel", DirectNotChosenWhenOffOrUnsupported);
r.Add("salvage without the panel: batches of up to 50 items, the rest in the next request", DirectBatching);
r.Add("salvage without the panel: worn, retained, Items-list items and the UST never go in", DirectFiltersStillApply);
r.Add("salvage without the panel: matching under-full bags ride along and merge", DirectBagsRideAlong);
r.Add("salvage without the panel: a request that changes nothing is tried once through the panel", DirectFallsBackToPanelOnce);
r.Add("salvage without the panel: an unbound sender -> the panel, and off for the session", DirectUnboundSenderFallsBack);
r.Add("salvage without the panel: after 3 batches the panel had to save, the session uses the panel", DirectTurnsOffAfterRepeatedFallbacks);
r.Add("salvage without the panel: no UST -> no request, no panel, items kept", DirectNoUstDoesNothing);
r.Add("salvage without the panel: a failing item is still bounded (rests, gives up)", DirectGiveUpIsBounded);
r.Add("salvage without the panel: the combine sweep sends bag groups as requests too", DirectCombineSweep);
r.Add("salvage without the panel: a combine request that merges nothing is tried once through the panel", DirectCombineFallsBackToPanel);
}
// ── Loot pickup (bug A) ───────────────────────────────────────────────────
@ -129,10 +144,17 @@ internal static class LootSalvageTests
public long Now = 1_000_000;
public readonly HashSet<uint> Unsalvageable = new();
public World(IEnumerable<uint> items, bool withUst = true, Action? beforeCreate = null)
/// <summary>Direct worlds: the server ignores requests without the panel (they change nothing).</summary>
public bool ServerIgnoresDirect;
/// <summary>Salvage bags the fake server made (one per request that salvaged something).</summary>
public readonly List<uint> NewBags = new();
private uint _nextBag = 0x80000E00;
public World(IEnumerable<uint> items, bool withUst = true, Action? beforeCreate = null, bool direct = false)
{
FakeHost.Reset();
FakeHost.SalvageCalls = true;
FakeHost.SalvageDirectCalls = direct;
var ids = new List<uint>();
if (withUst) AddUst(ids);
foreach (uint id in items)
@ -144,6 +166,10 @@ internal static class LootSalvageTests
}
beforeCreate?.Invoke();
Host = FakeHost.Create(Player);
// SalvageManager logs through RynthLog (LogCat.Salvage), which forwards to the host it
// is bound to; bind it to this fake so FakeHost.Logs sees the [Salvage] lines. A temp
// folder keeps the test's diagnostics.json and log files out of the real install.
RynthLog.Init(Host, TestLogDirectory);
Cache = FakeHost.MakeCache(Host, Player, ids);
Settings.EnableCombineSalvage = false; // bag merging has its own tests in game
Settings.SalvageOpenDelayFirstMs = 400; Settings.SalvageOpenDelayFastMs = 50;
@ -151,15 +177,41 @@ internal static class LootSalvageTests
Settings.SalvageSalvageDelayMs = 50;
Settings.SalvageResultDelayFirstMs = 1000; Settings.SalvageResultDelayFastMs = 250;
Mgr = new SalvageManager(Host, Settings, Cache) { Clock = () => Now };
FakeHost.OnSalvageExecute = added =>
FakeHost.OnSalvageExecute = added => ServerSalvages(Ust, added);
// The 0x027D request without the panel reaches the same server code (ACE HandleSalvaging).
FakeHost.OnSalvageDirect = (tool, ids) => { if (!ServerIgnoresDirect) ServerSalvages(tool, ids); };
}
/// <summary>What ACE does with a salvage request: a carried UST, then each salvageable id is
/// consumed (salvage bags too, merged), and one new bag holds the result.</summary>
private void ServerSalvages(uint tool, List<uint> ids)
{
if (!InWorld(tool)) { Mgr.OnChatWindowText("You do not own that salvage tool!"); return; }
int consumed = 0;
foreach (uint id in ids)
{
foreach (uint id in added)
{
if (Unsalvageable.Contains(id)) continue;
FakeHost.Names.Remove(id);
Cache.OnDeleteObject(id);
}
};
if (Unsalvageable.Contains(id) || !InWorld(id)) continue;
FakeHost.Names.Remove(id);
Cache.OnDeleteObject(id);
consumed++;
}
if (consumed == 0) return;
uint bag = _nextBag++;
NewBags.Add(bag);
FakeHost.Names[bag] = "Salvage (100)";
FakeHost.Ints[(bag, 131)] = 64;
_ = Cache[unchecked((int)bag)];
Mgr.OnChatWindowText("You obtain 100 Steel (ws 7.00) using your knowledge of Salvaging.");
}
/// <summary>An under-full salvage bag of material 64 in the pack.</summary>
public void AddBag(uint id, int structure)
{
FakeHost.Names[id] = $"Salvage ({structure})";
FakeHost.Ints[(id, 131)] = 64;
FakeHost.Ints[(id, 92)] = structure;
FakeHost.Ints[(id, 91)] = 100;
_ = Cache[unchecked((int)id)];
}
public static void AddUst(List<uint> ids)
@ -353,4 +405,247 @@ internal static class LootSalvageTests
int logLines = w.SalvageLogs.Count();
Check.True(logLines < 25, $"bounded logging ({logLines} salvage lines over 10 minutes)");
}
// ── Salvage without the panel ─────────────────────────────────────────────
private static int PanelOpens => FakeHost.Uses.Count(u => u == Ust);
private static void DirectOneRequest()
{
var items = Items(12);
var w = new World(items, direct: true);
foreach (uint id in items) w.Mgr.EnqueueItem(id);
w.Run(5_000);
Check.Eq(FakeHost.SalvageDirects.Count, 1, "one request");
Check.Eq(FakeHost.SalvageDirects[0].Tool, Ust, "with the UST");
Check.Eq(FakeHost.SalvageDirects[0].Ids.Count, 12, "and all twelve items");
Check.Eq(PanelOpens, 0, "the UST is never used (the panel never opens)");
Check.Eq(FakeHost.SalvageAdds.Count + FakeHost.SalvageExecutes.Count, 0, "no panel calls");
Check.True(items.All(id => !w.InWorld(id)), "every item salvaged");
string line = w.SalvageLogs.FirstOrDefault(l => l.Contains("Batch 1", StringComparison.Ordinal)) ?? "";
Check.True(line.Contains("Batch 1 without the panel: salvaged 12/12", StringComparison.Ordinal), "one summary line, saying how: " + line);
Check.True(line.Contains("1 new salvage bag(s)", StringComparison.Ordinal), "the new bag is noticed");
Check.True(line.Contains("using your knowledge of", StringComparison.Ordinal), "the server's line is quoted");
var v = w.Mgr.GetStateSnapshot();
Check.True(v.DirectOn && v.HasDirectApi, "the snapshot says it is on");
Check.Eq(v.DirectRequests, 1, "one request counted");
Check.False(w.Mgr.IsBusy, "idle afterwards");
}
private static void DirectNotChosenWhenOffOrUnsupported()
{
var items = Items(3);
var w = new World(items, direct: true);
w.Settings.SalvageWithoutPanel = false;
foreach (uint id in items) w.Mgr.EnqueueItem(id);
w.Run(10_000);
Check.Eq(FakeHost.SalvageDirects.Count, 0, "setting off: no request without the panel");
Check.Eq(FakeHost.SalvageExecutes.Count, 1, "the panel salvaged them");
Check.Eq(w.Mgr.GetStateSnapshot().DirectOffReason, "setting off", "the snapshot says why");
var w2 = new World(items, direct: false); // an engine before v81: no SalvageDirectFn
foreach (uint id in items) w2.Mgr.EnqueueItem(id);
w2.Run(10_000);
Check.Eq(FakeHost.SalvageExecutes.Count, 1, "older engine: the panel");
Check.True(items.All(id => !w2.InWorld(id)), "every item salvaged");
Check.Eq(w2.Mgr.GetStateSnapshot().DirectOffReason, "engine before API v82", "the snapshot says why");
}
private static void DirectBatching()
{
var items = Items(SalvageManager.MaxDirectBatchItems + 10);
var w = new World(items, direct: true);
foreach (uint id in items) w.Mgr.EnqueueItem(id);
w.Run(10_000);
Check.Eq(FakeHost.SalvageDirects.Count, 2, "two requests");
Check.Eq(FakeHost.SalvageDirects[0].Ids.Count, SalvageManager.MaxDirectBatchItems, "a full first request (50)");
Check.Eq(FakeHost.SalvageDirects[1].Ids.Count, 10, "the rest in the second");
Check.True(FakeHost.SalvageDirects.All(r => r.Ids.Count <= RynthCore.PluginSdk.RynthCoreHost.MaxSalvageDirectItems), "never over the engine's cap");
Check.Eq(FakeHost.SalvageDirects.SelectMany(r => r.Ids).Distinct().Count(), items.Length, "each item sent once");
Check.True(items.All(id => !w.InWorld(id)), "every item salvaged");
Check.Eq(PanelOpens, 0, "no panel");
}
private static void DirectFiltersStillApply()
{
uint good = ItemBase + 1, retained = ItemBase + 2, listed = ItemBase + 3;
var w = new World(new[] { good, retained, listed, Ring }, direct: true, beforeCreate: () =>
{
FakeHost.Names[good] = "Iron Breastplate";
FakeHost.Names[retained] = "Heirloom Coat";
FakeHost.Bools[(retained, 91)] = true;
FakeHost.Names[listed] = "Favourite Sword";
FakeHost.Names[Ring] = "Gold Ring";
FakeHost.ItemTypes[Ring] = ItemTypeJewelry;
FakeHost.Wielded[Ring] = 0x40000;
});
w.Settings.ItemRules.Add(new ItemRule { Id = unchecked((int)listed), Name = "Favourite Sword" });
foreach (uint id in new[] { good, retained, listed, Ring, Ust }) w.Mgr.EnqueueItem(id);
w.Run(5_000);
Check.Eq(FakeHost.SalvageDirects.Count, 1, "one request");
Check.Eq(string.Join(",", FakeHost.SalvageDirects[0].Ids), good.ToString(), "only the good item went in");
Check.True(w.InWorld(retained) && w.InWorld(listed) && w.InWorld(Ring) && w.InWorld(Ust), "the skipped items are untouched");
string line = w.SalvageLogs.FirstOrDefault(l => l.Contains("Batch 1", StringComparison.Ordinal)) ?? "";
Check.True(line.Contains("retained: Heirloom Coat", StringComparison.Ordinal), "the retained item and why");
Check.True(line.Contains("on the Items list: Favourite Sword", StringComparison.Ordinal), "the Items-list item and why");
Check.True(line.Contains("it is the UST", StringComparison.Ordinal), "the UST and why");
Check.True(w.SalvageLogs.Any(l => l.Contains("worn", StringComparison.Ordinal) && l.Contains("Gold Ring", StringComparison.Ordinal)), "the worn ring and why");
}
private static void DirectBagsRideAlong()
{
uint item = ItemBase + 1, bagA = 0x80000D01, bagB = 0x80000D02, fullBag = 0x80000D03;
var w = new World(new[] { item }, direct: true);
w.AddBag(bagA, 30);
w.AddBag(bagB, 45);
w.AddBag(fullBag, 100);
w.Mgr.EnqueueItem(item);
w.Run(5_000);
Check.Eq(FakeHost.SalvageDirects.Count, 1, "one request");
var ids = FakeHost.SalvageDirects[0].Ids;
Check.True(ids[0] == item && ids.Contains(bagA) && ids.Contains(bagB), "the item, then the two under-full bags");
Check.False(ids.Contains(fullBag), "a full bag stays out");
Check.True(!w.InWorld(bagA) && !w.InWorld(bagB) && w.InWorld(fullBag), "the under-full bags merged, the full one untouched");
string line = w.SalvageLogs.FirstOrDefault(l => l.Contains("Batch 1", StringComparison.Ordinal)) ?? "";
Check.True(line.Contains("2/2 bag(s) merged in", StringComparison.Ordinal), "the log says the bags merged: " + line);
}
private static void DirectFallsBackToPanelOnce()
{
var items = Items(4);
var w = new World(items, direct: true) { ServerIgnoresDirect = true };
foreach (uint id in items) w.Mgr.EnqueueItem(id);
w.Run(15_000);
Check.Eq(FakeHost.SalvageDirects.Count, 1, "one request without the panel");
Check.Eq(PanelOpens, 1, "then the panel, once");
Check.Eq(FakeHost.SalvageExecutes.Count, 1, "one Salvage press");
Check.Eq(FakeHost.SalvageExecutes[0].Count, 4, "with the same four items");
Check.True(items.All(id => !w.InWorld(id)), "the panel salvaged them");
Check.True(w.SalvageLogs.Any(l => l.Contains("changed nothing", StringComparison.Ordinal) && l.Contains("no salvage reply", StringComparison.Ordinal)
&& l.Contains("once through the panel", StringComparison.Ordinal)), "the log says why it fell back");
Check.True(w.SalvageLogs.Any(l => l.Contains("Batch 1 through the panel (the request without the panel changed nothing): salvaged 4/4", StringComparison.Ordinal)),
"the batch line says how it went");
var v = w.Mgr.GetStateSnapshot();
Check.Eq(v.DirectFallbacks, 1, "one fallback counted");
Check.True(v.DirectOn, "one fallback doesn't turn it off");
Check.Eq(v.ItemsSalvaged, 4, "session total");
}
private static void DirectUnboundSenderFallsBack()
{
var items = Items(3);
var w = new World(items, direct: true);
FakeHost.SalvageDirectAnswer = -1; // the engine couldn't bind Event_CreateTinkeringTool
foreach (uint id in items) w.Mgr.EnqueueItem(id);
w.Run(10_000);
Check.Eq(FakeHost.SalvageExecutes.Count, 1, "the panel took the batch");
Check.True(items.All(id => !w.InWorld(id)), "every item salvaged");
Check.True(w.SalvageLogs.Any(l => l.Contains("wasn't sent", StringComparison.Ordinal) && l.Contains("isn't bound", StringComparison.Ordinal)), "the log says why");
var v = w.Mgr.GetStateSnapshot();
Check.False(v.DirectOn, "off for the session");
Check.True(v.DirectOffReason.Contains("isn't bound", StringComparison.Ordinal), "with the reason");
foreach (uint id in Items(2).Select(i => i + 100)) { w.Arrive(id, "Steel Helm"); w.Mgr.EnqueueItem(id); }
w.Run(10_000);
Check.Eq(FakeHost.SalvageDirects.Count, 1, "no second request without the panel");
Check.Eq(FakeHost.SalvageExecutes.Count, 2, "the next batch goes straight to the panel");
}
private static void DirectTurnsOffAfterRepeatedFallbacks()
{
var w = new World(Array.Empty<uint>(), direct: true) { ServerIgnoresDirect = true };
for (int round = 0; round < SalvageManager.DirectOffAfterFailures; round++)
{
uint id = ItemBase + 200 + (uint)round;
w.Arrive(id, $"Steel Helm {round}");
w.Mgr.EnqueueItem(id);
w.Run(10_000);
Check.False(w.InWorld(id), $"round {round + 1}: salvaged through the panel");
}
Check.Eq(FakeHost.SalvageDirects.Count, SalvageManager.DirectOffAfterFailures, "one request per round");
Check.False(w.Mgr.GetStateSnapshot().DirectOn, "then off for the session");
Check.True(FakeHost.Chat.Any(c => c.Contains("using the salvage panel for the rest of the session", StringComparison.Ordinal)), "chat says so");
uint next = ItemBase + 300;
w.Arrive(next, "Steel Helm 9");
w.Mgr.EnqueueItem(next);
w.Run(10_000);
Check.Eq(FakeHost.SalvageDirects.Count, SalvageManager.DirectOffAfterFailures, "no more requests without the panel");
Check.False(w.InWorld(next), "the panel salvaged the next one");
}
private static void DirectNoUstDoesNothing()
{
var items = Items(3);
var w = new World(items, withUst: false, direct: true);
foreach (uint id in items) w.Mgr.EnqueueItem(id);
w.Run(5_000);
Check.Eq(FakeHost.SalvageDirects.Count, 0, "no request without a UST");
Check.Eq(FakeHost.SalvageExecutes.Count + FakeHost.SalvageAdds.Count, 0, "no panel either");
Check.Eq(FakeHost.Chat.Count(c => c.Contains("no UST", StringComparison.Ordinal)), 1, "one chat warning");
Check.Eq(w.Mgr.GetStateSnapshot().QueueCount, 3, "the items are kept");
Check.False(w.Mgr.HasUst(), "HasUst false (looting leaves salvage-only items)");
var ids = new List<uint>();
World.AddUst(ids);
_ = w.Cache[unchecked((int)Ust)];
w.Run(15_000);
Check.Eq(FakeHost.SalvageDirects.Count, 1, "a request once a UST is there");
Check.True(items.All(id => !w.InWorld(id)), "every item salvaged");
}
private static void DirectGiveUpIsBounded()
{
uint stubborn = ItemBase + 7;
var w = new World(new[] { stubborn }, direct: true);
w.Unsalvageable.Add(stubborn); // the server never consumes it (no request, no panel)
w.Mgr.EnqueueItem(stubborn);
w.Run(10 * 60_000, step: 100);
Check.Eq(FakeHost.SalvageDirects.Count, 3 * SalvageManager.MaxGiveUpRounds, "three rounds of three tries without the panel");
Check.Eq(FakeHost.SalvageExecutes.Count, 3 * SalvageManager.MaxGiveUpRounds, "each tried once through the panel");
Check.True(w.SalvageLogs.Any(l => l.Contains("Giving up on", StringComparison.Ordinal)), "giving up is logged");
Check.Eq(w.Mgr.GetStateSnapshot().TrackedItems, 0, "no longer tracked");
Check.True(w.Mgr.GetStateSnapshot().DirectOn, "the panel never succeeded either: no reason to turn it off");
}
private static void DirectCombineSweep()
{
uint bagA = 0x80000D01, bagB = 0x80000D02, bagC = 0x80000D03;
var w = new World(Array.Empty<uint>(), direct: true);
w.Settings.EnableCombineSalvage = true;
w.AddBag(bagA, 20);
w.AddBag(bagB, 30);
w.AddBag(bagC, 40);
w.Run(5_000);
Check.Eq(FakeHost.SalvageDirects.Count, 1, "one request for the group");
Check.Eq(string.Join(",", FakeHost.SalvageDirects[0].Ids.OrderBy(x => x)), string.Join(",", new[] { bagA, bagB, bagC }), "with the three bags");
Check.Eq(PanelOpens, 0, "no panel");
Check.True(!w.InWorld(bagA) && !w.InWorld(bagB) && !w.InWorld(bagC), "merged");
Check.True(w.SalvageLogs.Any(l => l.Contains("Combine group 1/1 (without the panel): merged 3 bag(s)", StringComparison.Ordinal)), "the log says so");
}
private static void DirectCombineFallsBackToPanel()
{
uint bagA = 0x80000D01, bagB = 0x80000D02;
var w = new World(Array.Empty<uint>(), direct: true) { ServerIgnoresDirect = true };
w.Settings.EnableCombineSalvage = true;
w.AddBag(bagA, 20);
w.AddBag(bagB, 30);
w.Run(8_000);
Check.Eq(FakeHost.SalvageDirects.Count, 1, "one request for the group");
Check.Eq(PanelOpens, 1, "then the panel, once");
Check.Eq(FakeHost.SalvageExecutes.Count, 1, "one Salvage press");
Check.True(!w.InWorld(bagA) && !w.InWorld(bagB), "the panel merged them");
Check.True(w.SalvageLogs.Any(l => l.Contains("merged nothing", StringComparison.Ordinal) && l.Contains("trying the panel once", StringComparison.Ordinal)), "the fallback is logged");
Check.True(w.SalvageLogs.Any(l => l.Contains("Combine group 1/1 (panel retry): merged", StringComparison.Ordinal)), "the retry's result is logged");
}
}

View file

@ -0,0 +1,524 @@
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;
// 2026-10-12, DreamWeave "Thread" caches (~100 items, ~20 keepers) took ~50 s to loot:
// 1. A stack that merges into one already in the pack is deleted by the server (ACE
// StackableMerge: InventoryRemoveObject), so it never shows up in the inventory, and the
// pickup waited PickupArriveMaxMs (4 s) for it: 4.8 s instead of ~1.5 s per stack.
// 2. A decided item waited behind the assess window's busy-count gate.
// 3. Every move went out only after the last pickup's Return had played and the client had
// seen the character still. ACE queues a move that arrives during the Return (NextPickup,
// one ahead), so the next move now goes out at the answer.
// 4. Matched items were re-judged and re-logged before every pickup; the mana stone cap line
// was printed per stone.
// The ACE side is simulated (AceSim): pickup motion, item moved, Return; a move during the
// Return is queued, one during the pickup motion is "You're too busy"; and the client's own
// one-request-at-a-time slot (a move sent while the last is unanswered never leaves the client).
internal static class LootSpeedTests
{
private const uint Player = 0x50000D01;
private const uint Chest = 0x7A9B5001;
private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800, ItemTypeMisc = 0x80, ItemTypeArmor = 0x2;
private const uint KeyMaxStack = 11, KeyStack = 12, KeyArmorLevel = 28;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
private const long TickMs = 33;
public static void Register(Runner r)
{
r.Add("loot speed: a stack that merges into a pack stack is confirmed at the server's answer, not after 4 s", MergedStackConfirmsAtAnswer);
r.Add("loot speed: a decided item is picked up while the other IDs are still coming in", DecidedItemBeforeIds);
r.Add("loot speed: the next move goes out when the last item leaves the chest (queued behind its Return), one at a time", NextMoveAtAnswer);
r.Add("loot speed: a 'You're too busy' answer is sent again once the character is still, without using up a try", TooBusyRetried);
r.Add("loot speed: the chest closes only after the last pickup's Return has played", CloseWaitsForLastReturn);
r.Add("loot speed: a 100-item chest with 20 keepers (6 merging stacks) against simulated ACE timings", FullChestTiming);
r.Add("loot speed: a matched item's [LootEval] line is printed once per open, not before every pickup", LootEvalLoggedOnce);
}
// ── Fake clock ────────────────────────────────────────────────────────────
private static long _t;
private static T WithClock<T>(Func<T> body)
{
var saved = RynthAiPlugin.CorpseClock;
_t = 10_000_000;
RynthAiPlugin.CorpseClock = () => _t;
try { return body(); }
finally { RynthAiPlugin.CorpseClock = saved; }
}
private static void WithClock(Action body) => WithClock(() => { body(); return 0; });
// ── World ─────────────────────────────────────────────────────────────────
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
private static void BaseWorld()
{
FakeHost.Reset();
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.CloseContainerCalls = true; // CloseContainer + GetGroundContainerId
FakeHost.ServerGates = true; // GetCastBusyState (the pickup motions)
FakeHost.WeenieErrorCalls = true; // GetLastWeenieError ("You're too busy")
FakeHost.Names[Player] = "Dargoth Hera";
FakeHost.Positions[Player] = Me0;
FakeHost.PlayerPose = Me0;
FakeHost.Names[Chest] = "Drakkon's Thread Cache";
FakeHost.ItemTypes[Chest] = ItemTypeContainer;
FakeHost.Positions[Chest] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
FakeHost.NotAttackable.Add(Chest);
FakeHost.Containers[Chest] = 0;
}
private static void AddItem(uint id, string name, uint type, bool appraised = true, bool stack = false)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = type;
FakeHost.Containers[id] = Chest;
if (appraised) FakeHost.Appraised.Add(id);
if (stack)
{
FakeHost.Ints[(id, KeyMaxStack)] = 100;
FakeHost.Ints[(id, KeyStack)] = 1;
}
}
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 AceSim? Sim;
public Bot(RynthCoreHost host, bool armorStatRule = false)
{
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);
string profile = Path.Combine(Program.TempRoot, armorStatRule ? "loot-speed-armor.json" : "loot-speed.json");
var p = new LootProfile { Name = "speed" };
var gems = new LootRule { Name = "Gems", Action = LootAction.Keep };
gems.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
p.Rules.Add(gems);
var misc = new LootRule { Name = "Peas", Action = LootAction.Keep };
misc.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Misc });
p.Rules.Add(misc);
if (armorStatRule)
{
// A stat rule: armor is judged only with its appraisal.
var armor = new LootRule { Name = "AL 300 armor", Action = LootAction.Keep };
armor.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Armor });
armor.Conditions.Add(new LongValKeyGECondition { Key = (int)KeyArmorLevel, Value = 300 });
p.Rules.Add(armor);
}
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 void Create(IEnumerable<uint> ids)
{
var list = ids.ToList();
foreach (uint id in list) Cache.OnCreateObject(id);
// The cache classifies new objects on a per-tick time budget: tick it until every item
// is filed (in game this happens during the CreateObject burst, before the open).
int items = list.Count(i => i != Chest);
for (int i = 0; i < 200; i++)
{
Cache.Tick();
if (Cache.GetContainedItems(unchecked((int)Chest)).Count() >= items) break;
}
}
public void ServerOpens(uint container)
{
FakeHost.GroundContainer = container;
P.OnViewObjectContents(container);
P.OnUpdateObjectInventory(container);
}
/// <summary>One plugin tick: the clock moves on TickMs, the simulated server catches up, the looter runs.</summary>
public void Tick()
{
_t += TickMs;
Sim?.Step(_t);
Set("_activity", BotActivity.Looting);
typeof(RynthAiPlugin).GetMethod("TickCorpseOpening", Any)!.Invoke(P, null);
}
public void TickUntil(Func<bool> done, long maxMs)
{
long end = _t + maxMs;
while (_t < end && !done()) Tick();
}
public void TickFor(long ms)
{
long end = _t + ms;
while (_t < end) Tick();
}
public int MovesOf(uint id) => FakeHost.ExternalMoves.Count(m => m.Id == id);
}
/// <summary>
/// ACE's pickup (Player_Inventory.cs: StartPickup, the pickup motion, DoHandleActionPutItemInContainer
/// or StackableMerge, EnqueuePickupDone's Return, NextPickup) and the client's pending-request slot.
/// Server events run at server time; what the client sees of them lands Rtt/2 later.
/// </summary>
private sealed class AceSim
{
public long Rtt = 40, PickupMs = 740, ReturnMs = 740;
public readonly HashSet<uint> Mergers = new(); // stacks that merge into a pack stack
public readonly HashSet<uint> Junk = new(); // FakeHost.Containers keys never moved
public bool KeepNameOnMerge; // the client still reads the merged object's name
public int TooBusy, LocalRefused, Queued;
public readonly List<(uint Id, long Answer)> Answers = new();
private enum St { Idle, Pickup, Return }
private St _st;
private uint _next;
private int _seenMoves;
private uint _clientPending;
private readonly List<(long At, int Seq, Action Act)> _events = new();
private int _seq;
private void At(long at, Action act) => _events.Add((at, _seq++, act));
public void Step(long now)
{
// Moves the client sent since the last step (sent "now": the plugin tick before).
while (_seenMoves < FakeHost.ExternalMoves.Count)
{
uint id = FakeHost.ExternalMoves[_seenMoves++].Id;
if (_clientPending != 0) { LocalRefused++; continue; } // "You can only move or use one item at a time"
_clientPending = id;
long arrive = now - TickMs + Rtt / 2;
At(arrive, () => Receive(id, arrive));
}
while (true)
{
var due = _events.Where(e => e.At <= now).OrderBy(e => e.At).ThenBy(e => e.Seq).ToList();
if (due.Count == 0) break;
var e = due[0];
_events.Remove(e);
e.Act();
}
}
private void Receive(uint id, long ts)
{
if (_st == St.Idle) { StartPickup(id, ts); return; }
if (_st == St.Return && _next == 0) { _next = id; Queued++; return; }
TooBusy++;
At(ts + Rtt / 2, () =>
{
FakeHost.WeenieError(0x1D); // YoureTooBusy
FakeHost.WeenieError(0, 0x00A0, id); // InventoryServerSaveFailed(item)
if (_clientPending == id) _clientPending = 0;
});
}
private void StartPickup(uint id, long ts)
{
_st = St.Pickup;
At(ts + Rtt / 2, () => FakeHost.CastBusy = 1);
At(ts + PickupMs, () => MoveItem(id, ts + PickupMs));
}
private void MoveItem(uint id, long ts)
{
_st = St.Return;
At(ts + Rtt / 2, () =>
{
if (Mergers.Contains(id))
{
// InventoryRemoveObject: the client drops the object; a pack stack grows.
FakeHost.Containers.Remove(id);
if (!KeepNameOnMerge) FakeHost.Names.Remove(id);
FakeHost.Positions.Remove(id);
}
else
FakeHost.Containers[id] = Player;
if (_clientPending == id) _clientPending = 0;
Answers.Add((id, ts + Rtt / 2));
});
At(ts + ReturnMs, () => ReturnDone(ts + ReturnMs));
}
private void ReturnDone(long ts)
{
if (_next != 0)
{
uint n = _next;
_next = 0;
StartPickup(n, ts); // the queued move runs the moment the Return ends
return;
}
_st = St.Idle;
At(ts + Rtt / 2, () => FakeHost.CastBusy = 0);
}
}
private static Bot OpenChest(IEnumerable<uint> items, bool armorStatRule = false, AceSim? sim = null)
{
var host = FakeHost.Create(Player);
var bot = new Bot(host, armorStatRule) { Sim = sim };
bot.Create(new[] { Chest }.Concat(items));
bot.ServerOpens(Chest);
return bot;
}
private static string Log(string needle) => FakeHost.Logs.FirstOrDefault(l => l.Contains(needle)) ?? "";
// ── 1. Merged stack ───────────────────────────────────────────────────────
private static void MergedStackConfirmsAtAnswer()
{
MergedStack(keepName: false);
MergedStack(keepName: true); // owner gone, name still readable: the stack flag decides
}
private static void MergedStack(bool keepName) => WithClock(() =>
{
BaseWorld();
const uint Pea = 0x80264001;
AddItem(Pea, "Silver Pea", ItemTypeMisc, stack: true);
var sim = new AceSim { KeepNameOnMerge = keepName };
sim.Mergers.Add(Pea);
var bot = OpenChest(new[] { Pea }, sim: sim);
bot.TickUntil(() => bot.MovesOf(Pea) > 0, 1000);
Check.Eq(bot.MovesOf(Pea), 1, "the pea's move is sent");
long sent = _t;
bot.TickUntil(() => FakeHost.Logs.Any(l => l.Contains("pickup confirmed for 0x80264001")), 6000);
long confirmedAfter = _t - sent;
Check.True(Log("pickup confirmed for 0x80264001").Contains("merged into a stack"), "confirmed as a merge: " + Log("pickup confirmed"));
Check.True(confirmedAfter < 1200, $"confirmed at the server's answer (~0.8 s), not after PickupArriveMaxMs: {confirmedAfter} ms");
// The chest is closed once the Return has played (~0.74 s more), not before.
bot.TickUntil(() => FakeHost.Closes.Count > 0, 3000);
long closedAfter = _t - sent;
Check.Eq(FakeHost.Closes.Count, 1, "closed once");
Check.True(closedAfter >= sim.PickupMs + sim.ReturnMs, $"not before the Return ended ({closedAfter} ms)");
Check.True(closedAfter < 2000, $"and soon after it ({closedAfter} ms; it was ~4.8 s)");
});
// ── 2. Startup ────────────────────────────────────────────────────────────
private static void DecidedItemBeforeIds() => WithClock(() =>
{
BaseWorld();
const uint Gem = 0x80264101, Armor1 = 0x80264102, Armor2 = 0x80264103;
AddItem(Gem, "Black Opal", ItemTypeGem); // appraised: decided
AddItem(Armor1, "Chainmail Tassets", ItemTypeArmor, appraised: false); // stat rule: needs its ID
AddItem(Armor2, "Leather Cap", ItemTypeArmor, appraised: false);
FakeHost.Ints[(Armor1, KeyArmorLevel)] = 350;
FakeHost.Ints[(Armor2, KeyArmorLevel)] = 120;
var bot = OpenChest(new[] { Gem, Armor1, Armor2 }, armorStatRule: true);
bot.Set("_busyCount", 3); // the client's busy count is up (the old assess-window gate held the pickup on it)
// The contents settle (LootContentSettleMs' 50 ms floor), then the IDs go out.
bot.TickUntil(() => FakeHost.IdRequests.Count > 0, 500);
Check.True(FakeHost.IdRequests.Contains(Armor1) && FakeHost.IdRequests.Contains(Armor2), "the armor's IDs are requested");
Check.Eq(bot.MovesOf(Gem), 1, "the gem is picked up on that same tick, while the armor IDs are out");
Check.Eq(bot.MovesOf(Armor1) + bot.MovesOf(Armor2), 0, "the armor waits for its appraisal");
// The gem lands; the armor still has no ID: still nothing taken, nothing closed.
FakeHost.Containers[Gem] = Player;
bot.TickFor(1500);
Check.Eq(bot.MovesOf(Armor1) + bot.MovesOf(Armor2), 0, "no unappraised armor taken");
Check.Eq(FakeHost.Closes.Count, 0, "the chest stays open while IDs are out");
// The appraisals arrive: the good one is taken, the poor one left.
FakeHost.Appraised.Add(Armor1);
FakeHost.Appraised.Add(Armor2);
bot.TickUntil(() => bot.MovesOf(Armor1) > 0, 1000);
Check.Eq(bot.MovesOf(Armor1), 1, "the AL 350 armor is taken once appraised");
FakeHost.Containers[Armor1] = Player;
bot.TickUntil(() => FakeHost.Closes.Count > 0, 3000);
Check.Eq(bot.MovesOf(Armor2), 0, "the AL 120 armor is left");
Check.Eq(FakeHost.Closes.Count, 1, "then the chest closes");
});
// ── 3. Pipelining ─────────────────────────────────────────────────────────
private static void NextMoveAtAnswer() => WithClock(() =>
{
BaseWorld();
const uint G1 = 0x80264201, G2 = 0x80264202, G3 = 0x80264203;
AddItem(G1, "Emerald", ItemTypeGem);
AddItem(G2, "Ruby", ItemTypeGem);
AddItem(G3, "Sapphire", ItemTypeGem);
var bot = OpenChest(new[] { G1, G2, G3 });
bot.TickUntil(() => bot.MovesOf(G1) > 0, 1000);
Check.Eq(bot.MovesOf(G1), 1, "first move");
// The server's pickup motion plays; the item is still in the chest.
FakeHost.CastBusy = 1;
bot.TickFor(700);
Check.Eq(bot.MovesOf(G2), 0, "nothing else while the first item is still in the chest");
// The answer: the item is in the pack and the Return starts (still animating).
FakeHost.Containers[G1] = Player;
bot.Tick();
Check.Eq(bot.MovesOf(G2), 1, "the next move goes out on the tick the first item left the chest, during its Return");
Check.True(FakeHost.Logs.Any(l => l.Contains("queuing 0x80264202")), "logged as queued behind the Return");
// One queued at a time: G3 waits for G2's answer however long the animation runs.
bot.TickFor(1400);
Check.Eq(bot.MovesOf(G3), 0, "no second queued move");
Check.Eq(bot.MovesOf(G2), 1, "and no early retry of the queued one while the character animates");
FakeHost.Containers[G2] = Player;
bot.Tick();
Check.Eq(bot.MovesOf(G3), 1, "the third goes out at the second's answer");
Check.Eq(FakeHost.Closes.Count, 0, "nothing closed yet");
});
private static void TooBusyRetried() => WithClock(() =>
{
BaseWorld();
const uint G1 = 0x80264301, G2 = 0x80264302;
AddItem(G1, "Emerald", ItemTypeGem);
AddItem(G2, "Ruby", ItemTypeGem);
var bot = OpenChest(new[] { G1, G2 });
bot.TickUntil(() => bot.MovesOf(G1) > 0, 1000);
FakeHost.CastBusy = 1;
bot.TickFor(700);
FakeHost.Containers[G1] = Player;
bot.Tick();
Check.Eq(bot.MovesOf(G2), 1, "G2 queued at G1's answer");
// The server says it is too busy (the move beat the Return), then the save-failed for G2.
FakeHost.WeenieError(0x1D);
FakeHost.WeenieError(0, 0x00A0, G2);
bot.TickFor(500);
Check.Eq(bot.MovesOf(G2), 1, "no resend while the character still animates");
FakeHost.CastBusy = 0;
bot.Tick();
Check.Eq(bot.MovesOf(G2), 2, "sent again on the first still tick (no retry window)");
Check.True(FakeHost.Logs.Any(l => l.Contains("the server refused 0x80264302")), "the refusal is logged");
Check.Eq(bot.Get<int>("_currentLootItemMoveAttempts"), 0, "the refused send didn't use up one of the 3 tries");
// This time it goes through.
FakeHost.CastBusy = 1;
bot.TickFor(700);
FakeHost.Containers[G2] = Player;
bot.TickFor(700);
FakeHost.CastBusy = 0;
bot.TickUntil(() => FakeHost.Closes.Count > 0, 2000);
Check.Eq(FakeHost.Closes.Count, 1, "both looted, then closed");
Check.False(FakeHost.Logs.Any(l => l.Contains("pickup failed")), "nothing given up on");
});
// ── The close ─────────────────────────────────────────────────────────────
private static void CloseWaitsForLastReturn() => WithClock(() =>
{
BaseWorld();
const uint G1 = 0x80264401;
AddItem(G1, "Emerald", ItemTypeGem);
var bot = OpenChest(new[] { G1 });
bot.TickUntil(() => bot.MovesOf(G1) > 0, 1000);
FakeHost.CastBusy = 1;
bot.TickFor(700);
FakeHost.Containers[G1] = Player; // answered: the Return plays
bot.TickFor(700);
Check.True(FakeHost.Logs.Any(l => l.Contains("pickup confirmed for 0x80264401")), "the pickup is confirmed at the answer");
Check.Eq(FakeHost.Closes.Count, 0, "but the chest isn't closed while the Return plays");
FakeHost.CastBusy = 0;
bot.TickUntil(() => FakeHost.Closes.Count > 0, 1000);
Check.Eq(FakeHost.Closes.Count, 1, "closed once the character stands still");
});
// ── The whole chest ───────────────────────────────────────────────────────
private static void FullChestTiming() => WithClock(() =>
{
BaseWorld();
var sim = new AceSim();
var all = new List<uint>();
uint id = 0x80265000;
for (int i = 0; i < 14; i++) { AddItem(++id, $"Gem {i}", ItemTypeGem); all.Add(id); }
for (int i = 0; i < 6; i++) { AddItem(++id, $"Pea {i}", ItemTypeMisc, stack: true); sim.Mergers.Add(id); all.Add(id); }
for (int i = 0; i < 80; i++) { AddItem(++id, $"Junk {i}", ItemTypeArmor); all.Add(id); }
// Keepers spread through the listing, as in a real cache.
var rnd = new Random(7);
var order = all.OrderBy(_ => rnd.Next()).ToList();
var bot = OpenChest(order, sim: sim);
Check.Eq(bot.Cache.GetContainedItems(unchecked((int)Chest)).Count(), 100, "all 100 items listed in the chest");
long opened = _t;
bot.TickUntil(() => FakeHost.Closes.Count > 0, 120_000);
long total = _t - opened;
int keepersTaken = FakeHost.ExternalMoves.Select(m => m.Id).Distinct().Count();
long serverFloor = 20 * (sim.PickupMs + sim.ReturnMs);
Console.WriteLine($" (100 items, 20 keepers: {total / 1000.0:0.0} s open to close; ACE's own animations {serverFloor / 1000.0:0.0} s; " +
$"queued {sim.Queued}, too busy {sim.TooBusy}, refused by the client {sim.LocalRefused})");
Check.Eq(FakeHost.Closes.Count, 1, "the chest is closed at the end");
Check.Eq(keepersTaken, 20, "all 20 keepers taken, no junk");
Check.Eq(sim.Answers.Count, 20, "20 answers from the server");
Check.Eq(sim.TooBusy, 0, "no 'You're too busy'");
Check.Eq(sim.LocalRefused, 0, "no move refused by the client's one-at-a-time slot");
Check.True(sim.Queued >= 18, $"the moves were queued behind the Returns ({sim.Queued})");
Check.True(total < serverFloor + 1500, $"within 1.5 s of ACE's own animation time: {total} ms vs {serverFloor} ms (was ~50 s)");
Check.False(FakeHost.Logs.Any(l => l.Contains("pickup failed")), "nothing given up on");
});
// ── 4. Log spam ───────────────────────────────────────────────────────────
private static void LootEvalLoggedOnce() => WithClock(() =>
{
BaseWorld();
var sim = new AceSim();
var ids = new List<uint>();
uint id = 0x80266000;
for (int i = 0; i < 5; i++) { AddItem(++id, $"Gem {i}", ItemTypeGem); ids.Add(id); }
var bot = OpenChest(ids, sim: sim);
bot.TickUntil(() => FakeHost.Closes.Count > 0, 30_000);
Check.Eq(FakeHost.Closes.Count, 1, "looted and closed");
foreach (uint g in ids)
{
int lines = FakeHost.Logs.Count(l => l.Contains("[LootEval]") && l.Contains($"id=0x{g:X8}"));
Check.Eq(lines, 1, $"one [LootEval] line for 0x{g:X8}");
}
});
}

View file

@ -0,0 +1,154 @@
using System.Collections.Generic;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.ItemInfo;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The Mag-style item info line (/ra iteminfo, ID-on-click) against what the ACECustom appraisal
// panel shows for the same item: whole-number damage range, signed bonuses, Crushing Blow as the
// dealt multiplier, and the imbue strength / grade / wield gate that only exist as text.
internal static class MagItemDescriberTests
{
public static void Register(Runner r)
{
r.Add("iteminfo: T11 fire staff matches the appraisal panel", T11FireStaff);
r.Add("iteminfo: Biting Strike and a defense penalty", BitingStrikeAndPenalty);
r.Add("iteminfo: retail imbues stay bare labels without detail text", RetailImbuesBare);
r.Add("iteminfo: Int64 wield requirement never prints as a skill", Int64WieldHidden);
r.Add("iteminfo: T11 armor modifiers print on the ratings line", T11ArmorModifiers);
r.Add("iteminfo: T11 tier, gear grade, slots and tainted", T11GradedArmor);
}
/// <summary>In-memory property bag standing in for the client object cache.</summary>
private sealed class FakeItem : IItemPropertySource
{
public readonly Dictionary<uint, int> Ints = new();
public readonly Dictionary<uint, double> Doubles = new();
public readonly Dictionary<uint, string> Strings = new();
public FakeItem(string name, AcObjectClass cls) { Name = name; ObjectClass = cls; }
public string Name { get; }
public AcObjectClass ObjectClass { get; }
public bool TryGetInt(uint stype, out int value) => Ints.TryGetValue(stype, out value);
public bool TryGetDouble(uint stype, out double value) => Doubles.TryGetValue(stype, out value);
public string GetString(uint stype) => Strings.TryGetValue(stype, out string? v) ? v : string.Empty;
public IReadOnlyList<int> SpellIds { get; } = new List<int>();
}
private static List<string> Pet(FakeItem item) => MagItemDescriber.Build(item, MagItemInfoOptions.Default).ToPetLines();
// The item from the bug report: ACECustom shows Damage 1790 - 2069, Bonus to Attack Skill
// +20%, Melee Defense +20.0%, Crushing Blow 3.66x, Fire Rending +176%, Grade S (100%),
// Crit Dam 24, Wield requires 2,000 Item Augmentations.
private static void T11FireStaff()
{
var staff = new FakeItem("Flaming Quarter Staff", AcObjectClass.MeleeWeapon);
staff.Ints[44] = 2069; // max damage
staff.Ints[45] = 0x10; // fire
staff.Ints[353] = 7; // staff mastery
staff.Ints[105] = 9; // workmanship
staff.Ints[179] = 0x0200; // Fire Rending
staff.Ints[374] = 24; // crit damage rating
staff.Doubles[22] = 0.135; // variance
staff.Doubles[62] = 1.20; // attack
staff.Doubles[29] = 1.20; // melee defense
staff.Doubles[136] = 2.66; // CriticalMultiplier (Crushing Blow 3.66x)
staff.Ints[9061] = 11; // WeaponAugScaleTier (sent since ACECustom 2026-09-29)
staff.Ints[9060] = 1000; // WeaponAugScaleQuality: the S roll
staff.Strings[16] =
"Property Details:\n" +
"- Weapon Grade: S (100% of max damage)\n" +
"- Properties: 2 of 5\n" +
"- Crushing Blow: 3.66x Crit Dmg\n" +
"- Fire Rending: +176% Dmg\n" +
"- Effective Melee Defense: 39851\n" +
"- Wield requires: 2,000 Item Augmentations\n";
List<string> lines = Pet(staff);
Check.Eq(lines.Count, 3, "line count");
Check.Eq(lines[0], "Flaming Quarter Staff (Fire Staff), T11, Quality 1000, Props 2/5, Grade S (100%), Craft 9", "identity line");
Check.Eq(lines[1], "FireRend +176%, Crushing Blow 3.66x, 1790-2069, 0.135v, +20%a, +20%md", "combat line");
Check.Eq(lines[2], "[CD 24] Wield 2,000 Item Augs", "ratings / requirements line");
}
private static void BitingStrikeAndPenalty()
{
var sword = new FakeItem("Sword", AcObjectClass.MeleeWeapon);
sword.Ints[44] = 100;
sword.Doubles[147] = 0.15; // Biting Strike
sword.Doubles[136] = 1.0; // normal 2x crit, not Crushing Blow
sword.Doubles[29] = 0.95; // -5% melee defense
string line = MagItemDescriber.Describe(sword, MagItemInfoOptions.Default);
Check.True(line.Contains("Biting Strike 15%"), $"Biting Strike shown: {line}");
Check.False(line.Contains("Crushing Blow"), $"1.0 multiplier is not Crushing Blow: {line}");
Check.True(line.Contains("-5%md"), $"penalty keeps its sign: {line}");
Check.True(line.Contains(", 100,") || line.EndsWith(", 100"), $"no variance prints max only: {line}");
}
private static void RetailImbuesBare()
{
var axe = new FakeItem("Axe", AcObjectClass.MeleeWeapon);
axe.Ints[179] = 0x0001 | 0x0004; // CS + AR
string line = MagItemDescriber.Describe(axe, MagItemInfoOptions.Default);
Check.True(line.Contains(", CS AR"), $"bare Mag labels: {line}");
axe.Strings[16] =
"Property Details:\n" +
"- Critical Strike: +12.5 % Crit Chance\n" + // culture space before %
"- Armor Rending: 30.0% Ignored\n";
line = MagItemDescriber.Describe(axe, MagItemInfoOptions.Default);
Check.True(line.Contains("CS +12.5%, AR 30.0%"), $"strengths from detail text: {line}");
}
private static void Int64WieldHidden()
{
var mace = new FakeItem("Mace", AcObjectClass.MeleeWeapon);
mace.Ints[158] = 13; // WieldRequirement.Int64Stat
mace.Ints[159] = 9008; // LumAugItemCount
mace.Ints[160] = 2500;
string line = MagItemDescriber.Describe(mace, MagItemInfoOptions.Default);
Check.False(line.Contains("Skill 9008"), $"no fake skill name: {line}");
}
private static void T11ArmorModifiers()
{
var helm = new FakeItem("T11 - Helm", AcObjectClass.Armor);
helm.Strings[16] = "Wield requires: 500 Triune Weave\n";
helm.Strings[14] =
"Modifiers:\n" +
"- Damage Resist +6 [2-12]\n" +
"- Max Health +100 [40-200]\n";
List<string> lines = Pet(helm);
string last = lines[^1];
Check.True(last.Contains("Mods: Damage Resist +6, Max Health +100"), $"modifiers listed: {last}");
Check.True(last.Contains("Wield 500 Triune Weave"), $"triune gate listed: {last}");
}
// Armor in the #543 appraisal format: Gear Grade, Properties and Tainted lead / close the
// block, markers follow the band. No tier property, so the tier is the gate estimate ("~").
private static void T11GradedArmor()
{
var helm = new FakeItem("T11 - Helm", AcObjectClass.Armor);
helm.Strings[16] = "Wield requires: 500 Triune Weave\n";
helm.Strings[14] =
"Modifiers:\n" +
"- Gear Grade: B+ (average of 2 rolled lines)\n" +
"- Properties: 2 of 5\n" +
"- Damage Resist +60 [35-69] (Built-in)\n" +
"- Max Health +50 [14-69] (+20 tinkered) (Locked)\n" +
"- Tainted: bags no longer work on this item\n";
string line = MagItemDescriber.Describe(helm, MagItemInfoOptions.Default);
Check.True(line.Contains("~T16, Gear B+ (2 lines), Props 2/5, Tainted"), $"T11 state listed: {line}");
Check.True(line.Contains("Mods: Damage Resist +60, Max Health +50 (+20 tink) (Locked)"), $"markers on mods: {line}");
Check.False(line.Contains("Gear Grade:") || line.Contains("Properties:"), $"item lines are not mods: {line}");
// The stamped tier wins over the estimate and drops the "~".
helm.Ints[50109] = 17;
line = MagItemDescriber.Describe(helm, MagItemInfoOptions.Default);
Check.True(line.Contains(", T17, Gear B+"), $"ZcTier shown exact: {line}");
Check.True(MagItemInfoCatalog.TryFindField("t11", out var field) && field == MagItemInfoField.T11, "t11 field found by name");
}
}

View file

@ -154,6 +154,9 @@ internal static class ManaReserveTests
// and mana regenerates meanwhile with attacks still held.
var u = new Rig(mana: 50);
BuffManager.ManaCostOverride = _ => 0;
// Mana Conversion untrained: the rest below. Trained, a recovery vital retries in 200 ms
// instead (RecoveryRetryTests).
FakeHost.Skills[(Player, 16)] = (10, 1);
Check.True(u.B.CheckVitals(), "50/383 under Get Mana At: Stamina to Mana goes");
Check.Eq(FakeHost.Casts.Count, 1, "one cast");
u.B.OnChatWindowText(NotEnoughMana, 0);

View file

@ -0,0 +1,212 @@
using System;
using System.Linq;
using System.Threading;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Choppy melee, Drakkon 2026-10-12 (Olthoi Slayers/Slashers, landblock 0x6146, Tetsubo):
// * the server's move-to the target stalled 2 m short and the bot waited 6 s for the watchdog's
// CancelAttack, which fixed it at once every time (flight recorder 20:47:35 and 20:48:20);
// * four ghosts (objects the client drew, the server no longer had for him) were attacked round
// and round for 25+ minutes: every attack answered by AttackDone ActionCancelled, they never
// moved, the server sent nothing about them, each got a 30 s blacklist and came back;
// * after a kill or a rebind the next swing waited out the 1000 ms re-attack interval.
internal static class MeleeStallTests
{
public static void Register(Runner r)
{
r.Add("melee stall: step 1 after 2.5 s when no swing plays and the character stands still, else 6 s", EarlyStepWhenQuiet);
r.Add("ghost: no swing after the re-issue, not moved, the server silent 8 s+ = a ghost", GhostVerdict);
r.Add("ghost: a swing, a move, a server message or another target means it is alive", GhostAlive);
r.Add("ghost: skipped until the server updates or creates it, it moves, or the landblock changes", GhostTrackerClears);
r.Add("ghost: combat skips a marked ghost, counts it in the lock line, and takes it back when the server updates it", GhostSkippedByCombat);
r.Add("melee interval: the first swing at a new target doesn't wait out the old 1000 ms", PhysicalNewTargetInterval);
}
private static readonly DateTime T0 = new(2026, 10, 12, 20, 47, 35);
private static void EarlyStepWhenQuiet()
{
// Quiet (the caller's read: attacks sent, nothing animating, standing still).
var w = new CombatStallWatchdog();
DateTime evidence = T0; // the last hit
DateTime t = T0;
CombatStallWatchdog.StallAction act = CombatStallWatchdog.StallAction.None;
double stalled = 0;
for (int ms = 0; ms <= 3000; ms += 100)
{
t = T0.AddMilliseconds(ms);
act = w.Tick(t, eligible: true, evidence, out stalled, quiet: ms >= 1500);
if (act != CombatStallWatchdog.StallAction.None) break;
}
Check.Eq(act, CombatStallWatchdog.StallAction.Reissue, "quiet: step 1 (re-issue)");
Check.True(stalled >= CombatStallWatchdog.QuietStallMs && stalled < CombatStallWatchdog.StallMs,
$"fired at {stalled:0} ms, between 2.5 s and 6 s");
Check.True(w.LastFireWasEarly, "flagged early for the log");
// A swing comes back: recovered, as before.
act = w.Tick(t.AddMilliseconds(400), true, t.AddMilliseconds(350), out _, quiet: false);
Check.Eq(act, CombatStallWatchdog.StallAction.Recovered, "a hit after the step: recovered");
// Not quiet (a swing animating, or the server walking us to the mob): the old 6 s.
var w2 = new CombatStallWatchdog();
act = CombatStallWatchdog.StallAction.None;
int firedAt = -1;
for (int ms = 0; ms <= 7000; ms += 100)
{
act = w2.Tick(T0.AddMilliseconds(ms), true, T0, out _, quiet: false);
if (act != CombatStallWatchdog.StallAction.None) { firedAt = ms; break; }
}
Check.Eq(act, CombatStallWatchdog.StallAction.Reissue, "not quiet: step 1 still comes");
Check.True(firedAt >= 6000, $"but only after 6 s (fired at {firedAt} ms)");
Check.False(w2.LastFireWasEarly, "not early");
// Quiet but the stall is younger than 2.5 s: nothing yet.
var w3 = new CombatStallWatchdog();
act = w3.Tick(T0, true, T0, out _, quiet: true);
act = w3.Tick(T0.AddMilliseconds(2000), true, T0, out _, quiet: true);
Check.Eq(act, CombatStallWatchdog.StallAction.None, "2 s: too early even when quiet");
}
private static readonly GhostSpot Mob = new(162.36, -168.80, -6.0);
private static void GhostVerdict()
{
var c = new GhostCheck();
const int Ghost = unchecked((int)0x800B87EC);
c.Arm(Ghost, T0, Mob);
Check.True(c.IsArmed, "armed by the step-1 re-issue");
Check.Eq(c.Check(Ghost, T0.AddMilliseconds(500), DateTime.MinValue, Mob, 900_000), GhostCheck.Verdict.None, "0.5 s: still waiting");
Check.Eq(c.Check(Ghost, T0.AddMilliseconds(1600), DateTime.MinValue, Mob, 900_000), GhostCheck.Verdict.Ghost,
"1.6 s, no swing, not moved, the server silent 15 min: ghost");
Check.False(c.IsArmed, "one verdict per arm");
c.Arm(Ghost, T0, Mob);
Check.Eq(c.Check(Ghost, T0.AddMilliseconds(1600), DateTime.MinValue, Mob, -1), GhostCheck.Verdict.Ghost,
"no server record at all (the client had it before anyone watched): ghost");
c.Arm(Ghost, T0, null);
Check.False(c.IsArmed, "no target position: no verdicts");
}
private static void GhostAlive()
{
const int Mob1 = 0x10001, Mob2 = 0x10002;
var c = new GhostCheck();
c.Arm(Mob1, T0, Mob);
Check.Eq(c.Check(Mob1, T0.AddMilliseconds(900), T0.AddMilliseconds(800), Mob, 900_000), GhostCheck.Verdict.Alive, "a hit since the re-issue: alive");
c.Arm(Mob1, T0, Mob);
var moved = new GhostSpot(Mob.X + 0.4, Mob.Y, Mob.Z);
Check.Eq(c.Check(Mob1, T0.AddMilliseconds(1600), DateTime.MinValue, moved, 900_000), GhostCheck.Verdict.Alive, "it moved: alive");
c.Arm(Mob1, T0, Mob);
Check.Eq(c.Check(Mob1, T0.AddMilliseconds(1600), DateTime.MinValue, Mob, 300), GhostCheck.Verdict.Alive,
"the server sent something about it 0.3 s ago (after the re-issue): alive");
c.Arm(Mob1, T0, Mob);
Check.Eq(c.Check(Mob1, T0.AddMilliseconds(1600), DateTime.MinValue, Mob, 5000), GhostCheck.Verdict.Alive,
"the server talked about it 5 s ago (under 8 s): not called a ghost");
c.Arm(Mob1, T0, Mob);
Check.Eq(c.Check(Mob2, T0.AddMilliseconds(1600), DateTime.MinValue, Mob, 900_000), GhostCheck.Verdict.Alive, "another target now: no verdict on the old one");
c.Arm(Mob1, T0, Mob);
Check.Eq(c.Check(Mob1, T0.AddMilliseconds(1600), DateTime.MinValue, null, 900_000), GhostCheck.Verdict.Alive, "target position gone: no verdict");
}
private static void GhostTrackerClears()
{
var g = new GhostTracker();
string? cleared = null;
g.Cleared = (id, why) => cleared = $"{id:X}:{why}";
const uint Lb = 0x6146;
g.Mark(1, "Olthoi Slayer", Mob, Lb, T0);
g.Mark(2, "Olthoi Slasher", Mob, Lb, T0);
g.Mark(3, "Olthoi Slayer", Mob, Lb, T0);
Check.Eq(g.Count, 3, "three ghosts");
Check.True(g.IsGhost(1), "marked");
g.NoteServerUpdate(1, T0.AddMinutes(2));
Check.False(g.IsGhost(1), "a server update: real again");
Check.True(cleared != null && cleared.StartsWith("1:"), $"logged: {cleared}");
Check.Eq(g.SilentMs(1, T0.AddMinutes(2).AddSeconds(3)), 3000.0, "the plugin's own update clock");
g.CheckMoved(id => id == 2 ? new GhostSpot(Mob.X, Mob.Y + 1, Mob.Z) : Mob);
Check.False(g.IsGhost(2), "it moved: real");
Check.True(g.IsGhost(3), "the one that didn't move stays a ghost (no fixed timeout)");
g.OnPlayerLandblock(Lb);
Check.True(g.IsGhost(3), "same landblock: kept");
g.OnPlayerLandblock(0x6346);
Check.False(g.IsGhost(3), "another landblock: let go");
g.Mark(4, "Olthoi Slayer", Mob, Lb, T0);
g.NoteDeleted(4);
Check.False(g.IsGhost(4), "deleted (e.g. removed from the client): forgotten");
Check.Eq(g.MarkedTotal, 4, "four marked in all");
}
private const uint Player = 0x50000180;
private const uint Lb = 0x61460000;
private static void GhostSkippedByCombat()
{
FakeHost.Reset();
Place(Player, "Drakkon", 96, 96, creature: false);
FakeHost.PlayerPose = (Lb | 0x0329, 96f, 96f, 0f);
uint ghost = 0x800B87E3, real = 0x800F2516;
Place(ghost, "Olthoi Slasher", 96, 97.4f); // 1.4 m: the pick, but a ghost
Place(real, "Olthoi Slasher", 96, 99.0f); // 3 m
var s = new LegacyUiSettings { MonsterRange = 20 };
var host = FakeHost.Create();
var cache = FakeHost.MakeCache(host, Player, new[] { ghost, real });
var c = new CombatManager(host, s, cache);
c.SetPlayerId(Player);
c.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
c.ScanNearbyTargets();
c.HandleCombatTrigger();
Check.Eq((uint)c.activeTargetId, ghost, "first pick: the closer one (not known to be a ghost yet)");
c.MarkGhost((int)ghost, "Olthoi Slasher", 900_000, "test");
Check.Eq(c.activeTargetId, 0, "marking the target drops it");
Check.True(FakeHost.Logs.Any(l => l.Contains("[Ghost] 0x800B87E3") && l.Contains("is a ghost")), "logged");
Thread.Sleep(80); // the scan runs at most every 50 ms
c.ScanNearbyTargets();
Check.False(c.ScannedTargets.Any(t => (uint)t.Id == ghost), "the ghost isn't scanned");
c.HandleCombatTrigger();
Check.Eq((uint)c.activeTargetId, real, "the real one is fought");
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] lock 0x800F2516") && l.Contains("1 ghost(s) in range skipped")),
"the lock line counts the skipped ghost");
// The server sends an update for it: real again, targetable.
c.OnServerObjectUpdate(ghost);
Check.False(c.Ghosts.IsGhost((int)ghost), "an update: no longer a ghost");
Thread.Sleep(80);
c.ScanNearbyTargets();
Check.True(c.ScannedTargets.Any(t => (uint)t.Id == ghost), "scanned again");
}
private static void Place(uint id, string name, float x, float y, bool creature = true)
{
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (Lb | 0x0329, x, y, 0f);
if (creature) FakeHost.ItemTypes[id] = 0x10;
}
private static void PhysicalNewTargetInterval()
{
const int Melee = CombatMode.Melee, Missile = CombatMode.Missile;
Check.Eq(CombatManager.AttackIntervalMs(Melee, 1500, true, false), 1000.0, "melee, same target: the 1000 ms re-attack cadence");
Check.Eq(CombatManager.AttackIntervalMs(Melee, 1500, true, true), CombatManager.NewTargetPhysicalFloorMs, "melee, new target: the short floor");
Check.Eq(CombatManager.AttackIntervalMs(Missile, 1500, true, true), CombatManager.NewTargetPhysicalFloorMs, "missile, new target: the short floor");
Check.Eq(CombatManager.AttackIntervalMs(Melee, 1500, false, true), 1000.0, "no server gates: 1000 ms as before");
Check.True(CombatManager.AttackAfterCancelMs < 1000.0, "after a CancelAttack the attack follows sooner than a full interval");
}
}

View file

@ -37,6 +37,12 @@ internal static class NavEngineTests
r.Add("nav engine: a recall that never fires, next waypoint close: moves on after 60 s", RecallTimeoutNear);
r.Add("nav engine: macro start picks the nearest plain waypoint", ResumeNearest);
r.Add("nav engine: indoors, macro start picks the nearest waypoint on foot, not through a wall", ResumeNearestByWalk);
r.Add("nav engine: macro start skips a nearest waypoint already walked past, not one still ahead", ResumeNearestPassed);
r.Add("nav engine: back from a pause that moved 10+ yd, nav heads for the closest waypoint", ResumeAfterPauseMoved);
r.Add("nav engine: back from a pause that moved under 10 yd, nav keeps its waypoint", ResumeAfterPauseStill);
r.Add("nav engine: the dungeon patrol keeps its waypoint after a pause that moved it (no closest-waypoint pick)", ResumeAfterPausePatrol);
r.Add("nav engine: Go To Closest Waypoint off keeps the last waypoint (hazard/corpse still rejoin)", ResumeNearestOff);
r.Add("nav engine: a loaded route starts at [0] for Once/Follow, or for any route with the option off", StartsAtFirstPoint);
r.Add("nav engine: nearest waypoint lookup", FindNearest);
r.Add("nav engine: off track only beyond 160 yd (159 yd never), after 5 s, once per trip", OffTrack159);
r.Add("nav engine: coming back from a pause far off the route is not off track", OffTrackDisarmedByStop);
@ -427,6 +433,93 @@ internal static class NavEngineTests
Check.Eq(p3.PlanTargets.Count, 0, "outdoors: no plans asked for");
}
/// <summary>A 40 yd square, run clockwise: [0] origin, [1] 40 east, [2] 40 north-east, [3] 40 north.</summary>
private static NavRouteParser Square()
=> Route(RT.Circular, Pt(0, 0), Pt(0, 40), Pt(40, 40), Pt(40, 0));
private static void ResumeNearestPassed()
{
// Just beyond [2] on the leg toward [3]: the closest spot on the route is on that leg.
FakeHost.Reset(); At(42, 30);
var past = new Nav(Square(), idx: 0);
past.E.ResumeFromNearestWaypoint();
Check.Eq(past.Idx, 3, "walked past [2]: on to [3] instead of turning back");
// Still short of [1], a little off the leg into it: [1] stays the target.
FakeHost.Reset(); At(2, 30);
var shy = new Nav(Square(), idx: 0);
shy.E.ResumeFromNearestWaypoint();
Check.Eq(shy.Idx, 1, "still on the leg into [1]: [1]");
}
private static void ResumeAfterPauseMoved()
{
FakeHost.Reset(); At(0, 10);
var nav = new Nav(Square(), idx: 1);
nav.Tick();
nav.E.Stop(); // a fight starts
At(38, 42); // ... and the chase ends near [2]
nav.Run(6.0); // past any teleport settle
Check.Eq(nav.Idx, 2, "the closest waypoint, not the one it was heading for");
Check.True(LogCount("back from a pause") == 1, "logged once");
}
private static void ResumeAfterPausePatrol()
{
FakeHost.Reset(); At(0, 10);
var nav = new Nav(Square(), idx: 1);
nav.E.KeepWaypointAfterPause = () => true; // the plugin: _dunPatrolActive
nav.Tick();
nav.E.Stop();
At(38, 42); // the same chase as ResumeAfterPauseMoved
nav.Run(6.0);
Check.Eq(nav.Idx, 1, "patrol: carries on to the waypoint it was heading for");
Check.Eq(LogCount("back from a pause"), 0, "nothing re-picked");
nav.E.ResumeFromNearestWaypoint(always: true);
Check.Eq(nav.Idx, 2, "hazard escape / corpse run: still rejoins at the closest waypoint");
}
private static void ResumeAfterPauseStill()
{
FakeHost.Reset(); At(2, 38);
var nav = new Nav(Square(), idx: 2);
nav.Tick();
nav.E.Stop();
At(-3, 36); // 5 yd: [1] is now nearer, but the pause barely moved us
nav.Run(1.0);
Check.Eq(nav.Idx, 2, "kept: moved under 10 yd");
Check.Eq(LogCount("back from a pause"), 0, "nothing re-picked");
}
private static void ResumeNearestOff()
{
FakeHost.Reset(); At(0, 10);
var nav = new Nav(Square(), idx: 1);
nav.S.NavResumeNearest = false;
nav.Tick();
nav.E.Stop();
At(38, 42);
nav.Run(6.0);
Check.Eq(nav.Idx, 1, "pause: carries on to the waypoint it was heading for");
nav.E.ResumeFromNearestWaypoint();
Check.Eq(nav.Idx, 1, "macro start: keeps the last waypoint");
nav.E.ResumeFromNearestWaypoint(always: true);
Check.Eq(nav.Idx, 2, "hazard escape / corpse run: rejoins at the closest waypoint anyway");
}
private static void StartsAtFirstPoint()
{
Check.False(NavRouteParser.StartsAtFirstPoint(RT.Circular, true), "Circular, option on: nearest");
Check.False(NavRouteParser.StartsAtFirstPoint(RT.Linear, true), "Linear, option on: nearest");
Check.True(NavRouteParser.StartsAtFirstPoint(RT.Once, true), "Once: always [0]");
Check.True(NavRouteParser.StartsAtFirstPoint(RT.Follow, true), "Follow: always [0]");
Check.True(NavRouteParser.StartsAtFirstPoint(RT.Circular, false), "Circular, option off: [0]");
Check.True(NavRouteParser.StartsAtFirstPoint(RT.Linear, false), "Linear, option off: [0]");
}
private static void FindNearest()
{
FakeHost.Reset(); At(48, 0);

View file

@ -0,0 +1,191 @@
using System;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiTests.Harness;
using T = RynthCore.Plugin.RynthAi.LegacyUi.NavPointType;
namespace RynthCore.RynthAiHostTests.Tests;
// The engine Dungeon Map's route edits (2026-10-12): addPointAt / movePointTo carry the map's
// coordinates (worked out from the floor under the cursor), setActive picks the next waypoint.
// RynthPluginGetNavJson reports MapEdit so the engine only offers editing to a RynthAi that has
// these commands; older builds ignore them.
internal static class NavMapEditTests
{
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("nav map edit: addPointAt appends a Point at the map's coordinates", AddAppends);
r.Add("nav map edit: addPointAt after a selected step inserts there and keeps the next waypoint", AddInsertsAfter);
r.Add("nav map edit: movePointTo moves a step and keeps its type and other fields", MoveKeepsFields);
r.Add("nav map edit: bad index or coordinates change nothing", Refusals);
r.Add("nav map edit: setActive sets the next waypoint", SetActive);
r.Add("nav map edit: the engine's command JSON reads; the nav JSON says MapEdit", JsonShapes);
r.Add("nav map edit: an edit through the dashboard saves the route file", SavesRouteFile);
}
private static LegacyUiSettings Settings(params NavPoint[] pts)
{
var s = new LegacyUiSettings();
s.CurrentRoute = new NavRouteParser { RouteType = NavRouteType.Circular };
s.CurrentRoute.Points.AddRange(pts);
return s;
}
private static NavPoint P(double ns, double ew, T type = T.Point) => new() { Type = type, NS = ns, EW = ew, Z = -0.1 };
private static NavCommand Add(double ns, double ew, double z, int addMode = 0, int insertAt = -1) =>
new() { Cmd = "addPointAt", NS = ns, EW = ew, Z = z, AddMode = addMode, InsertAt = insertAt };
private static void AddAppends()
{
var s = Settings(P(1, 1), P(2, 2));
var res = NavMapEdit.Apply(s, Add(-12.5, 40.25, -0.1), out string status);
Check.Eq(res, NavMapEdit.Result.RouteChanged, "route changed");
Check.Eq(s.CurrentRoute.Points.Count, 3, "one point added");
NavPoint p = s.CurrentRoute.Points[2];
Check.Eq(p.Type, T.Point, "a Point");
Check.Near(p.NS, -12.5, 1e-9, "NS");
Check.Near(p.EW, 40.25, 1e-9, "EW");
Check.Near(p.Z, -0.1, 1e-9, "Z (nav units)");
Check.True(status.Contains("2"), "status names the new step: " + status);
// Into an empty route, whatever InsertAt says.
var e = Settings();
NavMapEdit.Apply(e, Add(1, 2, 0, addMode: 2, insertAt: 5), out _);
Check.Eq(e.CurrentRoute.Points.Count, 1, "first point of an empty route");
Check.Eq(e.ActiveNavIndex, 0, "active stays 0");
}
private static void AddInsertsAfter()
{
var s = Settings(P(0, 0), P(1, 1), P(2, 2), P(3, 3));
s.ActiveNavIndex = 2;
NavMapEdit.Apply(s, Add(9, 9, 0, addMode: 2, insertAt: 0), out _); // after step 0 -> index 1
Check.Near(s.CurrentRoute.Points[1].NS, 9, 1e-9, "inserted after step 0");
Check.Eq(s.ActiveNavIndex, 3, "active follows its step (was 2, shifted down)");
Check.Near(s.CurrentRoute.Points[s.ActiveNavIndex].NS, 2, 1e-9, "still heading for the same point");
NavMapEdit.Apply(s, Add(8, 8, 0, addMode: 2, insertAt: 3), out _); // after the active step -> index 4
Check.Near(s.CurrentRoute.Points[4].NS, 8, 1e-9, "inserted after the active step");
Check.Eq(s.ActiveNavIndex, 3, "active unchanged by a point after it");
NavMapEdit.Apply(s, Add(7, 7, 0, addMode: 2, insertAt: 99), out _); // past the end -> appended
Check.Near(s.CurrentRoute.Points[^1].NS, 7, 1e-9, "InsertAt past the end appends");
Check.Eq(NavMapEdit.InsertIndex(5, 1, 2), 2, "AddMode 1 = before");
Check.Eq(NavMapEdit.InsertIndex(5, 0, 2), 5, "AddMode 0 = end");
}
private static void MoveKeepsFields()
{
var recall = new NavPoint { Type = T.Recall, NS = 5, EW = 5, Z = 0.2, SpellId = 1635 };
var chat = new NavPoint { Type = T.Chat, NS = 6, EW = 6, Z = 0.2, ChatCommand = "/say hi" };
var s = Settings(P(1, 1), recall, chat);
var res = NavMapEdit.Apply(s, new NavCommand { Cmd = "movePointTo", Index = 1, NS = -3.25, EW = 7.5, Z = -0.05 }, out _);
Check.Eq(res, NavMapEdit.Result.RouteChanged, "route changed");
Check.True(ReferenceEquals(s.CurrentRoute.Points[1], recall), "same step object (moved in place)");
Check.Eq(recall.Type, T.Recall, "type kept");
Check.Eq(recall.SpellId, 1635, "spell kept");
Check.Near(recall.NS, -3.25, 1e-9, "NS moved");
Check.Near(recall.EW, 7.5, 1e-9, "EW moved");
Check.Near(recall.Z, -0.05, 1e-9, "Z from the floor under the drop");
NavMapEdit.Apply(s, new NavCommand { Cmd = "movePointTo", Index = 2, NS = 1, EW = 2, Z = 0 }, out _);
Check.Eq(chat.ChatCommand, "/say hi", "chat text kept");
Check.Eq(s.CurrentRoute.Points.Count, 3, "count unchanged");
}
private static void Refusals()
{
var s = Settings(P(1, 1), P(2, 2));
Check.Eq(NavMapEdit.Apply(s, new NavCommand { Cmd = "movePointTo", Index = 2, NS = 1, EW = 1 }, out _),
NavMapEdit.Result.None, "index past the end");
Check.Eq(NavMapEdit.Apply(s, new NavCommand { Cmd = "movePointTo", Index = -1, NS = 1, EW = 1 }, out _),
NavMapEdit.Result.None, "negative index");
Check.Eq(NavMapEdit.Apply(s, Add(double.NaN, 1, 0), out _), NavMapEdit.Result.None, "NaN NS");
Check.Eq(NavMapEdit.Apply(s, Add(1, 500, 0), out _), NavMapEdit.Result.None, "EW off the world");
Check.Eq(NavMapEdit.Apply(s, Add(1, 1, double.PositiveInfinity), out _), NavMapEdit.Result.None, "infinite Z");
Check.Eq(NavMapEdit.Apply(s, new NavCommand { Cmd = "movePointTo", Index = 0, NS = 1, EW = 1, Z = 1e9 }, out _),
NavMapEdit.Result.None, "absurd Z on a move");
Check.Eq(NavMapEdit.Apply(s, new NavCommand { Cmd = "somethingElse" }, out _), NavMapEdit.Result.None, "unknown command");
Check.Eq(s.CurrentRoute.Points.Count, 2, "route untouched");
Check.Near(s.CurrentRoute.Points[0].NS, 1, 1e-9, "point untouched");
Check.True(NavMapEdit.Handles("addPointAt") && NavMapEdit.Handles("movePointTo") && NavMapEdit.Handles("setActive"),
"the three map commands are routed here");
Check.False(NavMapEdit.Handles("addWaypoint"), "addWaypoint is not");
}
private static void SetActive()
{
var s = Settings(P(1, 1), P(2, 2), P(3, 3));
Check.Eq(NavMapEdit.Apply(s, new NavCommand { Cmd = "setActive", Index = 2 }, out _), NavMapEdit.Result.ActiveChanged, "changed");
Check.Eq(s.ActiveNavIndex, 2, "active = 2");
Check.Eq(NavMapEdit.Apply(s, new NavCommand { Cmd = "setActive", Index = 3 }, out _), NavMapEdit.Result.None, "past the end refused");
Check.Eq(s.ActiveNavIndex, 2, "active unchanged");
}
private static void JsonShapes()
{
// What the engine's NavCmd serializes to (source-generated, PascalCase, every property).
const string json = "{\"Cmd\":\"addPointAt\",\"SpellId\":0,\"Index\":0,\"RouteType\":0,\"AddMode\":2,\"InsertAt\":3,"
+ "\"NavName\":\"\",\"Text\":\"\",\"On\":false,\"Indices\":null,\"Delta\":0,\"Seconds\":0,\"Yards\":0,\"Reverse\":false,"
+ "\"NS\":-12.5,\"EW\":40.25,\"Z\":-0.1}";
NavCommand? cmd = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.NavCommand);
Check.NotNull(cmd, "parsed");
Check.Eq(cmd!.Cmd, "addPointAt", "Cmd");
Check.Near(cmd.NS, -12.5, 1e-9, "NS");
Check.Near(cmd.EW, 40.25, 1e-9, "EW");
Check.Near(cmd.Z, -0.1, 1e-9, "Z");
Check.Eq(cmd.AddMode, 2, "AddMode");
Check.Eq(cmd.InsertAt, 3, "InsertAt");
// An older engine's command (no NS/EW/Z) still reads, coordinates 0.
NavCommand? old = JsonSerializer.Deserialize("{\"Cmd\":\"deletePoint\",\"Index\":4}", RynthAiJsonContext.Default.NavCommand);
Check.Eq(old!.Index, 4, "old command reads");
Check.Near(old.NS, 0, 0, "absent NS = 0");
// RynthPluginGetNavJson reports the map edit version with the route.
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, Settings(P(1, 2), P(3, 4)));
typeof(LegacyDashboardRenderer).GetField("_navFiles", Any)!.SetValue(dash, new System.Collections.Generic.List<string>());
// Field initializers don't run on an uninitialized object; the route editor's status line.
typeof(LegacyDashboardRenderer).GetField("_navEditStatus", Any)!.SetValue(dash, string.Empty);
using JsonDocument doc = JsonDocument.Parse(dash.BuildNavJson());
Check.True(doc.RootElement.TryGetProperty("MapEdit", out JsonElement me), "MapEdit present");
Check.Eq(me.GetInt32(), NavMapEdit.Version, "MapEdit = Version");
Check.Eq(doc.RootElement.GetProperty("Points").GetArrayLength(), 2, "points exported");
}
private static void SavesRouteFile()
{
string dir = Path.Combine(Program.TempRoot, "NavMapEdit");
Directory.CreateDirectory(dir);
string path = Path.Combine(dir, "maproute.nav");
var s = Settings(P(1, 1), P(2, 2));
s.CurrentRoute.Save(path);
s.CurrentNavPath = path;
var nav = (LegacyNavigationUi)RuntimeHelpers.GetUninitializedObject(typeof(LegacyNavigationUi));
typeof(LegacyNavigationUi).GetField("_settings", Any)!.SetValue(nav, s);
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_navigationUi", Any)!.SetValue(dash, nav);
dash.HandleMapNavCommand(Add(-1.5, 2.5, -0.1, addMode: 2, insertAt: 0));
NavRouteParser reread = NavRouteParser.Load(path);
Check.Eq(reread.Points.Count, 3, "file has the added point");
Check.Near(reread.Points[1].NS, -1.5, 1e-6, "at step 1 (after the selected step 0)");
dash.HandleMapNavCommand(new NavCommand { Cmd = "movePointTo", Index = 2, NS = 4.25, EW = -3.75, Z = -0.2 });
reread = NavRouteParser.Load(path);
Check.Near(reread.Points[2].NS, 4.25, 1e-6, "file has the moved NS");
Check.Near(reread.Points[2].EW, -3.75, 1e-6, "file has the moved EW");
Check.Near(reread.Points[2].Z, -0.2, 1e-6, "file has the moved Z");
}
}

View file

@ -0,0 +1,335 @@
using System;
using System.Linq;
using System.Reflection;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Bounds on the pacer's holds: the 0x1D latch must not throttle melee and missile (ACE sends no
// UseDone for a swing), StuckCastMs = 0 must not hold for ever, a teleport's gap must not break a
// cast by jump, the settle gate stands apart from the animation gate, and only 'too busy' answers
// count toward the refusal burst.
internal static class PacerEdgeTests
{
private const uint Player = 0x50000F21;
private const uint Monster = 0x80116791;
private const int DrainHealthOtherI = 1237;
private static (uint Cell, float X, float Y, float Z) Me0 => (0x6347028Au, 100f, 100f, 0f);
public static void Register(Runner r)
{
r.Add("pacer edge: after a lone 'too busy' answer, attack repeats go (over 50 swings in 60 s); a cast with ours open is still held", AttackRepeatsPastLatch);
r.Add("pacer edge: a 'too busy' latch with no cast of ours open ends after LatchMaxMs (logged once)", LatchExpires);
r.Add("pacer edge: StuckCastMs 0 never deadlocks: a hung cast is dropped as stale by StaleCastMs (inside 120 s)", StuckCastZeroBounded);
r.Add("pacer edge: in portal space nothing is broken (no jump, ForceBreak refused); a cast sent before a 20 s gap is dropped, not jumped", PortalAndGap);
r.Add("pacer edge: 5 'too busy' answers in one second hold every start but a heal, attack repeats too, for the rest of that second", RefusalBurst);
r.Add("pacer edge: the settle gate holds a start with the animation gate off", SettleGateSplit);
r.Add("pacer edge: portal-enter and the death hold forget the open cast and the latch", PortalAndDeathForget);
r.Add("pacer edge: a client-refused forced jump with no cast open does not hold starts for good (latch expiry, probe)", RefusedForcedJumpNoDeadlock);
r.Add("pacer edge: the refusal burst counts 'too busy' only and never holds a heal", BurstCountsTooBusyAndSparesHeals);
}
private static long _t;
private static RynthCoreHost Setup()
{
FakeHost.Reset();
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.WeaponCalls = true;
FakeHost.CombatModeCalls = true;
FakeHost.TapJumpCalls = true;
FakeHost.CombatModeValue = ActionPacer.MagicMode;
FakeHost.Names[Player] = "Mira";
FakeHost.PlayerPose = Me0;
FakeHost.Positions[Player] = Me0;
FakeHost.Positions[Monster] = (Me0.Cell, Me0.X + 10f, Me0.Y, Me0.Z);
var host = FakeHost.Create(Player);
_t = 70_000_000;
ActionPacer.Reset();
ActionPacer.Enabled = true;
ActionPacer.NowMs = () => _t;
MoveAudit.Reset();
MoveAudit.NowMs = () => _t;
ActionPacer.StuckCastMs = 8000;
FakeHost.UseDone(0);
ActionPacer.MayStart(host, "Setup", HealNeed.None, out _); // the UseDone observer's baseline
return host;
}
private static void Done()
{
ActionPacer.Enabled = false;
ActionPacer.Reset();
ActionPacer.NowMs = () => Environment.TickCount64;
MoveAudit.Reset();
MoveAudit.NowMs = () => Environment.TickCount64;
ActionPacer.StuckCastMs = 8000;
FakeHost.Portaling = false;
}
private static bool May(RynthCoreHost host) => ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _);
private static bool Swing(RynthCoreHost host, out string why) =>
ActionPacer.MayStart(host, "Combat", HealNeed.None, out why, animationGate: false, settleGate: false, attackRepeat: true);
private static void Cast(RynthCoreHost host) =>
Check.True(host.CastSpellFor(Monster, DrainHealthOtherI, "Buff", "Drain Health Other I"), "cast sent");
private static int Jumps() => FakeHost.TapJumps + FakeHost.Jumps;
private static void AttackRepeatsPastLatch()
{
var host = Setup();
try
{
FakeHost.CombatModeValue = 2; // melee
FakeHost.UseDone(ActionPacer.TooBusyErr); // a lone 0x1D (a pickup, a player command)
Check.False(May(host), "a gated start is held by the latch");
Check.True(ActionPacer.ServerBusy, "latched");
int swings = 0;
for (int i = 0; i < 60; i++)
{
_t += 1000;
if (Swing(host, out _)) { swings++; ActionPacer.NoteAttackSent(); }
}
Check.True(swings > 55, $"a swing a second for 60 s after the 0x1D (no UseDone ever comes for a swing): {swings}");
// Our cast open (hung past CastMaxMs) and another send refused 'too busy': a cast is still held.
var h2 = Setup();
ActionPacer.StuckCastMs = 0;
Cast(h2);
_t += ActionPacer.CastMaxMs + 100;
Check.False(May(h2), "our cast hung");
FakeHost.UseDone(ActionPacer.TooBusyErr);
bool any = false;
for (int i = 0; i < 50; i++) { _t += 100; any |= May(h2); }
Check.False(any, "a cast with ours open and refused: held");
}
finally { Done(); }
}
private static void LatchExpires()
{
var host = Setup();
ActionPacer.StuckCastMs = 0;
try
{
FakeHost.UseDone(ActionPacer.TooBusyErr);
May(host); // observed here: the latch starts
long t0 = _t;
while (_t + 100 < t0 + ActionPacer.LatchMaxMs) { _t += 100; May(host); }
Check.True(ActionPacer.ServerBusy, "still latched just under LatchMaxMs");
Check.Eq(ActionPacer.LatchExpiries, 0L, "no expiry yet");
_t = t0 + ActionPacer.LatchMaxMs;
Check.True(May(host), "at LatchMaxMs: free");
Check.False(ActionPacer.ServerBusy, "the latch is gone");
Check.Eq(ActionPacer.LatchExpiries, 1L, "one expiry");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("no answer cleared the 'too busy' latch in")), 1, "logged once");
}
finally { Done(); }
}
private static void StuckCastZeroBounded()
{
var host = Setup();
ActionPacer.StuckCastMs = 0;
try
{
Cast(host);
long t0 = _t;
_t += ActionPacer.CastMaxMs + 100;
Check.False(May(host), "our cast hung");
FakeHost.UseDone(ActionPacer.TooBusyErr); // another send refused while it is open
long freeAt = -1;
while (_t < t0 + 120_000) { _t += 100; if (May(host)) { freeAt = _t - t0; break; } }
Check.True(freeAt > 0, "free within 120 s");
Check.True(freeAt >= ActionPacer.StaleCastMs - 100 && freeAt <= ActionPacer.StaleCastMs + 100, $"free at StaleCastMs ({ActionPacer.StaleCastMs}): {freeAt}");
Check.Eq(Jumps(), 0, "StuckCastMs 0: no jump");
Check.True(FakeHost.Logs.Any(l => l.Contains("is stale (") && l.Contains("dropped, the server is taken as free")), "logged");
}
finally { Done(); }
}
private static void PortalAndGap()
{
var host = Setup();
try
{
Cast(host);
FakeHost.Portaling = true;
for (int i = 0; i < 150; i++) { _t += 100; May(host); } // 15 s in portal space
Check.Eq(Jumps(), 0, "portal space: no breaker jump");
Check.False(ActionPacer.ForceBreak(host, "test"), "portal space: ForceBreak refused");
Check.Eq(Jumps(), 0, "still no jump");
FakeHost.Portaling = false;
// A 20 s gap with no check (a freeze, a long portal with the macro off): stale, dropped.
// The tick's frame, then the cast 5 ms later in the same tick, then the freeze.
var g = Setup();
ActionPacer.NoteFrame();
_t += 5;
Cast(g);
_t += 20_000;
ActionPacer.NoteFrame(); // the first frame after the freeze
Check.True(May(g), "after the gap: the cast is dropped and starts go");
Check.Eq(Jumps(), 0, "no jump for a cast sent before the gap");
Check.Eq(ActionPacer.StaleDrops, 1L, "one stale drop");
Check.True(FakeHost.Logs.Any(l => l.Contains("is stale (") && l.Contains("ms gap with no check")), "the gap is in the line");
// Control: the same 20 s with frames every 100 ms is a stuck cast, broken by the jump.
var c = Setup();
Cast(c);
for (int i = 0; i < 200; i++) { _t += 100; ActionPacer.NoteFrame(); May(c); }
Check.True(Jumps() >= 1, "no gap: the stuck cast is broken (control)");
Check.Eq(ActionPacer.StaleDrops, 0L, "and not dropped");
}
finally { Done(); }
}
private static void RefusalBurst()
{
var host = Setup();
try
{
FakeHost.CombatModeValue = 2;
string why = "";
bool[] free = new bool[ActionPacer.RefusalBurstMax];
for (int i = 0; i < ActionPacer.RefusalBurstMax; i++)
{
FakeHost.UseDone(ActionPacer.TooBusyErr);
_t += 50;
free[i] = Swing(host, out why);
}
Check.True(free.Take(ActionPacer.RefusalBurstMax - 1).All(b => b), "4 refusals: still free");
Check.False(free[^1], "the 5th refusal inside a second: held");
Check.True(why.Contains("refusals from the server in the last second"), "why: " + why);
Check.False(May(host), "a gated start too");
Check.True(ActionPacer.BurstHolds >= 1, "counted (the heal start above is held by the latch, not the burst)");
_t += 1000;
Check.True(Swing(host, out _), "a second later: free");
}
finally { Done(); }
}
private static void SettleGateSplit()
{
var host = Setup();
try
{
FakeHost.AutoRun = true;
host.SetAutoRunBy("Nav", true);
_t += 1000;
host.SetAutoRunBy("Nav", false); // the stop goes out this tick
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out string why, animationGate: false),
"animation gate off, settle gate on: held in the tick of the stop");
Check.True(why.Length > 0, "why: " + why);
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _, animationGate: false, settleGate: false),
"both off: free (only attack repeats do this)");
_t += MoveAudit.MoveSettleMinMs;
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _, animationGate: false), "settled: free");
}
finally { Done(); }
}
// ForceBreak with no cast open and the client refusing the jump must not leave the breaker stage
// at Landed for nothing, which would hold every start for good.
private static void RefusedForcedJumpNoDeadlock()
{
var host = Setup();
try
{
FakeHost.UseDone(ActionPacer.TooBusyErr);
May(host); // the latch starts here
long t0 = _t;
FakeHost.TapJumpRefuse = true;
Check.True(ActionPacer.ForceBreak(host, "test"), "the forced break is tried");
Check.Eq(FakeHost.TapJumps, 1, "the jump was sent (and refused)");
long firstFree = -1;
while (_t < t0 + ActionPacer.LatchMaxMs + 500) { _t += 100; if (May(host) && firstFree < 0) firstFree = _t - t0; }
Check.True(firstFree > 0 && firstFree <= ActionPacer.LatchMaxMs + 100, $"a start goes by LatchMaxMs (first at {firstFree} ms)");
Check.False(ActionPacer.ServerBusy, "the latch is gone by then");
Check.Eq(ActionPacer.LatchExpiries, 1L, "it expired");
}
finally { Done(); }
}
// 0x401 retries (5 a second by design) do not trip the burst, and the burst never holds a heal.
private static void BurstCountsTooBusyAndSparesHeals()
{
var host = Setup();
try
{
for (int i = 0; i < ActionPacer.RefusalBurstMax + 1; i++) { FakeHost.UseDone(0x401); _t += 50; May(host); }
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out string w1), "6 'not enough mana' answers in a second: no burst hold (" + w1 + ")");
Check.Eq(ActionPacer.BurstHolds, 0L, "none counted");
var h = Setup();
for (int i = 0; i < ActionPacer.RefusalBurstMax; i++)
{
FakeHost.UseDone(ActionPacer.TooBusyErr);
_t += 50;
ActionPacer.MayStart(h, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true);
}
FakeHost.UseDone(0); // the server answers: the latch is gone, the burst is not
_t += 50;
Check.False(ActionPacer.MayStart(h, "Buff", HealNeed.None, out string why), "inside the second: a buff is held by the burst");
Check.True(why.Contains("refusals from the server in the last second"), "why: " + why);
Check.True(ActionPacer.MayStart(h, "Buff", HealNeed.Emergency, out string hw), "an emergency heal is not (" + hw + ")");
Check.True(ActionPacer.MayStart(h, "Buff", HealNeed.Heal, out _), "nor a heal");
}
finally { Done(); }
}
internal static void SetHost(RynthAiPlugin p, RynthCoreHost host)
{
for (Type? t = p.GetType(); t != null; t = t.BaseType)
{
var prop = t.GetProperty("Host", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
if (prop?.SetMethod != null) { prop.SetValue(p, host); return; }
var f = t.GetField("<Host>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
?? t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly).FirstOrDefault(x => x.FieldType == typeof(RynthCoreHost));
if (f != null) { f.SetValue(p, host); return; }
}
throw new InvalidOperationException("no Host to set on RynthAiPlugin");
}
private static void Call(object o, string name) =>
o.GetType().GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(o, null);
private static void PortalAndDeathForget()
{
var host = Setup();
try
{
ActionPacer.StuckCastMs = 0;
var p = new RynthAiPlugin();
SetHost(p, host);
Cast(host);
_t += ActionPacer.CastMaxMs + 100;
FakeHost.UseDone(ActionPacer.TooBusyErr);
May(host);
Check.True(ActionPacer.ServerBusy, "our cast hung, latched");
Call(p, "NotePortalForPacer");
Check.True(ActionPacer.ServerBusy, "not portaling: nothing forgotten");
FakeHost.Portaling = true;
Call(p, "NotePortalForPacer");
Check.False(ActionPacer.ServerBusy, "portal-enter: the latch is forgotten");
Check.True(May(host), "and starts go");
FakeHost.Portaling = false;
Call(p, "NotePortalForPacer");
Cast(host);
_t += ActionPacer.CastMaxMs + 100;
FakeHost.UseDone(ActionPacer.TooBusyErr);
May(host);
Check.True(ActionPacer.ServerBusy, "latched again");
FakeHost.Vitals = (0, 100, 0, 100, 0, 100);
Call(p, "HoldForDeath");
Check.False(ActionPacer.ServerBusy, "the death hold forgets the latch");
Check.True(May(host), "and starts go");
}
finally { Done(); }
}
}

View file

@ -27,9 +27,10 @@ namespace RynthCore.RynthAiHostTests.Tests;
internal static class PatrolDoorwayTests
{
// 2026-10-10, 0x6146: hazards cut the loops and the patrol fell back to every dead end. Now,
// in that case, only short spurs (closets) go: a junction J with a 1-cell closet, a 3-cell
// spur and a 5-cell branch hanging off a loop.
private static void TrimShortSpurs()
// in that case, only small dead ends (closets) go: a junction J with a 1-cell closet, a 3-cell
// spur and a 5-cell branch hanging off a loop. Since 2026-10-13 whole dead-end areas
// (TrimDeadEndPockets, PatrolPocketTests): the branch is walked until 3 cells are left.
private static void TrimSmallDeadEnds()
{
var g = new Dictionary<uint, DungeonNavNode>();
void Link(uint a, uint b)
@ -44,12 +45,13 @@ internal static class PatrolDoorwayTests
Link(0x01, 0x20); Link(0x20, 0x21); Link(0x21, 0x22); // 3-cell spur
Link(0x02, 0x30); Link(0x30, 0x31); Link(0x31, 0x32); Link(0x32, 0x33); Link(0x33, 0x34); // 5-cell branch
var all = new HashSet<uint>(g.Keys);
var kept = DungeonPathfinder.TrimShortSpurs(g, all, 0x03, DungeonPathfinder.PatrolMaxSpurCells);
var kept = DungeonPathfinder.TrimDeadEndPockets(g, all, 0x03, 3);
Check.False(kept.Contains(0x10), "the 1-cell closet goes");
Check.False(kept.Overlaps(new uint[] { 0x20, 0x21, 0x22 }), "the 3-cell spur goes");
Check.True(kept.IsSupersetOf(new uint[] { 0x30, 0x31, 0x32, 0x33, 0x34 }), "the 5-cell branch stays whole");
Check.True(kept.IsSupersetOf(new uint[] { 0x30, 0x31 }) && !kept.Overlaps(new uint[] { 0x32, 0x33, 0x34 }),
"the 5-cell branch is walked until 3 cells are left");
Check.True(kept.IsSupersetOf(new uint[] { 1, 2, 3, 4 }), "the loop stays");
var keepStart = DungeonPathfinder.TrimShortSpurs(g, all, 0x10, DungeonPathfinder.PatrolMaxSpurCells);
var keepStart = DungeonPathfinder.TrimDeadEndPockets(g, all, 0x10, DungeonPathfinder.PatrolMaxDeadEndCells);
Check.True(keepStart.Contains(0x10), "the start cell is never trimmed");
}
@ -63,9 +65,10 @@ internal static class PatrolDoorwayTests
r.Add("dungeon rooms: an L-shaped room's crossing goes round the corner, on the floor", LShapedRoom);
r.Add("dungeon rooms: a pillar in the way bends the crossing round it", PillarInTheWay);
r.Add("dungeon patrol: a loop through a big room: no points inside it, every doorway taken", PatrolLoop);
r.Add("dungeon patrol: a big dead-end room is looked into, not skirted", PatrolLooksIntoDeadEndRoom);
r.Add("dungeon patrol: a big dead-end room is looked into, not skirted (and not when under Walk Into Rooms From)", PatrolLooksIntoDeadEndRoom);
r.Add("dungeon patrol settings: Distance From Walls 0.5 / 1 / 1.5 / 2 m kept by every point", PatrolWallDistanceSetting);
r.Add("dungeon floors: a ceiling (facing down) is not a floor", CeilingIsNotFloor);
r.Add("dungeon patrol: spurs of up to 3 cells trimmed, a long branch kept whole", TrimShortSpurs);
r.Add("dungeon patrol: dead ends of up to 3 cells trimmed, a longer one walked until 3 are left", TrimSmallDeadEnds);
r.Add("dungeon clearance: walls, floor edges and slopes too steep to stand on bound it; a face high above doesn't", ClearanceMeasure);
r.Add("dungeon clearance: a point next to a wall (or past the floor's edge) is pushed out to 1 m", PushedOffWall);
r.Add("dungeon clearance: a point in a corridor narrower than 2 m ends on its middle line", NarrowCorridorCentred);
@ -407,6 +410,32 @@ internal static class PatrolDoorwayTests
var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo);
bool looked = route.Points.Any(p => X(p) > 10 && X(p) < 20 && Y(p) > 10 && Y(p) < 20);
Check.True(looked, "the patrol walks into the middle of the dead-end room");
// Settings "Walk Into Rooms From": the room (3x3 cells, 20 m between its outer cell
// centres: spread 28 m) is under 40 m, so it is only looked into from its doorway.
var big = DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo, new DungeonPatrolOptions { LookInRoomMeters = 40 });
Check.False(big.Points.Any(p => X(p) > 10 && X(p) < 20 && Y(p) > 10 && Y(p) < 20),
"with rooms from 40 m: the 28 m room's middle is not walked to");
var at20 = DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo, new DungeonPatrolOptions { LookInRoomMeters = 20 });
Check.True(at20.Points.Any(p => X(p) > 10 && X(p) < 20 && Y(p) > 10 && Y(p) < 20), "with rooms from 20 m: it is");
}
// Settings "Distance From Walls": every patrol point keeps the chosen distance where the
// corridors (5.3 m wide) and rooms allow it.
private static void PatrolWallDistanceSetting()
{
var (d, _, west, _, _) = LoopDungeon();
var geo = d.Geo();
foreach (double wall in new[] { 0.5, 1.0, 1.5, 2.0 })
{
var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo, new DungeonPatrolOptions { WallClearance = wall });
Check.True(route.Points.Count > 0, $"{wall} m: a patrol");
double least = route.Points.Min(p => Clear(geo, p));
Check.True(least >= wall - 0.02, $"{wall} m: every point at least that far from the walls (least {least:F2})");
}
var near = DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo, new DungeonPatrolOptions { WallClearance = 0.5 });
var far = DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo, new DungeonPatrolOptions { WallClearance = 2.0 });
Check.True(far.Points.Min(p => Clear(geo, p)) > near.Points.Min(p => Clear(geo, p)) + 0.5, "2 m keeps points further off the walls than 0.5 m");
}
private static void CeilingIsNotFloor()

View file

@ -0,0 +1,205 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Dead ends the patrol leaves out (DungeonPathfinder.TrimDeadEndPockets, Settings "Skip Dead Ends
// Up To", 2026-10-13). They were spurs: from a tip inward through corridor cells to the first
// junction, at most 3 cells. A small room's cells join each other (junctions), so the walk
// stopped at the room and a corridor ending in a 3-5 cell room was always walked into (Tom:
// "running into small rooms again"; raising the limit changed nothing in 0x6146). Now whole
// dead-end areas are measured: everything hanging off the rest by one cell (or room) counts.
//
// The fixture: a 12-cell loop (1..12, 10 m a cell) with
// off 1: a corridor 0x20-0x21 into a 4-cell room 0x22-0x25 (its cells all joined): 6 cells
// off 4: a closet 0x30
// off 7: a branch: corridor 0x40-0x43, then a 16-cell hall 0x50-0x5F (a 4x4 grid), and off
// the hall a corridor 0x60 into a 3-cell room 0x61-0x63 (4 cells); off corridor cell
// 0x41 a closet 0x48
internal static class PatrolPocketTests
{
public static void Register(Runner r)
{
r.Add("patrol dead ends: a corridor into a small room is one dead end, left out whole (spurs kept it)", CorridorAndRoomDropped);
r.Add("patrol dead ends: a branch to a big hall is walked; the small dead ends off it are not", BigBranchKept);
r.Add("patrol dead ends: in a long dead end the patrol turns round where only N cells are left", LongDeadEndTurnsRound);
r.Add("patrol dead ends: the start's own dead end is kept (it walks out of it)", StartInsidePocket);
r.Add("patrol dead ends: a linear dungeon is walked end to end, room and all", LinearUntouched);
r.Add("patrol dead ends: by room, a junction's own arms are part of it; a big room is never left out", ByRoom);
r.Add("patrol dead ends: the main route log says dead-end areas", MainRouteNote);
}
private static readonly uint[] Loop = Enumerable.Range(1, 12).Select(i => (uint)i).ToArray();
private static readonly uint[] SmallRoomPocket = { 0x20, 0x21, 0x22, 0x23, 0x24, 0x25 };
private static readonly uint[] Hall = Enumerable.Range(0x50, 16).Select(i => (uint)i).ToArray();
private static readonly uint[] HallCorridor = { 0x40, 0x41, 0x42, 0x43 };
private static readonly uint[] OffHall = { 0x60, 0x61, 0x62, 0x63 };
private sealed class G
{
public readonly Dictionary<uint, DungeonNavNode> Graph = new();
public void At(uint c, double eastM, double northM)
{
if (!Graph.TryGetValue(c, out var n)) Graph[c] = n = new DungeonNavNode { CellId = c };
n.EW = eastM / 240.0; n.NS = northM / 240.0;
}
public void Link(uint a, uint b)
{
foreach (uint c in new[] { a, b })
if (!Graph.ContainsKey(c)) At(c, (c & 0xF) * 10, (c >> 4) * 10);
Graph[a].Neighbors.Add(b); Graph[b].Neighbors.Add(a);
}
public void Chain(params uint[] cells) { for (int i = 0; i + 1 < cells.Length; i++) Link(cells[i], cells[i + 1]); }
public void Clique(params uint[] cells) { for (int i = 0; i < cells.Length; i++) for (int j = i + 1; j < cells.Length; j++) Link(cells[i], cells[j]); }
}
private static G Fixture()
{
var g = new G();
for (int i = 0; i < Loop.Length; i++)
{
double a = 2 * Math.PI * i / Loop.Length;
g.At(Loop[i], 200 + 20 * Math.Cos(a), 200 + 20 * Math.Sin(a));
}
for (int i = 0; i < Loop.Length; i++) g.Link(Loop[i], Loop[(i + 1) % Loop.Length]);
g.Chain(1, 0x20, 0x21, 0x22);
g.Clique(0x22, 0x23, 0x24, 0x25);
g.Link(4, 0x30);
g.Chain(7, 0x40, 0x41, 0x42, 0x43, 0x50);
for (int y = 0; y < 4; y++)
for (int x = 0; x < 4; x++)
{
uint c = (uint)(0x50 + y * 4 + x);
if (x < 3) g.Link(c, c + 1);
if (y < 3) g.Link(c, c + 4);
}
g.Chain(0x5F, 0x60, 0x61);
g.Clique(0x61, 0x62, 0x63);
g.Link(0x41, 0x48);
return g;
}
private static HashSet<uint> All(G g) => new(g.Graph.Keys);
private static string Ids(IEnumerable<uint> c) => string.Join(",", c.OrderBy(x => x).Select(x => x.ToString("X")));
private static void CorridorAndRoomDropped()
{
var g = Fixture();
var kept = DungeonPathfinder.TrimDeadEndPockets(g.Graph, All(g), 6, 10);
Check.False(kept.Overlaps(SmallRoomPocket), $"corridor + room (6 cells) left out ({Ids(kept.Intersect(SmallRoomPocket))} kept)");
Check.False(kept.Contains(0x30), "the closet left out");
Check.True(kept.IsSupersetOf(Loop), "the loop walked");
Check.True(DungeonPathfinder.TrimDeadEndPockets(g.Graph, All(g), 6, 6).IsSupersetOf(Loop)
&& !DungeonPathfinder.TrimDeadEndPockets(g.Graph, All(g), 6, 6).Overlaps(SmallRoomPocket), "at 6 too (exactly its size)");
Check.Eq(DungeonPathfinder.TrimDeadEndPockets(g.Graph, All(g), 6, 0).Count, g.Graph.Count, "0: nothing left out");
}
private static void BigBranchKept()
{
var g = Fixture();
var kept = DungeonPathfinder.TrimDeadEndPockets(g.Graph, All(g), 6, 10);
Check.True(kept.IsSupersetOf(HallCorridor) && kept.IsSupersetOf(Hall), $"the corridor and the 16-cell hall walked ({Ids(kept)})");
Check.False(kept.Overlaps(OffHall), "the corridor + small room off the hall left out");
Check.False(kept.Contains(0x48), "the closet off the branch's corridor left out");
// Cell by cell the hall past its first cell (0x50) hangs off that cell alone: 19 cells.
var at18 = DungeonPathfinder.TrimDeadEndPockets(g.Graph, All(g), 6, 18);
Check.True(at18.IsSupersetOf(Hall) && !at18.Overlaps(OffHall), $"at 18 the hall is still walked ({Ids(at18)})");
var at20 = DungeonPathfinder.TrimDeadEndPockets(g.Graph, All(g), 6, 20);
Check.True(at20.IsSupersetOf(HallCorridor) && !at20.Overlaps(Hall),
"at 20 the hall and what's behind it (20 cells) is a small dead end: the patrol turns round before it");
var at30 = DungeonPathfinder.TrimDeadEndPockets(g.Graph, All(g), 6, 30);
Check.False(at30.Overlaps(Hall) || at30.Overlaps(HallCorridor), "at 30 the whole branch is a small dead end");
}
private static void LongDeadEndTurnsRound()
{
// A 14-cell corridor off a loop, nothing at its end: at 10 the first 4 cells are walked.
var g = new G();
for (int i = 0; i < Loop.Length; i++) g.Link(Loop[i], Loop[(i + 1) % Loop.Length]);
var corridor = Enumerable.Range(0x70, 14).Select(i => (uint)i).ToArray();
g.Chain(new[] { 3u }.Concat(corridor).ToArray());
var kept = DungeonPathfinder.TrimDeadEndPockets(g.Graph, All(g), 9, 10);
Check.True(kept.IsSupersetOf(corridor.Take(4)) && !kept.Overlaps(corridor.Skip(4)),
$"walked in until 10 cells are left ({Ids(kept.Intersect(corridor))})");
}
private static void StartInsidePocket()
{
var g = Fixture();
var inRoom = DungeonPathfinder.TrimDeadEndPockets(g.Graph, All(g), 0x23, 10);
Check.True(inRoom.IsSupersetOf(SmallRoomPocket), "starting in the small room: the room and its corridor kept");
Check.False(inRoom.Contains(0x30), "the closet elsewhere still left out");
Check.True(inRoom.IsSupersetOf(Loop) && inRoom.IsSupersetOf(Hall), "and the rest walked");
var inCloset = DungeonPathfinder.TrimDeadEndPockets(g.Graph, All(g), 0x30, 10);
Check.True(inCloset.Contains(0x30), "starting in the closet: kept");
Check.False(inCloset.Overlaps(SmallRoomPocket), "the small room still left out");
// Through GetMainRouteNodes (the patrol's way in).
var route = DungeonPathfinder.GetMainRouteNodes(g.Graph, 0x30, null, DungeonPatrolOptions.Default);
Check.True(route.Contains(0x30) && !route.Overlaps(SmallRoomPocket), $"main route from the closet ({Ids(route)})");
}
private static void LinearUntouched()
{
// No loops: a 12-cell corridor with a 3-cell side passage and a 2-cell closet off it.
// The dungeon is linear and every cell is walked whatever the limit.
var g = new G();
var corridor = Enumerable.Range(0x70, 12).Select(i => (uint)i).ToArray();
g.Chain(corridor);
g.Chain(0x74, 0x80, 0x81, 0x82);
g.Chain(0x79, 0x90, 0x91);
foreach (PatrolCoverage cov in Enum.GetValues<PatrolCoverage>())
foreach (int n in new[] { 3, 10, 30 })
Check.Eq(DungeonPathfinder.GetMainRouteNodes(g.Graph, 0x76, null, new DungeonPatrolOptions { Coverage = cov, MaxDeadEndCells = n }).Count,
17, $"{cov}, dead ends {n}: all 17 cells");
}
private static void ByRoom()
{
// A star junction: centre 0x91 with arms 0x90, 0x92, 0x93, 0x94 (one room: the pieces of a
// junction). 0x90 and 0x92 go on round a loop; 0x93 and 0x94 lead nowhere.
var g = new G();
foreach (uint arm in new uint[] { 0x90, 0x92, 0x93, 0x94 }) g.Link(0x91, arm);
var ring = Enumerable.Range(0xA0, 10).Select(i => (uint)i).ToArray();
g.Chain(new[] { 0x92u }.Concat(ring).Concat(new[] { 0x90u }).ToArray());
// Off the ring: a corridor 0xB0 into a big room 0xB1-0xB4 (cells spread 30 m: a hall).
g.Link(0xA5, 0xB0);
g.Clique(0xB1, 0xB2, 0xB3, 0xB4);
g.Link(0xB0, 0xB1);
g.At(0xB1, 500, 500); g.At(0xB2, 520, 500); g.At(0xB3, 500, 520); g.At(0xB4, 520, 520);
var rooms = new DungeonRooms();
void Room(params uint[] cells)
{
int r = rooms.Cells.Count;
rooms.Cells.Add(cells.ToList());
foreach (uint c in cells) rooms.RoomOf[c] = r;
}
Room(0x90, 0x91, 0x92, 0x93, 0x94);
Room(0xB1, 0xB2, 0xB3, 0xB4);
foreach (uint c in g.Graph.Keys) if (!rooms.RoomOf.ContainsKey(c)) Room(c);
var byCell = DungeonPathfinder.TrimDeadEndPockets(g.Graph, All(g), 0xA2, 10);
Check.False(byCell.Contains(0x93) || byCell.Contains(0x94), "cell by cell, the junction's dead arms are closets");
var byRoom = DungeonPathfinder.TrimDeadEndPockets(g.Graph, All(g), 0xA2, 10, rooms);
Check.True(byRoom.IsSupersetOf(new uint[] { 0x90, 0x91, 0x92, 0x93, 0x94 }), "by room, the junction is walked whole");
Check.True(byRoom.IsSupersetOf(new uint[] { 0xB0, 0xB1, 0xB2, 0xB3, 0xB4 }), "a big room (28 m) in a 5-cell dead end is walked");
var lookIn40 = DungeonPathfinder.TrimDeadEndPockets(g.Graph, All(g), 0xA2, 10, rooms, bigRoomMeters: 40);
Check.False(lookIn40.Overlaps(new uint[] { 0xB0, 0xB1, 0xB2, 0xB3, 0xB4 }), "with Walk Into Rooms From 40 it is a small one: left out");
Check.False(byCell.Overlaps(new uint[] { 0xB0, 0xB1 }), "cell by cell (no rooms, no sizes) it is left out too");
}
private static void MainRouteNote()
{
var g = Fixture();
DungeonPathfinder.PointLog = new Dictionary<NavPoint, DungeonPathfinder.PatrolPointInfo>(ReferenceEqualityComparer.Instance);
try { DungeonPathfinder.GetMainRouteNodes(g.Graph, 6, null, DungeonPatrolOptions.Default); }
finally { DungeonPathfinder.PointLog = null; }
string note = DungeonPathfinder.MainRouteNote ?? "";
Check.True(note.Contains("dead-end areas of <= 10 cells"), note);
}
}

View file

@ -0,0 +1,213 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Settings > Navigation > Dungeon Patrol (DungeonPatrolOptions, 2026-10-12): which cells the
// patrol walks for each Coverage, the dead-end limit, lava/acid floors on or off; the defaults
// give the patrol as it was before the settings, but for the dead-end limit (whole dead-end areas
// since 2026-10-13, default 10; PatrolPocketTests); the settings reach the options in range and
// round-trip through the engine payload and profiles; a change mid-patrol rebuilds it once it
// settles. The look-into-rooms size and the wall distance are in PatrolDoorwayTests (they need
// the map geometry).
//
// The fixture: a 10-cell loop (cells 1..10) with, off cell 1, a 1-cell closet (0x10) and a
// 3-cell spur (0x20-0x22), and off cell 2 a 5-cell branch (0x30-0x34). 19 cells, 2-core 10.
internal static class PatrolSettingsTests
{
public static void Register(Runner r)
{
r.Add("patrol settings: the defaults (whole dungeon, dead-end areas of <= 10 cells skipped)", DefaultsAreToday);
r.Add("patrol settings: Loops only walks the 2-core", LoopsOnly);
r.Add("patrol settings: Everything walks every reachable cell", Everything);
r.Add("patrol settings: Skip Dead Ends 0 / 1 / 3 / 4 / 5 / 10 / 99", SpurLimits);
r.Add("patrol settings: a linear dungeon walks everything whatever the coverage", LinearWalksEverything);
r.Add("patrol settings: Avoid Lava/Acid Floors off walks the floor cells, sighted/marked cells still avoided", HazardFloors);
r.Add("patrol settings: settings to options, defaults equal, out-of-range values clamped", OptionsFromSettings);
r.Add("patrol settings: sent to the engine face, applied from it, absent = unchanged", EnginePayload);
r.Add("patrol settings: a change rebuilds the patrol once it has settled for 1 s", RebuildWhenSettled);
}
private const uint Closet = 0x10;
private static readonly uint[] Spur3 = { 0x20, 0x21, 0x22 };
private static readonly uint[] Branch5 = { 0x30, 0x31, 0x32, 0x33, 0x34 };
private static readonly uint[] Loop = Enumerable.Range(1, 10).Select(i => (uint)i).ToArray();
private static Dictionary<uint, DungeonNavNode> Fixture()
{
var g = new Dictionary<uint, DungeonNavNode>();
void Link(uint a, uint b)
{
foreach (uint c in new[] { a, b })
if (!g.ContainsKey(c)) g[c] = new DungeonNavNode { CellId = c, NS = (c & 0x0F) * 0.01, EW = (c >> 4 & 0x0F) * 0.01 };
g[a].Neighbors.Add(b); g[b].Neighbors.Add(a);
}
for (int i = 0; i < Loop.Length; i++) Link(Loop[i], Loop[(i + 1) % Loop.Length]);
Link(1, Closet);
Link(1, Spur3[0]); Link(Spur3[0], Spur3[1]); Link(Spur3[1], Spur3[2]);
Link(2, Branch5[0]);
for (int i = 0; i + 1 < Branch5.Length; i++) Link(Branch5[i], Branch5[i + 1]);
return g;
}
private static HashSet<uint> Cells(DungeonPatrolOptions? o, IReadOnlySet<uint>? hazards = null, uint start = 5)
=> DungeonPathfinder.GetMainRouteNodes(Fixture(), start, hazards, o);
private static string Ids(IEnumerable<uint> c) => string.Join(",", c.OrderBy(x => x).Select(x => x.ToString("X")));
private static void DefaultsAreToday()
{
var expected = new HashSet<uint>(Loop); // the closet, the 3-cell spur and the 5-cell branch go
Check.True(Cells(null).SetEquals(expected), $"no options: the loop ({Ids(Cells(null))})");
Check.True(Cells(DungeonPatrolOptions.Default).SetEquals(expected), "DungeonPatrolOptions.Default: the same");
Check.True(Cells(RynthAiPlugin.PatrolOptionsFrom(new LegacyUiSettings())).SetEquals(expected), "a fresh profile's settings: the same");
// And the route itself: no options = default options = a fresh profile's settings, point for point.
var g = Fixture();
var a = DungeonPathfinder.BuildPatrolRoute(g, 5, null, null);
var b = DungeonPathfinder.BuildPatrolRoute(g, 5, null, null, DungeonPatrolOptions.Default);
var c = DungeonPathfinder.BuildPatrolRoute(g, 5, null, null, RynthAiPlugin.PatrolOptionsFrom(new LegacyUiSettings()));
Check.True(a.Points.Count > 0, "a patrol");
Check.True(Same(a, b) && Same(a, c), "the same points in the same order");
}
private static bool Same(NavRouteParser a, NavRouteParser b)
=> a.Points.Count == b.Points.Count
&& a.Points.Zip(b.Points).All(p => p.First.NS == p.Second.NS && p.First.EW == p.Second.EW && p.First.Z == p.Second.Z);
private static void LoopsOnly()
{
var cells = Cells(new DungeonPatrolOptions { Coverage = PatrolCoverage.LoopsOnly });
Check.True(cells.SetEquals(Loop), $"just the loop ({Ids(cells)})");
}
private static void Everything()
{
var cells = Cells(new DungeonPatrolOptions { Coverage = PatrolCoverage.Everything });
Check.Eq(cells.Count, 19, "all 19 cells");
Check.True(cells.Contains(Closet) && cells.IsSupersetOf(Spur3), "the closet and the short spur too");
var anySpurs = Cells(new DungeonPatrolOptions { Coverage = PatrolCoverage.Everything, MaxDeadEndCells = 10 });
Check.Eq(anySpurs.Count, 19, "the dead-end limit doesn't apply to Everything");
}
private static void SpurLimits()
{
DungeonPatrolOptions Spurs(int n) => new() { MaxDeadEndCells = n };
Check.Eq(Cells(Spurs(0)).Count, 19, "0: every dead end entered");
// A dead end longer than the limit is walked until only the limit is left ahead.
Check.True(Cells(Spurs(3)).SetEquals(Loop.Concat(Branch5.Take(2))), $"3: closet and 3-cell spur skipped, 2 cells into the branch ({Ids(Cells(Spurs(3)))})");
Check.True(Cells(Spurs(4)).SetEquals(Loop.Concat(Branch5.Take(1))), "4: 1 cell into the 5-cell branch");
Check.True(Cells(Spurs(5)).SetEquals(Loop), "5: the 5-cell branch skipped too");
Check.True(Cells(Spurs(10)).SetEquals(Loop), "10: the same");
Check.Eq(Cells(Spurs(99)).Count, Cells(Spurs(10)).Count, "99: as 10 here (BuildPatrolRoute clamps it to 30)");
var one = Cells(Spurs(1));
Check.True(!one.Contains(Closet) && !one.Contains(Spur3[2]) && one.IsSupersetOf(Spur3.Take(2)) && !one.Contains(Branch5[4]),
$"1: the closet and the last cell of each dead end skipped ({Ids(one)})");
}
private static void LinearWalksEverything()
{
var g = new Dictionary<uint, DungeonNavNode>();
for (uint i = 1; i <= 12; i++) g[i] = new DungeonNavNode { CellId = i, NS = i * 0.01, EW = 0 };
for (uint i = 1; i < 12; i++) { g[i].Neighbors.Add(i + 1); g[i + 1].Neighbors.Add(i); }
foreach (PatrolCoverage cov in Enum.GetValues<PatrolCoverage>())
Check.Eq(DungeonPathfinder.GetMainRouteNodes(g, 6, null, new DungeonPatrolOptions { Coverage = cov }).Count, 12,
$"{cov}: all 12 cells of a corridor");
}
private static void HazardFloors()
{
// 0x31 has a lava floor texture; 0x07 (on the loop) is a sighted pool.
var floor = new HashSet<uint> { 0x31 };
var marked = new HashSet<uint> { 0x07 };
var live = new HashSet<uint> { 0x31, 0x07 };
var on = new DungeonPatrolOptions();
var off = new DungeonPatrolOptions { AvoidHazardFloors = false };
var hzOn = DungeonPathfinder.PatrolHazards(live, floor, marked, on);
Check.True(hzOn!.SetEquals(live), "on: every hazard cell avoided");
var cellsOn = Cells(on, hzOn);
Check.False(cellsOn.Contains(0x31) || cellsOn.Contains(0x32), "on: the lava cell and the branch beyond it are not walked");
var hzOff = DungeonPathfinder.PatrolHazards(live, floor, marked, off);
Check.True(hzOff!.SetEquals(new uint[] { 0x07 }), $"off: only the sighted pool left ({Ids(hzOff!)})");
var cellsOff = Cells(off with { Coverage = PatrolCoverage.Everything }, hzOff);
Check.True(cellsOff.IsSupersetOf(Branch5), "off: the lava cell and the branch beyond it are walked");
Check.False(cellsOff.Contains(0x07), "off: the sighted pool is still avoided");
var both = DungeonPathfinder.PatrolHazards(live, floor, new HashSet<uint> { 0x07, 0x31 }, off);
Check.True(both!.Contains(0x31), "off: a floor cell that was also marked by hand stays avoided");
Check.True(DungeonPathfinder.PatrolHazards(null, floor, marked, off) == null, "no hazards: none");
}
private static void OptionsFromSettings()
{
var d = RynthAiPlugin.PatrolOptionsFrom(new LegacyUiSettings());
Check.True(d.Equals(DungeonPatrolOptions.Default), "a fresh profile = the defaults: " + d.Describe());
var s = new LegacyUiSettings
{
DunPatrolCoverage = 7, DunPatrolSkipDeadEnds = 99, DunPatrolAvoidFloors = false,
DunPatrolWallDistance = 9f, DunPatrolLookInSize = -4f,
};
var o = RynthAiPlugin.PatrolOptionsFrom(s);
Check.Eq(o.Coverage, PatrolCoverage.Everything, "coverage 7 -> 2 (everything)");
Check.Eq(o.MaxDeadEndCells, 30, "dead ends 99 -> 30");
Check.False(o.AvoidHazardFloors, "floors off");
Check.Near(o.WallClearance, 2.0, 1e-9, "walls 9 -> 2 m");
Check.Near(o.LookInRoomMeters, 3.0, 1e-9, "look-in -4 -> 3 m");
s.DunPatrolCoverage = 1; s.DunPatrolSkipDeadEnds = 5; s.DunPatrolWallDistance = 1.5f; s.DunPatrolLookInSize = 20f;
o = RynthAiPlugin.PatrolOptionsFrom(s);
Check.True(o.Coverage == PatrolCoverage.LoopsOnly && o.MaxDeadEndCells == 5 && o.WallClearance == 1.5 && o.LookInRoomMeters == 20,
"in-range values pass through: " + o.Describe());
}
private static void EnginePayload()
{
var s = new LegacyUiSettings { DunPatrolCoverage = 1, DunPatrolSkipDeadEnds = 6, DunPatrolAvoidFloors = false, DunPatrolWallDistance = 1.25f, DunPatrolLookInSize = 15f };
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)!
.SetValue(dash, new LegacyAdvancedSettingsUi(s));
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!;
Check.True(sent.DunPatrolCoverage == 1 && sent.DunPatrolSkipDeadEnds == 6 && sent.DunPatrolAvoidFloors == false
&& sent.DunPatrolWallDistance == 1.25f && sent.DunPatrolLookInSize == 15f, "every patrol setting sent to the engine face");
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
Check.True(s.DunPatrolCoverage == 1 && s.DunPatrolSkipDeadEnds == 6 && !s.DunPatrolAvoidFloors && s.DunPatrolWallDistance == 1.25f
&& s.DunPatrolLookInSize == 15f, "a save from an engine without them leaves them alone");
dash.ApplySettingsJson("{\"DunPatrolCoverage\":2,\"DunPatrolSkipDeadEnds\":0,\"DunPatrolAvoidFloors\":true,\"DunPatrolWallDistance\":0.75,\"DunPatrolLookInSize\":30}");
Check.True(s.DunPatrolCoverage == 2 && s.DunPatrolSkipDeadEnds == 0 && s.DunPatrolAvoidFloors && s.DunPatrolWallDistance == 0.75f
&& s.DunPatrolLookInSize == 30f, "a save with them applies them");
dash.ApplySettingsJson("{\"DunPatrolCoverage\":9,\"DunPatrolSkipDeadEnds\":40,\"DunPatrolWallDistance\":0.1,\"DunPatrolLookInSize\":100}");
Check.True(s.DunPatrolCoverage == 2 && s.DunPatrolSkipDeadEnds == 30 && s.DunPatrolWallDistance == 0.5f && s.DunPatrolLookInSize == 40f,
$"out of range clamped ({s.DunPatrolCoverage}, {s.DunPatrolSkipDeadEnds}, {s.DunPatrolWallDistance}, {s.DunPatrolLookInSize})");
}
private static void RebuildWhenSettled()
{
var w = new PatrolSettingsWatch();
var a = DungeonPatrolOptions.Default;
var b = a with { MaxDeadEndCells = 5 };
var c = a with { MaxDeadEndCells = 6 };
Check.False(w.ShouldRebuild(b, 0), "no patrol built yet: nothing to rebuild");
w.MarkBuilt(a);
Check.False(w.ShouldRebuild(a, 100), "unchanged: no rebuild");
Check.False(w.ShouldRebuild(b, 1000), "changed: wait for it to settle");
Check.False(w.ShouldRebuild(b, 1999), "still within 1 s");
Check.False(w.ShouldRebuild(c, 2100), "changed again (a second click): the wait starts over");
Check.False(w.ShouldRebuild(c, 3000), "0.9 s after the last change");
Check.True(w.ShouldRebuild(c, 3100), "1 s unchanged: rebuild");
w.MarkBuilt(c);
Check.False(w.ShouldRebuild(c, 5000), "rebuilt with it: no more rebuilds");
Check.False(w.ShouldRebuild(b, 6000), "changed");
Check.False(w.ShouldRebuild(c, 6500), "and changed back before it settled: nothing to do");
Check.False(w.ShouldRebuild(c, 9000), "still nothing");
}
}

View file

@ -0,0 +1,246 @@
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Loot;
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;
// Plugin-only fixes:
// - a selection change sent duplicate identifies and health queries (the engine selects every
// corpse it opens and every item it moves): creatures only, and no identify when cached;
// - the fellowship name read scanned to a NUL without a bound.
// (The Shutdown exports' try/catch is an [UnmanagedCallersOnly] method: managed code cannot call
// it, so it has no test here.)
internal static class PluginFixTests
{
private const uint Player = 0x50000F21;
private const uint Wolf = 0x80400001, Dead = 0x80400002, Peas = 0x80400003, Wolf2 = 0x80400004;
private const uint Ghost = 0x80400005, Ghost2 = 0x80400006, Ghost3 = 0x80400007, Ghost4 = 0x80400008, CorpseX = 0x80400009;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
public static void Register(Runner r)
{
r.Add("selection: selecting a creature whose appraisal is cached sends no identify", CachedCreatureNoId);
r.Add("selection: selecting an uncached creature sends exactly one identify (and one health query)", UncachedCreatureOneId);
r.Add("selection: selecting a corpse or an item sends no identify and no health query", CorpseAndItemNothing);
r.Add("selection: the dashboard alone sends no health query", DashboardNoHealthQuery);
r.Add("selection: a monster cached as Unknown (type not read yet) still gets its identify and health query", UnknownMonsterStillAsked);
r.Add("selection: an Unknown that is typed as an item, or not attackable, gets nothing; a late creature flag does", UnknownNonCreatureNothing);
r.Add("selection: no cache entry - a corpse is rejected by name, a creature by its flag", NullCacheFallback);
r.Add("selection: creature classes are Monster, Player, Npc and CombatPet only", CreatureClasses);
r.Add("fellowship name read: ReadableBytesFrom ends at the page whose neighbour is PAGE_NOACCESS", ReadableBytesAtGuardPage);
r.Add("fellowship name read: it stops at 64 characters and at the end of the probed bytes", NameReadBounded);
}
// -- Selection ------------------------------------------------------------
private sealed class World
{
public readonly RynthAiPlugin P = new();
public readonly WorldObjectCache Cache;
public readonly RynthCoreHost Host;
public readonly LegacyDashboardRenderer Dash;
public World()
{
FakeHost.Reset();
FakeHost.WeaponCalls = true; // RequestId + HasAppraisalData
FakeHost.TargetCalls = true; // QueryHealth + GetLastIdTime
FakeHost.Names[Player] = "Reader";
FakeHost.PlayerIdValue = Player;
FakeHost.Positions[Player] = (0x1048002Au, 100f, 100f, 0f);
FakeHost.PlayerPose = (0x1048002Au, 100f, 100f, 0f);
Landscape(Wolf, "Grievver", 0x10);
Landscape(Wolf2, "Shadow", 0x10);
Landscape(Dead, "Corpse of Grievver", 0x10); // a corpse keeps the creature flag
FakeHost.Names[Peas] = "Pyreal Pea";
FakeHost.Containers[Peas] = Player;
FakeHost.ItemTypes[Peas] = 0x8;
Host = FakeHost.Create(playerId: Player);
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
Dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(Dash, new LegacyUiSettings());
typeof(LegacyDashboardRenderer).GetField("_host", Any)!.SetValue(Dash, Host);
Cache = new WorldObjectCache(Host);
Cache.SetPlayerId(Player);
Set("_dashboard", Dash);
Set("_objectCache", Cache);
Set("_playerId", Player);
Set("_initialized", true);
Set("_loginComplete", true);
Set("_lootInspectMode", false); // not under test: keeps the loot-rule check out of the way
foreach (uint id in new[] { Wolf, Wolf2, Dead, Peas }) Cache.OnCreateObject(id);
Cache.Tick();
}
private static void Landscape(uint id, string name, uint type)
{
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (0x1048002Au, 105f, 100f, 0f);
FakeHost.ItemTypes[id] = type;
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public void Select(uint id) => P.OnSelectedTargetChange(id, 0);
}
private static void CachedCreatureNoId()
{
var w = new World();
FakeHost.Appraised.Add(Wolf);
w.Select(Wolf);
Check.Eq(FakeHost.IdRequests.Count, 0, "appraisal cached: no identify");
Check.Eq(FakeHost.HealthQueries.Count, 1, "the creature's health is still asked once");
FakeHost.IdTimes[Wolf2] = 1234; // an engine that only reports GetLastIdTime
w.Select(Wolf2);
Check.Eq(FakeHost.IdRequests.Count, 0, "a reply on record (GetLastIdTime > 0) counts as cached");
}
private static void UncachedCreatureOneId()
{
var w = new World();
w.Select(Wolf);
Check.True(FakeHost.IdRequests.SequenceEqual(new[] { Wolf }), $"exactly one identify: [{string.Join(",", FakeHost.IdRequests.Select(i => i.ToString("X8")))}]");
Check.True(FakeHost.HealthQueries.SequenceEqual(new[] { Wolf }), "and one health query");
}
private static void CorpseAndItemNothing()
{
var w = new World();
SelfSelect.Mark(Peas); // the engine's own pick (the looter moving an item)
w.Select(Dead);
w.Select(Peas);
Check.Eq(FakeHost.IdRequests.Count, 0, "a corpse and an item: no identify");
Check.Eq(FakeHost.HealthQueries.Count, 0, "and no health query");
}
private static void DashboardNoHealthQuery()
{
var w = new World();
w.Dash.SetSelectedTarget(Wolf);
w.Dash.SetSelectedTarget(Dead);
w.Dash.SetSelectedTarget(Peas);
Check.Eq(FakeHost.HealthQueries.Count, 0, "the dashboard's own selection handler sends no health query");
Check.Eq(FakeHost.IdRequests.Count, 0, "nor an identify");
}
// -- Fellowship name read -------------------------------------------------
private static void NameReadBounded()
{
const int Size = 256;
IntPtr buf = Marshal.AllocHGlobal(Size);
try
{
for (int i = 0; i < Size; i++) Marshal.WriteByte(buf, i, i < 200 ? (byte)'A' : (byte)0); // 200 chars, then NULs
string capped = FellowshipTracker.ReadBoundedAnsi(buf, FellowshipTracker.MaxNameChars, 200);
Check.Eq(capped.Length, 64, "a long run is cut at 64 characters");
string atPageEnd = FellowshipTracker.ReadBoundedAnsi(buf, FellowshipTracker.MaxNameChars, 10);
Check.Eq(atPageEnd.Length, 10, "an unterminated run is cut where the probed bytes end");
Marshal.WriteByte(buf, 5, 0);
Check.Eq(FellowshipTracker.ReadBoundedAnsi(buf, FellowshipTracker.MaxNameChars, 200), "AAAAA", "a terminated name reads whole");
Check.Eq(FellowshipTracker.ReadBoundedAnsi(buf, FellowshipTracker.MaxNameChars, 0), "", "nothing readable: empty");
Check.Eq(FellowshipTracker.ReadBoundedAnsi(IntPtr.Zero, FellowshipTracker.MaxNameChars, 64), "", "null: empty");
}
finally { Marshal.FreeHGlobal(buf); }
}
private static void Land(uint id, string name)
{
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (0x1048002Au, 106f, 100f, 0f);
}
private static void UnknownMonsterStillAsked()
{
var w = new World();
Land(Ghost, "Drudge Skulker"); // no ItemTypes entry: the type is not readable yet
Check.True(w.Cache[unchecked((int)Ghost)]?.ObjectClass == AcObjectClass.Unknown, "set-up: cached as Unknown");
w.Select(Ghost);
Check.True(FakeHost.IdRequests.SequenceEqual(new[] { Ghost }), "identify sent for the Unknown");
Check.True(FakeHost.HealthQueries.SequenceEqual(new[] { Ghost }), "health asked for the Unknown");
}
private static void UnknownNonCreatureNothing()
{
var w = new World();
Land(Ghost2, "Marble Statue");
Land(Ghost3, "Mute Thing");
Land(Ghost4, "Late Wolf");
foreach (uint g in new[] { Ghost2, Ghost3, Ghost4 })
Check.True(w.Cache[unchecked((int)g)]?.ObjectClass == AcObjectClass.Unknown, $"set-up: {g:X8} cached as Unknown");
FakeHost.ItemTypes[Ghost2] = 0x8; // the type arrives: an item
FakeHost.NotAttackable.Add(Ghost2);
FakeHost.NotAttackable.Add(Ghost3); // never typed, but the engine says not attackable
FakeHost.ItemTypes[Ghost4] = 0x10; // the type arrives: a creature
w.Select(Ghost2);
w.Select(Ghost3);
Check.Eq(FakeHost.IdRequests.Count, 0, "typed item / not attackable: no identify");
Check.Eq(FakeHost.HealthQueries.Count, 0, "and no health query");
w.Select(Ghost4);
Check.True(FakeHost.IdRequests.SequenceEqual(new[] { Ghost4 }) && FakeHost.HealthQueries.SequenceEqual(new[] { Ghost4 }), "the late creature flag is honoured");
}
private static void NullCacheFallback()
{
var w = new World();
w.Set("_objectCache", null);
Land(CorpseX, "Corpse of Grievver");
FakeHost.ItemTypes[CorpseX] = 0x10; // a corpse keeps the creature flag
w.Select(CorpseX);
Check.Eq(FakeHost.IdRequests.Count + FakeHost.HealthQueries.Count, 0, "an uncached corpse is rejected by name");
w.Select(Wolf);
Check.True(FakeHost.IdRequests.SequenceEqual(new[] { Wolf }) && FakeHost.HealthQueries.SequenceEqual(new[] { Wolf }),
"positive control: an uncached creature (flag 0x10) is asked");
}
private static void CreatureClasses()
{
var m = typeof(RynthAiPlugin).GetMethod("IsCreatureClass", Any)!;
bool Is(AcObjectClass c) => (bool)m.Invoke(null, new object[] { c })!;
foreach (var c in new[] { AcObjectClass.Monster, AcObjectClass.Player, AcObjectClass.Npc, AcObjectClass.CombatPet })
Check.True(Is(c), $"{c} is a creature");
foreach (var c in new[] { AcObjectClass.Corpse, AcObjectClass.Unknown, AcObjectClass.Vendor, AcObjectClass.Door, AcObjectClass.Portal })
Check.False(Is(c), $"{c} is not");
}
// -- ReadableBytesFrom at a guard page ------------------------------------
[DllImport("kernel32.dll")] private static extern IntPtr VirtualAlloc(IntPtr addr, UIntPtr size, uint type, uint protect);
[DllImport("kernel32.dll")] private static extern bool VirtualProtect(IntPtr addr, UIntPtr size, uint protect, out uint old);
[DllImport("kernel32.dll")] private static extern bool VirtualFree(IntPtr addr, UIntPtr size, uint type);
private static void ReadableBytesAtGuardPage()
{
const uint CommitReserve = 0x3000, ReadWrite = 0x04, NoAccess = 0x01, Release = 0x8000;
IntPtr p = VirtualAlloc(IntPtr.Zero, (UIntPtr)8192u, CommitReserve, ReadWrite);
Check.True(p != IntPtr.Zero, "set-up: two pages allocated");
if (p == IntPtr.Zero) return;
try
{
Check.True(VirtualProtect(p + 4096, (UIntPtr)4096u, NoAccess, out _), "set-up: second page PAGE_NOACCESS");
for (int i = 0; i < 4096; i++) Marshal.WriteByte(p, i, (byte)'A'); // no NUL before the guard page
IntPtr s = p + 4090;
Check.Eq(FellowshipTracker.ReadableBytesFrom(s), 6, "six readable bytes left before the guard page");
Check.Eq(FellowshipTracker.ReadableBytesFrom(p + 4096), 0, "the guard page itself: none");
Check.Eq(FellowshipTracker.ReadBoundedAnsi(s, FellowshipTracker.MaxNameChars, FellowshipTracker.ReadableBytesFrom(s)), "AAAAAA",
"an unterminated name at the page end stops there, without touching the guard page");
}
finally { VirtualFree(p, UIntPtr.Zero, Release); }
}}

View file

@ -4,18 +4,21 @@ using System.IO;
using System.Reflection;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.ItemInfo;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Loading a profile (login, profile switch) runs LegacyDashboardRenderer.CopySettings, which
// copies the loaded file into the live settings one field at a time. A field with no copy line
// keeps its in-memory default, and the next autosave writes that default over the profile.
// PetAutoRefill, MonsterNameBlacklist and the radar placement were dropped that way.
// 2026-10-08: "Describe items when selected" and the Item Info options did not stay with the
// character's profile. They were written to the profile file, but LegacyDashboardRenderer.
// CopySettings (used by every login and profile switch) copies the loaded profile field by
// field and had no line for ItemInfoSettings, so the in-memory defaults stayed and the next
// autosave wrote them over the file. NavOverlay, PetAutoRefill, EnableGroundLoot,
// MonsterNameBlacklist, AmmoRules and the radar placement were dropped the same way.
// - every serialized LegacyUiSettings member set to a non-default value comes through
// CopySettings (catches any field added later without a copy line);
// - a profile written to disk and loaded back serializes unchanged.
// - the item info options survive a save / load through a profile file on disk.
internal static class ProfileLoadTests
{
private const BindingFlags Any = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
@ -23,7 +26,8 @@ internal static class ProfileLoadTests
public static void Register(Runner r)
{
r.Add("profile: every saved setting survives loading (CopySettings lists each serialized field)", EverySavedFieldIsCopied);
r.Add("profile: settings survive a save and a reload through the profile file", SettingsSurviveReload);
r.Add("profile: Describe Items and the Item Info options survive a save and a reload", ItemInfoSurvivesReload);
r.Add("profile: a profile with null item info / nav overlay loads defaults, not null", NullNestedOptionsLoadDefaults);
}
/// <summary>LegacyDashboardRenderer.CopySettings(src, dst): what LoadSettings / SwitchProfile run.</summary>
@ -36,17 +40,16 @@ internal static class ProfileLoadTests
mutated = null;
if (name == nameof(LegacyUiSettings.OffhandDefault)) { mutated = "Shield"; return true; } // must parse as an OffhandMode
if (name == nameof(LegacyUiSettings.NavLabelMode)) { mutated = 1; return true; } // NavLabelModes.Clamp: 0..2
Type t = Nullable.GetUnderlyingType(type) ?? type;
if (t == typeof(bool)) { mutated = !((bool?)value ?? false); return true; }
if (t == typeof(int)) { mutated = ((int?)value ?? 0) + 3; return true; } // +3: MovementMode 1/2 map back to 0
if (t == typeof(long)) { mutated = ((long?)value ?? 0) + 3; return true; }
if (t == typeof(uint)) { mutated = ((uint?)value ?? 0) + 3; return true; }
if (t == typeof(float)) { mutated = ((float?)value ?? 0f) + 3f; return true; }
if (t == typeof(double)) { mutated = ((double?)value ?? 0.0) + 3.0; return true; }
if (t == typeof(string)) { mutated = (string?)value + "x"; return true; }
if (t.IsEnum)
if (type == typeof(bool)) { mutated = !(bool)value!; return true; }
if (type == typeof(int)) { mutated = (int)value! + 3; return true; } // +3: MovementMode 1/2 map back to 0
if (type == typeof(long)) { mutated = (long)value! + 3; return true; }
if (type == typeof(uint)) { mutated = (uint)value! + 3; return true; }
if (type == typeof(float)) { mutated = (float)value! + 3f; return true; }
if (type == typeof(double)) { mutated = (double)value! + 3.0; return true; }
if (type == typeof(string)) { mutated = (string?)value + "x"; return true; }
if (type.IsEnum)
{
foreach (object v in Enum.GetValues(t))
foreach (object v in Enum.GetValues(type))
if (!v.Equals(value)) { mutated = v; return true; }
}
return false;
@ -101,14 +104,22 @@ internal static class ProfileLoadTests
Check.Eq(missing.Count, 0, "members CopySettings leaves at their default: " + string.Join(", ", missing));
}
private static void SettingsSurviveReload()
private static void ItemInfoSurvivesReload()
{
// What the Item Info window / the engine checkbox change, then autosave writes.
var saved = new LegacyUiSettings();
saved.ItemInfoOnSelect = !saved.ItemInfoOnSelect;
saved.PetAutoRefill = !saved.PetAutoRefill;
MagItemInfoSettings s = saved.ItemInfoSettings;
s.OnSelect = true;
s.ClickTrigger = MagItemInfoSettings.ClickRight;
s.OnSelectArmor = false;
s.SetHidden(MagItemInfoField.Spells, true);
s.SetRatingHidden(2, true);
s.Layout = MagItemInfoSettings.LayoutOneLine;
s.ChatType = 7;
s.Prefix = "[ii] ";
saved.EnableGroundLoot = true;
saved.PetAutoRefill = false;
saved.MonsterNameBlacklist.Add("Drudge Skulker");
saved.RadarPosX = 120f;
saved.RadarSizeY = 300f;
string path = Path.Combine(Program.TempRoot, "profile-load", "Default.json");
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
@ -119,15 +130,43 @@ internal static class ProfileLoadTests
var live = new LegacyUiSettings();
CopySettings(loaded, live);
Check.Eq(live.ItemInfoOnSelect, saved.ItemInfoOnSelect, "describe items when selected");
Check.Eq(live.PetAutoRefill, saved.PetAutoRefill, "pet auto refill");
MagItemInfoSettings l = live.ItemInfoSettings;
Check.True(l.OnSelect, "Describe items when selected stays on");
Check.Eq(l.ClickTrigger, MagItemInfoSettings.ClickRight, "click trigger");
Check.False(l.OnSelectArmor, "armor filter off");
Check.True(l.IsHidden(MagItemInfoField.Spells), "hidden field");
Check.True(l.IsRatingHidden(2), "hidden rating");
Check.Eq(l.Layout, MagItemInfoSettings.LayoutOneLine, "layout");
Check.Eq(l.ChatType, 7, "chat type");
Check.Eq(l.Prefix, "[ii] ", "prefix");
Check.True(live.EnableGroundLoot, "ground loot");
Check.False(live.PetAutoRefill, "pet auto refill");
Check.True(live.MonsterNameBlacklist.Contains("Drudge Skulker"), "monster blacklist");
Check.Eq(live.RadarPosX, 120f, "radar position");
Check.Eq(live.RadarSizeY, 300f, "radar size");
// Unchanged JSON means the autosave right after login has nothing to write over the file.
Check.Eq(JsonSerializer.Serialize(live, RynthAiJsonContext.Default.LegacyUiSettings),
JsonSerializer.Serialize(saved, RynthAiJsonContext.Default.LegacyUiSettings),
"the reloaded profile saves back unchanged (autosave writes nothing different)");
}
private static void NullNestedOptionsLoadDefaults()
{
string json = JsonSerializer.Serialize(new LegacyUiSettings(), RynthAiJsonContext.Default.LegacyUiSettings);
var doc = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!;
doc.ItemInfoSettings = null!;
doc.NavOverlay = null!;
var live = new LegacyUiSettings();
live.ItemInfoSettings.Prefix = new string('p', 40); // replaced by the loaded (default) object
CopySettings(doc, live);
Check.NotNull(live.ItemInfoSettings, "item info is never null after a load");
Check.NotNull(live.NavOverlay, "nav overlay is never null after a load");
Check.Eq(live.ItemInfoSettings.Prefix, new MagItemInfoSettings().Prefix, "item info falls back to defaults");
// An over-long hand-edited prefix is trimmed on load (Sanitize).
var edited = new LegacyUiSettings();
edited.ItemInfoSettings.Prefix = new string('p', 40);
var live2 = new LegacyUiSettings();
CopySettings(edited, live2);
Check.Eq(live2.ItemInfoSettings.Prefix.Length, 32, "prefix trimmed to 32");
}
}

View file

@ -0,0 +1,287 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Recovery retry: Stamina to Mana at about 10 mana took a long time to get off. ACE rolls Mana
// Conversion on every attempt (Creature_Magic.GetManaCost, at least 1 mana when trained) before the
// windup, and a refusal (UseDone 0x401) costs nothing. RynthAi parked the family 15 s after each
// refusal. Recovery vitals now retry every RecoveryRetryMs (200), at most 5 a second and 20 refusals
// in a row; everything else keeps the old rest.
internal static class RecoveryRetryTests
{
private const uint Player = 0x50000B21;
private const uint STypeLife = 33;
private const uint STypeManaConversion = 16;
private const uint NotEnoughMana = 0x401;
private const string RefusalLine = "You don't have enough Mana to cast this spell.";
public static void Register(Runner r)
{
r.Add("recovery retry: with spell costs unknown, Stamina to Mana goes out at 1 mana and a refusal is retried", PrecheckAllowsBelowBaseCost);
r.Add("recovery retry: with spell costs known, the mana reserve holds Stamina to Mana under its cost (no cast, no episode); Heal Self still retries", CostKnownHoldsStaminaToMana);
r.Add("recovery retry: a mana refusal is retried after 200 ms, past Spell Interval; the episode line counts the tries", RetryCadence);
r.Add("recovery retry: 20 refusals in a row end it (the vital's 2 s rest); stamina too low ends it; untrained Mana Conversion never starts it", RetryCap);
r.Add("recovery retry: at most 5 recovery casts in any second (Heal Self and Stamina to Mana alternating)", RateCeiling);
r.Add("recovery retry: an episode with no refusal for RecoveryEpisodeStaleMs (7 s) ends; it no longer lets casts past Spell Interval", StaleEpisodeEnds);
r.Add("recovery retry: RecoveryRetryMs at its 5000 ms maximum keeps its episode between retries", SlowRetryKeepsEpisode);
}
// With RecoveryRetryMs at the slider's 5000 ms maximum the retry (plus a little pacing) must not
// come after the stale limit, or the episode would end itself between retries.
private static void SlowRetryKeepsEpisode()
{
var r = new Rig(manaPct: 10);
r.S.RecoveryRetryMs = 5000;
r.S.SpellCastIntervalMs = 0;
r.At(0); r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "Stamina to Mana goes out");
r.Refuse();
r.At(5.05); r.B.OnHeartbeat(); // the retry, 50 ms late
Check.Eq(CastsOf("Stamina to Mana Self"), 2, "the retry at 5.05 s");
Check.True(r.B.RecoveryRetryOpen, "the episode is still open");
Check.False(r.Logged("stopped retrying"), "not ended between retries: " + r.B.LastRecoverySummary);
}
// The vital stops being needed (mana regenerated) and no refusal comes again: the open episode
// must end, or it would let every cast past Spell Interval for good.
private static void StaleEpisodeEnds()
{
var r = new Rig(manaPct: 10);
r.S.SpellCastIntervalMs = 60_000; // real clock: nothing else gets past it in this test
r.At(0); r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "Stamina to Mana goes out");
r.Refuse();
Check.True(r.B.RecoveryRetryOpen, "an episode opens");
r.V.CurrentMana = 100; // no longer needed
r.At(BuffManager.RecoveryEpisodeStaleMs / 1000.0 + 0.1); r.B.OnHeartbeat();
Check.False(r.B.RecoveryRetryOpen, "no refusal for RecoveryEpisodeStaleMs: the episode ends");
Check.True(r.B.LastRecoverySummary.Contains("no refusal for 7 s"), "summary: " + r.B.LastRecoverySummary);
r.V.CurrentHealth = 40; // a heal is needed now
int before = FakeHost.Casts.Count;
r.At(BuffManager.RecoveryEpisodeStaleMs / 1000.0 + 1); r.B.OnHeartbeat();
Check.Eq(FakeHost.Casts.Count, before, "the heal waits for Spell Interval (the ended episode lets nothing past)");
}
private sealed class Rig
{
public DateTime T0 = new(2026, 10, 10, 18, 0, 0);
public DateTime NowAt;
public readonly BuffManager B;
public readonly LegacyUiSettings S;
public readonly PlayerVitalsCache V;
public Rig(int healthPct = 100, int manaPct = 10, bool manaConversion = true)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
FakeHost.Skills[(Player, STypeManaConversion)] = manaConversion ? (300, 2) : (10, 1);
var host = FakeHost.Create();
S = new LegacyUiSettings
{
IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0,
GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false,
EnableBuffing = false,
};
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, S);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
V = new PlayerVitalsCache
{
MaxHealth = 100, CurrentHealth = (uint)healthPct, MaxStamina = 100, CurrentStamina = 100,
MaxMana = 100, CurrentMana = (uint)manaPct,
};
B = new BuffManager(host, S, sm, V);
B.SetCharacterSkills(skills);
NowAt = T0;
B.Clock = () => NowAt;
B.MarkLiveBuffsReadyForTests();
}
public void At(double seconds) => NowAt = T0.AddMilliseconds(Math.Round(seconds * 1000));
public bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
public int LogCount(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal));
public string LastCastName => SpellTable.ById(FakeHost.Casts.Last().SpellId)?.Name ?? "";
/// <summary>The server's answer to an unaffordable cast: UseDone 0x401, the client's chat line.</summary>
public void Refuse()
{
FakeHost.UseDone(NotEnoughMana);
B.OnChatWindowText(RefusalLine, 0);
}
}
private static int CastsOf(string baseName)
{
int cat = SpellTable.Named(baseName + " I").First().Category;
return FakeHost.Casts.Count(c => SpellTable.ById(c.SpellId)?.Category == cat);
}
private static void PrecheckAllowsBelowBaseCost()
{
// This rig leaves spell costs unknown (FakeHost.Reset: ManaCostOverride 0, as with no
// portal.dat), so the mana reserve's cost check in AttemptVitalCast has nothing to hold on.
var r = new Rig(manaPct: 1);
Check.True(r.B.CheckVitals(), "1 mana: the vitals step acts");
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "costs unknown: Stamina to Mana is sent at 1 mana (the server rolls the cost)");
// Refused at 1 mana: the retry is allowed (the least a trained cast can cost is 1 mana).
r.Refuse();
Check.True(r.B.RecoveryRetryOpen, "a retry episode is open at 1 mana");
Check.True(r.Logged("retrying in 200 ms"), "and the refusal line says so");
// At 0 mana no cast can be afforded: the old rest.
var z = new Rig(manaPct: 0);
z.B.CheckVitals();
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "0 mana: the first try still goes (as before)");
z.Refuse();
Check.False(z.B.RecoveryRetryOpen, "0 mana: no retry episode");
Check.True(z.Logged("resting the family 2s") && z.Logged("(no mana at all)"), "the vital's 2 s rest, and why");
}
private static void CostKnownHoldsStaminaToMana()
{
// Costs known (level x 10 here, as ManaReserveTests): at 5 mana even Stamina to Mana I (10)
// is unaffordable, so AttemptVitalCast's reserve check sends nothing and no episode opens.
try
{
var r = new Rig(manaPct: 5);
BuffManager.ManaCostOverride = id => (SpellTableStub.GetById(id)?.Level ?? 0) * 10;
r.At(0); r.B.CheckVitals();
r.At(0.2); r.B.CheckVitals();
Check.Eq(CastsOf("Stamina to Mana Self"), 0, "under its cost: Stamina to Mana is not cast");
Check.False(r.B.RecoveryRetryOpen, "and no retry episode opens");
// Heal Self is tried below its cost (60 here) and a refusal is still retried.
var h = new Rig(healthPct: 40, manaPct: 5);
BuffManager.ManaCostOverride = id => (SpellTableStub.GetById(id)?.Level ?? 0) * 10;
h.At(0); h.B.CheckVitals();
Check.Eq(CastsOf("Heal Self"), 1, "Heal Self goes out under its cost");
h.Refuse();
Check.True(h.B.RecoveryRetryOpen, "refused for mana: a retry episode");
h.At(0.2); h.B.CheckVitals();
Check.Eq(CastsOf("Heal Self"), 2, "retried after 200 ms");
Check.Eq(CastsOf("Stamina to Mana Self"), 0, "Stamina to Mana still held under its cost");
}
finally { BuffManager.ManaCostOverride = _ => 0; }
}
private static void RetryCadence()
{
var r = new Rig(manaPct: 10);
r.At(0); r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "Stamina to Mana goes out");
r.Refuse();
Check.False(r.Logged("resting the family"), "no family rest");
r.At(0.1); r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "100 ms after the refusal: still waiting");
r.At(0.2); r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self"), 2, "200 ms: tried again (Spell Interval 400 on the real clock does not hold it)");
r.Refuse();
r.At(0.3); r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self"), 2, "300 ms: waiting");
r.At(0.4); r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self"), 3, "400 ms: the third try");
// A good roll: the result line ends the episode with its summary.
r.At(0.55);
r.B.OnChatWindowText($"You cast {r.LastCastName} on yourself and lose 35 points of stamina and also gain 47 points of mana", 0);
Check.False(r.B.RecoveryRetryOpen, "the result closes the episode");
Check.True(r.B.LastRecoverySummary.Contains("went through after 3 attempts (2 refused for mana") && r.B.LastRecoverySummary.Contains("in 550 ms"),
$"summary: {r.B.LastRecoverySummary}");
// The retry gap is a setting.
var s = new Rig(manaPct: 10);
s.S.RecoveryRetryMs = 1000;
s.At(0); s.B.CheckVitals(); s.Refuse();
s.At(0.9); s.B.CheckVitals();
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "RecoveryRetryMs 1000: nothing at 900 ms");
s.At(1.0); s.B.CheckVitals();
Check.Eq(CastsOf("Stamina to Mana Self"), 2, "RecoveryRetryMs 1000: the retry at 1 s");
// ...clamped to 200 at the bottom.
var c = new Rig(manaPct: 10);
c.S.RecoveryRetryMs = 50;
c.At(0); c.B.CheckVitals(); c.Refuse();
c.At(0.1); c.B.CheckVitals();
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "RecoveryRetryMs 50 is clamped: nothing at 100 ms");
c.At(0.2); c.B.CheckVitals();
Check.Eq(CastsOf("Stamina to Mana Self"), 2, "...the retry at 200 ms");
}
private static void RetryCap()
{
var r = new Rig(manaPct: 10);
for (int i = 0; i < 25; i++)
{
r.At(i * 0.2);
int before = FakeHost.Casts.Count;
r.B.CheckVitals();
if (FakeHost.Casts.Count == before) break;
r.Refuse();
}
Check.Eq(CastsOf("Stamina to Mana Self"), 20, "20 tries, then it stops");
Check.True(r.B.LastRecoverySummary.Contains("after 20 mana refusals") && r.B.LastRecoverySummary.Contains("(20 refusals in a row)"),
$"summary: {r.B.LastRecoverySummary}");
Check.Eq(r.LogCount("resting the family 2s"), 1, "the 20th refusal rests the family 2 s, as before");
r.At(4.2); r.B.CheckVitals();
Check.Eq(CastsOf("Stamina to Mana Self"), 20, "no try inside the rest");
// Stamina too low to convert when the refusal comes: the old rest.
var st = new Rig(manaPct: 10);
st.V.CurrentStamina = 20;
st.B.CheckVitals();
st.V.CurrentStamina = 10;
st.Refuse();
Check.False(st.B.RecoveryRetryOpen, "stamina 10%: no retry");
Check.True(st.B.LastRecoverySummary.Contains("stamina 10% too low to convert") && st.Logged("resting the family 2s"),
$"summary: {st.B.LastRecoverySummary}");
// Mana Conversion untrained: the cost is never rolled, so no retry (the vital's 2 s rest).
var u = new Rig(manaPct: 10, manaConversion: false);
u.B.CheckVitals();
u.Refuse();
Check.False(u.B.RecoveryRetryOpen, "untrained: no retry");
Check.True(u.Logged("resting the family 2s") && u.B.LastRecoverySummary.Contains("Mana Conversion not trained"), "the old rest, and why");
}
private static void RateCeiling()
{
// 40% health and 2% mana: Heal Self and Stamina to Mana each retry every 200 ms, which would
// be 10 casts a second. Two vitals checks per 100 ms, every cast refused.
var r = new Rig(healthPct: 40, manaPct: 2);
var sentAt = new List<double>();
for (int step = 0; step < 30; step++)
{
double t = step * 0.1;
r.At(t);
for (int k = 0; k < 2; k++)
{
int before = FakeHost.Casts.Count;
r.B.CheckVitals();
if (FakeHost.Casts.Count == before) continue;
sentAt.Add(t);
r.Refuse();
}
}
Check.True(CastsOf("Heal Self") > 0 && CastsOf("Stamina to Mana Self") > 0, "both spells were tried");
int worst = 0;
foreach (double a in sentAt)
worst = Math.Max(worst, sentAt.Count(b => b >= a && b < a + 1.0 - 1e-9));
Check.True(worst <= BuffManager.RecoveryRetryMaxPerSecond, $"at most 5 in any second (worst {worst}, sent at {string.Join(",", sentAt.Select(x => x.ToString("0.0")))})");
Check.True(worst == BuffManager.RecoveryRetryMaxPerSecond, $"and the ceiling is reached, so it is what held them (worst {worst})");
Check.True(r.B.RecoveryRateHolds > 0, "the ceiling held some");
}
}

View file

@ -0,0 +1,337 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using RynthCore.Loot.Editing;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.Diagnostics;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-10-13: players reported metas and navs "not saving" and the plugin folders being
// "read only". Every save of a meta, nav, settings profile (and the loot editor's autosave
// path) swallowed its exception, so a folder the client can't write looked like a save that did
// nothing. Diagnostics/DataWriteGuard.cs now:
// - clears the ReadOnly attribute on our own file before overwriting it;
// - reports a failed save in chat once per folder (path, reason, fix) and logs every one
// (throttled per folder);
// - runs a startup self-check of the data folders.
// Only scratch files are written; nothing here changes permissions (a file held open with
// FileShare.None stands in for "Windows refused the write").
internal static class SaveFailureTests
{
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("save failure: exceptions are classified (access denied, read-only, in use, disk full, cloud, missing)", Classify);
r.Add("save failure: reported in chat once per folder, with the path, the reason and the fix", OncePerFolder);
r.Add("save failure: a folder inside a reported one isn't announced again", SubfolderQuiet);
r.Add("save failure: the log is throttled per folder and counts what it skipped", LogThrottled);
r.Add("save failure: an explicit save shows it itself (nothing queued, reason has the fix)", CallerShows);
r.Add("save failure: a file open in another program is reported as in use (real file)", RealFileInUse);
r.Add("save failure: a read-only .af meta is overwritten (attribute cleared)", ReadOnlyMetaSaved);
r.Add("save failure: a read-only .nav is overwritten (attribute cleared)", ReadOnlyNavSaved);
r.Add("save failure: a read-only settings profile is autosaved (attribute cleared)", ReadOnlySettingsSaved);
r.Add("save failure: a settings autosave that fails is reported and retried later, not every tick", SettingsFailureReported);
r.Add("save failure: /ra nav save to a file in use says NOT saved and why", NavSaveRouteReports);
r.Add("save failure: a read-only loot profile is saved; a failed loot write hands over its exception", LootSession);
r.Add("save failure: startup self-check passes writable folders and flags an unusable one", SelfCheck);
r.Add("save failure: the data folders checked are under the resolved RynthAi folder", DataFoldersResolved);
}
private static string NewDir(string name)
{
string dir = Path.Combine(Program.TempRoot, "save-failure", name);
if (Directory.Exists(dir)) { ClearAttributes(dir); Directory.Delete(dir, recursive: true); }
Directory.CreateDirectory(dir);
return dir;
}
private static void ClearAttributes(string dir)
{
foreach (string f in Directory.GetFiles(dir, "*", SearchOption.AllDirectories))
File.SetAttributes(f, FileAttributes.Normal);
}
private static List<string> Fresh()
{
DataWriteGuard.Reset();
DataWriteGuard.Clock = () => Environment.TickCount64;
var log = new List<string>();
DataWriteGuard.LogSink = log.Add;
return log;
}
private static List<string> Chat()
{
var lines = new List<string>();
DataWriteGuard.DrainChat(lines.Add);
return lines;
}
private static IOException Io(int hr) => new IOException("io", hr);
private static void Classify()
{
string dir = NewDir("classify");
string ro = Path.Combine(dir, "ro.af");
File.WriteAllText(ro, "x");
File.SetAttributes(ro, FileAttributes.ReadOnly);
try
{
Check.Eq(DataWriteGuard.Classify(new UnauthorizedAccessException(), ro), WriteFailureKind.ReadOnlyFile, "denied on a read-only file");
Check.Eq(DataWriteGuard.Classify(new UnauthorizedAccessException(), Path.Combine(dir, "new.af")), WriteFailureKind.AccessDenied, "denied, no such file");
Check.Eq(DataWriteGuard.Classify(new UnauthorizedAccessException(), null), WriteFailureKind.AccessDenied, "denied, no path");
}
finally { File.SetAttributes(ro, FileAttributes.Normal); }
Check.Eq(DataWriteGuard.Classify(Io(unchecked((int)0x80070020)), null), WriteFailureKind.InUse, "sharing violation");
Check.Eq(DataWriteGuard.Classify(Io(unchecked((int)0x80070021)), null), WriteFailureKind.InUse, "lock violation");
Check.Eq(DataWriteGuard.Classify(Io(unchecked((int)0x80070070)), null), WriteFailureKind.DiskFull, "disk full");
Check.Eq(DataWriteGuard.Classify(Io(unchecked((int)0x8007016A)), null), WriteFailureKind.CloudProvider, "OneDrive not running");
Check.Eq(DataWriteGuard.Classify(Io(unchecked((int)0x80070005)), null), WriteFailureKind.AccessDenied, "E_ACCESSDENIED as IOException");
Check.Eq(DataWriteGuard.Classify(new DirectoryNotFoundException(), null), WriteFailureKind.PathMissing, "missing folder");
Check.Eq(DataWriteGuard.Classify(new InvalidOperationException("boom"), null), WriteFailureKind.Other, "anything else");
Check.True(DataWriteGuard.Describe(WriteFailureKind.AccessDenied, null).Contains("Controlled folder access"), "access denied names Controlled folder access");
Check.True(DataWriteGuard.Describe(WriteFailureKind.Other, new Exception("the text")) == "the text", "other: the exception's message");
}
private static void OncePerFolder()
{
var log = Fresh();
string a = @"C:\Nowhere\RynthAi\MetaFiles\one.af";
string b = @"C:\Nowhere\RynthAi\MetaFiles\two.af";
string c = @"C:\Nowhere\RynthAi\NavProfiles\route.nav";
Action denied = () => throw new UnauthorizedAccessException("Access to the path is denied.");
Check.False(DataWriteGuard.TrySave("the meta", a, denied), "first save fails");
Check.False(DataWriteGuard.TrySave("the meta", b, denied), "second save, same folder, fails");
var lines = Chat();
Check.Eq(lines.Count, 1, "one chat line for the folder");
Check.True(lines[0].Contains(a), "names the file: " + lines[0]);
Check.True(lines[0].Contains("the meta"), "says what wasn't saved");
Check.True(lines[0].Contains("access denied"), "says why");
Check.True(lines[0].Contains("Fix folder permissions"), "points at the launcher's repair");
Check.False(DataWriteGuard.TrySave("the nav", c, denied), "nav folder fails");
lines = Chat();
Check.Eq(lines.Count, 1, "another folder gets its own line");
Check.True(lines[0].Contains("the nav") && lines[0].Contains(c), "the nav line: " + (lines.Count > 0 ? lines[0] : ""));
Check.Eq(DataWriteGuard.PendingCount, 0, "drained");
Check.True(log.Count >= 2, "every folder logged");
}
private static void SubfolderQuiet()
{
Fresh();
Action denied = () => throw new UnauthorizedAccessException();
DataWriteGuard.TrySave("the settings profile", @"C:\Nowhere\RynthAi\SettingsProfiles\x.json", denied);
DataWriteGuard.TrySave("the settings profile", @"C:\Nowhere\RynthAi\SettingsProfiles\Server\Toon\Default.json", denied);
DataWriteGuard.TrySave("the settings profile", @"C:\Nowhere\RynthAi\SettingsProfilesOther\a.json", denied);
Check.Eq(Chat().Count, 2, "the character folder is inside SettingsProfiles; a look-alike sibling is not");
}
private static void LogThrottled()
{
var log = Fresh();
long now = 1_000_000;
DataWriteGuard.Clock = () => now;
Action denied = () => throw new UnauthorizedAccessException();
string p = @"C:\Nowhere\RynthAi\MetaFiles\a.af";
DataWriteGuard.TrySave("the meta", p, denied);
now += 1000;
DataWriteGuard.TrySave("the meta", p, denied);
DataWriteGuard.TrySave("the meta", p, denied);
Check.Eq(log.Count, 1, "one log line within the minute");
now += DataWriteGuard.LogThrottleMs;
DataWriteGuard.TrySave("the meta", p, denied);
Check.Eq(log.Count, 2, "a minute later it logs again");
Check.True(log[1].Contains("2 more failure(s)"), "and counts the skipped ones: " + log[1]);
DataWriteGuard.Clock = () => Environment.TickCount64;
}
private static void CallerShows()
{
Fresh();
bool ok = DataWriteGuard.TrySave("the nav", @"C:\Nowhere\RynthAi\NavProfiles\a.nav",
() => throw new UnauthorizedAccessException(), out string why, callerShows: true);
Check.False(ok, "fails");
Check.Eq(DataWriteGuard.PendingCount, 0, "nothing queued: the caller shows it");
Check.True(why.Contains("access denied") && why.Contains("Fix folder permissions"), "reason and fix: " + why);
DataWriteGuard.TrySave("the nav", @"C:\Nowhere\RynthAi\NavProfiles\b.nav", () => throw new UnauthorizedAccessException());
Check.Eq(DataWriteGuard.PendingCount, 0, "the folder already counts as reported");
}
private static void RealFileInUse()
{
Fresh();
string dir = NewDir("inuse");
string path = Path.Combine(dir, "farm.af");
File.WriteAllText(path, "old");
using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
bool ok = DataWriteGuard.TrySave("the meta", path, () => File.WriteAllText(path, "new"), out string why);
Check.False(ok, "write refused while another handle holds it");
Check.True(why.Contains("open in another program"), "in use: " + why);
}
var lines = Chat();
Check.Eq(lines.Count, 1, "one chat line");
Check.True(lines.Count == 1 && lines[0].Contains("Close the program"), "with the in-use hint");
Check.Eq(File.ReadAllText(path), "old", "file untouched");
}
private static void ReadOnlyMetaSaved()
{
Fresh();
string dir = NewDir("ro-meta");
string path = Path.Combine(dir, "farm.af");
File.WriteAllText(path, "old");
File.SetAttributes(path, FileAttributes.ReadOnly);
var rules = new List<MetaRule> { new MetaRule { State = "Default" } };
bool ok = DataWriteGuard.TrySave("the meta", path, () => AfFileWriter.Save(path, rules, new Dictionary<string, List<string>>()));
Check.True(ok, "saved");
Check.True(File.ReadAllText(path).Contains("STATE:"), "new content written");
Check.Eq(File.GetAttributes(path) & FileAttributes.ReadOnly, (FileAttributes)0, "read-only cleared");
Check.Eq(DataWriteGuard.PendingCount, 0, "nothing to report");
}
private static void ReadOnlyNavSaved()
{
string dir = NewDir("ro-nav");
string path = Path.Combine(dir, "route.nav");
File.WriteAllText(path, "old");
File.SetAttributes(path, FileAttributes.ReadOnly);
var route = new NavRouteParser();
route.Points.Add(new NavPoint());
route.Save(path); // NavRouteParser clears it itself (it is linked into tools without the guard)
Check.False(File.ReadAllText(path) == "old", "new content written");
Check.Eq(File.GetAttributes(path) & FileAttributes.ReadOnly, (FileAttributes)0, "read-only cleared");
}
private static LegacyDashboardRenderer DashboardSavingTo(string path)
{
FakeHost.Reset();
var dash = new LegacyDashboardRenderer(FakeHost.Create());
typeof(LegacyDashboardRenderer).GetField("_settingsFilePath", Any)!.SetValue(dash, path);
return dash;
}
private static void ReadOnlySettingsSaved()
{
Fresh();
string dir = NewDir("ro-settings");
string path = Path.Combine(dir, "Default.json");
File.WriteAllText(path, "{}");
File.SetAttributes(path, FileAttributes.ReadOnly);
var dash = DashboardSavingTo(path);
dash.TickAutoSave();
Check.True(File.ReadAllText(path).Length > 2, "settings written");
Check.Eq(File.GetAttributes(path) & FileAttributes.ReadOnly, (FileAttributes)0, "read-only cleared");
Check.Eq(DataWriteGuard.PendingCount, 0, "nothing to report");
}
private static void SettingsFailureReported()
{
var log = Fresh();
string dir = NewDir("settings-fail");
string path = Path.Combine(dir, "Default.json");
File.WriteAllText(path, "{}");
var dash = DashboardSavingTo(path);
using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
dash.TickAutoSave();
int logged = log.Count;
dash.TickAutoSave(); // within the retry window: no second attempt
Check.Eq(log.Count, logged, "no retry on the next tick");
Check.True(log.Count == 1 && log[0].Contains(path), "logged with the path");
}
var lines = Chat();
Check.Eq(lines.Count, 1, "one chat line");
Check.True(lines.Count == 1 && lines[0].Contains("the settings profile") && lines[0].Contains(path), "names it: " + (lines.Count > 0 ? lines[0] : ""));
Check.Eq(File.ReadAllText(path), "{}", "nothing written while held");
// After the retry window it saves.
typeof(LegacyDashboardRenderer).GetField("_autosaveRetryAt", Any)!.SetValue(dash, 0L);
dash.TickAutoSave();
Check.True(File.ReadAllText(path).Length > 2, "saved once the file is free");
}
private static void NavSaveRouteReports()
{
Fresh();
string dir = NewDir("nav-saveroute");
string path = Path.Combine(dir, "Route.nav");
File.WriteAllText(path, "old");
var settings = new LegacyUiSettings { CurrentNavPath = path };
settings.CurrentRoute.Points.Add(new NavPoint());
var ui = new LegacyNavigationUi(settings, FakeHost.Create());
string msg;
using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
msg = ui.SaveRoute();
Check.True(msg.Contains("NOT saved") && msg.Contains(path) && msg.Contains("open in another program"), "says so: " + msg);
Check.Eq(DataWriteGuard.PendingCount, 0, "the command's reply is the report");
msg = ui.SaveRoute();
Check.True(msg.Contains("Saved 1 waypoints"), "saves once free: " + msg);
}
private static void LootSession()
{
string dir = NewDir("loot");
string path = Path.Combine(dir, "profile.utl");
File.Copy(Path.Combine(AppContext.BaseDirectory, "Fixtures", "salvage-combine.utl"), path);
File.SetAttributes(path, FileAttributes.ReadOnly);
var s = new LootEditSession();
Check.True(s.Open(path), "opens: " + s.Message);
Check.True(s.Save(force: true), "saves a read-only profile: " + s.Message);
Check.Eq(File.GetAttributes(path) & FileAttributes.ReadOnly, (FileAttributes)0, "read-only cleared");
Check.Null(s.TakeWriteError(), "no write error");
using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
Check.False(s.Save(force: true), "a held file fails");
Exception? err = s.TakeWriteError();
Check.NotNull(err, "the write's exception is handed over");
Check.Null(s.TakeWriteError(), "once");
if (err != null)
Check.Eq(DataWriteGuard.Classify(err, path), WriteFailureKind.InUse, "classified as in use");
foreach (string f in Directory.GetFiles(dir)) File.SetAttributes(f, FileAttributes.Normal);
}
private static void SelfCheck()
{
var log = Fresh();
string dir = NewDir("selfcheck");
string ok1 = Path.Combine(dir, "MetaFiles");
string ok2 = Path.Combine(dir, "NavProfiles"); // created by the check
string blocker = Path.Combine(dir, "blocker");
File.WriteAllText(blocker, "a file where a folder should be");
string bad = Path.Combine(blocker, "LootProfiles");
Directory.CreateDirectory(ok1);
var problems = DataWriteGuard.CheckFolders(new[] { ok1, ok2, bad });
Check.Eq(problems.Count, 1, "one problem");
Check.True(problems.Count == 1 && problems[0].Folder == bad, "the unusable folder");
Check.True(Directory.Exists(ok2), "missing folder created");
Check.Eq(Directory.GetFiles(ok1).Length + Directory.GetFiles(ok2).Length, 0, "no probe files left behind");
var lines = Chat();
Check.Eq(lines.Count, 1, "one chat line");
Check.True(lines.Count == 1 && lines[0].Contains(bad) && lines[0].Contains("will NOT be kept"), "says what it means: " + (lines.Count > 0 ? lines[0] : ""));
Check.True(log.Count == 1 && log[0].Contains(bad), "logged");
DataWriteGuard.TrySave("the loot profile", Path.Combine(bad, "x.utl"), () => throw new UnauthorizedAccessException());
Check.Eq(DataWriteGuard.PendingCount, 0, "a later save there isn't announced twice");
}
private static void DataFoldersResolved()
{
string root = RynthCore.Install.RynthInstallPaths.RynthAiDir;
var folders = new List<string>(RynthAiPlugin.DataFolders());
Check.Eq(folders.Count, 5, "root + MetaFiles, NavProfiles, LootProfiles, SettingsProfiles");
foreach (string f in folders)
Check.True(f.StartsWith(root, StringComparison.OrdinalIgnoreCase), f + " is under " + root);
Check.Eq(LegacyNavigationUi.NavFolder, Path.Combine(root, "NavProfiles"), "/ra nav save uses the resolved folder");
}
}

View file

@ -0,0 +1,78 @@
using RynthCore.Plugin.RynthAi.Huds;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Mini Remote right-click menu (2026-10-11): RynthCore pushes its server sections (which server
// the client is on, and the installed server plugins' windows for it) as a tab-separated
// "servermenu" payload; RynthAi parses it for the menu's bottom half.
internal static class ServerMenuTests
{
public static void Register(Runner r)
{
r.Add("server menu: sections and items parse in order", ParsesSections);
r.Add("server menu: malformed lines are skipped, never thrown", SkipsMalformed);
r.Add("server menu: tab features name the Mini Remote tab", TabFeature);
r.Add("mini remote tabs: Quests and Pets are universal and first; Guardian is ILT's panel", UniversalTabs);
}
private static void UniversalTabs()
{
var tabs = RynthCore.Plugin.RynthAi.IltHub.IltSections.Tabs;
Check.Eq(tabs[0], RynthCore.Plugin.RynthAi.IltHub.IltSection.Quests, "Quests leads the tab bar");
Check.Eq(tabs[1], RynthCore.Plugin.RynthAi.IltHub.IltSection.Pet, "Pets second");
int universal = 0;
foreach (var t in tabs)
if (RynthCore.Plugin.RynthAi.IltHub.IltSections.IsUniversal(t)) universal++;
Check.Eq(universal, 2, "only Quests and Pets are universal");
Check.True(!RynthCore.Plugin.RynthAi.IltHub.IltSections.IsUniversal(RynthCore.Plugin.RynthAi.IltHub.IltSection.Guardian), "Guardian is ILT only");
Check.True(!RynthCore.Plugin.RynthAi.IltHub.IltSections.IsTab(RynthCore.Plugin.RynthAi.IltHub.IltSection.Guardian), "Guardian is a panel, not a tab");
Check.True(!RynthCore.Plugin.RynthAi.IltHub.IltSections.IsUniversal(RynthCore.Plugin.RynthAi.IltHub.IltSection.Character), "the Character tab is ILT's");
}
private static void ParsesSections()
{
const string payload =
"S\tilt\tInfinite Leaftide\t1\t/rc ilt on\n" +
"I\tQuests\t/rc miniremote tab quests\tThe Quests tab.\ttab:quests\n" +
"I\tBounties\t/rc bounties toggle\tBounties.\t\n" +
"S\tother\tOther World\t0\t\n" +
"I\tThing\t/rc thing\t\t\n";
var groups = ServerMenuModel.Parse(payload);
Check.Eq(groups.Length, 2, "two sections");
Check.Eq(groups[0].Id, "ilt", "first section id");
Check.Eq(groups[0].Name, "Infinite Leaftide", "first section name");
Check.True(groups[0].Active, "first section is active");
Check.Eq(groups[0].ForceCommand, "/rc ilt on", "force command");
Check.Eq(groups[0].Items.Length, 2, "first section has its two items");
Check.Eq(groups[0].Items[1].Command, "/rc bounties toggle", "item command");
Check.Eq(groups[0].Items[1].Feature, "", "empty feature stays empty");
Check.True(!groups[1].Active, "second section is not active");
Check.Eq(groups[1].Items.Length, 1, "items attach to the section above them");
}
private static void SkipsMalformed()
{
Check.Eq(ServerMenuModel.Parse(null).Length, 0, "null payload = no sections");
Check.Eq(ServerMenuModel.Parse("").Length, 0, "empty payload = no sections");
const string payload =
"I\tOrphan\t/rc x\t\t\n" + // before any section
"S\tshort\n" + // too few fields
"S\tilt\tInfinite Leaftide\t0\t\r\n" + // CRLF tolerated
"X\tunknown\tkind\t\t\n" +
"I\t\t/rc nolabel\t\t\n" + // no label
"I\tGuardian\t/rc guardian toggle\t\t\n";
var groups = ServerMenuModel.Parse(payload);
Check.Eq(groups.Length, 1, "only the well-formed section");
Check.Eq(groups[0].Items.Length, 1, "only the labelled item under it");
Check.Eq(groups[0].Items[0].Label, "Guardian", "the kept item");
}
private static void TabFeature()
{
Check.Eq(ServerMenuModel.TabOf("tab:quests"), "quests", "tab id");
Check.True(ServerMenuModel.TabOf("tab:") == null, "no id = not a tab");
Check.True(ServerMenuModel.TabOf("") == null, "no feature = not a tab");
Check.True(ServerMenuModel.TabOf("panel:x") == null, "other features are not tabs");
}
}

View file

@ -0,0 +1,83 @@
using RynthCore.Plugin.RynthAi.IltHub;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Enlightenment 301-325 sigil craft chain (2026-10-07). Each target level T costs T - 5 sigils and
// T x 2B luminance (ACECustom tier 5). Sigil = Lifeblood Elixir + Ascension Coin; Ascension Coin =
// E-coin + Ancient Yalani Trinket; Elixir = Lifebloom Resin + Necrolytic Extract; Resin = Life
// Splitter + Plant. Stock is used from the top of the chain down.
internal static class SigilChainTests
{
public static void Register(Runner r)
{
r.Add("sigil chain: 301-325 tier rates and sigil counts", TierRates);
r.Add("sigil chain: shortfall uses stock top-down", ShortfallTopDown);
r.Add("sigil chain: fulfillable count and shared e-coin pool", FulfillableAndCoins);
r.Add("sigil chain: item names (plural stacks, Plant exact)", Names);
}
private static void TierRates()
{
var t301 = IltProgression.EnlStepCost(301);
Check.Eq(t301.Item, "Enlightenment Sigils", "301 takes sigils");
Check.Eq(t301.Count, 296, "301 takes T - 5 sigils");
Check.Eq(t301.Lum, 301 * 2_000_000_000m, "301 costs T x 2B luminance (no step multiplier yet)");
Check.Eq(IltProgression.EnlStepCost(325).Lum, 325 * 2_000_000_000m, "325 still has no step multiplier");
Check.Eq(IltProgression.EnlStepCost(326).Item, "Enlightenment Crests", "326 moves to crests");
Check.Eq(IltSigilChain.SigilsForRange(300, 302), 296L + 297L, "range 300 -> 302 sums both levels");
Check.Eq(IltSigilChain.SigilsForRange(324, 330), 320L, "range clamps at 325");
Check.Eq(IltSigilChain.SigilsForRange(200, 300), 0L, "no sigils below 301");
}
private static void ShortfallTopDown()
{
var empty = IltSigilChain.Shortfall(10, new IltSigilStock());
Check.Eq(empty.CoinsShort, 10L, "empty pack: one e-coin per sigil");
Check.Eq(empty.PlantsShort, 10L, "empty pack: one plant per sigil");
Check.True(!empty.Covered, "empty pack is not covered");
var stock = new IltSigilStock
{
Sigils = 2, AscensionCoins = 3, LifebloodElixirs = 1, LifebloomResins = 4,
EnlightenedCoins = 100, YalaniTrinkets = 1, NecrolyticExtracts = 2, LifeSplitters = 0, Plants = 5,
};
var s = IltSigilChain.Shortfall(10, stock);
Check.Eq(s.SigilsToCraft, 8L, "2 finished sigils used first");
Check.Eq(s.AscensionToCraft, 5L, "3 Ascension Coins on hand");
Check.Eq(s.ElixirsToCraft, 7L, "1 Elixir on hand");
Check.Eq(s.CoinsShort, 0L, "100 e-coins cover 5 crafts");
Check.Eq(s.TrinketsShort, 4L, "1 trinket on hand");
Check.Eq(s.ExtractsShort, 5L, "2 extracts on hand");
Check.Eq(s.ResinsToCraft, 3L, "4 resins on hand");
Check.Eq(s.SplittersShort, 3L, "no splitters");
Check.Eq(s.PlantsShort, 0L, "5 plants cover 3 resins");
Check.True(IltSigilChain.Shortfall(5, new IltSigilStock { Sigils = 9 }).Covered, "finished sigils cover the demand");
}
private static void FulfillableAndCoins()
{
var stock = new IltSigilStock
{
Sigils = 1, AscensionCoins = 1, EnlightenedCoins = 10, YalaniTrinkets = 2,
LifebloomResins = 1, LifeSplitters = 10, Plants = 10, NecrolyticExtracts = 4,
};
Check.Eq(IltSigilChain.Fulfillable(stock), 4L, "1 finished + min(3 coins, 4 elixirs)");
IltSigilChain.EcoinDemand(50, 30, 2, 20, out long fromCoins, out long still, out long need);
Check.Eq(fromCoins, 1L, "20 coins left after Ascension crafts make 1 token");
Check.Eq(still, 1L, "one token still short");
Check.Eq(need, 20L, "one more token's worth of coins");
IltSigilChain.EcoinDemand(10, 25, 0, 20, out _, out _, out need);
Check.Eq(need, 15L, "Ascension crafts alone exceed the pool");
}
private static void Names()
{
Check.True(IltSigilChain.NameIs("Ascension Coins", IltSigilChain.AscensionCoin), "plural stack name");
Check.True(IltSigilChain.NameIs(" plant ", IltSigilChain.Plant), "case and spaces ignored");
Check.True(!IltSigilChain.NameIs("Plant Fiber", IltSigilChain.Plant), "Plant must be the whole name");
Check.True(!IltSigilChain.NameIs("Lifebloom Resin", IltSigilChain.LifebloodElixir), "Lifebloom is not Lifeblood");
}
}

View file

@ -0,0 +1,273 @@
using System;
using System.IO;
using System.Linq;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The Spells window's data and buff profiles: ACECustom's spell catalog (Combat\SpellCatalog.tsv),
// the buffing key a catalog spell maps to, profile files, and how buffing uses a chosen profile
// (its list replaces the built-in one; names without a tier ladder fall back to the spell family).
// Spell ids and levels below are read from the generated catalog.
internal static class SpellCatalogTests
{
private const uint Player = 0x50000B01;
private const uint STypeCreature = 31;
// Catalog ids (ACECustom SpellCatalog-Full.csv).
private const int StrengthSelfI = 2, StrengthSelfIII = 1329, StrengthSelfVI = 1332, StrengthOtherVI = 1337;
private const int MightOfTheLugians = 2087, BladeBaneVI = 1562, IncantationOfBladeBane = 4393;
private const int AuraOfBloodDrinkerSelfIII = 1613, ImpenetrabilityIncantation = 3980;
private const int StrengthFamily = 1;
public static void Register(Runner r)
{
r.Add("spell catalog: every ACECustom spell with school, level and target", CatalogLoads);
r.Add("spell catalog: tier names strip to buffing's base names", StripTier);
r.Add("spell catalog: Other, lore and item spells map to the ladder buffing casts", BuffKeys);
r.Add("spell catalog: Item Enchantment buffs count as item spells", ItemSchool);
r.Add("buff profile: save, list and load round-trip", ProfileRoundTrip);
r.Add("buff profile: an id-only entry is filled in; a newer schema is refused", ProfileNormalizeAndSchema);
r.Add("buff profile: a chosen profile replaces the built-in list (order kept, no disabled or duplicate lines)", ProfileReplacesList);
r.Add("buff profile: a profile spell casts the best level known", ProfileResolvesTier);
r.Add("buff profile: a name with no tier ladder falls back to its spell family", ProfileFamilyFallback);
r.Add("buff profile: Loaded Files lists profiles, picks one by index, and the snapshot reports it", LoadedFilesPicker);
}
// ── Rig ─────────────────────────────────────────────────────────────────
private static SpellCatalogEntry Spell(int id) =>
SpellCatalog.Get(id) ?? throw new InvalidOperationException($"spell {id} missing from the catalog");
/// <summary>A buff manager over FakeHost with the given buffed Creature skill and known spells.</summary>
private static BuffManager NewBuffs(int buffedCreature, params int[] known)
{
FakeHost.Reset();
foreach (int id in known) FakeHost.Spellbook.Add((uint)id);
FakeHost.Skills[(Player, STypeCreature)] = (buffedCreature, 2);
var host = FakeHost.Create();
var settings = new LegacyUiSettings { EnableBuffing = true };
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var spells = new SpellManager(host, settings);
spells.InitializeNatively();
spells.SetCharacterSkills(skills);
var buffs = new BuffManager(host, settings, spells, new PlayerVitalsCache());
buffs.SetCharacterSkills(skills);
return buffs;
}
/// <summary>Runs <paramref name="body"/> with profile files in a fresh scratch folder.</summary>
private static void WithProfileFolder(Action<string> body)
{
string folder = Path.Combine(Program.TempRoot, "BuffProfiles-" + Guid.NewGuid().ToString("N"));
string? previous = BuffProfileStore.FolderOverride;
BuffProfileStore.FolderOverride = folder;
try { body(folder); }
finally { BuffProfileStore.FolderOverride = previous; }
}
// ── Catalog ─────────────────────────────────────────────────────────────
private static void CatalogLoads()
{
Check.True(SpellCatalog.IsLoaded, "the embedded catalog loads");
Check.True(SpellCatalog.All.Count >= 6000, $"6000+ spells (got {SpellCatalog.All.Count})");
foreach (string school in SpellCatalog.Schools)
Check.True(SpellCatalog.All.Any(e => e.School == school), $"school present: {school}");
Check.True(SpellCatalog.Effects.Contains("Buff"), "Buff is an effect");
var s = Spell(StrengthSelfI);
Check.Eq(s.Name, "Strength Self I", "id 2 is Strength Self I");
Check.Eq(s.Level, 1, "level 1");
Check.Eq(s.School, "Creature Enchantment", "Creature school");
Check.True(s.IsSelf && s.IsBuff, "a Self buff");
Check.Eq(s.FamilyId, StrengthFamily, "Strength family");
Check.Eq(Spell(StrengthOtherVI).Target, "Other", "Strength Other VI targets Other");
Check.Eq(SpellCatalog.GetByName("strength self vi")?.Id ?? 0, StrengthSelfVI, "name lookup ignores case");
Check.True(SpellCatalog.Family(StrengthFamily).Count >= 16, "the Strength family has Self and Other ladders");
}
private static void StripTier()
{
Check.Eq(SpellCatalog.StripTier("Strength Self VI"), "Strength Self", "roman VI");
Check.Eq(SpellCatalog.StripTier("Strength Self VIII"), "Strength Self", "roman VIII (not VII + I)");
Check.Eq(SpellCatalog.StripTier("Strength Self IV"), "Strength Self", "roman IV (not V)");
Check.Eq(SpellCatalog.StripTier("Incantation of Blade Bane"), "Blade Bane", "Incantation of");
Check.Eq(SpellCatalog.StripTier("Aura of Blood Drinker Self III"), "Blood Drinker Self", "Aura of");
Check.Eq(SpellCatalog.StripTier("Impenetrability Incantation"), "Impenetrability", "trailing Incantation");
Check.Eq(SpellCatalog.StripTier("Might of the Lugians"), "Might of the Lugians", "lore names are unchanged");
}
private static void BuffKeys()
{
Check.Eq(SpellCatalog.BuffKeyFor(Spell(StrengthSelfVI)), "Strength Self", "a Self spell is its own ladder");
Check.Eq(SpellCatalog.BuffKeyFor(Spell(StrengthOtherVI)), "Strength Self", "an Other spell casts the Self ladder");
Check.Eq(SpellCatalog.BuffKeyFor(Spell(MightOfTheLugians)), "Strength Self", "a lore name casts its family's Self ladder");
Check.Eq(SpellCatalog.BuffKeyFor(Spell(BladeBaneVI)), "Blade Bane", "an Item spell is its own ladder");
Check.Eq(SpellCatalog.BuffKeyFor(Spell(IncantationOfBladeBane)), "Blade Bane", "the Incantation joins the Item ladder");
Check.Eq(SpellCatalog.BuffKeyFor(Spell(AuraOfBloodDrinkerSelfIII)), "Blood Drinker Self", "weapon auras");
Check.Eq(SpellCatalog.BuffKeyFor(Spell(ImpenetrabilityIncantation)), "Impenetrability", "Impenetrability Incantation");
}
private static void ItemSchool()
{
Check.True(SpellCatalog.IsItemSchoolBuff("Blade Bane VI"), "Blade Bane VI is an item spell");
Check.True(SpellCatalog.IsItemSchoolBuff("Aura of Blood Drinker Self III"), "weapon auras are item spells");
Check.False(SpellCatalog.IsItemSchoolBuff("Strength Self VI"), "Strength Self VI is not");
Check.False(SpellCatalog.IsItemSchoolBuff("No Such Spell"), "unknown names are not");
Check.Eq(SpellCatalog.SkillForSchool("Item Enchantment"), AcSkillType.ItemEnchantment, "Item school casts with Item Enchantment");
Check.Eq(SpellCatalog.SkillForSchool("Life Magic"), AcSkillType.LifeMagic, "Life school casts with Life Magic");
}
// ── Profile files ───────────────────────────────────────────────────────
private static void ProfileRoundTrip() => WithProfileFolder(folder =>
{
var profile = new BuffProfile { Name = "Mage: main", Notes = "test" };
profile.Entries.Add(BuffProfileStore.EntryFor(Spell(StrengthOtherVI)));
profile.Entries.Add(BuffProfileStore.EntryFor(Spell(BladeBaneVI)));
profile.Entries[1].Enabled = false;
string path = BuffProfileStore.PathFor(profile.Name);
Check.Eq(Path.GetFileName(path), "Mage_ main.json", "':' is not allowed in a file name");
BuffProfileStore.Save(profile, path);
Check.False(File.Exists(path + ".tmp"), "no temp file left behind");
Check.Eq(string.Join(",", BuffProfileStore.ListFileNames()), "Mage_ main.json", "the folder lists it");
Check.True(BuffProfileStore.TryLoad(path, out var loaded, out string error), "loads: " + error);
Check.Eq(loaded.Name, "Mage: main", "name kept");
Check.Eq(loaded.Notes, "test", "notes kept");
Check.Eq(loaded.Entries.Count, 2, "two entries");
Check.Eq(loaded.Entries[0].SpellId, StrengthOtherVI, "spell id kept");
Check.Eq(loaded.Entries[0].Key, "Strength Self", "buffing key kept");
Check.Eq(loaded.Entries[0].School, "Creature Enchantment", "school kept");
Check.False(loaded.Entries[1].Enabled, "disabled flag kept");
Check.True(BuffProfileStore.Delete(path), "deletes");
Check.Eq(BuffProfileStore.ListFileNames().Count, 0, "the folder is empty again");
});
private static void ProfileNormalizeAndSchema() => WithProfileFolder(folder =>
{
Directory.CreateDirectory(folder);
string idOnly = Path.Combine(folder, "Hand Edited.json");
File.WriteAllText(idOnly, "{\"Entries\":[{\"SpellId\":" + BladeBaneVI + "},{\"SpellId\":0}]}");
Check.True(BuffProfileStore.TryLoad(idOnly, out var p, out string error), "an id-only file loads: " + error);
Check.Eq(p.Name, "Hand Edited", "a blank name comes from the file name");
Check.Eq(p.Entries.Count, 1, "an entry with neither id nor key is dropped");
Check.Eq(p.Entries[0].Name, "Blade Bane VI", "name filled from the catalog");
Check.Eq(p.Entries[0].Key, "Blade Bane", "key filled from the catalog");
Check.Eq(p.Entries[0].School, "Item Enchantment", "school filled from the catalog");
Check.Eq(p.Entries[0].Level, 6, "level filled from the catalog");
Check.True(p.Entries[0].Enabled, "entries default to enabled");
string newer = Path.Combine(folder, "Newer.json");
File.WriteAllText(newer, "{\"Schema\":99,\"Entries\":[]}");
Check.False(BuffProfileStore.TryLoad(newer, out _, out string why), "a newer schema is refused");
Check.True(why.Contains("newer"), "and says why: " + why);
Check.False(BuffProfileStore.TryLoad(Path.Combine(folder, "missing.json"), out _, out _), "a missing file is refused");
});
// ── Buffing with a profile ──────────────────────────────────────────────
private static void ProfileReplacesList()
{
var buffs = NewBuffs(500);
var builtIn = buffs.BuildBuiltInBuffList();
Check.Eq(string.Join(",", buffs.BuildDynamicBuffList()), string.Join(",", builtIn), "no profile: the built-in list");
var profile = new BuffProfile { Name = "test" };
profile.Entries.Add(BuffProfileStore.EntryFor(Spell(BladeBaneVI)));
profile.Entries.Add(BuffProfileStore.EntryFor(Spell(StrengthOtherVI)));
profile.Entries.Add(BuffProfileStore.EntryFor(Spell(StrengthSelfIII))); // same ladder as the line above
var focus = BuffProfileStore.EntryFor(Spell(SpellCatalog.GetByName("Focus Self VI")!.Id));
focus.Enabled = false;
profile.Entries.Add(focus);
buffs.ApplyBuffProfile(profile);
Check.Eq(string.Join(",", buffs.BuildDynamicBuffList()), "Blade Bane,Strength Self", "profile order, one line per ladder, disabled skipped");
Check.Eq(buffs.ActiveBuffProfileName, "test", "the active profile is named");
Check.Eq(buffs.ActiveBuffProfileCount, 2, "two spells in use");
Check.Eq(buffs.SkillFor("Blade Bane"), AcSkillType.ItemEnchantment, "the profile's school picks the casting skill");
}
private static void ProfileResolvesTier()
{
var buffs = NewBuffs(500, StrengthSelfI, StrengthSelfIII, StrengthSelfVI);
var profile = new BuffProfile { Name = "test" };
profile.Entries.Add(BuffProfileStore.EntryFor(Spell(StrengthOtherVI)));
buffs.ApplyBuffProfile(profile);
Check.Eq(buffs.FindBestSpellId("Strength Self", buffs.SkillFor("Strength Self")), StrengthSelfVI,
"Strength Other VI in the profile casts the best Strength Self known (VI)");
}
private static void ProfileFamilyFallback()
{
// A server-custom line: its base name has no tier ladder, only its family is known.
var custom = new BuffProfileEntry
{
SpellId = StrengthSelfI, Name = "Custom Strength", Key = "Custom Strength",
FamilyId = StrengthFamily, School = "Creature Enchantment", Target = "Self", Level = 1,
};
var profile = new BuffProfile { Name = "custom" };
profile.Entries.Add(custom);
var buffs = NewBuffs(500, StrengthSelfIII, MightOfTheLugians);
buffs.ApplyBuffProfile(profile);
Check.Eq(buffs.FindBestSpellId("Custom Strength", AcSkillType.CreatureEnchantment), MightOfTheLugians,
"skill 500: the family's highest known level (Might of the Lugians, 7)");
buffs = NewBuffs(250, StrengthSelfIII, MightOfTheLugians);
buffs.ApplyBuffProfile(profile);
Check.Eq(buffs.FindBestSpellId("Custom Strength", AcSkillType.CreatureEnchantment), StrengthSelfIII,
"skill 250 (tier 5): capped below 7, so Strength Self III");
buffs = NewBuffs(500);
buffs.ApplyBuffProfile(profile);
Check.Eq(buffs.FindBestSpellId("Custom Strength", AcSkillType.CreatureEnchantment), 0,
"cold spellbook: no guess for a name without a ladder");
}
// ── Loaded Files (engine picker → RynthPluginSelectProfile kind 4) ─────
private static void LoadedFilesPicker() => WithProfileFolder(folder =>
{
foreach (string name in new[] { "Beta", "Alpha" })
{
var p = new BuffProfile { Name = name };
p.Entries.Add(BuffProfileStore.EntryFor(Spell(StrengthSelfVI)));
BuffProfileStore.Save(p, BuffProfileStore.PathFor(name));
}
FakeHost.Reset();
var dash = new LegacyDashboardRenderer(FakeHost.Create());
dash.RefreshBuffProfileFiles();
using (var doc = System.Text.Json.JsonDocument.Parse(dash.BuildSnapshotJson()))
{
var root = doc.RootElement;
string list = string.Join(",", root.GetProperty("buffProfiles").EnumerateArray().Select(e => e.GetString()));
Check.Eq(list, "Built-in,Alpha.json,Beta.json", "Built-in first, then the files sorted");
Check.Eq(root.GetProperty("currentBuffName").GetString(), "Built-in", "no profile chosen yet");
Check.Eq(root.GetProperty("selectedBuffIdx").GetInt32(), 0, "Built-in selected");
}
dash.SelectProfileAtIndex(4, 2);
Check.Eq(dash.Settings.CurrentBuffProfilePath, Path.Combine(folder, "Beta.json"), "index 2 picks Beta");
using (var doc = System.Text.Json.JsonDocument.Parse(dash.BuildSnapshotJson()))
{
Check.Eq(doc.RootElement.GetProperty("currentBuffName").GetString(), "Beta", "the snapshot names it");
Check.Eq(doc.RootElement.GetProperty("selectedBuffIdx").GetInt32(), 2, "and selects it");
}
dash.SelectProfileAtIndex(4, 99);
Check.Eq(dash.Settings.CurrentBuffProfilePath, Path.Combine(folder, "Beta.json"), "an out-of-range index changes nothing");
dash.SelectProfileAtIndex(4, 0);
Check.Eq(dash.Settings.CurrentBuffProfilePath, "", "index 0 goes back to the built-in list");
});
}

View file

@ -0,0 +1,364 @@
using System;
using System.Linq;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// In a client log, two casts were held open by ACE's fast-tick turn-to-cast wait (40.8 s and 37 s);
// every cast after them came back UseDone 0x1D and the vitals path re-sent a heal every 2.5 s. A
// client mode change ended the second. ActionPacer now holds every start after a 0x1D until the
// server answers, turns to face a held cast's target, breaks a stuck cast with a jump (then Peace
// mode), waits until landed, and holds starts until a movement change has settled.
internal static class StuckCastTests
{
private const uint Player = 0x50000F01;
private const uint Monster = 0x80116781;
private const int DrainHealthOtherI = 1237;
private static (uint Cell, float X, float Y, float Z) Me0 => (0x6347028Au, 100f, 100f, 0f);
public static void Register(Runner r)
{
r.Add("stuck cast: after a 'too busy' UseDone nothing starts until the server answers; no timer re-send while our cast is open", NoResendAfterTooBusy);
r.Add("stuck cast: with no cast of ours open, one probe after 1.5 s, then doubling; a UseDone(0) clears", ProbeWhenNothingOpen);
r.Add("stuck cast: a held cast is turned to its target at cycle + 1 s, broken by a jump at cycle + 2 s; a normal 4 s cast trips neither", TurnThenJump);
r.Add("stuck cast: no starts in the air; after landing, no UseDone in 3 s -> Peace mode, 3 s more -> going on", AfterTheJump);
r.Add("stuck cast: a 'too busy' answer while our cast is open past 3 s breaks it at once; before 3 s it does not", RefusalWhileOpen);
r.Add("stuck cast: StuckCastMs 0 turns nothing and breaks nothing; no TapJump -> Peace mode", BreakerOffAndNoJump);
r.Add("move settle: no start in the tick of a movement change; 150 ms and a clear motion queue (or 600 ms) let it go", MoveSettle);
r.Add("stuck cast: the HP failsafe's forced break jumps once and holds starts until landed", ForcedBreak);
r.Add("stuck cast: a script's cast is not jumped before ScriptCastMinBreakMs (6 s): answered at 5.5 s, no jump; RynthAi's own is jumped at 5 s", ScriptCastGetsNudgeWindow);
}
private static long _t;
private static RynthCoreHost Setup(int mode = ActionPacer.MagicMode, bool tapJump = true)
{
FakeHost.Reset();
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.WeaponCalls = true; // GetCurrentCombatMode
FakeHost.CombatModeCalls = true; // ChangeCombatMode
FakeHost.TapJumpCalls = tapJump;
FakeHost.CombatModeValue = mode;
FakeHost.Names[Player] = "Mira";
FakeHost.PlayerPose = Me0;
FakeHost.Positions[Player] = Me0;
FakeHost.HeadingDeg = 0; // facing north
FakeHost.Positions[Monster] = (Me0.Cell, Me0.X + 10f, Me0.Y, Me0.Z); // due east: 90 deg off
var host = FakeHost.Create(Player);
_t = 90_000_000;
ActionPacer.Reset();
ActionPacer.Enabled = true;
ActionPacer.NowMs = () => _t;
MoveAudit.Reset();
MoveAudit.NowMs = () => _t;
ActionPacer.StuckCastMs = 8000;
FakeHost.UseDone(0); // an earlier action's answer: the observer's baseline
return host;
}
private static void Done()
{
ActionPacer.Enabled = false;
ActionPacer.Reset();
ActionPacer.NowMs = () => Environment.TickCount64;
MoveAudit.Reset();
MoveAudit.NowMs = () => Environment.TickCount64;
ActionPacer.StuckCastMs = 8000;
}
private static bool May(RynthCoreHost host, HealNeed heal = HealNeed.Heal) =>
ActionPacer.MayStart(host, "Buff", heal, out _);
private static void Cast(RynthCoreHost host, string label = "Drain Health Other I") =>
Check.True(host.CastSpellFor(Monster, DrainHealthOtherI, "Buff", label), "cast sent");
private static int JumpLines() => FakeHost.Logs.Count(l => l.Contains("stuck cast broken by jump after"));
private static void Run(RynthCoreHost host, long ms) { for (long s = 0; s < ms; s += 100) { _t += 100; May(host); } }
private static void ScriptCastGetsNudgeWindow()
{
// Control: RynthAi's own cast of a spell with no learned cycle (3 s) is jumped at cycle + 2 s.
var own = Setup();
try
{
Cast(own);
Run(own, 5500);
Check.Eq(JumpLines(), 1, "RynthAi's own cast: jumped by 5.5 s (at 5 s)");
}
finally { Done(); }
// The same cast chosen by a script, answered at 5.5 s: no jump.
var host = Setup();
try
{
Cast(host);
ActionPacer.MarkScriptCast(DrainHealthOtherI);
Run(host, 5500);
Check.Eq(JumpLines(), 0, "a script's cast: no jump in the first 5.5 s");
FakeHost.UseDone(0); // its answer
Run(host, 3000);
Check.Eq(JumpLines(), 0, "answered: never jumped");
}
finally { Done(); }
// A script's cast with no answer is still broken, once ScriptCastMinBreakMs has passed.
var held = Setup();
try
{
Cast(held);
ActionPacer.MarkScriptCast(DrainHealthOtherI);
Run(held, ActionPacer.ScriptCastMinBreakMs + 200);
Check.Eq(JumpLines(), 1, "unanswered: jumped after ScriptCastMinBreakMs");
}
finally { Done(); }
}
private static void NoResendAfterTooBusy()
{
var host = Setup();
ActionPacer.StuckCastMs = 0; // the hold alone (the breaker has its own tests)
try
{
Check.True(May(host), "free at first");
Cast(host); // the cast the server will hold open: no UseDone
_t += 500;
Check.False(May(host), "our cast is unanswered");
// Past CastMaxMs (7 s) the pacer used to "go on" and the heal went out into a busy server.
_t += ActionPacer.CastMaxMs - 500;
Check.False(May(host), "unanswered past CastMaxMs: still held (the cast is hung, the server is busy with it)");
Check.True(ActionPacer.ServerBusy, "the server is taken as busy");
// A cast the player sent by hand is refused: 0x1D. Still nothing goes for 13 s (no timer re-send).
FakeHost.UseDone(ActionPacer.TooBusyErr);
bool any = false;
for (int i = 0; i < 130; i++) { _t += 100; any |= May(host); }
Check.False(any, "nothing goes for 13 s after the 0x1D while our cast is hung");
Check.True(FakeHost.Logs.Any(l => l.Contains("Buff waits:") && l.Contains("has had no answer")), "the hold is logged");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("Buff waits:") && l.Contains("has had no answer")), 1, "once");
// The server finally answers (the cast's own UseDone): everything goes again.
FakeHost.UseDone(0x402);
Check.True(May(host), "a UseDone with another error clears the hold");
Check.False(ActionPacer.ServerBusy, "not busy any more");
Check.True(FakeHost.Logs.Any(l => l.Contains("the server answered again (UseDone 0x402)")), "logged");
}
finally { Done(); }
}
private static void ProbeWhenNothingOpen()
{
var host = Setup();
try
{
Check.True(May(host), "free");
Cast(host, "Heart Rend");
_t += 100;
FakeHost.UseDone(ActionPacer.TooBusyErr); // refused: the server is busy with something of no UseDone (a pickup)
Check.False(May(host), "held right after the 0x1D");
_t += ActionPacer.BusyProbeMs - 1;
Check.False(May(host), "held until BusyProbeMs");
_t += 1;
Check.True(May(host), "one probe at BusyProbeMs");
Check.False(May(host), "only one");
Cast(host, "Heart Rend");
_t += 100;
FakeHost.UseDone(ActionPacer.TooBusyErr); // refused again
_t += ActionPacer.BusyProbeMs * 2 - 101;
Check.False(May(host), "the next probe waits twice as long");
_t += 1;
Check.True(May(host), "second probe at 2 x BusyProbeMs");
Check.Eq(FakeHost.TapJumps + FakeHost.CombatModeRequests.Count, 0, "no breaker: no cast of ours was left open");
Cast(host, "Heart Rend");
_t += 900;
FakeHost.UseDone(0);
Check.True(May(host), "a UseDone(0) clears it");
}
finally { Done(); }
}
private static void TurnThenJump()
{
var host = Setup();
try
{
// A normal 4 s cast: answered; it sets the spell's cycle (4 s) and trips nothing.
Check.True(May(host), "free");
Cast(host);
_t += 4000;
FakeHost.UseDone(0);
May(host); // the answer seen at 4000 ms
Run(host, 10_000);
Check.Eq(FakeHost.Turns + FakeHost.TapJumps + FakeHost.CombatModeRequests.Count, 0, "a normal 4 s cast: no turn, no jump, no mode change");
Check.Eq(ActionPacer.NormalCycleMs(DrainHealthOtherI), 4000L, "the cycle learned from it");
// The next one is held open: turn at 4 + 1 s, jump at 4 + 2 s.
Cast(host);
long sent = _t;
while (_t - sent < 4900) { _t += 100; May(host); }
Check.Eq(FakeHost.Turns, 0, "no turn before cycle + 1 s");
_t += 100; May(host);
Check.Eq(FakeHost.Turns, 1, "turned at cycle + 1 s");
Check.Near(FakeHost.HeadingDeg, 90.0, 0.5, "to face the target (east)");
Check.True(FakeHost.Logs.Any(l => l.Contains("held cast:") && l.Contains("turning 90 deg to face 0x80116781")), "logged");
while (_t - sent < 5900) { _t += 100; Check.False(May(host), "held"); }
Check.Eq(FakeHost.TapJumps, 0, "no jump before cycle + 2 s");
_t += 100; May(host);
Check.Eq(FakeHost.TapJumps, 1, "the breaker jump at cycle + 2 s");
Check.True(FakeHost.Logs.Any(l => l.Contains("[Pace] stuck cast broken by jump after 6000 ms")), "logged with the time");
Run(host, 2000);
Check.Eq(FakeHost.TapJumps, 1, "one jump");
Check.Eq(FakeHost.Turns, 1, "one turn");
// The fizzle (0x402): free again once landed.
FakeHost.UseDone(0x402);
Check.True(May(host), "free after the cast's UseDone");
}
finally { Done(); }
}
private static void AfterTheJump()
{
var host = Setup();
try
{
Check.True(May(host), "free");
Cast(host);
long sent = _t;
while (FakeHost.TapJumps == 0 && _t - sent < 10_000) { _t += 100; May(host); }
Check.Eq(_t - sent, ActionPacer.DefaultCycleMs + ActionPacer.JumpAfterMs, "unknown spell cycle: the jump at 3 + 2 s");
long jumped = _t;
// In the air: even with the cast's UseDone in, nothing starts.
FakeHost.PlayerPose = (Me0.Cell, Me0.X, Me0.Y, Me0.Z + 0.6f);
FakeHost.UseDone(0x402);
_t += 200;
Check.False(May(host), "in the air: held even with the UseDone in");
Check.True(ActionPacer.BreakerAirborne, "airborne");
_t += 300;
Check.False(May(host), "still above the take-off height at 500 ms");
FakeHost.PlayerPose = Me0;
Check.True(May(host), "landed: free (the cast was answered)");
// A second hung cast: jump, land, no answer: Peace mode 3 s after landing, then going on 3 s later.
Cast(host);
sent = _t;
while (FakeHost.TapJumps < 2 && _t - sent < 10_000) { _t += 100; May(host); }
Check.Eq(FakeHost.TapJumps, 2, "jumped");
_t += ActionPacer.JumpLandMinMs; May(host); // landed (height unchanged)
long landed = _t;
while (_t - landed < ActionPacer.BreakerWaitMaxMs - 100) { _t += 100; Check.False(May(host), "held after landing, no answer"); }
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no Peace yet");
_t += 100; May(host);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), ActionPacer.PeaceMode.ToString(), "Peace requested once, 3 s after landing");
Check.True(FakeHost.Logs.Any(l => l.Contains("stuck cast broken by Peace mode after")), "logged");
FakeHost.CombatModeValue = ActionPacer.PeaceMode;
Run(host, ActionPacer.BreakerWaitMaxMs);
Check.True(FakeHost.Logs.Any(l => l.Contains("no UseDone after the stuck-cast break")), "going on, logged");
_t += ActionPacer.ModeSettleMs;
Check.True(May(host), "free after it");
Check.Eq(FakeHost.CombatModeRequests.Count, 1, "one Peace request");
}
finally { Done(); }
}
private static void RefusalWhileOpen()
{
var host = Setup();
try
{
Check.True(May(host), "free");
Cast(host);
_t += 2000;
Cast(host, "Rushed Recovery"); // a heal let ahead of it: refused, 2 s in (a recoil refusal is normal)
FakeHost.UseDone(ActionPacer.TooBusyErr);
_t += 100; May(host);
Check.Eq(FakeHost.TapJumps, 0, "a 0x1D at 2 s: no jump");
_t += 900; May(host);
Check.Eq(FakeHost.TapJumps, 1, "past RefusalBreakMinMs with a 0x1D in: jump at once (before cycle + 2 s)");
Check.True(FakeHost.Logs.Any(l => l.Contains("was refused 'too busy' while it was open")), "the reason is logged");
}
finally { Done(); }
}
private static void BreakerOffAndNoJump()
{
var host = Setup();
try
{
ActionPacer.StuckCastMs = 0;
Check.True(May(host), "free");
Cast(host);
Run(host, 30_000);
Check.Eq(FakeHost.Turns + FakeHost.TapJumps + FakeHost.CombatModeRequests.Count, 0, "StuckCastMs 0: nothing");
}
finally { Done(); }
host = Setup(tapJump: false);
try
{
Check.True(May(host), "free");
Cast(host);
Run(host, 6000);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), ActionPacer.PeaceMode.ToString(), "no TapJump: Peace mode at the jump time");
Check.True(FakeHost.Logs.Any(l => l.Contains("no TapJump on this engine")), "logged");
}
finally { Done(); }
}
private static void MoveSettle()
{
var host = Setup();
try
{
FakeHost.AutoRun = true;
Check.True(May(host), "free");
host.SetAutoRunBy("Nav", true);
_t += 1000;
host.SetAutoRunBy("Nav", false); // nav's stop goes out this tick
Check.False(May(host), "no cast in the tick of the stop");
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true), "an attack repeat is not held");
_t += MoveAudit.MoveSettleMinMs - 1;
Check.False(May(host), "held under MoveSettleMinMs");
_t += 1;
FakeHost.CastBusy = 1; // the client still animates the stop
Check.False(May(host), "the motion queue still busy: held");
FakeHost.CastBusy = 0;
Check.True(May(host), "settled: free");
Check.True(FakeHost.Logs.Any(l => l.Contains("SetAutoRun(False) sent") && l.Contains("has not settled")), "logged");
host.TurnToHeadingBy("Nav", 45f);
FakeHost.CastBusy = 1;
_t += MoveAudit.MoveSettleMaxMs - 1;
Check.False(May(host), "busy queue: held under MoveSettleMaxMs");
_t += 1;
// The gesture gate itself would still hold a busy queue; the settle gate lets go at its max.
Check.True(!MoveAudit.SettleHolds(host, out _), "the settle gate lets go at MoveSettleMaxMs");
FakeHost.CastBusy = 0;
}
finally { Done(); }
}
private static void ForcedBreak()
{
var host = Setup();
try
{
Check.True(ActionPacer.ForceBreak(host, "HP failsafe"), "the forced break goes");
Check.Eq(FakeHost.TapJumps, 1, "one jump");
Check.False(ActionPacer.ForceBreak(host, "HP failsafe"), "not twice while in the air");
FakeHost.PlayerPose = (Me0.Cell, Me0.X, Me0.Y, Me0.Z + 0.5f);
_t += 300;
Check.False(May(host), "in the air: held");
FakeHost.PlayerPose = Me0;
_t += 200;
Check.True(May(host), "landed: free (nothing of ours was open)");
Check.True(FakeHost.Logs.Any(l => l.Contains("stuck cast broken by jump after 0 ms") && l.Contains("HP failsafe")), "logged");
}
finally { Done(); }
}
}

View file

@ -36,6 +36,7 @@ internal static class T11LootTests
r.Add("loot t11: a live rating wins over the modifier text", LiveRatingWins);
r.Add("loot t11: retail items are untouched", RetailUntouched);
r.Add("loot t11: Can Wield from the /aug reply and the override", CanWield);
r.Add("loot t11: server tier and quality properties", ServerProps);
}
private static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
@ -124,4 +125,28 @@ internal static class T11LootTests
Check.Eq(new Item("T11 - Robe").Str(16, "A robe.").Wo.Values(T11Keys.CanWield, -5), 1, "appraised, no gate: wieldable");
T11ItemSupport.Reset();
}
// ACECustom sends ZcTier (50109) and WeaponAugScaleTier / Quality (9061 / 9060) in the appraisal.
private static void ServerProps()
{
T11ItemSupport.Reset();
Item weapon = Weapon();
WorldObject w = weapon;
Check.Eq(w.Values(T11Keys.EstimatedTier, -5), 12, "before the props: gate estimate T12");
Check.Eq(w.Values(T11Keys.TierIsExact, -5), 0, "before the props: estimate");
weapon.Int(T11Catalog.PropWeaponAugScaleTier, 14).Int(T11Catalog.PropWeaponAugScaleQuality, 873);
Check.Eq(w.Values(T11Keys.EstimatedTier, -5), 14, "props arriving later re-parse: stamped T14");
Check.Eq(w.Values(T11Keys.TierIsExact, -5), 1, "stamped tier is exact");
Check.True(M(w, C(N.LongValKeyGE, "850", K(T11Catalog.PropWeaponAugScaleQuality))), "rule: raw quality >= 850");
Check.False(M(w, C(N.LongValKeyGE, "900", K(T11Catalog.PropWeaponAugScaleQuality))), "rule: raw quality >= 900");
// No name prefix: the stamped tier alone makes it T11 and turns on the stripped-key fallback.
WorldObject plain = new Item("Celdon Breastplate", AcObjectClass.Armor)
.Str(16, "Wield requires: 4,000 Item Augmentations\n").Str(14, ArmorUse).Int(T11Catalog.PropZcTier, 18);
Check.Eq(plain.Values(T11Keys.IsT11, -5), 1, "ZcTier 18 marks T11 without the prefix");
Check.Eq(plain.Values(T11Keys.EstimatedTier, -5), 18, "tier from ZcTier");
Check.Eq(plain.Values(160, 0), 4000, "stripped wield gate restored on a ZcTier item");
Check.Eq(plain.Values(371, 0), 6, "stripped rating restored on a ZcTier item");
T11ItemSupport.Reset();
}
}

View file

@ -0,0 +1,545 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using RynthCore.Loot;
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;
// VTank's hotkey actions as /ra commands (2026-10-13, RynthAiPlugin.VTankHotkeys.cs): target lock,
// melee height, Boost Nav/Loot Priority toggles, LootThisCont (loot the open container, never
// house storage or your own packs) and Recharge (one vitals pass with the Top Off lines).
internal static class VTankHotkeyTests
{
private const uint Player = 0x50000F01;
private const uint Lb = 0xA9B40000;
private const uint A = 0x80000501, B = 0x80000502, C = 0x80000503, Npc = 0x80000504;
private const uint Chest = 0x7A9B5001, Gem = 0x80264101, Spoon = 0x80264102, SidePack = 0x80264200, PackGem = 0x80264201;
private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800, ItemTypeMisc = 0x80;
private const uint STypeLife = 33;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("vt keys: target lock picks the selected monster over the Targeting setting and a higher priority", TargetLockPicks);
r.Add("vt keys: target lock holds through blinks, ends on the kill / after 30 s out of reach / when cleared", TargetLockEnds);
r.Add("vt keys: /ra targetlock refuses non-monsters and dead ones; the same monster again releases", TargetLockCommand);
r.Add("vt keys: /ra meleelow|meleemid|meleehigh set the melee attack height", MeleeHeight);
r.Add("vt keys: NavPrio / LootPrio / NavLootPrio toggle Boost Nav / Loot Priority", PriorityToggles);
r.Add("vt keys: /ra setmetastate switches the state (the meta's spelling), lists states without one", MetaState);
r.Add("vt keys: LootThisCont loots an open chest with the macro and Looting off, and one Chest loot skips", LootThisLoots);
r.Add("vt keys: LootThisCont never takes house storage, your own packs, a vendor, or nothing open", LootThisRefuses);
r.Add("vt keys: LootThisCont re-loots a corpse marked done", LootThisCorpse);
r.Add("vt keys: Recharge is one vitals pass with the Top Off lines, macro off, on the next heartbeat", RechargeOnce);
}
// ── Target lock ───────────────────────────────────────────────────────────
private sealed class Rig
{
public readonly CombatManager Combat;
public readonly LegacyUiSettings S;
public readonly WorldObjectCache Cache;
public readonly RynthCoreHost Host;
private DateTime _now = DateTime.Now;
public Rig()
{
FakeHost.Reset();
Place(Player, "Me", 96, 96, creature: false);
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
Place(A, "Mob A", 96, 98);
Place(B, "Mob B", 96, 99);
Place(C, "Boss", 96, 100);
S = new LegacyUiSettings { MonsterRange = 20, TargetSelection = 1 /* closest */, TargetLock = true };
S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 });
var host = FakeHost.Create();
Host = host;
Cache = FakeHost.MakeCache(host, Player, new[] { A, B, C });
Combat = new CombatManager(host, S, Cache);
Combat.SetPlayerId(Player);
Combat.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
Combat.TargetClock = () => _now;
}
public void Advance(double ms) => _now = _now.AddMilliseconds(ms);
public uint Pick(params (uint Id, double Dist)[] scan)
{
Combat.SetScannedTargetsForTests(scan.Select(t => new CombatManager.ScannedTarget
{
Id = unchecked((int)t.Id), Distance = t.Dist, Angle = 0, Bearing = double.NaN, Name = FakeHost.Names[t.Id],
}));
Combat.HandleCombatTrigger();
return unchecked((uint)Combat.activeTargetId);
}
}
private static void Place(uint id, string name, float x, float y, bool creature = true)
{
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f);
if (creature) FakeHost.ItemTypes[id] = 0x10;
}
private static void TargetLockPicks()
{
var t = new Rig();
Check.Eq(t.Pick((A, 2), (B, 6)), A, "no lock: closest, A");
Check.Eq(t.Combat.ForcedTargetRefusal(unchecked((int)B)), null, "B can be locked onto");
t.Combat.SetForcedTarget(unchecked((int)B));
Check.Eq(t.Pick((A, 2), (B, 6)), B, "target lock: B, though A is closer and Target Lock held A");
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] switch 0x80000501") && l.Contains("(target lock,") && l.Contains("picked by the player")),
"the switch says it was the target lock");
Check.Eq(t.Pick((A, 1), (B, 6), (C, 3)), B, "kept when the Boss (priority 5) is in range");
t = new Rig();
Check.Eq(t.Pick((A, 2), (C, 4)), C, "no lock: the Boss's priority wins");
t.Combat.SetForcedTarget(unchecked((int)A));
Check.Eq(t.Pick((A, 2), (C, 4)), A, "target lock: A, over the higher priority");
// Not in the scan yet (out of sight): normal selection meanwhile, the lock waits.
t = new Rig();
t.Combat.SetForcedTarget(unchecked((int)B));
Check.Eq(t.Pick((A, 2)), A, "B not in the scan: A meanwhile");
Check.Eq(t.Pick((A, 2), (B, 7)), B, "B comes into sight: B");
}
private static void TargetLockEnds()
{
var t = new Rig();
t.Combat.SetForcedTarget(unchecked((int)C));
S(t).MonsterRules[0].Priority = 0; // the Boss rule now says ignore: the lock still attacks it
Check.Eq(t.Pick((A, 2), (C, 5)), C, "a Priority 0 monster is attacked when locked onto");
Check.False(t.Combat.IsIgnored(unchecked((int)C)), "and isn't treated as ignored meanwhile");
Check.Eq(t.Pick((A, 2)), C, "it blinks out of the scan: kept within the grace");
t.Advance(1000);
Check.Eq(t.Pick((A, 2)), C, "still within the 1.5 s grace");
Check.Eq(t.Pick((A, 2), (C, 5)), C, "back in the scan");
t.Combat.OnKillNotification("Boss's perforated corpse falls before you!");
Check.Eq(t.Pick((A, 2)), A, "killed: the next target is picked normally");
Check.Eq(t.Combat.ForcedTargetId, 0, "and the lock is over");
Check.True(FakeHost.Chat.Any(c => c.Contains("Target lock on Boss ended: killed")), "chat says the lock ended");
// Never in reach: ends after ForcedTargetLostMs.
t = new Rig();
t.Combat.SetForcedTarget(unchecked((int)B));
Check.Eq(t.Pick((A, 2)), A, "B never in the scan: A");
t.Advance(CombatManager.ForcedTargetLostMs + 100);
t.Pick((A, 2));
Check.Eq(t.Combat.ForcedTargetId, 0, "30 s never in reach: the lock ends");
Check.True(FakeHost.Chat.Any(c => c.Contains("ended: never in reach")), "and says why");
// Cleared: normal selection again.
t = new Rig();
t.Combat.SetForcedTarget(unchecked((int)B));
Check.Eq(t.Pick((A, 2), (B, 6)), B, "locked on B");
t.Combat.ClearForcedTarget();
Check.Eq(t.Pick((A, 2), (B, 6)), B, "cleared: Target Lock (the setting) keeps the current fight");
}
private static LegacyUiSettings S(Rig t) => t.S;
private static void TargetLockCommand()
{
var t = new Rig();
FakeHost.Names[Npc] = "Town Crier";
FakeHost.ItemTypes[Npc] = 0x10;
FakeHost.NotAttackable.Add(Npc);
t.Cache.OnCreateObject(Npc);
t.Cache.Tick();
var bot = new Bot(t.Host, t.Cache);
bot.Set("_combatManager", t.Combat);
bot.S.IsMacroRunning = true;
bot.S.EnableCombat = true;
FakeHost.SelectedItem = 0;
bot.Ra("/ra targetlock");
Check.True(bot.LastChat.Contains("nothing is selected"), "nothing selected: refused (" + bot.LastChat + ")");
FakeHost.SelectedItem = Npc;
bot.Ra("/ra targetlock");
Check.True(bot.LastChat.Contains("can't be attacked"), "an NPC: refused (" + bot.LastChat + ")");
Check.Eq(t.Combat.ForcedTargetId, 0, "no lock");
t.Cache.OnUpdateHealth(A, 0f);
FakeHost.SelectedItem = A;
bot.Ra("/ra targetlock");
Check.True(bot.LastChat.Contains("is dead"), "a dead monster: refused (" + bot.LastChat + ")");
FakeHost.SelectedItem = B;
bot.Ra("/ra targetlock");
Check.Eq(t.Combat.ForcedTargetId, unchecked((int)B), "B selected: locked");
Check.True(bot.LastChat.Contains("Target lock: attacking Mob B."), "chat: " + bot.LastChat);
bot.Ra("/ra targetlock");
Check.Eq(t.Combat.ForcedTargetId, 0, "the same monster again: released");
Check.True(bot.LastChat.Contains("released"), "chat: " + bot.LastChat);
bot.Ra("/ra targetlock");
bot.S.IsMacroRunning = false;
FakeHost.SelectedItem = C;
bot.Ra("/ra targetlock");
Check.Eq(t.Combat.ForcedTargetId, unchecked((int)C), "another monster: the lock moves to it");
Check.True(bot.LastChat.Contains("the macro is off"), "macro off: said (" + bot.LastChat + ")");
bot.Ra("/ra targetlock off");
Check.Eq(t.Combat.ForcedTargetId, 0, "/ra targetlock off");
}
// ── Plugin harness ───────────────────────────────────────────────────────
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 Bot(RynthCoreHost host, WorldObjectCache? cache = null)
{
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 = cache ?? new WorldObjectCache(host);
Cache.SetPlayerId(Player);
Set("_objectCache", Cache);
Set("_playerId", Player);
}
public void UseGemProfile()
{
string profile = Path.Combine(Program.TempRoot, "loot-vtkeys-" + Guid.NewGuid().ToString("N")[..8] + ".json");
var p = new LootProfile { Name = "vtkeys" };
var gems = new LootRule { Name = "Gems", Action = LootAction.Keep };
gems.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
p.Rules.Add(gems);
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 void Ra(string line)
{
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
object[] args = { parts[1].ToLowerInvariant(), parts, 0 };
typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(P, args);
}
public string LastChat => FakeHost.Chat.Count > 0 ? FakeHost.Chat[^1] : "";
public string AllChat => string.Join(" | ", FakeHost.Chat);
public void Create(params uint[] ids)
{
foreach (uint id in ids) Cache.OnCreateObject(id);
Cache.Tick();
}
public void Tick(BotActivity act = BotActivity.Idle)
{
Set("_activity", act);
Call("TickCorpseOpening");
}
public void TickUntil(Func<bool> done, int max = 200)
{
for (int i = 0; i < max && !done(); i++) { Tick(); Thread.Sleep(10); }
}
public bool Moved(uint id) => FakeHost.ExternalMoves.Any(m => m.Id == id);
}
// ── Melee height, priorities, meta state ─────────────────────────────────
private static void MeleeHeight()
{
FakeHost.Reset();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.MeleeAttackHeight = 1;
bot.Ra("/ra meleelow");
Check.Eq(bot.S.MeleeAttackHeight, 0, "MeleeLow: 0 (Low)");
Check.True(bot.LastChat.Contains("Melee attack height: Low"), bot.LastChat);
bot.Ra("/ra meleehigh");
Check.Eq(bot.S.MeleeAttackHeight, 2, "MeleeHigh: 2 (High)");
bot.Ra("/ra meleemid");
Check.Eq(bot.S.MeleeAttackHeight, 1, "MeleeMid: 1 (Medium)");
Check.True(bot.LastChat.Contains("Medium"), bot.LastChat);
int missile = bot.S.MissileAttackHeight;
bot.Ra("/ra meleelow");
Check.Eq(bot.S.MissileAttackHeight, missile, "missile height untouched");
}
private static void PriorityToggles()
{
// Pure rule.
Check.Eq(RynthAiPlugin.NextPriority(false, false, true, false, ""), (true, false), "NavPrio from off: nav on");
Check.Eq(RynthAiPlugin.NextPriority(true, true, true, false, ""), (false, true), "NavPrio from on: nav off, loot kept");
Check.Eq(RynthAiPlugin.NextPriority(false, true, false, true, ""), (false, false), "LootPrio from on: off");
Check.Eq(RynthAiPlugin.NextPriority(false, false, true, true, ""), (true, true), "NavLootPrio, both off: both on");
Check.Eq(RynthAiPlugin.NextPriority(true, false, true, true, ""), (true, true), "NavLootPrio, one on: both on");
Check.Eq(RynthAiPlugin.NextPriority(true, true, true, true, ""), (false, false), "NavLootPrio, both on: both off");
Check.Eq(RynthAiPlugin.NextPriority(true, false, true, false, "on"), (true, false), "'on' sets, doesn't toggle");
Check.Eq(RynthAiPlugin.NextPriority(true, true, true, true, "off"), (false, false), "'off'");
FakeHost.Reset();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Ra("/ra navprio");
Check.True(bot.S.BoostNavPriority && !bot.S.BoostLootPriority, "/ra navprio: Boost Nav on");
Check.True(bot.LastChat.Contains("Boost Nav Priority on"), bot.LastChat);
bot.Ra("/ra lootprio");
Check.True(bot.S.BoostNavPriority && bot.S.BoostLootPriority, "/ra lootprio: Boost Loot on");
bot.Ra("/ra navlootprio");
Check.True(!bot.S.BoostNavPriority && !bot.S.BoostLootPriority, "/ra navlootprio with both on: both off");
bot.Ra("/ra navlootprio");
Check.True(bot.S.BoostNavPriority && bot.S.BoostLootPriority, "again: both on");
Check.True(bot.LastChat.Contains("Boost Nav Priority on, Boost Loot Priority on"), bot.LastChat);
bot.Ra("/ra navprio off");
Check.True(!bot.S.BoostNavPriority && bot.S.BoostLootPriority, "/ra navprio off");
}
private static void MetaState()
{
FakeHost.Reset();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.MetaRules.Add(new MetaRule { State = "Default" });
bot.S.MetaRules.Add(new MetaRule { State = "Hunting Grounds" });
bot.S.MetaRules.Add(new MetaRule { State = "Hunting Grounds" });
bot.S.MetaRules.Add(new MetaRule { State = "Go Home" });
bot.Set("_metaManager", new RynthCore.Plugin.RynthAi.Meta.MetaManager(bot.S, host, new PlayerVitalsCache()));
Check.Eq(string.Join(",", (List<string>)bot.Call("LoadedMetaStates")!), "Default,Hunting Grounds,Go Home", "the loaded meta's states, once each");
bot.Ra("/ra setmetastate hunting grounds");
Check.Eq(bot.S.CurrentState, "Hunting Grounds", "set, in the meta's spelling");
Check.True(bot.S.ForceStateReset, "the state restarts");
bot.Ra("/ra setmetastate Nowhere");
Check.Eq(bot.S.CurrentState, "Nowhere", "an unknown state is still set (it may come with another meta)");
Check.True(bot.LastChat.Contains("has no state 'Nowhere'"), bot.LastChat);
FakeHost.Chat.Clear();
bot.Ra("/ra setmetastate");
Check.True(bot.AllChat.Contains("States: Default, Hunting Grounds, Go Home"), "no state: lists them (" + bot.AllChat + ")");
}
// ── LootThisCont ──────────────────────────────────────────────────────────
private static void ChestWorld(string name = "Chest")
{
FakeHost.Reset();
FakeHost.SalvageCalls = true;
FakeHost.WeaponCalls = true;
FakeHost.CloseContainerCalls = true;
var me = (0x1048002Au, 100f, 100f, 0f);
FakeHost.Names[Player] = "Dargoth Hera";
FakeHost.Positions[Player] = me;
FakeHost.PlayerPose = me;
FakeHost.Names[Chest] = name;
FakeHost.ItemTypes[Chest] = ItemTypeContainer;
FakeHost.Positions[Chest] = (me.Item1, 101f, 100f, 0f);
FakeHost.NotAttackable.Add(Chest);
FakeHost.Containers[Chest] = 0;
AddItem(Gem, "Black Opal", ItemTypeGem, Chest);
AddItem(Spoon, "Rusty Spoon", ItemTypeMisc, Chest);
}
private static void AddItem(uint id, string name, uint type, uint container)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = type;
FakeHost.Containers[id] = container;
FakeHost.Appraised.Add(id);
}
private static void LootThisLoots()
{
// Macro off and Looting off: nothing happens on its own; LootThisCont loots it.
ChestWorld();
var bot = new Bot(FakeHost.Create(Player));
bot.UseGemProfile();
bot.S.IsMacroRunning = false;
bot.S.EnableLooting = false;
bot.Create(Chest, Gem, Spoon);
FakeHost.GroundContainer = Chest;
bot.P.OnViewObjectContents(Chest);
bot.P.OnUpdateObjectInventory(Chest);
for (int i = 0; i < 20; i++) { bot.Tick(); Thread.Sleep(5); }
Check.False(bot.Moved(Gem), "macro off: the chest isn't looted on its own");
bot.Ra("/ra lootthis");
bot.TickUntil(() => bot.Moved(Gem));
Check.True(FakeHost.ExternalMoves.Contains((Gem, Player, 0)), "LootThisCont: the gem goes into the pack");
Check.True(FakeHost.Chat.Any(c => c.Contains("LootThisCont: looting Chest (the macro is off: this container only)")), bot.AllChat);
FakeHost.Containers[Gem] = Player;
bot.TickUntil(() => FakeHost.Closes.Count > 0);
Check.False(bot.Moved(Spoon), "the spoon matches nothing and stays");
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{Chest:X8}", "closed when done");
int moves = FakeHost.ExternalMoves.Count;
for (int i = 0; i < 20; i++) { bot.Tick(); Thread.Sleep(5); }
Check.Eq(bot.Get<int>("_forcedLootContainerId"), 0, "the flag ends with the container");
Check.Eq(FakeHost.ExternalMoves.Count, moves, "and nothing else is looted with the macro off");
// A chest Chest loot skips (held by another object): looted when flagged.
ChestWorld();
FakeHost.Containers[Chest] = 0x7A9B5099;
bot = new Bot(FakeHost.Create(Player));
bot.UseGemProfile();
bot.Create(Chest, Gem, Spoon);
FakeHost.GroundContainer = Chest;
bot.P.OnViewObjectContents(Chest);
bot.P.OnUpdateObjectInventory(Chest);
for (int i = 0; i < 20; i++) { bot.Tick(BotActivity.Looting); Thread.Sleep(5); }
Check.False(bot.Moved(Gem), "held by another object: Chest loot skips it");
bot.Ra("/ra lootthiscont");
bot.TickUntil(() => bot.Moved(Gem));
Check.True(bot.Moved(Gem), "flagged: looted anyway");
}
private static void LootThisRefuses()
{
// Nothing open.
ChestWorld();
var bot = new Bot(FakeHost.Create(Player));
bot.Create(Chest, Gem, Spoon);
bot.Ra("/ra lootthis");
bot.Tick();
Check.True(bot.LastChat.Contains("no container is open"), bot.LastChat);
// House storage by its house owner, and by name.
ChestWorld();
FakeHost.InstanceIds[(Chest, 32)] = 0x50000ABC;
bot = new Bot(FakeHost.Create(Player));
bot.Create(Chest, Gem, Spoon);
FakeHost.GroundContainer = Chest;
bot.Ra("/ra lootthis");
bot.TickUntil(() => FakeHost.ExternalMoves.Count > 0, 30);
Check.True(FakeHost.Chat.Any(c => c.Contains("house storage is never looted")), bot.AllChat);
Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing taken out of house storage");
ChestWorld("Storage");
bot = new Bot(FakeHost.Create(Player));
bot.Create(Chest, Gem, Spoon);
FakeHost.GroundContainer = Chest;
Check.Eq(bot.Call("LootThisRefusal", unchecked((int)Chest)), "house storage is never looted", "named Storage");
// Your own packs.
ChestWorld();
FakeHost.Names[SidePack] = "Pack";
FakeHost.ItemTypes[SidePack] = ItemTypeContainer;
FakeHost.Containers[SidePack] = Player;
AddItem(PackGem, "Black Opal", ItemTypeGem, SidePack);
bot = new Bot(FakeHost.Create(Player));
bot.Create(SidePack, PackGem);
Check.Eq(bot.Call("LootThisRefusal", unchecked((int)SidePack)), "it's in your inventory", "a side pack");
Check.Eq(bot.Call("LootThisRefusal", unchecked((int)Player)), "that's your own pack", "the main pack");
FakeHost.GroundContainer = SidePack;
bot.Ra("/ra lootthis");
bot.TickUntil(() => FakeHost.ExternalMoves.Count > 0, 30);
Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing moved out of your own pack");
// A vendor.
ChestWorld();
FakeHost.Bitfields[Chest] = 0x00000200;
bot = new Bot(FakeHost.Create(Player));
bot.Create(Chest);
Check.Eq(bot.Call("LootThisRefusal", unchecked((int)Chest)), "it's a vendor", "a vendor");
Check.Eq(bot.Call("LootThisRefusal", 0), "no container is open (open a corpse or chest first)", "nothing");
}
private static void LootThisCorpse()
{
const uint Corpse = 0x80264301, Loot = 0x80264302;
ChestWorld();
FakeHost.Names[Corpse] = "Corpse of Mob A";
FakeHost.ItemTypes[Corpse] = ItemTypeContainer;
FakeHost.Positions[Corpse] = (0x1048002Au, 101f, 100f, 0f);
FakeHost.Bitfields[Corpse] = 0x00002000; // a corpse
FakeHost.Containers[Corpse] = 0;
AddItem(Loot, "Black Opal", ItemTypeGem, Corpse);
var bot = new Bot(FakeHost.Create(Player));
bot.UseGemProfile();
bot.Create(Corpse, Loot);
Check.True((bool)bot.Call("IsCorpseLikeObject", unchecked((int)Corpse))!, "the test corpse is a corpse to the looter");
bot.Get<Dictionary<int, long>>("_completedCorpses")[unchecked((int)Corpse)] = 1; // looted (or skipped) before
FakeHost.GroundContainer = Corpse;
bot.P.OnViewObjectContents(Corpse);
for (int i = 0; i < 20; i++) { bot.Tick(BotActivity.Looting); Thread.Sleep(5); }
Check.False(bot.Moved(Loot), "a completed corpse reopened: not looted again on its own");
bot.Ra("/ra lootthis");
bot.TickUntil(() => bot.Moved(Loot));
Check.True(bot.Moved(Loot), "LootThisCont: looted again");
}
// ── Recharge ──────────────────────────────────────────────────────────────
private static BuffManager Vitals(uint hp, uint st, uint mn, out LegacyUiSettings s)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
var host = FakeHost.Create();
s = new LegacyUiSettings
{
IsMacroRunning = false, HealAt = 50, TopOffHP = 90, EmergencyHealAt = 0, StaminaToHealthAt = 0,
RestamAt = 0, TopOffStam = 0, GetManaAt = 0, TopOffMana = 0, UsePotions = false,
};
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, s);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = hp, MaxStamina = 100, CurrentStamina = st, MaxMana = 100, CurrentMana = mn };
var b = new BuffManager(host, s, sm, vitals);
b.SetCharacterSkills(skills);
b.InCombatOverride = () => true; // a monster in range: the in-combat lines
return b;
}
private static void RechargeOnce()
{
// 70% health: over Heal At 50 (in combat nothing heals), under Top Off HP 90.
var b = Vitals(70, 100, 100, out _);
Check.False(b.CheckVitals(), "the normal step in combat: 70% is over Heal At 50, nothing");
Check.Eq(FakeHost.Casts.Count, 0, "no cast");
string said = b.RechargeOnceNow();
Check.Eq(FakeHost.Casts.Count, 1, "Recharge: one cast");
Check.True(said.StartsWith("healing"), "it says it heals (" + said + ")");
int healFamily = SpellTableStub.GetById(SpellTable.Rows.First(r => r.Name == "Heal Self I").Id)?.Family ?? -1;
Check.Eq(SpellTableStub.GetById(FakeHost.Casts[0].SpellId)?.Family, healFamily, "a Heal Self (the top level known)");
Check.True(b.InCombatOverride!(), "the in-combat lines are back after the pass");
// Everything over Top Off: nothing.
b = Vitals(95, 100, 100, out _);
said = b.RechargeOnceNow();
Check.Eq(FakeHost.Casts.Count, 0, "all over Top Off: no cast");
Check.True(said.StartsWith("nothing to do"), said);
// Requested (as /ra recharge does): runs on the next heartbeat, macro off, and says so.
ActionPacer.Reset();
b = Vitals(70, 100, 100, out var s);
Check.False(s.IsMacroRunning, "macro off");
b.RequestRecharge();
Check.True(b.RechargePending, "pending until a heartbeat");
for (int i = 0; i < 20 && b.RechargePending; i++) { b.OnHeartbeat(); Thread.Sleep(10); }
Check.False(b.RechargePending, "taken on the heartbeat");
Check.Eq(FakeHost.Casts.Count, 1, "one cast, macro off");
Check.True(FakeHost.Chat.Any(c => c.StartsWith("[RynthAi] Recharge: healing")), string.Join(" | ", FakeHost.Chat));
for (int i = 0; i < 5; i++) { b.OnHeartbeat(); Thread.Sleep(10); }
Check.Eq(FakeHost.Casts.Count, 1, "one pass only: nothing more with the macro off");
}
}

View file

@ -48,10 +48,12 @@ internal static class WeaponTests
r.Add("slayer: creature type unknown, the old choice", SlayerUnknownType);
r.Add("slayer: the element follows the chosen weapon", SlayerElement);
r.Add("slayer: read through the host (int 166, float 138, monster int 2), cached by wcid", SlayerFromHost);
r.Add("refusal: a refused stance change in combat's equip pass sets no backoff and starts no stuck clock", StanceRefusedKeepsBackoff);
r.Add("weapon choice: an unlisted wand is never picked (Damage tab, learned, pack, name)", UnlistedNeverPicked);
r.Add("Items list: a listed item no longer carried is reported missing (pack, hand, unknown)", MissingFromPack);
r.Add("weapon swap: one in flight, confirmed, retry cap, then what's in hand", SwapOneInFlight);
r.Add("weapon swap: no flip-flop between two weapons", SwapNoFlipFlop);
r.Add("weapon swap: a new target that wants the weapon just swapped away from gets it at once (Drakkon 2026-10-12)", SwapBackForNewTarget);
r.Add("weapon swap: a server refusal counts as a failed try", SwapRefused);
r.Add("tester's case: Dragon's Isle, an unlisted fire wand and Blades", TesterDragonsIsle);
}
@ -645,10 +647,11 @@ internal static class WeaponTests
public readonly MonsterDamageStore Store = new();
public WorldObject Target;
public Rig(uint wcid, string monsterName)
public Rig(uint wcid, string monsterName, bool modeCalls = false)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.CombatModeCalls = modeCalls;
FakeHost.CombatModeValue = CombatMode.Magic;
FakeHost.Names[ListedWand] = "Wand"; FakeHost.ItemTypes[ListedWand] = 0x8000;
FakeHost.Ints[(ListedWand, 45)] = 0x40; // identified: Lightning
@ -698,6 +701,26 @@ internal static class WeaponTests
Check.Eq(missing.Count, 0, "inventory not known yet (empty, logging in): nothing reported missing");
}
private static void StanceRefusedKeepsBackoff()
{
var rig = new Rig(1535, "Ethereal Wisp", modeCalls: true);
rig.C.InHandOverride = () => unchecked((int)ListedWand); // the wand is in hand
FakeHost.CombatModeValue = CombatMode.NonCombat; // but the stance is not Magic yet
FakeHost.Ints[(ListedWand, 10)] = 0x01000000; // CurrentWieldedLocation: reads wielded (the stuck-clock branch)
var equip = typeof(CombatManager).GetMethod("EquipWeaponAndSetStance", BindingFlags.Instance | BindingFlags.NonPublic)!;
var last = typeof(CombatManager).GetField("lastStanceAttempt", BindingFlags.Instance | BindingFlags.NonPublic)!;
var stuck = typeof(CombatManager).GetField("_stanceStuckSince", BindingFlags.Instance | BindingFlags.NonPublic)!;
FakeHost.CombatModeRefuse = true;
for (int i = 0; i < 5; i++) equip.Invoke(rig.C, new object[] { rig.Target, "Auto" });
Check.Eq(FakeHost.CombatModeRefusals, 5, "every pass asks again: a refusal sets no backoff");
Check.True((DateTime)last.GetValue(rig.C)! == DateTime.MinValue, "lastStanceAttempt stays put");
Check.True((DateTime)stuck.GetValue(rig.C)! == DateTime.MinValue, "the stuck clock has not started");
Check.Eq(FakeHost.Uses.Count, 0, "no re-equip UseObject");
FakeHost.CombatModeRefuse = false;
equip.Invoke(rig.C, new object[] { rig.Target, "Auto" });
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), CombatMode.Magic.ToString(), "accepted: the request goes out");
Check.True((DateTime)last.GetValue(rig.C)! != DateTime.MinValue, "and only now lastStanceAttempt is stamped");
}
private static void UnlistedNeverPicked()
{
var rig = new Rig(1535, "Ethereal Wisp");
@ -799,6 +822,48 @@ internal static class WeaponTests
Check.Eq(tr2.Next(99, hand, t.AddSeconds(5)), WeaponSwapTracker.Step.Hold, "a fifth swap inside a minute: held");
}
// Drakkon 2026-10-12 (0x01C5): Tetsubo -> Lightning Quadrelle for a Giant Maggot; 16 s later
// the next target, a Noble Grub weak to Bludgeon, was fought with the Quadrelle ("keeping ...
// just swapped away from it") until the 20 s dwell ran out, 5.3 s after the lock.
private static void SwapBackForNewTarget()
{
const int Tetsubo = 1, Quadrelle = 2, Maggot = 0x7001, Grub = 0x7002;
var tr = new WeaponSwapTracker();
DateTime t = new(2026, 10, 12, 20, 35, 8);
Check.Eq(tr.Next(Quadrelle, Tetsubo, t, forKey: Maggot), WeaponSwapTracker.Step.Swap, "maggot: Tetsubo -> Quadrelle");
tr.Sent(Quadrelle, Tetsubo, t);
tr.Next(Quadrelle, Quadrelle, t.AddSeconds(1), forKey: Maggot); // landed
Check.Eq(tr.Next(Tetsubo, Quadrelle, t.AddSeconds(16), forKey: Grub), WeaponSwapTracker.Step.Swap,
"the grub (a new target) gets the Tetsubo back at once");
tr.Sent(Tetsubo, Quadrelle, t.AddSeconds(16));
tr.Next(Tetsubo, Tetsubo, t.AddSeconds(17), forKey: Grub); // landed
// The same target asking to flip back is still held (weakness data flickering mid-fight).
Check.Eq(tr.Next(Quadrelle, Tetsubo, t.AddSeconds(19), forKey: Grub), WeaponSwapTracker.Step.Hold,
"same target flipping straight back: held");
Check.Eq(tr.HoldReason, "just swapped away from it", "the reason");
// No target given (old callers): the old rule.
Check.Eq(tr.Next(Quadrelle, Tetsubo, t.AddSeconds(20)), WeaponSwapTracker.Step.Hold, "no key: held as before");
// A third target: free to swap.
Check.Eq(tr.Next(Quadrelle, Tetsubo, t.AddSeconds(20), forKey: 0x7003), WeaponSwapTracker.Step.Swap, "another new target: swap");
// The window cap still holds a fight that alternates between two kinds of monster.
var tr2 = new WeaponSwapTracker();
DateTime u = new(2026, 10, 12, 21, 0, 0);
int hand = Tetsubo;
for (int i = 0; i < 4; i++)
{
int want = hand == Tetsubo ? Quadrelle : Tetsubo;
u = u.AddSeconds(5);
Check.Eq(tr2.Next(want, hand, u, forKey: 0x8000 + i), WeaponSwapTracker.Step.Swap, $"alternating target {i}: swap");
tr2.Sent(want, hand, u);
tr2.Next(want, want, u.AddSeconds(1), forKey: 0x8000 + i);
hand = want;
}
int next = hand == Tetsubo ? Quadrelle : Tetsubo;
Check.Eq(tr2.Next(next, hand, u.AddSeconds(5), forKey: 0x8010), WeaponSwapTracker.Step.Hold, "a fifth swap inside a minute: held");
}
private static void SwapRefused()
{
var tr = new WeaponSwapTracker { MaxTries = 2 };

View file

@ -26,6 +26,7 @@
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\CreatureData\CreatureWeakness.cs" Link="Linked\CreatureWeakness.cs" />
<!-- Learned per-monster damage (System only), for the Aelrynth difficulty-tier tests. -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\CreatureData\MonsterDamageStore.cs" Link="Linked\MonsterDamageStore.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\CreatureData\PlayerWeenies.cs" Link="Linked\PlayerWeenies.cs" />
</ItemGroup>
<ItemGroup>

View file

@ -21,6 +21,7 @@ internal static class CombatStallWatchdogTests
r.Add("stall: a swing after a step is a recovery", Recovery);
r.Add("stall: a tick gap starts the count over", TickGapResets);
r.Add("stall: ineligible never acts", Ineligible);
r.Add("stall: Unfire takes a step back - the same step is due again next tick, not 3 s later", UnfireRetries);
}
/// <summary>Ticks every 500 ms from <paramref name="fromMs"/> to <paramref name="toMs"/>
@ -95,4 +96,27 @@ internal static class CombatStallWatchdogTests
Check.Eq(acted, 0, "no action in a minute of ineligible ticks");
Check.Eq(w.Episodes, 0, "no episodes");
}
}
private static void UnfireRetries()
{
var w = new CombatStallWatchdog();
Check.Eq(RunUntilAction(w, 0, 20_000, NoEvidence), (Act.Reissue, 6000), "step 1");
Check.Eq(RunUntilAction(w, 6500, 20_000, NoEvidence), (Act.Reselect, 9000), "step 2");
Check.Eq(RunUntilAction(w, 9500, 20_000, NoEvidence), (Act.ToggleMode, 12000), "step 3 fires");
w.Unfire(); // the engine refused the toggle
Check.Eq(w.CurrentStep, 2, "Unfire: back at step 2");
Check.Eq(RunUntilAction(w, 12_500, 20_000, NoEvidence), (Act.ToggleMode, 12_500), "the toggle is due again on the very next tick");
Check.Eq(RunUntilAction(w, 13_000, 20_000, NoEvidence), (Act.Rewield, 15_500), "an accepted toggle then spaces step 4 a full 3 s after it");
// Unfire at step 1 gives the episode back too.
var v = new CombatStallWatchdog();
Check.Eq(RunUntilAction(v, 0, 10_000, NoEvidence), (Act.Reissue, 6000), "step 1");
Check.Eq(v.Episodes, 1, "one episode");
v.Unfire();
Check.Eq(v.CurrentStep, 0, "back to no step");
Check.Eq(v.Episodes, 0, "and the episode is not counted until a step really goes out");
Check.Eq(RunUntilAction(v, 6500, 10_000, NoEvidence), (Act.Reissue, 6500), "step 1 again next tick");
Check.Eq(v.Episodes, 1, "one episode");
}
}

View file

@ -25,6 +25,7 @@ internal static class CreatureWeaknessTests
r.Add("weakness: server table ranks most damage first", ServerTable);
r.Add("weakness: type keyword is a whole word", TypeKeyword);
r.Add("weakness: learned element goes first, then the type order", LearnedFirst);
r.Add("weakness: UB seed ranks after server data and learned, before the type", SeedBeforeType);
}
private static void Normalize()
@ -130,4 +131,34 @@ internal static class CreatureWeaknessTests
Check.Eq(alone?.Order.Count, 1, "only the learned element");
Check.Eq(alone?.Describe(), "Fire", "describe without a multiplier");
}
private static void SeedBeforeType()
{
var type = CreatureWeakness.Rank(0, OlthoiByKeyword, 0, null);
var r = CreatureWeakness.Rank(0, OlthoiByKeyword, 0, null, new[] { "Electric", "fire", "Holy", "Fire" });
Check.NotNull(r, "ranking with a seed");
if (r == null || type == null) return;
Check.Eq(r.Source, "UB seed, then Olthoi type", "source");
Check.Eq(r.Order[0].Element, "Lightning", "seed order first (normalised)");
Check.Eq(r.Order[1].Element, "Fire", "second seed element");
Check.True(double.IsNaN(r.Order[1].Mult), "seed elements have no multiplier");
Check.Eq(r.Order.Count, 8, "unknown names dropped, no element listed twice");
var rest = new List<string>();
foreach (var (e, _) in type.Order) if (e != "Lightning" && e != "Fire") rest.Add(e);
for (int i = 0; i < rest.Count; i++)
Check.Eq(r.Order[i + 2].Element, rest[i], $"then the type order at {i + 2}");
var learned = CreatureWeakness.Rank(0, OlthoiByKeyword, 0, "Cold", new[] { "Fire" });
Check.Eq(learned?.Source, "learned, then Olthoi type", "learned element beats the seed");
Check.Eq(learned?.Order[0].Element, "Cold", "learned element first");
var row = FirstServerRow();
if (row is { } sr)
Check.Eq(CreatureWeakness.Rank(sr.Wcid, sr.Name, 0, null, new[] { "Nether" })?.Source, "server data", "server table beats the seed");
var alone = CreatureWeakness.Rank(0, Unknown, 0, null, new[] { "Acid" });
Check.Eq(alone?.Source, "UB seed", "seed with no type");
Check.Eq(alone?.Order.Count, 1, "only the seed element");
Check.True(CreatureWeakness.Rank(0, Unknown, 0, null, new[] { "Holy" }) == null, "a seed with no element is ignored");
}
}

View file

@ -1,5 +1,4 @@
using System;
using RynthCore.Plugin.RynthTracker;
using RynthCore.Plugin.Shared;
namespace RynthCore.TrackerSessionTests;

View file

@ -1,6 +1,6 @@
using System;
using System.IO;
using RynthCore.Plugin.RynthTracker;
using RynthCore.Plugin.Shared;
namespace RynthCore.TrackerSessionTests;
@ -46,6 +46,7 @@ internal static partial class Program
TestFiles();
TestCleanup();
TestKillCounter();
TestSessionStats();
Console.WriteLine($"\n{_asserts} assertions, {_fails} failed.");
if (_asserts == 0) { Console.WriteLine("ABORT: zero assertions ran."); return 1; }
@ -77,6 +78,11 @@ internal static partial class Program
RadBase = 0,
BankedBase = 77,
DrawnBase = -5,
BankLumBase = 3_900_000_000_000,
LumOwn = 5_000,
BankIncome = 9_000,
OwnSinceBank = 4_000,
RecentLum = { (Now.AddMinutes(-2).Ticks, 300), (Now.AddMinutes(-1).Ticks, 700) },
};
private static void SameState(TrackerSessionState a, TrackerSessionState b, string what)
@ -101,6 +107,11 @@ internal static partial class Program
Eq(a.RadBase, b.RadBase, what + " radbase");
Eq(a.BankedBase, b.BankedBase, what + " bankedbase");
Eq(a.DrawnBase, b.DrawnBase, what + " drawnbase");
Eq(a.BankLumBase, b.BankLumBase, what + " bankbase");
Eq(a.LumOwn, b.LumOwn, what + " lumown");
Eq(a.BankIncome, b.BankIncome, what + " bankincome");
Eq(a.OwnSinceBank, b.OwnSinceBank, what + " ownsincebank");
Eq(string.Join(";", a.RecentLum), string.Join(";", b.RecentLum), what + " recentlum");
}
// First read is the baseline; rises count; a drop only moves the baseline.
@ -130,6 +141,8 @@ internal static partial class Program
{
var s = Sample();
s.XpBase = null; s.LumBase = null; s.RadBase = null; s.BankedBase = null; s.DrawnBase = null;
s.BankLumBase = null;
s.RecentLum.Clear();
s.MaxLevel = false;
Check(TrackerSessionStore.TryParse(TrackerSessionStore.Serialize(s), out var back), "null baselines parse");
SameState(back, s, "null baselines");
@ -168,6 +181,21 @@ internal static partial class Program
Check(TrackerSessionStore.TryParse(good.Replace("\n", "\r\n"), out var crlf), "CRLF parses");
SameState(crlf, Sample(), "CRLF");
Check(TrackerSessionStore.TryParse(good.Replace("end=1", "future=thing\nend=1"), out _), "unknown key ignored");
// A save written before the 2026-10-11 keys still carries the session on.
string old = good;
foreach (string key in new[] { "bankbase", "lumown", "bankincome", "ownsincebank", "recentlum" })
{
int at = old.IndexOf("\n" + key + "=", StringComparison.Ordinal);
int end = old.IndexOf('\n', at + 1);
old = old.Remove(at, end - at);
}
Check(TrackerSessionStore.TryParse(old, out var oldBack), "save without the 2026-10-11 keys parses");
Eq(oldBack.XpTotal, Sample().XpTotal, "older save keeps its totals");
Eq(oldBack.BankLumBase, (long?)null, "older save: no bank baseline");
Eq(oldBack.RecentLum.Count, 0, "older save: no recent luminance");
Check(!TrackerSessionStore.TryParse(good.Replace("lumown=5000", "lumown=x"), out _), "malformed new key rejected");
Check(!TrackerSessionStore.TryParse(good.Replace("recentlum=", "recentlum=12"), out _), "malformed recent luminance rejected");
}
private static void TestShouldRestore()

View file

@ -16,9 +16,10 @@
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthTracker\TrackerSessionStore.cs" Link="Linked\TrackerSessionStore.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthTracker\KillCounter.cs" Link="Linked\KillCounter.cs" />
<Compile Include="..\..\Plugins\Shared\TrackerSessionStore.cs" Link="Linked\TrackerSessionStore.cs" />
<Compile Include="..\..\Plugins\Shared\KillCounter.cs" Link="Linked\KillCounter.cs" />
<Compile Include="..\..\Plugins\Shared\CombatText.cs" Link="Linked\CombatText.cs" />
<Compile Include="..\..\Plugins\Shared\SessionStats.cs" Link="Linked\SessionStats.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,224 @@
using System;
using RynthCore.Plugin.Shared;
namespace RynthCore.TrackerSessionTests;
// SessionStats (Plugins\Shared): the numbers RynthTracker and RynthAi's Mini Remote both show
// (2026-10-11). Luminance on each server kind, ACECustom pass-up, the five-minute window,
// kills / XP per kill, and a reload in the middle giving the same numbers as no reload.
internal static partial class Program
{
private static readonly DateTime S0 = new(2026, 10, 11, 12, 0, 0, DateTimeKind.Utc);
private static SessionSample Ilt(long xp, long avail, long bank) => new(xp, avail, bank, null, null, null);
private static void TestSessionStats()
{
TestLumChatLines();
TestIltBankLum();
TestIltDepositExpires();
TestChatFallbackUntilBank();
TestAelrynthAndRetailLum();
TestLumLast5Min();
TestKillsAndXpPerKill();
TestSessionStatsReloadMatches();
}
private static void TestLumChatLines()
{
Check(SessionLumChat.TryOwn("You've banked 1,234,567 Luminance.", out long a) && a == 1_234_567, "own lum line with commas");
Check(SessionLumChat.TryOwn(" You've banked 5 Luminance.\n", out long b) && b == 5, "leading space and newline");
Check(!SessionLumChat.TryOwn("Bob tells you, \"You've banked 5 Luminance.\"", out _), "a quoted line is not ours");
Check(!SessionLumChat.TryOwn("You've banked Luminance.", out _), "no amount");
Check(SessionLumChat.TryMovedIntoBank("Deposited 2,000 luminance", out long d) && d == 2_000, "deposit line");
Check(SessionLumChat.TryMovedIntoBank("Received 1,000 luminance from Bob", out long r) && r == 1_000, "transfer-in line");
Check(!SessionLumChat.TryMovedIntoBank("Transferred 1,000 Luminance to Bob", out _), "transfer out is not into the bank");
Check(!SessionLumChat.TryMovedIntoBank("No luminance available to deposit", out _), "nothing deposited");
}
// ACECustom: earned lum goes to the bank (9005); own kill / quest lum prints a line, pass-up doesn't;
// withdrawals, deposits, transfers in and spending are not income.
private static void TestIltBankLum()
{
var s = new SessionStats();
s.Reset(S0);
DateTime t = S0;
s.Sample(Ilt(1_000, 0, 1_000_000), t);
Eq(s.LumTotal, 0L, "ILT: first read is the baseline");
Check(s.BankTracked, "ILT: bank tracked after the first read");
t = t.AddSeconds(1);
s.OnChat("You've banked 500 Luminance.", t);
s.Sample(Ilt(1_100, 0, 1_000_500), t);
Eq(s.LumTotal, 500L, "ILT: own kill lum counts once (chat and bank)");
Eq(s.LumPassUp, 0L, "ILT: own lum is not pass-up");
t = t.AddSeconds(1);
s.Sample(Ilt(1_100, 0, 1_000_800), t);
Eq(s.LumTotal, 800L, "ILT: silent bank rise counts");
Eq(s.LumPassUp, 300L, "ILT: silent bank rise is pass-up");
t = t.AddSeconds(1);
s.Sample(Ilt(1_100, 10_000, 990_800), t);
Eq(s.LumTotal, 800L, "ILT: a withdrawal (character up, bank down) is not income");
t = t.AddSeconds(1);
s.OnChat("Deposited 2,000 luminance", t);
s.Sample(Ilt(1_100, 8_000, 992_800), t);
Eq(s.LumTotal, 800L, "ILT: a deposit is not income");
t = t.AddSeconds(1);
s.OnChat("Received 1,000 luminance from Bob", t);
s.Sample(Ilt(1_100, 8_000, 993_800), t);
Eq(s.LumTotal, 800L, "ILT: a transfer from another player is not income");
Eq(s.LumPassUp, 300L, "ILT: nor pass-up");
t = t.AddSeconds(1);
s.Sample(Ilt(1_100, 8_000, 993_750), t);
s.Sample(Ilt(1_100, 8_000, 993_850), t.AddSeconds(1));
Eq(s.LumTotal, 900L, "ILT: spending moves the baseline, the next rise counts");
Eq(s.LumOwn, 500L, "ILT: own lum total");
Eq(s.XpTotal, 100L, "ILT: experience rise");
}
// A deposit line with no bank rise behind it stops holding back later income after a minute.
private static void TestIltDepositExpires()
{
var s = new SessionStats();
s.Reset(S0);
s.Sample(Ilt(1, 0, 5_000), S0);
s.OnChat("Deposited 1,000 luminance", S0.AddSeconds(1));
s.Sample(Ilt(1, 0, 5_000), S0.AddSeconds(2));
s.Sample(Ilt(1, 0, 5_400), S0.AddSeconds(70));
Eq(s.LumTotal, 400L, "an expired deposit line no longer eats income");
}
// "You've banked" counts only until a bank property is read; then the bank covers it.
private static void TestChatFallbackUntilBank()
{
var s = new SessionStats();
s.Reset(S0);
s.OnChat("You've banked 400 Luminance.", S0);
Eq(s.LumTotal, 400L, "chat counts before the bank property");
s.Sample(Ilt(1, 0, 5_000), S0.AddSeconds(1));
s.OnChat("You've banked 100 Luminance.", S0.AddSeconds(2));
s.Sample(Ilt(1, 0, 5_100), S0.AddSeconds(2));
Eq(s.LumTotal, 500L, "after the bank is read the chat line doesn't count twice");
Eq(s.LumPassUp, 0L, "own lum after the bank read isn't pass-up");
}
private static void TestAelrynthAndRetailLum()
{
var ael = new SessionStats();
ael.Reset(S0);
ael.Sample(new SessionSample(1, 1_000, null, 0, 0, 0), S0);
ael.Sample(new SessionSample(1, 1_100, null, 0, 0, 0), S0.AddSeconds(1));
Eq(ael.LumTotal, 100L, "Aelrynth: character rise counts");
ael.Sample(new SessionSample(1, 1_150, null, 0, 50, 0), S0.AddSeconds(2));
Eq(ael.LumTotal, 100L, "Aelrynth: drawn from the bank is not earned");
ael.Sample(new SessionSample(1, 1_150, null, 200, 50, 7), S0.AddSeconds(3));
Eq(ael.LumTotal, 300L, "Aelrynth: auto-banked counts");
ael.OnChat("You've banked 999 Luminance.", S0.AddSeconds(4));
Eq(ael.LumTotal, 300L, "Aelrynth: chat ignored once its bank totals are read");
Eq(ael.RadTotal, 7L, "Aelrynth: Radiance rise");
Check(!ael.BankTracked, "Aelrynth: no ACECustom bank, pass-up unknown");
var retail = new SessionStats();
retail.Reset(S0);
retail.Sample(new SessionSample(1, 0, null, null, null, null), S0);
retail.Sample(new SessionSample(1, 250, null, null, null, null), S0.AddSeconds(1));
retail.Sample(new SessionSample(1, 50, null, null, null, null), S0.AddSeconds(2));
retail.Sample(new SessionSample(1, 80, null, null, null, null), S0.AddSeconds(3));
Eq(retail.LumTotal, 280L, "retail: rises count, spending doesn't");
}
private static void TestLumLast5Min()
{
var s = new SessionStats();
s.Reset(S0);
s.Sample(Ilt(1, 0, 0), S0);
s.Sample(Ilt(1, 0, 100), S0.AddSeconds(10));
s.Sample(Ilt(1, 0, 300), S0.AddMinutes(3));
Eq(s.LumLast5Min(S0.AddMinutes(3)), 300L, "both gains inside five minutes");
Eq(s.LumLast5Min(S0.AddMinutes(6)), 200L, "the first gain left the window");
Eq(s.LumLast5Min(S0.AddMinutes(9)), 0L, "both gone");
Eq(s.LumTotal, 300L, "the session total keeps them");
var v = s.View(S0.AddMinutes(30));
Eq(v.LumLast5Min, 0L, "view: last five minutes");
Check(Math.Abs(v.LumPerHour - 600) < 0.001, "view: 300 lum in half an hour = 600/h");
}
private static void TestKillsAndXpPerKill()
{
var s = new SessionStats();
s.Reset(S0);
s.Sample(Ilt(1_000, 0, 0), S0);
s.OnKillNotice("You killed the Drudge Skulker!", S0.AddSeconds(1));
s.Sample(Ilt(1_600, 0, 0), S0.AddSeconds(2));
s.Sample(Ilt(1_600, 0, 0), S0.AddSeconds(5)); // window closed
Eq(s.Kills, 1, "notice kill");
Eq(s.XpPerKill, 600L, "XP in the kill window belongs to it");
// A multi-target volley hits two monsters; one dies with no notice and leaves a corpse.
DateTime v = S0.AddSeconds(10);
s.Sample(Ilt(2_000, 0, 0), v); // unattributed XP just before the corpse
s.OnChat("You blast Drudge Slinker for 153 points with Whirling Blade VII.", v);
s.OnChat("You blast Drudge Prowler for 160 points with Whirling Blade VII.", v.AddMilliseconds(100));
var result = s.OnCorpse("Drudge Slinker", v.AddSeconds(3));
Check(result == KillCounter.CorpseResult.Counted, "corpse of a multi-target victim counts");
Eq(s.Kills, 2, "corpse kill joins the kills");
Eq(s.XpPerKill, 500L, "corpse kill takes the XP just before it: (600 + 400) / 2");
s.OnPlayerDied();
Eq(s.View(S0.AddHours(1)).Deaths, 1, "death");
}
// A reload (capture, save text, parse, apply) mid-session gives the same numbers as none.
private static void TestSessionStatsReloadMatches()
{
SessionSample[] reads =
{
Ilt(1_000, 0, 10_000), Ilt(1_500, 0, 10_400), Ilt(2_000, 0, 10_900),
Ilt(2_200, 500, 10_400), Ilt(2_900, 500, 11_600), Ilt(3_000, 500, 12_000),
};
string?[] chat = { null, "You've banked 400 Luminance.", null, null, "You've banked 200 Luminance.", null };
var straight = new SessionStats();
straight.Reset(S0);
for (int i = 0; i < reads.Length; i++)
{
DateTime t = S0.AddMinutes(i);
straight.OnChat(chat[i], t);
straight.Sample(reads[i], t);
}
var a = new SessionStats();
a.Reset(S0);
SessionStats current = a;
for (int i = 0; i < reads.Length; i++)
{
DateTime t = S0.AddMinutes(i);
if (i == 3)
{
var st = Sample();
current.CaptureInto(st, t);
Check(TrackerSessionStore.TryParse(TrackerSessionStore.Serialize(st), out var back), "stats save parses");
current = new SessionStats();
current.ApplyFrom(back);
}
current.OnChat(chat[i], t);
current.Sample(reads[i], t);
}
DateTime end = S0.AddMinutes(reads.Length);
var x = straight.View(end);
var y = current.View(end);
Eq(y.Xp, x.Xp, "reload: XP");
Eq(y.Lum, x.Lum, "reload: luminance");
Eq(y.LumPassUp, x.LumPassUp, "reload: pass-up");
Eq(y.LumLast5Min, x.LumLast5Min, "reload: last five minutes");
Eq(y.SessionStartUtc, x.SessionStartUtc, "reload: session start");
Eq(x.Lum, 2_500L, "lum: bank rises 400 + 500 + 1,200 + 400; the withdrawal isn't income");
Eq(x.LumPassUp, 1_900L, "pass-up: bank income 2,500 minus own 600");
}
}

View file

@ -0,0 +1,179 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Plugin.Shared;
namespace RynthLua.CompatTests;
/// <summary>
/// A fake "RynthAi.Combat" table (Shared/RynthAiCombatApi.cs) for the compat tests: the same
/// lease, owner, poll and decide rules as RynthAi's CombatHook, served by FakeHost's
/// GetPluginInterface while <see cref="Enabled"/> is set. The test script drives it through
/// the harness (open a request, read the decisions, the claim and release counts).
/// </summary>
internal static unsafe class FakeCombat
{
public sealed record Decision(uint Seq, uint Kind, uint Spell, uint Target, uint Flags, bool Taken);
/// <summary>Served by GetPluginInterface (off: RynthAi without the hook, an older build).</summary>
public static bool Enabled;
public static string Owner = "";
public static uint Kinds;
public static long LeaseUntil;
public static int Claims, Refusals, Releases;
public static uint ReleasedKinds; // every kind a Release named, or'ed
public static readonly List<Decision> Decisions = new();
public static readonly List<(uint Id, float Distance)> Scanned = new();
private sealed class Req { public CombatRequestV1 R; public bool Open, Decided; }
private static readonly Dictionary<uint, Req> Slots = new();
private static uint _seq;
private static RynthAiCombatApiV1* _table;
private static long Now => Environment.TickCount64;
/// <summary>Per kind, as RynthAi's CombatHook: the taken cast in flight, and the most recent resolved one (Err -1 = no answer read).</summary>
private sealed class Cast { public uint Seq, Spell, Target; public long At; public int Err = -1; }
private static readonly Dictionary<uint, Cast> InFlight = new(), Resolved = new();
/// <summary>OlderRynthAi: a RynthAi from before the resolved/pending fields (writes none of them).</summary>
public static bool OlderRynthAi;
/// <summary>The server answers the cast in flight of <paramref name="kind"/> (err -1: no answer read).</summary>
public static void ResolveInFlight(uint kind, int err)
{
if (!InFlight.Remove(kind, out var c)) return;
c.Err = err;
Resolved[kind] = c;
}
public static void Reset()
{
InFlight.Clear(); Resolved.Clear();
OlderRynthAi = false;
Enabled = false;
Owner = "";
Kinds = 0;
LeaseUntil = 0;
Claims = Refusals = Releases = 0;
ReleasedKinds = 0;
Decisions.Clear();
Scanned.Clear();
Slots.Clear();
}
/// <summary>RynthAi reloaded: its seq restarts and nothing is claimed or open (the table stays served).</summary>
public static void Reload()
{
_seq = 0;
Slots.Clear();
Owner = "";
Kinds = 0;
LeaseUntil = 0;
}
public static IntPtr Table()
{
if (!Enabled) return IntPtr.Zero;
if (_table == null)
{
var t = (RynthAiCombatApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiCombatApiV1));
t->Version = RynthAiCombatApiV1.InterfaceVersion;
t->StructSize = (uint)sizeof(RynthAiCombatApiV1);
t->Claim = &Claim;
t->Release = &Release;
t->Poll = &Poll;
t->Decide = &Decide;
t->GetScanned = &GetScanned;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>Opens a request of <paramref name="kind"/> (RynthAi reaching a cast choice). Returns its seq.</summary>
public static uint Open(uint kind, uint targetId, long timeoutMs = 2000)
{
uint seq = ++_seq;
var r = new CombatRequestV1
{
StructSize = (uint)sizeof(CombatRequestV1), Seq = seq, Kind = kind, TargetId = targetId,
TargetHealth = kind == RynthAiCombat.KindAttack ? 0.5f : -1f, HealthPct = 80, StaminaPct = 70, ManaPct = 60,
HealLine = kind == RynthAiCombat.KindHeal ? 60 : 0, InCombat = 1, CombatMode = 8,
IssuedAtMs = Now, DeadlineMs = Now + timeoutMs, ResolvedErr = -1,
};
if (Slots.TryGetValue(kind, out var old) && old.Decided)
{
r.LastSeq = old.R.Seq;
Decision? d = Decisions.FindLast(x => x.Seq == old.R.Seq && x.Taken);
r.LastSpell = d?.Spell ?? 0;
r.LastTarget = d?.Target ?? 0;
r.LastAtMs = Now;
if (r.LastSpell != 0)
{
ResolveInFlight(kind, -1); // the cast before it, still unanswered: no answer read
InFlight[kind] = new Cast { Seq = old.R.Seq, Spell = r.LastSpell, Target = r.LastTarget, At = Now };
}
}
if (Resolved.TryGetValue(kind, out var rc)) { r.ResolvedSeq = rc.Seq; r.ResolvedSpell = rc.Spell; r.ResolvedTarget = rc.Target; r.ResolvedAtMs = rc.At; r.ResolvedErr = rc.Err; }
if (InFlight.TryGetValue(kind, out var pc)) { r.PendingSeq = pc.Seq; r.PendingSpell = pc.Spell; r.PendingTarget = pc.Target; r.PendingAtMs = pc.At; }
Slots[kind] = new Req { R = r, Open = true };
return seq;
}
private static bool Active(uint kind) => (Kinds & kind) != 0 && Now < LeaseUntil;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Claim(uint kinds, uint leaseMs, uint attackTimeoutMs, uint healTimeoutMs, byte* owner)
{
string name = owner == null ? "" : Marshal.PtrToStringUTF8((IntPtr)owner) ?? "";
kinds &= RynthAiCombat.KindsAll;
if (Kinds != 0 && Now < LeaseUntil && Owner != name) { Refusals++; return 0; }
Claims++;
Owner = kinds == 0 ? "" : name;
Kinds = kinds;
LeaseUntil = kinds == 0 ? 0 : Now + RynthAiCombat.ClampLease(leaseMs);
return (int)kinds;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void Release(uint kinds)
{
Releases++;
ReleasedKinds |= kinds;
Kinds &= ~kinds;
if (Kinds == 0) { Owner = ""; LeaseUntil = 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Poll(uint kind, CombatRequestV1* req)
{
if (req == null || !Active(kind) || !Slots.TryGetValue(kind, out var s) || !s.Open || s.Decided || Now > s.R.DeadlineMs) return 0;
uint room = req->StructSize == 0 || req->StructSize > (uint)sizeof(CombatRequestV1) ? (uint)sizeof(CombatRequestV1) : req->StructSize;
if (OlderRynthAi) room = Math.Min(room, (uint)Marshal.OffsetOf<CombatRequestV1>(nameof(CombatRequestV1.ResolvedSeq))); // writes none of the appended fields
CombatRequestV1 r = s.R;
r.StructSize = room;
Buffer.MemoryCopy(&r, req, room, room);
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Decide(uint seq, uint kind, uint spellId, uint targetId, uint flags)
{
bool taken = Active(kind) && Slots.TryGetValue(kind, out var s) && s.Open && !s.Decided && s.R.Seq == seq && Now <= s.R.DeadlineMs;
if (taken) Slots[kind].Decided = true;
Decisions.Add(new Decision(seq, kind, spellId, targetId, flags, taken));
return taken ? 1 : 0;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetScanned(uint* ids, float* distances, int capacity)
{
if (ids != null)
for (int i = 0; i < Scanned.Count && i < capacity; i++)
{
ids[i] = Scanned[i].Id;
if (distances != null) distances[i] = Scanned[i].Distance;
}
return Scanned.Count;
}
}

View file

@ -137,7 +137,12 @@ internal static unsafe class FakeHost
private static IntPtr GetAccountName() => Ansi("testaccount");
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr GetPluginInterface(IntPtr plugin, IntPtr iface, uint version) => IntPtr.Zero;
private static IntPtr GetPluginInterface(IntPtr plugin, IntPtr iface, uint version)
{
// RynthAi's combat hook when a test turned it on (FakeCombat); nothing else is served.
string p = Marshal.PtrToStringAnsi(plugin) ?? string.Empty, i = Marshal.PtrToStringAnsi(iface) ?? string.Empty;
return p == "RynthAi" && i == RynthCore.Plugin.Shared.RynthAiCombatApiV1.InterfaceName && version == 1 ? FakeCombat.Table() : IntPtr.Zero;
}
// ── Objects ─────────────────────────────────────────────────────────────

View file

@ -22,11 +22,20 @@ internal static class Harness
private static FakeWorld W => FakeWorld.W;
/// <summary>Plugins\RynthCore.Plugin.RynthLua\Examples\<paramref name="file"/>, found from this source file's folder.</summary>
private static string ExamplePath(string file, [System.Runtime.CompilerServices.CallerFilePath] string source = "")
{
string tools = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(source) ?? string.Empty) ?? string.Empty;
string root = System.IO.Path.GetDirectoryName(tools) ?? string.Empty;
return System.IO.Path.Combine(root, "Plugins", "RynthCore.Plugin.RynthLua", "Examples", System.IO.Path.GetFileName(file));
}
public static void Reset()
{
Checks = 0;
Failures.Clear();
Done = false;
FakeCombat.Reset();
}
public static void Register(Script s, string scriptName)
@ -216,6 +225,55 @@ internal static class Harness
foreach (uint id in W.SalvageItems) t.Append(DynValue.NewNumber(id));
return DynValue.NewTable(t);
});
// RynthAi's combat hook (FakeCombat): turn the table on/off, open a request as RynthAi
// would, and read back what RynthLua claimed, decided and released.
Fn("combatTable", a => { FakeCombat.Enabled = a.Count > 0 && a[0].CastToBool(); return DynValue.Nil; });
Fn("combatOpen", a => DynValue.NewNumber(FakeCombat.Open((uint)Num(a, 0, 1), Id(a, 1), (long)Num(a, 2, 2000))));
Fn("combatResolve", a => { FakeCombat.ResolveInFlight(RynthCore.Plugin.Shared.RynthAiCombat.KindAttack, (int)Num(a, 0, -1)); return DynValue.Nil; });
Fn("combatOlderRynthAi", a => { FakeCombat.OlderRynthAi = a.Count > 0 && a[0].CastToBool(); return DynValue.Nil; });
Fn("combatScanned", a =>
{
FakeCombat.Scanned.Clear();
if (a.Count > 0 && a[0].Type == DataType.Table)
foreach (DynValue row in a[0].Table.Values)
FakeCombat.Scanned.Add(((uint)row.Table.Get(1).Number, (float)row.Table.Get(2).Number));
return DynValue.Nil;
});
Fn("combatDecisions", a =>
{
var t = new Table(s);
foreach (var d in FakeCombat.Decisions)
{
var row = new Table(s);
row["seq"] = (double)d.Seq; row["kind"] = (double)d.Kind; row["spell"] = (double)d.Spell;
row["target"] = (double)d.Target; row["flags"] = (double)d.Flags; row["taken"] = d.Taken;
t.Append(DynValue.NewTable(row));
}
return DynValue.NewTable(t);
});
Fn("combatState", a =>
{
var t = new Table(s);
t["owner"] = FakeCombat.Owner; t["kinds"] = (double)FakeCombat.Kinds;
t["claims"] = (double)FakeCombat.Claims; t["refusals"] = (double)FakeCombat.Refusals;
t["releases"] = (double)FakeCombat.Releases; t["releasedKinds"] = (double)FakeCombat.ReleasedKinds;
return DynValue.NewTable(t);
});
// A second script in the same plugin (another script competing for a handler).
Fn("runScript", a => { Plugin!.RunCode(Str(a, 0), Str(a, 1)); return DynValue.Nil; });
Fn("stopScript", a => DynValue.NewBoolean(Plugin!.StopScript(Str(a, 0))));
Fn("scriptLoaded", a => DynValue.NewBoolean(Plugin!.ScriptIsLoaded(Str(a, 0))));
Fn("scriptConsole", a => DynValue.NewString(Plugin!.ScriptConsoleText(Str(a, 0))));
Fn("combatReload", a => { FakeCombat.Reload(); return DynValue.Nil; });
// The text of a script in the plugin's Examples folder (so a test can run it).
Fn("exampleCode", a => DynValue.NewString(System.IO.File.ReadAllText(ExamplePath(Str(a, 0)))));
Fn("scriptHooks", a =>
{
var (keepAlive, onStop) = Plugin!.ScriptHookCounts(Str(a, 0));
var t = new Table(s);
t["keepAlive"] = (double)keepAlive; t["onStop"] = (double)onStop;
return DynValue.NewTable(t);
});
s.Globals["harness"] = DynValue.NewTable(h);
}
}

View file

@ -28,6 +28,7 @@
<ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthLua\**\*.cs" Exclude="..\..\Plugins\RynthCore.Plugin.RynthLua\obj\**;..\..\Plugins\RynthCore.Plugin.RynthLua\bin\**" Link="Plugin\%(RecursiveDir)%(Filename)%(Extension)" />
<Compile Include="..\..\Plugins\Shared\RynthAiScriptApi.cs" Link="Plugin\Shared\RynthAiScriptApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiCombatApi.cs" Link="Plugin\Shared\RynthAiCombatApi.cs" />
<Compile Include="..\..\Plugins\Shared\UseAudit.cs" Link="Plugin\Shared\UseAudit.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\*.cs" Link="Sdk\%(Filename)%(Extension)" />
<!-- The SDK takes CurrentApiVersion from the engine's constant since plugin manifests (API v79). -->

View file

@ -0,0 +1,345 @@
-- RynthAi's combat hook from a script (rynth.ai SetAttackHandler / SetHealHandler, RynthLua's
-- CombatHookPump against a fake "RynthAi.Combat" table): the handler's answer reaches Decide, a
-- yielding handler still answers, an error declines, three in a row unregister, one script per
-- kind, a stopped script releases its kinds, and no table means a refusal with the reason.
local ai = require("rynth.ai")
local ATTACK, HEAL = 1, 2
local function decisions() return harness.combatDecisions() end
local function waitDecisions(n)
return waitfor(function() return #decisions() >= n end, 3000)
end
-- No table: RynthAi without the hook (or not loaded).
harness.combatTable(false)
local ok, why = ai.SetAttackHandler(function() return 1 end)
eq(ok, false, "no combat table: refused")
eq(why, "RynthAi has no combat hook", "and says why")
eq(ai.CombatHook.Supported, false, "CombatHook.Supported is false")
eq(ai.CombatHook.AttackOwner, nil, "no owner")
harness.combatTable(true)
sleep(10) -- RynthLua looks the table up again on its next tick
eq(ai.CombatHook.Supported, true, "table on: supported")
-- 1. A decision is posted, with the request's context.
local seen
ok = ai.SetAttackHandler(function(ctx)
seen = ctx
return 1234, ctx.monsters[2].id
end)
eq(ok, true, "attack handler registered")
eq(ai.CombatHook.AttackOwner, "combathook", "the owner is this script")
check(waitfor(function() return harness.combatState().kinds == ATTACK end, 2000), "the pump claims the attack kind")
eq(harness.combatState().owner, "RynthLua/combathook", "claimed under RynthLua/<script>")
eq(ai.CombatHook.Claimed, true, "Claimed")
harness.combatScanned({ { 0x80000101, 3.5 }, { 0x80000102, 7.25 } })
local seq1 = harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(1), "the handler answered")
local d = decisions()[1]
eq(d.seq, seq1, "decided for the open seq")
eq(d.kind, ATTACK, "attack kind")
eq(d.spell, 1234, "the handler's spell")
eq(d.target, 0x80000102, "the handler's target")
eq(d.flags, 0, "no flags")
eq(d.taken, true, "taken by RynthAi")
eq(seen.seq, seq1, "ctx.seq")
eq(seen.kind, "attack", "ctx.kind")
eq(seen.targetId, 0x80000101, "ctx.targetId")
eq(seen.targetHealth, 0.5, "ctx.targetHealth")
eq(seen.healthPct, 80, "ctx.healthPct")
eq(seen.inCombat, true, "ctx.inCombat")
eq(seen.combatMode, 8, "ctx.combatMode")
check(seen.deadline > seen.issuedAt, "ctx.deadline after ctx.issuedAt")
check(seen.deadline > clock(), "ctx.deadline is on clock()'s scale and still ahead")
eq(#seen.monsters, 2, "ctx.monsters")
eq(seen.monsters[1].distance, 3.5, "ctx.monsters[1].distance")
eq(seen.last.seq, 0, "no resolved cast yet")
eq(seen.pending, nil, "nothing in flight yet")
-- ctx.pending: the cast in flight; ctx.last: the most recent RESOLVED cast, err final.
local seq2 = harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(2), "second request answered")
eq(seen.pending.seq, seq1, "ctx.pending.seq: the first cast, no answer yet")
eq(seen.pending.spell, 1234, "ctx.pending.spell")
eq(seen.pending.target, 0x80000102, "ctx.pending.target")
eq(seen.last.seq, 0, "ctx.last: still no resolved cast")
eq(seen.last.err, nil, "ctx.last.err: nil before the first resolved cast")
harness.combatResolve(0x1D) -- the first cast's UseDone: 0x1D
local seqE = harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(3), "third request answered")
eq(seen.last.seq, seq1, "ctx.last: the first cast, now resolved")
eq(seen.last.spell, 1234, "ctx.last.spell")
eq(seen.last.target, 0x80000102, "ctx.last.target")
eq(seen.last.err, 29, "ctx.last.err = 0x1D (refused 'too busy')")
eq(seen.pending.seq, seq2, "ctx.pending: the second cast")
-- No answer for the second before the third went out: resolved with no answer (nil).
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(4), "fourth request answered")
eq(seen.last.seq, seq2, "ctx.last: the second cast")
eq(seen.last.err, nil, "no answer read for it: nil")
eq(seen.pending.seq, seqE, "ctx.pending: the third cast")
harness.combatResolve(0)
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(5), "fifth request answered")
eq(seen.last.seq, seqE, "ctx.last: the third cast")
eq(seen.last.err, 0, "ctx.last.err = 0 (done)")
harness.combatResolve(0x1D)
harness.combatOlderRynthAi(true)
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(6), "older RynthAi request answered")
eq(seen.last.err, nil, "an older RynthAi: no err")
eq(seen.pending, nil, "an older RynthAi: no pending")
check(seen.last.seq > seqE, "an older RynthAi: ctx.last is its last decision")
harness.combatOlderRynthAi(false)
-- 2. A yielding handler (the same script registering again replaces its handler), area flag.
ok = ai.SetAttackHandler(function(ctx)
sleep(60)
return 55, nil, "area"
end)
eq(ok, true, "the same script replaces its handler")
local seq3 = harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(7), "the yielding handler still answers")
d = decisions()[7]
eq(d.seq, seq3, "for its seq")
eq(d.spell, 55, "its spell")
eq(d.target, 0, "nil target = the request's target")
eq(d.flags, 1, "\"area\" sets the AREA flag")
eq(d.taken, true, "taken")
-- 3. nil declines.
ai.SetAttackHandler(function(ctx) return nil end)
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(8), "a nil answer is still an answer")
eq(decisions()[8].spell, 0, "nil = decline (spell 0)")
-- 4. An error declines at once; three in a row unregister.
ai.SetAttackHandler(function(ctx) error("boom (expected)") end)
for i = 1, 3 do
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(8 + i), "error " .. i .. ": declined at once")
eq(decisions()[8 + i].spell, 0, "error " .. i .. ": spell 0")
eq(decisions()[8 + i].taken, true, "error " .. i .. ": taken (no wait for the deadline)")
end
eq(ai.CombatHook.AttackOwner, nil, "three errors: the handler is removed")
check(waitfor(function() return harness.combatState().kinds == 0 end, 2000), "and the kind released in RynthAi")
local unregistered = false
for _, line in ipairs(harness.chatLog()) do
if line:find("failed 3 times in a row", 1, true) then unregistered = true end
end
check(unregistered, "a chat warning says so")
check(harness.scriptConsole("combathook"):find("combat attack handler failed (declined; 3/3 in a row)", 1, true) ~= nil, "each error is in the console")
local _, booms = harness.scriptConsole("combathook"):gsub("boom %(expected%)", "")
eq(booms, 3, "each Lua error's message is printed once (by the script host), not again by the pump")
-- A bad answer counts as an error too (and declines).
ai.SetAttackHandler(function(ctx) return "fireball" end)
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(12), "a bad answer declines")
eq(decisions()[12].spell, 0, "spell 0")
check(harness.scriptConsole("combathook"):find("expected a spell id", 1, true) ~= nil, "and says what was wrong")
ai.ClearCombatHandlers()
eq(ai.CombatHook.AttackOwner, nil, "ClearCombatHandlers drops it")
-- 5. One script per kind; a stopped script releases its kinds.
ok = ai.SetHealHandler(function(ctx) return 2001, 0 end)
eq(ok, true, "heal handler registered")
harness.runScript("rival", [[
local ai = require("rynth.ai")
local ok, why = ai.SetHealHandler(function(ctx) return 9 end)
eq(ok, false, "rival: the heal kind is taken")
eq(why, "the heal handler is already set by combathook", "rival: and by whom")
ok = ai.SetAttackHandler(function(ctx) return 777 end)
eq(ok, true, "rival: the attack kind is free")
rivalReady = true
]])
check(waitfor(function() return ai.CombatHook.AttackOwner == "rival" end, 2000), "the rival holds attack")
eq(ai.CombatHook.HealOwner, "combathook", "this script still holds heal")
check(waitfor(function() return harness.combatState().kinds == ATTACK + HEAL end, 2000), "both kinds claimed")
eq(harness.combatState().owner, "RynthLua/combathook+rival", "under both scripts' names")
check(harness.scriptLoaded("rival"), "the rival's main chunk ended but its handler keeps it running")
local healSeq = harness.combatOpen(HEAL, 0)
check(waitDecisions(13), "heal answered")
eq(decisions()[13].seq, healSeq, "heal seq")
eq(decisions()[13].kind, HEAL, "heal kind")
eq(decisions()[13].spell, 2001, "heal spell")
local releasesBefore = harness.combatState().releases
check(harness.stopScript("rival"), "stop the rival")
check(not harness.scriptLoaded("rival"), "stopped")
check(harness.combatState().releases > releasesBefore, "stopping it released in RynthAi")
check(harness.combatState().releasedKinds % 2 == 1, "the attack kind among the released")
eq(ai.CombatHook.AttackOwner, nil, "attack is free again")
eq(ai.CombatHook.HealOwner, "combathook", "heal untouched")
check(waitfor(function() return harness.combatState().kinds == HEAL end, 2000), "only heal claimed now")
-- SetHealHandler(nil) clears this script's heal handler.
ai.SetHealHandler(nil)
eq(ai.CombatHook.HealOwner, nil, "nil clears it")
check(waitfor(function() return harness.combatState().kinds == 0 end, 2000), "nothing claimed")
-- 6. Flags: "nojudge", a table of flags, true = area; an unknown flag is an error.
local function answerWith(fn)
ai.SetAttackHandler(fn)
local n = #decisions()
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(n + 1), "answered")
return decisions()[n + 1]
end
eq(answerWith(function() return 55, nil, "nojudge" end).flags, 2, "\"nojudge\" sets the NOJUDGE flag")
eq(answerWith(function() return 55, nil, { area = true, nojudge = true } end).flags, 3, "a table sets both")
eq(answerWith(function() return 55, nil, { nojudge = true, area = false } end).flags, 2, "a false field is no flag")
eq(answerWith(function() return 55, nil, true end).flags, 1, "true is still \"area\"")
d = answerWith(function() return 55, nil, "aera" end)
eq(d.spell, 0, "an unknown flag declines")
check(harness.scriptConsole("combathook"):find('expected "area", "nojudge"', 1, true) ~= nil, "and says what it expected")
ai.ClearCombatHandlers()
-- 7. Set/clear cycles register the script's KeepAlive / OnStop hooks once, not once per cycle.
ai.SetAttackHandler(function() return nil end)
local hooks = harness.scriptHooks("combathook")
check(hooks.keepAlive >= 1 and hooks.onStop >= 1, "the hooks are registered")
for i = 1, 3 do
ai.ClearCombatHandlers()
ai.SetAttackHandler(function() return nil end)
ai.SetHealHandler(function() return nil end)
end
local after = harness.scriptHooks("combathook")
eq(after.keepAlive, hooks.keepAlive, "no KeepAlive hook added by the cycles")
eq(after.onStop, hooks.onStop, "no OnStop hook added by the cycles")
ai.ClearCombatHandlers()
check(waitfor(function() return harness.combatState().kinds == 0 end, 2000), "nothing claimed")
-- 8. A handler that never returns is aborted after the deadline plus the stall budget and counts
-- as an error; three in a row remove it and release the kind.
ai.SetAttackHandler(function(ctx) while true do sleep(50) end end)
check(waitfor(function() return harness.combatState().kinds == ATTACK end, 2000), "the stalling handler's kind is claimed")
for i = 1, 3 do
local n = #decisions()
local t0 = clock()
harness.combatOpen(ATTACK, 0x80000101, 100)
check(waitDecisions(n + 1), "stall " .. i .. ": the stuck handler is aborted and declines")
eq(decisions()[n + 1].spell, 0, "stall " .. i .. ": spell 0")
check(clock() - t0 >= 1000, "stall " .. i .. ": only after the deadline plus the stall budget")
end
eq(ai.CombatHook.AttackOwner, nil, "three stalls: the handler is removed")
check(waitfor(function() return harness.combatState().kinds == 0 end, 2000), "and the kind released in RynthAi")
local stalledLine = false
for _, line in ipairs(harness.chatLog()) do
if line:find("did not answer within the deadline 3 times in a row", 1, true) then stalledLine = true end
end
check(stalledLine, "a chat line says the handler did not answer within the deadline")
check(harness.scriptConsole("combathook"):find("the handler did not answer within the deadline", 1, true) ~= nil, "each stall is in the console")
-- 8b. A handler that answers after the deadline but within the stall budget: RynthAi has already
-- chosen for itself, so the answer is wasted. It declines and counts as a stall; three in a row
-- remove the handler.
ai.SetAttackHandler(function(ctx) sleep(300); return 4321 end)
check(waitfor(function() return harness.combatState().kinds == ATTACK end, 2000), "the late handler's kind is claimed")
for i = 1, 3 do
local n = #decisions()
local t0 = clock()
harness.combatOpen(ATTACK, 0x80000101, 100)
check(waitDecisions(n + 1), "late " .. i .. ": an answer comes")
eq(decisions()[n + 1].spell, 0, "late " .. i .. ": declined (spell 0), not its late spell")
check(clock() - t0 < 1000, "late " .. i .. ": at the late answer, not after the stall budget")
end
eq(ai.CombatHook.AttackOwner, nil, "three late answers: the handler is removed")
check(waitfor(function() return harness.combatState().kinds == 0 end, 2000), "and the kind released in RynthAi")
check(harness.scriptConsole("combathook"):find("answered after the deadline", 1, true) ~= nil, "each late answer is in the console")
-- Control: the same handler with a deadline it meets is taken and keeps its kind.
ai.SetAttackHandler(function(ctx) sleep(300); return 4321 end)
check(waitfor(function() return harness.combatState().kinds == ATTACK end, 2000), "claimed again")
for i = 1, 3 do
local n = #decisions()
harness.combatOpen(ATTACK, 0x80000101, 2000)
check(waitDecisions(n + 1), "in time " .. i .. ": answered")
eq(decisions()[n + 1].spell, 4321, "in time " .. i .. ": its spell")
end
eq(ai.CombatHook.AttackOwner, "combathook", "answers in time: the handler stays")
ai.ClearCombatHandlers()
check(waitfor(function() return harness.combatState().kinds == 0 end, 2000), "nothing claimed")
-- 9. RynthAi reloads (its seq restarts): a new request whose seq repeats the last one started is
-- still answered.
ai.SetAttackHandler(function(ctx) return 4242 end)
harness.combatReload()
local before = #decisions()
eq(harness.combatOpen(ATTACK, 0x80000101), 1, "after a reload the first request is seq 1")
check(waitDecisions(before + 1), "answered")
harness.combatReload() -- again: the next request is seq 1 too, the same seq as the last one started
before = #decisions()
eq(harness.combatOpen(ATTACK, 0x80000101), 1, "seq 1 again")
check(waitDecisions(before + 1), "the repeated seq is still answered (it is a new request)")
eq(decisions()[before + 1].spell, 4242, "with the handler's spell")
eq(decisions()[before + 1].taken, true, "taken")
ai.ClearCombatHandlers()
-- 10. Replacing a handler while it is still answering: the new one answers the open request.
local slowStarted = false
ai.SetAttackHandler(function(ctx) slowStarted = true; sleep(400); return 11 end)
check(waitfor(function() return harness.combatState().kinds == ATTACK end, 2000), "claimed")
before = #decisions()
harness.combatOpen(ATTACK, 0x80000101)
check(waitfor(function() return slowStarted end, 2000), "the slow handler is running")
ai.SetAttackHandler(function(ctx) return 77 end)
check(waitDecisions(before + 1), "the replacement answers the open request")
eq(decisions()[before + 1].spell, 77, "the new handler's answer")
eq(decisions()[before + 1].taken, true, "taken")
sleep(500)
eq(#decisions(), before + 1, "the replaced handler's answer never arrives")
ai.ClearCombatHandlers()
check(waitfor(function() return harness.combatState().kinds == 0 end, 2000), "nothing claimed")
-- 11. Examples\combat-handler.lua, with its spell ids and lines set.
local example = harness.exampleCode("combat-handler.lua")
local code = example
local n1, n2, n3, n4
code, n1 = code:gsub("local FINISHER_SPELL = 0", "local FINISHER_SPELL = 3001", 1)
code, n2 = code:gsub("local FINISH_BELOW = 0%.30", "local FINISH_BELOW = 0.60", 1)
code, n3 = code:gsub("local HEAL_SPELL = 0", "local HEAL_SPELL = 3002", 1)
code, n4 = code:gsub("local HEAL_BELOW = 50", "local HEAL_BELOW = 90", 1)
eq(n1 + n2 + n3 + n4, 4, "example: its four settings found")
harness.runScript("combat-handler", code)
check(waitfor(function() return ai.CombatHook.AttackOwner == "combat-handler" and ai.CombatHook.HealOwner == "combat-handler" end, 2000),
"example: holds attack and heal")
check(harness.scriptConsole("combat-handler"):find("combat handlers on", 1, true) ~= nil, "example: says it is on")
before = #decisions()
harness.combatOpen(ATTACK, 0x80000101) -- target health 0.5, under its 0.60
check(waitDecisions(before + 1), "example: attack answered")
eq(decisions()[before + 1].spell, 3001, "example: its finisher under the line")
eq(decisions()[before + 1].target, 0, "example: at RynthAi's target")
harness.combatOpen(HEAL, 0) -- health 80%, under its 90
check(waitDecisions(before + 2), "example: heal answered")
eq(decisions()[before + 2].spell, 3002, "example: its heal under the line")
eq(decisions()[before + 2].target, 0, "example: on yourself")
harness.chatInput("/combathook")
check(waitfor(function() return ai.CombatHook.AttackOwner == nil and harness.combatState().kinds == 0 end, 2000), "example: /combathook turns it off")
harness.chatInput("/combathook")
check(waitfor(function() return ai.CombatHook.AttackOwner == "combat-handler" end, 2000), "example: and on again")
check(harness.stopScript("combat-handler"), "example: stopped")
eq(ai.CombatHook.AttackOwner, nil, "example: stopping releases attack")
eq(ai.CombatHook.HealOwner, nil, "example: and heal")
-- As shipped (ids 0) it declines; a kind held by another script is refused with the reason.
ai.SetAttackHandler(function() return nil end)
harness.runScript("combat-handler", example)
check(waitfor(function() return ai.CombatHook.HealOwner == "combat-handler" end, 2000), "shipped example: holds heal")
check(harness.scriptConsole("combat-handler"):find("attack handler refused: the attack handler is already set by combathook", 1, true) ~= nil,
"shipped example: prints why attack was refused")
before = #decisions()
harness.combatOpen(HEAL, 0)
check(waitDecisions(before + 1), "shipped example: heal answered")
eq(decisions()[before + 1].spell, 0, "shipped example: no heal id set, so it declines")
harness.stopScript("combat-handler")
ai.ClearCombatHandlers()
done()

View file

@ -0,0 +1,135 @@
-- "/lua <name> [args]" runs a script's game.RegisterCommand("/name") handler. In a Decal
-- (bridge-mode) client the engine only forwards /lua to the plugin, so this is the only way
-- to reach a script command there. Built-in /lua verbs always win over a script command.
local calls = {}
game.RegisterCommand("/demo", function(args) calls[#calls + 1] = args end)
game.RegisterCommand("/list", function(args) calls[#calls + 1] = "SHADOW:" .. args end)
local function settle(ms)
local t = 0
while t < ms do sleep(20); t = t + 20 end
end
local function chatHas(needle)
for _, l in ipairs(harness.chatLog()) do
if string.find(l, needle, 1, true) then return true end
end
return false
end
-- 1. a script command through /lua: eaten, runs once, with the rest of the line
harness.clearCalls()
check(harness.chatInput("/lua demo status"), "/lua demo status is eaten")
settle(300)
eq(#calls, 1, "/lua demo status ran the /demo handler exactly once")
eq(calls[1], "status", "the handler got args 'status'")
check(not chatHas("/lua list | start"), "no usage text when a script owns the command")
-- no args and mixed case (owners are case-insensitive, args keep their case)
harness.chatInput("/lua DEMO")
settle(300)
eq(#calls, 2, "/lua DEMO ran the handler")
eq(calls[2], "", "no args gives an empty string")
harness.chatInput("/lua demo Two Words")
settle(300)
eq(calls[3], "Two Words", "args pass through unchanged")
-- 2. an unknown name prints usage and runs nothing
harness.clearCalls()
local before = #calls
harness.chatInput("/lua nosuchcmd x")
settle(300)
eq(#calls, before, "an unknown command ran no handler")
check(chatHas("/lua list | start"), "an unknown command prints usage")
check(chatHas("registered: demo."), "usage lists the registered script commands")
harness.clearCalls()
harness.chatInput("/lua")
settle(300)
check(chatHas("/lua list | start"), "bare /lua prints usage")
-- 3. a built-in verb is not shadowed by a script command of the same name
harness.clearCalls()
before = #calls
harness.chatInput("/lua list")
settle(300)
eq(#calls, before, "/lua list did not run the script's /list handler")
check(chatHas("Scripts ("), "/lua list ran the built-in list")
-- typed natively, the script's own /list is still its own
check(harness.chatInput("/list direct"), "a typed /list still reaches the script")
settle(300)
eq(calls[#calls], "SHADOW:direct", "typed /list ran the script handler")
-- 4. the slash form the usage text shows is accepted too
harness.clearCalls()
before = #calls
harness.chatInput("/lua /demo hi")
settle(300)
eq(#calls, before + 1, "/lua /demo hi ran the handler once")
eq(calls[#calls], "hi", "/lua /demo hi: args 'hi'")
-- 5. odd spacing and quoted args pass through; the line is trimmed
before = #calls
harness.chatInput(" /lua demo hi there ")
settle(300)
eq(#calls, before + 1, "extra spaces: ran once")
eq(calls[#calls], "hi there", "extra spaces: args trimmed at the ends only")
harness.chatInput("/lua demo say \"hello world\" 'x'")
settle(300)
eq(calls[#calls], "say \"hello world\" 'x'", "quotes are not interpreted")
-- 6. the usage lists names in the form the fallback accepts, minus the unreachable ones
harness.clearCalls()
harness.chatInput("/lua nosuchcmd")
settle(300)
local summary
for _, l in ipairs(harness.chatLog()) do
summary = summary or string.match(l, "registered: ([^%.]*)%.")
end
check(summary ~= nil, "usage has a registered: list")
check(string.find(summary or "", "demo", 1, true) ~= nil, "the list names demo")
check(string.find(summary or "", "/", 1, true) == nil, "the list has no slash: " .. tostring(summary))
check(string.find(summary or "", "list", 1, true) == nil, "a script /list is left out (it is a built-in verb)")
-- and every name it shows really works
harness.clearCalls()
before = #calls
harness.chatInput("/lua " .. summary)
settle(300)
eq(#calls, before + 1, "the listed form runs the handler")
-- 7. a script command named like a built-in verb is not reachable through /lua
game.RegisterCommand("/exec", function(args) calls[#calls + 1] = "SHADOW-EXEC:" .. args end)
harness.clearCalls()
before = #calls
harness.chatInput("/lua exec return 1")
harness.chatInput("/lua /exec return 1")
settle(300)
eq(#calls, before, "/lua exec did not run the script's /exec handler")
game.UnregisterCommand("/exec")
-- 8. a stopped owner no longer answers: usage instead
harness.chatInput("/lua exec game.RegisterCommand('/ghost', function(a) end)")
settle(300)
harness.clearCalls()
harness.chatInput("/lua ghost")
settle(300)
check(not chatHas("/lua list | start"), "a live owner's /ghost is found (no usage)")
harness.chatInput("/lua stop exec")
settle(300)
harness.clearCalls()
harness.chatInput("/lua ghost")
settle(300)
check(chatHas("/lua list | start"), "after its owner stopped, /lua ghost prints usage")
check(not chatHas("ghost."), "a stopped owner's command is not listed")
-- 9. nothing registered: the usage says so
game.UnregisterCommand("/demo")
game.UnregisterCommand("/list")
harness.clearCalls()
before = #calls
harness.chatInput("/lua demo status")
settle(300)
check(chatHas("none registered now."), "no commands: usage says none registered")
eq(#calls, before, "no handler ran")
done()

View file

@ -31,6 +31,7 @@
<ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthLua\*.cs" Link="RynthLua\%(Filename)%(Extension)" />
<Compile Include="..\..\Plugins\Shared\RynthAiScriptApi.cs" Link="RynthLua\RynthAiScriptApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiCombatApi.cs" Link="RynthLua\RynthAiCombatApi.cs" />
<Compile Include="..\..\Plugins\Shared\UseAudit.cs" Link="RynthLua\UseAudit.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
<!-- The engine's AC icon decoder (pure code) and its DXT helper: decoded against the real client_portal.dat when it is there (read only). -->

View file

@ -0,0 +1,297 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthThreads.Threads;
using RynthCore.RynthAiTests.Harness;
namespace RynthThreads.Tests;
// The odds (Threads/PressInference.cs): rates, intervals and comparisons, on the first real presses
// and on made-up ones.
internal static class InferenceTests
{
public static void Register(Runner r)
{
r.Add("infer: the 4 real Lead Scarab presses (old JSON lines): rates, intervals, Affinity group", RealPresses);
r.Add("infer: with/without a component; 'more likely' only when clear; 'always' only at 10+", WithWithout);
r.Add("infer: Wilson intervals and the Fisher test", Statistics);
r.Add("infer: exact combinations of components", Combinations);
r.Add("infer: No components and All presses rows; incomplete presses left out", NoComponentsAndAll);
r.Add("infer: Affinity grouping and the split by material", AffinityGroup);
r.Add("infer: per-modifier view: overall, no components, each component (0% too)", ModifierView);
r.Add("infer: values by level, tags, results and modifiers per press", ReportDetails);
r.Add("infer: the sample press runs through the whole report", SampleReport);
}
/// <summary>The first 4 presses from presses.jsonl (2026-10-12, all Lead Scarab), exactly as written.</summary>
internal static readonly string[] RealLines =
{
"""{"v":1,"id":"ccbf1dd788704e08","time":"2026-10-12T23:44:32.8501639Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Radiant","description":"kills pay x1.84 luminance","numbers":[{"value":1.84,"kind":"mult","text":"x1.84"}]},{"name":"Amethyst Affinity","description":"10% of kills leave amethyst to salvage","numbers":[{"value":10,"kind":"pct","text":"10%"}]},{"name":"Precise","description":"monsters have \u002B27 critical strike rating, landing more critical hits","numbers":[{"value":27,"kind":"plus","text":"\u002B27"}]},{"name":"Guarded","description":"the boss has x1.91 health","numbers":[{"value":1.91,"kind":"mult","text":"x1.91"}]},{"name":"Savage","description":"monsters attack with \u002B35 damage rating, hitting harder","numbers":[{"value":35,"kind":"plus","text":"\u002B35"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Radiant - kills pay x1.84 luminance"," Amethyst Affinity - 10% of kills leave amethyst to salvage"," Precise - monsters have \u002B27 critical strike rating, landing more critical hits"," Guarded - the boss has x1.91 health"," Savage - monsters attack with \u002B35 damage rating, hitting harder","Level 175, 3 entries."],"extra":[]}""",
"""{"v":1,"id":"6613196a36424f8c","time":"2026-10-12T23:50:31.1229501Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Radiant","description":"kills pay x1.75 luminance","numbers":[{"value":1.75,"kind":"mult","text":"x1.75"}]},{"name":"Iron Affinity","description":"8% of kills leave iron to salvage","numbers":[{"value":8,"kind":"pct","text":"8%"}]},{"name":"Teeming","description":"67% more monsters","numbers":[{"value":67,"kind":"pct","text":"67%"}]},{"name":"Guarded","description":"the boss has x1.83 health","numbers":[{"value":1.83,"kind":"mult","text":"x1.83"}]},{"name":"Swift","description":"monsters move at x1.21 speed","numbers":[{"value":1.21,"kind":"mult","text":"x1.21"}]},{"name":"Shieldbreaker","description":"monsters ignore 54% of your shield","numbers":[{"value":54,"kind":"pct","text":"54%"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Radiant - kills pay x1.75 luminance"," Iron Affinity - 8% of kills leave iron to salvage"," Teeming - 67% more monsters"," Guarded - the boss has x1.83 health"," Swift - monsters move at x1.21 speed"," Shieldbreaker - monsters ignore 54% of your shield","Level 175, 3 entries."],"extra":[]}""",
"""{"v":1,"id":"1e960ea87fa64343","time":"2026-10-13T00:22:04.7703741Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Bounteous","description":"kills drop x1.51 loot","numbers":[{"value":1.51,"kind":"mult","text":"x1.51"}]},{"name":"Serpentine Affinity","description":"22% of kills leave serpentine to salvage","numbers":[{"value":22,"kind":"pct","text":"22%"}]},{"name":"Champions","description":"30% of the run\u0027s monsters are elites","numbers":[{"value":30,"kind":"pct","text":"30%"}]},{"name":"Guarded","description":"the boss has x2.18 health","numbers":[{"value":2.18,"kind":"mult","text":"x2.18"}]},{"name":"Enraged","description":"the boss attacks with \u002B54 damage rating, hitting harder","numbers":[{"value":54,"kind":"plus","text":"\u002B54"}]},{"name":"Precise","description":"monsters have \u002B19 critical strike rating, landing more critical hits","numbers":[{"value":19,"kind":"plus","text":"\u002B19"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Bounteous - kills drop x1.51 loot"," Serpentine Affinity - 22% of kills leave serpentine to salvage"," Champions - 30% of the run\u0027s monsters are elites"," Guarded - the boss has x2.18 health"," Enraged - the boss attacks with \u002B54 damage rating, hitting harder"," Precise - monsters have \u002B19 critical strike rating, landing more critical hits","Level 175, 3 entries."],"extra":[]}""",
"""{"v":1,"id":"f0bf2c2811904c52","time":"2026-10-13T00:34:08.9352276Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Enlightened","description":"kills pay x1.43 experience","numbers":[{"value":1.43,"kind":"mult","text":"x1.43"}]},{"name":"Obsidian Affinity","description":"7% of kills leave obsidian to salvage","numbers":[{"value":7,"kind":"pct","text":"7%"}]},{"name":"Shieldbreaker","description":"monsters ignore 51% of your shield","numbers":[{"value":51,"kind":"pct","text":"51%"}]},{"name":"Savage","description":"monsters attack with \u002B33 damage rating, hitting harder","numbers":[{"value":33,"kind":"plus","text":"\u002B33"}]},{"name":"Stalwart","description":"monsters have \u002B20 damage resist rating, taking less damage from you","numbers":[{"value":20,"kind":"plus","text":"\u002B20"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Enlightened - kills pay x1.43 experience"," Obsidian Affinity - 7% of kills leave obsidian to salvage"," Shieldbreaker - monsters ignore 51% of your shield"," Savage - monsters attack with \u002B33 damage rating, hitting harder"," Stalwart - monsters have \u002B20 damage resist rating, taking less damage from you","Level 175, 3 entries."],"extra":["[BANK] Debited 1 Trade Notes (250,000) (250,000 pyreals) from your bank."]}""",
};
internal static List<Press> Real() => RealLines.Select(l => PressStore.FromJson(l)!).ToList();
private static int _n;
/// <summary>A complete press with these components and modifiers ("Name" or "Name=x1.5 text").</summary>
internal static Press P(string components, string modifiers, int level = 100, bool complete = true, int? result = null, int? entries = null)
{
var p = new Press
{
Id = "t" + (++_n),
TimeUtc = new DateTime(2026, 10, 12, 19, 0, 0, DateTimeKind.Utc).AddSeconds(_n),
Character = "Tester",
Server = "DreamWeave",
Fragment = "Raw Fragment",
FragmentLevel = level,
Outcome = "Pressed. It holds.",
ComponentsSeen = true,
Components = PressParser.SplitComponents(components),
Complete = complete,
End = complete ? "done" : "timeout",
ResultLevel = result,
Entries = entries,
};
foreach (string m in modifiers.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
string[] parts = m.Split('=', 2);
string desc = parts.Length > 1 ? parts[1] : "something";
p.Modifiers.Add(new GemModifier { Name = parts[0], Description = desc, Numbers = PressParser.Numbers(desc) });
}
return p;
}
private static List<Press> Many(int count, string components, string modifiers) =>
Enumerable.Range(0, count).Select(_ => P(components, modifiers)).ToList();
private static Odds? Odd(GroupReport? g, string mod) => g?.Find(mod);
private static void RealPresses()
{
List<Press> presses = Real();
Check.True(presses.All(p => p != null && p.Usable), "all 4 old lines load as complete presses");
Check.Eq(string.Join(",", presses.Select(p => p.ComponentsText).Distinct()), "Lead Scarab", "all Lead Scarab");
ThreadsReport r = PressInference.Build(presses);
GroupReport? ls = r.Component("Lead Scarab");
Check.NotNull(ls, "Lead Scarab row");
if (ls == null) return;
Check.Eq(ls.Presses, 4, "4 presses");
Odds g = Odd(ls, "Guarded")!;
Check.Eq((g.Hits, g.N), (3, 4), "Guarded 3/4");
Check.Eq(PressInference.OddsText(g), "75% (3/4, 30-95%)", "Guarded text");
Check.Eq(g.Values, "x1.83 to x2.18", "Guarded values");
Odds rad = Odd(ls, "Radiant")!;
Check.Eq(PressInference.OddsText(rad), "50% (2/4, 15-85%)", "Radiant 2/4");
Check.Eq(PressInference.OddsText(Odd(ls, "Champions")!), "25% (1/4, 5-70%)", "Champions 1/4");
Odds aff = Odd(ls, PressInference.AffinityGroup)!;
Check.Eq((aff.Hits, aff.N), (4, 4), "Affinity group 4/4");
Check.Eq(PressInference.OddsText(aff), "100% (4/4, 51-100%)", "Affinity text");
Check.Eq(PressInference.SplitText(aff), "Amethyst 1, Iron 1, Obsidian 1, Serpentine 1", "split 1 each");
Check.Eq(aff.Values, "7% to 22%", "affinity values across materials");
Check.Null(Odd(ls, "Amethyst Affinity"), "materials are not rows of their own");
Check.Eq(ls.Odds[0].Modifier, PressInference.AffinityGroup, "sorted by rate: Affinity first");
Check.Eq(ls.Odds[1].Modifier, "Guarded", "then Guarded");
Check.Eq(PressInference.OtherText(g, ls.OtherLabel), "without: no data", "nothing without Lead Scarab");
Check.False(ls.Odds.Any(o => o.MoreLikely), "no 'more likely' with nothing to compare");
Check.Eq(r.All?.Presses, 4, "All presses row");
Check.Eq(r.Combinations.Count, 0, "no combinations");
Check.Null(r.NoComponents, "no No components row");
Check.Eq(PressInference.ModifiersText(ls), "5.5 modifiers per press (5-6)", "modifiers per press");
Check.Eq(PressInference.ResultsText(ls), "L185 -> 175, 3 entries: 4", "results");
Check.Eq(r.Modifier("Affinity")?.Overall.Hits, 4, "modifier view: Affinity 4/4");
Check.Null(r.Modifier("Iron Affinity"), "no Iron Affinity modifier entry");
Check.Eq(r.Modifiers.Count, 13, "13 modifiers (affinities as one)");
}
private static void WithWithout()
{
var presses = Many(5, "Red Taper", "Bounteous, Hardy");
presses.Add(P("Red Taper", "Teeming, Hardy"));
presses.AddRange(Many(3, "", "Hardy, Teeming"));
presses.AddRange(Many(3, "", "Savage, Teeming"));
ThreadsReport r = PressInference.Build(presses);
GroupReport red = r.Component("Red Taper")!;
Odds b = Odd(red, "Bounteous")!;
Check.Eq((b.Hits, b.N, b.OtherHits, b.OtherN), (5, 6, 0, 6), "Bounteous 5/6 with, 0/6 without");
Check.True(b.MoreLikely, "Bounteous more likely with Red Taper");
Check.Eq(PressInference.LikelyText(b, red), "more likely with Red Taper", "wording");
Check.Eq(PressInference.OtherText(b, red.OtherLabel), "without: 0% (0/6)", "without text");
Odds h = Odd(red, "Hardy")!;
Check.Eq((h.Hits, h.OtherHits), (6, 3), "Hardy 6/6 with, 3/6 without");
Check.False(h.MoreLikely, "Hardy 6/6 vs 3/6: not clear (p ~ 0.09)");
Check.Eq(red.Odds[0].Modifier, "Hardy", "sorted by rate: Hardy (100%) first");
// Few presses: nothing claimed.
r = PressInference.Build(Many(2, "Blue Taper", "Bounteous").Concat(Many(2, "", "Hardy")).ToList());
Check.False(Odd(r.Component("Blue Taper"), "Bounteous")!.MoreLikely, "2/2 vs 0/2: not claimed");
// 'always' only at 100% over 10 or more.
r = PressInference.Build(Many(9, "Green Taper", "Teeming").Concat(Many(9, "", "Hardy")).ToList());
GroupReport green = r.Component("Green Taper")!;
Check.Eq(PressInference.LikelyText(Odd(green, "Teeming")!, green), "more likely with Green Taper", "9/9: more likely, not always");
r = PressInference.Build(Many(10, "Green Taper", "Teeming").Concat(Many(10, "", "Hardy")).ToList());
green = r.Component("Green Taper")!;
Check.Eq(PressInference.LikelyText(Odd(green, "Teeming")!, green), "always with Green Taper so far", "10/10: always so far");
// The No components row is compared with presses that had components.
r = PressInference.Build(Many(6, "Red Taper", "Hardy").Concat(Many(6, "", "Teeming")).ToList());
Odds t = Odd(r.NoComponents, "Teeming")!;
Check.True(t.MoreLikely, "Teeming 6/6 plain vs 0/6 with components");
Check.Eq(PressInference.LikelyText(t, r.NoComponents!), "more likely with no components", "no-components wording");
}
private static void Statistics()
{
var (lo, hi) = PressInference.Wilson(3, 4);
Check.True(Math.Abs(lo - 0.3006) < 0.001 && Math.Abs(hi - 0.9544) < 0.001, $"3/4: 30.1-95.4% ({lo:0.0000}-{hi:0.0000})");
(lo, hi) = PressInference.Wilson(0, 5);
Check.True(lo == 0 && Math.Abs(hi - 0.4345) < 0.001, $"0/5: 0-43% ({hi:0.0000})");
(lo, hi) = PressInference.Wilson(0, 0);
Check.True(lo == 0 && hi == 1, "0/0: anything");
Check.True(Math.Abs(PressInference.FisherGreater(3, 3, 0, 3) - 0.05) < 1e-9, "3/3 vs 0/3: p = 1/20");
Check.True(Math.Abs(PressInference.FisherGreater(5, 6, 0, 6) - 7.0 / 924) < 1e-9, "5/6 vs 0/6: p = 7/924");
Check.True(Math.Abs(PressInference.FisherGreater(0, 4, 4, 4) - 1) < 1e-9, "0 hits: p = 1");
Check.Eq(PressInference.OddsText(new Odds { Hits = 30, N = 60 }), "50% (30/60)", "no interval from 50 presses");
Check.Eq(PressInference.OddsText(new Odds { Hits = 0, N = 0 }), "no data", "empty");
}
private static void Combinations()
{
var presses = Many(3, "Red Taper, Blue Taper", "Bounteous, Savage");
presses.AddRange(Many(2, "Red Taper", "Bounteous, Hardy"));
presses.Add(P("Blue Taper", "Savage, Hardy"));
presses.AddRange(Many(2, "", "Hardy, Teeming"));
ThreadsReport r = PressInference.Build(presses);
Check.Eq(r.Combinations.Count, 1, "one combination");
GroupReport? combo = r.Combination("Blue Taper + Red Taper");
Check.NotNull(combo, "named by its sorted components");
if (combo == null) return;
Check.Eq(combo.Presses, 3, "3 presses with exactly both");
Check.Eq(combo.Members.Count, 2, "two members");
Check.Eq(r.Component("Red Taper")!.Presses, 5, "component row counts every press with it");
Check.Eq(r.Component("Blue Taper")!.Presses, 4, "Blue Taper 4");
Odds s = Odd(combo, "Savage")!;
Check.Eq((s.Hits, s.N, s.OtherHits, s.OtherN), (3, 3, 1, 5), "Savage 3/3 in the combination, 1/5 in other presses");
Check.Eq(PressInference.OtherText(s, combo.OtherLabel), "other presses: 20% (1/5)", "comparison label");
Check.Eq(PressInference.Build(Many(2, "Blue Taper, Red Taper", "Hardy").Concat(Many(1, "Red Taper, Blue Taper", "Hardy")).ToList())
.Combination("Blue Taper + Red Taper")?.Presses, 3, "order of components doesn't matter");
}
private static void NoComponentsAndAll()
{
var presses = Many(4, "Red Taper", "Bounteous, Hardy");
presses.AddRange(Many(2, "", "Hardy, Teeming"));
presses.Add(P("", "Teeming"));
presses.Add(P("Red Taper", "Savage", complete: false));
presses.Add(P("", "")); // finished but no gem block: not usable
ThreadsReport r = PressInference.Build(presses);
Check.Eq((r.Total, r.Usable, r.Incomplete), (9, 7, 1), "totals");
Check.Eq(r.Component("Red Taper")!.Presses, 4, "incomplete press left out");
GroupReport? nc = r.NoComponents;
Check.NotNull(nc, "No components row");
if (nc == null) return;
Check.Eq((nc.Presses, nc.Kind), (3, GroupKind.NoComponents), "3 plain presses");
Odds t = Odd(nc, "Teeming")!;
Check.Eq((t.Hits, t.N, t.OtherHits, t.OtherN), (3, 3, 0, 4), "Teeming 3/3 plain, 0/4 with components");
Check.Eq(PressInference.OtherText(t, nc.OtherLabel), "with components: 0% (0/4)", "comparison label");
Check.Eq(nc.Odds[0].Modifier, "Teeming", "most common plain draw first");
GroupReport all = r.All!;
Check.Eq((all.Presses, all.Kind), (7, GroupKind.All), "All presses: every usable press");
Odds h = Odd(all, "Hardy")!;
Check.Eq((h.Hits, h.N), (6, 7), "Hardy 6/7 overall");
Check.False(h.Compared, "the baseline isn't compared");
Check.Eq(PressInference.OtherText(h, all.OtherLabel), "", "no comparison text");
Check.False(all.Odds.Any(o => o.MoreLikely), "never flagged");
}
private static void AffinityGroup()
{
Check.Eq(PressInference.Material("Green Garnet Affinity"), "Green Garnet", "two-word material");
Check.Eq(PressInference.Key("Tourmaline Affinity"), PressInference.AffinityGroup, "grouped");
Check.Null(PressInference.Material("Affinity"), "bare 'Affinity' is not a material");
Check.Eq(PressInference.Key("Guarded"), "Guarded", "others keep their name");
Check.Eq(PressInference.Display(PressInference.AffinityGroup), "Affinity (any)", "display name");
var presses = new List<Press>
{
P("Red Taper", "Iron Affinity=8% of kills leave iron to salvage, Hardy"),
P("Red Taper", "Iron Affinity=10% of kills leave iron to salvage, Teeming"),
P("Red Taper", "Amethyst Affinity=12% of kills leave amethyst to salvage, Gold Affinity=5% of kills leave gold to salvage"),
P("", "Hardy"),
};
ThreadsReport r = PressInference.Build(presses);
Odds a = Odd(r.Component("Red Taper"), PressInference.AffinityGroup)!;
Check.Eq((a.Hits, a.N, a.OtherHits, a.OtherN), (3, 3, 0, 1), "a press with two affinities counts once");
Check.Eq(PressInference.SplitText(a), "Iron 2, Amethyst 1, Gold 1", "split counts both, most first");
ModifierReport m = r.Modifier("Affinity")!;
Check.True(m.IsGroup, "modifier view: the group");
Check.Eq(m.Tag, "reward", "salvage: reward");
Check.Eq(m.Values, "8% to 12%", "values over every material (first affinity per press)");
}
private static void ModifierView()
{
var presses = Many(3, "Red Taper", "Bounteous, Hardy");
presses.AddRange(Many(2, "Blue Taper", "Hardy"));
presses.Add(P("Blue Taper, Red Taper", "Bounteous"));
presses.AddRange(Many(2, "", "Teeming, Bounteous"));
ThreadsReport r = PressInference.Build(presses);
ModifierReport b = r.Modifier("Bounteous")!;
Check.Eq((b.Overall.Hits, b.Overall.N), (6, 8), "overall 6/8");
Check.Eq((b.NoComponents?.Hits, b.NoComponents?.N, b.NoComponents?.OtherHits, b.NoComponents?.OtherN), ((int?)2, (int?)2, (int?)4, (int?)6), "no components 2/2 vs 4/6");
Check.Eq(string.Join(", ", b.ByGroup.Select(x => $"{x.Group.Name} {x.Odds.Hits}/{x.Odds.N}")),
"Red Taper 4/4, Blue Taper + Red Taper 1/1, Blue Taper 1/3", "each component and combination, likeliest first");
Odds teemingBlue = r.Modifier("Teeming")!.ByGroup.First(x => x.Group.Name == "Blue Taper").Odds;
Check.Eq((teemingBlue.Hits, teemingBlue.N, teemingBlue.OtherHits, teemingBlue.OtherN), (0, 3, 2, 5), "0% rows are kept, with their comparison");
}
private static void ReportDetails()
{
var presses = new List<Press>
{
P("Red Taper", "Bounteous=kills drop x1.38 loot, Hardy=monsters have x1.5 health", level: 185, result: 175, entries: 3),
P("Red Taper", "Bounteous=kills drop x1.52 loot", level: 185, result: 175, entries: 3),
P("Red Taper", "Bounteous=kills drop x1.20 loot", level: 120, result: 110, entries: 2),
P("Red Taper", "Hardy=monsters have x2 health", complete: false),
P("", "Hardy=monsters have x1.81 health, Teeming=75% more monsters", level: 120),
P("", "Teeming=60% more monsters", level: 120),
};
ThreadsReport r = PressInference.Build(presses);
GroupReport red = r.Component("Red Taper")!;
Check.Eq(PressInference.ResultsText(red), "L185 -> 175, 3 entries: 2; L120 -> 110, 2 entries: 1", "results, most common first");
Check.Eq(PressInference.ModifiersText(red), "1.33 modifiers per press (1-2)", "modifiers per press");
Check.Eq(Odd(red, "Bounteous")!.Values, "x1.2 to x1.52", "values with the component");
ModifierReport b = r.Modifier("Bounteous")!;
Check.Eq(b.Values, "x1.2 to x1.52", "value range");
Check.Eq(b.ByLevel.Count, 2, "two fragment levels");
Check.Eq(b.ByLevel[0].Level, 120, "lowest level first");
Check.Eq(b.ByLevel[1].Values, "x1.38 to x1.52", "level 185 range");
Check.Eq(b.Tag, "reward", "loot is a reward");
Check.Eq(r.Modifier("Hardy")!.Tag, "harder", "monster health is harder");
Check.Eq(PressInference.Tag("something odd"), "", "no tag when the text doesn't say");
ThreadsReport empty = PressInference.Build(new List<Press>());
Check.True(empty.Usable == 0 && empty.All == null && empty.Modifiers.Count == 0, "empty input");
}
private static void SampleReport()
{
Press p = new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0];
ThreadsReport r = PressInference.Build(new[] { p });
Check.Eq(r.Component("Red Taper")?.Presses, 1, "Red Taper counted");
Check.Eq(r.Modifiers.Count, 6, "six modifiers in the report");
Check.Eq(r.Modifier("Affinity")?.Tag, "reward", "salvage is a reward");
Check.Eq(PressInference.SplitText(r.Modifier("Affinity")!.Overall), "Tourmaline 1", "Tourmaline");
Check.Eq(r.Modifier("Enraged")?.Tag, "harder", "boss damage is harder");
Check.Eq(PressInference.OddsText(r.Component("Red Taper")!.Find("Hardy")!), "100% (1/1, 21-100%)", "one press: wide range");
}
}

View file

@ -0,0 +1,258 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthThreads.Threads;
using RynthCore.RynthAiTests.Harness;
namespace RynthThreads.Tests;
// The chat parser (Threads/PressParser.cs). The sample is real DreamWeave chat from 2026-10-12
// (timestamps removed: the plugin sees the text without them), with another player's line in it.
internal static class ParserTests
{
public static readonly string[] Sample =
{
"Using the Raw Fragment (Level 185) with the Fragment Press",
"Yorick is recalling to the marketplace.",
"Pressed. It holds.",
"Components selected: Red Taper",
"Remaining slots drawn at random.",
"The gem carries:",
" Bounteous - kills drop x1.38 loot",
" Tourmaline Affinity - 12% of kills leave tourmaline to salvage",
" Hardy - monsters have x1.81 health",
" Enraged - the boss attacks with +29 damage rating, hitting harder",
" Teeming - 75% more monsters",
" Savage - monsters attack with +20 damage rating, hitting harder",
"Level 190, 4 entries.",
};
public static void Register(Runner r)
{
r.Add("parse: the real sample, line by line, with another player's line in it", SampleLineByLine);
r.Add("parse: the sample as one message with newlines", SampleOneMessage);
r.Add("parse: several components (commas, 'and'), sorted", SeveralComponents);
r.Add("parse: no components (no line, 'none', 'No components ...')", NoComponents);
r.Add("parse: incomplete presses (timeout, next press, other Using line, logout)", Incomplete);
r.Add("parse: unknown and odd lines never throw and never become modifiers", UnknownLines);
r.Add("parse: numbers and their forms", NumberForms);
}
private static List<Press> FeedAll(PressParser parser, IEnumerable<string> lines, long now = 1000)
{
var done = new List<Press>();
foreach (string line in lines)
if (parser.Feed(line, now) is { } d) done.AddRange(d);
return done;
}
private static void SampleLineByLine()
{
var parser = new PressParser();
List<Press> done = FeedAll(parser, Sample);
Check.Eq(done.Count, 1, "one press");
if (done.Count != 1) return;
CheckSample(done[0]);
Check.False(parser.Busy, "parser idle after the Level line");
}
private static void SampleOneMessage()
{
var parser = new PressParser();
List<Press>? done = parser.Feed(string.Join("\n", Sample) + "\n", 1000);
Check.Eq(done?.Count ?? 0, 1, "one press from one message");
if (done is { Count: 1 }) CheckSample(done[0]);
// CRLF too.
done = new PressParser().Feed(string.Join("\r\n", Sample), 1000);
Check.Eq(done?[0].Modifiers.Count ?? -1, 6, "CRLF lines: 6 modifiers");
}
internal static void CheckSample(Press p)
{
Check.Eq(p.Fragment, "Raw Fragment", "fragment name");
Check.Eq(p.FragmentLevel, 185, "fragment level");
Check.Eq(p.Tool, "Fragment Press", "tool");
Check.Eq(p.Outcome, "Pressed. It holds.", "outcome");
Check.True(p.Held, "held");
Check.True(p.ComponentsSeen, "components line seen");
Check.Eq(string.Join("|", p.Components), "Red Taper", "components");
Check.Eq(p.RandomNote, "Remaining slots drawn at random.", "random note");
Check.Eq(p.ResultLevel, 190, "result level");
Check.Eq(p.Entries, 4, "entries (raw, not the modifier count)");
Check.True(p.Complete, "complete");
Check.Eq(p.End, "done", "end reason");
Check.Eq(p.Modifiers.Count, 6, "six modifiers");
Check.Eq(p.Raw.Count, 12, "12 own raw lines");
Check.Eq(string.Join("|", p.Extra), "Yorick is recalling to the marketplace.", "the foreign line is kept apart");
Check.False(p.Raw.Any(l => l.Contains("Yorick")), "no foreign line in Raw");
Check.Eq(p.Raw[5], " Bounteous - kills drop x1.38 loot", "raw lines kept as is (indent too)");
if (p.Modifiers.Count != 6) return;
(string Name, string Kinds, string Values, string Desc)[] want =
{
("Bounteous", "mult", "1.38", "kills drop x1.38 loot"),
("Tourmaline Affinity", "pct", "12", "12% of kills leave tourmaline to salvage"),
("Hardy", "mult", "1.81", "monsters have x1.81 health"),
("Enraged", "plus", "29", "the boss attacks with +29 damage rating, hitting harder"),
("Teeming", "pct", "75", "75% more monsters"),
("Savage", "plus", "20", "monsters attack with +20 damage rating, hitting harder"),
};
for (int i = 0; i < want.Length; i++)
{
GemModifier m = p.Modifiers[i];
Check.Eq(m.Name, want[i].Name, $"modifier {i} name");
Check.Eq(m.Description, want[i].Desc, $"{want[i].Name} description");
Check.Eq(string.Join(",", m.Numbers.Select(n => n.Kind)), want[i].Kinds, $"{want[i].Name} number kinds");
Check.Eq(string.Join(",", m.Numbers.Select(n => n.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))), want[i].Values, $"{want[i].Name} values");
}
Check.Eq(p.Modifiers[0].Numbers[0].Text, "x1.38", "text as written");
Check.Eq(p.Modifiers[3].Numbers[0].Text, "+29", "rating text");
}
private static string[] Press(string components, params string[] mods)
{
var lines = new List<string> { "Using the Raw Fragment (Level 100) with the Fragment Press", "Pressed. It holds." };
if (components != null) lines.Add(components);
lines.Add("Remaining slots drawn at random.");
lines.Add("The gem carries:");
lines.AddRange(mods.Select(m => " " + m));
lines.Add("Level 104, 2 entries.");
return lines.ToArray();
}
private static void SeveralComponents()
{
Press p = FeedAll(new PressParser(), Press("Components selected: Red Taper, Blue Taper, Pyreal", "Hardy - monsters have x1.5 health")).Single();
Check.Eq(string.Join("|", p.Components), "Blue Taper|Pyreal|Red Taper", "three, sorted");
p = FeedAll(new PressParser(), Press("Components selected: Red Taper and Yellow Taper.", "Hardy - x")).Single();
Check.Eq(string.Join("|", p.Components), "Red Taper|Yellow Taper", "'and' splits, trailing dot dropped");
p = FeedAll(new PressParser(), Press("Components selected: Red Taper, red taper", "Hardy - x")).Single();
Check.Eq(p.Components.Count, 1, "the same component twice counts once");
}
private static void NoComponents()
{
Press p = FeedAll(new PressParser(), Press(null!, "Teeming - 75% more monsters")).Single();
Check.False(p.ComponentsSeen, "no line: not seen");
Check.Eq(p.Components.Count, 0, "no line: none");
Check.True(p.Complete && p.Usable, "still complete and usable");
p = FeedAll(new PressParser(), Press("Components selected: none", "Teeming - 75% more monsters")).Single();
Check.True(p.ComponentsSeen && p.Components.Count == 0, "'none'");
p = FeedAll(new PressParser(), Press("No components selected.", "Teeming - 75% more monsters")).Single();
Check.True(p.ComponentsSeen && p.Components.Count == 0, "'No components selected.'");
Check.Eq(p.ComponentsText, "no components", "shown as 'no components'");
}
private static void Incomplete()
{
// Timeout: the Level line never comes.
var parser = new PressParser();
string[] lines = Sample.Take(Sample.Length - 1).ToArray();
Check.Eq(FeedAll(parser, lines, 1000).Count, 0, "nothing finished yet");
Check.Null(parser.Tick(1000 + PressParser.TimeoutMs - 1), "not before the timeout");
// Other chat doesn't keep it open.
parser.Feed("Someone says, \"hello\"", 1000 + PressParser.TimeoutMs - 1);
Press? t = parser.Tick(1000 + PressParser.TimeoutMs);
Check.NotNull(t, "timed out");
if (t != null)
{
Check.False(t.Complete, "incomplete");
Check.Eq(t.End, "timeout", "reason");
Check.Eq(t.Modifiers.Count, 6, "what was gathered is kept");
Check.Null(t.ResultLevel, "no result level");
Check.False(t.Usable, "not used by the inference");
}
// The next press starts before this one's Level line.
parser = new PressParser();
var done = FeedAll(parser, Sample.Take(4).Concat(Sample));
Check.Eq(done.Count, 2, "two presses");
if (done.Count == 2)
{
Check.True(!done[0].Complete && done[0].End == "next use", "first: incomplete, next use");
Check.Eq(done[0].Outcome, "Pressed. It holds.", "first kept its outcome");
Check.True(done[1].Complete && done[1].Modifiers.Count == 6, "second complete");
}
// Some other "Using ..." line ends it and starts nothing.
parser = new PressParser();
done = FeedAll(parser, Sample.Take(3).Append("Using the Mana Stone on the Robe of Ages"));
Check.Eq(done.Count, 1, "ended by another Using line");
Check.False(parser.Busy, "no new press from an unrelated Using line");
Check.Eq(done.Count == 1 ? done[0].End : "", "next use", "reason");
// Logout.
parser = new PressParser();
FeedAll(parser, Sample.Take(2));
Press? f = parser.Flush("logout");
Check.True(f != null && f.End == "logout" && !f.Complete, "flush at logout");
Check.Null(parser.Flush("logout"), "nothing left to flush");
}
private static void UnknownLines()
{
var parser = new PressParser();
string[] junk =
{
"", " ", "\n\n", "Level 190, 4 entries.", "Pressed. It holds.", " Hardy - monsters have x1.81 health",
new string('x', 5000), "Components selected:", "The gem carries:", "☃ éè ???", "Using", "Using the",
"with the Fragment Press", "1234567890123456789012345678901234567890", " - just a dash", "x%+",
};
int finished = 0;
foreach (string j in junk)
finished += parser.Feed(j, 1000)?.Count ?? 0;
Check.Eq(finished, 0, "nothing comes out of junk while idle");
Check.False(parser.Busy, "still idle");
Check.Null(parser.Feed(null, 1000), "null text");
// Inside a press: junk goes to Extra, chat-like dash lines don't become modifiers, a failed outcome is kept.
var lines = new List<string>
{
"Using the Woven Shard (Level 12) with the Fragment Press",
"Pressed. It cracks.",
"The gem carries:",
"Bob says, \"Hardy - is that good?\"",
"[Trade] Alice - selling tapers",
"☃☃☃",
" Strange Sigil - something we've never seen, 3 times",
" not a modifier line",
new string('y', 2000),
"Level 12, 1 entry.",
};
List<Press> done = FeedAll(parser, lines);
Check.Eq(done.Count, 1, "one press");
if (done.Count != 1) return;
Press p = done[0];
Check.Eq(p.Fragment, "Woven Shard", "other fragment name");
Check.Eq(p.FragmentLevel, 12, "its level");
Check.Eq(p.Outcome, "Pressed. It cracks.", "a failed outcome is kept as said");
Check.False(p.Held, "not held");
Check.Eq(p.Modifiers.Count, 1, "only the real modifier line");
Check.Eq(p.Modifiers.Count == 1 ? p.Modifiers[0].Name : "", "Strange Sigil", "unknown modifier name kept");
Check.Eq(p.Entries, 1, "'1 entry' singular");
Check.True(p.Extra.Count >= 4, "unfitting lines kept in Extra");
Check.True(p.Extra.All(l => l.Length <= 400), "long lines cut");
// A fragment without a level, and a press that isn't the Fragment Press.
done = FeedAll(new PressParser(), new[] { "Using the Odd Shard with the Fragment Press", "Level 3, 0 entries." });
Check.True(done.Count == 1 && done[0].FragmentLevel == null && done[0].Fragment == "Odd Shard", "no level in the name");
Check.True(done.Count == 1 && done[0].Complete && !done[0].Usable, "complete, but no modifiers: not usable");
done = FeedAll(new PressParser(), new[] { "Using the Pyreal Ingot with the Forge", "Level 3, 0 entries." });
Check.Eq(done.Count, 0, "not a Press: ignored");
}
private static void NumberForms()
{
string Forms(string s) => string.Join(" ", PressParser.Numbers(s).Select(n => n.Kind + ":" + n.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)));
Check.Eq(Forms("kills drop x1.38 loot"), "mult:1.38", "multiplier");
Check.Eq(Forms("12% of kills"), "pct:12", "percent");
Check.Eq(Forms("+29 damage rating"), "plus:29", "rating");
Check.Eq(Forms("attacks with +29."), "plus:29", "rating before a full stop");
Check.Eq(Forms("-5 damage rating"), "plus:-5", "negative rating");
Check.Eq(Forms("+12% more"), "pct:12", "signed percent is a percent");
Check.Eq(Forms("spawns 3 bosses in 10.5 seconds"), "num:3 num:10.5", "plain numbers");
Check.Eq(Forms("max5 and box2"), "", "digits glued to words aren't numbers");
Check.Eq(Forms("no numbers here"), "", "none");
}
}

View file

@ -0,0 +1,51 @@
using System;
using System.IO;
using RynthCore.RynthAiTests.Harness;
// The engine parser's only outside dependency: the registry's limits (the engine's values).
namespace RynthCore.Engine.UI.ScriptWindows
{
internal static class ScriptWindowRegistry
{
public const int MaxOpsPerWindow = 1500;
public const int MaxBytesPerWindow = 64 * 1024;
public const int MaxWindowsPerOwner = 32;
public const int MaxBytesPerSubmit = 256 * 1024;
}
}
namespace RynthThreads.Tests
{
// Offline tests for RynthThreads. Each test prints PASS / FAIL.
//
// Run: dotnet run -c Release (all tests)
// dotnet run -c Release -- infer (tests whose name contains "infer")
internal static class Program
{
/// <summary>Scratch folder next to the exe for files tests write. Emptied at start.</summary>
public static string TempRoot { get; } = Path.Combine(AppContext.BaseDirectory, "scratch");
private static int Main(string[] args)
{
if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true);
Directory.CreateDirectory(TempRoot);
var runner = new Runner();
ParserTests.Register(runner);
InferenceTests.Register(runner);
StoreTests.Register(runner);
WindowTests.Register(runner);
int rc = runner.Run("RynthThreads tests", args.Length > 0 ? args[0] : null);
try { Directory.Delete(TempRoot, recursive: true); } catch { }
return rc;
}
/// <summary>A fresh empty folder under the scratch root.</summary>
public static string NewFolder(string name)
{
string path = Path.Combine(TempRoot, name + "-" + Guid.NewGuid().ToString("N").Substring(0, 6));
Directory.CreateDirectory(path);
return path;
}
}
}

View file

@ -0,0 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline tests for the RynthThreads plugin (DreamWeave Fragment Press results): the chat parser
(the real sample with an interleaved line, several / no components, incomplete presses, odd
text), the inference rules on made-up presses (a forced modifier at n = 3 but not n = 1, n = 2,
the 90% rule, base rates, several components in one press), the shared presses.jsonl (JSON
round trip, following the file's growth, two writers appending at once) and that the window's
display list is accepted by the engine's own parser (RynthCore
src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs, from the sibling checkout).
The plugin is a NativeAOT x86 library, so its sources are compiled in here. Files go to a
scratch folder next to the exe, never %LOCALAPPDATA%.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail; an argument filters by test name)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>RynthThreads.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
<!-- The engine parser's whitelists use ImGui.NET's enums. -->
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthThreads\**\*.cs" Exclude="..\..\Plugins\RynthCore.Plugin.RynthThreads\obj\**;..\..\Plugins\RynthCore.Plugin.RynthThreads\bin\**" Link="RynthThreads\%(RecursiveDir)%(Filename)%(Extension)" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
<!-- The RynthAi test tools' check/runner harness (no plugin code in it). -->
<Compile Include="..\RynthCore.RynthAiTests\Harness\Check.cs" Link="Harness\Check.cs" />
<Compile Include="..\RynthCore.RynthAiTests\Harness\Runner.cs" Link="Harness\Runner.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,181 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using RynthCore.Plugin.RynthThreads.Threads;
using RynthCore.RynthAiTests.Harness;
namespace RynthThreads.Tests;
// The shared presses.jsonl (Threads/PressStore.cs).
internal static class StoreTests
{
public static void Register(Runner r)
{
r.Add("store: a press survives the JSON round trip", RoundTrip);
r.Add("store: another client's presses are read as the file grows; no doubles", FollowsGrowth);
r.Add("store: odd lines are skipped, a half-written line waits", OddLines);
r.Add("store: two writers appending at once lose nothing", ConcurrentAppends);
r.Add("store: CSV export", CsvExport);
}
private static Press Sample() => new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0];
private static void RoundTrip()
{
Press p = Sample();
p.Server = "DreamWeave";
p.Character = "Tester \"Quote\"";
string json = PressStore.ToJson(p);
Check.False(json.Contains('\n'), "one line");
Press? back = PressStore.FromJson(json);
Check.NotNull(back, "reads back");
if (back == null) return;
ParserTests.CheckSample(back);
Check.Eq(back.Id, p.Id, "id");
Check.Eq(back.Character, "Tester \"Quote\"", "character (escaped quotes)");
Check.Eq(back.Server, "DreamWeave", "server");
Check.Eq(back.TimeUtc, p.TimeUtc, "time");
Check.Eq(back.Modifiers[3].Numbers[0].Text, "+29", "number text");
// Missing fields and unknown ones (a later version) are fine.
Press? minimal = PressStore.FromJson("{\"id\":\"x1\",\"future\":[1,2],\"modifiers\":[{\"name\":\"Hardy\"},{\"description\":\"no name\"}]}");
Check.True(minimal != null && minimal.Id == "x1" && minimal.Modifiers.Count == 1 && minimal.FragmentLevel == null,
"minimal line reads, nameless modifier dropped");
Check.Null(PressStore.FromJson("not json"), "garbage");
Check.Null(PressStore.FromJson("[1,2]"), "not an object");
}
private static void FollowsGrowth()
{
string folder = Program.NewFolder("growth");
var a = new PressStore(folder);
var b = new PressStore(folder);
Check.Eq(b.Poll(), 0, "no file yet");
Check.Null(a.Record(Sample()), "client A writes");
Check.Eq(a.Poll(), 0, "A reading its own press back adds nothing");
Check.Eq(a.Presses.Count, 1, "A has it once");
Check.Eq(b.Poll(), 1, "client B sees it");
Check.Eq(b.Poll(), 0, "and only once");
Press second = Sample();
second.Components = new List<string> { "Blue Taper" };
a.Record(second);
b.Record(Sample());
Check.Eq(b.Poll(), 1, "B gets A's second press (its own is already there)");
Check.Eq(a.Poll(), 1, "A gets B's press");
Check.Eq(a.Presses.Count, 3, "A: 3");
Check.Eq(b.Presses.Count, 3, "B: 3");
// A fresh client reads them all.
var c = new PressStore(folder);
Check.Eq(c.Poll(), 3, "a new client loads everything");
int v = c.Version;
c.Poll();
Check.Eq(c.Version, v, "nothing new: unchanged");
}
private static void OddLines()
{
string folder = Program.NewFolder("odd");
var s = new PressStore(folder);
Directory.CreateDirectory(folder);
string good = PressStore.ToJson(Sample());
File.WriteAllText(s.FilePath, good + "\n\nnot json at all\n{\"broken\":\n" + good.Substring(0, 20));
Check.Eq(s.Poll(), 1, "the good line");
Check.Eq(s.BadLines, 2, "two bad lines counted");
// The half line gets finished (with a different id: a new press).
Press other = Sample();
string rest = PressStore.ToJson(other);
File.WriteAllText(s.FilePath, good + "\n\nnot json at all\n{\"broken\":\n" + rest + "\n");
Check.Eq(s.Poll(), 1, "the finished line is read");
Check.Eq(s.Presses.Count, 2, "two presses");
}
private static void ConcurrentAppends()
{
string folder = Program.NewFolder("concurrent");
const int perWriter = 250;
var writers = new[] { new PressStore(folder), new PressStore(folder) };
var errors = new int[2];
using var stop = new CancellationTokenSource();
// A third party holding the file now and then, as another client mid-write would.
var holder = new Thread(() =>
{
while (!stop.IsCancellationRequested)
{
try
{
using var fs = new FileStream(Path.Combine(folder, PressStore.FileName), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
Thread.Sleep(3);
}
catch (IOException) { }
Thread.Sleep(2);
}
});
holder.Start();
var threads = Enumerable.Range(0, 2).Select(w => new Thread(() =>
{
for (int i = 0; i < perWriter; i++)
{
Press p = Sample();
p.Character = "Writer" + w;
p.Components = new List<string> { "C" + i };
if (writers[w].Record(p) != null) errors[w]++;
}
})).ToList();
threads.ForEach(t => t.Start());
threads.ForEach(t => t.Join());
stop.Cancel();
holder.Join();
// Whatever found the file busy every time is written now.
foreach (PressStore w in writers)
for (int i = 0; i < 50 && w.FlushPending() > 0; i++) Thread.Sleep(10);
Check.Eq(writers[0].PendingCount + writers[1].PendingCount, 0, "nothing left pending");
string[] lines = File.ReadAllLines(Path.Combine(folder, PressStore.FileName), Encoding.UTF8)
.Where(l => l.Length > 0).ToArray();
Check.Eq(lines.Length, 2 * perWriter, "every press is one line");
List<Press?> read = lines.Select(PressStore.FromJson).ToList();
Check.True(read.All(p => p != null && p.Modifiers.Count == 6), "every line is a whole press");
Check.Eq(read.Select(p => p!.Id).Distinct().Count(), 2 * perWriter, "all ids distinct");
Check.Eq(read.Count(p => p!.Character == "Writer0"), perWriter, "writer 0's presses all there");
Check.Eq(read.Count(p => p!.Character == "Writer1"), perWriter, "writer 1's presses all there");
var reader = new PressStore(folder);
Check.Eq(reader.Poll(), 2 * perWriter, "a reader loads them all");
Check.Eq(reader.BadLines, 0, "no bad lines");
Console.WriteLine($" (appends that found the file busy every try and waited: {errors[0] + errors[1]})");
}
private static void CsvExport()
{
string folder = Program.NewFolder("csv");
var s = new PressStore(folder);
Press p = Sample();
p.Character = "Tester, Jr.";
s.Record(p);
Press q = Sample();
q.Components = new List<string> { "=cmd", "Red Taper" };
q.Complete = false;
q.End = "timeout";
s.Record(q);
string path = s.ExportCsv(new DateTime(2026, 10, 12, 19, 30, 0));
Check.True(File.Exists(path) && Path.GetDirectoryName(path) == folder, "written next to presses.jsonl");
Check.Eq(Path.GetFileName(path), "presses-20261012-193000.csv", "file name");
string[] rows = File.ReadAllLines(path);
Check.Eq(rows.Length, 3, "header + 2 rows");
Check.True(rows[0].StartsWith("time_utc,server,character,fragment,fragment_level"), "header");
Check.True(rows[1].Contains("\"Tester, Jr.\""), "comma value quoted");
Check.True(rows[1].Contains(",Raw Fragment,185,Pressed. It holds.,Red Taper,190,4,yes,6,"), "columns");
Check.True(rows[1].Contains("Bounteous: kills drop x1.38 loot | Tourmaline Affinity"), "modifiers joined");
Check.True(rows[2].Contains("'=cmd; Red Taper"), "a formula-looking cell is defused");
Check.True(rows[2].Contains("no (timeout)"), "incomplete marked");
}
}

View file

@ -0,0 +1,186 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using RynthCore.Engine.UI.ScriptWindows;
using RynthCore.Plugin.RynthThreads;
using RynthCore.Plugin.RynthThreads.Threads;
using RynthCore.Plugin.RynthThreads.Ui;
using RynthCore.Plugin.RynthThreads.Views;
using RynthCore.RynthAiTests.Harness;
namespace RynthThreads.Tests;
// The window's display list against the engine's own parser, the server check and /rthreads stats.
internal static class WindowTests
{
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "Write")]
private static extern int Write(UiHost h);
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_submit")]
private static extern ref byte[] SubmitBuffer(UiHost h);
public static void Register(Runner r)
{
r.Add("window: every tab, headers open, parses in the engine (bar button set)", EveryTab);
r.Add("window: DreamWeave check and /rthreads stats lines", ServerAndStats);
r.Add("window: Components and Modifiers tab text for the 4 real presses", RealText);
}
private static List<Press> Data()
{
var presses = new List<Press>();
for (int i = 0; i < 3; i++) presses.Add(InferenceTests.P("Red Taper", "Bounteous=kills drop x1.38 loot, Hardy=monsters have x1.5 health", level: 185));
for (int i = 0; i < 4; i++) presses.Add(InferenceTests.P("", "Hardy=monsters have x1.81 health, Teeming=75% more monsters", level: 185));
presses.Add(InferenceTests.P("Blue Taper, Red Taper", "Bounteous=kills drop x1.4 loot", level: 120));
Press raw = new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0];
presses.Add(raw);
presses.Add(InferenceTests.P("Red Taper", "Hardy", complete: false));
return presses;
}
private static unsafe void EveryTab()
{
List<Press> presses = Data();
ThreadsReport report = PressInference.Build(presses);
var panel = new ThreadsPanel { Report = () => report, Presses = () => presses };
var host = new UiHost();
UiWindow w = host.Add(new UiWindow("RynthThreads/Main", "RynthThreads") { DefaultWidth = 440f, DefaultHeight = 480f, MinWidth = 320f, MinHeight = 220f });
void Pass()
{
w.Begin();
panel.Draw(w);
w.End();
}
void OpenAll(IEnumerable<string> ids)
{
foreach (string id in ids) w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvOpen, b: true));
}
void Click(string id) => w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvClicked));
string[] tabs = { "tab.c", "tab.m", "tab.p" };
foreach (string tab in tabs)
{
Pass();
Click(tab);
Pass();
OpenAll(report.Components.Select(c => "c:" + c.Name).Append("c:(none)").Append("c:(all)")
.Concat(report.Combinations.Select(c => "k:" + c.Name))
.Concat(report.Modifiers.Select(m => "m:" + m.Name))
.Concat(presses.Select(p => "p:" + p.Id)));
Pass();
int n = Write(host);
byte[] buf = SubmitBuffer(host);
int rc;
List<ParsedWindow> windows;
string error;
fixed (byte* p = buf) rc = DisplayListParser.Parse(p, n, 4000f, out _, out windows, out error);
Check.Eq(rc, 0, $"{tab}: the engine accepts the list ({error})");
if (rc != 0 || windows.Count != 1) continue;
Check.Eq(windows[0].Title, "RynthThreads", "title (the bar button's tooltip)");
Check.True((windows[0].Flags & WindowFlags.ShowInBar) != 0 && (windows[0].Flags & WindowFlags.BarButton) != 0, "bar button");
Check.True(windows[0].List!.OpCount > 20, $"{tab}: something drawn ({windows[0].List!.OpCount} ops)");
}
string body = System.Text.Encoding.UTF8.GetString(w.Body);
Check.True(body.Contains("Level 190, 4 entries."), "presses tab shows raw lines");
Check.True(body.Contains("Yorick is recalling"), "and the other lines kept beside them");
// Empty data still draws.
var empty = new ThreadsPanel();
w.Begin();
empty.Draw(w);
w.End();
Check.True(System.Text.Encoding.UTF8.GetString(w.Body).Contains("No presses yet"), "empty window explains itself");
}
private static void ServerAndStats()
{
Check.True(RynthThreadsPlugin.IsDreamWeave("DreamWeave"), "DreamWeave");
Check.True(RynthThreadsPlugin.IsDreamWeave("dreamweave PvE"), "any case, extra words");
Check.False(RynthThreadsPlugin.IsDreamWeave("Aelrynth"), "Aelrynth");
Check.False(RynthThreadsPlugin.IsDreamWeave(""), "empty");
Check.False(RynthThreadsPlugin.IsDreamWeave(null), "null");
List<string> lines = RynthThreadsPlugin.StatsLines(PressInference.Build(Data()), @"C:\x\presses.jsonl");
Check.True(lines[0].StartsWith("10 presses (9 complete, 1 incomplete)"), "totals line: " + lines[0]);
Check.True(lines.Any(l => l.StartsWith("Red Taper (5): Bounteous 100%+, Hardy 80%")), "Red Taper line");
Check.True(lines.Any(l => l == "Blue Taper (1): Bounteous 100%"), "Blue Taper line");
Check.True(lines.Any(l => l.StartsWith("No components (4): Hardy 100%")), "No components line");
Check.False(lines.Any(l => l.Contains("Affinity")), "the Affinity group is left out");
Check.True(lines.Contains("+ = more likely with it than without."), "legend");
Check.Eq(lines[^1], @"File: C:\x\presses.jsonl", "file named last");
Check.True(lines.Count <= 9, "short");
}
/// <summary>The window's text ops in order (headers as "== label", indented by Indent ops).</summary>
internal static List<string> TextOf(ReadOnlySpan<byte> b)
{
var lines = new List<string>();
int i = 0, indent = 0;
string Str(ReadOnlySpan<byte> s, int at) =>
System.Text.Encoding.UTF8.GetString(s.Slice(at + 2, s[at] | (s[at + 1] << 8)));
while (i + 4 <= b.Length)
{
byte code = b[i], flags = b[i + 1];
int len = b[i + 2] | (b[i + 3] << 8), at = i + 4;
if (code == UiFormat.OpEnd && len == 0) break;
string pad = new string(' ', indent * 2);
switch (code)
{
case UiFormat.OpText: case UiFormat.OpTextWrapped: case UiFormat.OpTextDisabled: case UiFormat.OpSeparatorText:
lines.Add(pad + Str(b, at)); break;
case UiFormat.OpBulletText: lines.Add(pad + "- " + Str(b, at)); break;
case UiFormat.OpTextColored: lines.Add(pad + Str(b, at + 4)); break;
case UiFormat.OpCollapsingHeader:
string h = Str(b, at + 4);
int cut = h.IndexOf("###", StringComparison.Ordinal);
lines.Add(pad + "== " + (cut >= 0 ? h.Substring(0, cut) : h)); break;
case UiFormat.OpIndent: indent++; break;
case UiFormat.OpUnindent: indent = Math.Max(0, indent - 1); break;
}
i = at + len + ((flags & UiFormat.OpHasBlock) != 0 ? 4 : 0);
}
return lines;
}
private static void RealText()
{
List<Press> presses = InferenceTests.Real();
ThreadsReport report = PressInference.Build(presses);
var panel = new ThreadsPanel { Report = () => report, Presses = () => presses };
var w = new UiWindow("RynthThreads/Main", "RynthThreads");
void Pass() { w.Begin(); panel.Draw(w); w.End(); }
void Open(string id) => w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvOpen, b: true));
Pass();
Open("c:(all)");
Open("c:Lead Scarab");
Pass();
List<string> comp = TextOf(w.Body);
Check.True(comp.Contains("== Lead Scarab (4 presses)"), "Lead Scarab header");
Check.True(comp.Any(l => l.Trim() == "- Guarded 75% (3/4, 30-95%); without: no data; x1.83 to x2.18"), "Guarded line");
Check.True(comp.Any(l => l.Trim() == "- Affinity (any) 100% (4/4, 51-100%); without: no data; 7% to 22%"), "Affinity line");
Check.True(comp.Any(l => l.Trim() == "Amethyst 1, Iron 1, Obsidian 1, Serpentine 1"), "split line");
Check.True(comp.Any(l => l.Trim() == "- Guarded 75% (3/4, 30-95%); x1.83 to x2.18"), "All presses: no comparison");
w.Dispatch(w.KeyOf("tab.m"), new UiEvent(UiFormat.EvClicked));
Pass();
Open("m:Affinity");
Open("m:Guarded");
Pass();
List<string> mods = TextOf(w.Body);
Check.True(mods.Contains("== Guarded 75% (3/4, 30-95%) [harder]") || mods.Contains("== Guarded 75% (3/4, 30-95%)"), "Guarded header");
Check.True(mods.Any(l => l.Trim() == "- Lead Scarab 75% (3/4, 30-95%); without: no data; x1.83 to x2.18"), "Guarded with Lead Scarab");
Check.True(mods.Any(l => l.Trim() == "- Amethyst: 25% (1/4, 5-70%)"), "Affinity by material");
if (Environment.GetEnvironmentVariable("RYNTHTHREADS_DUMP") == "1")
{
Console.WriteLine("---- Components tab ----");
foreach (string l in comp) Console.WriteLine(l);
Console.WriteLine("---- Modifiers tab ----");
foreach (string l in mods) Console.WriteLine(l);
}
}
}