RynthSuite as of 2026-10-05 (internal 8b7d487): navigation no longer stalls after doorway turns, faster target and attack, corpses used from a distance and closed after looting, patrol wall clearance, add-to-loot-profile from an item, WCID loot rules, scroll and slayer fixes, release 2026.10.5.1
This commit is contained in:
parent
12ca25f911
commit
53438c65c1
29 changed files with 3951 additions and 86 deletions
506
Tools/RynthCore.LootSdkTests/LootAddItemTests.cs
Normal file
506
Tools/RynthCore.LootSdkTests/LootAddItemTests.cs
Normal file
|
|
@ -0,0 +1,506 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Loot.Editing;
|
||||
using RynthCore.Loot.VTank;
|
||||
|
||||
namespace RynthCore.LootSdkTests;
|
||||
|
||||
// "Add to loot profile" from a clicked item (2026-10-04): the rule an item
|
||||
// makes (LootItemRules), its placement, and LootEditSession.InsertAndSave on
|
||||
// both formats. The safety tests check the saved file byte for byte: the
|
||||
// original with one rule spliced in, the old file kept as .bak, and the result
|
||||
// opening editable in the in-game editor and loading in the parser the external
|
||||
// editor and the evaluator use. Only temp copies are ever written.
|
||||
internal static partial class Program
|
||||
{
|
||||
private static string _addDir = string.Empty;
|
||||
|
||||
private static void RunLootAddTests(string[] args)
|
||||
{
|
||||
_addDir = Path.Combine(Path.GetTempPath(), "RynthLootAddTests_" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(_addDir);
|
||||
try
|
||||
{
|
||||
TestAddDefaults();
|
||||
TestAddExactPattern();
|
||||
TestAddLikeThis();
|
||||
TestAddPreviewAndOrder();
|
||||
TestAddNative();
|
||||
TestAddUtlInsert(crlf: false);
|
||||
TestAddUtlInsert(crlf: true);
|
||||
TestAddUtlRefusals();
|
||||
TestAddUtlV0();
|
||||
TestAddJsonInsert(crlf: false);
|
||||
TestAddJsonInsert(crlf: true);
|
||||
TestAddJsonEdgeCases();
|
||||
TestAddDeployedCopies(args);
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(_addDir, recursive: true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private static string AddFile(string name, byte[] bytes)
|
||||
{
|
||||
string path = Path.Combine(_addDir, name);
|
||||
File.WriteAllBytes(path, bytes);
|
||||
return path;
|
||||
}
|
||||
|
||||
private static LootItemFacts Pea() => new() { Id = 1, Name = "Copper Pea", ObjectClass = (int)AcObjectClass.Misc, StackSize = 5, MaxStackSize = 100 };
|
||||
private static LootItemFacts Opal() => new() { Id = 2, Name = "Black Opal", ObjectClass = (int)AcObjectClass.Gem, Ints = { [131] = 16, [105] = 6 } };
|
||||
|
||||
private static LootItemRuleDraft BuildOk(LootItemFacts f, LootItemRuleOptions? o = null)
|
||||
{
|
||||
LootItemRuleDraft? d = LootItemRules.Build(f, o ?? new LootItemRuleOptions(), out string error);
|
||||
Check(d != null, $"build {f.Name}: {error}");
|
||||
return d ?? new LootItemRuleDraft();
|
||||
}
|
||||
|
||||
private static string Lines(VTankLootCondition c) => c.NodeType + ":" + string.Join("|", c.DataLines);
|
||||
|
||||
private static void TestAddDefaults()
|
||||
{
|
||||
Console.WriteLine("\n-- LootAdd: rule from an item, defaults --");
|
||||
LootItemRuleDraft opal = BuildOk(Opal());
|
||||
Eq(opal.Rule.Action, VTankLootAction.Keep, "gem: Keep");
|
||||
Eq(opal.Rule.KeepCount, (int?)null, "Keep has no count line");
|
||||
Eq(opal.Rule.Name, "Keep Black Opal", "default name");
|
||||
Eq(string.Join(" ; ", opal.Rule.Conditions.Select(Lines)), "7:11 ; 1:^Black Opal$|1", "name + class conditions");
|
||||
Eq(opal.Rule.CustomExpression, "", "v1 custom expression line (empty)");
|
||||
Check(opal.Rule.Enabled, "enabled");
|
||||
|
||||
LootItemRuleDraft pea = BuildOk(Pea());
|
||||
Eq(pea.Rule.Action, VTankLootAction.KeepUpTo, "stack: Keep #");
|
||||
Eq(pea.Rule.KeepCount, (int?)100, "Keep # defaults to one full stack");
|
||||
Eq(pea.Rule.Name, "Keep 100 Copper Pea", "Keep # name says the count");
|
||||
|
||||
var scroll = new LootItemFacts { Name = "Scroll of Fire Bolt VI", ObjectClass = (int)AcObjectClass.Scroll };
|
||||
Eq(BuildOk(scroll).Rule.Action, VTankLootAction.Read, "spell scroll: Read");
|
||||
|
||||
var bag = new LootItemFacts { Name = "Salvaged Iron", ObjectClass = (int)AcObjectClass.Salvage, Ints = { [131] = 61 } };
|
||||
Eq(BuildOk(bag).Rule.Action, VTankLootAction.Keep, "salvage bag: Keep (it is salvage already)");
|
||||
|
||||
var unstacked = new LootItemFacts { Name = "Mana Stone", ObjectClass = (int)AcObjectClass.ManaStone, StackSize = 3 };
|
||||
Eq(BuildOk(unstacked).Rule.KeepCount, (int?)3, "no max stack known: its own stack");
|
||||
|
||||
LootItemRuleDraft named = BuildOk(Pea(), new LootItemRuleOptions
|
||||
{
|
||||
Match = LootItemMatch.Name, Action = VTankLootAction.Sell, RuleName = " Sell peas\nplease ",
|
||||
});
|
||||
Eq(named.Rule.Action, VTankLootAction.Sell, "action chosen");
|
||||
Eq(named.Rule.KeepCount, (int?)null, "Sell: no count");
|
||||
Eq(named.Rule.Name, "Sell peas please", "rule name: one line, trimmed");
|
||||
Eq(string.Join(" ; ", named.Rule.Conditions.Select(Lines)), "1:^Copper Pea$|1", "name only");
|
||||
|
||||
LootItemRuleDraft kc = BuildOk(Pea(), new LootItemRuleOptions { Action = VTankLootAction.KeepUpTo, KeepCount = 25 });
|
||||
Eq(kc.Rule.KeepCount, (int?)25, "Keep # count chosen");
|
||||
Eq(kc.DefaultName, "Keep 25 Copper Pea", "default name follows the count");
|
||||
|
||||
var unknown = new LootItemFacts { Name = "Odd Thing" };
|
||||
LootItemRuleDraft u = BuildOk(unknown);
|
||||
Eq(u.Match, LootItemMatch.Name, "unknown class: name only");
|
||||
Check(u.Notes.Count == 1, "and says so");
|
||||
|
||||
Check(LootItemRules.Build(new LootItemFacts { ObjectClass = 11 }, new LootItemRuleOptions(), out string e1) == null && e1.Length > 0, "no name: refused");
|
||||
Check(LootItemRules.Build(Pea(), new LootItemRuleOptions { Action = (VTankLootAction)7 }, out string e2) == null && e2.Length > 0, "unknown action: refused");
|
||||
Check(LootItemRules.Build(Pea(), new LootItemRuleOptions { Action = VTankLootAction.KeepUpTo, KeepCount = -1 }, out _) == null, "negative Keep #: refused");
|
||||
}
|
||||
|
||||
private static void TestAddExactPattern()
|
||||
{
|
||||
Console.WriteLine("\n-- LootAdd: exact name patterns --");
|
||||
string name = "Scroll of Fire Bolt (III). [x] a+b? $5 ^ | {1} #9 \\";
|
||||
string pattern = LootItemRules.ExactPattern(name);
|
||||
Check(Regex.IsMatch(name, pattern, RegexOptions.IgnoreCase), "matches its own name");
|
||||
Check(Regex.IsMatch(name.ToUpperInvariant(), pattern, RegexOptions.IgnoreCase), "case-insensitive (as both evaluators match)");
|
||||
Check(!Regex.IsMatch(name + "x", pattern, RegexOptions.IgnoreCase), "not a longer name");
|
||||
Check(!Regex.IsMatch("x" + name, pattern, RegexOptions.IgnoreCase), "not a name with a prefix");
|
||||
Eq(LootItemRules.ExactPattern("Copper Pea"), "^Copper Pea$", "plain names stay readable (spaces not escaped)");
|
||||
Check(!Regex.IsMatch("Copper Peas", LootItemRules.ExactPattern("Copper Pea"), RegexOptions.IgnoreCase), "Copper Pea is not Copper Peas");
|
||||
}
|
||||
|
||||
private static void TestAddLikeThis()
|
||||
{
|
||||
Console.WriteLine("\n-- LootAdd: items like this --");
|
||||
var armor = new LootItemFacts
|
||||
{
|
||||
Name = "Iron Breastplate", ObjectClass = (int)AcObjectClass.Armor,
|
||||
Ints = { [131] = 61, [105] = 7, [28] = 300, [9] = 512, [370] = 2, [374] = 1 },
|
||||
Spells = { "Strength Self VI", "Impenetrability VI", "", "Blade Bane VI", "Fire Bane VI", "Acid Bane VI" },
|
||||
};
|
||||
LootItemRuleDraft d = BuildOk(armor, new LootItemRuleOptions { Match = LootItemMatch.Like });
|
||||
string conds = string.Join(" ; ", d.Rule.Conditions.Select(Lines));
|
||||
Eq(conds, "7:2 ; 12:61|131 ; 3:7|105 ; 12:512|9 ; 3:300|28 ; 2007:3 ; 0:^Strength Self VI$ ; 0:^Impenetrability VI$ ; 0:^Blade Bane VI$ ; 0:^Fire Bane VI$",
|
||||
"class, material, workmanship >=, slot, armor >=, ratings >=, the first 4 spells");
|
||||
Check(!d.Rule.Conditions.Any(c => c.NodeType == VTankNodeTypes.StringValueMatch), "no name condition");
|
||||
Check(d.Notes.Any(n => n.Contains("more than 4 spells")), "says spells were left out");
|
||||
Eq(d.Rule.Name, "Keep like Iron Breastplate", "like name");
|
||||
|
||||
var mace = new LootItemFacts { Name = "Iron Mace", ObjectClass = (int)AcObjectClass.MeleeWeapon, Ints = { [159] = 45, [44] = 20, [48] = 5 } };
|
||||
Eq(string.Join(" ; ", BuildOk(mace, new() { Match = LootItemMatch.Like }).Rule.Conditions.Select(Lines)),
|
||||
"7:1 ; 12:45|159 ; 3:20|44", "melee: wield skill and damage >= (wield skill preferred to weapon skill)");
|
||||
var wand = new LootItemFacts { Name = "Wand", ObjectClass = (int)AcObjectClass.WandStaffOrb, Doubles = { [152] = 1.12 } };
|
||||
Eq(string.Join(" ; ", BuildOk(wand, new() { Match = LootItemMatch.Like }).Rule.Conditions.Select(Lines)),
|
||||
"7:31 ; 5:1.12|152", "caster: elemental damage >=");
|
||||
|
||||
LootItemRuleDraft bare = BuildOk(new LootItemFacts { Name = "Gem", ObjectClass = 11 }, new() { Match = LootItemMatch.Like });
|
||||
Eq(bare.Rule.Conditions.Count, 1, "nothing known: class only");
|
||||
Check(bare.Notes.Any(n => n.Contains("every Gem") && n.Contains("Assess")), "warns that it matches every Gem");
|
||||
|
||||
Check(LootItemRules.Build(new LootItemFacts { Name = "x" }, new() { Match = LootItemMatch.Like }, out string e) == null && e.Length > 0,
|
||||
"like without a class: refused");
|
||||
}
|
||||
|
||||
private static void TestAddPreviewAndOrder()
|
||||
{
|
||||
Console.WriteLine("\n-- LootAdd: preview and placement --");
|
||||
List<string> p = LootItemRules.PreviewLines(BuildOk(Opal(), new() { Match = LootItemMatch.Like }).Rule);
|
||||
Eq(string.Join(" / ", p), "Rule: Keep like Black Opal / Action: Keep / If: Class is Gem / and MaterialType = Black Opal / and ItemWorkmanship >= 6",
|
||||
"preview lines (values by name)");
|
||||
List<string> k = LootItemRules.PreviewLines(BuildOk(Pea()).Rule);
|
||||
Eq(k[1], "Action: Keep # 100", "Keep # preview");
|
||||
Eq(k[3], "and Name matches \"^Copper Pea$\"", "name line");
|
||||
|
||||
Eq(LootItemRules.ChooseIndex(5, i => i == 3 || i == 4), 3, "before the first rule that matches");
|
||||
Eq(LootItemRules.ChooseIndex(5, _ => false), 5, "nothing matches: the end");
|
||||
Eq(LootItemRules.ChooseIndex(0, _ => true), 0, "empty profile: 0");
|
||||
|
||||
VTankLootRule a = BuildOk(Opal()).Rule, b = BuildOk(Opal(), new() { RuleName = "other" }).Rule;
|
||||
Check(LootItemRules.SameRule(a, b), "same rule, names aside");
|
||||
Check(!LootItemRules.SameRule(a, BuildOk(Opal(), new() { Action = VTankLootAction.Sell }).Rule), "another action differs");
|
||||
Check(!LootItemRules.SameRule(a, BuildOk(Opal(), new() { Match = LootItemMatch.Name }).Rule), "other conditions differ");
|
||||
}
|
||||
|
||||
private static void TestAddNative()
|
||||
{
|
||||
Console.WriteLine("\n-- LootAdd: native (JSON) form --");
|
||||
var dropped = new List<string>();
|
||||
LootRule? n = LootItemRules.ToNative(BuildOk(Pea()).Rule, dropped);
|
||||
Check(n != null && dropped.Count == 0, "name + class converts whole");
|
||||
Eq(n?.Action, LootAction.KeepUpTo, "Keep #");
|
||||
Eq(n?.KeepCount, 100, "count");
|
||||
Eq(n == null ? "" : string.Join(" ; ", n.Conditions), "ObjectClass == Misc ; StringKey[1] matches \"^Copper Pea$\"", "conditions");
|
||||
Eq(LootItemRules.ToNative(BuildOk(Opal()).Rule, dropped)?.KeepCount, 1, "Keep: count 1 (the native default)");
|
||||
|
||||
var armor = new LootItemFacts { Name = "Robe", ObjectClass = (int)AcObjectClass.Clothing, Ints = { [28] = 50 }, Spells = { "Epic Strength" } };
|
||||
dropped.Clear();
|
||||
LootRule? like = LootItemRules.ToNative(BuildOk(armor, new() { Match = LootItemMatch.Like }).Rule, dropped);
|
||||
Eq(like == null ? "" : string.Join(" ; ", like.Conditions), "ObjectClass == Clothing ; LongKey[28] >= 50", "spell left out");
|
||||
Eq(dropped.Count, 1, "and named");
|
||||
var onlySpell = new VTankLootRule { Conditions = { new VTankLootCondition(VTankNodeTypes.SpellNameMatch, "0", new[] { "x" }) } };
|
||||
Check(LootItemRules.ToNative(onlySpell, new List<string>()) == null, "a rule left with no conditions is refused (it would match everything)");
|
||||
}
|
||||
|
||||
// ── .utl ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="after"/> is <paramref name="before"/> with the rule count line
|
||||
/// bumped and one block of <paramref name="blockLines"/> lines inserted, nothing else.
|
||||
/// </summary>
|
||||
private static void CheckSplicedUtl(string before, string after, int blockLines, string label)
|
||||
{
|
||||
string nl = before.Contains("\r\n") ? "\r\n" : "\n";
|
||||
Check(after.Contains("\r\n") == (nl == "\r\n"), $"{label}: line endings kept");
|
||||
var a = before.Split(nl).ToList();
|
||||
var b = after.Split(nl).ToList();
|
||||
Eq(b.Count, a.Count + blockLines, $"{label}: one block of {blockLines} lines added");
|
||||
int countLine = a[0] == "UTL" ? 2 : 0;
|
||||
Eq(int.Parse(b[countLine]), int.Parse(a[countLine]) + 1, $"{label}: rule count line +1");
|
||||
b[countLine] = a[countLine];
|
||||
int first = 0;
|
||||
while (first < a.Count && a[first] == b[first]) first++;
|
||||
b.RemoveRange(first, Math.Min(blockLines, b.Count - first));
|
||||
Check(a.SequenceEqual(b), $"{label}: every other line unchanged");
|
||||
}
|
||||
|
||||
private static int RuleLineCount(VTankLootRule r, int version)
|
||||
{
|
||||
string text = VTankLootWriter.Serialize(new VTankLootProfile { FileVersion = version, Rules = { r } });
|
||||
return text.Split('\n').Length - 1 - (version >= 1 ? 3 : 1);
|
||||
}
|
||||
|
||||
private static void TestAddUtlInsert(bool crlf)
|
||||
{
|
||||
string label = crlf ? "utl CRLF" : "utl LF";
|
||||
Console.WriteLine($"\n-- LootAdd: insert into a .utl ({label}) --");
|
||||
string text = crlf ? EditFixture.Replace("\n", "\r\n") : EditFixture;
|
||||
byte[] original = Encoding.UTF8.GetBytes(text);
|
||||
string path = AddFile(crlf ? "add-crlf.utl" : "add.utl", original);
|
||||
var s = new LootEditSession();
|
||||
Check(s.Open(path) && !s.IsReadOnly && s.CanInsert, $"{label}: opens editable");
|
||||
var before = VTankLootParser.LoadFromText(text);
|
||||
|
||||
VTankLootRule rule = BuildOk(Pea()).Rule;
|
||||
Check(s.InsertAndSave(rule, null, 2), $"{label}: inserted at 3: {s.Message}");
|
||||
Check(s.Message.Contains("Added \"Keep 100 Copper Pea\" at 3"), $"{label}: message says what and where ({s.Message})");
|
||||
Check(!s.IsDirty, $"{label}: saved, nothing pending");
|
||||
Eq(s.BuildState("", null).Focus, 2, $"{label}: focus on the new rule (the editor selects it)");
|
||||
byte[] saved = File.ReadAllBytes(path);
|
||||
Check(File.ReadAllBytes(path + ".bak").AsSpan().SequenceEqual(original), $"{label}: .bak == the original bytes");
|
||||
Check(!File.Exists(path + ".tmp"), $"{label}: no .tmp left");
|
||||
CheckSplicedUtl(text, Encoding.UTF8.GetString(saved), RuleLineCount(rule, 1), label);
|
||||
|
||||
// Loads everywhere: the parser (external editor, evaluator, /ra lootparse) and the in-game editor.
|
||||
VTankLootProfile back = VTankLootParser.Load(path);
|
||||
Eq(back.Rules.Count, 6, $"{label}: parser reads 6 rules");
|
||||
Eq(back.Rules[2].Name, "Keep 100 Copper Pea", $"{label}: new rule at 3");
|
||||
Eq(back.Rules[2].KeepCount, (int?)100, $"{label}: its count");
|
||||
Eq(string.Join(" ; ", back.Rules[2].Conditions.Select(Lines)), "7:8 ; 1:^Copper Pea$|1", $"{label}: its conditions");
|
||||
for (int i = 0, j = 0; i < back.Rules.Count; i++)
|
||||
{
|
||||
if (i == 2) continue;
|
||||
VTankLootRule o = before.Rules[j++], n = back.Rules[i];
|
||||
Check(o.Name == n.Name && o.Action == n.Action && o.KeepCount == n.KeepCount && o.Priority == n.Priority
|
||||
&& o.CustomExpression == n.CustomExpression && o.Conditions.Select(Lines).SequenceEqual(n.Conditions.Select(Lines))
|
||||
&& o.Conditions.Select(c => c.LengthCode).SequenceEqual(n.Conditions.Select(c => c.LengthCode)),
|
||||
$"{label}: rule '{o.Name}' unchanged");
|
||||
}
|
||||
Check(back.SalvageCombine != null && back.SalvageCombine.PerMaterial.Count == before.SalvageCombine!.PerMaterial.Count,
|
||||
$"{label}: salvage combine block kept");
|
||||
var again = new LootEditSession();
|
||||
Check(again.Open(path) && !again.IsReadOnly, $"{label}: reopens editable in the in-game editor (round-trips)");
|
||||
Check(again.Encode().AsSpan().SequenceEqual(saved), $"{label}: and would save it byte-identical");
|
||||
|
||||
// At the end, then at the top.
|
||||
Check(s.InsertAndSave(BuildOk(Opal()).Rule, null, -1), $"{label}: append");
|
||||
Eq(VTankLootParser.Load(path).Rules[^1].Name, "Keep Black Opal", $"{label}: appended last");
|
||||
Check(s.InsertAndSave(BuildOk(Opal(), new() { RuleName = "Top" }).Rule, null, 0), $"{label}: insert at the top");
|
||||
Eq(VTankLootParser.Load(path).Rules[0].Name, "Top", $"{label}: first");
|
||||
Eq(VTankLootParser.Load(path).Rules.Count, 8, $"{label}: 8 rules");
|
||||
}
|
||||
|
||||
private static void TestAddUtlRefusals()
|
||||
{
|
||||
Console.WriteLine("\n-- LootAdd: .utl refusals leave the file alone --");
|
||||
byte[] original = Encoding.UTF8.GetBytes(EditFixture);
|
||||
string path = AddFile("refuse.utl", original);
|
||||
var s = new LootEditSession();
|
||||
s.Open(path);
|
||||
Cmd(s, "rename", 0, "half-done edit");
|
||||
Check(s.IsDirty, "an unsaved edit");
|
||||
Check(!s.InsertAndSave(BuildOk(Pea()).Rule, null, 0), "refused while there are unsaved edits");
|
||||
Check(s.Message.Contains("Unsaved changes"), "says why");
|
||||
Check(File.ReadAllBytes(path).AsSpan().SequenceEqual(original), "file untouched");
|
||||
Eq(s.RuleCount, 5, "no phantom rule in the session");
|
||||
|
||||
string odd = EditFixture.Replace("3;1;7", "3;1;7;abc");
|
||||
string opath = AddFile("refuse-odd.utl", Encoding.UTF8.GetBytes(odd));
|
||||
var o = new LootEditSession();
|
||||
o.Open(opath);
|
||||
Check(o.IsReadOnly && !o.CanInsert, "non-round-tripping .utl: no insert");
|
||||
Check(!o.InsertAndSave(BuildOk(Pea()).Rule, null, 0), "refused");
|
||||
Eq(File.ReadAllText(opath), odd, "file untouched");
|
||||
|
||||
// Changed on disk since it was opened: refused, the file reloaded, then it works.
|
||||
string cpath = AddFile("refuse-changed.utl", original);
|
||||
var c = new LootEditSession();
|
||||
c.Open(cpath);
|
||||
string changed = EditFixture.Replace("Keep Coins", "Keep Coins!");
|
||||
File.WriteAllText(cpath, changed);
|
||||
Check(!c.InsertAndSave(BuildOk(Pea()).Rule, null, 0), "file changed on disk: refused");
|
||||
Check(c.Message.Contains("changed on disk"), $"says so ({c.Message})");
|
||||
Eq(File.ReadAllText(cpath), changed, "the other writer's file untouched");
|
||||
Check(!c.IsDirty && c.Profile?.Rules[0].Name == "Keep Coins!", "reloaded their version");
|
||||
Check(c.InsertAndSave(BuildOk(Pea()).Rule, null, 0), "then the add works");
|
||||
Eq(VTankLootParser.Load(cpath).Rules[1].Name, "Keep Coins!", "on top of their change");
|
||||
|
||||
var none = new LootEditSession();
|
||||
Check(!none.InsertAndSave(BuildOk(Pea()).Rule, null, 0), "nothing open: refused");
|
||||
var fresh = new LootEditSession();
|
||||
fresh.Open(Path.Combine(_addDir, "not-there.utl"));
|
||||
Check(!fresh.InsertAndSave(BuildOk(Pea()).Rule, null, 0), "a profile that doesn't exist yet: refused");
|
||||
Check(!File.Exists(Path.Combine(_addDir, "not-there.utl")), "and not created");
|
||||
}
|
||||
|
||||
private static void TestAddUtlV0()
|
||||
{
|
||||
Console.WriteLine("\n-- LootAdd: v0 (headerless) .utl --");
|
||||
string v0 = string.Join("\n", new[] { "1", "Keep Coins", "3;1;7", "7" }) + "\n";
|
||||
string path = AddFile("v0.utl", Encoding.UTF8.GetBytes(v0));
|
||||
var s = new LootEditSession();
|
||||
Check(s.Open(path) && !s.IsReadOnly, "v0 opens editable");
|
||||
VTankLootRule rule = BuildOk(Opal()).Rule;
|
||||
Check(s.InsertAndSave(rule, null, -1), $"append: {s.Message}");
|
||||
string after = File.ReadAllText(path);
|
||||
CheckSplicedUtl(v0, after, RuleLineCount(rule, 0), "v0");
|
||||
Check(!after.Contains("\n\n"), "no custom-expression line in a v0 file");
|
||||
Eq(VTankLootParser.Load(path).Rules.Count, 2, "2 rules");
|
||||
Check(new LootEditSession() is var r && r.Open(path) && !r.IsReadOnly, "reopens editable");
|
||||
}
|
||||
|
||||
// ── .json ────────────────────────────────────────────────────────────
|
||||
|
||||
private static LootProfile JsonFixture()
|
||||
{
|
||||
var p = new LootProfile { Name = "native" };
|
||||
var gems = new LootRule { Name = "Keep gems", Action = LootAction.Keep };
|
||||
gems.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
|
||||
var off = new LootRule { Name = "Off", Enabled = false, Action = LootAction.Sell };
|
||||
off.Conditions.Add(new LongValKeyGECondition { Key = 19, Value = 5000 });
|
||||
var peas = new LootRule { Name = "Peas", Action = LootAction.KeepUpTo, KeepCount = 0 };
|
||||
peas.Conditions.Add(new StringValueCondition { Key = 1, Pattern = "Pea$" });
|
||||
peas.Conditions.Add(new CharacterSkillGECondition { Skill = AcSkillType.Salvaging, Value = 100 });
|
||||
p.Rules.AddRange(new[] { gems, off, peas });
|
||||
p.SalvageCombine = new SalvageCombineSettings { Enabled = true, DefaultBands = "1-6, 7-10" };
|
||||
return p;
|
||||
}
|
||||
|
||||
private static void TestAddJsonInsert(bool crlf)
|
||||
{
|
||||
string label = crlf ? "json CRLF" : "json LF";
|
||||
Console.WriteLine($"\n-- LootAdd: insert into a native .json ({label}) --");
|
||||
string json = System.Text.Json.JsonSerializer.Serialize(JsonFixture(), LootJsonContext.Default.LootProfile).Replace("\r\n", "\n");
|
||||
// A property this build doesn't know: the splice keeps it (LootProfile.Save would drop it).
|
||||
json = json.Replace("\"Name\": \"native\",", "\"Name\": \"native\",\n \"FutureField\": { \"a\": [1, 2] },");
|
||||
if (crlf) json = json.Replace("\n", "\r\n");
|
||||
byte[] original = Encoding.UTF8.GetBytes(json);
|
||||
string path = AddFile(crlf ? "add-crlf.json" : "add.json", original);
|
||||
|
||||
var s = new LootEditSession();
|
||||
Check(s.Open(path) && s.IsReadOnly && s.CanInsert, $"{label}: opens (read-only for edits) and takes an insert");
|
||||
Eq(s.Format, "json", $"{label}: format");
|
||||
var dropped = new List<string>();
|
||||
LootRule native = LootItemRules.ToNative(BuildOk(Pea()).Rule, dropped)!;
|
||||
Check(s.InsertAndSave(BuildOk(Pea()).Rule, native, 1), $"{label}: inserted at 2: {s.Message}");
|
||||
Eq(s.RuleCount, 4, $"{label}: session shows 4 rules");
|
||||
Eq(s.JsonProfile?.Rules[1].Name, "Keep 100 Copper Pea", $"{label}: session's copy has it");
|
||||
byte[] saved = File.ReadAllBytes(path);
|
||||
string after = Encoding.UTF8.GetString(saved);
|
||||
Check(File.ReadAllBytes(path + ".bak").AsSpan().SequenceEqual(original), $"{label}: .bak == original");
|
||||
Check(after.Contains("\"FutureField\": { \"a\": [1, 2] }"), $"{label}: unknown property kept");
|
||||
Check(after.Contains("\r\n") == crlf && (crlf || !after.Contains('\r')), $"{label}: line endings kept");
|
||||
|
||||
// Byte-level: a common prefix and suffix, the middle is the new rule only.
|
||||
int pre = 0;
|
||||
while (pre < json.Length && json[pre] == after[pre]) pre++;
|
||||
int suf = 0;
|
||||
while (suf < json.Length - pre && json[json.Length - 1 - suf] == after[after.Length - 1 - suf]) suf++;
|
||||
Eq(pre + suf, json.Length, $"{label}: the original is all there, in order");
|
||||
string added = after.Substring(pre, after.Length - json.Length);
|
||||
Check(added.Contains("Copper Pea") && !added.Contains("Keep gems") && !added.Contains("\"Peas\""), $"{label}: only the new rule was added");
|
||||
|
||||
LootProfile back = LootProfile.Load(path);
|
||||
Eq(back.Rules.Count, 4, $"{label}: loads with 4 rules (RynthAi's loader, the external editor's)");
|
||||
Eq(back.Rules[1].Name, "Keep 100 Copper Pea", $"{label}: at 2");
|
||||
Eq(back.Rules[1].Action, LootAction.KeepUpTo, $"{label}: action");
|
||||
Eq(back.Rules[1].KeepCount, 100, $"{label}: count");
|
||||
Eq(string.Join(" ; ", back.Rules[1].Conditions), "ObjectClass == Misc ; StringKey[1] matches \"^Copper Pea$\"", $"{label}: conditions");
|
||||
LootProfile orig = JsonFixture();
|
||||
Eq(back.Rules[0].Name, "Keep gems", $"{label}: rule 1 kept");
|
||||
Check(!back.Rules[2].Enabled && back.Rules[2].Action == LootAction.Sell && back.Rules[2].Conditions[0].ToString() == orig.Rules[1].Conditions[0].ToString(),
|
||||
$"{label}: disabled rule kept as it was");
|
||||
Eq(back.Rules[3].KeepCount, 1, $"{label}: (KeepCount 0 reads back as 1 in the native loader, before and after alike)");
|
||||
Eq(LootProfile.Load(path + ".bak").Rules[2].KeepCount, back.Rules[3].KeepCount, $"{label}: same as the original reads");
|
||||
Eq(string.Join(" ; ", back.Rules[3].Conditions), string.Join(" ; ", orig.Rules[2].Conditions), $"{label}: rule 3's conditions kept");
|
||||
Eq(back.SalvageCombine?.DefaultBands, "1-6, 7-10", $"{label}: salvage combine kept");
|
||||
|
||||
// The end, then the top.
|
||||
Check(s.InsertAndSave(BuildOk(Opal()).Rule, LootItemRules.ToNative(BuildOk(Opal()).Rule, dropped), -1), $"{label}: append");
|
||||
Eq(LootProfile.Load(path).Rules[^1].Name, "Keep Black Opal", $"{label}: last");
|
||||
Check(s.InsertAndSave(BuildOk(Opal()).Rule, LootItemRules.ToNative(BuildOk(Opal(), new() { RuleName = "Top" }).Rule, dropped), 0), $"{label}: top");
|
||||
Eq(LootProfile.Load(path).Rules[0].Name, "Top", $"{label}: first");
|
||||
Eq(LootProfile.Load(path).Rules.Count, 6, $"{label}: 6 rules");
|
||||
Check(new LootEditSession() is var r && r.Open(path) && r.RuleCount == 6, $"{label}: the in-game editor opens it");
|
||||
}
|
||||
|
||||
private static void TestAddJsonEdgeCases()
|
||||
{
|
||||
Console.WriteLine("\n-- LootAdd: native .json edge cases --");
|
||||
LootRule native = LootItemRules.ToNative(BuildOk(Opal()).Rule, new List<string>())!;
|
||||
|
||||
string empty = "{\n \"Name\": \"e\",\n \"Rules\": []\n}";
|
||||
string epath = AddFile("empty.json", Encoding.UTF8.GetBytes(empty));
|
||||
var e = new LootEditSession();
|
||||
e.Open(epath);
|
||||
Check(e.InsertAndSave(BuildOk(Opal()).Rule, native, 0), $"empty Rules list: {e.Message}");
|
||||
Eq(LootProfile.Load(epath).Rules.Count, 1, "one rule");
|
||||
Check(File.ReadAllText(epath).StartsWith("{\n \"Name\": \"e\",\n \"Rules\": [\n {"), "indented like the writer");
|
||||
|
||||
byte[] bom = new byte[] { 0xEF, 0xBB, 0xBF }.Concat(Encoding.UTF8.GetBytes("{\"Rules\":[{\"Name\":\"a\",\"Enabled\":true}]}")).ToArray();
|
||||
string bpath = AddFile("bom.json", bom);
|
||||
var b = new LootEditSession();
|
||||
b.Open(bpath);
|
||||
Check(b.InsertAndSave(BuildOk(Opal()).Rule, native, 0), $"BOM, one line: {b.Message}");
|
||||
byte[] bsaved = File.ReadAllBytes(bpath);
|
||||
Check(bsaved[0] == 0xEF && bsaved[1] == 0xBB && bsaved[2] == 0xBF, "BOM kept");
|
||||
Eq(LootProfile.Load(bpath).Rules[1].Name, "a", "old rule now second");
|
||||
|
||||
foreach (var (name, text) in new[]
|
||||
{
|
||||
("norules.json", "{\"Name\":\"x\"}"),
|
||||
("twice.json", "{\"Rules\":[],\"Rules\":[]}"),
|
||||
("notlist.json", "{\"Rules\":{}}"),
|
||||
})
|
||||
{
|
||||
string path = AddFile(name, Encoding.UTF8.GetBytes(text));
|
||||
var s = new LootEditSession();
|
||||
if (!s.Open(path)) { Check(true, $"{name}: doesn't even open"); Eq(File.ReadAllText(path), text, $"{name}: untouched"); continue; }
|
||||
Check(!s.InsertAndSave(BuildOk(Opal()).Rule, native, 0), $"{name}: refused ({s.Message})");
|
||||
Eq(File.ReadAllText(path), text, $"{name}: untouched");
|
||||
}
|
||||
|
||||
// Changed on disk: refused and reloaded, then fine.
|
||||
string json = "{\"Rules\":[{\"Name\":\"a\",\"Enabled\":true}]}";
|
||||
string cpath = AddFile("changed.json", Encoding.UTF8.GetBytes(json));
|
||||
var c = new LootEditSession();
|
||||
c.Open(cpath);
|
||||
string theirs = "{\"Rules\":[{\"Name\":\"b\",\"Enabled\":true}]}";
|
||||
File.WriteAllText(cpath, theirs);
|
||||
Check(!c.InsertAndSave(BuildOk(Opal()).Rule, native, 0), "changed on disk: refused");
|
||||
Eq(File.ReadAllText(cpath), theirs, "theirs untouched");
|
||||
Check(c.InsertAndSave(BuildOk(Opal()).Rule, native, -1), "then fine");
|
||||
Eq(LootProfile.Load(cpath).Rules[0].Name, "b", "on top of theirs");
|
||||
|
||||
Check(!c.InsertAndSave(BuildOk(Opal()).Rule, null, 0), "no native form: refused");
|
||||
}
|
||||
|
||||
/// <summary>Bonus: every deployed loot profile, as a temp copy (the originals are only read).</summary>
|
||||
private static void TestAddDeployedCopies(string[] args)
|
||||
{
|
||||
const string folder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
|
||||
if (!Directory.Exists(folder)) return;
|
||||
var files = Directory.GetFiles(folder, "*.utl").Concat(Directory.GetFiles(folder, "*.json")).ToList();
|
||||
if (files.Count == 0) return;
|
||||
Console.WriteLine($"\n-- LootAdd: deployed profiles, temp copies (bonus, {files.Count}) --");
|
||||
foreach (string src in files)
|
||||
{
|
||||
byte[] original = File.ReadAllBytes(src);
|
||||
string copy = AddFile("deployed-" + Path.GetFileName(src), original);
|
||||
var s = new LootEditSession();
|
||||
if (!s.Open(copy)) { Console.WriteLine($" [skip] {Path.GetFileName(src)}: {s.Message}"); continue; }
|
||||
if (!s.CanInsert)
|
||||
{
|
||||
Check(!s.InsertAndSave(BuildOk(Pea()).Rule, null, 0), $"{Path.GetFileName(src)}: read-only, refused");
|
||||
Check(File.ReadAllBytes(copy).AsSpan().SequenceEqual(original), $"{Path.GetFileName(src)}: untouched");
|
||||
continue;
|
||||
}
|
||||
int count = s.RuleCount;
|
||||
VTankLootRule rule = BuildOk(Pea()).Rule;
|
||||
LootRule? native = LootItemRules.ToNative(rule, new List<string>());
|
||||
int at = count / 2;
|
||||
Check(s.InsertAndSave(rule, native, at), $"{Path.GetFileName(src)}: insert at {at + 1}: {s.Message}");
|
||||
var again = new LootEditSession();
|
||||
Check(again.Open(copy) && again.RuleCount == count + 1, $"{Path.GetFileName(src)}: reopens with {count + 1} rules");
|
||||
if (s.Format == "utl")
|
||||
{
|
||||
Check(!again.IsReadOnly, $"{Path.GetFileName(src)}: still editable");
|
||||
CheckSplicedUtl(LootEditSession_Decode(original), LootEditSession_Decode(File.ReadAllBytes(copy)), RuleLineCount(rule, s.Profile!.FileVersion),
|
||||
Path.GetFileName(src));
|
||||
}
|
||||
Check(File.ReadAllBytes(src).AsSpan().SequenceEqual(original), $"{Path.GetFileName(src)}: the deployed original is untouched");
|
||||
}
|
||||
}
|
||||
|
||||
private static string LootEditSession_Decode(byte[] bytes)
|
||||
{
|
||||
try { return new UTF8Encoding(false, true).GetString(bytes).TrimStart('\uFEFF'); }
|
||||
catch (DecoderFallbackException) { return Encoding.Latin1.GetString(bytes); }
|
||||
}
|
||||
}
|
||||
|
|
@ -43,6 +43,7 @@ internal static partial class Program
|
|||
TestVTankFixtureParse();
|
||||
TestMalformedInputs();
|
||||
RunLootEditTests(args);
|
||||
RunLootAddTests(args);
|
||||
|
||||
Console.WriteLine($"\nGolden tests: {_asserts} assertions, {_fails} failed.");
|
||||
|
||||
|
|
|
|||
295
Tools/RynthCore.PatrolProof/Clearance.cs
Normal file
295
Tools/RynthCore.PatrolProof/Clearance.cs
Normal file
|
|
@ -0,0 +1,295 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Raycasting;
|
||||
|
||||
namespace RynthCore.PatrolProof;
|
||||
|
||||
// "clear" mode: how far each point the dungeon pathfinder lays is from the nearest wall or
|
||||
// edge of the walkable floor (DungeonGeometry.Clearance), by the rule that laid it
|
||||
// (DungeonPathfinder.KindLog), for the patrol from a dozen start cells and for dunnav /
|
||||
// recovery paths between 40 random cell pairs, in each landblock given. Also the route
|
||||
// totals (points, doorway points, lap length, turns), to compare runs before and after a
|
||||
// change, and each leg's least clearance along it (sampled every 0.25 m).
|
||||
//
|
||||
// Run: dotnet run -c Release -- clear [landblock hex ...] [worst N] [human] [csv <file>]
|
||||
internal static class Clearance
|
||||
{
|
||||
private static readonly string[] Buckets = { "<0.25", "<0.50", "<0.75", "<1.00", "<1.50", ">=1.5" };
|
||||
private static readonly double[] Edges = { 0.25, 0.5, 0.75, 1.0, 1.5 };
|
||||
|
||||
public static int Run(string[] args)
|
||||
{
|
||||
string acDir = @"C:\Turbine\Asheron's Call";
|
||||
var lbs = new List<uint>();
|
||||
int worst = 0;
|
||||
string csv = null;
|
||||
bool human = false;
|
||||
var probes = new List<(double X, double Y, double Z)>();
|
||||
var legProbes = new List<double[]>();
|
||||
for (int i = 0; i < args.Length; i++)
|
||||
{
|
||||
string a = args[i];
|
||||
if (a == "worst" && i + 1 < args.Length) worst = int.Parse(args[++i]);
|
||||
else if (a == "csv" && i + 1 < args.Length) csv = args[++i];
|
||||
else if (a == "human") human = true;
|
||||
else if (a == "leg" && i + 6 < args.Length)
|
||||
{
|
||||
var v = Enumerable.Range(1, 6).Select(k => double.Parse(args[i + k], CultureInfo.InvariantCulture)).ToArray();
|
||||
legProbes.Add(v);
|
||||
i += 6;
|
||||
}
|
||||
else if (a == "probe" && i + 3 < args.Length)
|
||||
{
|
||||
probes.Add((double.Parse(args[i + 1], CultureInfo.InvariantCulture), double.Parse(args[i + 2], CultureInfo.InvariantCulture), double.Parse(args[i + 3], CultureInfo.InvariantCulture)));
|
||||
i += 3;
|
||||
}
|
||||
else if (a.Length <= 6 && uint.TryParse(a.Replace("0x", ""), NumberStyles.HexNumber, null, out uint v)) lbs.Add(v);
|
||||
else acDir = a;
|
||||
}
|
||||
if (lbs.Count == 0) lbs.AddRange(new uint[] { 0x6346, 0x6544, 0x0174 });
|
||||
|
||||
var loader = new GeometryLoader();
|
||||
if (!loader.Initialize(acDir)) { Console.WriteLine("Geometry loader failed: " + loader.StatusMessage); return 1; }
|
||||
|
||||
if (human)
|
||||
{
|
||||
var s = new SetupInfo();
|
||||
byte[] data = loader.PortalDat.GetFileData(0x02000001);
|
||||
if (data != null && s.Unpack(data))
|
||||
Console.WriteLine($"Human setup 0x02000001: radius {s.Radius:F3} height {s.Height:F3}, cylinders [{string.Join(", ", s.Cylinders.Select(c => $"r={c.Radius:F3} h={c.Height:F3}"))}], spheres [{string.Join(", ", s.Spheres.Select(c => $"r={c.Radius:F3} z={c.Center.Z:F2}"))}]");
|
||||
else Console.WriteLine("Human setup: could not read");
|
||||
}
|
||||
|
||||
StreamWriter csvOut = csv != null ? new StreamWriter(csv) : null;
|
||||
csvOut?.WriteLine("lb,set,kind,x,y,z,clearance");
|
||||
var pathfinderType = typeof(DungeonPathfinder);
|
||||
|
||||
foreach (uint lb in lbs)
|
||||
{
|
||||
DungeonPathfinder.InvalidateCache();
|
||||
var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat);
|
||||
if (graph.Count == 0) { Console.WriteLine($"0x{lb:X4}: no cells"); continue; }
|
||||
var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS);
|
||||
var floors = loader.DungeonLOS.GetDungeonMapFloorPolygons(lb);
|
||||
Console.WriteLine();
|
||||
Console.WriteLine($"=== 0x{lb:X4}: {graph.Count} cells, {geo.DoorwayCount} openings, floors for {geo.FloorCellCount} cells");
|
||||
foreach (var v in legProbes)
|
||||
{
|
||||
double least = geo.LegClearance(v[0], v[1], v[2], v[3], v[4], v[5], 1.0, 0.5, out double wx, out double wy, out double wz);
|
||||
double cx = wx, cy = wy;
|
||||
double cc = geo.PushClear(ref cx, ref cy, wz, 1.0, 2.5);
|
||||
double la = geo.LegClearance(v[0], v[1], v[2], cx, cy, wz, 1.0, 0.5, out _, out _, out _);
|
||||
double lb2 = geo.LegClearance(cx, cy, wz, v[3], v[4], v[5], 1.0, 0.5, out _, out _, out _);
|
||||
Console.WriteLine($" leg ({v[0]},{v[1]},{v[2]})->({v[3]},{v[4]},{v[5]}): least {least:F2} at ({wx:F2},{wy:F2},{wz:F2}); corner pushed to ({cx:F2},{cy:F2}) clearance {cc:F2}; new legs {la:F2} / {lb2:F2}");
|
||||
foreach (var d in geo.DoorwaysNear(wx, wy, wz, 4.0))
|
||||
Console.WriteLine($" opening {d.CellA:X8}-{d.CellB:X8} ({d.X:F2},{d.Y:F2},{d.Z:F2}) w={d.Width:F2} clearance {geo.Clearance(d.X, d.Y, d.Z, 1.5):F2}; legs {geo.LegClearance(v[0], v[1], v[2], d.X, d.Y, d.Z, 1.0, 0.5, out _, out _, out _):F2} / {geo.LegClearance(d.X, d.Y, d.Z, v[3], v[4], v[5], 1.0, 0.5, out _, out _, out _):F2}");
|
||||
var two = new List<NavPoint> { NP(v[0], v[1], v[2]), NP(v[3], v[4], v[5]) };
|
||||
DungeonPathfinder.KeepLegsOffWalls(geo, two, false);
|
||||
Console.WriteLine(" plugin's leg pass: " + string.Join(" -> ", two.Select(p => $"({X(p):F2},{Y(p):F2})")));
|
||||
}
|
||||
if (legProbes.Count > 0 && probes.Count == 0) continue;
|
||||
if (probes.Count > 0)
|
||||
{
|
||||
foreach (var (px, py, pz) in probes)
|
||||
{
|
||||
var runs = geo.ProbeRuns(px, py, pz, 4.0);
|
||||
Console.WriteLine($" probe ({px}, {py}, {pz}): clearance {geo.Clearance(px, py, pz, 4.0):F2}, on walkable floor {geo.OnWalkableFloor(px, py, pz)}; runs E,ENE,..: {string.Join(" ", runs.Select(r => r.ToString("F2")))}");
|
||||
foreach (var w in geo.WallsNear(px, py, 1.0).OrderBy(w => w.Dist))
|
||||
Console.WriteLine($" wall ({w.X0:F2},{w.Y0:F2})-({w.X1:F2},{w.Y1:F2}) z {w.ZMin:F2}..{w.ZMax:F2} at {w.Dist:F2}");
|
||||
foreach (var f in floors.Where(f => f.Vertices.Any(v => Math.Abs(v.X - px) < 2 && Math.Abs(v.Y - py) < 2)))
|
||||
Console.WriteLine($" floor {f.CellId:X8} up={DungeonGeometry.IsUpwardFloor(f.Vertices)}: " + string.Join(" ", f.Vertices.Select(v => $"({v.X:F2},{v.Y:F2},{v.Z:F2})")));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Patrol from a dozen start cells.
|
||||
var kinds = new Dictionary<NavPoint, string>(ReferenceEqualityComparer.Instance);
|
||||
DungeonPathfinder.KindLog = kinds;
|
||||
var starts = graph.Keys.OrderBy(k => k).Where((k, i) => i % Math.Max(1, graph.Count / 12) == 0).ToList();
|
||||
var patrolSamples = new List<(string Kind, NavPoint P, double C)>();
|
||||
var patrolLegs = new List<double>();
|
||||
var worstLegs = new List<(NavPoint A, NavPoint B, double C, double Wx, double Wy)>();
|
||||
int pts = 0, door = 0, t60 = 0, t120 = 0, off = 0; double len = 0, buildMs = 0;
|
||||
foreach (uint s in starts)
|
||||
{
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
var r = DungeonPathfinder.BuildPatrolRoute(graph, s, null, geo);
|
||||
buildMs += sw.Elapsed.TotalMilliseconds;
|
||||
int n = r.Points.Count;
|
||||
pts += n; door += r.Points.Count(p => p.Doorway);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
var a = r.Points[i]; var b = r.Points[(i + 1) % n];
|
||||
len += Yd(a, b);
|
||||
if (n > 2)
|
||||
{
|
||||
double turn = TurnDeg(a, b, r.Points[(i + 2) % n]);
|
||||
if (turn > 60) t60++;
|
||||
if (turn > 120) t120++;
|
||||
}
|
||||
if (!LegOnFloor(a, b, floors)) off++;
|
||||
double lc = LegClearance(geo, a, b, out double wx, out double wy);
|
||||
patrolLegs.Add(lc);
|
||||
worstLegs.Add((a, b, lc, wx, wy));
|
||||
patrolSamples.Add((kinds.TryGetValue(a, out var k) ? k : "other", a, PointClearance(geo, a)));
|
||||
}
|
||||
}
|
||||
Console.WriteLine($" patrol, {starts.Count} starts: {pts} points ({door} doorway), {len:F0} yd, turns >60 {t60}, >120 {t120}, off-floor legs {off}; built in {buildMs / starts.Count:F0} ms each");
|
||||
Table("patrol", patrolSamples, patrolLegs);
|
||||
|
||||
// Dunnav / recovery paths.
|
||||
kinds.Clear();
|
||||
var rnd = new Random(6346);
|
||||
var ids = graph.Keys.OrderBy(k => k).ToList();
|
||||
var pathSamples = new List<(string Kind, NavPoint P, double C)>();
|
||||
var pathLegs = new List<double>();
|
||||
int pairs = 0, ppts = 0, pdoor = 0, pt60 = 0, poff = 0; double plen = 0;
|
||||
for (int k = 0; k < 40; k++)
|
||||
{
|
||||
uint a = ids[rnd.Next(ids.Count)], b = ids[rnd.Next(ids.Count)];
|
||||
var path = DungeonPathfinder.FindPath(a, b, graph);
|
||||
if (path.Count < 3) continue;
|
||||
pairs++;
|
||||
var na = graph[a]; var nb = graph[b];
|
||||
var r = DungeonPathfinder.BuildNavRoute(path, graph, nb.NS, nb.EW, geo, null, na.NS, na.EW, na.Z, nb.Z);
|
||||
r.Points.Insert(0, new NavPoint { NS = na.NS, EW = na.EW, Z = na.Z / 240.0 });
|
||||
ppts += r.Points.Count; pdoor += r.Points.Count(p => p.Doorway);
|
||||
for (int i = 0; i + 1 < r.Points.Count; i++)
|
||||
{
|
||||
plen += Yd(r.Points[i], r.Points[i + 1]);
|
||||
if (i + 2 < r.Points.Count && TurnDeg(r.Points[i], r.Points[i + 1], r.Points[i + 2]) > 60) pt60++;
|
||||
if (!LegOnFloor(r.Points[i], r.Points[i + 1], floors)) poff++;
|
||||
// Legs from the start cell centre and into the destination aren't the pathfinder's.
|
||||
if (i > 0 && i + 2 < r.Points.Count) pathLegs.Add(LegClearance(geo, r.Points[i], r.Points[i + 1], out _, out _));
|
||||
}
|
||||
for (int i = 1; i + 1 < r.Points.Count; i++)
|
||||
pathSamples.Add((kinds.TryGetValue(r.Points[i], out var kk) ? kk : "other", r.Points[i], PointClearance(geo, r.Points[i])));
|
||||
}
|
||||
DungeonPathfinder.KindLog = null;
|
||||
Console.WriteLine($" dunnav/recovery, {pairs} paths: {ppts} points ({pdoor} doorway), {plen:F0} yd, turns >60 {pt60}, off-floor legs {poff}");
|
||||
Table("paths", pathSamples, pathLegs);
|
||||
|
||||
if (worst > 0)
|
||||
{
|
||||
Console.WriteLine($" worst {worst} patrol points:");
|
||||
foreach (var w in patrolSamples.OrderBy(s => s.C).Take(worst))
|
||||
Console.WriteLine($" {w.Kind,-16} ({X(w.P):F2}, {Y(w.P):F2}, {w.P.Z * 240:F2}) clearance {w.C:F2}");
|
||||
Console.WriteLine($" worst {worst} path points:");
|
||||
foreach (var w in pathSamples.OrderBy(s => s.C).Take(worst))
|
||||
Console.WriteLine($" {w.Kind,-16} ({X(w.P):F2}, {Y(w.P):F2}, {w.P.Z * 240:F2}) clearance {w.C:F2}");
|
||||
Console.WriteLine($" worst {worst} patrol legs:");
|
||||
foreach (var w in worstLegs.OrderBy(s => s.C).Take(worst))
|
||||
Console.WriteLine($" ({X(w.A):F2}, {Y(w.A):F2}, {w.A.Z * 240:F2}) -> ({X(w.B):F2}, {Y(w.B):F2}, {w.B.Z * 240:F2}) least {w.C:F2} at ({w.Wx:F2}, {w.Wy:F2})");
|
||||
}
|
||||
if (csvOut != null)
|
||||
{
|
||||
foreach (var s in patrolSamples) csvOut.WriteLine(Row(lb, "patrol", s));
|
||||
foreach (var s in pathSamples) csvOut.WriteLine(Row(lb, "paths", s));
|
||||
}
|
||||
}
|
||||
csvOut?.Dispose();
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static string Row(uint lb, string set, (string Kind, NavPoint P, double C) s)
|
||||
=> string.Join(",", $"0x{lb:X4}", set, s.Kind,
|
||||
X(s.P).ToString("F2", CultureInfo.InvariantCulture), Y(s.P).ToString("F2", CultureInfo.InvariantCulture),
|
||||
(s.P.Z * 240).ToString("F2", CultureInfo.InvariantCulture), s.C.ToString("F3", CultureInfo.InvariantCulture));
|
||||
|
||||
private static void Table(string set, List<(string Kind, NavPoint P, double C)> samples, List<double> legs)
|
||||
{
|
||||
Console.WriteLine($" {"kind",-18} {"n",5} {"min",5} " + string.Join(" ", Buckets.Select(b => $"{b,6}")));
|
||||
foreach (var g in samples.GroupBy(s => s.Kind).OrderBy(g => g.Key))
|
||||
Line(g.Key, g.Select(s => s.C).ToList());
|
||||
Line("ALL POINTS", samples.Select(s => s.C).ToList());
|
||||
Line("legs (least)", legs);
|
||||
}
|
||||
|
||||
private static void Line(string name, List<double> cs)
|
||||
{
|
||||
var counts = new int[Buckets.Length];
|
||||
foreach (double c in cs)
|
||||
{
|
||||
int b = 0;
|
||||
while (b < Edges.Length && c >= Edges[b]) b++;
|
||||
counts[b]++;
|
||||
}
|
||||
double min = cs.Count > 0 ? cs.Min() : 0;
|
||||
Console.WriteLine($" {name,-18} {cs.Count,5} {min,5:F2} " + string.Join(" ", counts.Select(c => $"{c,6}")));
|
||||
}
|
||||
|
||||
private static double PointClearance(DungeonGeometry geo, NavPoint p) => geo.Clearance(X(p), Y(p), p.Z * 240.0, 3.0);
|
||||
|
||||
// The least clearance along a leg, sampled every 0.25 m, leaving out 0.5 m at each end (the
|
||||
// end points are measured as points; within 0.5 m of a point with 1 m clearance a leg has at
|
||||
// least 0.5 m, so a lower reading there is the sampler taking a stacked floor's height).
|
||||
private static double LegClearance(DungeonGeometry geo, NavPoint a, NavPoint b, out double wx, out double wy)
|
||||
{
|
||||
wx = X(a); wy = Y(a);
|
||||
double ax = X(a), ay = Y(a), bx = X(b), by = Y(b), az = a.Z * 240, bz = b.Z * 240;
|
||||
double len = Math.Sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay));
|
||||
if (len <= 1.0) return 3.0;
|
||||
int steps = Math.Max(1, (int)Math.Ceiling(len / 0.25));
|
||||
double best = 3.0;
|
||||
double zf = az; // follows the floor (ramps aren't straight between the end points)
|
||||
for (int i = 0; i <= steps; i++)
|
||||
{
|
||||
double t = (double)i / steps;
|
||||
if (t * len < 0.5 - 1e-9 || t * len > len - 0.5 + 1e-9)
|
||||
{
|
||||
// still follow the floor's height through the skipped ends
|
||||
double sx0 = ax + (bx - ax) * t, sy0 = ay + (by - ay) * t;
|
||||
if (geo.TryFloorHeight(sx0, sy0, zf, 0.6, out double h0)) zf = h0;
|
||||
continue;
|
||||
}
|
||||
double x = ax + (bx - ax) * t, y = ay + (by - ay) * t;
|
||||
if (geo.TryFloorHeight(x, y, zf, 0.6, out double h)) zf = h;
|
||||
else if (geo.TryFloorHeight(x, y, az + (bz - az) * t, 0.6, out h)) zf = h;
|
||||
double c = geo.Clearance(x, y, zf, 3.0);
|
||||
if (c < best) { best = c; wx = x; wy = y; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static NavPoint NP(double x, double y, double z) => new() { EW = DungeonGeometry.WorldToNav(x), NS = DungeonGeometry.WorldToNav(y), Z = z / 240.0 };
|
||||
|
||||
private static double X(NavPoint p) => DungeonGeometry.NavToWorld(p.EW);
|
||||
private static double Y(NavPoint p) => DungeonGeometry.NavToWorld(p.NS);
|
||||
|
||||
private static double Yd(NavPoint a, NavPoint b) => Math.Sqrt((a.NS - b.NS) * (a.NS - b.NS) + (a.EW - b.EW) * (a.EW - b.EW)) * 240.0;
|
||||
|
||||
private static double TurnDeg(NavPoint a, NavPoint b, NavPoint c)
|
||||
{
|
||||
double ux = b.EW - a.EW, uy = b.NS - a.NS, vx = c.EW - b.EW, vy = c.NS - b.NS;
|
||||
double lu = Math.Sqrt(ux * ux + uy * uy), lv = Math.Sqrt(vx * vx + vy * vy);
|
||||
if (lu < 1e-9 || lv < 1e-9) return 0;
|
||||
double cos = Math.Clamp((ux * vx + uy * vy) / (lu * lv), -1, 1);
|
||||
return Math.Acos(cos) * 180 / Math.PI;
|
||||
}
|
||||
|
||||
// Same test as Program's: every half metre of the leg over some floor polygon near its height.
|
||||
private static bool LegOnFloor(NavPoint a, NavPoint b, List<DungeonLOS.MapPolygon> floors)
|
||||
{
|
||||
double ax = X(a), ay = Y(a), bx = X(b), by = Y(b), za = a.Z * 240.0, zb = b.Z * 240.0;
|
||||
double len = Math.Sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay));
|
||||
int steps = Math.Max(1, (int)(len / 0.5));
|
||||
for (int i = 0; i <= steps; i++)
|
||||
{
|
||||
double t = (double)i / steps, x = ax + (bx - ax) * t, y = ay + (by - ay) * t, z = za + (zb - za) * t;
|
||||
bool ok = false;
|
||||
foreach (var f in floors)
|
||||
{
|
||||
if (!DungeonGeometry.InsidePolygon2D(f.Vertices, x, y)) continue;
|
||||
double fz = f.Vertices.Average(v => v.Z);
|
||||
if (z - fz >= -1.5 && z - fz <= 4.5) { ok = true; break; }
|
||||
}
|
||||
if (!ok) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -32,6 +32,7 @@ internal static class Program
|
|||
{
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
if (args.Length > 0 && args[0] == "clear") return Clearance.Run(args.Skip(1).ToArray());
|
||||
uint lb = 0x6346;
|
||||
string acDir = @"C:\Turbine\Asheron's Call";
|
||||
string dumpDir = null;
|
||||
|
|
|
|||
|
|
@ -95,6 +95,13 @@ internal static unsafe class FakeHost
|
|||
/// <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;
|
||||
/// <summary>Opt-in (set before Create): the server gates combat paces casts on, GetUseDoneSeq
|
||||
/// (answering <see cref="UseDoneSeq"/>) and GetCastBusyState (answering <see cref="CastBusy"/>).</summary>
|
||||
public static bool ServerGates;
|
||||
/// <summary>The count of server UseDone (0x01C7) events the fake reports.</summary>
|
||||
public static int UseDoneSeq;
|
||||
/// <summary>1 while a cast gesture animates (GetCastBusyState), else 0.</summary>
|
||||
public static int CastBusy;
|
||||
public static int VTankSeq;
|
||||
public static int CombatModeValue = 1;
|
||||
/// <summary>Opt-in (set before Create): WieldItem (a wield into a named slot, API v70+). The
|
||||
|
|
@ -119,6 +126,15 @@ internal static unsafe class FakeHost
|
|||
/// <summary>Item id -> wielded location: GetObjectWielderInfo says the player wields it there.</summary>
|
||||
public static readonly Dictionary<uint, uint> Wielded = new();
|
||||
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>
|
||||
public static bool CloseContainerCalls;
|
||||
/// <summary>Every CloseContainer (container id), in order (opt-in with <see cref="CloseContainerCalls"/>).</summary>
|
||||
public static readonly List<uint> Closes = new();
|
||||
/// <summary>The container the client has open (GetGroundContainerId), 0 = none.</summary>
|
||||
public static uint GroundContainer;
|
||||
/// <summary>The item selected in the game (GetSelectedItemId); 0 = none.</summary>
|
||||
public static uint SelectedItem;
|
||||
|
||||
// ANSI strings handed back to tested code stay alive for the whole run.
|
||||
private static readonly Dictionary<string, IntPtr> _ansi = new();
|
||||
|
|
@ -137,9 +153,12 @@ internal static unsafe class FakeHost
|
|||
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; Turns = 0; Casts.Clear();
|
||||
Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1;
|
||||
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
|
||||
ServerGates = false; UseDoneSeq = 0; CastBusy = 0;
|
||||
WieldCalls = false; Wields.Clear();
|
||||
SalvageCalls = false; ExternalMoves.Clear(); SalvageAdds.Clear(); SalvageExecutes.Clear();
|
||||
RefuseSalvageAdd.Clear(); OnSalvageExecute = null; Wielded.Clear(); _panelItems.Clear();
|
||||
CloseContainerCalls = false; Closes.Clear(); GroundContainer = 0;
|
||||
SelectedItem = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -203,6 +222,7 @@ internal static unsafe class FakeHost
|
|||
api.WieldItemFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&WieldItem;
|
||||
}
|
||||
api.GetObjectWcidFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint>)&GetObjectWcid;
|
||||
api.GetSelectedItemIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetSelectedItemId;
|
||||
api.ReadKnownSpellsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, int, int>)&ReadKnownSpells;
|
||||
api.LogFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, void>)&Log;
|
||||
api.WriteToChatFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, int, int>)&WriteToChat;
|
||||
|
|
@ -232,11 +252,22 @@ internal static unsafe class FakeHost
|
|||
api.GetPlayerBaseVitalsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, uint*, uint*, int>)&GetPlayerBaseVitals;
|
||||
api.GetWorldNameFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr>)&GetWorldName;
|
||||
api.GetAccountNameFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr>)&GetAccountName;
|
||||
if (ServerGates)
|
||||
{
|
||||
api.GetUseDoneSeqFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetUseDoneSeq;
|
||||
api.GetCastBusyStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetCastBusyState;
|
||||
}
|
||||
if (VTankFlags >= 0)
|
||||
{
|
||||
api.Version = Math.Max(api.Version, 74u);
|
||||
api.GetVTankStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<int*, int>)&GetVTankState;
|
||||
}
|
||||
if (CloseContainerCalls)
|
||||
{
|
||||
api.Version = Math.Max(api.Version, 76u);
|
||||
api.CloseContainerFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&CloseContainer;
|
||||
api.GetGroundContainerIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetGroundContainerId;
|
||||
}
|
||||
LastApi = api;
|
||||
return new RynthCoreHost(api);
|
||||
}
|
||||
|
|
@ -290,6 +321,12 @@ internal static unsafe class FakeHost
|
|||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetUseDoneSeq() => UseDoneSeq;
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetCastBusyState() => CastBusy;
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int WriteToChat(IntPtr text, int type) { Chat.Add(Marshal.PtrToStringUni(text) ?? ""); return 1; }
|
||||
|
||||
|
|
@ -459,6 +496,9 @@ internal static unsafe class FakeHost
|
|||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static uint GetPlayerId() => PlayerIdValue;
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static uint GetSelectedItemId() => SelectedItem;
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int SetAutoRun(int on) { AutoRun = on != 0; AutoRunCalls.Add(AutoRun); return 1; }
|
||||
|
||||
|
|
@ -481,6 +521,12 @@ internal static unsafe class FakeHost
|
|||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int WieldItem(uint id, uint mask) { Wields.Add((id, mask)); return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int CloseContainer(uint id) { Closes.Add(id); return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static uint GetGroundContainerId() => GroundContainer;
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int MoveItemExternal(uint id, uint target, int amount) { ExternalMoves.Add((id, target, amount)); return 1; }
|
||||
|
||||
|
|
|
|||
|
|
@ -55,6 +55,8 @@ internal static class Program
|
|||
ArcWhenClearTests.Register(runner);
|
||||
UseAtLoginTests.Register(runner);
|
||||
LearnSpellsTests.Register(runner);
|
||||
AttackLatencyTests.Register(runner);
|
||||
LootAddItemTests.Register(runner);
|
||||
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
182
Tools/RynthCore.RynthAiHostTests/Tests/AttackLatencyTests.cs
Normal file
182
Tools/RynthCore.RynthAiHostTests/Tests/AttackLatencyTests.cs
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
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;
|
||||
|
||||
// Attack latency (2026-10-04, "it does a little thinking before it attacks"). Measured from the
|
||||
// client logs: a caster waited for a busy count AC had already lowered inline at the server's
|
||||
// UseDone (the busy hook never sees that decrement), up to the 5 s force-clear, after every cast
|
||||
// and after corpse opens; a killed monster was locked again for one tick from the old scan list;
|
||||
// and the first cast at a new target waited out the Attack Spell Delay left from the last target
|
||||
// although the UseDone and gesture gates already hold it. Plus the [CombatLatency] log line.
|
||||
internal static class AttackLatencyTests
|
||||
{
|
||||
private const uint Player = 0x50000E01;
|
||||
private const uint Lb = 0xA9B40000;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("attack latency: a busy count the server finished (UseDone since it rose, no gesture) is a leftover", BusyLeftover);
|
||||
r.Add("attack latency: without the engine's UseDone counter the busy count always holds", BusyWithoutServerGates);
|
||||
r.Add("attack latency: the first cast at a new target skips the Attack Spell Delay only with the server gates", NewTargetInterval);
|
||||
r.Add("attack latency: a killed monster isn't locked again from the old scan list", NoRelockOfTheDead);
|
||||
r.Add("attack latency: [CombatLatency] charges each wait, one line per engagement, throttled", LatencyLine);
|
||||
}
|
||||
|
||||
// ── Busy leftovers ────────────────────────────────────────────────────────
|
||||
|
||||
private static void BusyLeftover()
|
||||
{
|
||||
// The pure rule.
|
||||
var g = new CombatBusyGate();
|
||||
g.NoteCount(1, useDoneSeqNow: 5);
|
||||
Check.False(g.IsStale(1, true, 5, false), "just rose, no UseDone since: real");
|
||||
Check.True(g.IsStale(1, true, 6, false), "a UseDone since it rose: leftover");
|
||||
Check.False(g.IsStale(1, true, 6, true), "a gesture still animating: real");
|
||||
g.NoteCount(2, useDoneSeqNow: 6);
|
||||
Check.False(g.IsStale(2, true, 6, false), "rose again after that UseDone (a new action): real");
|
||||
g.NoteCount(1, useDoneSeqNow: 6);
|
||||
Check.False(g.IsStale(1, true, 6, false), "a hooked decrement doesn't count as the server finishing");
|
||||
Check.True(g.IsStale(1, true, 7, false), "the next UseDone: leftover");
|
||||
g.NoteCount(0, useDoneSeqNow: 7);
|
||||
Check.False(g.IsStale(0, true, 7, false), "zero is never busy");
|
||||
g.NoteCount(1, useDoneSeqNow: 7);
|
||||
Check.False(g.IsStale(1, true, 7, false), "a fresh rise from zero: real until its UseDone");
|
||||
|
||||
// Through CombatManager and the host.
|
||||
FakeHost.Reset();
|
||||
FakeHost.ServerGates = true;
|
||||
FakeHost.UseDoneSeq = 40;
|
||||
var c = MakeCombat(new LegacyUiSettings());
|
||||
c.BusyCount = 1; // a cast went out: the hooked increment
|
||||
Check.False(c.BusyIsLeftover(), "cast in flight (no UseDone yet): combat waits");
|
||||
FakeHost.CastBusy = 1;
|
||||
FakeHost.UseDoneSeq = 41; // the server finished it, AC lowered the field inline
|
||||
Check.False(c.BusyIsLeftover(), "UseDone in, gesture still animating: combat waits");
|
||||
FakeHost.CastBusy = 0;
|
||||
Check.True(c.BusyIsLeftover(), "UseDone in, gesture over: the count is a leftover");
|
||||
c.BusyCount = 0; // the shared mirror reset (RynthAiPlugin.OnCombatBusyStale)
|
||||
Check.False(c.BusyIsLeftover(), "reset to 0: nothing to wait for");
|
||||
c.BusyCount = 1; // a corpse open (UseObject) after that
|
||||
Check.False(c.BusyIsLeftover(), "a new action after the last UseDone: combat waits");
|
||||
}
|
||||
|
||||
private static void BusyWithoutServerGates()
|
||||
{
|
||||
var g = new CombatBusyGate();
|
||||
g.NoteCount(1, 0);
|
||||
Check.False(g.IsStale(1, hasUseDoneSeq: false, 0, false), "no UseDone counter: never a leftover");
|
||||
|
||||
FakeHost.Reset(); // ServerGates off: an engine without GetUseDoneSeq
|
||||
var c = MakeCombat(new LegacyUiSettings());
|
||||
c.BusyCount = 1;
|
||||
Check.False(c.BusyIsLeftover(), "old engine: the busy count holds as before");
|
||||
}
|
||||
|
||||
// ── Cast interval ─────────────────────────────────────────────────────────
|
||||
|
||||
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(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), 1500.0, "magic, setting 0 (old file): 1500");
|
||||
Check.Eq(CombatManager.AttackIntervalMs(Magic, 1500, true, true), CombatManager.NewTargetCastFloorMs,
|
||||
"magic, new target, server gates: the short floor (UseDone + gesture hold the cast)");
|
||||
Check.Eq(CombatManager.AttackIntervalMs(Magic, 1500, false, true), 1500.0,
|
||||
"magic, new target, no server gates: the setting (it is the only pacing then)");
|
||||
Check.Eq(CombatManager.AttackIntervalMs(Magic, 250, true, true), 250.0, "a setting under the floor stays as set");
|
||||
}
|
||||
|
||||
// ── No re-lock of a killed monster ────────────────────────────────────────
|
||||
|
||||
private static void NoRelockOfTheDead()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
Place(Player, "Me", 96, 96, creature: false);
|
||||
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
uint a = 0x80000301, b = 0x80000302;
|
||||
Place(a, "Olthoi Swarm Nymph", 96, 97.5f); // 1.5 m north: the pick
|
||||
Place(b, "Olthoi Swarm Gardener", 96, 98.0f); // 2.0 m north
|
||||
|
||||
var s = new LegacyUiSettings { MonsterRange = 20 };
|
||||
var host = FakeHost.Create();
|
||||
var cache = FakeHost.MakeCache(host, Player, new[] { a, b });
|
||||
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, a, "the closer Nymph is locked");
|
||||
|
||||
// The kill notice lands between ticks; the next tick picks again before the scan has
|
||||
// run again (it runs at most every 50 ms), so the old list is all it has.
|
||||
c.OnKillNotification("Olthoi Swarm Nymph's perforated corpse falls before you!");
|
||||
Check.Eq(c.activeTargetId, 0, "the kill drops the Nymph");
|
||||
Check.False(c.ScannedTargets.Any(t => (uint)t.Id == a), "and takes it out of the current scan list");
|
||||
c.HandleCombatTrigger();
|
||||
Check.Eq((uint)c.activeTargetId, b, "the next pick is the Gardener, not the dead Nymph again");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[CombatTarget] lock") && l.Contains("0x80000301")), 1,
|
||||
"the Nymph was locked once (before the kill), not again after it");
|
||||
}
|
||||
|
||||
// ── [CombatLatency] ───────────────────────────────────────────────────────
|
||||
|
||||
private static void LatencyLine()
|
||||
{
|
||||
var t = new CombatLatencyTracker();
|
||||
Check.False(t.Pending, "nothing pending before a lock");
|
||||
t.OnLock(1, 1000, killAtMs: 900);
|
||||
t.OnTick(1, 1033, CombatLatencyTracker.Wait.Stance);
|
||||
t.OnTick(1, 1066, CombatLatencyTracker.Wait.Busy);
|
||||
t.OnTick(1, 1100, CombatLatencyTracker.Wait.Interval);
|
||||
Check.Eq(t.Waited(CombatLatencyTracker.Wait.Busy), 33.0, "busy charged with its tick");
|
||||
string? line = t.OnAttack(1, 1133, "Melee", "Olthoi Swarm Nymph");
|
||||
Check.True(line != null, "the first attack logs the engagement");
|
||||
Check.Eq(line, "[CombatLatency] lock->attack 133 ms (stance 33, face 0, busy 33, cast 0, interval 34, other 33) Melee 'Olthoi Swarm Nymph', kill->attack 233 ms",
|
||||
"the line: total, each wait, mode, target, time since the kill");
|
||||
Check.False(t.Pending, "logged once: the next attack at it is not an engagement");
|
||||
Check.True(t.OnAttack(1, 1200, "Melee", null) == null, "a second attack logs nothing");
|
||||
|
||||
t.OnLock(2, 1500);
|
||||
Check.True(t.OnAttack(2, 1600, "Magic", "B") == null, "a second engagement within 1 s is counted, not logged");
|
||||
t.OnLock(3, 2600);
|
||||
string? third = t.OnAttack(3, 2700, "Magic", "C");
|
||||
Check.True((third ?? "").Contains("lock->attack 100 ms"), "the next one logs");
|
||||
Check.True((third ?? "").Contains("(+1 engagements not logged)"), "and says one wasn't");
|
||||
Check.False((third ?? "").Contains("kill->attack"), "a lock that didn't follow a kill has no kill->attack");
|
||||
|
||||
t.OnLock(4, 5000);
|
||||
t.OnTick(5, 5033, CombatLatencyTracker.Wait.Busy); // the target changed without a new lock
|
||||
Check.False(t.Pending, "another target: the engagement is abandoned");
|
||||
Check.True(t.OnAttack(4, 5100, "Melee", null) == null, "and logs nothing");
|
||||
t.OnLock(6, 6000);
|
||||
t.OnDrop();
|
||||
Check.True(t.OnAttack(6, 6100, "Melee", null) == null, "dropped before attacking: nothing");
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static CombatManager MakeCombat(LegacyUiSettings s)
|
||||
{
|
||||
var host = FakeHost.Create();
|
||||
var cache = FakeHost.MakeCache(host, Player, Array.Empty<uint>());
|
||||
var c = new CombatManager(host, s, cache);
|
||||
c.SetPlayerId(Player);
|
||||
return c;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
343
Tools/RynthCore.RynthAiHostTests/Tests/LootAddItemTests.cs
Normal file
343
Tools/RynthCore.RynthAiHostTests/Tests/LootAddItemTests.cs
Normal file
|
|
@ -0,0 +1,343 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Loot.Editing;
|
||||
using RynthCore.Loot.VTank;
|
||||
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;
|
||||
|
||||
// "Add to loot profile" from a clicked item (2026-10-04): /ra loot add on the
|
||||
// selected item, and the Loot Editor bridge's item_preview / item_add (what the
|
||||
// engine's popup sends), against temp copies of a .utl and a native .json
|
||||
// profile. Checks the chat line, the file, the reload into the evaluator that
|
||||
// loots, and that the clicked item is then decided by the new rule.
|
||||
internal static class LootAddItemTests
|
||||
{
|
||||
private const uint Player = 0x50000E01;
|
||||
private const uint Opal = 0x80271101, Taper = 0x80271102, Coin = 0x80271103;
|
||||
private const uint ItemTypeGem = 0x800, ItemTypeComponent = 0x1000;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("loot add: /ra loot add puts 'Keep Black Opal' before the rule that sold it, saves, reloads (.utl)", UtlAddBeforeBroaderRule);
|
||||
r.Add("loot add: native .json profile, same command, the native evaluator keeps it", NativeAdd);
|
||||
r.Add("loot add: nothing takes the item -> appended at the end", AppendWhenNothingMatches);
|
||||
r.Add("loot add: options (sell name, Keep # N, like) and preview leaves the file alone", CommandOptions);
|
||||
r.Add("loot add: refusals (nothing selected, the same rule twice, no profile)", Refusals);
|
||||
r.Add("loot add: the popup's item_preview / item_add / item_close through the editor bridge", BridgePopupFlow);
|
||||
r.Add("loot add: unsaved edits in the Loot Editor block the add (nothing saved behind them)", BridgeRefusesUnderEdits);
|
||||
}
|
||||
|
||||
// ── World and plugin ──────────────────────────────────────────────────────
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new();
|
||||
public readonly WorldObjectCache Cache;
|
||||
|
||||
public Bot()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.Names[Player] = "Tester";
|
||||
FakeHost.Names[Opal] = "Black Opal";
|
||||
FakeHost.ItemTypes[Opal] = ItemTypeGem;
|
||||
FakeHost.Ints[(Opal, 131)] = 16; // MaterialType Black Opal
|
||||
FakeHost.Ints[(Opal, 105)] = 6; // workmanship
|
||||
FakeHost.Names[Taper] = "Prismatic Taper";
|
||||
FakeHost.ItemTypes[Taper] = ItemTypeComponent;
|
||||
FakeHost.Ints[(Taper, 11)] = 100; // MaxStackSize
|
||||
FakeHost.Ints[(Taper, 12)] = 37; // StackCount
|
||||
FakeHost.Names[Coin] = "Pyreal";
|
||||
var host = FakeHost.Create(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, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = FakeHost.MakeCache(host, Player, new[] { Player, Opal, Taper, Coin });
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_charSkills", new CharacterSkills(host));
|
||||
}
|
||||
|
||||
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 Ra(string line)
|
||||
{
|
||||
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
int eat = 0;
|
||||
object[] args = { parts[1].ToLowerInvariant(), parts, eat };
|
||||
typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(P, args);
|
||||
}
|
||||
public string ChatText => string.Join("\n", FakeHost.Chat);
|
||||
public WorldObject Item(uint id) => Cache[unchecked((int)id)]!;
|
||||
}
|
||||
|
||||
private static string Utl(params string[] lines) => string.Join("\n", lines) + "\n";
|
||||
|
||||
// Rule 1 sells every gem, rule 2 keeps pyreals.
|
||||
private static readonly string SellGems = Utl(
|
||||
"UTL", "1", "2",
|
||||
"Sell all gems", "", "0;3;7", "0", "11",
|
||||
"Keep pyreals", "", "0;1;1", "0", "^Pyreal$", "1");
|
||||
|
||||
private static string Temp(string name, string text)
|
||||
{
|
||||
string path = Path.Combine(Program.TempRoot, "lootadd-" + Guid.NewGuid().ToString("N")[..8] + "-" + name);
|
||||
File.WriteAllText(path, text);
|
||||
return path;
|
||||
}
|
||||
|
||||
// ── .utl ──────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void UtlAddBeforeBroaderRule()
|
||||
{
|
||||
var bot = new Bot();
|
||||
string path = Temp("sell-gems.utl", SellGems);
|
||||
bot.S.CurrentLootPath = path;
|
||||
object?[] load = { string.Empty, null, null };
|
||||
Check.True((bool)typeof(RynthAiPlugin).GetMethod("TryLoadLootProfile", Any)!.Invoke(bot.P, load)!, "the profile in use loads");
|
||||
Check.Eq(bot.Get<VTankLootProfile>("_loadedLootProfile")?.Rules.Count, 2, "profile in use: 2 rules");
|
||||
var before = VTankLootEvaluator.FirstMatch(bot.Get<VTankLootProfile>("_loadedLootProfile")!, bot.Item(Opal), null, out _);
|
||||
Check.Eq(before?.Action, VTankLootAction.Sell, "before: the gem rule sells it");
|
||||
|
||||
FakeHost.SelectedItem = Opal;
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Ra("/ra loot add");
|
||||
|
||||
Check.True(FakeHost.Chat.Contains($"[RynthAi] Added loot rule 'Keep Black Opal' to {Path.GetFileName(path)}."),
|
||||
"chat: [RynthAi] Added loot rule 'Keep Black Opal' to <profile>.\n" + bot.ChatText);
|
||||
Check.True(bot.ChatText.Contains("just before rule 1 'Sell all gems'"), "chat says where and why");
|
||||
VTankLootProfile onDisk = VTankLootParser.Load(path);
|
||||
Check.Eq(onDisk.Rules.Count, 3, "3 rules on disk");
|
||||
Check.Eq(onDisk.Rules[0].Name, "Keep Black Opal", "inserted first, before the broader gem rule");
|
||||
Check.Eq(string.Join(" ; ", onDisk.Rules[0].Conditions.Select(c => c.NodeType + ":" + string.Join("|", c.DataLines))),
|
||||
"7:11 ; 1:^Black Opal$|1", "exact name + class");
|
||||
Check.Eq(onDisk.Rules[1].Name, "Sell all gems", "the old rules follow, unchanged");
|
||||
Check.Eq(File.ReadAllText(path + ".bak"), SellGems, ".bak is the original");
|
||||
|
||||
VTankLootProfile? live = bot.Get<VTankLootProfile>("_loadedLootProfile");
|
||||
Check.Eq(live?.Rules.Count, 3, "reloaded at once: the bot loots with 3 rules");
|
||||
var after = VTankLootEvaluator.FirstMatch(live!, bot.Item(Opal), null, out int idx);
|
||||
Check.Eq(after?.Name, "Keep Black Opal", "the clicked gem is now decided by the new rule");
|
||||
Check.Eq(after?.Action, VTankLootAction.Keep, "Keep");
|
||||
var coin = VTankLootEvaluator.FirstMatch(live!, bot.Item(Coin), null, out _);
|
||||
Check.Eq(coin?.Name, "Keep pyreals", "other items: same rule as before");
|
||||
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Ra("/ra lootcheck");
|
||||
Check.True(bot.ChatText.Contains("Black Opal: [Keep] Keep Black Opal"), "/ra lootcheck agrees\n" + bot.ChatText);
|
||||
}
|
||||
|
||||
// ── .json ─────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void NativeAdd()
|
||||
{
|
||||
var bot = new Bot();
|
||||
var p = new LootProfile { Name = "native" };
|
||||
var sell = new LootRule { Name = "Sell gems", Action = LootAction.Sell };
|
||||
sell.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
|
||||
p.Rules.Add(sell);
|
||||
string path = Path.Combine(Program.TempRoot, "lootadd-native-" + Guid.NewGuid().ToString("N")[..8] + ".json");
|
||||
p.Save(path);
|
||||
string original = File.ReadAllText(path);
|
||||
bot.S.CurrentLootPath = path;
|
||||
Check.True((bool)typeof(RynthAiPlugin).GetMethod("TryLoadNativeLootProfile", Any)!.Invoke(bot.P, new object?[] { null, null })!, "native profile loads");
|
||||
|
||||
FakeHost.SelectedItem = Opal;
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Ra("/ra loot add");
|
||||
Check.True(FakeHost.Chat.Contains($"[RynthAi] Added loot rule 'Keep Black Opal' to {Path.GetFileName(path)}."), "chat line\n" + bot.ChatText);
|
||||
LootProfile disk = LootProfile.Load(path);
|
||||
Check.Eq(disk.Rules.Count, 2, "2 rules on disk");
|
||||
Check.Eq(disk.Rules[0].Name, "Keep Black Opal", "before the gem rule");
|
||||
Check.Eq(File.ReadAllText(path + ".bak"), original, ".bak is the original");
|
||||
LootProfile? live = bot.Get<LootProfile>("_nativeLootProfile");
|
||||
Check.Eq(live?.Rules.Count, 2, "reloaded at once");
|
||||
var (action, rule) = LootEvaluator.Classify(live!, bot.Item(Opal), null);
|
||||
Check.Eq(rule?.Name, "Keep Black Opal", "the native evaluator picks the new rule");
|
||||
Check.Eq(action, LootAction.Keep, "Keep");
|
||||
}
|
||||
|
||||
private static void AppendWhenNothingMatches()
|
||||
{
|
||||
var bot = new Bot();
|
||||
string path = Temp("coins-only.utl", Utl("UTL", "1", "1", "Keep pyreals", "", "0;1;1", "0", "^Pyreal$", "1"));
|
||||
bot.S.CurrentLootPath = path;
|
||||
FakeHost.SelectedItem = Opal;
|
||||
bot.Ra("/ra loot add");
|
||||
VTankLootProfile disk = VTankLootParser.Load(path);
|
||||
Check.Eq(disk.Rules.Count, 2, "2 rules");
|
||||
Check.Eq(disk.Rules[1].Name, "Keep Black Opal", "appended (nothing took the gem)");
|
||||
Check.True(bot.ChatText.Contains("at the end"), "chat says why\n" + bot.ChatText);
|
||||
}
|
||||
|
||||
private static void CommandOptions()
|
||||
{
|
||||
var bot = new Bot();
|
||||
string path = Temp("options.utl", SellGems);
|
||||
bot.S.CurrentLootPath = path;
|
||||
|
||||
FakeHost.SelectedItem = Taper;
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Ra("/ra loot add preview");
|
||||
Check.Eq(File.ReadAllText(path), SellGems, "preview: file untouched");
|
||||
Check.False(File.Exists(path + ".bak"), "preview: no save at all");
|
||||
Check.True(bot.ChatText.Contains("Rule: Keep 100 Prismatic Taper") && bot.ChatText.Contains("Action: Keep # 100"),
|
||||
"preview: a stack defaults to Keep # one full stack\n" + bot.ChatText);
|
||||
|
||||
bot.Ra("/ra loot add 25");
|
||||
VTankLootProfile disk = VTankLootParser.Load(path);
|
||||
VTankLootRule kept = disk.Rules.Last();
|
||||
Check.Eq(kept.Name, "Keep 25 Prismatic Taper", "Keep # 25 by number");
|
||||
Check.Eq(kept.Action, VTankLootAction.KeepUpTo, "Keep #");
|
||||
Check.Eq(kept.KeepCount, (int?)25, "count 25");
|
||||
|
||||
FakeHost.SelectedItem = Opal;
|
||||
bot.Ra("/ra loot add sell name");
|
||||
disk = VTankLootParser.Load(path);
|
||||
Check.Eq(disk.Rules[0].Name, "Sell Black Opal", "sell, name only (before the gem rule)");
|
||||
Check.Eq(disk.Rules[0].Conditions.Count, 1, "one condition: the name");
|
||||
|
||||
bot.Ra("/ra loot add like");
|
||||
disk = VTankLootParser.Load(path);
|
||||
// The gem now hits "Sell Black Opal" first, so the like-rule goes before that.
|
||||
Check.Eq(disk.Rules[0].Name, "Keep like Black Opal", "like this: before the rule that takes it now");
|
||||
Check.Eq(string.Join(" ; ", disk.Rules[0].Conditions.Select(c => c.NodeType + ":" + string.Join("|", c.DataLines))),
|
||||
"7:11 ; 12:16|131 ; 3:6|105", "class + material + workmanship >=");
|
||||
Check.Eq(disk.Rules.Count, 5, "5 rules");
|
||||
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Ra("/ra loot add bogus");
|
||||
Check.True(bot.ChatText.Contains("'bogus'?"), "an unknown word is refused");
|
||||
Check.Eq(VTankLootParser.Load(path).Rules.Count, 5, "and adds nothing");
|
||||
}
|
||||
|
||||
private static void Refusals()
|
||||
{
|
||||
var bot = new Bot();
|
||||
string path = Temp("refuse.utl", SellGems);
|
||||
bot.S.CurrentLootPath = path;
|
||||
FakeHost.SelectedItem = 0;
|
||||
bot.Ra("/ra loot add");
|
||||
Check.True(bot.ChatText.Contains("Loot rule not added: No item selected"), "nothing selected\n" + bot.ChatText);
|
||||
Check.Eq(File.ReadAllText(path), SellGems, "untouched");
|
||||
|
||||
FakeHost.SelectedItem = Opal;
|
||||
bot.Ra("/ra loot add");
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Ra("/ra loot add");
|
||||
Check.True(bot.ChatText.Contains("Already there: rule 1 'Keep Black Opal'"), "the same rule twice is refused\n" + bot.ChatText);
|
||||
Check.Eq(VTankLootParser.Load(path).Rules.Count, 3, "one copy only");
|
||||
|
||||
FakeHost.SelectedItem = 0x8027FFFF; // not in the cache
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Ra("/ra loot add");
|
||||
Check.True(bot.ChatText.Contains("doesn't know item"), "unknown item\n" + bot.ChatText);
|
||||
|
||||
bot.S.CurrentLootPath = string.Empty;
|
||||
FakeHost.SelectedItem = Opal;
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Ra("/ra loot add");
|
||||
Check.True(bot.ChatText.Contains("No loot profile selected"), "no profile\n" + bot.ChatText);
|
||||
|
||||
bot.S.CurrentLootPath = path.Replace(".utl", "-missing.utl");
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Ra("/ra loot add");
|
||||
Check.True(bot.ChatText.Contains("not found"), "missing profile\n" + bot.ChatText);
|
||||
Check.False(File.Exists(bot.S.CurrentLootPath), "and not created");
|
||||
}
|
||||
|
||||
// ── The engine's popup, through the bridge ───────────────────────────────
|
||||
|
||||
private static LootEditState State(LootEditorBridge b) =>
|
||||
JsonSerializer.Deserialize(b.StateJson(), LootEditJsonContext.Default.LootEditState)!;
|
||||
|
||||
private static void Send(LootEditorBridge b, LootEditCommand c) =>
|
||||
b.Command(JsonSerializer.Serialize(c, LootEditJsonContext.Default.LootEditCommand));
|
||||
|
||||
private static void BridgePopupFlow()
|
||||
{
|
||||
var bot = new Bot();
|
||||
string path = Temp("popup.utl", SellGems);
|
||||
bot.S.CurrentLootPath = path;
|
||||
LootEditorBridge b = bot.P.LootEditor;
|
||||
Check.Eq(State(b).Rules.Count, 2, "editor shows the profile in use");
|
||||
int rev0 = b.Revision();
|
||||
|
||||
Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Taper, Seq = 7 } });
|
||||
Check.True(b.Revision() != rev0, "a preview moves the revision (the engine refetches)");
|
||||
LootEditState s = State(b);
|
||||
Check.Eq(s.Revision, (long)b.Revision(), "the state's revision is the one Revision() reports");
|
||||
LootEditItemDraft? d = s.ItemDraft;
|
||||
Check.True(d != null && d.Ok, "draft: " + d?.Error);
|
||||
Check.Eq(d?.Seq, 7, "echoes the popup's seq");
|
||||
Check.Eq(d?.ItemName, "Prismatic Taper", "item");
|
||||
Check.Eq(d?.ClassName, "SpellComponent", "class");
|
||||
Check.True(d?.Stackable == true, "stackable");
|
||||
Check.Eq(d?.Action, (int)VTankLootAction.KeepUpTo, "default Keep #");
|
||||
Check.Eq(d?.KeepCount, 100, "one full stack");
|
||||
Check.Eq(d?.RuleName, "Keep 100 Prismatic Taper", "name");
|
||||
Check.Eq(d?.InsertAt, 2, "nothing takes it: the end");
|
||||
Check.Eq(d?.Format, "utl", "format");
|
||||
Check.True(d?.TargetInUse == true, "target is the profile in use");
|
||||
Check.True(d?.Preview.Any(l => l.Contains("Class is SpellComponent")) == true, "preview lines");
|
||||
Check.Eq(File.ReadAllText(path), SellGems, "preview saves nothing");
|
||||
|
||||
// The popup changes its mind: Keep 10, own name. Then Add.
|
||||
Send(b, new LootEditCommand { Op = "item_add", Item = new LootEditItemRequest
|
||||
{
|
||||
ItemId = Taper, Seq = 8, Action = (int)VTankLootAction.KeepUpTo, KeepCount = 10, RuleName = "Tapers", Match = (int)LootItemMatch.Name,
|
||||
} });
|
||||
s = State(b);
|
||||
Check.True(s.ItemDraft?.Added == true, "added: " + s.ItemDraft?.Error);
|
||||
Check.Eq(s.ItemDraft?.Seq, 8, "seq");
|
||||
Check.True(FakeHost.Chat.Contains($"[RynthAi] Added loot rule 'Tapers' to {Path.GetFileName(path)}."), "chat line\n" + bot.ChatText);
|
||||
Check.Eq(s.Rules.Count, 3, "the editor's list has it (same session)");
|
||||
Check.Eq(s.Focus, 2, "and focuses it");
|
||||
Check.Eq(s.Rules[2].Name, "Tapers", "named as asked");
|
||||
Check.False(s.Dirty, "saved");
|
||||
VTankLootRule r = VTankLootParser.Load(path).Rules[2];
|
||||
Check.True(r.Action == VTankLootAction.KeepUpTo && r.KeepCount == 10 && r.Conditions.Count == 1, "Keep # 10 by name only, on disk");
|
||||
Check.Eq(bot.Get<VTankLootProfile>("_loadedLootProfile")?.Rules.Count, 3, "RynthAi reloaded it");
|
||||
|
||||
Send(b, new LootEditCommand { Op = "item_close" });
|
||||
Check.True(State(b).ItemDraft == null, "closed: no draft in the state");
|
||||
|
||||
// ItemId 0 = the selected item.
|
||||
FakeHost.SelectedItem = Opal;
|
||||
Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { Seq = 9, ToOpenProfile = true } });
|
||||
Check.Eq(State(b).ItemDraft?.ItemId, Opal, "0 = the selected item, resolved once");
|
||||
Check.Eq(State(b).ItemDraft?.InsertAt, 0, "before the gem rule");
|
||||
}
|
||||
|
||||
private static void BridgeRefusesUnderEdits()
|
||||
{
|
||||
var bot = new Bot();
|
||||
string path = Temp("edits.utl", SellGems);
|
||||
bot.S.CurrentLootPath = path;
|
||||
LootEditorBridge b = bot.P.LootEditor;
|
||||
_ = State(b);
|
||||
Send(b, new LootEditCommand { Op = "rename", Index = 1, Value = "half-done", Expect = "Keep pyreals" });
|
||||
Check.True(State(b).Dirty, "the editor has an unsaved edit");
|
||||
Send(b, new LootEditCommand { Op = "item_add", Item = new LootEditItemRequest { ItemId = Opal, Seq = 1 } });
|
||||
LootEditItemDraft? d = State(b).ItemDraft;
|
||||
Check.True(d != null && !d.Added && d.Error.Contains("unsaved changes"), "refused: " + d?.Error);
|
||||
Check.True(d != null && d.Preview.Count > 0, "the preview still shows");
|
||||
Check.Eq(File.ReadAllText(path), SellGems, "nothing saved");
|
||||
Check.Eq(State(b).Rules[1].Name, "half-done", "the edit is still there, unsaved");
|
||||
}
|
||||
}
|
||||
|
|
@ -46,6 +46,10 @@ internal static class LootCorpseTests
|
|||
r.Add("loot chain: 'My Kills Only' loots your kill and skips another player's", OwnershipModes);
|
||||
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("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);
|
||||
}
|
||||
|
||||
// ── World set-up ──────────────────────────────────────────────────────────
|
||||
|
|
@ -330,4 +334,110 @@ internal static class LootCorpseTests
|
|||
int lines = FakeHost.Logs.Count(l => l.Contains($"corpse 0x{Corpse:X8} waits for combat"));
|
||||
Check.Eq(lines, 1, "one line for the held corpse, not one per tick");
|
||||
}
|
||||
|
||||
// ── Closing the corpse when done (2026-10-04: "when finished looting I don't think the
|
||||
// corpse closes"). API v76 CloseContainer sends the client's own close packet (0x0195). ──
|
||||
|
||||
/// <summary>Claims, opens and starts looting the corpse; the gem's move has been sent.
|
||||
/// With <paramref name="closeSupported"/> the host has CloseContainer and GetGroundContainerId,
|
||||
/// and the client reports the corpse open (as the engine does after ViewContents).</summary>
|
||||
private static Bot OpenCorpseAndSendPickup(bool closeSupported)
|
||||
{
|
||||
BaseWorld(corpsePositioned: true);
|
||||
FakeHost.CloseContainerCalls = closeSupported;
|
||||
var host = FakeHost.Create(Player);
|
||||
Check.Eq(host.HasCloseContainer, closeSupported, "the host's CloseContainer support");
|
||||
var bot = new Bot(host);
|
||||
bot.Cache.OnCreateObject(Corpse);
|
||||
bot.Cache.Tick();
|
||||
bot.Tick(BotActivity.Looting);
|
||||
Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened");
|
||||
|
||||
bot.Cache.OnCreateObject(Gem);
|
||||
bot.Cache.Tick();
|
||||
if (closeSupported)
|
||||
FakeHost.GroundContainer = Corpse;
|
||||
bot.P.OnViewObjectContents(Corpse);
|
||||
for (int i = 0; i < 100 && !FakeHost.ExternalMoves.Any(m => m.Id == Gem); i++)
|
||||
{
|
||||
bot.Tick(BotActivity.Looting);
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
Check.True(FakeHost.ExternalMoves.Contains((Gem, Player, 0)), "the gem's move is sent");
|
||||
Check.Eq(FakeHost.Closes.Count, 0, "nothing closed while an item is still being looted");
|
||||
return bot;
|
||||
}
|
||||
|
||||
private static bool Completed(Bot bot) =>
|
||||
bot.Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)Corpse));
|
||||
|
||||
/// <summary>The gem lands in the pack; ticks until the corpse is marked completed.</summary>
|
||||
private static void FinishLooting(Bot bot)
|
||||
{
|
||||
FakeHost.Containers[Gem] = Player;
|
||||
for (int i = 0; i < 200 && !Completed(bot); i++)
|
||||
{
|
||||
bot.Tick(BotActivity.Looting);
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
Check.True(Completed(bot), "the corpse is completed once its last item is in the pack");
|
||||
}
|
||||
|
||||
private static void FinishedCorpseClosedOnce()
|
||||
{
|
||||
var bot = OpenCorpseAndSendPickup(closeSupported: true);
|
||||
FinishLooting(bot);
|
||||
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{Corpse:X8}", "the finished corpse is closed, once");
|
||||
Check.Eq(bot.Get<int>("_busyCount"), 0, "the close adds nothing to the busy count");
|
||||
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "the bot no longer holds it open");
|
||||
|
||||
// Until the server's answer lands the client still reports it open: no second close.
|
||||
for (int i = 0; i < 5; i++) bot.Tick(BotActivity.Looting);
|
||||
Check.Eq(FakeHost.Closes.Count, 1, "no re-close while the client still shows it");
|
||||
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "a completed corpse is not re-claimed from the client's state");
|
||||
|
||||
// The server's CloseGroundContainer: the window goes, StopViewingObjectContents follows.
|
||||
FakeHost.GroundContainer = 0;
|
||||
bot.P.OnStopViewingObjectContents(Corpse);
|
||||
for (int i = 0; i < 5; i++) bot.Tick(BotActivity.Looting);
|
||||
Check.Eq(FakeHost.Closes.Count, 1, "still one close after the server's answer");
|
||||
Check.Eq(FakeHost.Uses.Count(u => u == Corpse), 1, "never a UseObject to close it");
|
||||
}
|
||||
|
||||
private static void FinishedCorpseNotClosedOnOldEngine()
|
||||
{
|
||||
var bot = OpenCorpseAndSendPickup(closeSupported: false);
|
||||
FinishLooting(bot);
|
||||
Check.Eq(FakeHost.Closes.Count, 0, "no CloseContainer on an engine before v76");
|
||||
Check.Eq(FakeHost.Uses.Count(u => u == Corpse), 1, "and no UseObject to close it either");
|
||||
}
|
||||
|
||||
private static void AbandonedCorpseClosed()
|
||||
{
|
||||
var bot = OpenCorpseAndSendPickup(closeSupported: true);
|
||||
bot.Call("AbandonCurrentCorpse", Environment.TickCount64, "timeout");
|
||||
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{Corpse:X8}", "the abandoned corpse is closed, once");
|
||||
Check.True(Completed(bot), "an opened corpse that timed out is completed (as before)");
|
||||
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "and released");
|
||||
}
|
||||
|
||||
private static void MacroStopClosesCorpse()
|
||||
{
|
||||
var bot = OpenCorpseAndSendPickup(closeSupported: true);
|
||||
bot.S.IsMacroRunning = false;
|
||||
bot.Call("CloseOpenCorpseOnMacroStop");
|
||||
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{Corpse:X8}", "the open corpse is closed when the macro stops");
|
||||
Check.False(Completed(bot), "not completed: a later run can loot what is left");
|
||||
|
||||
// Macro off, ticking on: no further close before the server's answer.
|
||||
for (int i = 0; i < 5; i++) bot.Tick(BotActivity.Idle);
|
||||
Check.Eq(FakeHost.Closes.Count, 1, "one close");
|
||||
FakeHost.GroundContainer = 0;
|
||||
bot.P.OnStopViewingObjectContents(Corpse);
|
||||
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "the server's answer clears the open corpse");
|
||||
|
||||
// No open corpse: nothing to close.
|
||||
bot.Call("CloseOpenCorpseOnMacroStop");
|
||||
Check.Eq(FakeHost.Closes.Count, 1, "a stop with no corpse open closes nothing");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,7 +19,11 @@ namespace RynthCore.RynthAiHostTests.Tests;
|
|||
// crossing round the corner;
|
||||
// - the patrol over such a dungeon puts no point inside the big room and still goes
|
||||
// through every doorway; a big dead-end room is looked into;
|
||||
// - ceilings are not floors.
|
||||
// - ceilings are not floors;
|
||||
// - every point keeps 1 m from walls and floor edges where the space allows (pushed off a
|
||||
// wall, centred in a narrow corridor, a doorway point moved back along its centre line,
|
||||
// a crypt bend, a dead end's look-in point out of its end cap), and a leg cutting an
|
||||
// inside corner gets a corner.
|
||||
internal static class PatrolDoorwayTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
|
|
@ -34,6 +38,13 @@ internal static class PatrolDoorwayTests
|
|||
r.Add("dungeon patrol: a loop through a big room: no points inside it, every doorway taken", PatrolLoop);
|
||||
r.Add("dungeon patrol: a big dead-end room is looked into, not skirted", PatrolLooksIntoDeadEndRoom);
|
||||
r.Add("dungeon floors: a ceiling (facing down) is not a floor", CeilingIsNotFloor);
|
||||
r.Add("dungeon 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);
|
||||
r.Add("dungeon doorways: a doorway point near the far wall of a T junction moves back along the centre line", DoorwayPointMovesAlongCentreLine);
|
||||
r.Add("dungeon doorways: in a short chamfered bend (crypt corner) the points come off the bend's outer wall", ChamferedBend);
|
||||
r.Add("dungeon patrol: a dead end's look-in point comes out of the end cap onto the floor", DeadEndLookInOnFloor);
|
||||
r.Add("dungeon legs: a leg cutting an inside corner gets a corner put in", LegAroundInsideCorner);
|
||||
}
|
||||
|
||||
// ── Fixture builder ──────────────────────────────────────────────────────
|
||||
|
|
@ -77,6 +88,15 @@ internal static class PatrolDoorwayTests
|
|||
|
||||
public void Wall(uint cell, double x0, double y0, double x1, double y1) => Walls.Add((cell, VerticalQuad(x0, y0, x1, y1)));
|
||||
|
||||
/// <summary>A cell whose origin is (ox, oy) and whose floor is the given polygon (counter-clockwise from above).</summary>
|
||||
public uint CellPoly(double ox, double oy, params (double X, double Y, double Z)[] floor)
|
||||
{
|
||||
uint id = _next++;
|
||||
Graph[id] = new DungeonNavNode { CellId = id, EW = DungeonGeometry.WorldToNav(ox), NS = DungeonGeometry.WorldToNav(oy), Z = 0 };
|
||||
Floors.Add((id, floor.Select(v => new V3((float)v.X, (float)v.Y, (float)v.Z)).ToArray()));
|
||||
return id;
|
||||
}
|
||||
|
||||
public DungeonGeometry Geo() => DungeonGeometry.Build(Graph, Portals, Floors, Walls);
|
||||
}
|
||||
|
||||
|
|
@ -375,6 +395,161 @@ internal static class PatrolDoorwayTests
|
|||
Check.True(geo.OnFloorOfAny(new[] { a }, 5, 5, 0), "so nothing is checked against it");
|
||||
}
|
||||
|
||||
// ── Clearance from walls ─────────────────────────────────────────────────
|
||||
|
||||
private static double Clear(DungeonGeometry geo, NavPoint p) => geo.Clearance(X(p), Y(p), p.Z * 240.0, 3.0);
|
||||
|
||||
private static void ClearanceMeasure()
|
||||
{
|
||||
// A 10 x 10 room, a wall along its west side; a steep slope (2 m up over 1.6 m, about 51
|
||||
// degrees) beyond its east side.
|
||||
var d = new Dungeon();
|
||||
uint room = d.Cell(0, 0, 10, 10);
|
||||
d.Wall(room, 0, 0, 0, 10);
|
||||
d.Floors.Add((room, new[] { new V3(10f, 0f, 0f), new V3(11.6f, 0f, 2f), new V3(11.6f, 10f, 2f), new V3(10f, 10f, 0f) }));
|
||||
// A face across the room's north half that starts 2.5 m up (the face above an arch).
|
||||
d.Walls.Add((room, new[] { new V3(0f, 8f, 2.5f), new V3(10f, 8f, 2.5f), new V3(10f, 8f, 4f), new V3(0f, 8f, 4f) }));
|
||||
var geo = d.Geo();
|
||||
Check.Near(geo.Clearance(0.4, 5, 0), 0.4, 0.06, "0.4 m from the west wall");
|
||||
Check.Near(geo.Clearance(9.3, 5, 0), 0.7, 0.06, "the slope too steep to stand on bounds the floor (0.7 m to its foot)");
|
||||
Check.Near(geo.Clearance(5, 5, 0), 3.0, 1e-6, "the middle: nothing within 3 m (the face 3 m north is 2.5 m up)");
|
||||
Check.Near(geo.Clearance(5, 8.2, 0), 1.8, 0.06, "under the high face: the nearest bound is the room's north edge, 1.8 m away");
|
||||
Check.Eq(geo.Clearance(-0.5, 5, 0), 0.0, "past the floor's edge: 0");
|
||||
Check.Eq(geo.Clearance(10.8, 5, 1), 0.0, "on the steep slope: 0");
|
||||
}
|
||||
|
||||
private static void PushedOffWall()
|
||||
{
|
||||
var d = new Dungeon();
|
||||
uint room = d.Cell(0, 0, 10, 10);
|
||||
d.Wall(room, 0, 0, 0, 10);
|
||||
var geo = d.Geo();
|
||||
double x = 0.3, y = 5;
|
||||
double c = geo.PushClear(ref x, ref y, 0, 1.0, 2.0);
|
||||
Check.True(c >= 0.98, $"pushed to 1 m clearance ({c:F2})");
|
||||
Check.True(x >= 0.98 && x <= 1.2, $"straight out from the wall, not further than needed (x {x:F2})");
|
||||
Check.Near(y, 5, 0.15, "along the wall's normal");
|
||||
|
||||
// Past the floor's edge (a dead end's cell origin inside its end cap): onto the floor first.
|
||||
x = -0.5; y = 5;
|
||||
c = geo.PushClear(ref x, ref y, 0, 1.0, 3.0);
|
||||
Check.True(c >= 0.98 && x > 0, $"onto the floor with 1 m clearance ({x:F2}, {y:F2}: {c:F2})");
|
||||
|
||||
// In the open: left alone.
|
||||
x = 5; y = 5;
|
||||
geo.PushClear(ref x, ref y, 0, 1.0, 2.0);
|
||||
Check.True(x == 5 && y == 5, "a point with room enough is not moved");
|
||||
}
|
||||
|
||||
private static void NarrowCorridorCentred()
|
||||
{
|
||||
var d = new Dungeon();
|
||||
uint corr = d.Cell(0, 0, 20, 1.6);
|
||||
d.Wall(corr, 0, 0, 20, 0);
|
||||
d.Wall(corr, 0, 1.6, 20, 1.6);
|
||||
var geo = d.Geo();
|
||||
double x = 10, y = 0.3;
|
||||
double c = geo.PushClear(ref x, ref y, 0, 1.0, 2.0);
|
||||
Check.Near(y, 0.8, 0.06, $"on the middle line of the 1.6 m corridor (y {y:F2})");
|
||||
Check.Near(c, 0.8, 0.06, "as clear as the corridor allows");
|
||||
Check.Near(x, 10, 0.5, "not moved along the corridor");
|
||||
}
|
||||
|
||||
private static void DoorwayPointMovesAlongCentreLine()
|
||||
{
|
||||
// A room (x 0..10) opening east into a north-south corridor 4.6 m wide (x 10..14.6), like
|
||||
// a hive corridor: the 4 m standoff would put the exit point 0.6 m from the far wall.
|
||||
var d = new Dungeon();
|
||||
uint room = d.Cell(0, 0, 10, 10);
|
||||
uint corr = d.Cell(10, -10, 14.6, 20);
|
||||
d.OpenX(room, corr, 10, 2.35, 7.65);
|
||||
d.Wall(corr, 14.6, -10, 14.6, 20);
|
||||
var geo = d.Geo();
|
||||
var pts = Path(d, geo, 2, 5, 12.3, -8, room, corr);
|
||||
var exit = pts.First(p => X(p) > 10);
|
||||
Check.Near(Y(exit), 5, 1e-3, "the exit point stays on the opening's centre line");
|
||||
Check.Near(X(exit), 13.5, 0.13, $"3.5 m beyond the opening, not 4 (x {X(exit):F2})");
|
||||
Check.True(Clear(geo, exit) >= 0.98, $"1 m from the far wall ({Clear(geo, exit):F2})");
|
||||
Check.True(exit.Doorway, "still a doorway point");
|
||||
Check.Near(X(pts[0]), 6, 1e-3, "the approach in the open room keeps its 4 m");
|
||||
}
|
||||
|
||||
// Rithwic Crypt's corner: a corridor 3.33 m wide comes from the west, a chamfered cell turns
|
||||
// it north. The chamfer strip is 2.36 m across, so the doorway points' centre lines (y 1.67
|
||||
// and x 5) run into its outer wall within a metre of the openings.
|
||||
private static (Dungeon D, uint West, uint Corner, uint North) ChamferDungeon()
|
||||
{
|
||||
var d = new Dungeon();
|
||||
uint west = d.Cell(-10, 0, 0, 3.33);
|
||||
uint corner = d.CellPoly(2.5, 4.2, (0, 0, 0), (6.67, 6.67, 0), (3.33, 6.67, 0), (0, 3.33, 0));
|
||||
uint north = d.Cell(3.33, 6.67, 6.67, 16.67);
|
||||
d.OpenX(west, corner, 0, 0, 3.33);
|
||||
d.OpenY(corner, north, 6.67, 3.33, 6.67);
|
||||
d.Wall(corner, 0, 0, 6.67, 6.67); // the bend's outer wall
|
||||
d.Wall(corner, 0, 3.33, 3.33, 6.67); // its inner wall
|
||||
d.Wall(west, -10, 0, 0, 0); d.Wall(west, -10, 3.33, 0, 3.33);
|
||||
d.Wall(north, 3.33, 6.67, 3.33, 16.67); d.Wall(north, 6.67, 6.67, 6.67, 16.67);
|
||||
return (d, west, corner, north);
|
||||
}
|
||||
|
||||
private static void ChamferedBend()
|
||||
{
|
||||
var (d, west, corner, north) = ChamferDungeon();
|
||||
var geo = d.Geo();
|
||||
var pts = Path(d, geo, -8, 1.67, 5, 15, west, corner, north);
|
||||
var inBend = pts.Where(p => X(p) > 0 && Y(p) < 6.67).ToList();
|
||||
Check.True(inBend.Count >= 1, $"points in the bend ({inBend.Count})");
|
||||
foreach (var p in pts)
|
||||
Check.True(Clear(geo, p) >= 0.98, $"({X(p):F2}, {Y(p):F2}) is 1 m from every wall ({Clear(geo, p):F2})");
|
||||
// Before: the exit point on the west opening's centre line, 1 m in: 0.47 m from the outer wall.
|
||||
Check.True(geo.Clearance(1, 1.67, 0) < 0.5, "the centre line's best spot was under 0.5 m from the outer wall");
|
||||
var cells = new[] { west, corner, north };
|
||||
Check.True(LegsClear(geo, cells, -8, 1.67, pts, 5, 15), "every leg stays on the floor and off the walls");
|
||||
}
|
||||
|
||||
private static void DeadEndLookInOnFloor()
|
||||
{
|
||||
// The loop dungeon with a dead end off its east corner: a corridor (x 45.3..53.7) closed by
|
||||
// a steep end cap (53.7..55.3, 2 m up), its cell origin behind the cap (55.8), as in the
|
||||
// Olthoi hive. The patrol starts there, so it looks into it.
|
||||
var (d, _, _, _, _) = LoopDungeon();
|
||||
uint corner = d.Graph.Values.First(n => Math.Abs(DungeonGeometry.NavToWorld(n.EW) - 42.65) < 0.01 && Math.Abs(DungeonGeometry.NavToWorld(n.NS) - 5) < 0.01).CellId;
|
||||
uint dead = d.CellPoly(55.8, 5, (45.3, 2.35, 0), (53.7, 2.35, 0), (53.7, 7.65, 0), (45.3, 7.65, 0));
|
||||
d.Floors.Add((dead, new[] { new V3(53.7f, 7.65f, 0f), new V3(53.7f, 2.35f, 0f), new V3(55.3f, 5f, 2f) }));
|
||||
d.OpenX(corner, dead, 45.3, 2.35, 7.65);
|
||||
var geo = d.Geo();
|
||||
var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, dead, null, geo);
|
||||
var lookIn = route.Points.Where(p => X(p) > 46 && Math.Abs(Y(p) - 5) < 1).ToList();
|
||||
Check.True(lookIn.Count >= 1, "the patrol walks into the dead end");
|
||||
Check.False(route.Points.Any(p => X(p) > 53.7), "no point on or behind the end cap (the cell origin is at x 55.8)");
|
||||
foreach (var p in lookIn) Check.True(Clear(geo, p) >= 0.98, $"look-in point ({X(p):F2}, {Y(p):F2}) 1 m from the cap and walls ({Clear(geo, p):F2})");
|
||||
}
|
||||
|
||||
private static void LegAroundInsideCorner()
|
||||
{
|
||||
// An L: a corridor down from the north (x 0..3.33) turning east (y 0..3.33); the inside
|
||||
// corner at (3.33, 3.33). A leg from the north arm to the east arm cuts through it.
|
||||
var d = new Dungeon();
|
||||
uint down = d.Cell(0, 3.33, 3.33, 13.33);
|
||||
uint turn = d.Cell(0, 0, 3.33, 3.33);
|
||||
uint across = d.Cell(3.33, 0, 13.33, 3.33);
|
||||
d.OpenY(turn, down, 3.33, 0, 3.33);
|
||||
d.OpenX(turn, across, 3.33, 0, 3.33);
|
||||
d.Wall(down, 3.33, 3.33, 3.33, 13.33);
|
||||
d.Wall(across, 3.33, 3.33, 13.33, 3.33);
|
||||
var geo = d.Geo();
|
||||
NavPoint P(double x, double y) => new() { EW = DungeonGeometry.WorldToNav(x), NS = DungeonGeometry.WorldToNav(y), Z = 0 };
|
||||
var pts = new List<NavPoint> { P(1.67, 8), P(9, 1.67) };
|
||||
Check.True(geo.LegClearance(1.67, 8, 0, 9, 1.67, 0, 1.0, 0.5, out _, out _, out _) < 0.3, "the straight leg passes the inside corner closer than 0.3 m");
|
||||
DungeonPathfinder.KeepLegsOffWalls(geo, pts, closed: false);
|
||||
Check.True(pts.Count >= 3, $"a corner put in ({pts.Count - 2})");
|
||||
for (int i = 0; i + 1 < pts.Count; i++)
|
||||
{
|
||||
double least = geo.LegClearance(X(pts[i]), Y(pts[i]), 0, X(pts[i + 1]), Y(pts[i + 1]), 0, 1.0, 0.5, out _, out _, out _);
|
||||
Check.True(least >= 0.6, $"leg {i} keeps 0.6 m from the corner ({least:F2})");
|
||||
}
|
||||
}
|
||||
|
||||
private static double DistToSegment(double px, double py, double ax, double ay, double bx, double by)
|
||||
{
|
||||
double dx = bx - ax, dy = by - ay, len2 = dx * dx + dy * dy;
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ internal static class VTankLootTests
|
|||
r.Add("loot vtank: DisabledRule node (9999)", DisabledRuleNode);
|
||||
r.Add("loot vtank: string value match", StringValueMatch);
|
||||
r.Add("loot vtank: long keys LE/GE/E/NE and flag, at the boundary", LongKeys);
|
||||
r.Add("loot vtank: Decal's Type key (0x0D000000) is the WCID - 'loot everything that isn't retail'", WcidKey);
|
||||
r.Add("loot vtank: double keys LE/GE", DoubleKeys);
|
||||
r.Add("loot vtank: object class", ObjectClass);
|
||||
r.Add("loot vtank: value and workmanship requirements", ValueAndWorkmanship);
|
||||
|
|
@ -143,6 +144,27 @@ internal static class VTankLootTests
|
|||
Check.True(M(item, C(N.LongValKeyGE, " 1000 ", " 19 ")), "surrounding spaces in data lines are accepted");
|
||||
}
|
||||
|
||||
// Tom (2026-10-04): a rule that loots everything not retail by weenie id. Retail WCIDs on
|
||||
// Aelrynth end at 53488; custom content is above. VTank writes it as LongValKeyGE on Decal's
|
||||
// synthetic "Type" key, which RynthAi now reads as the WCID through the object cache.
|
||||
private static void WcidKey()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var host = FakeHost.Create();
|
||||
var cache = new WorldObjectCache(host);
|
||||
const uint Custom = 0x80001001, Retail = 0x80001002;
|
||||
FakeHost.Wcids[Custom] = 3000105;
|
||||
FakeHost.Wcids[Retail] = 20646;
|
||||
var custom = new WorldObject(unchecked((int)Custom), "Driftwarden Greataxe", AcObjectClass.MeleeWeapon) { Cache = cache };
|
||||
var retail = new WorldObject(unchecked((int)Retail), "Ust", AcObjectClass.Ust) { Cache = cache };
|
||||
string type = WorldObjectCache.DecalTypeKey.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
Check.Eq(custom.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0), 3000105, "the Type key reads the WCID");
|
||||
Check.True(M(custom, C(N.LongValKeyGE, "53489", type)), "custom WCID 3000105 >= 53489: looted");
|
||||
Check.False(M(retail, C(N.LongValKeyGE, "53489", type)), "retail WCID 20646: not");
|
||||
Check.True(M(retail, C(N.LongValKeyE, "20646", type)), "an exact WCID match works too");
|
||||
}
|
||||
|
||||
private static void DoubleKeys()
|
||||
{
|
||||
var item = new Item("x").Dbl(29, 1.25);
|
||||
|
|
|
|||
Loading…
Reference in a new issue