Merge rynth/main (2026.10.8.1) into sk/features-on-rynth-main
Resolves the conflicts that kept PR #2 from merging. Where rynth/main already ships the same feature, its version wins: the shared read-only RynthInstallPaths, /ra iteminfo (PR #2's Mag-Tools item info window is dropped), pet essence refill trust, object filing, spell metadata and the Monster Editor's Category / MatchExpression. See Changelog/2026-10-08-merge-rynth-main-into-pr2.md. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
commit
2e54796b15
160 changed files with 15447 additions and 2566 deletions
|
|
@ -480,7 +480,6 @@ internal static class Program
|
|||
(new SafetyFacts { Appraised = true, Value = 100, CanBeSold = false }, "not sellable"),
|
||||
(new SafetyFacts { Appraised = true, Value = 100, IsRare = true }, "rare"),
|
||||
(new SafetyFacts { Appraised = true, Value = 100, Attuned = 1 }, "attuned"),
|
||||
(new SafetyFacts { Appraised = true, Value = 100, Bonded = 1 }, "bonded"),
|
||||
(new SafetyFacts { Appraised = true, Value = 100, Retained = true }, "retained"),
|
||||
(new SafetyFacts { Appraised = true, Value = 100, TimesTinkered = 1 }, "tinkered"),
|
||||
(new SafetyFacts { Appraised = true, Value = 100, Imbued = 1 }, "imbued"),
|
||||
|
|
@ -495,6 +494,8 @@ internal static class Program
|
|||
|
||||
var side = new SafetyFacts { Appraised = true, Class = AcObjectClass.Salvage, Value = 100, InMainPack = false };
|
||||
Eq(AutoVendorPlanner.UnsafeReason(side, false), null, "side pack ok by default");
|
||||
// Bonded only decides what a death keeps on ACE: peas, trade notes and salvage are bonded and sell (2026-10-07).
|
||||
Eq(AutoVendorPlanner.UnsafeReason(new SafetyFacts { Appraised = true, Value = 12500, Bonded = 1 }, false), null, "bonded (kept on death) still sells");
|
||||
Eq(AutoVendorPlanner.UnsafeReason(side, true), "not in main pack", "OnlyFromMainPack");
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -14,10 +14,10 @@ namespace RynthCore.LootEditor;
|
|||
|
||||
public class MainViewModel : INotifyPropertyChanged
|
||||
{
|
||||
private const string DefaultFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
|
||||
private static readonly string DefaultFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
|
||||
// RynthAi's AutoVendor reads <Vendor Name>.utl / default.utl from here (and from
|
||||
// AutoVendor folders per server and per character, which IsAutoVendorPath also covers).
|
||||
private const string AutoVendorFolder = @"C:\Games\RynthSuite\RynthAi\AutoVendor";
|
||||
private static readonly string AutoVendorFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "AutoVendor");
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
private void Set<T>(ref T field, T value, [CallerMemberName] string? name = null)
|
||||
|
|
|
|||
|
|
@ -22,4 +22,9 @@
|
|||
<ProjectReference Include="..\..\Shared\RynthCore.LootSdk\RynthCore.LootSdk.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
|
||||
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -366,15 +366,7 @@ internal static class TypedEditors
|
|||
RynthCore.Loot.Editing.LootRuleText.LongKeys;
|
||||
|
||||
public static readonly (int Id, string Name)[] DoubleKeys =
|
||||
{
|
||||
(5, "ApproachDistance"),
|
||||
(22, "DamageVariance"),
|
||||
(29, "WeaponLength"),
|
||||
(62, "WeaponDefense"),
|
||||
(63, "WeaponOffense"),
|
||||
(152, "ElementalDamageVsMonsters"),
|
||||
(167, "ManaRate"),
|
||||
};
|
||||
RynthCore.Loot.Editing.LootRuleText.DoubleKeys;
|
||||
|
||||
public static readonly (int Id, string Name)[] StringKeys =
|
||||
{
|
||||
|
|
|
|||
117
Tools/RynthCore.LootSdkTests/LootAddT11Tests.cs
Normal file
117
Tools/RynthCore.LootSdkTests/LootAddT11Tests.cs
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Loot.Editing;
|
||||
using RynthCore.Loot.T11;
|
||||
using RynthCore.Loot.VTank;
|
||||
|
||||
namespace RynthCore.LootSdkTests;
|
||||
|
||||
// "Add to loot profile" with "Include T11 attributes" (2026-10-07): the T11 conditions a
|
||||
// clicked item adds, on the server-format weapon and armor text LootT11Tests parses.
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunLootAddT11Tests()
|
||||
{
|
||||
Console.WriteLine("\n-- LootAdd: include T11 attributes --");
|
||||
TestAddT11Weapon();
|
||||
TestAddT11Armor();
|
||||
TestAddT11EdgeCases();
|
||||
}
|
||||
|
||||
/// <summary>A condition as "type:line,line" for order-sensitive comparisons.</summary>
|
||||
private static string CondText(VTankLootCondition c) => c.NodeType + ":" + string.Join(",", c.DataLines);
|
||||
|
||||
private static string GE(int key, int v) => $"{VTankNodeTypes.LongValKeyGE}:{v},{key}";
|
||||
private static string EQ(int key, int v) => $"{VTankNodeTypes.LongValKeyE}:{v},{key}";
|
||||
|
||||
private static List<string> T11Conds(VTankLootRule r) =>
|
||||
r.Conditions.Where(c => c.DataLines.Count == 2 && int.TryParse(c.DataLines[1], out int k) && T11Keys.IsVirtual(k))
|
||||
.Select(CondText).ToList();
|
||||
|
||||
private static LootItemFacts T11Facts(string name, AcObjectClass cls, string? longDesc, string? use) => new()
|
||||
{
|
||||
Id = 0x7000_0001,
|
||||
Name = name,
|
||||
ObjectClass = (int)cls,
|
||||
T11 = T11ItemInfo.Parse(name, longDesc, use),
|
||||
};
|
||||
|
||||
private static void TestAddT11Weapon()
|
||||
{
|
||||
LootItemFacts f = T11Facts("T11 - Tachi", AcObjectClass.MeleeWeapon, T11WeaponLongDesc, null);
|
||||
|
||||
LootItemRuleDraft? off = LootItemRules.Build(f, new LootItemRuleOptions(), out _);
|
||||
Eq(off == null ? -1 : T11Conds(off.Rule).Count, 0, "add t11: unchecked adds no T11 conditions");
|
||||
|
||||
LootItemRuleDraft? d = LootItemRules.Build(f, new LootItemRuleOptions { IncludeT11 = true }, out string err);
|
||||
Check(d != null, "add t11: weapon builds (" + err + ")");
|
||||
if (d == null) return;
|
||||
Eq(CondText(d.Rule.Conditions[0]), $"{VTankNodeTypes.ObjectClass}:{(int)AcObjectClass.MeleeWeapon}", "add t11: name + class first");
|
||||
Eq(string.Join(" | ", T11Conds(d.Rule)), string.Join(" | ", new[]
|
||||
{
|
||||
EQ(T11Keys.IsT11, 1),
|
||||
GE(T11Keys.EstimatedTier, 13),
|
||||
GE(T11Keys.WeaponGrade, 12),
|
||||
GE(T11Keys.DamagePercent, 86),
|
||||
GE(T11Keys.ForModifier(28), 41), // Damage Rating
|
||||
GE(T11Keys.ForModifier(29), 10), // Crit Damage Rating
|
||||
GE(T11Keys.ForModifier(44), 2), // Pct HP Damage: a slot special with a value
|
||||
GE(T11Keys.CastOnStrikeCount, 1),
|
||||
}), "add t11: weapon conditions, at least this item's");
|
||||
Check(d.Rule.Conditions.All(c => CondText(c) != EQ(T11Keys.HasSlotSpecial, 1)), "add t11: valued special needs no Has Slot Special");
|
||||
Check(d.Rule.Conditions.All(c => CondText(c) != EQ(T11Keys.ZoneLocked, 1)), "add t11: zone lock left out");
|
||||
Eq(d.Notes.Count, 0, "add t11: weapon has no notes");
|
||||
Check(LootItemRules.PreviewLines(d.Rule).Any(l => l.Contains("T11 Mod: Damage Rating")), "add t11: preview names the modifier key");
|
||||
|
||||
var dropped = new List<string>();
|
||||
LootRule? native = LootItemRules.ToNative(d.Rule, dropped);
|
||||
Eq(dropped.Count, 0, "add t11: native format keeps every T11 condition");
|
||||
Eq(native?.Conditions.Count ?? -1, d.Rule.Conditions.Count, "add t11: native condition count");
|
||||
}
|
||||
|
||||
private static void TestAddT11Armor()
|
||||
{
|
||||
LootItemFacts f = T11Facts("T11 - Celdon Breastplate", AcObjectClass.Armor, T11ArmorLongDesc, T11ArmorUse);
|
||||
LootItemRuleDraft? d = LootItemRules.Build(f, new LootItemRuleOptions { IncludeT11 = true }, out _);
|
||||
Check(d != null, "add t11: armor builds");
|
||||
if (d == null) return;
|
||||
List<string> t = T11Conds(d.Rule);
|
||||
Check(t.Contains(GE(T11Keys.EstimatedTier, 16)), "add t11: armor tier from the Triune Weave gate");
|
||||
Check(!t.Any(c => c.EndsWith("," + T11Keys.WeaponGrade)), "add t11: no grade on armor");
|
||||
Check(t.Contains(GE(T11Keys.ForModifier(50), 8)), "add t11: Damage Resist");
|
||||
Check(t.Contains(GE(T11Keys.ForModifier(19), 120)), "add t11: Max Health");
|
||||
Check(t.Contains(GE(T11Keys.ForModifier(47), 2)), "add t11: Max Health Pct");
|
||||
Check(!t.Any(c => c.EndsWith("," + T11Keys.ForModifier(60))), "add t11: unknown modifier has no condition");
|
||||
Check(d.Notes.Any(n => n.Contains("Modifier 60")), "add t11: unknown modifier named in a note");
|
||||
}
|
||||
|
||||
private static void TestAddT11EdgeCases()
|
||||
{
|
||||
// Not T11 gear: a note, no conditions.
|
||||
var plain = new LootItemFacts { Id = 2, Name = "Iron Mace", ObjectClass = (int)AcObjectClass.MeleeWeapon, T11 = T11ItemInfo.None };
|
||||
LootItemRuleDraft? p = LootItemRules.Build(plain, new LootItemRuleOptions { IncludeT11 = true }, out _);
|
||||
Eq(p == null ? -1 : T11Conds(p.Rule).Count, 0, "add t11: non-T11 item adds nothing");
|
||||
Check(p != null && p.Notes.Any(n => n.StartsWith("Not a T11 item")), "add t11: non-T11 note");
|
||||
|
||||
// T11 by name but not identified yet: Is T11 only, and a note to assess it.
|
||||
LootItemFacts unid = T11Facts("T11 - Tachi", AcObjectClass.MeleeWeapon, null, null);
|
||||
LootItemRuleDraft? u = LootItemRules.Build(unid, new LootItemRuleOptions { IncludeT11 = true }, out _);
|
||||
Eq(u == null ? "" : string.Join(" | ", T11Conds(u.Rule)), EQ(T11Keys.IsT11, 1), "add t11: unidentified gives Is T11 only");
|
||||
Check(u != null && u.Notes.Any(n => n.Contains("hasn't been identified")), "add t11: unidentified note");
|
||||
|
||||
// A value-less slot special is required through Has Slot Special.
|
||||
LootItemFacts ring = T11Facts("T11 - Ring", AcObjectClass.Jewelry, null, "Modifiers:\n- Fortify Vitals\n");
|
||||
LootItemRuleDraft? r = LootItemRules.Build(ring, new LootItemRuleOptions { IncludeT11 = true }, out _);
|
||||
Check(r != null && T11Conds(r.Rule).Contains(EQ(T11Keys.HasSlotSpecial, 1)), "add t11: value-less special -> Has Slot Special");
|
||||
|
||||
// "Items like this": T11 conditions count, so the "matches every X" warning goes away.
|
||||
LootItemFacts like = T11Facts("T11 - Tachi", AcObjectClass.MeleeWeapon, T11WeaponLongDesc, null);
|
||||
LootItemRuleDraft? l = LootItemRules.Build(like, new LootItemRuleOptions { Match = LootItemMatch.Like, IncludeT11 = true }, out _);
|
||||
Check(l != null && !l.Notes.Any(n => n.StartsWith("Nothing but the class")), "add t11: like + T11 is not class-only");
|
||||
Check(l != null && l.Rule.Conditions.All(c => c.NodeType != VTankNodeTypes.StringValueMatch), "add t11: like still has no name");
|
||||
LootItemRuleDraft? bare = LootItemRules.Build(plain, new LootItemRuleOptions { Match = LootItemMatch.Like, IncludeT11 = true }, out _);
|
||||
Check(bare != null && bare.Notes.Any(n => n.StartsWith("Nothing but the class")), "add t11: like + non-T11 still warns class-only");
|
||||
}
|
||||
}
|
||||
210
Tools/RynthCore.LootSdkTests/LootT11Tests.cs
Normal file
210
Tools/RynthCore.LootSdkTests/LootT11Tests.cs
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using RynthCore.Loot.Editing;
|
||||
using RynthCore.Loot.T11;
|
||||
|
||||
namespace RynthCore.LootSdkTests;
|
||||
|
||||
// T11 (ACECustom tier 11+) loot support: the item-text parser against the server's exact
|
||||
// strings, tier estimates, the "/aug" reply reader, wield checks, virtual keys, the stripped
|
||||
// wield/rating fallbacks, and the editor's key names and grade table.
|
||||
internal static partial class Program
|
||||
{
|
||||
// A T13 weapon as ACECustom appraises it: Property Details then Modifiers in LongDesc.
|
||||
private const string T11WeaponLongDesc =
|
||||
"A finely made sword.\n\n" +
|
||||
"Property Details:\n" +
|
||||
"- Weapon Grade: B+ (86% of max damage)\n" +
|
||||
"- Wield requires: 3,000 Item Augmentations\n" +
|
||||
"- Wield requires: 25 Crashing Steel\n" +
|
||||
"- Cast on Strike: Force Arc (13% proc chance)\n" +
|
||||
"\n" +
|
||||
"Modifiers:\n" +
|
||||
"- Damage Rating +41 [14-69]\n" +
|
||||
"- Crit Damage Rating +10 [5-15]\n" +
|
||||
"- Pct HP Damage 2%\n" +
|
||||
"- Zone Locked (Power Reduced)\n";
|
||||
|
||||
// T16 armor: gates in LongDesc without a dash, Modifiers in the Use string.
|
||||
private const string T11ArmorLongDesc =
|
||||
"Sturdy plate.\n" +
|
||||
"Wield requires: 4.000 Item Augmentations\n" +
|
||||
"Wield requires: 500 Triune Weave\n";
|
||||
|
||||
private const string T11ArmorUse =
|
||||
"Modifiers:\n" +
|
||||
"- Damage Resist +8 [2-12]\n" +
|
||||
"- Max Health +120 [40-200]\n" +
|
||||
"- Max Health Pct +2% [1-4]\n" +
|
||||
"- Modifier 60 +3 [1-5]\n";
|
||||
|
||||
private static void RunT11Tests()
|
||||
{
|
||||
Console.WriteLine("\n-- T11 loot --");
|
||||
TestT11WeaponParse();
|
||||
TestT11ArmorParse();
|
||||
TestT11NonT11();
|
||||
TestT11Tier();
|
||||
TestT11AugReport();
|
||||
TestT11Keys();
|
||||
TestT11Editor();
|
||||
}
|
||||
|
||||
private static void TestT11WeaponParse()
|
||||
{
|
||||
T11ItemInfo w = T11ItemInfo.Parse("T11 - Tachi", T11WeaponLongDesc, null);
|
||||
Check(w.IsT11 && w.HasNamePrefix, "weapon: T11 by prefix");
|
||||
Eq(w.Grade, "B+", "weapon: grade label");
|
||||
Eq(w.GradeRank, 12, "weapon: grade rank B+ = 12");
|
||||
Eq(w.DamagePercent, 86, "weapon: damage % of max");
|
||||
Eq(w.WieldItemAugs, 3000, "weapon: item-aug gate with group separator");
|
||||
Eq(w.GateAmount(T11Counter.CrashingSteel), 25, "weapon: charm gate");
|
||||
Eq(w.Procs.Count, 1, "weapon: one cast on strike");
|
||||
Eq(w.Procs.Count > 0 ? w.Procs[0].Name : "", "Force Arc", "weapon: proc name");
|
||||
Eq(w.Procs.Count > 0 ? w.Procs[0].ChancePercent : 0, 13.0, "weapon: proc chance");
|
||||
Check(w.ZoneLocked, "weapon: zone locked line inside Modifiers");
|
||||
Eq(w.Modifiers.Count, 3, "weapon: zone lock line is not a modifier");
|
||||
T11Modifier dr = w.Modifiers.First(m => m.Key == 28);
|
||||
Eq(dr.Value, 41, "weapon: Damage Rating value");
|
||||
Eq((dr.Min, dr.Max), ((int?)14, (int?)69), "weapon: Damage Rating band");
|
||||
Eq(dr.RollPercent, 49, "weapon: Damage Rating roll (41-14)/(69-14)");
|
||||
Check(w.Modifiers.Any(m => m.Key == 44 && m.IsSlotSpecial), "weapon: slot special without a band");
|
||||
Check(w.HasSlotSpecial, "weapon: HasSlotSpecial");
|
||||
Eq(w.RatingFromModifiers(370), 41, "weapon: 370 from Damage Rating");
|
||||
Eq(w.RatingFromModifiers(374), 10, "weapon: 374 from Crit Damage Rating");
|
||||
Eq(w.ModifierRatingTotal, 51, "weapon: modifier rating total");
|
||||
Eq(w.EstimatedTier, 13, "weapon: 3,000 gate = T13");
|
||||
Eq(w.BestRollPercent, 50, "weapon: best roll (Crit Damage 10 in 5-15)");
|
||||
}
|
||||
|
||||
private static void TestT11ArmorParse()
|
||||
{
|
||||
T11ItemInfo a = T11ItemInfo.Parse("T11 - Celdon Breastplate", T11ArmorLongDesc, T11ArmorUse);
|
||||
Check(a.IsT11, "armor: T11");
|
||||
Eq(a.Grade, null, "armor: no weapon grade");
|
||||
Eq(a.WieldItemAugs, 4000, "armor: dot group separator, no dash");
|
||||
Eq(a.GateAmount(T11Counter.TriuneWeave), 500, "armor: Triune Weave gate");
|
||||
Eq(a.EstimatedTier, 16, "armor: 500 Triune Weave = T16");
|
||||
Eq(T11Keys.TryGetValue(a, T11Keys.EstimatedTier, null, out int at) ? at : 0, 16, "armor: tier key reads T16");
|
||||
Eq(a.Modifiers.Count, 4, "armor: modifiers from Use");
|
||||
Check(a.Modifiers.Any(m => m.Key == 47 && m.Value == 2), "armor: Max Health Pct is not Max Health");
|
||||
Check(a.Modifiers.Any(m => m.Key == 19 && m.Value == 120), "armor: Max Health");
|
||||
Check(a.Modifiers.Any(m => m.Key == 60 && m.Name == "Modifier 60" && m.Value == 3), "armor: unknown server key kept");
|
||||
Eq(a.RatingFromModifiers(371), 8, "armor: 371 from Damage Resist");
|
||||
Eq(a.RatingFromModifiers(379), 120, "armor: 379 from Max Health");
|
||||
Eq(a.ModifierRatingTotal, 128, "armor: rating total 371 + 379");
|
||||
}
|
||||
|
||||
private static void TestT11NonT11()
|
||||
{
|
||||
Check(!T11ItemInfo.Parse("Tachi", "A finely made sword.", "").IsT11, "plain item is not T11");
|
||||
Check(!T11ItemInfo.Parse(null, null, null).IsT11, "no text is not T11");
|
||||
Check(!T11ItemInfo.Parse("Wand", "- Cast on Strike: Bolt (5% proc chance)", null).IsT11, "a proc alone doesn't mark T11");
|
||||
Check(T11ItemInfo.Parse("T11 - Robe", null, null).IsT11, "unappraised T11 name still T11");
|
||||
Eq(T11ItemInfo.Parse("T11 - Robe", null, null).EstimatedTier, 11, "unappraised T11 = tier 11");
|
||||
Check(!T11ItemInfo.Parse("T11 - Robe", null, null).HasText, "unappraised T11 has no text");
|
||||
Eq(T11Keys.TryGetValue(T11ItemInfo.Parse("T11 - Robe", null, null), T11Keys.CanWield, new T11PlayerAugs(), out int cw) ? cw : 99, -1,
|
||||
"unappraised T11: Can Wield unknown");
|
||||
Eq(T11Keys.TryGetValue(T11ItemInfo.Parse("T11 - Robe", "A robe.", null), T11Keys.CanWield, null, out int cw2) ? cw2 : 99, 1,
|
||||
"appraised T11 without a gate: wieldable");
|
||||
Check(!T11ItemInfo.Parse("x", "Modifiers:\n- ", "\n\n- [").IsT11, "malformed text doesn't throw or mark");
|
||||
}
|
||||
|
||||
private static void TestT11Tier()
|
||||
{
|
||||
Eq(T11Catalog.EstimateTier(0, false), 0, "tier: nothing");
|
||||
Eq(T11Catalog.EstimateTier(2000, true), 11, "tier: 2,000 = T11");
|
||||
Eq(T11Catalog.EstimateTier(2500, true), 12, "tier: 2,500 = T12");
|
||||
Eq(T11Catalog.EstimateTier(3500, true), 14, "tier: 3,500 = T14");
|
||||
Eq(T11Catalog.EstimateTier(9000, true), 15, "tier: capped at 15");
|
||||
|
||||
// T16-T25: the item-aug gate is frozen at 4,000, the Triune Weave gate carries the tier.
|
||||
Eq(T11Catalog.EstimateTier(4000, 0, true), 15, "tier: 4,000 without Triune = T15");
|
||||
Eq(T11Catalog.EstimateTier(3000, 0, true), 13, "tier: no Triune falls back to the item-aug gate");
|
||||
Eq(T11Catalog.EstimateTier(4000, 500, true), 16, "tier: 500 Triune = T16");
|
||||
Eq(T11Catalog.EstimateTier(4000, 1500, true), 18, "tier: 1,500 Triune = T18");
|
||||
Eq(T11Catalog.EstimateTier(4000, 5000, true), 25, "tier: 5,000 Triune = T25");
|
||||
Eq(T11Catalog.EstimateTier(4000, 9000, true), T11Catalog.MaxTier, "tier: capped at T25");
|
||||
Eq(T11Catalog.EstimateTier(4000, 250, true), 16, "tier: any Triune gate is at least T16");
|
||||
Eq(T11Catalog.EstimateTier(0, 0, false), 0, "tier: nothing (three-argument)");
|
||||
|
||||
// A T25 weapon as appraised: item augs frozen at 4,000, Triune and family charm 5,000 each.
|
||||
T11ItemInfo t25 = T11ItemInfo.Parse("T11 - Tachi",
|
||||
"Property Details:\n" +
|
||||
"- Weapon Grade: A (95% of max damage)\n" +
|
||||
"- Wield requires: 4,000 Item Augmentations\n" +
|
||||
"- Wield requires: 5,000 Triune Weave\n" +
|
||||
"- Wield requires: 5,000 Crashing Steel\n", null);
|
||||
Eq(t25.EstimatedTier, 25, "tier: T25 weapon from its Triune gate");
|
||||
Eq(t25.GateAmount(T11Counter.CrashingSteel), 5000, "tier: T25 weapon charm gate");
|
||||
}
|
||||
|
||||
private static void TestT11AugReport()
|
||||
{
|
||||
var p = new T11PlayerAugs();
|
||||
var r = new T11AugReportParser();
|
||||
Check(!r.Feed("Item:2,500", 0, p), "aug: Item line before the header ignored");
|
||||
Check(!r.Feed("Advanced Augmentation Levels:", 1000, p), "aug: header opens the window");
|
||||
Check(r.Feed("Item:2,500", 1100, p), "aug: Item line read");
|
||||
Check(r.Feed("Triune Weave: 3 (adds 3% damage)", 1200, p), "aug: Triune Weave read");
|
||||
Check(r.Feed("Crashing Steel Charm: 20", 1300, p), "aug: charm read");
|
||||
Check(!r.Feed("Item:9999", 1300 + T11AugReportParser.WindowMs + 1, p), "aug: window closes");
|
||||
Eq(p.Get(T11Counter.ItemAugmentations), (long?)2500, "aug: item count");
|
||||
Eq(p.Get(T11Counter.TriuneWeave), (long?)3, "aug: triune count");
|
||||
Eq(p.Get(T11Counter.NetherVeil), null, "aug: unreported counter unknown");
|
||||
|
||||
T11ItemInfo weapon = T11ItemInfo.Parse("T11 - Tachi", T11WeaponLongDesc, null);
|
||||
Eq(p.CanWield(weapon), 0, "wield: 2,500 < 3,000");
|
||||
p.ItemAugOverride = 3000;
|
||||
Eq(p.CanWield(weapon), 0, "wield: crashing steel 20 < 25");
|
||||
p.Set(T11Counter.CrashingSteel, 25);
|
||||
Eq(p.CanWield(weapon), 1, "wield: override + charm met");
|
||||
p.Clear();
|
||||
Eq(p.Get(T11Counter.ItemAugmentations), (long?)3000, "aug: Clear keeps the override");
|
||||
Eq(p.CanWield(weapon), -1, "wield: charm unknown after Clear");
|
||||
}
|
||||
|
||||
private static void TestT11Keys()
|
||||
{
|
||||
T11ItemInfo w = T11ItemInfo.Parse("T11 - Tachi", T11WeaponLongDesc, null);
|
||||
int V(int key, T11PlayerAugs? pl = null) => T11Keys.TryGetValue(w, key, pl, out int v) ? v : int.MinValue;
|
||||
Eq(V(T11Keys.IsT11), 1, "key: IsT11");
|
||||
Eq(V(T11Keys.EstimatedTier), 13, "key: tier");
|
||||
Eq(V(T11Keys.WeaponGrade), 12, "key: grade");
|
||||
Eq(V(T11Keys.DamagePercent), 86, "key: damage %");
|
||||
Eq(V(T11Keys.WieldItemAugs), 3000, "key: wield item augs");
|
||||
Eq(V(T11Keys.CanWield), -1, "key: can wield unknown without player");
|
||||
Eq(V(T11Keys.ModifierCount), 3, "key: modifier count");
|
||||
Eq(V(T11Keys.ModifierRatingTotal), 51, "key: modifier ratings");
|
||||
Eq(V(T11Keys.CastOnStrikeCount), 1, "key: procs");
|
||||
Eq(V(T11Keys.ZoneLocked), 1, "key: zone locked");
|
||||
Eq(V(T11Keys.ForModifier(28)), 41, "key: per-modifier Damage Rating");
|
||||
Eq(V(T11Keys.ForModifier(50)), 0, "key: absent modifier = 0");
|
||||
Eq(V(T11Keys.ModifierBase + 999), int.MinValue, "key: unknown modifier id unused");
|
||||
Eq(V(370), int.MinValue, "key: retail key isn't virtual");
|
||||
Check(T11Keys.IsVirtual(T11Keys.IsT11) && !T11Keys.IsVirtual(T11Keys.Base) && !T11Keys.IsVirtual(T11Keys.End), "key: block bounds");
|
||||
|
||||
int S(T11ItemInfo item, int key) => T11Keys.TryGetStrippedValue(item, key, out int v) ? v : int.MinValue;
|
||||
Eq(S(w, 158), 13, "stripped: 158 = Int64 Property");
|
||||
Eq(S(w, 159), 9008, "stripped: 159 = item augs stat");
|
||||
Eq(S(w, 160), 3000, "stripped: 160 = gate");
|
||||
Eq(S(w, 370), 41, "stripped: 370 from modifier");
|
||||
Eq(S(w, 371), int.MinValue, "stripped: no modifier for 371");
|
||||
Eq(S(T11ItemInfo.None, 158), int.MinValue, "stripped: non-T11 gives nothing");
|
||||
Eq(S(T11ItemInfo.Parse("T11 - Robe", null, null), 160), int.MinValue, "stripped: no gate read yet");
|
||||
Check(T11Keys.IsStrippedKey(158) && T11Keys.IsStrippedKey(379) && !T11Keys.IsStrippedKey(161), "stripped: key set");
|
||||
}
|
||||
|
||||
private static void TestT11Editor()
|
||||
{
|
||||
Check(LootRuleText.LongKeys.Any(k => k.Id == T11Keys.CanWield && k.Name == "T11: Can Wield"), "editor: Can Wield key named");
|
||||
Check(LootRuleText.LongKeys.Any(k => k.Id == T11Keys.ForModifier(28) && k.Name == "T11 Mod: Damage Rating"), "editor: per-modifier key named");
|
||||
Check(LootRuleText.LongKeys.Any(k => k.Id == 377), "editor: NetherResistRating listed");
|
||||
Eq(LootRuleText.LongKeys.Select(k => k.Id).Distinct().Count(), LootRuleText.LongKeys.Length, "editor: long key ids unique");
|
||||
Check(ReferenceEquals(LootRuleText.ValueTableFor(T11Keys.WeaponGrade), T11Catalog.Grades), "editor: grade value table");
|
||||
Eq(LootRuleText.ValueName(T11Keys.WeaponGrade, "12"), "B+", "editor: grade 12 named B+");
|
||||
Eq(LootRuleText.WieldRequirements.First(w => w.Id == 13).Name, "Int64 Property", "editor: wield requirement 13");
|
||||
Check(LootRuleText.StringKeys.Any(k => k.Id == 14) && LootRuleText.StringKeys.Any(k => k.Id == 16), "editor: Use and LongDesc string keys");
|
||||
Eq(T11Catalog.Grades.Select(g => g.Name).Distinct().Count(), T11Catalog.Grades.Length, "editor: grade names unique");
|
||||
}
|
||||
}
|
||||
|
|
@ -67,7 +67,7 @@ internal static partial class Program
|
|||
Eq(LootRuleText.Materials.First(m => m.Id == 15).Name, "Black Garnet", "material 15");
|
||||
Eq(LootRuleText.Materials.Length, 78, "materials 0..77");
|
||||
Eq(LootRuleText.WieldRequirements.First(w => w.Id == 2).Name, "Base Skill", "wield requirement 2 (RawSkill)");
|
||||
Eq(LootRuleText.WieldRequirements.Length, 13, "wield requirements 0..12");
|
||||
Eq(LootRuleText.WieldRequirements.Length, 14, "wield requirements 0..13 (13 = ACECustom Int64 Property)");
|
||||
Eq(LootRuleText.DamageTypes.First(d => d.Id == 64).Name, "Electric", "damage type 64");
|
||||
|
||||
// Lookup and labels; unknown and odd values stay expressible.
|
||||
|
|
|
|||
|
|
@ -44,6 +44,8 @@ internal static partial class Program
|
|||
TestMalformedInputs();
|
||||
RunLootEditTests(args);
|
||||
RunLootAddTests(args);
|
||||
RunT11Tests();
|
||||
RunLootAddT11Tests();
|
||||
|
||||
Console.WriteLine($"\nGolden tests: {_asserts} assertions, {_fails} failed.");
|
||||
|
||||
|
|
|
|||
|
|
@ -7,5 +7,6 @@ namespace RynthCore.MonsterEditor;
|
|||
[JsonSerializable(typeof(EditorSettings))]
|
||||
// UB damage-insights seed written for the RynthAi plugin (see UbMobSeedImport).
|
||||
[JsonSerializable(typeof(RynthCore.CreatureSeed.UbMobSeedFile))]
|
||||
[JsonSourceGenerationOptions(WriteIndented = true, IncludeFields = true)]
|
||||
// Case-insensitive like the plugin's RynthAiJsonContext, which reads the same files.
|
||||
[JsonSourceGenerationOptions(WriteIndented = true, IncludeFields = true, PropertyNameCaseInsensitive = true)]
|
||||
internal partial class EditorJsonContext : JsonSerializerContext { }
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
xmlns:local="clr-namespace:RynthCore.MonsterEditor"
|
||||
x:Class="RynthCore.MonsterEditor.MainWindow"
|
||||
Title="RynthAi — Monster Rules Editor"
|
||||
Width="1060" Height="520" MinWidth="800" MinHeight="300">
|
||||
Width="1300" Height="520" MinWidth="800" MinHeight="300">
|
||||
|
||||
<DockPanel LastChildFill="True">
|
||||
|
||||
|
|
@ -124,6 +124,14 @@
|
|||
</DataTemplate></DataGridTemplateColumn.CellTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
|
||||
<DataGridTemplateColumn Header="Wl" Width="26" CanUserResize="False" CanUserSort="False">
|
||||
<DataGridTemplateColumn.CellTemplate><DataTemplate>
|
||||
<ToggleButton Classes="light" Content="Wl"
|
||||
IsChecked="{Binding UseWall, Mode=TwoWay}"
|
||||
ToolTip.Tip="Wall — War wall spells (a row of projectiles straight ahead; turns to face the target first). Needs Wall Range in the settings."/>
|
||||
</DataTemplate></DataGridTemplateColumn.CellTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
|
||||
<!-- Name -->
|
||||
<DataGridTemplateColumn Header="Name" Width="*" MinWidth="100">
|
||||
<DataGridTemplateColumn.CellTemplate><DataTemplate>
|
||||
|
|
@ -138,6 +146,28 @@
|
|||
</DataTemplate></DataGridTemplateColumn.CellEditingTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
|
||||
<!-- Category (the plugin's rule group label) -->
|
||||
<DataGridTemplateColumn Header="Category" Width="90" MinWidth="60">
|
||||
<DataGridTemplateColumn.CellTemplate><DataTemplate>
|
||||
<TextBlock Text="{Binding Category}" Padding="3,1" VerticalAlignment="Center"/>
|
||||
</DataTemplate></DataGridTemplateColumn.CellTemplate>
|
||||
<DataGridTemplateColumn.CellEditingTemplate><DataTemplate>
|
||||
<TextBox Text="{Binding Category, Mode=TwoWay}" Padding="3,1"/>
|
||||
</DataTemplate></DataGridTemplateColumn.CellEditingTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
|
||||
<!-- Match expression (empty = match by name only) -->
|
||||
<DataGridTemplateColumn Header="Match" Width="150" MinWidth="80">
|
||||
<DataGridTemplateColumn.CellTemplate><DataTemplate>
|
||||
<TextBlock Text="{Binding MatchExpression}" Padding="3,1" VerticalAlignment="Center"
|
||||
TextTrimming="CharacterEllipsis"
|
||||
ToolTip.Tip="Match expression: when set, the rule matches when it is true (and the name, if any, is in the target's name). Empty = by name only."/>
|
||||
</DataTemplate></DataGridTemplateColumn.CellTemplate>
|
||||
<DataGridTemplateColumn.CellEditingTemplate><DataTemplate>
|
||||
<TextBox Text="{Binding MatchExpression, Mode=TwoWay}" Padding="3,1"/>
|
||||
</DataTemplate></DataGridTemplateColumn.CellEditingTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
|
||||
<!-- Priority -->
|
||||
<DataGridTemplateColumn Header="P" Width="32" MinWidth="30">
|
||||
<DataGridTemplateColumn.CellTemplate><DataTemplate>
|
||||
|
|
|
|||
|
|
@ -33,6 +33,8 @@ public partial class MainWindow : Window
|
|||
private string _charFolder = string.Empty;
|
||||
private string _monstersPath = string.Empty;
|
||||
private bool _initialized;
|
||||
// Set when the monsters file couldn't be read: saving would replace it with what's on screen.
|
||||
private bool _loadFailed;
|
||||
|
||||
public MainWindow()
|
||||
{
|
||||
|
|
@ -51,7 +53,7 @@ public partial class MainWindow : Window
|
|||
|
||||
string[] args = Environment.GetCommandLineArgs();
|
||||
if (args.Length > 1)
|
||||
OpenCharFolder(args[1].Trim('"'));
|
||||
Open(args[1].Trim('"'));
|
||||
else
|
||||
await PromptOpenFileAsync();
|
||||
}
|
||||
|
|
@ -65,11 +67,11 @@ public partial class MainWindow : Window
|
|||
|
||||
var pick = await sp.OpenFilePickerAsync(new FilePickerOpenOptions
|
||||
{
|
||||
Title = "Open monsters.json",
|
||||
Title = "Open a monster rules file (RynthAi > MonsterProfiles > character.json)",
|
||||
AllowMultiple = false,
|
||||
FileTypeFilter = new[]
|
||||
{
|
||||
new FilePickerFileType("Monster Rules") { Patterns = new[] { "monsters.json" } },
|
||||
new FilePickerFileType("Monster Rules") { Patterns = new[] { "*.json" } },
|
||||
new FilePickerFileType("All Files") { Patterns = new[] { "*" } },
|
||||
}
|
||||
});
|
||||
|
|
@ -83,14 +85,21 @@ public partial class MainWindow : Window
|
|||
|
||||
string? path = file.TryGetLocalPath();
|
||||
if (!string.IsNullOrEmpty(path))
|
||||
OpenCharFolder(Path.GetDirectoryName(path)!);
|
||||
Open(path);
|
||||
}
|
||||
|
||||
private void OpenCharFolder(string charFolder)
|
||||
/// <summary>Opens a monsters file, or a character's settings folder (what the plugin passes):
|
||||
/// the folder maps to the file the plugin reads, MonsterProfiles\(server)\(character).json
|
||||
/// (MonsterRulesFile.ResolveRulesPath). Before 2026-10-05 the editor always used
|
||||
/// monsters.json in that folder, which the plugin now moves to MonsterProfiles at load, so the
|
||||
/// editor opened empty and its saves were never read once the plugin's own file existed.</summary>
|
||||
private void Open(string pathOrFolder)
|
||||
{
|
||||
_charFolder = charFolder;
|
||||
_monstersPath = Path.Combine(charFolder, "monsters.json");
|
||||
Title = $"RynthAi — Monster Rules — {Path.GetFileName(charFolder)}";
|
||||
_monstersPath = MonsterRulesFile.ResolveRulesPath(pathOrFolder);
|
||||
_charFolder = Directory.Exists(pathOrFolder) ? pathOrFolder : MonsterRulesFile.CharFolderForRulesPath(_monstersPath);
|
||||
string who = Path.GetFileNameWithoutExtension(_monstersPath);
|
||||
if (who.Equals("monsters", StringComparison.OrdinalIgnoreCase)) who = Path.GetFileName(_charFolder);
|
||||
Title = $"RynthAi — Monster Rules — {who}";
|
||||
|
||||
LoadWeaponOptions();
|
||||
LoadRules();
|
||||
|
|
@ -128,17 +137,17 @@ public partial class MainWindow : Window
|
|||
{
|
||||
foreach (var r in Rules) r.PropertyChanged -= Rule_Changed;
|
||||
Rules.Clear();
|
||||
_loadFailed = false;
|
||||
|
||||
if (File.Exists(_monstersPath))
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
string json = File.ReadAllText(_monstersPath);
|
||||
var rules = JsonSerializer.Deserialize(json, EditorJsonContext.Default.ListMonsterRule);
|
||||
if (rules != null)
|
||||
foreach (var r in rules) AddRule(r);
|
||||
}
|
||||
catch (Exception ex) { SetStatus($"Load error: {ex.Message}", error: true); return; }
|
||||
foreach (var r in MonsterRulesFile.Load(_monstersPath)) AddRule(r);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_loadFailed = true;
|
||||
SetStatus($"Load error: {ex.Message} - not saving over {_monstersPath}; fix the file and reopen it.", error: true);
|
||||
return;
|
||||
}
|
||||
|
||||
EnsureDefault();
|
||||
|
|
@ -187,12 +196,10 @@ public partial class MainWindow : Window
|
|||
|
||||
private void Save()
|
||||
{
|
||||
if (string.IsNullOrEmpty(_monstersPath)) return;
|
||||
if (string.IsNullOrEmpty(_monstersPath) || _loadFailed) return;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(_charFolder);
|
||||
string json = JsonSerializer.Serialize(new List<MonsterRule>(Rules), EditorJsonContext.Default.ListMonsterRule);
|
||||
File.WriteAllText(_monstersPath, json);
|
||||
MonsterRulesFile.Save(_monstersPath, Rules);
|
||||
SetStatus($"Saved {Rules.Count} rule(s) — {DateTime.Now:HH:mm:ss}");
|
||||
}
|
||||
catch (Exception ex) { SetStatus($"Save error: {ex.Message}", error: true); }
|
||||
|
|
|
|||
|
|
@ -1,36 +1,39 @@
|
|||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace RynthCore.MonsterEditor;
|
||||
|
||||
/// <summary>The editor's copy of RynthAi's MonsterRule (Plugins/RynthCore.Plugin.RynthAi/LegacyUi/
|
||||
/// LegacyUiSettings.cs), read from and saved to the same monsters file. A field the plugin has and
|
||||
/// this class doesn't still survives a save, through <see cref="ExtraFields"/>.</summary>
|
||||
public class MonsterRule : INotifyPropertyChanged
|
||||
{
|
||||
private string _name = "New Monster";
|
||||
private string _category = "";
|
||||
private string _matchExpression = "";
|
||||
private int _priority = 1;
|
||||
private string _damageType = "Auto";
|
||||
private int _weaponId;
|
||||
private bool _fester, _broadside, _gravityWell, _imperil, _yield, _vuln;
|
||||
private bool _useArc, _useBolt = true, _useRing, _useStreak, _useBlast;
|
||||
private bool _useArc, _useBolt = true, _useRing, _useStreak, _useBlast, _useWall;
|
||||
private string _exVuln = "None";
|
||||
private int _offhandId;
|
||||
private int _preferredAmmoItemId;
|
||||
private string _petDamage = "PAuto";
|
||||
/// <summary>Dashboard-only label; optional (empty shows as "Default" in the game UI).</summary>
|
||||
private string _category = string.Empty;
|
||||
/// <summary>vTank-style match expression. Empty = for named rules, match on Name substring; for the Default row, it is the global fallback when nothing else matches.</summary>
|
||||
private string _matchExpression = string.Empty;
|
||||
|
||||
public string Name { get => _name; set { _name = value; OnPropertyChanged(); } }
|
||||
/// <summary>The plugin's rule group label. Kept and editable here (before 2026-10-05 an
|
||||
/// editor save dropped it).</summary>
|
||||
public string Category { get => _category; set { _category = value ?? ""; OnPropertyChanged(); } }
|
||||
/// <summary>The plugin's match expression (CombatManager.GetRuleForTarget): when set, the
|
||||
/// rule matches when the expression is true (and the name, if any, is in the target's).
|
||||
/// Empty = match by name only. Kept and editable here (before 2026-10-05 an editor save
|
||||
/// dropped it, so expression rules fell back to name-only).</summary>
|
||||
public string MatchExpression { get => _matchExpression; set { _matchExpression = value ?? ""; OnPropertyChanged(); } }
|
||||
public int Priority { get => _priority; set { _priority = value; OnPropertyChanged(); } }
|
||||
public string Category { get => _category; set { _category = value ?? string.Empty; OnPropertyChanged(); } }
|
||||
/// <summary>vTank-style match expression. Empty matches on the rule name.</summary>
|
||||
public string MatchExpression
|
||||
{
|
||||
get => _matchExpression;
|
||||
set { _matchExpression = value ?? string.Empty; OnPropertyChanged(); }
|
||||
}
|
||||
public string DamageType { get => _damageType; set { _damageType = value; OnPropertyChanged(); } }
|
||||
public int WeaponId { get => _weaponId; set { _weaponId = value; OnPropertyChanged(); } }
|
||||
public bool Fester { get => _fester; set { _fester = value; OnPropertyChanged(); } }
|
||||
|
|
@ -44,12 +47,18 @@ public class MonsterRule : INotifyPropertyChanged
|
|||
public bool UseRing { get => _useRing; set { _useRing = value; OnPropertyChanged(); } }
|
||||
public bool UseStreak { get => _useStreak; set { _useStreak = value; OnPropertyChanged(); } }
|
||||
public bool UseBlast { get => _useBlast; set { _useBlast = value; OnPropertyChanged(); } }
|
||||
public bool UseWall { get => _useWall; set { _useWall = value; OnPropertyChanged(); } }
|
||||
public string ExVuln { get => _exVuln; set { _exVuln = value; OnPropertyChanged(); } }
|
||||
public int OffhandId { get => _offhandId; set { _offhandId = value; OnPropertyChanged(); } }
|
||||
/// <summary>Optional loose ammo stack id for missile combat while this rule matches (0 = auto).</summary>
|
||||
public int PreferredAmmoItemId { get => _preferredAmmoItemId; set { _preferredAmmoItemId = value; OnPropertyChanged(); } }
|
||||
public string PetDamage { get => _petDamage; set { _petDamage = value; OnPropertyChanged(); } }
|
||||
|
||||
/// <summary>Every field in the file this class doesn't know (e.g. the plugin's CustomDebuffs,
|
||||
/// or one added later), written back unchanged.</summary>
|
||||
[JsonExtensionData]
|
||||
public Dictionary<string, JsonElement>? ExtraFields { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
/// <summary>True for the special row named "Default" — the catch-all when no other rule matches.</summary>
|
||||
public bool IsDefault => string.Equals(_name, "Default", System.StringComparison.OrdinalIgnoreCase);
|
||||
|
|
@ -76,10 +85,13 @@ public class MonsterRule : INotifyPropertyChanged
|
|||
UseRing = _useRing,
|
||||
UseStreak = _useStreak,
|
||||
UseBlast = _useBlast,
|
||||
UseWall = _useWall,
|
||||
ExVuln = _exVuln,
|
||||
OffhandId = _offhandId,
|
||||
PreferredAmmoItemId = _preferredAmmoItemId,
|
||||
PetDamage = _petDamage,
|
||||
// JsonElements are immutable, so a new dictionary over the same values is a full copy.
|
||||
ExtraFields = ExtraFields == null ? null : new Dictionary<string, JsonElement>(ExtraFields),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -104,6 +116,7 @@ public class MonsterRule : INotifyPropertyChanged
|
|||
UseRing = src.UseRing;
|
||||
UseStreak = src.UseStreak;
|
||||
UseBlast = src.UseBlast;
|
||||
UseWall = src.UseWall;
|
||||
ExVuln = src.ExVuln;
|
||||
OffhandId = src.OffhandId;
|
||||
PreferredAmmoItemId = src.PreferredAmmoItemId;
|
||||
|
|
|
|||
99
Tools/RynthCore.MonsterEditor/MonsterRulesFile.cs
Normal file
99
Tools/RynthCore.MonsterEditor/MonsterRulesFile.cs
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.MonsterEditor;
|
||||
|
||||
/// <summary>
|
||||
/// Reading and writing a monsters file (a JSON array of MonsterRule, the format RynthAi's
|
||||
/// LegacyDashboardRenderer reads and writes), and finding the file the plugin uses. No UI:
|
||||
/// Tools/RynthCore.RynthAiHostTests compiles this file in and round-trips a file through it and
|
||||
/// the plugin's own serializer.
|
||||
/// </summary>
|
||||
public static class MonsterRulesFile
|
||||
{
|
||||
private const string SettingsProfilesDir = "SettingsProfiles";
|
||||
private const string MonsterProfilesDir = "MonsterProfiles";
|
||||
// RynthAi's LegacyServerFolder: its monsters live straight in MonsterProfiles\.
|
||||
private const string LegacyServerFolder = "ACEmulator";
|
||||
private const string LegacyFileName = "monsters.json";
|
||||
|
||||
/// <summary>The rules in <paramref name="path"/>; empty when the file doesn't exist.
|
||||
/// Throws on a file that isn't a JSON array of rules (the caller shows the error and
|
||||
/// doesn't save over it).</summary>
|
||||
public static List<MonsterRule> Load(string path)
|
||||
{
|
||||
if (!File.Exists(path)) return new List<MonsterRule>();
|
||||
string json = File.ReadAllText(path);
|
||||
return JsonSerializer.Deserialize(json, EditorJsonContext.Default.ListMonsterRule) ?? new List<MonsterRule>();
|
||||
}
|
||||
|
||||
/// <summary>Writes <paramref name="rules"/> in place (File.WriteAllText, as before: the
|
||||
/// plugin's FileSystemWatcher reloads on a LastWrite change).</summary>
|
||||
public static void Save(string path, IEnumerable<MonsterRule> rules)
|
||||
{
|
||||
string? dir = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
File.WriteAllText(path, JsonSerializer.Serialize(new List<MonsterRule>(rules), EditorJsonContext.Default.ListMonsterRule));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The monsters file for what the editor was given: a .json file is edited as is. A
|
||||
/// character's settings folder (RynthAi\SettingsProfiles\<server>\<character>, what the
|
||||
/// plugin passes) maps to the plugin's file, RynthAi\MonsterProfiles\<server>\<character>.json
|
||||
/// (MonsterProfiles\<character>.json for the ACEmulator folder). The old
|
||||
/// <folder>\monsters.json is used only when that file doesn't exist and the old one does
|
||||
/// (the plugin moves it across at its next load).
|
||||
/// </summary>
|
||||
public static string ResolveRulesPath(string pathOrFolder)
|
||||
{
|
||||
string p = pathOrFolder.Trim().Trim('"').TrimEnd('\\', '/');
|
||||
if (File.Exists(p) || p.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
|
||||
return p;
|
||||
|
||||
string legacy = Path.Combine(p, LegacyFileName);
|
||||
string? current = PluginRulesPathForCharFolder(p);
|
||||
if (current == null) return legacy;
|
||||
if (File.Exists(current)) return current;
|
||||
return File.Exists(legacy) ? legacy : current;
|
||||
}
|
||||
|
||||
/// <summary>RynthAi's MonsterProfiles file for a SettingsProfiles character folder; null when
|
||||
/// the folder isn't laid out that way.</summary>
|
||||
public static string? PluginRulesPathForCharFolder(string charFolder)
|
||||
{
|
||||
var character = new DirectoryInfo(charFolder.TrimEnd('\\', '/'));
|
||||
DirectoryInfo? server = character.Parent;
|
||||
DirectoryInfo? profiles = server?.Parent;
|
||||
DirectoryInfo? root = profiles?.Parent;
|
||||
if (server == null || profiles == null || root == null) return null;
|
||||
if (!profiles.Name.Equals(SettingsProfilesDir, StringComparison.OrdinalIgnoreCase)) return null;
|
||||
|
||||
string monsters = Path.Combine(root.FullName, MonsterProfilesDir);
|
||||
return server.Name.Equals(LegacyServerFolder, StringComparison.OrdinalIgnoreCase)
|
||||
? Path.Combine(monsters, character.Name + ".json")
|
||||
: Path.Combine(monsters, server.Name, character.Name + ".json");
|
||||
}
|
||||
|
||||
/// <summary>The character's settings folder (where active_profile.txt and the profile with
|
||||
/// the weapon list live) for a monsters file: the file's own folder for an old
|
||||
/// monsters.json, the matching SettingsProfiles folder for a MonsterProfiles file, else the
|
||||
/// file's own folder.</summary>
|
||||
public static string CharFolderForRulesPath(string rulesPath)
|
||||
{
|
||||
var file = new FileInfo(rulesPath);
|
||||
string folder = file.DirectoryName ?? "";
|
||||
if (file.Name.Equals(LegacyFileName, StringComparison.OrdinalIgnoreCase))
|
||||
return folder;
|
||||
|
||||
string character = Path.GetFileNameWithoutExtension(file.Name);
|
||||
DirectoryInfo? dir = file.Directory;
|
||||
if (dir == null) return folder;
|
||||
if (dir.Name.Equals(MonsterProfilesDir, StringComparison.OrdinalIgnoreCase) && dir.Parent != null)
|
||||
return Path.Combine(dir.Parent.FullName, SettingsProfilesDir, LegacyServerFolder, character);
|
||||
if (dir.Parent is { } monsters && monsters.Name.Equals(MonsterProfilesDir, StringComparison.OrdinalIgnoreCase) && monsters.Parent != null)
|
||||
return Path.Combine(monsters.Parent.FullName, SettingsProfilesDir, dir.Name, character);
|
||||
return folder;
|
||||
}
|
||||
}
|
||||
|
|
@ -24,8 +24,8 @@
|
|||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Install-location resolver (installer-chosen RynthCore / RynthSuite folders). -->
|
||||
<Compile Include="..\..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
|
||||
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
<!-- UB damage-insights seed schema, shared with the RynthAi plugin. -->
|
||||
<Compile Include="..\..\Shared\UbMobSeed.cs" Link="Shared\UbMobSeed.cs" />
|
||||
</ItemGroup>
|
||||
|
|
|
|||
|
|
@ -48,6 +48,9 @@ internal static unsafe class FakeHost
|
|||
/// <summary>Item id -> container id. When it has entries at Create() time the host also gets
|
||||
/// GetObjectOwnershipInfo (opt-in, so tests written without it see no ownership, as before).</summary>
|
||||
public static readonly Dictionary<uint, uint> Containers = new();
|
||||
/// <summary>Item id -> the creature wielding it (GetObjectOwnershipInfo's wielder). Entries here
|
||||
/// also install GetObjectOwnershipInfo; an id in neither map reads as unknown ownership.</summary>
|
||||
public static readonly Dictionary<uint, uint> Wielders = new();
|
||||
/// <summary>Object id -> PublicWeenieDesc bitfield (0x2000 corpse, 0x8 player, ...). When it has
|
||||
/// entries at Create() time the host also gets GetObjectBitfield (opt-in, as Containers).</summary>
|
||||
public static readonly Dictionary<uint, uint> Bitfields = new();
|
||||
|
|
@ -79,12 +82,18 @@ internal static unsafe class FakeHost
|
|||
public static readonly List<bool> AutoRunCalls = new();
|
||||
public static bool AutoRun;
|
||||
public static int Jumps;
|
||||
/// <summary>Opt-in: wires TapJump (the keyboard jump, 0xF61B); calls land in <see cref="TapJumps"/>.</summary>
|
||||
public static bool TapJumpCalls;
|
||||
public static int TapJumps;
|
||||
public static int Turns;
|
||||
public static readonly List<(uint Target, int SpellId)> Casts = new();
|
||||
/// <summary>Opt-in: wires GiveObjectTo (AC's give action); every call lands in <see cref="Gives"/>.</summary>
|
||||
public static bool GiveCalls;
|
||||
/// <summary>Every GiveObjectTo (item, target, amount; 0 = the whole object), in order.</summary>
|
||||
public static readonly List<(uint Item, uint Target, int Amount)> Gives = new();
|
||||
/// <summary>When true (the default) a give lands at once, as the server does when it isn't busy:
|
||||
/// the item goes to the target. False = the server hasn't taken it (still carried).</summary>
|
||||
public static bool GiveLands = true;
|
||||
/// <summary>Opt-in: wires StopCompletely (off by default so no other test sees it).</summary>
|
||||
public static bool StopCalls;
|
||||
/// <summary>StopCompletely calls (opt-in with <see cref="StopCalls"/>).</summary>
|
||||
|
|
@ -118,6 +127,9 @@ internal static unsafe class FakeHost
|
|||
public static int CastBusy;
|
||||
public static int VTankSeq;
|
||||
public static int CombatModeValue = 1;
|
||||
/// <summary>Opt-in (set before Create): ChangeCombatMode, recorded in <see cref="CombatModeRequests"/>.</summary>
|
||||
public static bool CombatModeCalls;
|
||||
public static readonly List<int> CombatModeRequests = new();
|
||||
/// <summary>Opt-in (set before Create): WieldItem (a wield into a named slot, API v70+). The
|
||||
/// host then reports API version 73, so only tests that ask for it see the newer calls.</summary>
|
||||
public static bool WieldCalls;
|
||||
|
|
@ -149,28 +161,45 @@ internal static unsafe class FakeHost
|
|||
public static uint GroundContainer;
|
||||
/// <summary>The item selected in the game (GetSelectedItemId); 0 = none.</summary>
|
||||
public static uint SelectedItem;
|
||||
/// <summary>Opt-in (set before Create): UseObjectOn (an item used on another, e.g. a spirit on a
|
||||
/// pet essence); every call lands in <see cref="UsesOn"/>.</summary>
|
||||
public static bool UseOnCalls;
|
||||
/// <summary>Every UseObjectOn (source, target), in order (opt-in with <see cref="UseOnCalls"/>).</summary>
|
||||
public static readonly List<(uint Source, uint Target)> UsesOn = new();
|
||||
/// <summary>Opt-in: install SendPluginCommand (the engine's plugin-command broker, API v64).</summary>
|
||||
public static bool PluginCommandCalls;
|
||||
/// <summary>What SendPluginCommand answers: true = delivered (the target plugin is loaded).</summary>
|
||||
public static bool PluginCommandDelivered = true;
|
||||
/// <summary>Every SendPluginCommand (plugin, action, value), in order.</summary>
|
||||
public static readonly List<(string Plugin, string Action, string Value)> PluginCommands = new();
|
||||
/// <summary>Opt-in (set before Create): ForceResetBusyCount (counted in <see cref="ForceResets"/>)
|
||||
/// and GetBusyState (answering <see cref="BusyStateValue"/>).</summary>
|
||||
public static bool BusyCalls;
|
||||
public static int ForceResets;
|
||||
public static int BusyStateValue;
|
||||
|
||||
// ANSI strings handed back to tested code stay alive for the whole run.
|
||||
private static readonly Dictionary<string, IntPtr> _ansi = new();
|
||||
|
||||
/// <summary>Opt-in: install the Nav3D calls (clear, ring, line, triangle) and record them.</summary>
|
||||
public static bool Nav3DCalls;
|
||||
public static readonly List<(float X, float Y, float Z, float Radius, uint Color)> Nav3DRings = new();
|
||||
public static readonly List<(float X1, float Y1, float Z1, float X2, float Y2, float Z2, float Thick, uint Color)> Nav3DLines = new();
|
||||
public static readonly List<(float X1, float Y1, float Z1, float X2, float Y2, float Z2, float X3, float Y3, float Z3, uint Color)> Nav3DTriangles = new();
|
||||
|
||||
public static void Reset()
|
||||
{
|
||||
Nav3DCalls = false; Nav3DRings.Clear(); Nav3DLines.Clear(); Nav3DTriangles.Clear();
|
||||
Names.Clear(); Positions.Clear(); ItemTypes.Clear();
|
||||
Ints.Clear(); Doubles.Clear(); Quads.Clear(); Bools.Clear(); Strings.Clear();
|
||||
Skills.Clear(); SkillLevels.Clear(); Attributes.Clear();
|
||||
SpellIds.Clear(); DataIds.Clear(); Palettes.Clear(); KnownSpells.Clear(); NotAttackable.Clear(); Enchantments.Clear();
|
||||
Containers.Clear(); Bitfields.Clear();
|
||||
Containers.Clear(); Wielders.Clear(); Bitfields.Clear();
|
||||
ServerTime = 0; Vitae = 1.0f; Portaling = false; PlayerPose = default; HasPose = true;
|
||||
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
|
||||
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
|
||||
Logs.Clear(); Chat.Clear(); ChatCommands.Clear();
|
||||
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear();
|
||||
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear(); GiveLands = true;
|
||||
Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1;
|
||||
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
|
||||
ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false;
|
||||
|
|
@ -179,7 +208,10 @@ internal static unsafe class FakeHost
|
|||
RefuseSalvageAdd.Clear(); OnSalvageExecute = null; Wielded.Clear(); _panelItems.Clear();
|
||||
CloseContainerCalls = false; Closes.Clear(); GroundContainer = 0;
|
||||
SelectedItem = 0;
|
||||
UseOnCalls = false; UsesOn.Clear();
|
||||
PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear();
|
||||
CombatModeCalls = false; CombatModeRequests.Clear();
|
||||
BusyCalls = false; ForceResets = 0; BusyStateValue = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -212,16 +244,25 @@ internal static unsafe class FakeHost
|
|||
PlayerIdValue = playerId;
|
||||
if (playerId != 0)
|
||||
api.GetPlayerIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetPlayerId;
|
||||
if (Containers.Count > 0)
|
||||
if (Containers.Count > 0 || Wielders.Count > 0)
|
||||
api.GetObjectOwnershipInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, uint*, int>)&GetObjectOwnershipInfo;
|
||||
if (Bitfields.Count > 0)
|
||||
api.GetObjectBitfieldFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint>)&GetObjectBitfield;
|
||||
api.SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&SetAutoRun;
|
||||
api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&TurnToHeading;
|
||||
api.JumpNonAutonomousFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&JumpNonAutonomous;
|
||||
if (TapJumpCalls)
|
||||
api.TapJumpFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&TapJump;
|
||||
api.CastSpellFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int>)&CastSpell;
|
||||
if (StopCalls)
|
||||
api.StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&StopCompletely;
|
||||
if (Nav3DCalls)
|
||||
{
|
||||
api.Nav3DClearFn = (IntPtr)(delegate* unmanaged[Cdecl]<void>)&Nav3DClear;
|
||||
api.Nav3DAddRingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, float, float, float, float, uint, void>)&Nav3DAddRing;
|
||||
api.Nav3DAddLineFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, float, float, float, float, float, float, uint, void>)&Nav3DAddLine;
|
||||
api.Nav3DAddTriangleFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, float, float, float, float, float, float, float, float, uint, void>)&Nav3DAddTriangle;
|
||||
}
|
||||
if (GiveCalls)
|
||||
api.GiveObjectToFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int>)&GiveObjectTo;
|
||||
if (WeaponCalls)
|
||||
|
|
@ -241,6 +282,15 @@ internal static unsafe class FakeHost
|
|||
api.SalvagePanelExecuteFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&SalvagePanelExecute;
|
||||
api.GetObjectWielderInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, int>)&GetObjectWielderInfo;
|
||||
}
|
||||
if (CombatModeCalls)
|
||||
api.ChangeCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&ChangeCombatMode;
|
||||
if (BusyCalls)
|
||||
{
|
||||
api.ForceResetBusyCountFn = (IntPtr)(delegate* unmanaged[Cdecl]<void>)&ForceResetBusyCount;
|
||||
api.GetBusyStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetBusyState;
|
||||
}
|
||||
if (UseOnCalls)
|
||||
api.UseObjectOnFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&UseObjectOn;
|
||||
if (WieldCalls)
|
||||
{
|
||||
api.Version = 73;
|
||||
|
|
@ -402,9 +452,11 @@ internal static unsafe class FakeHost
|
|||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetObjectOwnershipInfo(uint id, uint* container, uint* wielder, uint* location)
|
||||
{
|
||||
if (!Containers.TryGetValue(id, out uint c)) return 0;
|
||||
bool inPack = Containers.TryGetValue(id, out uint c);
|
||||
bool worn = Wielders.TryGetValue(id, out uint w);
|
||||
if (!inPack && !worn) return 0;
|
||||
*container = c;
|
||||
*wielder = 0;
|
||||
*wielder = w;
|
||||
*location = 0;
|
||||
return 1;
|
||||
}
|
||||
|
|
@ -543,6 +595,20 @@ internal static unsafe class FakeHost
|
|||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static uint GetPlayerId() => PlayerIdValue;
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static void Nav3DClear() { Nav3DRings.Clear(); Nav3DLines.Clear(); Nav3DTriangles.Clear(); }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static void Nav3DAddRing(float x, float y, float z, float radius, float thick, uint color) => Nav3DRings.Add((x, y, z, radius, color));
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static void Nav3DAddLine(float x1, float y1, float z1, float x2, float y2, float z2, float thick, uint color)
|
||||
=> Nav3DLines.Add((x1, y1, z1, x2, y2, z2, thick, color));
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static void Nav3DAddTriangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint color)
|
||||
=> Nav3DTriangles.Add((x1, y1, z1, x2, y2, z2, x3, y3, z3, color));
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static uint GetSelectedItemId() => SelectedItem;
|
||||
|
||||
|
|
@ -556,19 +622,36 @@ internal static unsafe class FakeHost
|
|||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int JumpNonAutonomous(float extent) { Jumps++; return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int TapJump() { TapJumps++; return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); return 1; }
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int StopCompletely() { Stops++; return 1; }
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GiveObjectTo(uint item, uint target, int amount) { Gives.Add((item, target, amount)); return 1; }
|
||||
private static void ForceResetBusyCount() { ForceResets++; BusyStateValue = 0; }
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetBusyState() => BusyStateValue;
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GiveObjectTo(uint item, uint target, int amount)
|
||||
{
|
||||
Gives.Add((item, target, amount));
|
||||
if (GiveLands && amount == 0) Containers[item] = target;
|
||||
return 1;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetCurrentCombatMode() => CombatModeValue;
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int ChangeCombatMode(int mode) { CombatModeRequests.Add(mode); return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int UseObject(uint id) { Uses.Add(id); return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int UseObjectOn(uint source, uint target) { UsesOn.Add((source, target)); return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int WieldItem(uint id, uint mask) { Wields.Add((id, mask)); return 1; }
|
||||
|
||||
|
|
|
|||
|
|
@ -17,6 +17,9 @@ internal static class Program
|
|||
/// <summary>Scratch folder next to the exe for files tests write. Emptied at start.</summary>
|
||||
public static string TempRoot { get; } = Path.Combine(AppContext.BaseDirectory, "scratch");
|
||||
|
||||
/// <summary>DungeonHazardStore's folder before Main pointed it at the scratch folder.</summary>
|
||||
public static string LiveHazardFolder { get; private set; } = "";
|
||||
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true);
|
||||
|
|
@ -30,6 +33,9 @@ internal static class Program
|
|||
ExpressionEngine.ItemGiverDir = Path.Combine(TempRoot, "ItemGiver");
|
||||
// The dungeon map bake writes floor plans under C:\Games\RynthSuite\RynthAi\Maps.
|
||||
RynthCore.Plugin.RynthAi.Maps.DungeonMapBake.CacheDir = Path.Combine(TempRoot, "Maps");
|
||||
// A sighted lava/acid hotspot is persisted under C:\Games\RynthSuite\RynthAi\DungeonHazards.
|
||||
LiveHazardFolder = RynthCore.Plugin.RynthAi.DungeonHazardStore.Folder;
|
||||
RynthCore.Plugin.RynthAi.DungeonHazardStore.Folder = Path.Combine(TempRoot, "DungeonHazards");
|
||||
|
||||
// Spell names (item spells, spell expiry by name) come from the plugin's embedded table.
|
||||
SpellDatabase.Load();
|
||||
|
|
@ -37,10 +43,13 @@ internal static class Program
|
|||
var runner = new Runner();
|
||||
NativeLootTests.Register(runner);
|
||||
VTankLootTests.Register(runner);
|
||||
T11LootTests.Register(runner);
|
||||
ExpressionTests.Register(runner);
|
||||
MetaTests.Register(runner);
|
||||
NoKillTests.Register(runner);
|
||||
MetaSchedulerTests.Register(runner);
|
||||
NavEngineTests.Register(runner);
|
||||
NavReachTests.Register(runner);
|
||||
PatrolDoorwayTests.Register(runner);
|
||||
BuffTests.Register(runner);
|
||||
CombatMathTests.Register(runner);
|
||||
|
|
@ -53,11 +62,14 @@ internal static class Program
|
|||
LootSalvageTests.Register(runner);
|
||||
LootCorpseTests.Register(runner);
|
||||
OwnCorpseTests.Register(runner);
|
||||
UseRefusalTests.Register(runner);
|
||||
VitalsTests.Register(runner);
|
||||
MultiTargetTests.Register(runner);
|
||||
CastSafetyTests.Register(runner);
|
||||
HealLatencyTests.Register(runner);
|
||||
BlastTests.Register(runner);
|
||||
ArcWhenClearTests.Register(runner);
|
||||
WallTests.Register(runner);
|
||||
UseAtLoginTests.Register(runner);
|
||||
LearnSpellsTests.Register(runner);
|
||||
AttackLatencyTests.Register(runner);
|
||||
|
|
@ -65,6 +77,16 @@ internal static class Program
|
|||
GiveTests.Register(runner);
|
||||
DungeonMapBakeTests.Register(runner);
|
||||
AttributeRaiserTests.Register(runner);
|
||||
MonsterEditorTests.Register(runner);
|
||||
InstallPathsTests.Register(runner);
|
||||
PetRefillTests.Register(runner);
|
||||
WorldCacheTypedTests.Register(runner);
|
||||
ItemInfoTests.Register(runner);
|
||||
NavOverlayTests.Register(runner);
|
||||
ActionPacingTests.Register(runner);
|
||||
HazardEscapeTests.Register(runner);
|
||||
ManaStoneChoiceTests.Register(runner);
|
||||
CustomDebuffTests.Register(runner);
|
||||
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -50,6 +50,17 @@
|
|||
RynthAi's JSON against the engine's real reader. Same relative engine path the plugin
|
||||
itself references. -->
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\RadarSnapshotJson.cs" Link="Engine\RadarSnapshotJson.cs" />
|
||||
<!-- The Meta editor's "Set current" landblock / landcell text (self-contained), so MetaTests
|
||||
check that MetaManager matches what the editor writes (engine 2026-10-05). -->
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\MetaLocation.cs" Link="Engine\MetaLocation.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- The standalone Monster Editor's model and file code (no Avalonia in these), so its
|
||||
load/save is checked against the plugin's own serializer (MonsterEditorTests). -->
|
||||
<Compile Include="..\RynthCore.MonsterEditor\Models.cs" Link="MonsterEditor\Models.cs" />
|
||||
<Compile Include="..\RynthCore.MonsterEditor\JsonContext.cs" Link="MonsterEditor\JsonContext.cs" />
|
||||
<Compile Include="..\RynthCore.MonsterEditor\MonsterRulesFile.cs" Link="MonsterEditor\MonsterRulesFile.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
832
Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs
Normal file
832
Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs
Normal file
|
|
@ -0,0 +1,832 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// One server action at a time (2026-10-06, ops\overnight\2026-10-06-action-pacing.md).
|
||||
// Drakkon's stuck uses and stuck casts on DreamWeave: every stall began with a combat-mode change
|
||||
// sent while a corpse use was still unanswered, and once the server held an action RynthAi fired
|
||||
// the next cast or use every 0.4-2.5 s on top of it (it paced on a busy count it kept zeroing, and
|
||||
// on the enchantment rather than the server's UseDone). These tests replay those sequences against
|
||||
// Plugins/Shared/ActionPacer.cs and the RynthAi code wired to it:
|
||||
// - the pacer itself: answers (UseDone, a refusal, a wield, a stance read), time limits, the heal
|
||||
// rules, and that nothing is ever force-cleared;
|
||||
// - the onset sequence (corpse use -> idle peace swap 3-677 ms later) and the movement hold;
|
||||
// - BuffManager: a cast whose result is in but whose UseDone isn't waits (one cast, not a flood),
|
||||
// heals still go first, and the emergency stance settle is unchanged;
|
||||
// - looting: one open per answer; Drakkon's stall is still found and reported once;
|
||||
// - CombatManager's idle peace swap waits for an unanswered kit;
|
||||
// - the busy mirror is reset without touching the client's count.
|
||||
internal static class ActionPacingTests
|
||||
{
|
||||
private const uint Player = 0x50000E01;
|
||||
private const uint Corpse = 0x80068ACE;
|
||||
private const uint CorpseB = 0x80072023;
|
||||
private const uint Kit = 0x8004BEF8;
|
||||
private const uint Wand = 0x8007467A;
|
||||
private const uint Pack = 0x50000E01; // the player's main pack is the player
|
||||
private const uint ItemTypeContainer = 0x200;
|
||||
private const uint LongDescKey = 16;
|
||||
private const uint TooBusy = 0x1D;
|
||||
private const string Me = "Drakkon";
|
||||
private static readonly (uint Cell, float X, float Y, float Z) Me0 = (0xA9B40019u, 100f, 100f, 0f);
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("pacing: a use is the server action until its UseDone; a refusal answers it too; a wield answers by wielding", UseAnswers);
|
||||
r.Add("pacing: the stall onset replayed - the idle peace swap waits for the corpse use's answer, then goes; no swap to the mode you're in", OnsetModeChangeHeld);
|
||||
r.Add("pacing: moves, turns and redundant stops wait while the server answers; a real stop and the cast nudge go through", MovesHeld);
|
||||
r.Add("pacing: no answer - each kind's time limit lets the next action go, logged, and nothing is force-cleared", TimeLimits);
|
||||
r.Add("pacing: heals (a plain heal waits for a corpse use's answer, 300 ms at Emergency, one behind a cast's result, 300 ms after the stance reads)", HealRules);
|
||||
r.Add("pacing (vitals): Drakkon 07:03 - a cast whose result is in waits for its UseDone: one cast, not a too-busy flood", CastWaitsForUseDone);
|
||||
r.Add("pacing (vitals): a heal waits for an unanswered corpse use's answer, then goes at once; the emergency stance settle is unchanged", HealLatencyKept);
|
||||
r.Add("pacing (looting): one open per server answer, never re-sent on top of an unanswered one", LootOneOpenPerAnswer);
|
||||
r.Add("pacing (looting): Drakkon's stall is still found and said once with pacing on", LootStallStillDetected);
|
||||
r.Add("pacing (combat): the idle peace swap waits while a kit is unanswered", CombatPeaceWaitsForKit);
|
||||
r.Add("pacing (arbiter): the activity-change StopCompletely only when RynthAi itself has the character moving", ArbiterStopOnlyWhenMoving);
|
||||
r.Add("busy mirror: follows the engine's count (1.5 s), never reset while the engine says busy; old engines: the mirror only; never a force-clear", MirrorResetOnly);
|
||||
r.Add("motion gate (14:29): a kit waits for the swing's animation; the corpse open waits for the kit's answer and then its animation", MotionGate1429);
|
||||
r.Add("pacing (motion): after a swing is sent, nothing else starts until it has played (16:45 wand on a swing)", SwingNotStarted);
|
||||
r.Add("motion gate (13:58): wand wield -> the cast and the Magic stance wait until the wield's animation is over", MotionGate1358);
|
||||
r.Add("motion gate (morning): corpse use -> the idle peace swap waits for the UseDone and then the turn's animation", MotionGateMorning);
|
||||
r.Add("motion gate: 4 s of 'animating' is taken as stuck (logged once, open until it reads clear); an emergency heal waits 1.5 s at most", MotionGateLimits);
|
||||
r.Add("motion gate: melee/missile attack repeats are not held by the animation, peace/magic combat starts are; off with the pacing", MotionGateAttackExempt);
|
||||
r.Add("motion gate (looting): a corpse open waits while the character animates, then goes", MotionGateLooting);
|
||||
r.Add("motion gate (items): the item managers' busy count includes the animation", MotionGateItems);
|
||||
}
|
||||
|
||||
// ── Pacer rig ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static long _t;
|
||||
|
||||
/// <summary>Turns the pacing on with RynthAi's use recorder and a hand-moved clock.</summary>
|
||||
private static void PaceOn()
|
||||
{
|
||||
_t = 10_000_000;
|
||||
ActionPacer.Reset();
|
||||
ActionPacer.Enabled = true;
|
||||
ActionPacer.NowMs = () => _t;
|
||||
UseAudit.Reset("RynthAi", () => true);
|
||||
UseAudit.NowMs = () => _t;
|
||||
MoveAudit.Reset();
|
||||
MoveAudit.NowMs = () => _t;
|
||||
var rec = typeof(RynthAiPlugin).GetMethod("RecordUseForPacing", Any)!;
|
||||
UseAudit.AfterSend = (h, u) => rec.Invoke(null, new object[] { h, u });
|
||||
}
|
||||
|
||||
private static void PaceOff()
|
||||
{
|
||||
ActionPacer.Enabled = false;
|
||||
ActionPacer.Reset();
|
||||
ActionPacer.NowMs = () => Environment.TickCount64;
|
||||
UseAudit.Reset("?", null);
|
||||
UseAudit.NowMs = () => Environment.TickCount64;
|
||||
MoveAudit.Reset();
|
||||
MoveAudit.NowMs = () => Environment.TickCount64;
|
||||
}
|
||||
|
||||
private static void Paced(Action body)
|
||||
{
|
||||
PaceOn();
|
||||
try { body(); }
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
|
||||
private static RynthCoreHost World(int combatMode = 2)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true; // UseObject, GetCurrentCombatMode
|
||||
FakeHost.SalvageCalls = true; // GetObjectWielderInfo
|
||||
FakeHost.ServerGates = true; // GetUseDoneSeq
|
||||
FakeHost.LastUseDoneCalls = true;
|
||||
FakeHost.UseOnCalls = true;
|
||||
FakeHost.CombatModeCalls = true;
|
||||
FakeHost.StopCalls = true;
|
||||
FakeHost.BusyCalls = true;
|
||||
FakeHost.CombatModeValue = combatMode;
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Names[Corpse] = "Corpse of Olthoi Swarm Worker";
|
||||
FakeHost.Names[Kit] = "Peerless Healing Kit";
|
||||
FakeHost.Names[Wand] = "Academy Wand";
|
||||
FakeHost.Bitfields[Corpse] = 0x2000;
|
||||
FakeHost.Containers[Kit] = Pack;
|
||||
FakeHost.Containers[Wand] = Pack;
|
||||
return FakeHost.Create(Player);
|
||||
}
|
||||
|
||||
private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
|
||||
|
||||
// ── The pacer ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static void UseAnswers() => Paced(() =>
|
||||
{
|
||||
var host = World();
|
||||
Check.True(host.UseFor(Corpse, "Loot", "open the claimed corpse"), "the open goes out");
|
||||
var a = ActionPacer.Current(host);
|
||||
Check.True(a != null && a.Kind == PacedKind.WorldUse, "a corpse is a world use the server walks to");
|
||||
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out string why), "nothing else starts meanwhile");
|
||||
Check.True(why.Contains("Corpse of Olthoi Swarm Worker") && why.Contains("RynthAi/Loot"), "why names the corpse and the sender: " + why);
|
||||
_t += 690; // the healthy median answer
|
||||
Check.True(ActionPacer.Current(host) != null, "still unanswered at 690 ms");
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(ActionPacer.Current(host) == null, "its UseDone answers it");
|
||||
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "the next action may go");
|
||||
|
||||
// A kit on yourself is an item use; "You're too busy" (0x1D) is an answer as well.
|
||||
Check.True(host.UseOnFor(Kit, Player, "Buff", "vitals: healing kit on yourself"), "the kit goes out");
|
||||
Check.True(ActionPacer.Current(host)?.Kind == PacedKind.ItemUse, "a kit on yourself is an item use");
|
||||
FakeHost.UseDone(TooBusy);
|
||||
Check.True(ActionPacer.Current(host) == null, "a refusal answers it (the server is busy with something else; the caller backs off)");
|
||||
|
||||
// A wield gets no UseDone at all (0 of 18 wand wields on 10-05/10-06): it answers by wielding.
|
||||
Check.True(host.UseFor(Wand, "Buff", "buffing: wield the wand"), "the wield goes out");
|
||||
Check.True(ActionPacer.Current(host)?.Kind == PacedKind.ItemUse, "an item use");
|
||||
_t += 400;
|
||||
Check.True(ActionPacer.Current(host) != null, "not wielded yet: waiting");
|
||||
FakeHost.Wielded[Wand] = 0x1000000;
|
||||
Check.True(ActionPacer.Current(host) != null, "wielded: a short settle first");
|
||||
_t += ActionPacer.WieldSettleMs;
|
||||
Check.True(ActionPacer.Current(host) == null, "wielded and settled: answered");
|
||||
Check.Eq(ActionPacer.TimedOut, 0L, "no time limit was needed");
|
||||
});
|
||||
|
||||
private static void OnsetModeChangeHeld() => Paced(() =>
|
||||
{
|
||||
// 06:18:44.549 corpse use in melee stance, 06:18:44.552 RequestCombatMode(peace).
|
||||
var host = World(combatMode: 2);
|
||||
host.UseFor(Corpse, "Loot", "open the claimed corpse");
|
||||
_t += 3;
|
||||
Check.False(host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", "idle: no target"), "3 ms later: the peace swap is held");
|
||||
_t += 674;
|
||||
Check.False(host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", "idle: no target"), "677 ms later (10-05 13:18:31): still held");
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no mode change reached the server while the use was unanswered");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("change to Peace mode held")), 1, "logged once");
|
||||
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", "idle: no target"), "answered: the swap goes out");
|
||||
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "one request, to peace");
|
||||
Check.True(ActionPacer.Current(host)?.Kind == PacedKind.CombatMode, "the stance change is now the action the server is answering");
|
||||
|
||||
// The next corpse waits for the stance: the client reads peace, then the animation.
|
||||
FakeHost.CombatModeValue = 1;
|
||||
_t += 500;
|
||||
Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "500 ms: the stance animation is still running");
|
||||
_t += ActionPacer.ModeSettleMs - 500;
|
||||
Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "800 ms: settled, the next open may go");
|
||||
|
||||
// No request for the mode the client already reads (the engine pushed a raw 0x53 anyway).
|
||||
FakeHost.CombatModeRequests.Clear();
|
||||
Check.False(host.ChangeCombatModeFor(CombatMode.NonCombat, "Loot/Wedge", "loot wedge reset"), "already in peace: nothing to send");
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "nothing sent");
|
||||
Check.True(host.ChangeCombatModeFor(CombatMode.NonCombat, "Command", "/ra panic", force: true), "a typed command forces it");
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, 1, "forced: sent");
|
||||
});
|
||||
|
||||
private static void MovesHeld() => Paced(() =>
|
||||
{
|
||||
var host = World();
|
||||
host.UseFor(Corpse, "Loot", "open the claimed corpse");
|
||||
Check.False(host.SetAutoRunBy("Nav", true), "nav can't start running");
|
||||
Check.False(host.TurnToHeadingBy("Nav", 90f), "nor turn");
|
||||
Check.False(host.SetMotionBy("Combat", 0x6500000D, true), "nor start a turn motion");
|
||||
Check.False(host.StopCompletelyBy("Arbiter"), "a stop with nothing of ours moving is a redundant movement packet: held");
|
||||
Check.False(host.SetMotionBy("Combat", 0x6500000D, false), "Combat's turn-off with no turn on: held");
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "no autorun reached the client");
|
||||
Check.Eq(FakeHost.Stops, 0, "no stop either");
|
||||
Check.True(Logged("held (move/turn): the server is still answering the use of"), "the hold is logged");
|
||||
|
||||
Check.True(host.SetAutoRunBy("Buff/Nudge", true) && host.SetAutoRunBy("Buff/Nudge", false), "the held-cast nudge is deliberate: it goes through");
|
||||
Check.True(host.StopCompletelyBy("MacroStop"), "a macro stop goes through");
|
||||
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(host.SetAutoRunBy("Nav", true), "answered: nav runs again");
|
||||
host.UseFor(CorpseB, "Loot", "open the claimed corpse");
|
||||
FakeHost.Names[CorpseB] = "Corpse of Olthoi Swarm Drone";
|
||||
Check.True(host.StopCompletelyBy("Arbiter"), "while we really run, a stop always goes through");
|
||||
Check.False(MoveAudit.OwnMovementActive, "and we are not moving any more");
|
||||
});
|
||||
|
||||
private static void TimeLimits() => Paced(() =>
|
||||
{
|
||||
var host = World();
|
||||
void Expect(PacedKind kind, long limit, Action send)
|
||||
{
|
||||
long before = ActionPacer.TimedOut;
|
||||
send();
|
||||
Check.True(ActionPacer.Current(host)?.Kind == kind, $"{kind}: outstanding");
|
||||
_t += limit - 1;
|
||||
Check.True(ActionPacer.Current(host) != null, $"{kind}: still waiting 1 ms before {limit} ms");
|
||||
_t += 1;
|
||||
Check.True(ActionPacer.Current(host) == null, $"{kind}: the time limit lets the next action go");
|
||||
Check.Eq(ActionPacer.TimedOut, before + 1, $"{kind}: counted");
|
||||
}
|
||||
Expect(PacedKind.WorldUse, ActionPacer.WorldUseMaxMs, () => host.UseFor(Corpse, "Loot", "open"));
|
||||
Expect(PacedKind.ItemUse, ActionPacer.ItemUseMaxMs, () => host.UseOnFor(Kit, Player, "Buff", "kit"));
|
||||
Expect(PacedKind.Cast, ActionPacer.CastMaxMs, () => host.CastSpellFor(Player, 1426, "Buff", "Focus Self VI"));
|
||||
FakeHost.CombatModeValue = 2;
|
||||
Expect(PacedKind.CombatMode, ActionPacer.ModeMaxMs, () => host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand"));
|
||||
Check.True(Logged("no answer from the server to the cast of Focus Self VI") && Logged("nothing cleared"), "each is logged, and says nothing was cleared");
|
||||
Check.Eq(FakeHost.ForceResets, 0, "the client's busy count was never force-cleared");
|
||||
});
|
||||
|
||||
private static void HealRules() => Paced(() =>
|
||||
{
|
||||
var host = World();
|
||||
host.UseFor(Corpse, "Loot", "open");
|
||||
_t += 900;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a heal 900 ms behind an unanswered corpse use waits");
|
||||
_t += 3000;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _),
|
||||
"a plain heal still waits at 3.9 s: on ACE any motion during the server's turn to the corpse stops that turn for good");
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "the use is answered: the heal goes");
|
||||
|
||||
host.UseFor(Corpse, "Loot", "open");
|
||||
_t += 299;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "at Emergency Heal At: not before 300 ms");
|
||||
_t += 1;
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "at Emergency Heal At: 300 ms");
|
||||
Check.True(Logged("the heal goes ahead of the use of"), "logged");
|
||||
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "anything else still waits");
|
||||
|
||||
FakeHost.UseDone(0);
|
||||
host.CastSpellFor(Player, 1426, "Buff", "Focus Self VI");
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a cast before its result: the heal waits (the server would refuse it)");
|
||||
ActionPacer.NoteCastResult();
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "its result is in: one heal may queue behind the recoil");
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "only one");
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "a buff waits for the UseDone");
|
||||
|
||||
FakeHost.UseDone(0);
|
||||
FakeHost.CombatModeValue = 2;
|
||||
host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode");
|
||||
_t += 60;
|
||||
FakeHost.CombatModeValue = 8;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "the client reads Magic: not yet");
|
||||
_t += 299;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "299 ms after the read: not yet");
|
||||
_t += 1;
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "300 ms after the read: the heal goes");
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "a buff waits for the full 800 ms settle");
|
||||
});
|
||||
|
||||
// ── BuffManager ──────────────────────────────────────────────────────────────
|
||||
|
||||
private sealed class BuffRig
|
||||
{
|
||||
public DateTime T0 = new(2026, 10, 6, 7, 3, 23);
|
||||
public DateTime NowAt;
|
||||
public readonly BuffManager B;
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly PlayerVitalsCache V;
|
||||
public RynthCoreHost Host;
|
||||
|
||||
public BuffRig(int combatMode = CombatMode.Magic)
|
||||
{
|
||||
Host = World(combatMode);
|
||||
FakeHost.Containers.Clear();
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, 33)] = (400, 2);
|
||||
Host = FakeHost.Create(Player);
|
||||
S = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false,
|
||||
EnableBuffing = false, SpellCastIntervalMs = 0,
|
||||
};
|
||||
var skills = new CharacterSkills(Host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(Host, S);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
V = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 10 };
|
||||
B = new BuffManager(Host, S, sm, V);
|
||||
B.SetCharacterSkills(skills);
|
||||
NowAt = T0;
|
||||
B.Clock = () => NowAt;
|
||||
B.MarkLiveBuffsReadyForTests();
|
||||
_t = 10_000_000;
|
||||
ActionPacer.NowMs = () => _t + (long)(NowAt - T0).TotalMilliseconds;
|
||||
MoveAudit.NowMs = ActionPacer.NowMs;
|
||||
}
|
||||
|
||||
public void At(double seconds) => NowAt = T0.AddSeconds(seconds);
|
||||
public void Chat(string text, int type = 0) => B.OnChatWindowText(text, type);
|
||||
public string CastName => SpellTable.ById(FakeHost.Casts.Last().SpellId)?.Name ?? "";
|
||||
}
|
||||
|
||||
private static void CastWaitsForUseDone()
|
||||
{
|
||||
// Without the pacing (as before): the result line ends the cast, and with mana still low the
|
||||
// next Stamina to Mana goes straight out - on a server holding the first one, "too busy".
|
||||
int Script(bool pacing)
|
||||
{
|
||||
PaceOn();
|
||||
ActionPacer.Enabled = pacing;
|
||||
try
|
||||
{
|
||||
var r = new BuffRig();
|
||||
r.At(0); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, $"pacing={pacing}: Stamina to Mana goes out");
|
||||
string name = r.CastName;
|
||||
r.At(0.1); r.Chat("You say, \"Puish Zharil\"", 17);
|
||||
// 07:03:26.799: the result is in 3.3 s later; the server's UseDone never comes.
|
||||
r.At(2.3); r.Chat($"You cast {name} on yourself and lose 35 points of stamina and also gain 47 points of mana");
|
||||
for (double s = 2.4; s < 4.0; s += 0.1) { r.At(s); r.B.OnHeartbeat(); }
|
||||
int before = FakeHost.Casts.Count;
|
||||
if (pacing)
|
||||
{
|
||||
Check.True(r.B.PacerHolds > 0, "the vitals step waited for the server's answer");
|
||||
FakeHost.UseDone(0);
|
||||
r.At(4.0); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 2, "the UseDone arrives: the next cast goes at once");
|
||||
}
|
||||
return before;
|
||||
}
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
int unpaced = Script(pacing: false);
|
||||
int paced = Script(pacing: true);
|
||||
Check.True(unpaced >= 2, $"without pacing a second cast went out before the server answered ({unpaced} casts by 4 s)");
|
||||
Check.Eq(paced, 1, "with pacing: one cast until the server answers it");
|
||||
}
|
||||
|
||||
private static void HealLatencyKept()
|
||||
{
|
||||
PaceOn();
|
||||
try
|
||||
{
|
||||
// A heal behind a corpse use the server walks/turns to: it waits for the use's answer (a cast
|
||||
// during the server's turn stops the turn for good on ACE), then goes at once.
|
||||
var r = new BuffRig();
|
||||
r.S.HealAt = 60; r.S.TopOffHP = 60; r.S.GetManaAt = 0; r.S.TopOffMana = 0;
|
||||
r.V.CurrentHealth = 50; r.V.CurrentMana = 100;
|
||||
r.At(0);
|
||||
r.Host.UseFor(Corpse, "Loot", "open the claimed corpse");
|
||||
r.B.BusyCount = 1; // the open's +1 on the client's count, as the engine reports it
|
||||
for (double s = 0; s < 1.45; s += 0.1) { r.At(s); r.B.OnHeartbeat(); }
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "behind the unanswered open: no heal");
|
||||
FakeHost.UseDone(0);
|
||||
r.B.BusyCount = 0; // the engine's UseDone decrement
|
||||
r.At(1.5); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "the open is answered: the heal goes on the next heartbeat");
|
||||
string healName = SpellTable.ById(FakeHost.Casts[0].SpellId)?.Name ?? "";
|
||||
Check.True(healName.StartsWith("Heal Self") || healName == "Adja's Intervention", "and it is the heal spell: " + healName);
|
||||
|
||||
// Nothing outstanding: the heal goes on the first heartbeat, as before.
|
||||
PaceOff(); PaceOn();
|
||||
var q = new BuffRig();
|
||||
q.S.HealAt = 60; q.S.TopOffHP = 60; q.S.GetManaAt = 0; q.S.TopOffMana = 0;
|
||||
q.V.CurrentHealth = 50; q.V.CurrentMana = 100;
|
||||
q.At(0); q.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "nothing outstanding: Heal Self on the first heartbeat");
|
||||
|
||||
// The emergency settle after a stance change (CastSafetyTests.EmergencyStanceWait) with the
|
||||
// pacing on: the stance change is the outstanding action, and the heal still goes 300 ms
|
||||
// after the client reads Magic.
|
||||
PaceOff(); PaceOn();
|
||||
var e = new BuffRig(CombatMode.NonCombat);
|
||||
e.S.EmergencyHealAt = 30; e.S.HealAt = 60; e.S.TopOffHP = 60; e.S.GetManaAt = 0; e.S.TopOffMana = 0;
|
||||
e.V.CurrentHealth = 20; e.V.CurrentMana = 100;
|
||||
e.At(0); e.B.OnHeartbeat();
|
||||
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", "out of Magic: the stance request goes out");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no cast before the stance");
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
e.At(0.06); e.B.OnHeartbeat();
|
||||
e.At(0.30); e.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "240 ms after Magic: still settling");
|
||||
e.At(0.37); e.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "310 ms after Magic (370 ms after the request): Heal Self goes, as without pacing");
|
||||
}
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
|
||||
// ── Looting ──────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void LootWorld()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true;
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.ServerGates = true;
|
||||
FakeHost.LastUseDoneCalls = true;
|
||||
FakeHost.StopCalls = true;
|
||||
FakeHost.BusyCalls = true;
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
foreach ((uint id, float dx) in new[] { (Corpse, 1.0f), (CorpseB, 1.5f) })
|
||||
{
|
||||
FakeHost.Names[id] = "Corpse of Olthoi Swarm Worker";
|
||||
FakeHost.ItemTypes[id] = ItemTypeContainer;
|
||||
FakeHost.Strings[(id, LongDescKey)] = $"Killed by {Me}.";
|
||||
FakeHost.NotAttackable.Add(id);
|
||||
FakeHost.Positions[id] = (Me0.Cell, Me0.X + dx, Me0.Y, Me0.Z);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new()
|
||||
{
|
||||
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
|
||||
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
|
||||
};
|
||||
|
||||
public Bot(RynthCoreHost host)
|
||||
{
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
Set("_objectCache", cache);
|
||||
Set("_playerId", Player);
|
||||
cache.OnCreateObject(Corpse);
|
||||
cache.OnCreateObject(CorpseB);
|
||||
cache.Tick();
|
||||
string profile = Path.Combine(Program.TempRoot, "action-pacing-test.json");
|
||||
new LootProfile { Name = "nothing" }.Save(profile);
|
||||
S.CurrentLootPath = profile;
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
|
||||
public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
|
||||
public void Tick() { Set("_activity", BotActivity.Looting); Call("TickCorpseOpening"); }
|
||||
}
|
||||
|
||||
/// <summary>The loot clock and the pacer clock on one fake time.</summary>
|
||||
private static void WithClock(Action<Func<long>, Action<long>> body)
|
||||
{
|
||||
long now = 50_000_000;
|
||||
var saved = RynthAiPlugin.CorpseClock;
|
||||
RynthAiPlugin.CorpseClock = () => now;
|
||||
ActionPacer.NowMs = () => now;
|
||||
UseAudit.NowMs = () => now;
|
||||
MoveAudit.NowMs = () => now;
|
||||
try { body(() => now, ms => now += ms); }
|
||||
finally { RynthAiPlugin.CorpseClock = saved; }
|
||||
}
|
||||
|
||||
private static void LootOneOpenPerAnswer()
|
||||
{
|
||||
LootWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
PaceOn();
|
||||
try
|
||||
{
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
for (int i = 0; i < 10 && FakeHost.Uses.Count == 0; i++) { bot.Tick(); advance(100); }
|
||||
Check.Eq(FakeHost.Uses.Count, 1, "the open goes out");
|
||||
// A long walk: no answer for 3 s. Before, the open was re-sent every LootOpenRetryMs,
|
||||
// and each re-send restarted the server's walk and failed the first open's callback.
|
||||
for (int i = 0; i < 30; i++) { bot.Tick(); advance(100); }
|
||||
Check.Eq(FakeHost.Uses.Count, 1, "not re-sent while the server hasn't answered");
|
||||
Check.True(Logged("[Pace] Loot waits: the use of"), "the wait is logged once");
|
||||
FakeHost.UseDone(0);
|
||||
bot.P.OnViewObjectContents(FakeHost.Uses.Last());
|
||||
Check.True(ActionPacer.Current(host) == null, "answered: nothing outstanding");
|
||||
// The empty corpse is done; the next one is opened - once, and only now.
|
||||
for (int i = 0; i < 20; i++) { bot.Tick(); advance(100); }
|
||||
Check.Eq(FakeHost.Uses.Count, 2, "the next corpse's open went out after the answer, once");
|
||||
Check.Eq(FakeHost.Uses.Last(), CorpseB, "it is the other corpse");
|
||||
Check.True(ActionPacer.Current(host)?.Id == CorpseB, "and it is the action the server is answering now");
|
||||
Check.Eq(FakeHost.ForceResets, 0, "no force-clear");
|
||||
});
|
||||
}
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
|
||||
private static void LootStallStillDetected()
|
||||
{
|
||||
LootWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
PaceOn();
|
||||
try
|
||||
{
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
long answerAt = 0;
|
||||
int maxOutstanding = 0;
|
||||
void Step()
|
||||
{
|
||||
int uses = FakeHost.Uses.Count;
|
||||
bot.Tick();
|
||||
if (FakeHost.Uses.Count > uses) answerAt = now() + 60;
|
||||
maxOutstanding = Math.Max(maxOutstanding, FakeHost.Uses.Count - FakeHost.UseDoneSeq);
|
||||
advance(100);
|
||||
if (answerAt != 0 && now() >= answerAt) { FakeHost.UseDone(0); answerAt = 0; }
|
||||
}
|
||||
int steps = 0;
|
||||
while (FakeHost.Chat.Count(c => c.Contains("isn't letting this character use objects")) == 0 && steps++ < 900) Step();
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("isn't letting this character use objects")), 1,
|
||||
$"the stall is found and said once ({steps / 10.0} s)");
|
||||
Check.True(steps <= 600, $"within a minute ({steps / 10.0} s)");
|
||||
Check.True(maxOutstanding <= 1, $"never more than one open unanswered (max {maxOutstanding})");
|
||||
});
|
||||
}
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
|
||||
// ── Combat ───────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void CombatPeaceWaitsForKit() => Paced(() =>
|
||||
{
|
||||
var host = World(combatMode: 2);
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
var s = new LegacyUiSettings { IsMacroRunning = true, EnableCombat = true, PeaceModeWhenIdle = true, MonsterRange = 50 };
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
var combat = new CombatManager(host, s, cache);
|
||||
combat.SetPlayerId(Player);
|
||||
|
||||
// 07:00:11.8: a kit on yourself in melee stance; the server answers 2.4 s later.
|
||||
host.UseOnFor(Kit, Player, "Buff", "vitals: healing kit on yourself");
|
||||
for (int i = 0; i < 5; i++) { combat.Think(); _t += 400; }
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no peace swap while the kit is unanswered");
|
||||
FakeHost.UseDone(0);
|
||||
combat.Think();
|
||||
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "the kit answered: the idle swap goes out");
|
||||
});
|
||||
|
||||
private static void ArbiterStopOnlyWhenMoving()
|
||||
{
|
||||
LootWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
PaceOn();
|
||||
try
|
||||
{
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
bot.Call("StopNavFor", BotActivity.Looting);
|
||||
Check.Eq(FakeHost.Stops, 0, "nothing of ours moving: no StopCompletely (another plugin's movement isn't cut off)");
|
||||
host.SetAutoRunBy("Nav", true);
|
||||
bot.Call("StopNavFor", BotActivity.Buffing);
|
||||
Check.Eq(FakeHost.Stops, 1, "our autorun on: the stop goes out");
|
||||
ActionPacer.Enabled = false;
|
||||
bot.Call("StopNavFor", BotActivity.Combat);
|
||||
Check.Eq(FakeHost.Stops, 2, "pacing off: as before, always");
|
||||
});
|
||||
}
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
|
||||
// ── Busy mirror ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static void MirrorResetOnly()
|
||||
{
|
||||
// The engine's count is the owner: a mirror left up follows it down after 1.5 s.
|
||||
LootWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
FakeHost.BusyStateValue = 0; // the engine has seen the UseDones
|
||||
bot.Set("_busyCount", 2);
|
||||
bot.Set("_busyCountBecamePositiveAt", now());
|
||||
bot.Call("CheckBusyTimeout");
|
||||
Check.Eq(bot.Get<int>("_busyCount"), 2, "a fresh disagreement waits (events may be on their way)");
|
||||
advance(1_600);
|
||||
bot.Call("CheckBusyTimeout");
|
||||
Check.Eq(bot.Get<int>("_busyCount"), 0, "1.6 s later: the mirror follows the engine's 0");
|
||||
Check.True(Logged("following the engine's count"), "logged");
|
||||
|
||||
FakeHost.BusyStateValue = 1; // the server owes an answer: the mirror follows that too
|
||||
bot.Call("CheckBusyTimeout"); advance(1_600); bot.Call("CheckBusyTimeout");
|
||||
Check.Eq(bot.Get<int>("_busyCount"), 1, "and up, while the server still owes an answer");
|
||||
advance(30_000); bot.Call("CheckBusyTimeout");
|
||||
Check.Eq(bot.Get<int>("_busyCount"), 1, "never reset on a timer while the engine says busy");
|
||||
Check.Eq(FakeHost.ForceResets, 0, "the client's busy count is left to the client");
|
||||
});
|
||||
|
||||
// An engine without GetBusyState: the old timer, resetting the mirror only.
|
||||
LootWorld();
|
||||
FakeHost.BusyCalls = false;
|
||||
host = FakeHost.Create(Player);
|
||||
bot = new Bot(host);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
bot.Set("_busyCount", 2);
|
||||
bot.Set("_busyCountBecamePositiveAt", now());
|
||||
advance(10_500);
|
||||
bot.Call("CheckBusyTimeout");
|
||||
Check.Eq(bot.Get<int>("_busyCount"), 0, "old engine: our mirror is reset after 10 s");
|
||||
Check.True(Logged("resetting the mirror only"), "and the line says so");
|
||||
});
|
||||
}
|
||||
|
||||
// ── The motion gate (2026-10-06 afternoon, ops\overnight\2026-10-06-turnto-stall.md) ──────────
|
||||
// Nothing starts while the character is still animating (the client's motion queue, the engine's
|
||||
// GetCastBusyState); FakeHost.CastBusy = 1 stands for "animating".
|
||||
|
||||
// 16:45:37: the wand's use went 110 ms after a MeleeAttack, before the swing animated.
|
||||
private static void SwingNotStarted() => Paced(() =>
|
||||
{
|
||||
var host = World();
|
||||
FakeHost.CastBusy = 0;
|
||||
ActionPacer.NoteAttackSent();
|
||||
_t += 110;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out string why), "the wand waits: the swing hasn't animated yet");
|
||||
Check.True(why.Contains("swing"), "why: " + why);
|
||||
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "the next attack isn't held");
|
||||
_t += 200;
|
||||
FakeHost.CastBusy = 1;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "swinging: still waits");
|
||||
_t += 700;
|
||||
FakeHost.CastBusy = 0;
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "the swing played: the wand goes");
|
||||
|
||||
ActionPacer.NoteAttackSent();
|
||||
_t += 600;
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "an emergency heal waits at most 500 ms");
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "anything else still waits");
|
||||
_t += 1000;
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "a swing that never animates holds at most 1.5 s");
|
||||
Check.True(ActionPacer.SwingHoldCount >= 2, "holds counted");
|
||||
});
|
||||
|
||||
private static void MotionGate1429() => Paced(() =>
|
||||
{
|
||||
var host = World();
|
||||
// 14:29:21.435 the swing; 22.380 AttackDone (the attack sequence is over, the swing still plays).
|
||||
FakeHost.CastBusy = 1;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out string why), "22.41: the kit waits for the swing's animation");
|
||||
Check.True(why.Contains("still animating"), "why says so: " + why);
|
||||
Check.True(Logged("[Pace] Buff waits: the character is still animating"), "logged once");
|
||||
_t += 300;
|
||||
FakeHost.CastBusy = 0;
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "the swing is over: the kit goes");
|
||||
host.UseOnFor(Kit, Player, "Buff", "vitals: healing kit on yourself");
|
||||
FakeHost.CastBusy = 1; // the kit's SkillHealSelf
|
||||
_t += 2400;
|
||||
Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "the corpse open waits for the kit's answer");
|
||||
FakeHost.UseDone(0); // 24.794 the kit's UseDone; the client still plays the kit's last frames
|
||||
Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out why), "answered, but still animating: the open waits");
|
||||
Check.True(why.Contains("still animating"), "why: " + why);
|
||||
_t += 120;
|
||||
FakeHost.CastBusy = 0;
|
||||
Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "at rest: the corpse open goes");
|
||||
Check.True(ActionPacer.GestureHoldCount >= 2, "holds counted");
|
||||
});
|
||||
|
||||
private static void MotionGate1358() => Paced(() =>
|
||||
{
|
||||
var host = World(combatMode: 2);
|
||||
// 13:58:54.210 the wand is wielded in melee stance (its use is an item use, answered by wielding).
|
||||
host.UseFor(Wand, "Buff", "buffing: switch to the wand");
|
||||
FakeHost.CastBusy = 1; // the unwield/wield and stance motion
|
||||
FakeHost.Wielded[Wand] = 0x01000000;
|
||||
_t += 50;
|
||||
ActionPacer.Current(host); // the wield is first seen done
|
||||
_t += 200;
|
||||
Check.True(ActionPacer.Current(host) == null, "the wield reads done: answered");
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "the cast waits: still animating");
|
||||
Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode"), "the Magic stance waits too");
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no mode request sent");
|
||||
Check.True(Logged("[Pace] mode:Buff waits: the character is still animating"), "logged");
|
||||
_t += 900;
|
||||
FakeHost.CastBusy = 0;
|
||||
Check.True(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode"), "at rest: Magic mode");
|
||||
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", "sent");
|
||||
FakeHost.CombatModeValue = 8;
|
||||
FakeHost.CastBusy = 1; // the stance animation
|
||||
_t += ActionPacer.ModeSettleMs;
|
||||
Check.True(ActionPacer.Current(host) == null, "the stance is read and settled");
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "but the client still animates it: the cast waits");
|
||||
FakeHost.CastBusy = 0;
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "at rest: the cast goes");
|
||||
});
|
||||
|
||||
private static void MotionGateMorning() => Paced(() =>
|
||||
{
|
||||
var host = World(combatMode: 2);
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
var s = new LegacyUiSettings { IsMacroRunning = true, EnableCombat = true, PeaceModeWhenIdle = true, MonsterRange = 50 };
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
var combat = new CombatManager(host, s, cache);
|
||||
combat.SetPlayerId(Player);
|
||||
|
||||
// 06:18:44.549 the corpse use in melee stance; the idle peace swap came 3 ms later.
|
||||
host.UseFor(Corpse, "Loot", "open the claimed corpse");
|
||||
_t += 3;
|
||||
combat.Think();
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "3 ms later: no peace swap (the use is unanswered)");
|
||||
FakeHost.CastBusy = 1; // the turn to the corpse
|
||||
_t += 400;
|
||||
FakeHost.UseDone(0);
|
||||
typeof(CombatManager).GetField("_lastPeaceAttempt", Any)!.SetValue(combat, DateTime.MinValue);
|
||||
combat.Think();
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "answered, but the character still animates: no peace swap");
|
||||
_t += 200;
|
||||
FakeHost.CastBusy = 0;
|
||||
typeof(CombatManager).GetField("_lastPeaceAttempt", Any)!.SetValue(combat, DateTime.MinValue);
|
||||
combat.Think();
|
||||
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "at rest: the idle swap goes out");
|
||||
});
|
||||
|
||||
private static void MotionGateLimits() => Paced(() =>
|
||||
{
|
||||
var host = World();
|
||||
FakeHost.CastBusy = 1;
|
||||
Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "animating: held");
|
||||
_t += 1499;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "an emergency heal waits up to 1.5 s");
|
||||
_t += 1;
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "at 1.5 s the emergency heal goes");
|
||||
Check.True(Logged("emergency heal after 1500 ms of animation - going on"), "logged");
|
||||
Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "anything else still waits");
|
||||
_t += ActionPacer.GestureHoldMaxMs - 1500;
|
||||
Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "4 s: taken as stuck, the action goes");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("taken as stuck, going on")), 1, "logged once");
|
||||
_t += 5000;
|
||||
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "still open while it reads busy");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("taken as stuck, going on")), 1, "not logged again");
|
||||
Check.Eq(ActionPacer.GestureLimits, 2L, "two limits counted");
|
||||
FakeHost.CastBusy = 0;
|
||||
Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "clear");
|
||||
Check.True(Logged("animation queue reads clear again"), "the recovery is logged");
|
||||
FakeHost.CastBusy = 1;
|
||||
Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "a new animation: held again (a fresh 4 s)");
|
||||
});
|
||||
|
||||
private static void MotionGateAttackExempt() => Paced(() =>
|
||||
{
|
||||
var host = World(combatMode: 2);
|
||||
FakeHost.CastBusy = 1; // the last swing still plays
|
||||
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "a melee attack repeat is not held by the animation");
|
||||
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "anything gated is");
|
||||
host.UseFor(Corpse, "Loot", "open");
|
||||
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "but an attack still waits for an unanswered corpse use (the server's turn)");
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(ActionPacer.Current(host) == null, "the use is answered");
|
||||
ActionPacer.Enabled = false;
|
||||
Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "pacing off: no gate");
|
||||
Check.False(ActionPacer.GestureHolds(host, "Loot", HealNeed.None, out _), "pacing off: no animation hold");
|
||||
ActionPacer.Enabled = true;
|
||||
FakeHost.ServerGates = false;
|
||||
var old = FakeHost.Create(Player);
|
||||
Check.True(ActionPacer.MayStart(old, "Loot", HealNeed.None, out _), "an engine without the gate: no opinion");
|
||||
});
|
||||
|
||||
private static void MotionGateLooting()
|
||||
{
|
||||
LootWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
PaceOn();
|
||||
try
|
||||
{
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
FakeHost.CastBusy = 1;
|
||||
for (int i = 0; i < 20; i++) { bot.Tick(); advance(100); }
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "no open while the character animates");
|
||||
Check.True(Logged("[Pace] Loot waits: the character is still animating"), "logged");
|
||||
FakeHost.CastBusy = 0;
|
||||
for (int i = 0; i < 10 && FakeHost.Uses.Count == 0; i++) { bot.Tick(); advance(100); }
|
||||
Check.Eq(FakeHost.Uses.Count, 1, "at rest: the open goes");
|
||||
});
|
||||
}
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
|
||||
private static void MotionGateItems()
|
||||
{
|
||||
LootWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
PaceOn();
|
||||
try
|
||||
{
|
||||
int Busy() => (int)typeof(RynthAiPlugin).GetProperty("PacedBusy", Any)!.GetValue(bot.P)!;
|
||||
Check.Eq(Busy(), 0, "at rest, nothing outstanding: 0");
|
||||
FakeHost.CastBusy = 1;
|
||||
Check.Eq(Busy(), 1, "animating: +1 (a pack move of a wielded item, a stone, a summon waits)");
|
||||
FakeHost.CastBusy = 0;
|
||||
Check.Eq(Busy(), 0, "at rest again: 0");
|
||||
}
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
}
|
||||
|
|
@ -87,7 +87,9 @@ internal static class AttackLatencyTests
|
|||
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, 0, true, false), 0.0, "magic, setting 0: no delay of its own (the server gates hold the cast)");
|
||||
Check.Eq(CombatManager.AttackIntervalMs(Magic, 0, false, false), CombatManager.NoGatesAttackFloorMs, "setting 0 without the server gates: the 250 ms floor");
|
||||
Check.Eq(CombatManager.AttackIntervalMs(Magic, -1, true, false), 1500.0, "unset: 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,
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ namespace RynthCore.RynthAiHostTests.Tests;
|
|||
internal static class BuffTests
|
||||
{
|
||||
private const uint Player = 0x50000B01;
|
||||
private const uint STypeCreature = 31, STypeItem = 32;
|
||||
private const uint STypeCreature = 31, STypeItem = 32, STypeLife = 33;
|
||||
|
||||
/// <summary>Buff/tier pairs the name tables used to miss (fixed by 940cb21); NameGapsResolve checks them by name.</summary>
|
||||
private static readonly HashSet<(string Buff, int Tier)> NameGaps = new()
|
||||
|
|
@ -54,6 +54,9 @@ internal static class BuffTests
|
|||
r.Add("rebuff: our own lower tier under an expiring higher one counts as on", RebuffUnderExpiringHigherTier);
|
||||
r.Add("rebuff: cast over item-granted buffs (CastBuffsOverItemBuffs on)", RebuffOverItemBuffs);
|
||||
r.Add("rebuff: CastBuffsOverItemBuffs defaults on, loads, saves, bridges", OverItemBuffsSetting);
|
||||
r.Add("buff toggles: by default every prot and bane is cast", TogglesDefaultAllOn);
|
||||
r.Add("buff toggles: an unticked prot or bane is never cast and never holds NeedsAnyBuff", UntickedSkipped);
|
||||
r.Add("buff toggles: an old profile loads all on; the list saves, copies and bridges", TogglesSetting);
|
||||
|
||||
r.Add("buff choice: spell names the tables miss (Bludgeon Bane, Nuhmudira's, T'ing, Celdiseth's)", NameGapsResolve); // was a known failure; fixed by 940cb21
|
||||
r.Add("buff choice: a mastery whose name has several spell ids", MultiIdMastery); // was a known failure; fixed by 0aedcee
|
||||
|
|
@ -596,6 +599,129 @@ internal static class BuffTests
|
|||
Check.True(s.CastBuffsOverItemBuffs, "a save with it on turns it on");
|
||||
}
|
||||
|
||||
// ── Prot and bane toggles (Buffing settings, DisabledBuffs) ───────────────
|
||||
|
||||
private static readonly MethodInfo CastSelfBuffs =
|
||||
typeof(BuffManager).GetMethod("CheckAndCastSelfBuffs", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
|
||||
/// <summary>Tier 6 Life and Item Magic, in Magic stance, knowing two prots and two banes.</summary>
|
||||
private static BuffRig ProtBaneRig()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
Know("Fire Protection Self VI", "Cold Protection Self VI", "Flame Bane VI", "Frost Bane VI");
|
||||
FakeHost.Skills[(Player, STypeLife)] = (300, 2);
|
||||
FakeHost.Skills[(Player, STypeItem)] = (300, 2);
|
||||
FakeHost.WeaponCalls = true; // GetCurrentCombatMode answers CombatModeValue
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
return new BuffRig();
|
||||
}
|
||||
|
||||
/// <summary>Runs the buff cast loop until it casts nothing, confirming each cast by chat as the
|
||||
/// server would. Returns the spells cast in order; <paramref name="done"/> = the loop's last
|
||||
/// answer was "nothing to do" (what ends a batch in the heartbeat).</summary>
|
||||
private static List<string> CastAll(BuffRig rig, out bool done)
|
||||
{
|
||||
var cast = new List<string>();
|
||||
done = false;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
int before = FakeHost.Casts.Count;
|
||||
bool acted = (bool)CastSelfBuffs.Invoke(rig.B, null)!;
|
||||
if (FakeHost.Casts.Count == before) { done = !acted; break; }
|
||||
string name = NameOf(FakeHost.Casts.Last().SpellId);
|
||||
cast.Add(name);
|
||||
rig.B.OnChatWindowText($"You cast {name} on {(name.Contains("Bane") ? "Rune Robe" : "yourself")}", 7);
|
||||
}
|
||||
return cast;
|
||||
}
|
||||
|
||||
private static void TogglesDefaultAllOn()
|
||||
{
|
||||
var rig = ProtBaneRig();
|
||||
Check.Eq(rig.S.DisabledBuffs.Count, 0, "a new profile unticks nothing");
|
||||
foreach (var (buff, _) in BuffManager.ToggleProtections.Concat(BuffManager.ToggleBanes))
|
||||
Check.True(rig.B.BuildDynamicBuffList().Contains(buff), $"every toggle names a buff in the list: {buff}");
|
||||
rig.Live(("Strength Self I", 3000)); // a registry read, with none of ours on
|
||||
Check.True(rig.B.NeedsAnyBuff(), "nothing on: needs buffs");
|
||||
var cast = CastAll(rig, out bool done);
|
||||
Check.Eq(string.Join(", ", cast), "Fire Protection Self VI, Cold Protection Self VI, Flame Bane VI, Frost Bane VI", $"all four are cast (last skip: {rig.B.LastBuffSkipReason})");
|
||||
Check.True(done, "then the loop has nothing left");
|
||||
}
|
||||
|
||||
private static void UntickedSkipped()
|
||||
{
|
||||
var rig = ProtBaneRig();
|
||||
rig.S.SetBuffEnabled("Fire Protection Self", false);
|
||||
rig.S.SetBuffEnabled("flame bane", false); // names match case-insensitively
|
||||
Check.False(rig.B.BuildDynamicBuffList().Contains("Fire Protection Self"), "an unticked prot leaves the list");
|
||||
Check.False(rig.B.BuildDynamicBuffList().Contains("Flame Bane"), "an unticked bane leaves the list");
|
||||
rig.Live(("Strength Self I", 3000));
|
||||
var cast = CastAll(rig, out bool done);
|
||||
Check.Eq(string.Join(", ", cast), "Cold Protection Self VI, Frost Bane VI", "only the ticked ones are cast");
|
||||
Check.True(done, "the loop ends with the unticked ones still off: the batch can finish");
|
||||
|
||||
// A fresh look, the ticked ones on and the unticked ones never cast: nothing is due.
|
||||
var idle = ProtBaneRig();
|
||||
idle.S.SetBuffEnabled("Fire Protection Self", false);
|
||||
idle.S.SetBuffEnabled("Flame Bane", false);
|
||||
idle.Live(("Cold Protection Self VI", 3000));
|
||||
idle.B.OnChatWindowText("You cast Frost Bane VI on Rune Robe", 7);
|
||||
Check.False(idle.B.NeedsAnyBuff(), "unticked and off doesn't hold Buffing");
|
||||
idle.S.SetBuffEnabled("Fire Protection Self", true);
|
||||
Check.True(idle.B.NeedsAnyBuff(), "ticked again: Fire Protection is due");
|
||||
Check.False(idle.S.IsBuffDisabled("Fire Protection Self"), "and leaves the list");
|
||||
|
||||
// Force Rebuff recasts everything, still not the unticked ones.
|
||||
var fr = ProtBaneRig();
|
||||
fr.S.SetBuffEnabled("Cold Protection Self", false);
|
||||
fr.S.SetBuffEnabled("Frost Bane", false);
|
||||
fr.Live(("Strength Self I", 3000));
|
||||
fr.B.ForceFullRebuff();
|
||||
cast = CastAll(fr, out done);
|
||||
Check.Eq(string.Join(", ", cast), "Fire Protection Self VI, Flame Bane VI", "Force Rebuff skips the unticked ones too");
|
||||
Check.True(done, "and finishes");
|
||||
Check.False(FakeHost.Casts.Any(c => NameOf(c.SpellId) is "Cold Protection Self VI" or "Frost Bane VI"), "never cast");
|
||||
}
|
||||
|
||||
private static void TogglesSetting()
|
||||
{
|
||||
var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true,\"RebuffSecondsRemaining\":300}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(old != null && old.DisabledBuffs.Count == 0, "a profile saved before the setting: all on");
|
||||
var nul = JsonSerializer.Deserialize("{\"DisabledBuffs\":null}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(nul != null && nul.DisabledBuffs.Count == 0, "a null list: all on");
|
||||
var some = new LegacyUiSettings();
|
||||
some.SetBuffEnabled("Acid Bane", false);
|
||||
some.SetBuffEnabled("Blade Protection Self", false);
|
||||
var back = JsonSerializer.Deserialize(JsonSerializer.Serialize(some, RynthAiJsonContext.Default.LegacyUiSettings),
|
||||
RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(back != null && back.IsBuffDisabled("Acid Bane") && back.IsBuffDisabled("Blade Protection Self") && back.DisabledBuffs.Count == 2,
|
||||
"unticked ones are saved and loaded");
|
||||
|
||||
// Profile switch/load copies it (CopySettings is the hand-written field list).
|
||||
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
var dst = new LegacyUiSettings();
|
||||
copy.Invoke(null, new object[] { some, dst });
|
||||
Check.True(dst.IsBuffDisabled("Acid Bane") && dst.DisabledBuffs.Count == 2, "a profile with unticked ones loads them");
|
||||
copy.Invoke(null, new object[] { old!, dst });
|
||||
Check.Eq(dst.DisabledBuffs.Count, 0, "an old profile loads all on");
|
||||
|
||||
// Engine Settings face: the payload carries the list; an engine without the field leaves it alone.
|
||||
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(payload != null && payload.DisabledBuffs == null, "an older engine's payload has no list");
|
||||
var s = new LegacyUiSettings();
|
||||
s.SetBuffEnabled("Frost Bane", false);
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)!
|
||||
.SetValue(dash, new LegacyAdvancedSettingsUi(s));
|
||||
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(sent?.DisabledBuffs != null && sent.DisabledBuffs.SequenceEqual(new[] { "Frost Bane" }), "sent to the engine face");
|
||||
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
|
||||
Check.True(s.IsBuffDisabled("Frost Bane"), "a save without the list leaves it alone");
|
||||
dash.ApplySettingsJson("{\"DisabledBuffs\":[]}");
|
||||
Check.Eq(s.DisabledBuffs.Count, 0, "a save with an empty list ticks everything");
|
||||
}
|
||||
|
||||
private static BuffRig ArmorRig()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
|
|
|
|||
|
|
@ -35,9 +35,7 @@ internal static class CombatMathTests
|
|||
r.Add("target range: closest first, then the one in front", ScanOrder);
|
||||
r.Add("target range: dead, unattackable, never-attack and spell projectiles are skipped", ScanFilters);
|
||||
|
||||
r.KnownFailure("damage text: a monster hitting our body part isn't our damage",
|
||||
"TryParseOutgoingDamage only rejects \"you for\"; a hit like 'Olthoi Swarm Harvester blisters your lower leg for 12 points of acid damage!' is counted as a hit by us while casting, which skews the Damage tab averages and the kill-shot prediction (not fixed on any branch)",
|
||||
BodyPartHitIsNotOurs);
|
||||
r.Add("damage text: a monster hitting our body part isn't our damage", BodyPartHitIsNotOurs); // was a known failure; fixed by feature/warchain-fix (the line must start with "You")
|
||||
r.Add("weapon choice: a weapon the character no longer has is skipped", WeaponMissingSkipped); // was a known failure; fixed by 996b2a5
|
||||
}
|
||||
|
||||
|
|
|
|||
55
Tools/RynthCore.RynthAiHostTests/Tests/CustomDebuffTests.cs
Normal file
55
Tools/RynthCore.RynthAiHostTests/Tests/CustomDebuffTests.cs
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
using System.Reflection;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-10-08: with Corruption V and VII known, the custom debuff "Corruption" cast V. A typed-in
|
||||
// debuff was capped by Creature and Life alone; Corruption is Void, so the search started at VI.
|
||||
internal static class CustomDebuffTests
|
||||
{
|
||||
private const uint Player = 0x50000180;
|
||||
private const uint STypeCreature = 31, STypeLife = 33, STypeVoid = 43;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("custom debuff: a base name casts the highest known level, capped by Void too (Corruption VII, not V)", VoidCap);
|
||||
}
|
||||
|
||||
private static void VoidCap()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
foreach (string n in new[] { "Corruption V", "Corruption VII" })
|
||||
foreach (var row in SpellTable.Named(n)) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, STypeCreature)] = (250, 2); // tier 5 by the thresholds below
|
||||
FakeHost.Skills[(Player, STypeLife)] = (250, 2);
|
||||
FakeHost.Skills[(Player, STypeVoid)] = (400, 3); // tier 7
|
||||
var s = new LegacyUiSettings
|
||||
{
|
||||
MinSkillLevelTier1 = 0, MinSkillLevelTier2 = 50, MinSkillLevelTier3 = 100, MinSkillLevelTier4 = 150,
|
||||
MinSkillLevelTier5 = 200, MinSkillLevelTier6 = 300, MinSkillLevelTier7 = 350, MinSkillLevelTier8 = 10000,
|
||||
};
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = FakeHost.MakeCache(host, Player, System.Array.Empty<uint>());
|
||||
var c = new CombatManager(host, s, cache);
|
||||
c.SetPlayerId(Player);
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
sm.RefreshKnownSpells();
|
||||
c.SetSpellManager(sm);
|
||||
|
||||
MethodInfo find = typeof(CombatManager).GetMethod("FindBestCustomDebuffWithTier", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
object[] args = { "Corruption", 0 };
|
||||
int id = (int)find.Invoke(c, args)!;
|
||||
Check.Eq(SpellTableStub.GetById(id)?.Name, "Corruption VII", "the highest known level");
|
||||
Check.Eq((int)args[1], 7, "tier 7");
|
||||
|
||||
object[] args5 = { "Corruption V", 0 };
|
||||
Check.Eq(SpellTableStub.GetById((int)find.Invoke(c, args5)!)?.Name, "Corruption V", "a full name still casts as is");
|
||||
}
|
||||
}
|
||||
|
|
@ -27,6 +27,7 @@ internal static class GiveTests
|
|||
r.Add("give: /ub give with a count hands over that many", UbGiveCount);
|
||||
r.Add("give: /mt give hands over only the first match", MtGivesFirst);
|
||||
r.Add("give: /ub givep matches part of the name", UbGivePartial);
|
||||
r.Add("give: the next give waits until the server took the last (it answers extra gives 'too busy')", WaitsForServer);
|
||||
}
|
||||
|
||||
private sealed class World
|
||||
|
|
@ -118,4 +119,20 @@ internal static class GiveTests
|
|||
Check.Eq(FakeHost.Gives.Count, 4, "partial: the three Mana Motes and the Lesser Mana Mote");
|
||||
Check.False(w.GivenItems.Contains(WornMote), "still not the worn one");
|
||||
}
|
||||
|
||||
// 2026-10-08: the queue sent a give every 150 ms; the server takes one at a time and the
|
||||
// rest came back "too busy", so /ub give handed over one item.
|
||||
private static void WaitsForServer()
|
||||
{
|
||||
var w = new World();
|
||||
FakeHost.GiveLands = false; // the server hasn't taken the first yet
|
||||
w.Run("/ub give Mana Mote to Town Crier");
|
||||
Check.Eq(FakeHost.Gives.Count, 1, "one give, then it waits for the server");
|
||||
|
||||
FakeHost.Containers[FakeHost.Gives[0].Item] = Npc; // the server took it
|
||||
FakeHost.GiveLands = true;
|
||||
for (int i = 0; i < 20; i++) w.Call("DrainGiveQueue");
|
||||
Check.Eq(FakeHost.Gives.Count, 3, "then the other two, each after the last landed");
|
||||
Check.Eq(FakeHost.Gives.Select(g => g.Item).Distinct().Count(), 3, "no item sent twice");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
161
Tools/RynthCore.RynthAiHostTests/Tests/HazardEscapeTests.cs
Normal file
161
Tools/RynthCore.RynthAiHostTests/Tests/HazardEscapeTests.cs
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-10-07, Drakkon: two deaths in an acid pool in an hour. The patrol left him in a pool the
|
||||
// hazard list didn't know, and topping up with healing kits held him there. Now the first
|
||||
// "You suffer N damage from acid!" stops everything and walks him back out along his footsteps.
|
||||
internal static class HazardEscapeTests
|
||||
{
|
||||
private const uint Player = 0x50000180;
|
||||
private const uint CellA = 0x63470160, CellB = 0x6347016C; // dungeon cells, one landblock
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("hazard: the hotspot damage line is read (amount, source); other lines are not", Parse);
|
||||
r.Add("hazard: a hit stops everything and walks back along the footsteps, then hands back", EscapeAlongFootsteps);
|
||||
r.Add("hazard: hurt again where it stopped - it goes further back", FurtherBack);
|
||||
r.Add("hazard: macro off - the cell is still learned, nothing moves", MacroOff);
|
||||
r.Add("hazard: Escape Acid and Lava off - no escape and nothing learned (some walk through acid)", SettingOff);
|
||||
}
|
||||
|
||||
private static void Parse()
|
||||
{
|
||||
Check.True(RynthAiPlugin.TryParseHotspotDamage("You suffer 32 damage from acid!", out int a, out string s) && a == 32 && s == "acid", "acid");
|
||||
Check.True(RynthAiPlugin.TryParseHotspotDamage("You suffer 11 damage from the lava.", out a, out s) && a == 11 && s == "lava", "lava, with 'the'");
|
||||
Check.False(RynthAiPlugin.TryParseHotspotDamage("You say, \"Malar Zhapaj\"", out _, out _), "speech");
|
||||
Check.False(RynthAiPlugin.TryParseHotspotDamage("Olthoi Swarm Worker bites you for 20 points of damage!", out _, out _), "a monster's hit");
|
||||
}
|
||||
|
||||
private sealed class Clock { public long Now = 1_000_000; }
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new() { IsMacroRunning = true };
|
||||
public readonly WorldObjectCache Cache;
|
||||
public readonly Clock C = new();
|
||||
|
||||
public Bot()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.StopCalls = true;
|
||||
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);
|
||||
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(P, dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
typeof(RynthAiPlugin).GetField("_objectCache", Any)!.SetValue(P, Cache);
|
||||
var clock = C;
|
||||
RynthAiPlugin.HazardClock = () => clock.Now;
|
||||
}
|
||||
|
||||
/// <summary>Stands at (x, y), lets time pass and records the footstep.</summary>
|
||||
public void At(uint cell, float x, float y, long ms = 300)
|
||||
{
|
||||
FakeHost.PlayerPose = (cell, x, y, -24f);
|
||||
C.Now += ms;
|
||||
P.RecordHazardTrail();
|
||||
}
|
||||
|
||||
public bool Hold() => P.HoldForHazardEscape();
|
||||
public void Hit() => P.NoteHotspotChat("You suffer 32 damage from acid!", 0);
|
||||
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
|
||||
}
|
||||
|
||||
private static (float X, float Y) Target(Bot b) => (b.Get<float>("_hazardTargetX"), b.Get<float>("_hazardTargetY"));
|
||||
|
||||
private static void EscapeAlongFootsteps()
|
||||
{
|
||||
var b = new Bot();
|
||||
// An L: north up x=60 from y=-185 to y=-175, then east to x=66 - into the acid.
|
||||
for (int i = 0; i <= 10; i++) b.At(CellA, 60f, -185f + i);
|
||||
for (int i = 1; i <= 6; i++) b.At(CellB, 60f + i, -175f);
|
||||
|
||||
b.Hit();
|
||||
Check.True(b.P.HazardEscaping, "the hit starts the escape");
|
||||
Check.True(b.Cache.IsHazardCell(CellB), "the cell it was hurt in is a hazard now");
|
||||
Check.True(b.Hold(), "the escape owns the tick (nothing else runs)");
|
||||
Check.True(FakeHost.AutoRun, "running");
|
||||
|
||||
var path = b.Get<System.Collections.Generic.List<(uint Cell, float X, float Y)>>("_hazardPath");
|
||||
Check.True(path.Count >= 3, $"a path of footsteps, not one straight line ({path.Count} points)");
|
||||
Check.True(path.Take(path.Count - 1).Any(p => p.Y == -175f && p.X > 60f), "it first walks back east-west along the way it came");
|
||||
var t = Target(b);
|
||||
Check.True(t.X == 60f && t.Y <= -175f, $"and ends back on the north-south leg, outside the hurt cell ({t.X}, {t.Y})");
|
||||
|
||||
// Walk the footsteps: each tick at the next one.
|
||||
foreach (var p in path)
|
||||
{
|
||||
FakeHost.PlayerPose = (p.Cell, p.X, p.Y, -24f);
|
||||
b.C.Now += 300;
|
||||
Check.True(b.Hold(), "still holding while it walks out");
|
||||
}
|
||||
Check.False(FakeHost.AutoRun, "stopped at the target");
|
||||
b.C.Now += RynthAiPlugin.HazardQuietMs;
|
||||
Check.False(b.Hold(), "no hit for a while at the target: the tick is handed back");
|
||||
Check.False(b.P.HazardEscaping, "escape over");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Hazard: out of it")), "and it says so");
|
||||
}
|
||||
|
||||
private static void FurtherBack()
|
||||
{
|
||||
var b = new Bot();
|
||||
for (int i = 0; i <= 12; i++) b.At(CellA, 60f, -190f + i);
|
||||
b.Hit();
|
||||
var first = Target(b);
|
||||
FakeHost.PlayerPose = (CellA, first.X, first.Y, -24f);
|
||||
b.C.Now += 300;
|
||||
foreach (var _ in Enumerable.Range(0, 20)) { b.Hold(); FakeHost.PlayerPose = (CellA, first.X, first.Y, -24f); }
|
||||
Check.False(FakeHost.AutoRun, "arrived at the first spot");
|
||||
|
||||
b.C.Now += 2500;
|
||||
b.Hit(); // the pool reaches further back
|
||||
var second = Target(b);
|
||||
Check.True(second.Y < first.Y - 1f, $"it goes further back ({first.Y} -> {second.Y})");
|
||||
Check.True(b.Hold(), "and keeps the tick");
|
||||
Check.True(FakeHost.AutoRun, "running again");
|
||||
}
|
||||
|
||||
private static void MacroOff()
|
||||
{
|
||||
var b = new Bot();
|
||||
b.S.IsMacroRunning = false;
|
||||
for (int i = 0; i <= 6; i++) b.At(CellA, 60f, -185f + i);
|
||||
b.Hit();
|
||||
Check.True(b.Cache.IsHazardCell(CellA), "the cell is learned");
|
||||
Check.False(b.P.HazardEscaping, "but nothing moves the character while you play it");
|
||||
Check.False(b.Hold(), "and the tick is not held");
|
||||
}
|
||||
|
||||
private static void SettingOff()
|
||||
{
|
||||
var b = new Bot();
|
||||
b.S.EscapeHazards = false;
|
||||
for (int i = 0; i <= 6; i++) b.At(CellA, 60f, -185f + i);
|
||||
b.Hit();
|
||||
Check.False(b.P.HazardEscaping, "no escape");
|
||||
Check.False(b.Cache.IsHazardCell(CellA), "and the cell is not learned (the patrol keeps its way through)");
|
||||
Check.False(b.Hold(), "the tick is not held");
|
||||
|
||||
// Turned off mid-escape: it lets go at once.
|
||||
b.S.EscapeHazards = true;
|
||||
b.Hit();
|
||||
Check.True(b.P.HazardEscaping, "on again: the next hit escapes");
|
||||
b.S.EscapeHazards = false;
|
||||
Check.False(b.Hold(), "turned off mid-escape: the tick is handed back");
|
||||
Check.False(b.P.HazardEscaping, "escape over");
|
||||
Check.False(new LegacyUiSettings().EscapeHazards == false, "on by default");
|
||||
}
|
||||
}
|
||||
144
Tools/RynthCore.RynthAiHostTests/Tests/InstallPathsTests.cs
Normal file
144
Tools/RynthCore.RynthAiHostTests/Tests/InstallPathsTests.cs
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Install;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// RynthInstallPaths (Plugins/Shared/RynthInstallPaths.cs, compiled into RynthAi): where RynthSuite
|
||||
// lives. Order is environment, HKCU, HKLM, then C:\Games\RynthSuite. The environment and the
|
||||
// registry are a fake here; the real registry is only READ, for a value that does not exist.
|
||||
// Idea from Silentkelpie (rynth PR #1); re-implemented here.
|
||||
internal static class InstallPathsTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("install paths: nothing set gives C:\\Games\\RynthSuite and C:\\Games\\RynthCore", NothingSet);
|
||||
r.Add("install paths: environment beats HKCU beats HKLM beats the default", Order);
|
||||
r.Add("install paths: empty, relative and broken values are skipped", Unusable);
|
||||
r.Add("install paths: folders with spaces", Spaces);
|
||||
r.Add("install paths: a source that throws falls through to the default", Throwing);
|
||||
r.Add("install paths: real registry, missing value reads as null (read only)", RealRegistryRead);
|
||||
r.Add("install paths: on a default install RynthAi's folders are exactly the old ones", DefaultInstallUnchanged);
|
||||
r.Add("install paths: same file as RynthCore src\\Shared (when the sibling is checked out)", SameAsRynthCore);
|
||||
}
|
||||
|
||||
private sealed class Fake : IInstallSettingSource
|
||||
{
|
||||
public readonly Dictionary<string, string?> Env = new();
|
||||
public readonly Dictionary<string, string?> User = new();
|
||||
public readonly Dictionary<string, string?> Machine = new();
|
||||
public int Asked;
|
||||
public bool Throw;
|
||||
|
||||
public string? EnvironmentVariable(string name) { Asked++; if (Throw) throw new InvalidOperationException(); return Env.GetValueOrDefault(name); }
|
||||
public string? CurrentUser(string valueName) { Asked++; if (Throw) throw new UnauthorizedAccessException(); return User.GetValueOrDefault(valueName); }
|
||||
public string? LocalMachine(string valueName) { Asked++; if (Throw) throw new IOException(); return Machine.GetValueOrDefault(valueName); }
|
||||
}
|
||||
|
||||
private static string Suite(Fake f) => RynthInstallPaths.Resolve(RynthInstallPaths.SuiteEnvironmentVariable,
|
||||
RynthInstallPaths.SuiteValueName, RynthInstallPaths.DefaultSuiteDir, f);
|
||||
|
||||
private static string Core(Fake f) => RynthInstallPaths.Resolve(RynthInstallPaths.CoreEnvironmentVariable,
|
||||
RynthInstallPaths.CoreValueName, RynthInstallPaths.DefaultCoreDir, f);
|
||||
|
||||
private static void NothingSet()
|
||||
{
|
||||
var f = new Fake();
|
||||
Check.Eq(Suite(f), @"C:\Games\RynthSuite", "suite default");
|
||||
Check.Eq(Core(f), @"C:\Games\RynthCore", "core default");
|
||||
Check.Eq(f.Asked, 6, "env, HKCU and HKLM asked for each folder");
|
||||
}
|
||||
|
||||
private static void Order()
|
||||
{
|
||||
var f = new Fake();
|
||||
f.Machine["SuiteDir"] = @"D:\Machine\RynthSuite";
|
||||
Check.Eq(Suite(f), @"D:\Machine\RynthSuite", "HKLM beats the default");
|
||||
f.User["SuiteDir"] = @"E:\User\RynthSuite";
|
||||
Check.Eq(Suite(f), @"E:\User\RynthSuite", "HKCU beats HKLM");
|
||||
f.Env["RYNTHSUITE_DIR"] = @"F:\Dev\RynthSuite";
|
||||
Check.Eq(Suite(f), @"F:\Dev\RynthSuite", "environment beats HKCU");
|
||||
Check.Eq(Core(f), @"C:\Games\RynthCore", "suite settings leave the core folder alone");
|
||||
}
|
||||
|
||||
private static void Unusable()
|
||||
{
|
||||
foreach (string? bad in new[] { null, "", " ", "RynthSuite", @"..\RynthSuite", "C:", "D:\\a|b", "D:\\a*", "D:\\x:y" })
|
||||
{
|
||||
var f = new Fake();
|
||||
f.Env["RYNTHSUITE_DIR"] = bad;
|
||||
f.User["SuiteDir"] = bad;
|
||||
f.Machine["SuiteDir"] = bad;
|
||||
Check.Eq(Suite(f), @"C:\Games\RynthSuite", $"'{bad}' everywhere -> default");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Spaces()
|
||||
{
|
||||
var f = new Fake();
|
||||
f.User["SuiteDir"] = @"C:\Program Files (x86)\Rynth Suite\";
|
||||
Check.Eq(Suite(f), @"C:\Program Files (x86)\Rynth Suite", "HKCU value with spaces, trailing separator dropped");
|
||||
Check.Eq(Path.Combine(Suite(f), "RynthAi", "LootProfiles"), @"C:\Program Files (x86)\Rynth Suite\RynthAi\LootProfiles", "joined");
|
||||
var g = new Fake();
|
||||
g.Env["RYNTHSUITE_DIR"] = " \"D:\\My Games\\Rynth Suite\" ";
|
||||
Check.Eq(Suite(g), @"D:\My Games\Rynth Suite", "quoted, padded environment value with spaces");
|
||||
}
|
||||
|
||||
private static void Throwing()
|
||||
{
|
||||
var f = new Fake { Throw = true };
|
||||
Check.Eq(Suite(f), @"C:\Games\RynthSuite", "every source throws -> default");
|
||||
Check.Eq(f.Asked, 3, "all three tried");
|
||||
}
|
||||
|
||||
private static void RealRegistryRead()
|
||||
{
|
||||
string missing = "NoSuchValue-" + Guid.NewGuid().ToString("N");
|
||||
Check.Null(SystemInstallSettings.Instance.CurrentUser(missing), "HKCU missing value");
|
||||
Check.Null(SystemInstallSettings.Instance.LocalMachine(missing), "HKLM missing value");
|
||||
Check.True(Path.IsPathFullyQualified(RynthInstallPaths.SuiteDir), "live SuiteDir is absolute: " + RynthInstallPaths.SuiteDir);
|
||||
}
|
||||
|
||||
private static void DefaultInstallUnchanged()
|
||||
{
|
||||
if (RynthInstallPaths.SuiteDir != RynthInstallPaths.DefaultSuiteDir)
|
||||
{
|
||||
Console.WriteLine($" (this machine sets the RynthSuite folder to {RynthInstallPaths.SuiteDir}; default-install check skipped)");
|
||||
return;
|
||||
}
|
||||
Check.Eq(RynthInstallPaths.RynthAiDir, @"C:\Games\RynthSuite\RynthAi", "RynthAi folder");
|
||||
Check.Eq(RynthCore.Plugin.RynthAi.Loot.LootEditorBridge.LootFolder, @"C:\Games\RynthSuite\RynthAi\LootProfiles", "loot profiles");
|
||||
Check.Eq(RynthCore.Plugin.RynthAi.Vendor.AutoVendorManager.MainProfileDir, @"C:\Games\RynthSuite\RynthAi\AutoVendor", "AutoVendor");
|
||||
Check.Eq(RynthCore.Plugin.RynthAi.Trade.AutoTradeManager.MainProfileDir, @"C:\Games\RynthSuite\RynthAi\AutoTrade", "AutoTrade");
|
||||
Check.Eq(RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder, @"C:\Games\RynthSuite\RynthAi\CreatureData", "creature data");
|
||||
Check.Eq(RynthCore.Plugin.RynthAi.CreatureData.CreatureWeakness.WeaknessFile, @"C:\Games\RynthSuite\RynthAi\Data\creature_weakness.json", "weakness file");
|
||||
Check.Eq(PrivateStatic(typeof(RynthCore.Plugin.RynthAi.RadarWallRenderer), "ExploredDir"), @"C:\Games\RynthSuite\RynthAi\ExploredDungeons", "explored dungeons");
|
||||
// The tests point the store at their scratch folder (Program.Main); this is its value before that.
|
||||
Check.Eq(Program.LiveHazardFolder, @"C:\Games\RynthSuite\RynthAi\DungeonHazards", "dungeon hazards");
|
||||
}
|
||||
|
||||
private static string? PrivateStatic(Type type, string field)
|
||||
=> type.GetField(field, BindingFlags.NonPublic | BindingFlags.Static)?.GetValue(null) as string;
|
||||
|
||||
private static void SameAsRynthCore()
|
||||
{
|
||||
string here = Path.GetFullPath(Path.Combine(ThisFile(), "..", "..", "..", "..", "Plugins", "Shared", "RynthInstallPaths.cs"));
|
||||
string sibling = Path.GetFullPath(Path.Combine(ThisFile(), "..", "..", "..", "..", "..", "RynthCore", "src", "Shared", "RynthInstallPaths.cs"));
|
||||
Check.True(File.Exists(here), "RynthSuite copy found at " + here);
|
||||
if (!File.Exists(sibling))
|
||||
{
|
||||
Console.WriteLine($" (no RynthCore sibling at {sibling}; comparison skipped)");
|
||||
return;
|
||||
}
|
||||
Check.True(Text(here) == Text(sibling),
|
||||
"Plugins\\Shared\\RynthInstallPaths.cs matches RynthCore src\\Shared\\RynthInstallPaths.cs");
|
||||
}
|
||||
|
||||
private static string Text(string path) => File.ReadAllText(path).Replace("\r\n", "\n");
|
||||
|
||||
private static string ThisFile([CallerFilePath] string path = "") => path;
|
||||
}
|
||||
349
Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTests.cs
Normal file
349
Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTests.cs
Normal file
|
|
@ -0,0 +1,349 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// /ra iteminfo (Silentkelpie's rynth PR #1 idea, re-implemented): a Mag-Tools style one-line
|
||||
// description of the selected or named item, identified first when the client hasn't
|
||||
// appraised it. The formatter is checked on fake appraisal data; the command end to end on
|
||||
// FakeHost (selection, ID request, the print when the ID lands, the timeout, name lookup).
|
||||
internal static class ItemInfoTests
|
||||
{
|
||||
private const uint Player = 0x50000F21;
|
||||
private const uint Sword = 0x80300001, Ring = 0x80300002, Scarab = 0x80300003, Scarab2 = 0x80300004;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("iteminfo: a weapon's damage, mods, imbue, slayer, spells and wield line", WeaponLine);
|
||||
r.Add("iteminfo: armor's set, AL, ratings, tinks and wield level", ArmorLine);
|
||||
r.Add("iteminfo: jewelry with mana, diff and craft; a bare item stays short", JewelryAndBareItem);
|
||||
r.Add("iteminfo: a selected item already appraised prints at once, no ID", SelectedAppraised);
|
||||
r.Add("iteminfo: an unappraised item is identified, then printed when the ID lands", IdentifiesThenPrints);
|
||||
r.Add("iteminfo: no reply prints what the client has after the timeout", TimeoutPrints);
|
||||
r.Add("iteminfo: a name picks the inventory item, exact before partial", NameLookup);
|
||||
r.Add("iteminfo: nothing selected or no such item says so", NothingSelected);
|
||||
r.Add("iteminfo on select: the player's pick prints quietly; the bot's own picks and the setting off do not", OnSelect);
|
||||
}
|
||||
|
||||
// ── Fake appraisal data ─────────────────────────────────────────────
|
||||
|
||||
private sealed class Fake : IItemInfoSource
|
||||
{
|
||||
public string Name { get; init; } = "";
|
||||
public Dictionary<uint, int> Ints { get; } = new();
|
||||
public Dictionary<uint, double> Floats { get; } = new();
|
||||
public List<int> Spells { get; } = new();
|
||||
public IReadOnlyList<int> SpellIds => Spells;
|
||||
public bool TryInt(uint key, out int value) => Ints.TryGetValue(key, out value);
|
||||
public bool TryFloat(uint key, out double value) => Floats.TryGetValue(key, out value);
|
||||
}
|
||||
|
||||
private static string Spell(int id) => SpellDatabase.GetSpellName(id);
|
||||
|
||||
/// <summary>Each part appears, in this order.</summary>
|
||||
private static void InOrder(string text, string[] parts, string what)
|
||||
{
|
||||
int at = 0;
|
||||
foreach (string p in parts)
|
||||
{
|
||||
int i = text.IndexOf(p, at, StringComparison.Ordinal);
|
||||
Check.True(i >= 0, $"{what}: has \"{p}\" after position {at} in: {text}");
|
||||
if (i >= 0) at = i + p.Length;
|
||||
}
|
||||
}
|
||||
|
||||
private static void WeaponLine()
|
||||
{
|
||||
var w = new Fake { Name = "Ornate Katar" };
|
||||
w.Ints[ItemInfoText.IntItemType] = 0x1;
|
||||
w.Ints[ItemInfoText.IntMaterial] = 61; // Iron
|
||||
w.Ints[ItemInfoText.IntWeaponSkill] = 44; // Heavy Weapons
|
||||
w.Ints[ItemInfoText.IntDamage] = 77;
|
||||
w.Floats[ItemInfoText.FloatDamageVariance] = 0.4;
|
||||
w.Ints[ItemInfoText.IntDamageType] = 16; // Fire
|
||||
w.Ints[ItemInfoText.IntWeaponTime] = 30;
|
||||
w.Floats[ItemInfoText.FloatWeaponOffense] = 1.18;
|
||||
w.Floats[ItemInfoText.FloatMeleeDefense] = 1.20;
|
||||
w.Floats[ItemInfoText.FloatMagicDefense] = 1.0; // +0%: left out
|
||||
w.Ints[ItemInfoText.IntImbued] = 0x2 | 0x200; // Crippling Blow, Fire Rending
|
||||
w.Ints[ItemInfoText.IntSlayerType] = 14; // Undead
|
||||
w.Ints[ItemInfoText.IntTinks] = 2;
|
||||
w.Spells.AddRange(new[] { 2531, 6107, 2531 }); // a repeat is named once
|
||||
w.Ints[ItemInfoText.IntWieldReq] = 1;
|
||||
w.Ints[ItemInfoText.IntWieldSkill] = 44;
|
||||
w.Ints[ItemInfoText.IntWieldDiff] = 375;
|
||||
w.Ints[ItemInfoText.IntWieldReq2] = 7;
|
||||
w.Ints[ItemInfoText.IntWieldDiff2] = 150;
|
||||
w.Ints[ItemInfoText.IntItemDifficulty] = 300;
|
||||
w.Ints[ItemInfoText.IntWorkmanship] = 9;
|
||||
w.Ints[ItemInfoText.IntValue] = 12345;
|
||||
w.Ints[ItemInfoText.IntEncumbrance] = 350;
|
||||
w.Ints[ItemInfoText.Ratings[0].Key] = 2; // D2
|
||||
|
||||
string s = ItemInfoText.Describe(w, Spell);
|
||||
InOrder(s, new[]
|
||||
{
|
||||
"Iron Ornate Katar (Melee Weapon)", "[D2]", "Heavy Weapons", "Dmg 46-77 Fire", "Speed 30",
|
||||
"(+18% atk, +20% md)", "Crippling Blow, Fire Rending", "Undead Slayer", "Tinks 2",
|
||||
"Spells: Major Heavy Weapon Aptitude, Legendary Strength", "Heavy Weapons 375 to wield",
|
||||
"Wield Lvl 150", "Diff 300", "Craft 9", "Mat Iron", "Value 12,345", "BU 350",
|
||||
}, "weapon");
|
||||
Check.False(s.Contains("mgd"), "a +0% mod is left out");
|
||||
Check.Eq(s.Split("Major Heavy Weapon Aptitude").Length, 2, "each spell named once");
|
||||
Check.False(s.Contains("not identified"), "identified: no note");
|
||||
}
|
||||
|
||||
private static void ArmorLine()
|
||||
{
|
||||
var a = new Fake { Name = "Chainmail Tassets" };
|
||||
a.Ints[ItemInfoText.IntItemType] = 0x2;
|
||||
a.Ints[ItemInfoText.IntSetId] = 16; // Defender's
|
||||
a.Ints[ItemInfoText.IntArmorLevel] = 584;
|
||||
a.Ints[371] = 1; // DR1
|
||||
a.Ints[375] = 2; // CDR2
|
||||
a.Ints[ItemInfoText.IntTinks] = 3;
|
||||
a.Ints[ItemInfoText.IntWieldReq] = 7;
|
||||
a.Ints[ItemInfoText.IntWieldDiff] = 180;
|
||||
a.Ints[ItemInfoText.IntMaterial] = 64; // Steel
|
||||
string s = ItemInfoText.Describe(a, Spell);
|
||||
InOrder(s, new[] { "Steel Chainmail Tassets (Armor)", "Defender's Set", "AL 584", "[DR1 CDR2]", "Tinks 3", "Wield Lvl 180", "Mat Steel" }, "armor");
|
||||
Check.False(s.Contains("Dmg"), "armor shows no damage");
|
||||
Check.False(s.Contains("Speed"), "or speed");
|
||||
}
|
||||
|
||||
private static void JewelryAndBareItem()
|
||||
{
|
||||
var j = new Fake { Name = "Gold Ring" };
|
||||
j.Ints[ItemInfoText.IntItemType] = 0x8;
|
||||
j.Ints[ItemInfoText.IntMaterial] = 60; // Gold: already in the name
|
||||
j.Ints[ItemInfoText.IntCurMana] = 1200;
|
||||
j.Ints[ItemInfoText.IntMaxMana] = 1500;
|
||||
j.Ints[ItemInfoText.IntItemDifficulty] = 285;
|
||||
j.Ints[ItemInfoText.IntWorkmanship] = 7;
|
||||
j.Ints[ItemInfoText.IntAttuned] = 1;
|
||||
j.Spells.Add(3964);
|
||||
string s = ItemInfoText.Describe(j, Spell);
|
||||
InOrder(s, new[] { "Gold Ring (Jewelry)", "Spells: Epic Focus", "Diff 285", "Mana 1200/1500", "Craft 7", "Mat Gold", "Attuned" }, "jewelry");
|
||||
Check.False(s.Contains("Gold Gold"), "the material isn't doubled");
|
||||
Check.False(s.Contains("AL "), "jewelry with no armor shows no AL");
|
||||
|
||||
var bare = new Fake { Name = "Mana Scarab" };
|
||||
bare.Ints[ItemInfoText.IntStackSize] = 25;
|
||||
string b = ItemInfoText.Describe(bare, Spell, identified: false);
|
||||
Check.True(b.StartsWith("Mana Scarab x25", StringComparison.Ordinal), $"a stack shows its size: {b}");
|
||||
Check.True(b.EndsWith("(not identified: no reply from the server)", StringComparison.Ordinal), "unidentified note last");
|
||||
Check.Eq(b.Split(", ").Length, 2, "nothing else is made up");
|
||||
}
|
||||
|
||||
// ── The command on FakeHost ─────────────────────────────────────────
|
||||
|
||||
private sealed class World
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly WorldObjectCache Cache;
|
||||
public long Now = 1_000_000;
|
||||
|
||||
public World()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.Names[Player] = "Reader";
|
||||
FakeHost.PlayerIdValue = Player;
|
||||
FakeHost.Positions[Player] = (0x1048002Au, 100f, 100f, 0f);
|
||||
FakeHost.PlayerPose = (0x1048002Au, 100f, 100f, 0f);
|
||||
Item(Sword, "Ornate Katar", 0x1);
|
||||
Item(Ring, "Gold Ring", 0x8);
|
||||
Item(Scarab, "Mana Scarab", 0x80);
|
||||
Item(Scarab2, "Platinum Scarab", 0x80);
|
||||
FakeHost.Ints[(Sword, ItemInfoText.IntDamage)] = 77;
|
||||
FakeHost.Ints[(Sword, ItemInfoText.IntWorkmanship)] = 9;
|
||||
FakeHost.Ints[(Ring, ItemInfoText.IntWorkmanship)] = 7;
|
||||
FakeHost.SpellIds[Ring] = new uint[] { 3964 };
|
||||
FakeHost.WeaponCalls = true; // RequestId + HasAppraisalData
|
||||
var host = FakeHost.Create(playerId: Player);
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, new LegacyUiSettings());
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_initialized", true);
|
||||
Set("_loginComplete", true);
|
||||
foreach (uint id in new[] { Sword, Ring, Scarab, Scarab2 }) Cache.OnCreateObject(id);
|
||||
Cache.Tick();
|
||||
RynthAiPlugin.ItemInfoClock = () => Now;
|
||||
}
|
||||
|
||||
private static void Item(uint id, string name, uint type)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Containers[id] = Player;
|
||||
FakeHost.ItemTypes[id] = type;
|
||||
FakeHost.Ints[(id, ItemInfoText.IntItemType)] = (int)type;
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
|
||||
public void Command(string text)
|
||||
{
|
||||
string[] parts = text.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
typeof(RynthAiPlugin).GetMethod("HandleItemInfoCommand", Any)!.Invoke(P, new object[] { parts });
|
||||
}
|
||||
|
||||
public void Tick() => typeof(RynthAiPlugin).GetMethod("TickItemInfo", Any)!.Invoke(P, null);
|
||||
|
||||
public string[] InfoLines => FakeHost.Chat.Where(c => c.StartsWith("[RynthAi] ", StringComparison.Ordinal)).ToArray();
|
||||
}
|
||||
|
||||
private static void Done() => RynthAiPlugin.ItemInfoClock = () => Environment.TickCount64;
|
||||
|
||||
private static void OnSelect()
|
||||
{
|
||||
var w = new World();
|
||||
try
|
||||
{
|
||||
void Select(uint id) => typeof(RynthAiPlugin).GetMethod("QueueItemInfoOnSelect", Any)!
|
||||
.Invoke(w.P, new object?[] { id, w.Cache[unchecked((int)id)] });
|
||||
|
||||
FakeHost.Appraised.Add(Ring);
|
||||
Select(Ring);
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 1, "the player's pick prints once");
|
||||
Check.True(w.InfoLines[0].Contains("Gold Ring (Jewelry)"), $"the ring's line: {w.InfoLines.FirstOrDefault()}");
|
||||
|
||||
Select(Sword);
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 1, "unappraised: no 'identifying' chatter on select");
|
||||
Check.True(FakeHost.IdRequests.Contains(Sword), "but the ID is asked for");
|
||||
FakeHost.Appraised.Add(Sword);
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 2, "printed when the appraisal lands");
|
||||
|
||||
SelfSelect.Mark(Ring);
|
||||
Select(Ring);
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 2, "an item RynthAi selected itself (the looter, a meta) prints nothing");
|
||||
|
||||
var dash = (LegacyDashboardRenderer)typeof(RynthAiPlugin).GetField("_dashboard", Any)!.GetValue(w.P)!;
|
||||
dash.Settings.ItemInfoOnSelect = false;
|
||||
Select(Scarab);
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 2, "setting off: nothing");
|
||||
}
|
||||
finally { Done(); }
|
||||
}
|
||||
|
||||
private static void SelectedAppraised()
|
||||
{
|
||||
var w = new World();
|
||||
try
|
||||
{
|
||||
FakeHost.SelectedItem = Ring;
|
||||
FakeHost.Appraised.Add(Ring);
|
||||
w.Command("/ra iteminfo");
|
||||
Check.Eq(FakeHost.Chat.Count, 0, "the command only queues (the tick prints)");
|
||||
w.Tick();
|
||||
Check.Eq(FakeHost.IdRequests.Count, 0, "appraised: no ID request");
|
||||
Check.Eq(w.InfoLines.Length, 1, "one line");
|
||||
Check.True(w.InfoLines[0].Contains("Gold Ring (Jewelry)") && w.InfoLines[0].Contains("Spells: Epic Focus") && w.InfoLines[0].Contains("Craft 7"),
|
||||
$"the ring's line: {w.InfoLines.FirstOrDefault()}");
|
||||
}
|
||||
finally { Done(); }
|
||||
}
|
||||
|
||||
private static void IdentifiesThenPrints()
|
||||
{
|
||||
var w = new World();
|
||||
try
|
||||
{
|
||||
FakeHost.SelectedItem = Sword;
|
||||
w.Command("/ra iteminfo");
|
||||
w.Tick();
|
||||
Check.True(FakeHost.IdRequests.SequenceEqual(new[] { Sword }), "one ID request for the sword");
|
||||
Check.Eq(w.InfoLines.Length, 1, "just the 'identifying' line so far");
|
||||
Check.True(w.InfoLines[0].Contains("identifying Ornate Katar"), "says it is identifying");
|
||||
w.Now += 1000;
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 1, "still waiting a second later");
|
||||
FakeHost.Appraised.Add(Sword);
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 2, "printed when the appraisal arrives");
|
||||
Check.True(w.InfoLines[1].Contains("Ornate Katar (Melee Weapon)") && w.InfoLines[1].Contains("Dmg 77") && !w.InfoLines[1].Contains("not identified"),
|
||||
$"the sword's line: {w.InfoLines[1]}");
|
||||
w.Now += 10_000;
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 2, "printed once");
|
||||
Check.Eq(FakeHost.IdRequests.Count, 1, "never asked twice");
|
||||
}
|
||||
finally { Done(); }
|
||||
}
|
||||
|
||||
private static void TimeoutPrints()
|
||||
{
|
||||
var w = new World();
|
||||
try
|
||||
{
|
||||
FakeHost.SelectedItem = Sword;
|
||||
w.Command("/ra iteminfo");
|
||||
w.Tick();
|
||||
w.Now += RynthAiPlugin.ItemInfoTimeoutMs - 1;
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 1, "not before the timeout");
|
||||
w.Now += 1;
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 2, "printed at the timeout");
|
||||
Check.True(w.InfoLines[1].Contains("Ornate Katar") && w.InfoLines[1].EndsWith("(not identified: no reply from the server)", StringComparison.Ordinal),
|
||||
$"with what the client has and the note: {w.InfoLines[1]}");
|
||||
}
|
||||
finally { Done(); }
|
||||
}
|
||||
|
||||
private static void NameLookup()
|
||||
{
|
||||
var w = new World();
|
||||
try
|
||||
{
|
||||
FakeHost.Appraised.Add(Scarab);
|
||||
FakeHost.Appraised.Add(Scarab2);
|
||||
FakeHost.Appraised.Add(Ring);
|
||||
w.Command("/ra iteminfo mana scarab");
|
||||
w.Tick();
|
||||
Check.True(w.InfoLines.Last().StartsWith("[RynthAi] Mana Scarab", StringComparison.Ordinal), $"exact name, any case: {w.InfoLines.Last()}");
|
||||
w.Command("/ra iteminfo Scarab");
|
||||
w.Tick();
|
||||
Check.True(w.InfoLines.Last().Contains("Scarab") && !w.InfoLines.Last().Contains("not in your"), "a partial name finds a scarab");
|
||||
w.Command("/ra iteminfo ring");
|
||||
w.Tick();
|
||||
Check.True(w.InfoLines.Last().StartsWith("[RynthAi] Gold Ring", StringComparison.Ordinal), "partial: Gold Ring");
|
||||
Check.Eq(FakeHost.SelectedItem, 0u, "a named lookup doesn't need a selection");
|
||||
}
|
||||
finally { Done(); }
|
||||
}
|
||||
|
||||
private static void NothingSelected()
|
||||
{
|
||||
var w = new World();
|
||||
try
|
||||
{
|
||||
w.Command("/ra iteminfo");
|
||||
w.Tick();
|
||||
Check.True(w.InfoLines.Length == 1 && w.InfoLines[0].Contains("nothing selected"), "nothing selected says so");
|
||||
w.Command("/ra iteminfo Shield of Nowhere");
|
||||
w.Tick();
|
||||
Check.True(w.InfoLines.Last().Contains("no \"Shield of Nowhere\" in your inventory"), $"unknown name says so: {w.InfoLines.Last()}");
|
||||
Check.Eq(FakeHost.IdRequests.Count, 0, "and nothing is identified");
|
||||
}
|
||||
finally { Done(); }
|
||||
}
|
||||
}
|
||||
|
|
@ -42,7 +42,7 @@ internal static class LootAddItemTests
|
|||
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);
|
||||
r.Add("loot add: the popup says when RynthAi's built-in looting takes the item (Mana Tap, mana stones)", BuiltInReasons);
|
||||
r.Add("loot: Mana Tap never loots a wand (ACE won't drain one, so it was kept for good)", ManaTapSkipsWands);
|
||||
r.Add("loot: Mana Tap takes a high-mana wand like any other item (they drain)", ManaTapTakesWands);
|
||||
}
|
||||
|
||||
// ── World and plugin ──────────────────────────────────────────────────────
|
||||
|
|
@ -445,16 +445,13 @@ internal static class LootAddItemTests
|
|||
Check.Eq(File.ReadAllText(path), SellGems, "preview saves nothing");
|
||||
}
|
||||
|
||||
private static void ManaTapSkipsWands()
|
||||
private static void ManaTapTakesWands()
|
||||
{
|
||||
var bot = TapWorld();
|
||||
bot.S.CurrentLootPath = Temp("wand.utl", SellGems);
|
||||
var wand = LootEval(bot, Sceptre);
|
||||
Check.False(wand.Taken, $"a 3,001-mana sceptre is left: [{wand.Action}] {wand.Rule}");
|
||||
Check.Eq(bot.Get<System.Collections.Generic.HashSet<int>>("_pendingManaTapIds")?.Count, 0, "not counted against the tap quota");
|
||||
Check.True(wand.Taken && wand.Action == "ManaTap", $"a 3,001-mana sceptre is tapped: [{wand.Action}] {wand.Rule}");
|
||||
var ring = LootEval(bot, Ring);
|
||||
Check.True(ring.Taken && ring.Action == "ManaTap", "a ring with the same mana is still tapped: " + ring.Action);
|
||||
Send(bot.P.LootEditor, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Sceptre, Seq = 1 } });
|
||||
Check.Eq(State(bot.P.LootEditor).ItemDraft?.BuiltInReason, "", "the popup has no built-in reason for the wand");
|
||||
Check.False(ring.Taken, "the one empty stone is now spoken for by the wand, so the ring waits: " + ring.Action);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -50,6 +50,8 @@ internal static class LootCorpseTests
|
|||
r.Add("corpse close: an engine without CloseContainer leaves it to the next open (no close)", FinishedCorpseNotClosedOnOldEngine);
|
||||
r.Add("corpse close: an abandoned open corpse is closed once", AbandonedCorpseClosed);
|
||||
r.Add("corpse close: stopping the macro mid-loot closes the open corpse, not marked completed", MacroStopClosesCorpse);
|
||||
r.Add("loot pacing: a pickup waits for the last bend-down, and no retry is timed while it plays", PickupWaitsForAnimation);
|
||||
r.Add("corpse close: not while the last item is between the corpse and the pack - it closes once the item is in the inventory", CloseWaitsForInventory);
|
||||
}
|
||||
|
||||
// ── World set-up ──────────────────────────────────────────────────────────
|
||||
|
|
@ -440,4 +442,78 @@ internal static class LootCorpseTests
|
|||
bot.Call("CloseOpenCorpseOnMacroStop");
|
||||
Check.Eq(FakeHost.Closes.Count, 1, "a stop with no corpse open closes nothing");
|
||||
}
|
||||
|
||||
// 2026-10-07, Drakkon: picking up an item plays a bend-down, and the engine holds queued
|
||||
// moves until it ends (about 2.2 s). RynthAi retried every 0.5 s from the send and gave up
|
||||
// after 3 tries, so items were skipped while their first move had not even gone out.
|
||||
private static void PickupWaitsForAnimation()
|
||||
{
|
||||
BaseWorld(corpsePositioned: true);
|
||||
FakeHost.ServerGates = true; // GetCastBusyState
|
||||
var host = FakeHost.Create(Player);
|
||||
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");
|
||||
|
||||
// The last pickup is still animating when the corpse's contents arrive.
|
||||
FakeHost.CastBusy = 1;
|
||||
bot.Cache.OnCreateObject(Gem);
|
||||
bot.Cache.Tick();
|
||||
bot.P.OnViewObjectContents(Corpse);
|
||||
TickFor(bot, 500);
|
||||
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "no pickup sent while the character animates");
|
||||
|
||||
FakeHost.CastBusy = 0;
|
||||
for (int i = 0; i < 100 && !FakeHost.ExternalMoves.Any(m => m.Id == Gem); i++)
|
||||
{
|
||||
bot.Tick(BotActivity.Looting);
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "the pickup goes out once the character is still");
|
||||
|
||||
// Its own bend-down plays for longer than 3 retry windows: no retry, no give-up.
|
||||
FakeHost.CastBusy = 1;
|
||||
TickFor(bot, 1800);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "no retry while the pickup animates");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("pickup failed")), "the item is not given up on");
|
||||
|
||||
// Still again and the item still on the corpse: the retry window starts now.
|
||||
FakeHost.CastBusy = 0;
|
||||
TickFor(bot, 250);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "the retry window counts from when the character is still");
|
||||
TickFor(bot, 500);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 2, "then one retry");
|
||||
}
|
||||
|
||||
// 2026-10-07: the client takes an item off the corpse list as soon as the move is sent; the
|
||||
// corpse was closed then, and the character picked the item up after the corpse closed.
|
||||
private static void CloseWaitsForInventory()
|
||||
{
|
||||
var bot = OpenCorpseAndSendPickup(closeSupported: true);
|
||||
FakeHost.Containers[Gem] = 0x7FFFFFF0; // off the corpse, not in a pack yet
|
||||
TickFor(bot, 1500);
|
||||
Check.Eq(FakeHost.Closes.Count, 0, "not closed while the item is on its way");
|
||||
Check.False(Completed(bot), "not completed either");
|
||||
|
||||
FakeHost.Containers[Gem] = Player; // in the main pack
|
||||
for (int i = 0; i < 200 && FakeHost.Closes.Count == 0; i++)
|
||||
{
|
||||
bot.Tick(BotActivity.Looting);
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
Check.Eq(FakeHost.Closes.Count, 1, "closed once the item is in the inventory");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("pickup confirmed")), "and the pickup confirmed");
|
||||
}
|
||||
|
||||
private static void TickFor(Bot bot, int ms)
|
||||
{
|
||||
long end = Environment.TickCount64 + ms;
|
||||
while (Environment.TickCount64 < end)
|
||||
{
|
||||
bot.Tick(BotActivity.Looting);
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,56 @@
|
|||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-10-08: RynthAi used an Aligned Mana Stone on a wand. Only the ordinary tapping stones
|
||||
// (and mana charges) are stones to RynthAi unless a ManaStone consumable rule names one.
|
||||
internal static class ManaStoneChoiceTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("mana stones: only ordinary stones and charges are used; special stones only when a rule names them", OrdinaryOnly);
|
||||
r.Add("mana stones: with tapping off, charged stones and Mana Charges still refill worn gear", RefillWithoutTapping);
|
||||
}
|
||||
|
||||
private static void OrdinaryOnly()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var host = FakeHost.Create();
|
||||
var cache = new WorldObjectCache(host);
|
||||
var s = new LegacyUiSettings { EnableManaTapping = true };
|
||||
var m = new ManaStoneManager(host, s, cache);
|
||||
WorldObject W(string name) => new(0x60001000, name, AcObjectClass.ManaStone);
|
||||
|
||||
foreach (string n in new[] { "Minor Mana Stone", "Lesser Mana Stone", "Moderate Mana Stone", "Mana Stone", "Greater Mana Stone", "Major Mana Stone", "Titan Mana Charge" })
|
||||
Check.True(m.IsManaStone(W(n)), $"'{n}' is a stone");
|
||||
foreach (string n in new[] { "Aligned Mana Stone", "Aetheria Mana Stone", "Unstable Mana Stone", "Enchanted Mana Stone", "Adjanite Mana Stone" })
|
||||
Check.False(m.IsManaStone(W(n)), $"'{n}' is left alone");
|
||||
|
||||
s.ConsumableRules.Add(new ConsumableRule { Name = "Aligned Mana Stone", Type = "ManaStone" });
|
||||
Check.True(m.IsManaStone(W("Aligned Mana Stone")), "a rule naming it opts it in");
|
||||
Check.False(m.IsManaStone(W("Mana Stone")), "with rules, only the named stones");
|
||||
}
|
||||
|
||||
private static void RefillWithoutTapping()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var host = FakeHost.Create();
|
||||
var cache = new WorldObjectCache(host);
|
||||
var s = new LegacyUiSettings { EnableManaTapping = false };
|
||||
var m = new ManaStoneManager(host, s, cache);
|
||||
WorldObject W(string name) => new(0x60001000, name, AcObjectClass.ManaStone);
|
||||
|
||||
Check.False(m.IsManaStone(W("Major Mana Stone")), "tapping off: not a stone to loot or drain into");
|
||||
Check.True(m.IsRefillStone(W("Major Mana Stone")), "but a charged one still refills gear");
|
||||
Check.True(m.IsRefillStone(W("Titan Mana Charge")), "a bought Mana Charge too");
|
||||
Check.False(m.IsRefillStone(W("Aligned Mana Stone")), "never a special stone");
|
||||
|
||||
s.ConsumableRules.Add(new ConsumableRule { Name = "Aligned Mana Stone", Type = "ManaStone" });
|
||||
Check.True(m.IsRefillStone(W("Aligned Mana Stone")), "unless a rule names it");
|
||||
Check.False(m.IsRefillStone(W("Major Mana Stone")), "with rules, only the named stones");
|
||||
}
|
||||
}
|
||||
|
|
@ -59,6 +59,127 @@ internal static class MetaTests
|
|||
SecondsInStatePPersists);
|
||||
r.Add("meta: MainHealthPHE / MainManaPHE mean 'percent >='", PercentConditionsAreGE); // was a known failure; fixed by a7c4618
|
||||
r.Add("meta: a negative vital threshold never holds", NegativeVitalThreshold); // was a known failure; fixed by 6f72b67
|
||||
r.Add("meta edit: saving a rule keeps the running meta's state, clocks and latch", EditKeepsRunningMeta);
|
||||
r.Add("meta edit: a saved rule keeps CallState's return state and ChatCapture's colours", EditKeepsHiddenFields);
|
||||
r.Add("meta edit: the editor's Set current text matches the landblock / landcell", SetCurrentMatches);
|
||||
r.Add("meta edit: a new state's Never -> None rule keeps it through a save and reload", NewStateSurvivesReload);
|
||||
}
|
||||
|
||||
private static void SetCurrentMatches()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
foreach (uint cell in new uint[] { 0xA9B4001Cu, 0x00070143u, 0x8B370105u, 0x0001FFFEu })
|
||||
{
|
||||
FakeHost.PlayerPose = (cell, 10f, 10f, 0f);
|
||||
var rig = new Rig(FakeHost.Create(), Player);
|
||||
string block = RynthCore.Engine.UI.Data.MetaLocation.Text(RynthCore.Engine.UI.Data.MetaLocation.LandblockCondition, cell)!;
|
||||
string here = RynthCore.Engine.UI.Data.MetaLocation.Text(RynthCore.Engine.UI.Data.MetaLocation.LandcellCondition, cell)!;
|
||||
Check.True(rig.Holds(C.Landblock_EQ, block), $"Landblock == {block} holds at {cell:X8}");
|
||||
Check.True(rig.Holds(C.Landcell_EQ, here), $"Landcell == {here} holds at {cell:X8}");
|
||||
FakeHost.PlayerPose = (cell + 0x00010000u, 10f, 10f, 0f);
|
||||
Check.False(rig.Holds(C.Landblock_EQ, block), $"not in the next landblock ({cell:X8})");
|
||||
FakeHost.PlayerPose = (cell + 1, 10f, 10f, 0f);
|
||||
Check.False(rig.Holds(C.Landcell_EQ, here), $"not in the next cell ({cell:X8})");
|
||||
}
|
||||
}
|
||||
|
||||
private static void NewStateSurvivesReload()
|
||||
{
|
||||
// What "+ New state..." adds (engine MetaRuleEdit.Placeholder): Never -> None in the new state.
|
||||
var rules = new List<MetaRule>
|
||||
{
|
||||
Rule("Default", C.Always, "", A.SetMetaState, "Loot"),
|
||||
new() { State = "Loot", Condition = C.Never, Action = A.None },
|
||||
};
|
||||
string text = AfFileWriter.SaveToString(rules, new Dictionary<string, List<string>>());
|
||||
var back = AfFileParser.LoadFromText(text);
|
||||
Check.Eq(back.Rules.Count, 2, "both rules back");
|
||||
var loot = back.Rules.FirstOrDefault(x => x.State == "Loot");
|
||||
Check.NotNull(loot, "the new state is still there");
|
||||
if (loot != null)
|
||||
{
|
||||
Check.Eq(loot.Condition, C.Never, "Never");
|
||||
Check.Eq(loot.Action, A.None, "None");
|
||||
}
|
||||
|
||||
// It never fires, and SetState into it just sits there.
|
||||
var rig = new Rig(rules: new[] { Rule("Default", C.Always, "", A.SetMetaState, "Loot"), Mark("Loot", C.Never, "", "x") });
|
||||
rig.Tick();
|
||||
rig.Tick(5);
|
||||
Check.Eq(rig.S.CurrentState, "Loot", "moved into the new state");
|
||||
Check.False(rig.Has("x"), "its Never rule never fires");
|
||||
}
|
||||
|
||||
// ── Panel edits on a running meta (MetaRuleEdits, update_rule; 2026-10-05 autosave) ─────
|
||||
|
||||
private static void EditKeepsRunningMeta()
|
||||
{
|
||||
var rig = new Rig(rules: new[]
|
||||
{
|
||||
Mark("Default", C.Always, "", "a"),
|
||||
Mark("Default", C.SecondsInState_GE, "10", "t"),
|
||||
});
|
||||
rig.Tick();
|
||||
Check.Eq(rig.Var("a"), "1", "the Always rule fired on entry");
|
||||
rig.Tick(6);
|
||||
|
||||
// What the editor's autosave sends: an edited copy of rule 0, then the structural bump
|
||||
// TryAutoSaveMetaCmd makes.
|
||||
MetaRule edited = Mark("Default", C.Always, "", "a");
|
||||
edited.ActionData = "setvar[a, getvar[a]+10]";
|
||||
Check.True(MetaRuleEdits.Replace(rig.S.MetaRules, 0, edited), "replaced");
|
||||
rig.S.MetaRulesStructuralVersion++;
|
||||
rig.Tick();
|
||||
Check.Eq(rig.Var("a"), "1", "the edited rule did not fire again (latch kept)");
|
||||
Check.Eq(rig.S.CurrentState, "Default", "state unchanged");
|
||||
Check.Near(rig.M.GetStateSnapshot().SecondsInState, 6, 1e-9, "seconds in state not restarted");
|
||||
rig.Tick(4.5);
|
||||
Check.Eq(rig.Var("t"), "1", "the 10 s rule fired on the original clock");
|
||||
|
||||
// A real state entry re-arms it, now with the edited action.
|
||||
rig.S.ForceStateReset = true;
|
||||
rig.Tick();
|
||||
Check.Eq(rig.Var("a"), "11", "re-armed by a state entry, runs the edited action");
|
||||
|
||||
// Out of range: nothing changes.
|
||||
Check.False(MetaRuleEdits.Replace(rig.S.MetaRules, 5, Mark("Default", C.Never, "", "z")), "bad index refused");
|
||||
Check.Eq(rig.S.MetaRules.Count, 2, "rule count unchanged");
|
||||
|
||||
// Before the fix (a plain replace) the same edit fired the rule again.
|
||||
var old = new Rig(rules: new[] { Mark("Default", C.Always, "", "a") });
|
||||
old.Tick();
|
||||
old.S.MetaRules[0] = Mark("Default", C.Always, "", "a");
|
||||
old.S.MetaRulesStructuralVersion++;
|
||||
old.Tick();
|
||||
Check.Eq(old.Var("a"), "2", "a plain replace re-fires (what MetaRuleEdits prevents)");
|
||||
}
|
||||
|
||||
private static void EditKeepsHiddenFields()
|
||||
{
|
||||
var call = new MetaRule
|
||||
{
|
||||
State = "Default", Condition = C.ChatMessageCapture, ConditionData = "x", ChatColors = "2;4",
|
||||
Action = A.CallMetaState, ActionData = "Buff", CallReturnState = "Hunt",
|
||||
};
|
||||
var rules = new List<MetaRule> { call };
|
||||
// The panel's DTO carries neither field.
|
||||
var edited = new MetaRule { State = "Default", Condition = C.ChatMessageCapture, ConditionData = "y", Action = A.CallMetaState, ActionData = "Buff2" };
|
||||
MetaRuleEdits.Replace(rules, 0, edited);
|
||||
Check.Eq(rules[0].CallReturnState, "Hunt", "CallState return kept");
|
||||
Check.Eq(rules[0].ChatColors, "2;4", "ChatCapture colours kept");
|
||||
Check.Eq(rules[0].ActionData, "Buff2", "the edit applied");
|
||||
|
||||
// Changing the action / condition drops them.
|
||||
var other = new MetaRule { State = "Default", Condition = C.Always, Action = A.SetMetaState, ActionData = "Buff" };
|
||||
MetaRuleEdits.Replace(rules, 0, other);
|
||||
Check.Eq(rules[0].CallReturnState, "", "not a CallState any more");
|
||||
Check.Eq(rules[0].ChatColors, "", "not a ChatCapture any more");
|
||||
|
||||
// Nested: an All's ChatCapture child by position.
|
||||
var parent = new MetaRule { Condition = C.All, Children = { new MetaRule { Condition = C.ChatMessageCapture, ChatColors = "7" } } };
|
||||
var parentEdit = new MetaRule { Condition = C.All, Children = { new MetaRule { Condition = C.ChatMessageCapture, ConditionData = "z" } } };
|
||||
MetaRuleEdits.KeepHidden(parent, parentEdit);
|
||||
Check.Eq(parentEdit.Children[0].ChatColors, "7", "child colours kept");
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────────
|
||||
|
|
|
|||
200
Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs
Normal file
200
Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using RynthCore.MonsterEditor;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
using EditorRule = RynthCore.MonsterEditor.MonsterRule;
|
||||
using PluginRule = RynthCore.Plugin.RynthAi.LegacyUi.MonsterRule;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The standalone Monster Editor (Tools/RynthCore.MonsterEditor; Models.cs, JsonContext.cs and
|
||||
// MonsterRulesFile.cs compiled in) reads and writes the plugin's monsters file. Before 2026-10-05
|
||||
// its MonsterRule had no Category or MatchExpression (or CustomDebuffs), so an editor save
|
||||
// dropped them and an expression rule fell back to matching by name only. Spotted by
|
||||
// Silentkelpie (rynth PR #1); re-implemented here. Every file goes through the plugin's own
|
||||
// serializer (RynthAiJsonContext) on the way in and out.
|
||||
internal static class MonsterEditorTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("monster editor: a plugin file round-trips through the editor (every field kept)", RoundTripKeepsEveryField);
|
||||
r.Add("monster editor: Category and MatchExpression load, edit and save", CategoryAndMatchEditable);
|
||||
r.Add("monster editor: unknown fields survive, files without the new fields still load", UnknownAndOldFields);
|
||||
r.Add("monster editor: a character folder opens the plugin's MonsterProfiles file", FindsThePluginsFile);
|
||||
}
|
||||
|
||||
private static string Dir(string name)
|
||||
{
|
||||
string dir = Path.Combine(Program.TempRoot, "monster-editor", name);
|
||||
Directory.CreateDirectory(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
private static List<PluginRule> PluginRules() => new()
|
||||
{
|
||||
new PluginRule { Name = "Default", Priority = 1 },
|
||||
new PluginRule
|
||||
{
|
||||
Name = "Olthoi", Category = "Olthoi nest", MatchExpression = "getcharintprop[25]>=200",
|
||||
Priority = 3, DamageType = "Acid", WeaponId = 0x50001234, Fester = true, Broadside = true,
|
||||
GravityWell = true, Imperil = true, Yield = true, Vuln = true, UseArc = true, UseRing = true,
|
||||
UseStreak = true, UseBolt = false, UseBlast = true, UseWall = true, ExVuln = "Fire", OffhandId = 2,
|
||||
PetDamage = "Cold", CustomDebuffs = "Corrosion Vulnerability Other, Fire Vulnerability Other VII",
|
||||
},
|
||||
new PluginRule { Name = "", Category = "Expression only", MatchExpression = "wobjectfindnearestbytemplatetype[1]" },
|
||||
};
|
||||
|
||||
private static string WriteAsPlugin(string dir, List<PluginRule> rules)
|
||||
{
|
||||
string path = Path.Combine(dir, "Toon.json");
|
||||
File.WriteAllText(path, JsonSerializer.Serialize(rules, RynthAiJsonContext.Default.MonsterRuleList));
|
||||
return path;
|
||||
}
|
||||
|
||||
private static List<PluginRule> ReadAsPlugin(string path) =>
|
||||
JsonSerializer.Deserialize(File.ReadAllText(path), RynthAiJsonContext.Default.MonsterRuleList)!;
|
||||
|
||||
/// <summary>Every public property of the plugin's rule, compared one by one.</summary>
|
||||
private static void SameRules(List<PluginRule> actual, List<PluginRule> expected, string what)
|
||||
{
|
||||
Check.Eq(actual.Count, expected.Count, what + ": rule count");
|
||||
PropertyInfo[] props = typeof(PluginRule).GetProperties(BindingFlags.Public | BindingFlags.Instance);
|
||||
Check.True(props.Any(p => p.Name == "MatchExpression") && props.Any(p => p.Name == "Category"), "the plugin's rule has both fields");
|
||||
for (int i = 0; i < Math.Min(actual.Count, expected.Count); i++)
|
||||
foreach (PropertyInfo p in props)
|
||||
Check.Eq(p.GetValue(actual[i])?.ToString(), p.GetValue(expected[i])?.ToString(), $"{what}: rule {i} {p.Name}");
|
||||
}
|
||||
|
||||
private static void RoundTripKeepsEveryField()
|
||||
{
|
||||
List<PluginRule> original = PluginRules();
|
||||
string path = WriteAsPlugin(Dir("roundtrip"), original);
|
||||
|
||||
// Open in the editor, change one thing (as a grid edit does), save.
|
||||
List<EditorRule> rules = MonsterRulesFile.Load(path);
|
||||
Check.Eq(rules.Count, 3, "editor loads every rule");
|
||||
rules[1].Priority = 4;
|
||||
MonsterRulesFile.Save(path, rules);
|
||||
|
||||
List<PluginRule> back = ReadAsPlugin(path);
|
||||
original[1].Priority = 4;
|
||||
SameRules(back, original, "after an editor save");
|
||||
|
||||
// A second save with no edits changes nothing more.
|
||||
MonsterRulesFile.Save(path, MonsterRulesFile.Load(path));
|
||||
SameRules(ReadAsPlugin(path), original, "after a second save");
|
||||
string json = File.ReadAllText(path);
|
||||
Check.Eq(CountOf(json, "\"MatchExpression\""), 3, "MatchExpression written once per rule");
|
||||
Check.Eq(CountOf(json, "\"CustomDebuffs\""), 3, "CustomDebuffs written once per rule");
|
||||
}
|
||||
|
||||
private static void CategoryAndMatchEditable()
|
||||
{
|
||||
string path = WriteAsPlugin(Dir("edit"), PluginRules());
|
||||
List<EditorRule> rules = MonsterRulesFile.Load(path);
|
||||
Check.Eq(rules[1].Category, "Olthoi nest", "Category read");
|
||||
Check.Eq(rules[1].MatchExpression, "getcharintprop[25]>=200", "MatchExpression read");
|
||||
|
||||
var changed = new List<string>();
|
||||
rules[1].PropertyChanged += (_, e) => changed.Add(e.PropertyName ?? "");
|
||||
rules[1].MatchExpression = ""; // back to matching by name
|
||||
rules[1].Category = null!; // a cleared grid cell
|
||||
Check.True(changed.Contains("MatchExpression") && changed.Contains("Category"), "edits raise PropertyChanged (the editor saves on it)");
|
||||
rules[2].MatchExpression = "true";
|
||||
MonsterRulesFile.Save(path, rules);
|
||||
|
||||
List<PluginRule> back = ReadAsPlugin(path);
|
||||
Check.Eq(back[1].MatchExpression, "", "cleared expression saved");
|
||||
Check.Eq(back[1].Category, "", "a null Category is saved as empty");
|
||||
Check.Eq(back[2].MatchExpression, "true", "edited expression saved");
|
||||
Check.Eq(back[2].Category, "Expression only", "untouched Category kept");
|
||||
|
||||
// A rule added in the editor carries the plugin's defaults for the new fields.
|
||||
var added = new EditorRule { Name = "Drudge" };
|
||||
Check.Eq(added.Category, "", "new rule: empty Category");
|
||||
Check.Eq(added.MatchExpression, "", "new rule: empty MatchExpression (by name)");
|
||||
}
|
||||
|
||||
private static void UnknownAndOldFields()
|
||||
{
|
||||
string dir = Dir("unknown");
|
||||
string path = Path.Combine(dir, "Toon.json");
|
||||
// A field neither side knows yet (a later plugin), a nested value, and a file from before
|
||||
// Category/MatchExpression existed (no such keys at all).
|
||||
File.WriteAllText(path, """
|
||||
[
|
||||
{ "Name": "Default", "Priority": 1 },
|
||||
{ "Name": "Mosswart", "Priority": 2, "FutureField": { "A": [1, 2], "B": null }, "Shout": "hi" }
|
||||
]
|
||||
""");
|
||||
List<EditorRule> rules = MonsterRulesFile.Load(path);
|
||||
Check.Eq(rules[1].Category, "", "old file: Category empty");
|
||||
Check.Eq(rules[1].MatchExpression, "", "old file: MatchExpression empty");
|
||||
MonsterRulesFile.Save(path, rules);
|
||||
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path));
|
||||
JsonElement mosswart = doc.RootElement[1];
|
||||
Check.True(mosswart.TryGetProperty("FutureField", out JsonElement future), "unknown field kept");
|
||||
Check.Eq(future.GetRawText().Replace(" ", "").Replace("\r", "").Replace("\n", ""), """{"A":[1,2],"B":null}""", "unknown field value unchanged");
|
||||
Check.Eq(mosswart.GetProperty("Shout").GetString(), "hi", "unknown string kept");
|
||||
Check.Eq(ReadAsPlugin(path)[1].Priority, 2, "the plugin still reads the file");
|
||||
}
|
||||
|
||||
// The plugin launches the editor with the character's settings folder
|
||||
// (SettingsProfiles\<server>\<character>) but reads MonsterProfiles\<server>\<character>.json
|
||||
// (LegacyDashboardRenderer.MonstersFilePath); the editor used to open <folder>\monsters.json.
|
||||
private static void FindsThePluginsFile()
|
||||
{
|
||||
string root = Dir("paths");
|
||||
string Rel(params string[] parts) => Path.Combine(new[] { root }.Concat(parts).ToArray());
|
||||
string aelChar = Rel("SettingsProfiles", "Aelrynth", "Toon");
|
||||
string aceChar = Rel("SettingsProfiles", "ACEmulator", "Toon");
|
||||
Directory.CreateDirectory(aelChar);
|
||||
Directory.CreateDirectory(aceChar);
|
||||
string aelFile = Rel("MonsterProfiles", "Aelrynth", "Toon.json");
|
||||
string aceFile = Rel("MonsterProfiles", "Toon.json");
|
||||
|
||||
// Not there yet: the plugin's path (a save creates it where the plugin reads).
|
||||
Check.Eq(MonsterRulesFile.ResolveRulesPath(aelChar), aelFile, "server folder -> MonsterProfiles\\<server>\\<char>.json");
|
||||
Check.Eq(MonsterRulesFile.ResolveRulesPath(aceChar + "\\"), aceFile, "ACEmulator -> MonsterProfiles\\<char>.json (trailing slash ok)");
|
||||
Check.Eq(MonsterRulesFile.ResolveRulesPath("\"" + aelChar + "\""), aelFile, "quoted argument");
|
||||
|
||||
// Only the old file exists: that one (the plugin moves it across at its next load).
|
||||
string legacy = Path.Combine(aelChar, "monsters.json");
|
||||
File.WriteAllText(legacy, "[]");
|
||||
Check.Eq(MonsterRulesFile.ResolveRulesPath(aelChar), legacy, "only the old monsters.json: use it");
|
||||
|
||||
// Both: the plugin's.
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(aelFile)!);
|
||||
File.WriteAllText(aelFile, "[]");
|
||||
Check.Eq(MonsterRulesFile.ResolveRulesPath(aelChar), aelFile, "both exist: the plugin's file");
|
||||
|
||||
// A file is edited as given; a folder outside SettingsProfiles keeps the old behaviour.
|
||||
Check.Eq(MonsterRulesFile.ResolveRulesPath(aelFile), aelFile, "a file opens as is");
|
||||
string loose = Rel("Elsewhere", "Toon");
|
||||
Check.Eq(MonsterRulesFile.ResolveRulesPath(loose), Path.Combine(loose, "monsters.json"), "unknown layout: <folder>\\monsters.json");
|
||||
|
||||
// And back: the settings folder for the weapon list.
|
||||
Check.Eq(MonsterRulesFile.CharFolderForRulesPath(aelFile), aelChar, "MonsterProfiles\\<server> file -> its settings folder");
|
||||
Check.Eq(MonsterRulesFile.CharFolderForRulesPath(aceFile), aceChar, "MonsterProfiles file -> SettingsProfiles\\ACEmulator");
|
||||
Check.Eq(MonsterRulesFile.CharFolderForRulesPath(legacy), aelChar, "old monsters.json -> its own folder");
|
||||
Check.Eq(MonsterRulesFile.CharFolderForRulesPath(Rel("Elsewhere", "x.json")), Rel("Elsewhere"), "unknown layout -> the file's folder");
|
||||
|
||||
// The plugin's own path for this character agrees.
|
||||
Check.Eq(MonsterRulesFile.PluginRulesPathForCharFolder(aelChar), aelFile, "PluginRulesPathForCharFolder");
|
||||
Check.Null(MonsterRulesFile.PluginRulesPathForCharFolder(loose), "not under SettingsProfiles: null");
|
||||
}
|
||||
|
||||
private static int CountOf(string text, string what)
|
||||
{
|
||||
int n = 0;
|
||||
for (int i = text.IndexOf(what, StringComparison.Ordinal); i >= 0; i = text.IndexOf(what, i + what.Length, StringComparison.Ordinal))
|
||||
n++;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
207
Tools/RynthCore.RynthAiHostTests/Tests/MultiTargetTests.cs
Normal file
207
Tools/RynthCore.RynthAiHostTests/Tests/MultiTargetTests.cs
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.CreatureData;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// One spell, several monsters: rings, walls, blasts and chain spells (Conquest). Each monster the
|
||||
// spell hurts gets its own damage line naming it, the server sends health only for the selected
|
||||
// target, and a kill notice names the monster that died. These tests drive CombatManager with
|
||||
// those lines on the fake host: every line goes to the monster it names (never to the fight
|
||||
// target), the other monsters get a health estimate, and kill notices from one cast keep the scan
|
||||
// off each monster that died without dropping a fight target that is still alive.
|
||||
internal static class MultiTargetTests
|
||||
{
|
||||
private const uint Player = 0x50000C01;
|
||||
private const uint Lb = 0xA9B40000;
|
||||
private const uint SkulkerWcid = 1001, MosswartWcid = 1002;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("damage text: the victim's name comes with the amount", VictimNames);
|
||||
r.Add("multi-target: each damage line goes to the monster it names", LinesGoToTheirMonsters);
|
||||
r.Add("multi-target: same-named monsters in one volley are told apart", SameNameVolley);
|
||||
r.Add("multi-target: other targets get a health estimate, the server's number wins", HealthEstimates);
|
||||
r.Add("multi-target: several kills from one cast keep the live fight target", KillsFromOneCast);
|
||||
r.Add("multi-target: the fight target's own kill notice still drops it", FightTargetKill);
|
||||
}
|
||||
|
||||
// ── The parser ───────────────────────────────────────────────────────────
|
||||
|
||||
private static string? Victim(string text) => CombatText.TryParseOutgoingHit(text, out string v, out _) ? v : null;
|
||||
|
||||
private static void VictimNames()
|
||||
{
|
||||
Check.Eq(Victim("You blast Drudge Skulker for 153 points with Whirling Blade VII."), "Drudge Skulker", "ACE war magic");
|
||||
Check.Eq(Victim("You scorch the Mosswart Worshipper for 1,234 points of fire damage!"), "Mosswart Worshipper", "retail, 'the' dropped");
|
||||
Check.Eq(Victim("Critical hit! Sneak Attack! You gore Olthoi Slasher for 1638 points with Force Arc VII."), "Olthoi Slasher", "two prefixes");
|
||||
Check.Eq(Victim("Overpower! You frost Tusker Guard for 40 points with Frost Bolt VI."), "Tusker Guard", "Overpower prefix");
|
||||
Check.Eq(Victim("You slash Banderling Scout for 12 points of slashing damage!"), "Banderling Scout", "melee");
|
||||
Check.Eq(Victim("Olthoi Swarm Harvester blisters your lower leg for 12 points of acid damage!"), null, "a monster's hit on us");
|
||||
Check.Eq(Victim("You drain 45 points of mana from Drudge Skulker."), null, "a drain");
|
||||
Check.Eq(Victim("You heal yourself for 64 points."), null, "a heal");
|
||||
Check.Eq(CombatText.CorpseOwnerName("Corpse of Drudge Skulker"), "Drudge Skulker", "corpse name");
|
||||
Check.Eq(CombatText.CorpseOwnerName("Drudge Skulker"), null, "not a corpse");
|
||||
}
|
||||
|
||||
// ── The rig ──────────────────────────────────────────────────────────────
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S = new() { MonsterRange = 30 };
|
||||
public readonly MonsterDamageStore Store = new();
|
||||
public CombatManager C = null!;
|
||||
public RynthCore.Plugin.RynthAi.WorldObjectCache Cache = null!;
|
||||
private readonly List<uint> _ids = new();
|
||||
private uint _next = 0x80000301;
|
||||
|
||||
public Rig()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true; // installs GetCurrentCombatMode
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
FakeHost.Names[Player] = "Me";
|
||||
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
}
|
||||
|
||||
public uint Mob(string name, uint wcid, float north, float east)
|
||||
{
|
||||
uint id = _next++;
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Positions[id] = (Lb | 0x1C, 96f + east, 96f + north, 0f);
|
||||
FakeHost.ItemTypes[id] = 0x10;
|
||||
FakeHost.Wcids[id] = wcid;
|
||||
_ids.Add(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
public void Build(uint fightTarget, IReadOnlyDictionary<uint, float>? health = null)
|
||||
{
|
||||
var host = FakeHost.Create();
|
||||
Cache = FakeHost.MakeCache(host, Player, _ids, health);
|
||||
C = new CombatManager(host, S, Cache);
|
||||
C.SetPlayerId(Player);
|
||||
C.SetDamageStores(null, Store);
|
||||
C.EngageForTest(unchecked((int)fightTarget));
|
||||
}
|
||||
|
||||
public float Hp(uint id) => Cache.GetHealthRatio(unchecked((int)id));
|
||||
|
||||
/// <summary>Learned non-crit average damage per monster type (the Damage tab's rows).</summary>
|
||||
public Dictionary<uint, (double Avg, int Samples)> Learned()
|
||||
=> Store.Snapshot().GroupBy(r => r.Wcid)
|
||||
.ToDictionary(g => g.Key, g => (g.First().AvgDamage, g.Sum(r => r.DmgSamples)));
|
||||
}
|
||||
|
||||
// ── The tests ────────────────────────────────────────────────────────────
|
||||
|
||||
private static void LinesGoToTheirMonsters()
|
||||
{
|
||||
var rig = new Rig();
|
||||
uint skulker = rig.Mob("Drudge Skulker", SkulkerWcid, 5, 0);
|
||||
uint moss = rig.Mob("Mosswart Worshipper", MosswartWcid, 6, 2);
|
||||
rig.Build(skulker);
|
||||
|
||||
rig.C.HandleChatForDamage("You blast Drudge Skulker for 100 points with Lightning Chain VI.");
|
||||
rig.C.HandleChatForDamage("You blast Mosswart Worshipper for 40 points with Lightning Chain VI.");
|
||||
|
||||
var learned = rig.Learned();
|
||||
Check.True(learned.ContainsKey(MosswartWcid), "the Mosswart's hit is learned against the Mosswart");
|
||||
Check.Near(learned.GetValueOrDefault(MosswartWcid).Avg, 40, 1e-6, "the Mosswart's damage is its own 40");
|
||||
Check.Near(learned.GetValueOrDefault(SkulkerWcid).Avg, 100, 1e-6, "the Skulker keeps only its own 100 (not 140, not 70)");
|
||||
Check.Eq(learned.GetValueOrDefault(SkulkerWcid).Samples, 1, "one hit learned for the Skulker");
|
||||
Check.True(rig.Hp(moss) > 0f && rig.Hp(moss) < 1f, $"the Mosswart is marked hurt ({rig.Hp(moss):0.00})");
|
||||
Check.True(rig.Cache.IsHealthEstimated(unchecked((int)moss)), "and its health is our estimate");
|
||||
Check.True(!rig.Cache.IsHealthEstimated(unchecked((int)skulker)), "the fight target gets no estimate (the server sends its health)");
|
||||
}
|
||||
|
||||
private static void SameNameVolley()
|
||||
{
|
||||
var rig = new Rig();
|
||||
uint target = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 5, 0);
|
||||
uint near = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 7, 0);
|
||||
uint far = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 20, 0);
|
||||
rig.Build(target);
|
||||
rig.Store.SetManualHp(SkulkerWcid, 200);
|
||||
|
||||
// One chain: the target, then the nearest other soldier, then the next.
|
||||
rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Lightning Chain VI.");
|
||||
rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 50 points with Lightning Chain VI.");
|
||||
rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 20 points with Lightning Chain VI.");
|
||||
|
||||
Check.Near(rig.Hp(near), 0.75, 1e-4, "second line -> the nearest other soldier (200 hp, -50)");
|
||||
Check.Near(rig.Hp(far), 0.90, 1e-4, "third line -> the next one (-20)");
|
||||
Check.True(!rig.Cache.IsHealthEstimated(unchecked((int)target)), "the first line was the fight target's");
|
||||
}
|
||||
|
||||
private static void HealthEstimates()
|
||||
{
|
||||
var rig = new Rig();
|
||||
uint target = rig.Mob("Drudge Skulker", SkulkerWcid, 5, 0);
|
||||
uint moss = rig.Mob("Mosswart Worshipper", MosswartWcid, 6, 2);
|
||||
rig.Build(target);
|
||||
rig.Store.SetManualHp(MosswartWcid, 100);
|
||||
int m = unchecked((int)moss);
|
||||
|
||||
Check.Near(rig.Hp(moss), -1, 1e-6, "no health known before the hit");
|
||||
rig.C.HandleChatForDamage("You blast Mosswart Worshipper for 30 points with Flame Ring VI.");
|
||||
Check.Near(rig.Hp(moss), 0.70, 1e-4, "100 hp, hit for 30 -> 0.70");
|
||||
System.Threading.Thread.Sleep(900); // next volley
|
||||
rig.C.HandleChatForDamage("You blast Mosswart Worshipper for 500 points with Flame Ring VI.");
|
||||
Check.Near(rig.Hp(moss), RynthCore.Plugin.RynthAi.WorldObjectCache.EstimatedHealthFloor, 1e-6,
|
||||
"an estimate never reads dead (0): only the server says dead");
|
||||
rig.Cache.OnUpdateHealth(moss, 0.40f);
|
||||
Check.Near(rig.Hp(moss), 0.40, 1e-6, "the server's number replaces the estimate");
|
||||
Check.True(!rig.Cache.IsHealthEstimated(m), "and it is no longer an estimate");
|
||||
rig.Cache.ApplyDamageEstimate(m, 0.0);
|
||||
Check.Near(rig.Hp(moss), 0.40, 1e-6, "an unknown-max hit never raises a known value");
|
||||
}
|
||||
|
||||
private static void KillsFromOneCast()
|
||||
{
|
||||
var rig = new Rig();
|
||||
uint target = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 5, 0);
|
||||
uint twin = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 7, 0);
|
||||
uint moss = rig.Mob("Mosswart Worshipper", MosswartWcid, 6, 2);
|
||||
rig.Build(target);
|
||||
|
||||
// A cast hits all three; the server has the fight target at 60%.
|
||||
rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Flame Ring VI.");
|
||||
rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Flame Ring VI.");
|
||||
rig.C.HandleChatForDamage("You blast Mosswart Worshipper for 100 points with Flame Ring VI.");
|
||||
rig.Cache.OnUpdateHealth(target, 0.60f);
|
||||
|
||||
// The next cast kills the twin and the Mosswart (one notice each), not the target.
|
||||
rig.C.OnKillNotification("Olthoi Swarm Soldier's death is preceded by a sharp, stabbing pain!");
|
||||
rig.C.OnKillNotification("You slay Mosswart Worshipper viciously enough to impart death several times over!");
|
||||
|
||||
Check.True(rig.C.IsKillSuppressed(unchecked((int)twin)), "the same-named twin is the one that died");
|
||||
Check.True(rig.C.IsKillSuppressed(unchecked((int)moss)), "the Mosswart died");
|
||||
Check.True(!rig.C.IsKillSuppressed(unchecked((int)target)), "the live fight target is not suppressed");
|
||||
Check.Eq(rig.C.activeTargetId, unchecked((int)target), "and is still the target");
|
||||
}
|
||||
|
||||
private static void FightTargetKill()
|
||||
{
|
||||
var rig = new Rig();
|
||||
uint target = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 5, 0);
|
||||
uint twin = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 7, 0);
|
||||
rig.Build(target);
|
||||
|
||||
rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Flame Ring VI.");
|
||||
rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Flame Ring VI.");
|
||||
rig.Cache.OnUpdateHealth(target, 0f); // ACE: the 0 comes with the lethal hit, before the notice
|
||||
rig.C.OnKillNotification("Olthoi Swarm Soldier's death is preceded by a sharp, stabbing pain!");
|
||||
|
||||
Check.True(rig.C.IsKillSuppressed(unchecked((int)target)), "the fight target died and is suppressed");
|
||||
Check.Eq(rig.C.activeTargetId, 0, "and dropped");
|
||||
Check.True(!rig.C.IsKillSuppressed(unchecked((int)twin)), "the twin is untouched");
|
||||
}
|
||||
}
|
||||
|
|
@ -14,8 +14,9 @@ namespace RynthCore.RynthAiHostTests.Tests;
|
|||
// when the selected profile is a .json file.
|
||||
internal static class NativeLootTests
|
||||
{
|
||||
private const int MaxDamage = 54, Value = 19, ArmorLevel = 28, Workmanship = 105, Material = 131;
|
||||
private const int DamageVariance = 22, DamageMod = 62, WeaponDefense = 29;
|
||||
private const int MaxDamage = 44, Value = 19, ArmorLevel = 28, Workmanship = 105, Material = 131;
|
||||
// ACE PropertyFloat ids (WeaponOffense 62 / DamageMod 63; 61 is EconRecoveryInterval).
|
||||
private const int DamageVariance = 22, WeaponOffense = 62, DamageMod = 63, WeaponDefense = 29;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
|
|
@ -32,6 +33,7 @@ internal static class NativeLootTests
|
|||
r.Add("loot native: string regex, case-insensitive, falls back to the name", StringValue);
|
||||
r.Add("loot native: min damage = max - variance * max", MinDamage);
|
||||
r.Add("loot native: damage percent reads DamageMod * 100", DamagePercent);
|
||||
r.Add("loot native: DoubleValueKey ids are ACE's PropertyFloat (DamageMod 63, not WeaponOffense 62)", DoubleValueKeyIds);
|
||||
r.Add("loot native: total ratings sum keys 370-376 and 379 only", TotalRatings);
|
||||
r.Add("loot native: character skill (null, stub and live skills)", CharacterSkill);
|
||||
r.Add("loot native: unknown condition type passes", UnknownConditionPasses);
|
||||
|
|
@ -211,6 +213,35 @@ internal static class NativeLootTests
|
|||
var bow = new Item("Bow").Dbl(DamageMod, 1.5);
|
||||
Check.True(Eval(new DamagePercentGECondition { Value = 150 }, bow), "1.5 -> 150%");
|
||||
Check.False(Eval(new DamagePercentGECondition { Value = 151 }, bow), "above");
|
||||
|
||||
// A launcher with a big attack mod and a small damage mod: the rule must read the damage
|
||||
// mod (63). With DamageMod = 62 in the enum (before 2026-10-05) it read the attack mod.
|
||||
var launcher = new Item("Bow").Dbl(WeaponOffense, 1.5).Dbl(DamageMod, 1.1).Dbl(61, 2.0);
|
||||
Check.True(Eval(new DamagePercentGECondition { Value = 110 }, launcher), "damage mod 1.1 -> 110%");
|
||||
Check.False(Eval(new DamagePercentGECondition { Value = 111 }, launcher), "the 1.5 attack mod is not read");
|
||||
Check.False(Eval(new DamagePercentGECondition { Value = 150 }, new Item("Bow").Dbl(WeaponOffense, 1.5)),
|
||||
"attack mod alone: no damage percent");
|
||||
}
|
||||
|
||||
private static void DoubleValueKeyIds()
|
||||
{
|
||||
Check.Eq((int)DoubleValueKey.DamageVariance, 22, "DamageVariance");
|
||||
Check.Eq((int)DoubleValueKey.MaximumVelocity, 26, "MaximumVelocity");
|
||||
Check.Eq((int)DoubleValueKey.WeaponDefense, 29, "WeaponDefense");
|
||||
Check.Eq((int)DoubleValueKey.UseRadius, 54, "UseRadius");
|
||||
Check.Eq((int)DoubleValueKey.WeaponOffense, 62, "WeaponOffense");
|
||||
Check.Eq((int)DoubleValueKey.DamageMod, 63, "DamageMod");
|
||||
Check.Eq((int)DoubleValueKey.PowerLevel, 92, "PowerLevel");
|
||||
Check.Eq((int)DoubleValueKey.AccuracyLevel, 93, "AccuracyLevel");
|
||||
Check.Eq((int)AcFloatProperty.AttackBonus, 62, "LootSdk AttackBonus = WeaponOffense");
|
||||
Check.Eq((int)AcFloatProperty.DamageMod, 63, "LootSdk DamageMod");
|
||||
Check.Eq((int)AcFloatProperty.ManaConvMod, 144, "LootSdk ManaConvMod");
|
||||
Check.Eq((int)AcFloatProperty.SlayerDamageBonus, 138, "LootSdk SlayerDamageBonus");
|
||||
|
||||
// The double-key condition reads the id it is given: 63 is the damage mod.
|
||||
var bow = new Item("Bow").Dbl(WeaponOffense, 1.25).Dbl(DamageMod, 1.05);
|
||||
Check.True(Eval(new DoubleValKeyGECondition { Key = 63, Value = 1.05 }, bow), "key 63 reads DamageMod");
|
||||
Check.False(Eval(new DoubleValKeyGECondition { Key = 63, Value = 1.06 }, bow), "not WeaponOffense");
|
||||
}
|
||||
|
||||
private static void TotalRatings()
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ internal static class NavEngineTests
|
|||
|
||||
r.Add("nav point reach: values under 1.5 yd work (it used to be floored at 1.5)", ReachBelowOneAndAHalf);
|
||||
r.Add("nav point reach: a doorway point is reached within 1 yd, its sweep pass within 1.5 yd", DoorwayPointTight);
|
||||
r.Add("nav point reach: no lookahead corner cut at a doorway point", DoorwayNoLookahead);
|
||||
r.Add("nav point reach: no lookahead corner cut at a doorway point (or at a small reach)", DoorwayNoLookahead);
|
||||
r.Add("nav point reach: Follow stops within it and moves again 3 yd farther out", FollowUsesReach);
|
||||
r.Add("nav point reach: metas set it as FollowNavMin (yd) or VTank's NavCloseStopRange (x240)", ReachFromMetas);
|
||||
|
||||
|
|
@ -746,18 +746,27 @@ internal static class NavEngineTests
|
|||
|
||||
private static void DoorwayNoLookahead()
|
||||
{
|
||||
// 3 yd short of a point, the next one due east: a plain point blends the aim east
|
||||
// (4 yd lookahead), a doorway point keeps aiming straight at itself.
|
||||
// 3 yd short of a point, the next one due east, with a 2.8 yd reach (big enough to round
|
||||
// corners: 3.6 yd of lookahead): a plain point blends the aim east, a doorway point keeps
|
||||
// aiming straight at itself. At the 1.5 yd default reach there is no rounding at all
|
||||
// (the lookahead scales with the reach since 2026-10-05, see NavReachTests).
|
||||
foreach (bool doorway in new[] { false, true })
|
||||
{
|
||||
FakeHost.Reset(); At(7, 0); Face(10, 0);
|
||||
var first = doorway ? Door(10, 0) : Pt(10, 0);
|
||||
var nav = new Nav(Route(RT.Circular, first, Pt(10, 10)));
|
||||
nav.S.FollowNavMin = 2.8f;
|
||||
nav.Tick();
|
||||
double h = FakeHost.HeadingDeg;
|
||||
if (doorway) Check.True(h < 1.0 || h > 359.0, $"doorway point: still heading north ({h:F1})");
|
||||
else Check.True(h > 3.0 && h < 90.0, $"plain point: turning east early ({h:F1})");
|
||||
}
|
||||
|
||||
FakeHost.Reset(); At(8, 0); Face(10, 0);
|
||||
var dflt = new Nav(Route(RT.Circular, Pt(10, 0), Pt(10, 10)));
|
||||
dflt.Tick();
|
||||
double hd = FakeHost.HeadingDeg;
|
||||
Check.True(hd < 1.0 || hd > 359.0, $"1.5 yd default reach, 2 yd short: a plain point is walked straight at too ({hd:F1})");
|
||||
}
|
||||
|
||||
private static void FollowUsesReach()
|
||||
|
|
|
|||
263
Tools/RynthCore.RynthAiHostTests/Tests/NavOverlayTests.cs
Normal file
263
Tools/RynthCore.RynthAiHostTests/Tests/NavOverlayTests.cs
Normal file
|
|
@ -0,0 +1,263 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using T = RynthCore.Plugin.RynthAi.LegacyUi.NavPointType;
|
||||
using RT = RynthCore.Plugin.RynthAi.LegacyUi.NavRouteType;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Nav3D waypoint labels and guide line (Silentkelpie's rynth PR #1 idea, re-implemented on our
|
||||
// pump-thread Nav3D markers). Both settings are off by default and then change nothing. Labels
|
||||
// are filled strokes (Nav3D triangles) on an upright plane facing the character; the guide is
|
||||
// one Nav3D line from the character's feet to the waypoint nav is heading for. The frame is
|
||||
// built from the route on the plugin tick and the emit reads only the frame.
|
||||
internal static class NavOverlayTests
|
||||
{
|
||||
private const double NS0 = 42.0, EW0 = 33.0;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("nav overlay: both settings off by default - markers draw exactly as before", OffByDefault);
|
||||
r.Add("nav overlay: number labels over nearby waypoints, upright, facing the character, readable left to right", NumberLabels);
|
||||
r.Add("nav overlay: names mode names jumps and checkpoints and hangs actions on the point before", NamesMode);
|
||||
r.Add("nav overlay: labels only within range, active point first, nearest next, capped", LabelRangeAndCap);
|
||||
r.Add("nav overlay: the guide line runs from the character's feet to the active waypoint, not to an action point", GuideLine);
|
||||
r.Add("nav overlay: the frame is a snapshot - emptying the route afterwards changes nothing", FrameIsSnapshot);
|
||||
r.Add("nav overlay: the label triangle budget holds for long names", TriangleBudget);
|
||||
r.Add("nav overlay: settings round-trip; an older engine's payload leaves them alone", SettingsRoundTrip);
|
||||
}
|
||||
|
||||
// ── Rig ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static NavPoint Pt(double north, double east, T type = T.Point)
|
||||
=> new() { Type = type, NS = NS0 + north / 240.0, EW = EW0 + east / 240.0 };
|
||||
|
||||
private static NavRouteParser Route(params NavPoint[] pts)
|
||||
{
|
||||
var r = new NavRouteParser { RouteType = RT.Linear };
|
||||
r.Points.AddRange(pts);
|
||||
return r;
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly NavMarkerRenderer R;
|
||||
public readonly float Px, Py; // the player's landblock-local metres (east, north)
|
||||
|
||||
public Rig(NavRouteParser route, int labels = 0, bool guide = false, int active = 0)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.Nav3DCalls = true;
|
||||
FakeHost.SetNavPosition(NS0, EW0);
|
||||
Px = FakeHost.PlayerPose.X;
|
||||
Py = FakeHost.PlayerPose.Y;
|
||||
S = new LegacyUiSettings { CurrentRoute = route, ActiveNavIndex = active, NavHeightOffset = 0f, NavSlopeSink = 0f };
|
||||
if (labels != 0) S.NavLabelMode = labels;
|
||||
if (guide) S.NavGuideLine = true;
|
||||
R = new NavMarkerRenderer(FakeHost.Create(), S);
|
||||
}
|
||||
|
||||
public void Submit()
|
||||
{
|
||||
FakeHost.Nav3DRings.Clear(); FakeHost.Nav3DLines.Clear(); FakeHost.Nav3DTriangles.Clear();
|
||||
R.SubmitNav3D();
|
||||
}
|
||||
|
||||
/// <summary>World position (Nav3D frame) of a point north/east of the player, in metres.</summary>
|
||||
public (float X, float Z) At(double north, double east) => (Px + (float)east, Py + (float)north);
|
||||
}
|
||||
|
||||
private sealed class Recorder : INav3DSink
|
||||
{
|
||||
public readonly List<float[]> Lines = new();
|
||||
public readonly List<float[]> Tris = new();
|
||||
public void Line(float x1, float y1, float z1, float x2, float y2, float z2, float t, uint c) => Lines.Add(new[] { x1, y1, z1, x2, y2, z2 });
|
||||
public void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint c)
|
||||
=> Tris.Add(new[] { x1, y1, z1, x2, y2, z2, x3, y3, z3 });
|
||||
}
|
||||
|
||||
private static IEnumerable<(float X, float Y, float Z)> Vertices(IEnumerable<float[]> tris)
|
||||
{
|
||||
foreach (float[] t in tris)
|
||||
for (int i = 0; i < 9; i += 3) yield return (t[i], t[i + 1], t[i + 2]);
|
||||
}
|
||||
|
||||
// ── Tests ───────────────────────────────────────────────────────────
|
||||
|
||||
private static void OffByDefault()
|
||||
{
|
||||
var d = new LegacyUiSettings();
|
||||
Check.Eq(d.NavLabelMode, NavLabelModes.Off, "labels default off");
|
||||
Check.False(d.NavGuideLine, "guide line default off");
|
||||
|
||||
var rig = new Rig(Route(Pt(5, 0), Pt(10, 0), Pt(10, 6)));
|
||||
rig.Submit();
|
||||
Check.Eq(FakeHost.Nav3DRings.Count, 3, "three rings");
|
||||
Check.Eq(FakeHost.Nav3DLines.Count, 2, "two route lines, nothing more");
|
||||
Check.Eq(FakeHost.Nav3DTriangles.Count, 0, "no label triangles");
|
||||
Check.True(FakeHost.Nav3DLines.All(l => l.Color == 0xFF0088FF), "only route-coloured lines");
|
||||
}
|
||||
|
||||
private static void NumberLabels()
|
||||
{
|
||||
// One waypoint 10 m north, one 10 m east.
|
||||
var rig = new Rig(Route(Pt(10, 0), Pt(0, 10)), labels: NavLabelModes.Numbers);
|
||||
rig.Submit();
|
||||
Check.True(FakeHost.Nav3DTriangles.Count > 0, "labels drawn as triangles");
|
||||
Check.Eq(FakeHost.Nav3DLines.Count, 1, "the route line only (labels use no lines)");
|
||||
|
||||
var (nx, nz) = rig.At(10, 0);
|
||||
var (ex, ez) = rig.At(0, 10);
|
||||
var north = FakeHost.Nav3DTriangles.Where(t => Math.Abs(t.Z1 - nz) < 2f && Math.Abs(t.X1 - nx) < 2f).ToList();
|
||||
var east = FakeHost.Nav3DTriangles.Where(t => Math.Abs(t.X1 - ex) < 2f && Math.Abs(t.Z1 - ez) < 2f).ToList();
|
||||
Check.Eq(north.Count + east.Count, FakeHost.Nav3DTriangles.Count, "every triangle belongs to one of the two labels");
|
||||
Check.True(north.Count > 0 && east.Count > 0, "both waypoints labelled");
|
||||
// Facing the character: the north label's plane is east-west (one Z), the east one's north-south (one X).
|
||||
Check.True(north.All(t => Math.Abs(t.Z1 - nz) < 1e-3 && Math.Abs(t.Z2 - nz) < 1e-3 && Math.Abs(t.Z3 - nz) < 1e-3), "north label faces south, toward you");
|
||||
Check.True(east.All(t => Math.Abs(t.X1 - ex) < 1e-3 && Math.Abs(t.X2 - ex) < 1e-3 && Math.Abs(t.X3 - ex) < 1e-3), "east label faces west, toward you");
|
||||
// Upright and above the ring.
|
||||
Check.True(north.All(t => t.Y1 >= 0.9f && t.Y2 >= 0.9f && t.Y3 >= 0.9f), "above the ring");
|
||||
float minY = north.Min(t => Math.Min(t.Y1, Math.Min(t.Y2, t.Y3))), maxY = north.Max(t => Math.Max(t.Y1, Math.Max(t.Y2, t.Y3)));
|
||||
Check.True(maxY - minY > 0.3f, "has height (upright)");
|
||||
|
||||
// Readable from the character: "12" north of you runs west to east ('1' left of '2').
|
||||
var rec = new Recorder();
|
||||
var frame = new NavOverlayFrame(new[] { new NavLabel(0f, 0f, 10f, "12", 0, NavOverlay.LabelColor) }, null, 0f, 0f, 0f);
|
||||
NavOverlay.EmitLabels(frame, rec);
|
||||
int oneTris = NavStrokeFont.Glyph('1')!.Sum(p => p.Length / 2 - 1) * 2;
|
||||
float oneX = Vertices(rec.Tris.Take(oneTris)).Average(v => v.X);
|
||||
float twoX = Vertices(rec.Tris.Skip(oneTris)).Average(v => v.X);
|
||||
Check.True(oneX < twoX, $"'1' is west of '2' seen from the south ({oneX:0.00} < {twoX:0.00})");
|
||||
// Seen looking east, left-to-right is north to south.
|
||||
rec = new Recorder();
|
||||
NavOverlay.EmitLabels(new NavOverlayFrame(new[] { new NavLabel(10f, 0f, 0f, "12", 0, NavOverlay.LabelColor) }, null, 0f, 0f, 0f), rec);
|
||||
float oneZ = Vertices(rec.Tris.Take(oneTris)).Average(v => v.Z), twoZ = Vertices(rec.Tris.Skip(oneTris)).Average(v => v.Z);
|
||||
Check.True(oneZ > twoZ, "looking east, '1' is north of '2'");
|
||||
// Far labels are bigger.
|
||||
Check.True(NavOverlay.LineHeight(50f) > NavOverlay.LineHeight(5f), "a far label is drawn taller");
|
||||
}
|
||||
|
||||
private static void NamesMode()
|
||||
{
|
||||
var pts = new List<NavPoint>
|
||||
{
|
||||
Pt(5, 0), // 0
|
||||
new() { Type = T.Chat, ChatCommand = "/vt stop" }, // 1
|
||||
new() { Type = T.Recall, SpellId = 2645 }, // 2
|
||||
Pt(10, 0, T.Checkpoint), // 3
|
||||
Pt(12, 0, T.Jump), // 4
|
||||
new() { Type = T.PortalNPC, TargetName = "Gateway" }, // 5
|
||||
new() { Type = T.Pause, PauseTimeMs = 2500 }, // 6
|
||||
new() { Type = T.Npc, TargetName = "Town Crier" }, // 7
|
||||
new() { Type = T.OpenVendor, TargetName = "Shopkeeper" }, // 8
|
||||
};
|
||||
var text = NavOverlay.BuildText(pts, pts, NavLabelModes.Names, id => id == 2645 ? "Portal Recall" : "?");
|
||||
Check.Eq(text.Own[0], "0", "plain point: its number");
|
||||
Check.True(text.Own[1] == null && text.Own[2] == null, "action points get no label of their own");
|
||||
Check.Eq(string.Join("|", text.Actions[0] ?? Array.Empty<string>()), "1 CHAT /VT STOP|2 PORTAL RECALL", "actions hang on the point before");
|
||||
Check.Eq(text.Own[3], "3 CHECKPOINT", "checkpoint named");
|
||||
Check.Eq(text.Own[4], "4 JUMP", "jump named");
|
||||
Check.Eq(string.Join("|", text.Actions[4] ?? Array.Empty<string>()), "5 PORTAL GATEWAY|6 PAUSE 2.5S|7 NPC TOWN CRIER|...",
|
||||
"at most three action lines, then ...");
|
||||
|
||||
var numbers = NavOverlay.BuildText(pts, pts, NavLabelModes.Numbers, _ => "");
|
||||
Check.Eq(numbers.Own[4], "4", "numbers mode: just the number");
|
||||
Check.True(numbers.Actions.All(a => a == null), "numbers mode: no action lines");
|
||||
|
||||
// Drawn: the action lines stack above the point's own line.
|
||||
var rig = new Rig(Route(pts.ToArray()), labels: NavLabelModes.Names);
|
||||
var frame = rig.R.BuildOverlay(rig.S.CurrentRoute!, rig.Px, rig.Py, 0f, NS0, EW0, 0f);
|
||||
var at0 = frame.Labels.Where(l => l.Text.StartsWith("0", StringComparison.Ordinal) || l.Text.StartsWith("1 ", StringComparison.Ordinal) || l.Text.StartsWith("2 ", StringComparison.Ordinal)).ToList();
|
||||
Check.Eq(string.Join("|", at0.Select(l => $"{l.Row}:{l.Text}")), "0:0|1:1 CHAT /VT STOP|2:2 PORTAL RECALL", "rows 0, 1, 2 over point 0");
|
||||
Check.True(at0.Skip(1).All(l => l.Color == NavOverlay.ActionLabelColor), "action lines in their own colour");
|
||||
}
|
||||
|
||||
private static void LabelRangeAndCap()
|
||||
{
|
||||
// 40 points in a line northwards, 2 m apart (0..78 m): 31 of them within 60 m.
|
||||
var pts = Enumerable.Range(0, 40).Select(i => Pt(2 * i, 0)).ToArray();
|
||||
var rig = new Rig(Route(pts), labels: NavLabelModes.Numbers, active: 5);
|
||||
var frame = rig.R.BuildOverlay(rig.S.CurrentRoute!, rig.Px, rig.Py, 0f, NS0, EW0, 0f);
|
||||
Check.Eq(frame.Labels.Count, NavOverlay.MaxLabelLines, "capped at the line budget");
|
||||
Check.Eq(frame.Labels[0].Text, "5", "the active point first");
|
||||
Check.Eq(frame.Labels[0].Color, NavOverlay.ActiveLabelColor, "in the active colour");
|
||||
Check.Eq(frame.Labels[1].Text, "0", "then the nearest");
|
||||
Check.True(frame.Labels.All(l => Math.Abs(l.Z - rig.Py) <= NavOverlay.LabelRange + 0.01f), "all within range");
|
||||
|
||||
var few = new Rig(Route(Pt(10, 0), Pt(100, 0)), labels: NavLabelModes.Numbers);
|
||||
var f2 = few.R.BuildOverlay(few.S.CurrentRoute!, few.Px, few.Py, 0f, NS0, EW0, 0f);
|
||||
Check.Eq(string.Join(",", f2.Labels.Select(l => l.Text)), "0", "a point 100 m away gets no label");
|
||||
}
|
||||
|
||||
private static void GuideLine()
|
||||
{
|
||||
var rig = new Rig(Route(Pt(5, 0), Pt(10, 4)), guide: true, active: 1);
|
||||
rig.Submit();
|
||||
Check.Eq(FakeHost.Nav3DLines.Count, 2, "the route line plus the guide");
|
||||
var g = FakeHost.Nav3DLines[0];
|
||||
Check.Eq(g.Color, NavOverlay.GuideColor, "the guide goes in first (never crowded out)");
|
||||
var (tx, tz) = rig.At(10, 4);
|
||||
Check.True(Math.Abs(g.X1 - rig.Px) < 1e-3 && Math.Abs(g.Z1 - rig.Py) < 1e-3, "starts at the character");
|
||||
Check.True(Math.Abs(g.X2 - tx) < 1e-3 && Math.Abs(g.Z2 - tz) < 1e-3, "ends at the active waypoint");
|
||||
Check.True(g.Y1 > 0f && g.Y1 < 0.5f, "at the feet, lifted a little");
|
||||
Check.Eq(FakeHost.Nav3DTriangles.Count, 0, "labels stay off");
|
||||
|
||||
var chat = new Rig(Route(Pt(5, 0), new NavPoint { Type = T.Chat, ChatCommand = "hi" }, Pt(10, 0)), guide: true, active: 1);
|
||||
chat.Submit();
|
||||
Check.False(FakeHost.Nav3DLines.Any(l => l.Color == NavOverlay.GuideColor), "no guide to an action point (placeholder coordinates)");
|
||||
}
|
||||
|
||||
private static void FrameIsSnapshot()
|
||||
{
|
||||
var route = Route(Pt(5, 0), Pt(10, 0), Pt(15, 0));
|
||||
var rig = new Rig(route, labels: NavLabelModes.Numbers, guide: true, active: 2);
|
||||
NavOverlayFrame frame = rig.R.BuildOverlay(route, rig.Px, rig.Py, 0f, NS0, EW0, 0f);
|
||||
var before = new Recorder();
|
||||
NavOverlay.EmitGuide(frame, before, 0.06f);
|
||||
NavOverlay.EmitLabels(frame, before);
|
||||
|
||||
route.Points.Clear(); // what a reload or an edit on another thread would do
|
||||
var after = new Recorder();
|
||||
NavOverlay.EmitGuide(frame, after, 0.06f);
|
||||
NavOverlay.EmitLabels(frame, after);
|
||||
Check.Eq(after.Tris.Count, before.Tris.Count, "same label triangles from the frame");
|
||||
Check.Eq(after.Lines.Count, 1, "same guide line");
|
||||
Check.True(before.Tris.Zip(after.Tris).All(p => p.First.SequenceEqual(p.Second)), "identical geometry");
|
||||
Check.False(frame.Labels is List<NavLabel>, "labels are not a list anyone can grow");
|
||||
|
||||
rig.Submit();
|
||||
Check.Eq(FakeHost.Nav3DTriangles.Count + FakeHost.Nav3DLines.Count + FakeHost.Nav3DRings.Count, 0, "an empty route draws nothing next tick");
|
||||
}
|
||||
|
||||
private static void TriangleBudget()
|
||||
{
|
||||
var labels = Enumerable.Range(0, NavOverlay.MaxLabelLines)
|
||||
.Select(i => new NavLabel(0f, 0f, 5f + i, "WWWWWWWWWWWWWWWWWWWWWW", 0, NavOverlay.LabelColor)).ToArray();
|
||||
var rec = new Recorder();
|
||||
int used = NavOverlay.EmitLabels(new NavOverlayFrame(labels, null, 0f, 0f, 0f), rec);
|
||||
Check.True(used <= NavOverlay.MaxLabelTriangles && rec.Tris.Count == used, $"at most {NavOverlay.MaxLabelTriangles} triangles ({used})");
|
||||
Check.True(used > NavOverlay.MaxLabelTriangles - 20, "and the budget is used, not cut short");
|
||||
}
|
||||
|
||||
private static void SettingsRoundTrip()
|
||||
{
|
||||
var s = new LegacyUiSettings { NavLabelMode = NavLabelModes.Names, NavGuideLine = true };
|
||||
string json = JsonSerializer.Serialize(s, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
var back = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!;
|
||||
Check.Eq(back.NavLabelMode, NavLabelModes.Names, "label mode saved per character");
|
||||
Check.True(back.NavGuideLine, "guide line saved per character");
|
||||
|
||||
var old = JsonSerializer.Deserialize("{\"NavRingThickness\":6}", RynthAiJsonContext.Default.SettingsBridgePayload)!;
|
||||
Check.Eq(old.NavLabelMode, -1, "an older engine's payload: label mode absent (-1, kept)");
|
||||
Check.Null(old.NavGuideLine, "an older engine's payload: guide line absent (null, kept)");
|
||||
|
||||
Check.Eq(NavLabelModes.Clamp(7), NavLabelModes.Off, "a bad mode reads as off");
|
||||
}
|
||||
}
|
||||
261
Tools/RynthCore.RynthAiHostTests/Tests/NavReachTests.cs
Normal file
261
Tools/RynthCore.RynthAiHostTests/Tests/NavReachTests.cs
Normal file
|
|
@ -0,0 +1,261 @@
|
|||
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;
|
||||
using T = RynthCore.Plugin.RynthAi.LegacyUi.NavPointType;
|
||||
using RT = RynthCore.Plugin.RynthAi.LegacyUi.NavRouteType;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The nav point reach (FollowNavMin) really decides how close nav gets to each point before it
|
||||
// turns for the next (Tom, 2026-10-05: "at 1.0 it should pretty much go directly to it. It gets
|
||||
// to it, passes it and turns around to go back"; "it's turning too early and running into walls").
|
||||
//
|
||||
// Unlike NavEngineTests, where the fake character only moves when a test puts it somewhere, these
|
||||
// walk it: each nav tick (33 ms) the character runs forward along FakeHost.HeadingDeg while nav
|
||||
// has autorun on (using the autorun state from the tick before, so a stop takes a tick to land,
|
||||
// as in the game). Nav turns it with TurnToHeading, rate-limited to the turn-rate setting.
|
||||
//
|
||||
// The corner: a corridor 2 yd wide runs north from the origin to a point 20 yd north, then east.
|
||||
// Its inside wall corner is at (19 N, 1 E): any step with north < 19 and east > 1 went through it.
|
||||
internal static class NavReachTests
|
||||
{
|
||||
private const double NS0 = 42.0, EW0 = 33.0;
|
||||
private static long _now;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("nav reach: 1 yd at a 90 degree corner by a wall - touches the point, then turns, no corner cut", CornerTightReach);
|
||||
r.Add("nav reach: the corner rounding scales with the reach - none up to the 1.5 yd default, the Lookahead setting at 3 yd+", CornerRoundingScales);
|
||||
r.Add("nav reach: 5 yd still rounds a corner (moves on 5 yd out and heads across)", CornerWideReach);
|
||||
r.Add("nav reach: going past a point on the side counts as reached - no turning round", PassBySide);
|
||||
r.Add("nav reach: a corner cut never counts as passing (the point must be behind)", CutIsNotAPass);
|
||||
r.Add("nav reach: fast run at a low frame rate skips over a 0.5 yd reach - counted, no turning round", FastRunSkipsOver);
|
||||
r.Add("nav reach: the sweep pass uses the closest approach, not the last tick", SweepUsesClosest);
|
||||
r.Add("nav reach: doorway points unchanged - 1 yd reach, no pass-through, no rounding", DoorwayUnchanged);
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────────
|
||||
|
||||
private static NavPoint Pt(double north, double east, bool doorway = false)
|
||||
=> new() { Type = T.Point, NS = NS0 + north / 240.0, EW = EW0 + east / 240.0, Doorway = doorway };
|
||||
|
||||
private static NavRouteParser Route(RT type, params NavPoint[] pts)
|
||||
{
|
||||
var r = new NavRouteParser { RouteType = type };
|
||||
r.Points.AddRange(pts);
|
||||
return r;
|
||||
}
|
||||
|
||||
private sealed class Walk
|
||||
{
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly NavigationEngine E;
|
||||
public double N, E_;
|
||||
public double SpeedYdPerS = 11.0; // a good run skill
|
||||
public int TickMs = 33;
|
||||
public readonly List<(double N, double E, int Idx, bool Run)> Path = new();
|
||||
|
||||
public Walk(NavRouteParser route, float reach, double north, double east, double faceDeg)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
_now = 1_000_000;
|
||||
NavigationEngine.Clock = static () => _now;
|
||||
N = north; E_ = east;
|
||||
FakeHost.SetNavPosition(NS0 + N / 240.0, EW0 + E_ / 240.0);
|
||||
FakeHost.HeadingDeg = faceDeg;
|
||||
S = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, EnableNavigation = true, CurrentRoute = route, ActiveNavIndex = 0,
|
||||
FollowNavMin = reach,
|
||||
};
|
||||
E = new NavigationEngine(FakeHost.Create(), S);
|
||||
}
|
||||
|
||||
public int Idx => S.ActiveNavIndex;
|
||||
|
||||
/// <summary>One nav tick, then the character moves for one tick if autorun is on.</summary>
|
||||
public void Step()
|
||||
{
|
||||
_now += TickMs;
|
||||
bool run = FakeHost.AutoRun; // what the client was doing going into this tick
|
||||
E.Tick();
|
||||
if (run)
|
||||
{
|
||||
double h = FakeHost.HeadingDeg * Math.PI / 180.0, d = SpeedYdPerS * TickMs / 1000.0;
|
||||
N += d * Math.Cos(h);
|
||||
E_ += d * Math.Sin(h);
|
||||
FakeHost.SetNavPosition(NS0 + N / 240.0, EW0 + E_ / 240.0);
|
||||
}
|
||||
Path.Add((N, E_, Idx, FakeHost.AutoRun));
|
||||
}
|
||||
|
||||
public void RunUntil(Func<bool> done, double maxSeconds = 20)
|
||||
{
|
||||
int n = (int)(maxSeconds * 1000 / TickMs);
|
||||
for (int i = 0; i < n && !done(); i++) Step();
|
||||
}
|
||||
}
|
||||
|
||||
private static double Dist(double n0, double e0, double n1, double e1) => Math.Sqrt((n1 - n0) * (n1 - n0) + (e1 - e0) * (e1 - e0));
|
||||
|
||||
private static int LogCount(string contains) => FakeHost.Logs.Count(l => l.Contains(contains));
|
||||
|
||||
/// <summary>Corridor north 20 yd then east 20 yd; returns the walk after it moved on from the corner.</summary>
|
||||
private static Walk Corner(float reach, float lookahead = 4.0f)
|
||||
{
|
||||
var w = new Walk(Route(RT.Once, Pt(20, 0), Pt(20, 20), Pt(20, 40)), reach, 0, 0, 0);
|
||||
w.S.NavLookaheadYards = lookahead;
|
||||
w.RunUntil(() => w.Idx >= 1 && w.E_ > 6);
|
||||
return w;
|
||||
}
|
||||
|
||||
private static double ClosestToCorner(Walk w) => w.Path.Min(p => Dist(p.N, p.E, 20, 0));
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void CornerTightReach()
|
||||
{
|
||||
var w = Corner(1.0f);
|
||||
Check.True(w.Idx >= 1, "moved on to the east leg");
|
||||
var onCorner = w.Path.Where(p => p.Idx == 0).ToList();
|
||||
var first = w.Path.FirstOrDefault(p => p.Idx >= 1);
|
||||
double atAdvance = Dist(first.N, first.E, 20, 0);
|
||||
Check.True(atAdvance <= 1.0, $"moved on within 1 yd of the corner point ({atAdvance:F2} yd)");
|
||||
double closest = ClosestToCorner(w);
|
||||
Check.True(closest <= 0.5, $"touched the point: came within {closest:F2} yd of it");
|
||||
// While the corner is the target the character runs straight up the corridor centre:
|
||||
// no turning east early.
|
||||
double drift = onCorner.Max(p => Math.Abs(p.E));
|
||||
Check.True(drift < 0.05, $"no early turn toward the next point ({drift:F2} yd off the centre line before arriving)");
|
||||
Check.False(w.Path.Any(p => p.N < 19 && p.E > 1), "never inside the corridor's inside wall corner (19 N, 1 E)");
|
||||
double over = w.Path.Max(p => p.N);
|
||||
Check.True(over < 21.0, $"no overshoot into the far wall at 21 N (got to {over:F2} N)");
|
||||
// No turning round: north never drops back more than a hair after its highest.
|
||||
double maxN = 0, back = 0;
|
||||
foreach (var p in w.Path) { maxN = Math.Max(maxN, p.N); back = Math.Max(back, maxN - p.N); }
|
||||
Check.True(back < 0.1, $"never walked back south ({back:F2} yd)");
|
||||
Check.Eq(LogCount("sweep-pass"), 0, "reached properly, not by a sweep pass");
|
||||
}
|
||||
|
||||
private static void CornerRoundingScales()
|
||||
{
|
||||
Check.Near(NavigationEngine.CornerLookaheadYards(4.0, 0.5), 0.0, 1e-9, "0.5 yd: no rounding");
|
||||
Check.Near(NavigationEngine.CornerLookaheadYards(4.0, 1.0), 0.0, 1e-9, "1 yd: no rounding");
|
||||
Check.True(NavigationEngine.CornerLookaheadYards(4.0, 1.5) <= 1.5, "1.5 yd default: rounding inside the reach, so none");
|
||||
Check.True(NavigationEngine.CornerLookaheadYards(4.0, 2.0) <= 2.0, "2 yd: still inside the reach, so none");
|
||||
Check.Near(NavigationEngine.CornerLookaheadYards(4.0, 3.0), 4.0, 1e-9, "3 yd: the 4 yd Lookahead setting");
|
||||
Check.Near(NavigationEngine.CornerLookaheadYards(4.0, 5.0), 4.0, 1e-9, "5 yd: the 4 yd Lookahead setting (as before)");
|
||||
Check.Near(NavigationEngine.CornerLookaheadYards(0.0, 5.0), 0.0, 1e-9, "Lookahead 0 is still off");
|
||||
Check.Near(NavigationEngine.CornerLookaheadYards(6.0, 5.0), 6.0, 1e-9, "a bigger Lookahead setting is used at a big reach");
|
||||
|
||||
// The default reach walks the corner like the 1 yd one: straight to the point.
|
||||
var w = Corner(1.5f);
|
||||
var onCorner = w.Path.Where(p => p.Idx == 0).ToList();
|
||||
Check.True(onCorner.Max(p => Math.Abs(p.E)) < 0.05, "1.5 yd: no early turn");
|
||||
var first = w.Path.First(p => p.Idx >= 1);
|
||||
Check.True(Dist(first.N, first.E, 20, 0) <= 1.5, "1.5 yd: moved on within 1.5 yd");
|
||||
Check.False(w.Path.Any(p => p.N < 19 && p.E > 1), "1.5 yd: no corner cut");
|
||||
}
|
||||
|
||||
private static void CornerWideReach()
|
||||
{
|
||||
// A 5 yd reach moves on 5 yd short of the corner and heads across it for the next point:
|
||||
// the open-area corner rounding a big reach has always given.
|
||||
var w = Corner(5.0f);
|
||||
Check.True(w.Idx >= 1, "moved on");
|
||||
var first = w.Path.First(p => p.Idx >= 1);
|
||||
double atAdvance = Dist(first.N, first.E, 20, 0);
|
||||
Check.True(atAdvance > 4.0 && atAdvance <= 5.0, $"moved on 4-5 yd short of the corner ({atAdvance:F2})");
|
||||
Check.True(w.Path.Any(p => p.N < 19 && p.E > 1), "rounded the corner (inside the 2 yd corridor's corner: fine in the open)");
|
||||
double maxN = 0, back = 0;
|
||||
foreach (var p in w.Path) { maxN = Math.Max(maxN, p.N); back = Math.Max(back, maxN - p.N); }
|
||||
Check.True(back < 0.1, $"never walked back south ({back:F2} yd)");
|
||||
}
|
||||
|
||||
private static void PassBySide()
|
||||
{
|
||||
// The character is carried past [0] 1.2 yd to its east (outside a 1 yd reach); the old
|
||||
// code saw the distance shrink then grow by under 0.3 yd a tick, so it turned round.
|
||||
var w = new Walk(Route(RT.Circular, Pt(10, 0), Pt(30, 0)), 1.0f, 0, 1.2, 0);
|
||||
void At(double n, double e) { w.N = n; w.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); }
|
||||
foreach (double n in new[] { 2.0, 5.0, 8.0, 9.5, 10.0 }) { At(n, 1.2); FakeHost.HeadingDeg = 0; w.Step(); }
|
||||
Check.Eq(w.Idx, 0, "level with the point, 1.2 yd off: not yet");
|
||||
At(10.4, 1.2); FakeHost.HeadingDeg = 0; w.Step();
|
||||
Check.Eq(w.Idx, 1, "just past it: counted as reached");
|
||||
Check.Eq(LogCount("passed [0]"), 1, "logged as a pass");
|
||||
At(10.8, 1.2); w.Step();
|
||||
Check.True(FakeHost.AutoRun, "still running");
|
||||
double h = FakeHost.HeadingDeg;
|
||||
Check.True(h < 20 || h > 340, $"heading on north to [1], not back to [0] ({h:F0})");
|
||||
|
||||
// Too far to the side is not a pass (2.5 yd sweep radius at a 1 yd reach).
|
||||
var far = new Walk(Route(RT.Circular, Pt(10, 0), Pt(30, 0)), 1.0f, 0, 3.0, 0);
|
||||
void AtF(double n, double e) { far.N = n; far.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); }
|
||||
foreach (double n in new[] { 2.0, 6.0, 9.0, 10.5, 12.0 }) { AtF(n, 3.0); FakeHost.HeadingDeg = 0; far.Step(); }
|
||||
Check.Eq(far.Idx, 0, "3 yd to the side: not passed");
|
||||
}
|
||||
|
||||
private static void CutIsNotAPass()
|
||||
{
|
||||
// Heading for the corner (20 N, 0 E) from the south, the character drifts east toward the
|
||||
// next point while still short of the corner: beyond the corner along the NEXT leg, but
|
||||
// the corner is not behind it, so it is not a pass.
|
||||
var w = new Walk(Route(RT.Once, Pt(20, 0), Pt(20, 20)), 1.0f, 0, 0, 0);
|
||||
void At(double n, double e) { w.N = n; w.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); }
|
||||
foreach (var (n, e) in new[] { (5.0, 0.0), (12.0, 0.5), (17.0, 1.5), (18.5, 2.0), (19.0, 2.2) })
|
||||
{
|
||||
At(n, e); w.Step();
|
||||
}
|
||||
Check.Eq(w.Idx, 0, "cutting toward the next point short of the corner never counts");
|
||||
Check.Eq(LogCount("passed [0]"), 0, "no pass logged");
|
||||
}
|
||||
|
||||
private static void FastRunSkipsOver()
|
||||
{
|
||||
// 15 yd/s at 10 frames a second: 1.5 yd a tick, three times the 0.5 yd reach's width.
|
||||
var w = new Walk(Route(RT.Once, Pt(20, 0.3), Pt(40, 0.3), Pt(60, 0.3)), 0.5f, 0, 0.3, 0);
|
||||
w.SpeedYdPerS = 15.0; w.TickMs = 100;
|
||||
w.RunUntil(() => w.Idx >= 1 && w.N > 25, 10);
|
||||
Check.True(w.Idx >= 1, "moved on");
|
||||
double maxN = 0, back = 0;
|
||||
foreach (var p in w.Path) { maxN = Math.Max(maxN, p.N); back = Math.Max(back, maxN - p.N); }
|
||||
Check.True(back < 0.1, $"never turned round ({back:F2} yd back)");
|
||||
}
|
||||
|
||||
private static void SweepUsesClosest()
|
||||
{
|
||||
// A slow pass by at about 2.3 yd (inside the 2.5 yd sweep radius of a 1 yd reach): the distance
|
||||
// grows 0.1 yd a tick, never 0.3 in one tick. The old check never fired.
|
||||
var w = new Walk(Route(RT.Circular, Pt(10, 0), Pt(10, 30)), 1.0f, 8, 2, 90);
|
||||
void At(double n, double e) { w.N = n; w.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); }
|
||||
// Coming from the south-east toward the point, then sliding away east (pushed along a wall).
|
||||
At(8.2, 1.4); w.Step(); // first tick: the approach starts here (2.3 yd)
|
||||
At(8.4, 1.6); w.Step();
|
||||
At(8.4, 1.8); w.Step();
|
||||
At(8.4, 2.0); w.Step();
|
||||
At(8.4, 2.2); w.Step();
|
||||
Check.Eq(w.Idx, 1, "0.3 yd beyond the closest approach (inside 2.5 yd): sweep pass");
|
||||
Check.Eq(LogCount("sweep-pass"), 1, "logged as a sweep pass");
|
||||
}
|
||||
|
||||
private static void DoorwayUnchanged()
|
||||
{
|
||||
// Doorway reach 1 yd, sweep 1.5 yd; the pass-through rule does not apply.
|
||||
var w = new Walk(Route(RT.Circular, Pt(10, 0, doorway: true), Pt(10, 10)), 1.5f, 0, 1.2, 0);
|
||||
void At(double n, double e) { w.N = n; w.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); }
|
||||
foreach (double n in new[] { 4.0, 8.0, 9.5, 10.4 }) { At(n, 1.2); FakeHost.HeadingDeg = 0; w.Step(); }
|
||||
Check.Eq(w.Idx, 0, "1.2 yd beside a doorway point and past it: not reached (doorways line up properly)");
|
||||
|
||||
// With the 5 yd reach a plain point would round the corner; a doorway point is walked straight.
|
||||
var d = new Walk(Route(RT.Once, Pt(20, 0, doorway: true), Pt(20, 20), Pt(20, 40)), 5.0f, 0, 0, 0);
|
||||
d.RunUntil(() => d.Idx >= 1 && d.E_ > 6);
|
||||
var onDoor = d.Path.Where(p => p.Idx == 0).ToList();
|
||||
Check.True(onDoor.Max(p => Math.Abs(p.E)) < 0.05, "doorway point: straight at it");
|
||||
var first = d.Path.First(p => p.Idx >= 1);
|
||||
Check.True(Dist(first.N, first.E, 20, 0) <= 1.0, "doorway point reached within 1 yd at a 5 yd reach");
|
||||
}
|
||||
}
|
||||
368
Tools/RynthCore.RynthAiHostTests/Tests/NoKillTests.cs
Normal file
368
Tools/RynthCore.RynthAiHostTests/Tests/NoKillTests.cs
Normal file
|
|
@ -0,0 +1,368 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Meta;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
using C = RynthCore.Plugin.RynthAi.LegacyUi.MetaConditionType;
|
||||
using A = RynthCore.Plugin.RynthAi.LegacyUi.MetaActionType;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// "No kills within X minutes" (2026-10-06): the plugin's KillClock, the expression
|
||||
// secondssincelastkill[] and the meta condition No Kills Within Minutes (.af NoKillsInMins).
|
||||
// The kill clock and MetaManager each run on a fake clock, moved together by Rig.Advance.
|
||||
internal static class NoKillTests
|
||||
{
|
||||
private static readonly DateTime T0 = new(2026, 10, 6, 2, 0, 0);
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("no-kill: secondssincelastkill[] counts from login, then the later of the last kill and the last macro start", FunctionClock);
|
||||
r.Add("no-kill: only KillerNotification counts, not death messages in chat", OnlyOurKills);
|
||||
r.Add("no-kill: the condition holds from N minutes without a kill", ConditionThreshold);
|
||||
r.Add("no-kill: bad minutes or no clock never hold", ConditionFailsClosed);
|
||||
r.Add("no-kill: NoKillsInMins survives an .af save and reload (also nested)", AfRoundTrip);
|
||||
r.Add("no-kill: survives the settings JSON; an unknown condition number loads and never holds", JsonRoundTrip);
|
||||
r.Add("no-kill: an unknown .af keyword loads as Never (how an older RynthAi reads NoKillsInMins)", UnknownKeywordFailsClosed);
|
||||
r.Add("no-kill: an editor save on a running meta doesn't re-fire it or reset the clock", AutosaveKeepsIt);
|
||||
r.Add("no-kill: the engine Meta editor's vocabulary matches MetaSchema", () => EngineVocabularyMatches());
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S = new() { IsMacroRunning = true, EnableMeta = true, CurrentState = "Default" };
|
||||
public readonly MetaManager M;
|
||||
public readonly KillClock K;
|
||||
public DateTime Now = T0;
|
||||
public long Ms;
|
||||
|
||||
public Rig(bool withClock = true, params MetaRule[] rules)
|
||||
{
|
||||
S.MetaRules = rules.ToList();
|
||||
M = new MetaManager(S, default, new PlayerVitalsCache()) { Clock = () => Now };
|
||||
K = new KillClock(() => Ms) { MacroRunning = () => S.IsMacroRunning };
|
||||
if (withClock) M.SetKillClock(K);
|
||||
}
|
||||
|
||||
public void Advance(double seconds)
|
||||
{
|
||||
Now = Now.AddSeconds(seconds);
|
||||
Ms += (long)Math.Round(seconds * 1000);
|
||||
}
|
||||
|
||||
public void Tick(double seconds = 0)
|
||||
{
|
||||
Advance(seconds);
|
||||
M.Think();
|
||||
}
|
||||
|
||||
public string Eval(string expr) => M.Expressions.Evaluate(expr);
|
||||
public string Var(string name) => M.Expressions.Variables.TryGetValue(name, out string? v) ? v : "(unset)";
|
||||
|
||||
/// <summary>One freshly armed tick with only this condition; did it fire? Time does not move.</summary>
|
||||
public bool Holds(MetaRule cond)
|
||||
{
|
||||
cond.State = S.CurrentState;
|
||||
cond.Action = A.ExpressionAction;
|
||||
cond.ActionData = "setvar[__hit, 1]";
|
||||
S.MetaRules = new List<MetaRule> { cond };
|
||||
M.Expressions.Evaluate("clearvar[__hit]");
|
||||
S.ForceStateReset = true;
|
||||
M.Think();
|
||||
return M.Expressions.Variables.ContainsKey("__hit");
|
||||
}
|
||||
|
||||
public bool Holds(string minutes) => Holds(NoKills(minutes));
|
||||
}
|
||||
|
||||
private static MetaRule NoKills(string minutes) => new() { Condition = C.NoKillsWithinMinutes, ConditionData = minutes };
|
||||
|
||||
private static MetaRule Mark(string state, C cond, string data, string v) => new()
|
||||
{
|
||||
State = state, Condition = cond, ConditionData = data,
|
||||
Action = A.ExpressionAction, ActionData = $"setvar[{v}, getvar[{v}]+1]",
|
||||
};
|
||||
|
||||
// ── secondssincelastkill[] ────────────────────────────────────────────
|
||||
|
||||
private static void FunctionClock()
|
||||
{
|
||||
var rig = new Rig();
|
||||
rig.S.IsMacroRunning = false;
|
||||
rig.Advance(5);
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "5", "macro never started: from login");
|
||||
Check.Eq(rig.K.Since, "login", "basis: login");
|
||||
Check.Eq(rig.K.SecondsSinceKillOnly(), -1, "status feed: no kill yet");
|
||||
|
||||
rig.S.IsMacroRunning = true;
|
||||
rig.Advance(5); // started at 10 s; nothing read until now
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "0", "macro just started: from the start");
|
||||
rig.Advance(2.5);
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "2", "whole seconds (2.5 -> 2)");
|
||||
Check.Eq(rig.K.Since, "macro start", "basis: macro start");
|
||||
|
||||
// A start between reads is still seen: the plugin tick observes the macro every tick.
|
||||
rig.S.IsMacroRunning = false;
|
||||
rig.K.ObserveMacro(false);
|
||||
rig.Advance(10);
|
||||
rig.S.IsMacroRunning = true;
|
||||
rig.K.ObserveMacro(true); // restarted at 22.5 s
|
||||
rig.Advance(3);
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "3", "a restart before any kill restarts the count");
|
||||
|
||||
rig.K.RecordKill(); // kill at 25.5 s
|
||||
rig.Advance(1.999);
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "1", "after a kill: since the kill");
|
||||
Check.Eq(rig.K.Since, "kill", "basis: kill");
|
||||
Check.Eq(rig.K.SecondsSinceKillOnly(), 1, "status feed: since the kill");
|
||||
|
||||
rig.S.IsMacroRunning = false;
|
||||
rig.K.ObserveMacro(false);
|
||||
rig.Advance(8);
|
||||
rig.S.IsMacroRunning = true;
|
||||
rig.Advance(1);
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "0", "a macro restart after a kill starts the count again");
|
||||
Check.Eq(rig.K.Since, "macro start", "basis: macro start");
|
||||
rig.Advance(10);
|
||||
Check.Eq(rig.Eval("secondssincelastkill[] >= 10"), "1", "usable in a comparison");
|
||||
Check.Eq(rig.Eval("SecondsSinceLastKill[]"), "10", "any case");
|
||||
|
||||
rig.K.SessionStarted(); // a new login
|
||||
rig.Advance(4);
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "4", "a new login forgets the old kill (macro already on: counts from login)");
|
||||
Check.False(rig.K.HasKill, "no kill this session");
|
||||
|
||||
var none = new Rig(withClock: false);
|
||||
none.Advance(600);
|
||||
Check.Eq(none.Eval("secondssincelastkill[]"), "0", "no clock wired: 0 (never 'a long time')");
|
||||
}
|
||||
|
||||
// ── Only our kills ────────────────────────────────────────────────────
|
||||
|
||||
private static void OnlyOurKills()
|
||||
{
|
||||
var p = new RynthAiPlugin();
|
||||
KillClock k = p.Kills;
|
||||
int eat = 0;
|
||||
foreach (string line in new[]
|
||||
{
|
||||
"You killed the Drudge Skulker!",
|
||||
"Drudge Skulker died.",
|
||||
"Your fellow Bob killed the Mite Scion!",
|
||||
"The Olthoi Soldier was killed by Bob.",
|
||||
"You have been slain!",
|
||||
})
|
||||
p.OnChatWindowText(line, 0, ref eat);
|
||||
Check.False(k.HasKill, "death messages in chat don't count as our kill");
|
||||
|
||||
p.OnKillNotification("");
|
||||
p.OnKillNotification(null);
|
||||
Check.False(k.HasKill, "an empty notification isn't a kill");
|
||||
|
||||
p.OnKillNotification("You killed the Drudge Skulker!");
|
||||
Check.True(k.HasKill, "KillerNotification (sent to the killer only) is our kill");
|
||||
Check.Eq(k.Since, "kill", "the clock counts from it");
|
||||
}
|
||||
|
||||
// ── The condition ─────────────────────────────────────────────────────
|
||||
|
||||
private static void ConditionThreshold()
|
||||
{
|
||||
var rig = new Rig();
|
||||
rig.Eval("secondssincelastkill[]"); // the macro start is seen at 0
|
||||
rig.Advance(59.999);
|
||||
Check.False(rig.Holds("1"), "59.999 s: not 1 minute yet");
|
||||
rig.Advance(0.001);
|
||||
Check.True(rig.Holds("1"), "60 s without a kill (from the macro start): holds");
|
||||
Check.True(rig.Holds("0.5"), "decimal minutes (0.5 = 30 s)");
|
||||
Check.True(rig.Holds("0,5"), "a comma decimal too");
|
||||
Check.True(rig.Holds(" 1 "), "spaces ignored");
|
||||
Check.False(rig.Holds("1.5"), "90 s: not yet");
|
||||
Check.True(rig.Holds("0"), "0 minutes: always");
|
||||
|
||||
rig.K.RecordKill();
|
||||
Check.False(rig.Holds("1"), "right after a kill: no");
|
||||
Check.False(rig.Holds("0.01"), "0.01 min, right after a kill: no");
|
||||
rig.Advance(119.999);
|
||||
Check.False(rig.Holds("2"), "just under 2 minutes after the kill");
|
||||
rig.Advance(0.001);
|
||||
Check.True(rig.Holds("2"), "2 minutes after the kill");
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "120", "same clock as the function");
|
||||
|
||||
// Nested like any other condition.
|
||||
Check.True(rig.Holds(new MetaRule { Condition = C.All, Children = { NoKills("1"), new MetaRule { Condition = C.Always } } }), "inside All");
|
||||
Check.False(rig.Holds(new MetaRule { Condition = C.Not, Children = { NoKills("1") } }), "Not of it");
|
||||
|
||||
// A rule fires once per state entry, like every condition.
|
||||
var latch = new Rig(true, Mark("Default", C.NoKillsWithinMinutes, "1", "n"));
|
||||
latch.Tick();
|
||||
latch.Tick(30);
|
||||
Check.Eq(latch.Var("n"), "(unset)", "not before a minute");
|
||||
latch.Tick(30);
|
||||
latch.Tick(30);
|
||||
Check.Eq(latch.Var("n"), "1", "fired once at a minute, latched after");
|
||||
}
|
||||
|
||||
private static void ConditionFailsClosed()
|
||||
{
|
||||
var rig = new Rig();
|
||||
rig.Eval("secondssincelastkill[]");
|
||||
rig.Advance(3600);
|
||||
foreach (string bad in new[] { "", " ", "abc", "-1", "5m", "NaN", "Infinity" })
|
||||
Check.False(rig.Holds(bad), $"'{bad}' never holds (an hour without a kill)");
|
||||
Check.True(rig.Holds("5"), "a real number does");
|
||||
|
||||
var none = new Rig(withClock: false);
|
||||
none.Advance(3600);
|
||||
Check.False(none.Holds("0"), "no kill clock wired: never holds");
|
||||
}
|
||||
|
||||
// ── Files ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void AfRoundTrip()
|
||||
{
|
||||
var rules = new List<MetaRule>
|
||||
{
|
||||
new() { State = "Default", Condition = C.NoKillsWithinMinutes, ConditionData = "2.5", Action = A.SetMetaState, ActionData = "Move" },
|
||||
new()
|
||||
{
|
||||
State = "Default", Condition = C.All, Action = A.ChatCommand, ActionData = "/say quiet",
|
||||
Children = { NoKills("5"), new MetaRule { Condition = C.NavrouteEmpty } },
|
||||
},
|
||||
new() { State = "Move", Condition = C.Not, Children = { NoKills("10") }, Action = A.SetMetaState, ActionData = "Default" },
|
||||
};
|
||||
string text = AfFileWriter.SaveToString(rules, new Dictionary<string, List<string>>());
|
||||
Check.True(text.Contains("NoKillsInMins 2.5"), "written as 'NoKillsInMins 2.5'");
|
||||
Check.False(text.Contains("Expr"), "not written as an expression");
|
||||
|
||||
LoadedMeta back = AfFileParser.LoadFromText(text);
|
||||
Check.Eq(back.Warnings.Count, 0, "loads without warnings");
|
||||
Check.Eq(back.Rules.Count, 3, "three rules back");
|
||||
MetaRule? top = back.Rules.FirstOrDefault(r => r.Condition == C.NoKillsWithinMinutes);
|
||||
Check.NotNull(top, "the top-level condition is back");
|
||||
if (top != null) Check.Eq(top.ConditionData, "2.5", "with its minutes");
|
||||
MetaRule? all = back.Rules.FirstOrDefault(r => r.Condition == C.All);
|
||||
Check.True(all != null && all.Children.Count == 2 && all.Children[0].Condition == C.NoKillsWithinMinutes
|
||||
&& all.Children[0].ConditionData == "5", "inside All");
|
||||
MetaRule? not = back.Rules.FirstOrDefault(r => r.Condition == C.Not);
|
||||
Check.True(not != null && not.Children.Count == 1 && not.Children[0].Condition == C.NoKillsWithinMinutes
|
||||
&& not.Children[0].ConditionData == "10", "under Not (same-line operand)");
|
||||
|
||||
string again = AfFileWriter.SaveToString(back.Rules, new Dictionary<string, List<string>>());
|
||||
Check.Eq(again, text, "a second save is identical");
|
||||
}
|
||||
|
||||
private static void JsonRoundTrip()
|
||||
{
|
||||
var s = new LegacyUiSettings();
|
||||
s.MetaRules.Add(new MetaRule { State = "Default", Condition = C.NoKillsWithinMinutes, ConditionData = "3", Action = A.ChatCommand, ActionData = "/say hi" });
|
||||
string json = JsonSerializer.Serialize(s, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
LegacyUiSettings? back = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(back != null && back.MetaRules.Count == 1 && back.MetaRules[0].Condition == C.NoKillsWithinMinutes
|
||||
&& back.MetaRules[0].ConditionData == "3", "the rule survives the settings JSON");
|
||||
Check.True(Regex.IsMatch(json, "\"Condition\":\\s*" + (int)C.NoKillsWithinMinutes), "stored as its number, like every condition");
|
||||
|
||||
// A condition number this build doesn't know (what an older RynthAi sees for 35): it loads
|
||||
// (System.Text.Json doesn't range-check enums) and the rule never fires.
|
||||
string future = Regex.Replace(json, "\"Condition\":\\s*" + (int)C.NoKillsWithinMinutes, "\"Condition\": 99");
|
||||
LegacyUiSettings? f = JsonSerializer.Deserialize(future, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(f != null && f.MetaRules.Count == 1 && (int)f.MetaRules[0].Condition == 99, "an unknown number loads");
|
||||
var rig = new Rig();
|
||||
rig.Eval("secondssincelastkill[]");
|
||||
rig.Advance(3600);
|
||||
Check.False(rig.Holds(new MetaRule { Condition = (C)99, ConditionData = "3" }), "and never holds");
|
||||
Check.Eq(MetaSchema.ConditionKeyword((C)99), "Never", "an .af save writes it as Never (never true)");
|
||||
}
|
||||
|
||||
private static void UnknownKeywordFailsClosed()
|
||||
{
|
||||
// An older RynthAi's AfFileParser has no NoKillsInMins: unknown keywords load as Never with a
|
||||
// warning (same code path, before 2026-10-06). Simulated with a keyword this build doesn't know.
|
||||
var rules = new List<MetaRule>
|
||||
{
|
||||
new() { State = "Default", Condition = C.NoKillsWithinMinutes, ConditionData = "1", Action = A.ExpressionAction, ActionData = "setvar[x, 1]" },
|
||||
};
|
||||
string text = AfFileWriter.SaveToString(rules, new Dictionary<string, List<string>>()).Replace("NoKillsInMins", "NoKillsInMinsV2");
|
||||
LoadedMeta back = AfFileParser.LoadFromText(text);
|
||||
Check.Eq(back.Rules.Count, 1, "the rule still loads");
|
||||
Check.Eq(back.Rules[0].Condition, C.Never, "as Never");
|
||||
Check.True(back.Warnings.Any(w => w.Contains("NoKillsInMinsV2")), "with a warning naming the keyword");
|
||||
|
||||
var rig = new Rig(true, back.Rules.ToArray());
|
||||
rig.Tick();
|
||||
rig.Tick(3600);
|
||||
Check.Eq(rig.Var("x"), "(unset)", "and never fires");
|
||||
}
|
||||
|
||||
// ── Editor autosave (MetaRuleEdits, update_rule) ─────────────────────
|
||||
|
||||
private static void AutosaveKeepsIt()
|
||||
{
|
||||
var rig = new Rig(true,
|
||||
Mark("Default", C.NoKillsWithinMinutes, "1", "nk"),
|
||||
Mark("Default", C.NoKillsWithinMinutes, "5", "late"));
|
||||
rig.Tick();
|
||||
rig.Tick(61);
|
||||
Check.Eq(rig.Var("nk"), "1", "fired after a minute without a kill");
|
||||
long before = rig.K.ElapsedMs();
|
||||
|
||||
// The editor's autosave: an edited copy of rule 0 (new minutes), then the structural bump.
|
||||
Check.True(MetaRuleEdits.Replace(rig.S.MetaRules, 0, Mark("Default", C.NoKillsWithinMinutes, "0.5", "nk")), "replaced");
|
||||
rig.S.MetaRulesStructuralVersion++;
|
||||
rig.Tick();
|
||||
Check.Eq(rig.Var("nk"), "1", "the saved rule did not fire again (latch kept)");
|
||||
Check.Eq(rig.K.ElapsedMs(), before, "the kill clock didn't move");
|
||||
Check.Eq(rig.S.MetaRules[0].ConditionData, "0.5", "the new minutes are in");
|
||||
|
||||
// An unfired rule saved with a lower threshold fires on the same clock (nothing restarted).
|
||||
Check.Eq(rig.Var("late"), "(unset)", "the 5-minute rule hasn't fired at 61 s");
|
||||
MetaRuleEdits.Replace(rig.S.MetaRules, 1, Mark("Default", C.NoKillsWithinMinutes, "1", "late"));
|
||||
rig.S.MetaRulesStructuralVersion++;
|
||||
rig.Tick();
|
||||
Check.Eq(rig.Var("late"), "1", "lowered to 1 minute: fires now, the 61 s weren't reset");
|
||||
Check.Eq(rig.S.CurrentState, "Default", "state unchanged");
|
||||
}
|
||||
|
||||
// ── Engine vocabulary drift ───────────────────────────────────────────
|
||||
|
||||
private static void EngineVocabularyMatches([CallerFilePath] string here = "")
|
||||
{
|
||||
// The engine's MetaVocabulary (RynthCore UI/Data/MetaData.cs) is indexed by the enum number
|
||||
// and can't reference the plugin; read its arrays from the side-by-side engine source.
|
||||
string path = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(here)!, "..", "..", "..", "..", "RynthCore",
|
||||
"src", "RynthCore.Engine", "UI", "Data", "MetaData.cs"));
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
Check.True(false, $"engine source not found at {path} (RynthCore must sit beside RynthSuite)");
|
||||
return;
|
||||
}
|
||||
string src = File.ReadAllText(path);
|
||||
string[] keywords = ArrayIn(src, "ConditionKeywords");
|
||||
string[] names = ArrayIn(src, "ConditionNames");
|
||||
string[] hints = ArrayIn(src, "ConditionHints");
|
||||
Check.Eq(keywords.Length, MetaSchema.Conditions.Length, "as many engine keywords as conditions");
|
||||
Check.Eq(names.Length, MetaSchema.Conditions.Length, "as many engine names as conditions");
|
||||
Check.Eq(hints.Length, MetaSchema.Conditions.Length, "as many engine hints as conditions");
|
||||
for (int i = 0; i < Math.Min(keywords.Length, MetaSchema.Conditions.Length); i++)
|
||||
Check.Eq(keywords[i], MetaSchema.Conditions[i].Keyword, $"keyword {i}");
|
||||
int nk = (int)C.NoKillsWithinMinutes;
|
||||
Check.Eq(nk, 35, "No Kills Within Minutes is 35 (engine MetaRuleEdit.NoKillsWithinMinutes)");
|
||||
if (names.Length > nk) Check.Eq(names[nk], MetaSchema.Conditions[nk].Label, "same label in the editor");
|
||||
}
|
||||
|
||||
private static string[] ArrayIn(string src, string name)
|
||||
{
|
||||
int i = src.IndexOf("string[] " + name, StringComparison.Ordinal);
|
||||
if (i < 0) return Array.Empty<string>();
|
||||
int j = src.IndexOf("};", i, StringComparison.Ordinal);
|
||||
string body = Regex.Replace(src.Substring(i, j - i), "//[^\n]*", "");
|
||||
int open = body.IndexOf('{');
|
||||
return Regex.Matches(body.Substring(open), "\"([^\"]*)\"").Select(m => m.Groups[1].Value).ToArray();
|
||||
}
|
||||
}
|
||||
|
|
@ -34,6 +34,8 @@ internal static class OffhandTests
|
|||
r.Add("offhand: two-hander -> the shield comes off first, back on with a one-hander", TwoHanderShieldOff);
|
||||
r.Add("offhand: bow -> the shield comes off, then the arrows still go on", BowShieldOffThenAmmo);
|
||||
r.Add("offhand: a caster -> the shield comes off first (swap gate held)", CasterShieldOff);
|
||||
r.Add("swap speed: a weapon in hand -> one use of the wand (the client swaps); the pack move only as the fallback", CasterDirectSwap);
|
||||
r.Add("swap speed: the gate lets the next step go once the server is done, else after 3 s", SwapGateSettles);
|
||||
r.Add("offhand: dual wield with the Dual Wield skill", DualWield);
|
||||
r.Add("offhand: no Dual Wield skill -> the shield", NoSkillShield);
|
||||
r.Add("offhand: None -> hands off (a worn shield is never taken off)", NoneHandsOff);
|
||||
|
|
@ -331,6 +333,61 @@ internal static class OffhandTests
|
|||
Check.Eq(FakeHost.Wields.Count, 0, "no shield with a caster");
|
||||
}
|
||||
|
||||
// 2026-10-06: Drakkon's axe -> wand took 4.2 s: the axe into the pack (1.2 s), then the swap
|
||||
// gate's flat 3 s before the wand. A use of the wand (the client's double-click) swaps by itself.
|
||||
private static void CasterDirectSwap()
|
||||
{
|
||||
var rig = new Rig(); // the sword in hand
|
||||
rig.List(Wand);
|
||||
rig.C.CanCastOverride = _ => true;
|
||||
Check.False(rig.Tick(), "not ready");
|
||||
Check.True(FakeHost.Uses.Contains(Wand), "UseObject(wand) with the sword still in hand");
|
||||
Check.Eq(FakeHost.Moves.Count, 0, "no pack move first");
|
||||
|
||||
// The use didn't swap in 2 s (SwapTracker retries at 2.5 s): the sword goes into the pack first from now on.
|
||||
var since = typeof(CombatManager).GetField("_combatDirectSwapSince", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
since.SetValue(rig.C, DateTime.Now.AddSeconds(-3));
|
||||
rig.C.SwapTracker.Reset(); // its 2.5 s resolve time is up
|
||||
rig.Tick();
|
||||
Check.True(FakeHost.Moves.Any(m => m.Id == Sword), "fallback: the sword into the pack");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("from now on the weapon goes into a pack first")), "logged once");
|
||||
}
|
||||
|
||||
private static void SwapGateSettles()
|
||||
{
|
||||
long t = 0;
|
||||
bool idle = true;
|
||||
var wielded = new Dictionary<int, bool> { [7] = true };
|
||||
var g = new WeaponSwapGate { NowMs = () => t, ServerIdle = () => idle, IsWielded = id => wielded[id] };
|
||||
Check.True(g.TryBeginSwap("shield off"), "first swap");
|
||||
g.NoteMove(7, wieldedNow: true);
|
||||
t = 500;
|
||||
Check.False(g.TryBeginSwap("weapon"), "the shield is still in hand");
|
||||
wielded[7] = false;
|
||||
t = 2999;
|
||||
Check.False(g.TryBeginSwap("weapon"), "a pack move: the full 3 s even once it reads done (the server's unwield motion, 13:58 wedge)");
|
||||
t = 3000;
|
||||
Check.True(g.TryBeginSwap("weapon"), "after 3 s");
|
||||
long claims = g.Claims;
|
||||
t = 3300;
|
||||
Check.False(g.TryBeginSwap("off hand"), "a use (the weapon): under the 400 ms floor");
|
||||
Check.Eq(g.Claims, claims, "a refused claim doesn't count");
|
||||
t = 3600;
|
||||
idle = false;
|
||||
Check.False(g.TryBeginSwap("off hand"), "the weapon's use is still unanswered");
|
||||
idle = true;
|
||||
Check.True(g.TryBeginSwap("off hand"), "answered: the off hand goes");
|
||||
|
||||
// No pacing (ServerIdle unset): the flat 3 s, as before.
|
||||
t = 0;
|
||||
var flat = new WeaponSwapGate { NowMs = () => t };
|
||||
Check.True(flat.TryBeginSwap("a"), "first");
|
||||
t = 2999;
|
||||
Check.False(flat.TryBeginSwap("b"), "inside 3 s");
|
||||
t = 3000;
|
||||
Check.True(flat.TryBeginSwap("b"), "after 3 s");
|
||||
}
|
||||
|
||||
private static void DualWield()
|
||||
{
|
||||
var rig = new Rig(dualWieldSkill: true);
|
||||
|
|
|
|||
198
Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs
Normal file
198
Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
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;
|
||||
|
||||
// Pet essence refill loop (2026-10-05; spotted by Silentkelpie, rynth PR #1). PetManager decides
|
||||
// "empty, refill it" from the essence's Structure read alone. When that read is stale (0 while the
|
||||
// server holds a full essence), the server answers "This essence is already full." and PetManager
|
||||
// went idle, read 0 again a second later and refilled again: a refill every couple of seconds,
|
||||
// each one forcing peace mode and a clap (ACE PetDevice refill), for as long as the read stayed
|
||||
// stale. A confirmed refill ("You add the spirit to the essence.") with a read that stays 0 burned
|
||||
// a spirit every time. Now the server's reply wins over the read until a summon says the essence
|
||||
// really is empty, the essence is re-identified after a refill, and an essence refilled twice in
|
||||
// 2 minutes that still reads empty is parked for 5 minutes.
|
||||
internal static class PetRefillTests
|
||||
{
|
||||
private const uint Player = 0x50000D01;
|
||||
private const uint Mob = 0x80300010;
|
||||
private const uint Essence = 0x80300001;
|
||||
private const uint Spirit = 0x80300002;
|
||||
private const uint StructureKey = 92; // AcIntProperty.Structure
|
||||
private const uint Lb = 0xA9B40000;
|
||||
|
||||
private const string AlreadyFull = "This essence is already full.";
|
||||
private const string Added = "You add the spirit to the essence.";
|
||||
private const string NoCharges = "Your summoning device does not have enough charges to function!";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("pets: a charged essence summons; an empty one is refilled once, then summons", NormalPath);
|
||||
r.Add("pets: stale empty read + 'already full' -> summon, not another refill (the loop)", AlreadyFullLoop);
|
||||
r.Add("pets: confirmed refill with a read that stays empty does not burn more spirits", AddedButStale);
|
||||
r.Add("pets: 'not enough charges' after a confirmed refill ends the trust; refill again", TrustEndsOnEmptySummon);
|
||||
r.Add("pets: refilled twice in 2 min and still empty (no reply) -> parked 5 min", SilentRefillsParked);
|
||||
r.Add("pets: the server's 'full' trust expires after 30 min", TrustExpires);
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────
|
||||
|
||||
private sealed class Rig : IDisposable
|
||||
{
|
||||
public long Now = 1_000_000;
|
||||
public readonly LegacyUiSettings S = new() { SummonPets = true, MonsterRange = 20, CustomPetRange = 5, PetAutoRefill = true };
|
||||
public readonly PetManager Pets;
|
||||
|
||||
public Rig(int charges)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true; // UseObject (summon), RequestId (re-identify)
|
||||
FakeHost.UseOnCalls = true; // UseObjectOn (spirit on essence)
|
||||
Place(Player, "Pet Tester", 96, 96, creature: false);
|
||||
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
Place(Mob, "Drudge Skulker", 96, 99, creature: true); // 3 m north
|
||||
FakeHost.Names[Essence] = "Fire Moar Essence (50)";
|
||||
FakeHost.Containers[Essence] = Player;
|
||||
FakeHost.Names[Spirit] = "Encapsulated Spirit";
|
||||
FakeHost.Containers[Spirit] = Player;
|
||||
SetCharges(charges);
|
||||
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = FakeHost.MakeCache(host, Player, new[] { Mob, Essence, Spirit });
|
||||
S.IsMacroRunning = true;
|
||||
S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Essence), Name = "Fire Moar Essence (50)", Type = "Pet" });
|
||||
var combat = new CombatManager(host, S, cache);
|
||||
combat.SetPlayerId(Player);
|
||||
combat.ScanNearbyTargets();
|
||||
Check.True(combat.ScannedTargets.Count == 1, "rig: the monster is scanned");
|
||||
PetManager.Clock = () => Now;
|
||||
Pets = new PetManager(host, S, cache, combat, null);
|
||||
}
|
||||
|
||||
private static void Place(uint id, string name, float x, float y, bool creature)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f);
|
||||
if (creature) FakeHost.ItemTypes[id] = 0x10;
|
||||
}
|
||||
|
||||
public static void SetCharges(int charges)
|
||||
{
|
||||
if (charges < 0) FakeHost.Ints.Remove((Essence, StructureKey));
|
||||
else FakeHost.Ints[(Essence, StructureKey)] = charges;
|
||||
}
|
||||
|
||||
/// <summary>Runs the heartbeat for <paramref name="ms"/> of fake time in 100 ms steps.</summary>
|
||||
public void Run(long ms)
|
||||
{
|
||||
for (long t = 0; t < ms; t += 100)
|
||||
{
|
||||
Now += 100;
|
||||
Pets.OnHeartbeat(0);
|
||||
}
|
||||
}
|
||||
|
||||
public void Chat(string line) => Pets.OnChatWindowText(line);
|
||||
|
||||
public int Refills => FakeHost.UsesOn.Count(u => u.Source == Spirit && u.Target == Essence);
|
||||
public int Summons => FakeHost.Uses.Count(u => u == Essence);
|
||||
|
||||
public void Dispose() => PetManager.Clock = static () => Environment.TickCount64;
|
||||
}
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void NormalPath()
|
||||
{
|
||||
using (var rig = new Rig(charges: 50))
|
||||
{
|
||||
rig.Run(1500);
|
||||
Check.Eq(rig.Summons, 1, "a charged essence: one summon");
|
||||
Check.Eq(rig.Refills, 0, "a charged essence: no refill");
|
||||
}
|
||||
|
||||
using (var rig = new Rig(charges: 0))
|
||||
{
|
||||
rig.Run(1500);
|
||||
Check.Eq(rig.Refills, 1, "an empty essence: one refill");
|
||||
Check.Eq(rig.Summons, 0, "an empty essence: no summon yet");
|
||||
Rig.SetCharges(50); // the server's Structure update lands
|
||||
rig.Chat(Added);
|
||||
rig.Run(1500);
|
||||
Check.Eq(rig.Refills, 1, "after the refill: still one refill");
|
||||
Check.Eq(rig.Summons, 1, "after the refill: it summons");
|
||||
Check.True(FakeHost.IdRequests.Contains(Essence), "the essence is re-identified after a refill");
|
||||
}
|
||||
}
|
||||
|
||||
private static void AlreadyFullLoop()
|
||||
{
|
||||
using var rig = new Rig(charges: 0); // the read says empty and never changes
|
||||
rig.Run(1500);
|
||||
Check.Eq(rig.Refills, 1, "the empty read starts one refill");
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
rig.Chat(AlreadyFull); // the server: it was full all along
|
||||
rig.Run(2000);
|
||||
}
|
||||
Check.Eq(rig.Refills, 1, "the server said full: no further refills over 20 s");
|
||||
Check.True(rig.Summons >= 1, "it summons from the essence the server called full");
|
||||
Check.True(FakeHost.IdRequests.Contains(Essence), "the stale essence is re-identified");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("already full", StringComparison.OrdinalIgnoreCase)), "the stale read is logged");
|
||||
}
|
||||
|
||||
private static void AddedButStale()
|
||||
{
|
||||
using var rig = new Rig(charges: 0);
|
||||
rig.Run(1500);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
rig.Chat(Added); // each reply would be a spirit spent
|
||||
rig.Run(2000);
|
||||
}
|
||||
Check.Eq(rig.Refills, 1, "one spirit spent, not one per think tick");
|
||||
Check.True(rig.Summons >= 1, "it summons after the confirmed refill");
|
||||
}
|
||||
|
||||
private static void TrustEndsOnEmptySummon()
|
||||
{
|
||||
using var rig = new Rig(charges: 0);
|
||||
rig.Run(1500);
|
||||
rig.Chat(AlreadyFull);
|
||||
rig.Run(1500);
|
||||
Check.Eq(rig.Summons, 1, "trusting the server, it summons");
|
||||
rig.Chat(NoCharges); // the summon says it really is empty
|
||||
rig.Run(1500);
|
||||
Check.Eq(rig.Refills, 2, "really empty: refilled again");
|
||||
}
|
||||
|
||||
private static void SilentRefillsParked()
|
||||
{
|
||||
using var rig = new Rig(charges: 0); // no reply ever arrives, the read stays 0
|
||||
rig.Run(10 * 60_000);
|
||||
// Before: a refill every ~38 s (8 s timeout + 30 s park) = about 16 in 10 minutes.
|
||||
// Now: two refills, a 5 minute park, two refills, a park.
|
||||
Check.True(rig.Refills <= 4, $"at most 4 refills in 10 minutes (got {rig.Refills})");
|
||||
Check.True(rig.Refills >= 2, $"it still tries to refill (got {rig.Refills})");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("parking", StringComparison.OrdinalIgnoreCase)), "the park is logged");
|
||||
}
|
||||
|
||||
private static void TrustExpires()
|
||||
{
|
||||
using var rig = new Rig(charges: 0);
|
||||
rig.Run(1500);
|
||||
rig.Chat(AlreadyFull);
|
||||
rig.Run(1500);
|
||||
int refills = rig.Refills;
|
||||
Check.Eq(refills, 1, "trusted: no second refill");
|
||||
// No summon lands (no pet appears, the read never moves): each summon times out and
|
||||
// parks the essence for 30 s. After 30 minutes the trust is gone and the read rules.
|
||||
rig.Run(31 * 60_000);
|
||||
Check.True(rig.Refills > refills, "after 30 minutes the empty read is believed again");
|
||||
}
|
||||
}
|
||||
127
Tools/RynthCore.RynthAiHostTests/Tests/T11LootTests.cs
Normal file
127
Tools/RynthCore.RynthAiHostTests/Tests/T11LootTests.cs
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
using RynthCore.Loot;
|
||||
using RynthCore.Loot.T11;
|
||||
using RynthCore.Loot.VTank;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.Loot;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
using N = RynthCore.Loot.VTank.VTankNodeTypes;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// T11 (ACECustom tier 11+) items through the real evaluator: the virtual T11 keys answered by
|
||||
// WorldObject.Values, the wield requirement and ratings the server strips put back from the
|
||||
// item text, and "Can Wield" fed by the "/aug" reply.
|
||||
internal static class T11LootTests
|
||||
{
|
||||
private const string WeaponLongDesc =
|
||||
"Property Details:\n" +
|
||||
"- Weapon Grade: A- (91% of max damage)\n" +
|
||||
"- Wield requires: 2,500 Item Augmentations\n" +
|
||||
"\n" +
|
||||
"Modifiers:\n" +
|
||||
"- Damage Rating +30 [14-69]\n" +
|
||||
"- Crit Chance +4 [1-8]\n";
|
||||
|
||||
private const string ArmorUse =
|
||||
"Modifiers:\n" +
|
||||
"- Damage Resist +6 [2-12]\n" +
|
||||
"- Max Health +100 [40-200]\n";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("loot t11: virtual keys read the item text", VirtualKeys);
|
||||
r.Add("loot t11: stripped wield requirement 158/159/160 restored", StrippedWield);
|
||||
r.Add("loot t11: modifier ratings feed Gear* keys and TotalRatings", ModifierRatings);
|
||||
r.Add("loot t11: a live rating wins over the modifier text", LiveRatingWins);
|
||||
r.Add("loot t11: retail items are untouched", RetailUntouched);
|
||||
r.Add("loot t11: Can Wield from the /aug reply and the override", CanWield);
|
||||
}
|
||||
|
||||
private static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
|
||||
|
||||
private static bool M(WorldObject item, params VTankLootCondition[] conds)
|
||||
{
|
||||
var rule = new VTankLootRule { Name = "r", Action = VTankLootAction.Keep };
|
||||
rule.Conditions.AddRange(conds);
|
||||
return VTankLootEvaluator.Match(rule, item);
|
||||
}
|
||||
|
||||
private static string K(int key) => key.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
private static Item Weapon() => new Item("T11 - Tachi", AcObjectClass.MeleeWeapon).Str(16, WeaponLongDesc);
|
||||
|
||||
private static void VirtualKeys()
|
||||
{
|
||||
T11ItemSupport.Reset();
|
||||
WorldObject w = Weapon();
|
||||
Check.Eq(w.Values(T11Keys.IsT11, -5), 1, "IsT11");
|
||||
Check.Eq(w.Values(T11Keys.EstimatedTier, -5), 12, "2,500 gate = T12");
|
||||
Check.Eq(w.Values(T11Keys.WeaponGrade, -5), 13, "A- = 13");
|
||||
Check.True(M(w, C(N.LongValKeyGE, "12", K(T11Keys.WeaponGrade))), "rule: grade B+ or better");
|
||||
Check.False(M(w, C(N.LongValKeyGE, "14", K(T11Keys.WeaponGrade))), "rule: grade A or better");
|
||||
Check.True(M(w, C(N.LongValKeyGE, "25", K(T11Keys.ForModifier(28)))), "rule: Damage Rating mod >= 25");
|
||||
Check.True(M(w, C(N.LongValKeyE, "0", K(T11Keys.ZoneLocked))), "rule: not zone locked");
|
||||
Check.Eq(w.Values(T11Keys.Base + 0x1FF, -5), -5, "unused virtual id = default");
|
||||
Check.Eq(new Item("Tachi").Wo.Values(T11Keys.IsT11, -5), 0, "retail item: IsT11 = 0");
|
||||
}
|
||||
|
||||
private static void StrippedWield()
|
||||
{
|
||||
T11ItemSupport.Reset();
|
||||
WorldObject w = Weapon();
|
||||
Check.Eq(w.Values(158, 0), T11Keys.WieldRequirementInt64Stat, "158 = Int64 Property");
|
||||
Check.Eq(w.Values(159, 0), 9008, "159 = item augs");
|
||||
Check.Eq(w.Values(160, 0), 2500, "160 = gate");
|
||||
Check.True(M(w, C(N.LongValKeyLE, "2500", "160")), "rule: wield difficulty <= 2500");
|
||||
Check.False(M(w, C(N.LongValKeyLE, "2000", "160")), "rule: wield difficulty <= 2000");
|
||||
Check.Eq(w.Values(161, -1), -1, "other keys keep the default");
|
||||
}
|
||||
|
||||
private static void ModifierRatings()
|
||||
{
|
||||
T11ItemSupport.Reset();
|
||||
WorldObject w = Weapon();
|
||||
Check.Eq(w.Values(370, 0), 30, "370 Damage Rating from text");
|
||||
Check.Eq(w.Values(372, 0), 4, "372 Crit from text");
|
||||
Check.True(M(w, C(N.TotalRatingsGE, "34")), "TotalRatings counts modifier ratings");
|
||||
Check.False(M(w, C(N.TotalRatingsGE, "35")), "TotalRatings exact");
|
||||
|
||||
WorldObject armor = new Item("T11 - Celdon Breastplate", AcObjectClass.Armor).Str(14, ArmorUse);
|
||||
Check.Eq(armor.Values(371, 0), 6, "371 from the Use string");
|
||||
Check.True(M(armor, C(N.TotalRatingsGE, "106")), "armor TotalRatings 371 + 379");
|
||||
}
|
||||
|
||||
private static void LiveRatingWins()
|
||||
{
|
||||
T11ItemSupport.Reset();
|
||||
WorldObject w = Weapon().Int(370, 7);
|
||||
Check.Eq(w.Values(370, 0), 7, "a property the item has is never replaced");
|
||||
}
|
||||
|
||||
private static void RetailUntouched()
|
||||
{
|
||||
T11ItemSupport.Reset();
|
||||
WorldObject retail = new Item("Tachi", AcObjectClass.MeleeWeapon).Str(16, WeaponLongDesc);
|
||||
Check.Eq(retail.Values(160, 0), 0, "no T11 prefix: no stripped-key fallback");
|
||||
Check.Eq(retail.Values(370, -1), -1, "no T11 prefix: rating default kept");
|
||||
}
|
||||
|
||||
private static void CanWield()
|
||||
{
|
||||
T11ItemSupport.Reset();
|
||||
WorldObject w = Weapon();
|
||||
Check.Eq(w.Values(T11Keys.CanWield, -5), -1, "unknown before /aug");
|
||||
T11ItemSupport.OnChat("Advanced Augmentation Levels:");
|
||||
T11ItemSupport.OnChat("Item:2,400");
|
||||
Check.Eq(w.Values(T11Keys.CanWield, -5), 0, "2,400 < 2,500");
|
||||
Check.False(M(w, C(N.LongValKeyE, "1", K(T11Keys.CanWield))), "rule: wieldable fails");
|
||||
T11ItemSupport.SyncOverride(2500);
|
||||
Check.Eq(w.Values(T11Keys.CanWield, -5), 1, "override 2,500 meets the gate");
|
||||
T11ItemSupport.SyncOverride(-1);
|
||||
Check.Eq(w.Values(T11Keys.CanWield, -5), 0, "back to the /aug count");
|
||||
Check.Eq(new Item("T11 - Robe").Wo.Values(T11Keys.CanWield, -5), -1, "not appraised yet: unknown");
|
||||
Check.Eq(new Item("T11 - Robe").Str(16, "A robe.").Wo.Values(T11Keys.CanWield, -5), 1, "appraised, no gate: wieldable");
|
||||
T11ItemSupport.Reset();
|
||||
}
|
||||
}
|
||||
693
Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs
Normal file
693
Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs
Normal file
|
|
@ -0,0 +1,693 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Loot;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-10-06, Drakkon on DreamWeave: from 06:18:44 every corpse/door use got the server's UseDone
|
||||
// (no error) about one round trip later and nothing opened; a relog fixed it. The bot kept
|
||||
// hammering corpses for 13 minutes. These tests cover:
|
||||
// - UseRefusalWatch: answered-but-nothing-opened opens -> one clean stop and retry -> "the server
|
||||
// isn't letting this character use objects" once, then a back-off with quiet probes;
|
||||
// - the same through RynthAi's corpse looting (fake clock, fake server);
|
||||
// - the trigger side: a corpse open waits for the arbiter's Looting tick, RynthAi's moves and
|
||||
// turns wait while a door/corpse use is in flight, and Combat's idle peace swap waits while
|
||||
// looting has work (on ACE a move or a mode change cancels the server's walk/turn to the corpse).
|
||||
internal static class UseRefusalTests
|
||||
{
|
||||
private const uint Player = 0x50000D01;
|
||||
private const uint CorpseA = 0x80068ACE;
|
||||
private const uint CorpseB = 0x80072023;
|
||||
private const uint ItemTypeContainer = 0x200;
|
||||
private const uint LongDescKey = 16;
|
||||
private const string Me = "Drakkon";
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private const string StuckLine = "isn't letting this character use objects";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("use check: three answered opens with nothing opened -> clean stop; a second corpse refused too -> stuck; probes back off; an open recovers", WatchEscalates);
|
||||
r.Add("use check: one corpse that never opens is dropped, not reported as a stuck server", WatchDropsSingleCorpse);
|
||||
r.Add("use check: a UseDone with an error, or no UseDone at all, counts as no refusal", WatchIgnoresErrorsAndSilence);
|
||||
r.Add("use check: the next open settles an answered one that opened nothing; an open resets", WatchSettlesOnNextOpen);
|
||||
r.Add("use check (looting): Drakkon's stall - stop once, retry, say it once in chat, stop opening corpses, probe, recover", LootingStall);
|
||||
r.Add("use check (looting): normal opens never trip it", LootingNormalOpens);
|
||||
r.Add("flight recorder: the use check asks the engine for a dump (clean stop, stuck); normal opens never do", FlightDumpRequests);
|
||||
r.Add("corpse open: a corpse claimed while Combat owns the tick is opened only on the Looting tick", OpenWaitsForLootingTick);
|
||||
r.Add("move hold: while a corpse use is in flight RynthAi's moves and turns wait, stops go through, UseDone or 1.5 s releases", MoveHoldWhileUseInFlight);
|
||||
r.Add("move hold: off unless the plugin opts in (RynthNav, RynthLua unchanged)", MoveHoldOptIn);
|
||||
r.Add("idle peace: Combat's idle peace swap waits while looting has work", IdlePeaceHeldWhileLooting);
|
||||
r.Add("idle peace: looting has work = a corpse claimed, a corpse open, a corpse in range, or a use in flight", LootHoldsIdlePeaceInputs);
|
||||
r.Add("use check jump: one jump per back-off, before the probe; none while normal or during the back-off", WatchProbeJump);
|
||||
r.Add("use check jump (looting): the clean stop jumps (TapJump, not JumpNonAutonomous), the retry waits the pause, an open after it is logged as cleared", LootingStallJumpClears);
|
||||
r.Add("use check jump (looting): still stuck after the jump -> back-off; the probe goes out only after a jump and the pause", LootingStallJumpBeforeProbe);
|
||||
r.Add("use check jump: no jump while the server still owes an answer to a cast (a jump would fail it)", NoJumpWhilePacerOutstanding);
|
||||
}
|
||||
|
||||
// ── UseRefusalWatch alone ─────────────────────────────────────────────────
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly UseRefusalWatch W = new();
|
||||
public long T = 1_000_000;
|
||||
public int Seq;
|
||||
|
||||
/// <summary>One open of <paramref name="id"/>: answered (UseDone err 0) after 60 ms, nothing opens.
|
||||
/// Returns the verdict of the tick after the grace.</summary>
|
||||
public UseRefusalWatch.Verdict RefusedOpen(int id)
|
||||
{
|
||||
var settle = W.SettleBeforeOpen(T);
|
||||
if (settle != UseRefusalWatch.Verdict.None) return settle;
|
||||
W.OnOpenSent(id, T, Seq);
|
||||
T += 60; Seq++;
|
||||
Check.Eq(W.OnTick(T, Seq, 0, true), UseRefusalWatch.Verdict.None, "answered: no verdict yet");
|
||||
T += UseRefusalWatch.AnswerGraceMs;
|
||||
var v = W.OnTick(T, Seq, 0, true);
|
||||
T += 500;
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
private static void WatchEscalates()
|
||||
{
|
||||
var r = new Rig();
|
||||
int a = unchecked((int)CorpseA), b = unchecked((int)CorpseB);
|
||||
Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.None, "refusal 1");
|
||||
Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.None, "refusal 2");
|
||||
Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.CleanStopAndRetry, "refusal 3: clean stop and retry");
|
||||
Check.Eq(r.W.State, UseRefusalWatch.Phase.Retrying, "retrying");
|
||||
Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.DropCorpse, "the retry refused on the same corpse: drop that corpse");
|
||||
Check.Eq(r.RefusedOpen(b), UseRefusalWatch.Verdict.Stuck, "a second corpse refused: the server refuses every use");
|
||||
Check.Eq(r.W.State, UseRefusalWatch.Phase.Stuck, "stuck");
|
||||
Check.Eq(r.W.BackoffMs, UseRefusalWatch.FirstBackoffMs, "first back-off");
|
||||
Check.True(r.W.HoldsOpens(r.T), "no opens during the back-off");
|
||||
Check.False(r.W.HoldsOpens(r.W.BackoffUntil), "the back-off ends");
|
||||
|
||||
r.T = r.W.BackoffUntil;
|
||||
Check.Eq(r.RefusedOpen(b), UseRefusalWatch.Verdict.StillStuck, "the probe refused: still stuck");
|
||||
Check.Eq(r.W.BackoffMs, UseRefusalWatch.FirstBackoffMs * 2, "the back-off doubles");
|
||||
for (int i = 0; i < 5; i++) { r.T = r.W.BackoffUntil; r.RefusedOpen(a); }
|
||||
Check.Eq(r.W.BackoffMs, UseRefusalWatch.MaxBackoffMs, "capped");
|
||||
|
||||
Check.Eq(r.W.OnOpened(r.T), UseRefusalWatch.Verdict.Recovered, "a corpse opened: recovered");
|
||||
Check.Eq(r.W.State, UseRefusalWatch.Phase.Normal, "back to normal");
|
||||
Check.Eq(r.W.Refusals, 0, "count cleared");
|
||||
Check.Eq(r.W.OnOpened(r.T), UseRefusalWatch.Verdict.None, "an open while normal says nothing");
|
||||
}
|
||||
|
||||
private static void WatchDropsSingleCorpse()
|
||||
{
|
||||
var r = new Rig();
|
||||
int a = unchecked((int)CorpseA);
|
||||
r.RefusedOpen(a); r.RefusedOpen(a);
|
||||
Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.CleanStopAndRetry, "three refusals");
|
||||
Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.DropCorpse, "same corpse: dropped");
|
||||
Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.DropCorpse, "still only that corpse: dropped again, never stuck");
|
||||
Check.Eq(r.W.OnOpened(r.T), UseRefusalWatch.Verdict.None, "another corpse opens: nothing to announce");
|
||||
Check.Eq(r.W.State, UseRefusalWatch.Phase.Normal, "normal");
|
||||
Check.Eq(r.W.RefusedCorpses.Count, 0, "the refused list is cleared by an open");
|
||||
}
|
||||
|
||||
private static void WatchIgnoresErrorsAndSilence()
|
||||
{
|
||||
var w = new UseRefusalWatch();
|
||||
long t = 5_000; int seq = 7;
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
w.OnOpenSent(1, t, seq);
|
||||
seq++; t += 60;
|
||||
w.OnTick(t, seq, 0x1D, true); // "you're too busy"
|
||||
t += 3000;
|
||||
Check.Eq(w.OnTick(t, seq, 0x1D, true), UseRefusalWatch.Verdict.None, "a too-busy answer is no refusal");
|
||||
Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.None, "and settles nothing");
|
||||
}
|
||||
Check.Eq(w.Refusals, 0, "no refusals from errors");
|
||||
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
w.OnOpenSent(1, t, seq); // the server never answers (a long walk, a lag)
|
||||
t += 2000;
|
||||
Check.Eq(w.OnTick(t, seq, 0, true), UseRefusalWatch.Verdict.None, "unanswered: no verdict");
|
||||
Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.None, "an unanswered open is not settled as refused");
|
||||
}
|
||||
w.OnOpenSent(1, t, seq);
|
||||
t += UseRefusalWatch.UnansweredForgetMs + 1;
|
||||
w.OnTick(t, seq, 0, true);
|
||||
seq++; t += 60;
|
||||
w.OnTick(t, seq, 0, true); // a late UseDone for something else
|
||||
t += 5000;
|
||||
Check.Eq(w.OnTick(t, seq, 0, true), UseRefusalWatch.Verdict.None, "a forgotten open is not judged by a later UseDone");
|
||||
Check.Eq(w.Refusals, 0, "no refusals from silence");
|
||||
}
|
||||
|
||||
private static void WatchSettlesOnNextOpen()
|
||||
{
|
||||
var w = new UseRefusalWatch();
|
||||
long t = 10_000; int seq = 0;
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.None, "below the threshold the open goes ahead");
|
||||
w.OnOpenSent(1, t, seq);
|
||||
seq++; t += 60;
|
||||
w.OnTick(t, seq, 0, true);
|
||||
t += 400; // the next attempt comes before the grace
|
||||
}
|
||||
Check.Eq(w.Refusals, 1, "the first answered open was settled as refused by the second");
|
||||
Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.None, "the second one now");
|
||||
Check.Eq(w.Refusals, 2, "two");
|
||||
w.OnOpenSent(1, t, seq); seq++; t += 60; w.OnTick(t, seq, 0, true); t += 400;
|
||||
Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.CleanStopAndRetry, "the third: hold this open, clean stop first");
|
||||
w.OnOpened(t);
|
||||
Check.Eq(w.Refusals, 0, "an open resets");
|
||||
Check.Eq(w.State, UseRefusalWatch.Phase.Normal, "normal");
|
||||
}
|
||||
|
||||
// ── Through RynthAi's corpse looting ──────────────────────────────────────
|
||||
|
||||
private static (uint Cell, float X, float Y, float Z) Me0 => (0x6347028Au, 100f, 100f, 0f);
|
||||
|
||||
private static void World()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
|
||||
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData, GetCurrentCombatMode
|
||||
FakeHost.ServerGates = true; // GetUseDoneSeq
|
||||
FakeHost.LastUseDoneCalls = true;
|
||||
FakeHost.StopCalls = true;
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
foreach ((uint id, float dx) in new[] { (CorpseA, 1.0f), (CorpseB, 1.5f) })
|
||||
{
|
||||
FakeHost.Names[id] = "Corpse of Olthoi Swarm Worker";
|
||||
FakeHost.ItemTypes[id] = ItemTypeContainer;
|
||||
FakeHost.Strings[(id, LongDescKey)] = $"Killed by {Me}.";
|
||||
FakeHost.NotAttackable.Add(id);
|
||||
FakeHost.Positions[id] = (Me0.Cell, Me0.X + dx, Me0.Y, Me0.Z);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new()
|
||||
{
|
||||
IsMacroRunning = true,
|
||||
EnableLooting = true,
|
||||
EnableCombat = false,
|
||||
LootOwnership = 0, // My Kills Only
|
||||
LootContentSettleMs = 0,
|
||||
LootEmptyCorpseMs = 0,
|
||||
StopLootingWhenPackFull = false,
|
||||
};
|
||||
public readonly WorldObjectCache Cache;
|
||||
|
||||
public Bot(RynthCoreHost host)
|
||||
{
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Cache.OnCreateObject(CorpseA);
|
||||
Cache.OnCreateObject(CorpseB);
|
||||
Cache.Tick();
|
||||
|
||||
string profile = Path.Combine(Program.TempRoot, "use-refusal-test.json");
|
||||
var p = new LootProfile { Name = "nothing" };
|
||||
p.Save(profile);
|
||||
S.CurrentLootPath = profile;
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
|
||||
public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
|
||||
public void Tick(BotActivity act)
|
||||
{
|
||||
Set("_activity", act);
|
||||
Call("TickCorpseOpening");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs the fake clock with RynthAiPlugin.CorpseClock pointed at it.</summary>
|
||||
private static void WithClock(Action<Func<long>, Action<long>> body)
|
||||
{
|
||||
long now = 50_000_000;
|
||||
var saved = RynthAiPlugin.CorpseClock;
|
||||
RynthAiPlugin.CorpseClock = () => now;
|
||||
try { body(() => now, ms => now += ms); }
|
||||
finally { RynthAiPlugin.CorpseClock = saved; }
|
||||
}
|
||||
|
||||
private static int ChatCount(string text) => FakeHost.Chat.Count(c => c.Contains(text));
|
||||
|
||||
private static void LootingStall()
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
// The server of 06:18:44 on: every open is answered (UseDone, no error) 60 ms later, nothing opens.
|
||||
long answerAt = 0;
|
||||
void Step()
|
||||
{
|
||||
int uses = FakeHost.Uses.Count;
|
||||
bot.Tick(BotActivity.Looting);
|
||||
if (FakeHost.Uses.Count > uses) answerAt = now() + 60;
|
||||
advance(100);
|
||||
if (answerAt != 0 && now() >= answerAt) { FakeHost.UseDone(0); answerAt = 0; }
|
||||
}
|
||||
|
||||
int steps = 0;
|
||||
while (ChatCount(StuckLine) == 0 && steps++ < 600) Step();
|
||||
Check.Eq(ChatCount(StuckLine), 1, "the player is told, once (after " + steps / 10.0 + " s of looting)");
|
||||
Check.True(steps <= 400, "within 40 s of the first refused open (took " + steps / 10.0 + " s)");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("one clean stop")), "the clean stop and retry came first");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("/Loot/UseCheck StopCompletely()")), "one StopCompletely from the use check");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: facing 0x80068ACE")), "and the corpse is faced for the retry");
|
||||
Check.Near(FakeHost.HeadingDeg, 90.0, 0.5, "facing east, where the corpse lies");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("giving up on it")), "the first corpse, retried alone, was dropped before the verdict");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: the server answers every use but nothing opens")), "the verdict is logged");
|
||||
Check.Eq(bot.Get<int>("_targetCorpseId"), 0, "no corpse held");
|
||||
|
||||
int usesAtStuck = FakeHost.Uses.Count;
|
||||
Check.False((bool)bot.Call("HasLootWork", bot.S, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())!,
|
||||
"no loot work during the back-off: nav and combat run on");
|
||||
for (int i = 0; i < 2400; i++) Step(); // 4 minutes
|
||||
Check.Eq(FakeHost.Uses.Count, usesAtStuck, "no corpse is opened during the back-off");
|
||||
Check.Eq(ChatCount(StuckLine), 1, "and nothing more is said");
|
||||
|
||||
for (int i = 0; i < 700 && FakeHost.Uses.Count == usesAtStuck; i++) Step();
|
||||
Check.Eq(FakeHost.Uses.Count, usesAtStuck + 1, "one probe after the back-off");
|
||||
for (int i = 0; i < 40; i++) Step();
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("still refused")), "the probe refused: logged");
|
||||
Check.Eq(ChatCount(StuckLine), 1, "not said again");
|
||||
Check.Eq(FakeHost.Uses.Count, usesAtStuck + 1, "and backed off again");
|
||||
|
||||
// A relog, or the server recovers: the next probe opens.
|
||||
int probeUses = FakeHost.Uses.Count;
|
||||
for (int i = 0; i < 6100 && FakeHost.Uses.Count == probeUses; i++)
|
||||
{
|
||||
bot.Tick(BotActivity.Looting);
|
||||
advance(100);
|
||||
}
|
||||
Check.Eq(FakeHost.Uses.Count, probeUses + 1, "the next probe after the longer back-off");
|
||||
uint probed = FakeHost.Uses.Last();
|
||||
bot.P.OnViewObjectContents(probed);
|
||||
Check.Eq(ChatCount("Objects open again"), 1, "the player is told uses work again");
|
||||
Check.False(bot.Get<UseRefusalWatch>("_useRefusals").HoldsOpens(now()), "looting is back on");
|
||||
});
|
||||
}
|
||||
|
||||
private static void LootingNormalOpens()
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
for (int round = 0; round < 6; round++)
|
||||
{
|
||||
uint id = round % 2 == 0 ? CorpseA : CorpseB;
|
||||
// Not completed yet: a fresh claim each round.
|
||||
bot.Get<System.Collections.Generic.Dictionary<int, long>>("_completedCorpses").Clear();
|
||||
int uses = FakeHost.Uses.Count;
|
||||
for (int i = 0; i < 30 && FakeHost.Uses.Count == uses; i++) { bot.Tick(BotActivity.Looting); advance(100); }
|
||||
Check.True(FakeHost.Uses.Count > uses, $"round {round}: an open went out");
|
||||
advance(200);
|
||||
FakeHost.UseDone(0);
|
||||
bot.P.OnViewObjectContents(FakeHost.Uses.Last());
|
||||
for (int i = 0; i < 30; i++) { bot.Tick(BotActivity.Looting); advance(100); }
|
||||
}
|
||||
var w = bot.Get<UseRefusalWatch>("_useRefusals");
|
||||
Check.Eq(w.Refusals, 0, "no refusals");
|
||||
Check.Eq(w.State, UseRefusalWatch.Phase.Normal, "normal");
|
||||
Check.Eq(ChatCount(StuckLine), 0, "nothing said");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("Use check:")), "nothing logged by the use check");
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The engine's flight recorder answers SendPluginCommand("RynthCore.FlightRecorder", "dump", reason).</summary>
|
||||
private static void FlightDumpRequests()
|
||||
{
|
||||
World();
|
||||
FakeHost.PluginCommandCalls = true;
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
long answerAt = 0;
|
||||
int steps = 0;
|
||||
while (ChatCount(StuckLine) == 0 && steps++ < 600)
|
||||
{
|
||||
int uses = FakeHost.Uses.Count;
|
||||
bot.Tick(BotActivity.Looting);
|
||||
if (FakeHost.Uses.Count > uses) answerAt = now() + 60;
|
||||
advance(100);
|
||||
if (answerAt != 0 && now() >= answerAt) { FakeHost.UseDone(0); answerAt = 0; }
|
||||
}
|
||||
var dumps = FakeHost.PluginCommands.Where(c => c.Plugin == "RynthCore.FlightRecorder").ToList();
|
||||
Check.True(dumps.Count >= 2, $"a dump asked at the clean stop and at the verdict ({dumps.Count})");
|
||||
Check.True(dumps.All(d => d.Action == "dump"), "all are dump requests");
|
||||
Check.True(dumps.Any(d => d.Value.StartsWith("RynthAi use check: corpse opens answered")), "the clean stop's reason");
|
||||
Check.True(dumps.Any(d => d.Value.StartsWith("RynthAi use check: server refuses every use")), "the verdict's reason");
|
||||
});
|
||||
|
||||
// Normal opens: nothing asked.
|
||||
World();
|
||||
FakeHost.PluginCommandCalls = true;
|
||||
var host2 = FakeHost.Create(Player);
|
||||
var bot2 = new Bot(host2);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
for (int round = 0; round < 4; round++)
|
||||
{
|
||||
bot2.Get<System.Collections.Generic.Dictionary<int, long>>("_completedCorpses").Clear();
|
||||
int uses = FakeHost.Uses.Count;
|
||||
for (int i = 0; i < 30 && FakeHost.Uses.Count == uses; i++) { bot2.Tick(BotActivity.Looting); advance(100); }
|
||||
advance(200);
|
||||
FakeHost.UseDone(0);
|
||||
bot2.P.OnViewObjectContents(FakeHost.Uses.Last());
|
||||
for (int i = 0; i < 30; i++) { bot2.Tick(BotActivity.Looting); advance(100); }
|
||||
}
|
||||
Check.False(FakeHost.PluginCommands.Any(c => c.Plugin == "RynthCore.FlightRecorder"), "no dump asked");
|
||||
});
|
||||
}
|
||||
|
||||
private static void OpenWaitsForLootingTick()
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
bot.Tick(BotActivity.Combat); // the kill tick: Combat still owns it
|
||||
Check.Eq(bot.Get<int>("_targetCorpseId"), unchecked((int)CorpseA), "the corpse is claimed");
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "but not opened while Combat owns the tick");
|
||||
advance(30);
|
||||
bot.Tick(BotActivity.Looting); // the arbiter hands the tick to Looting (its nav stop goes first)
|
||||
Check.Eq(FakeHost.Uses.Count, 1, "opened on the Looting tick");
|
||||
Check.Eq(FakeHost.Uses[0], CorpseA, "the claimed corpse");
|
||||
});
|
||||
}
|
||||
|
||||
// ── MoveAudit hold ────────────────────────────────────────────────────────
|
||||
|
||||
private static void WithAuditClock(Action<Action<long>> body)
|
||||
{
|
||||
long now = 7_000_000;
|
||||
var savedUse = UseAudit.NowMs;
|
||||
var savedMove = MoveAudit.NowMs;
|
||||
UseAudit.NowMs = () => now;
|
||||
MoveAudit.NowMs = () => now;
|
||||
try { body(ms => now += ms); }
|
||||
finally
|
||||
{
|
||||
UseAudit.NowMs = savedUse;
|
||||
MoveAudit.NowMs = savedMove;
|
||||
UseAudit.TrackWorldUses = false;
|
||||
UseAudit.ClearWorldUse();
|
||||
MoveAudit.Reset();
|
||||
UseAudit.Reset("?", null);
|
||||
}
|
||||
}
|
||||
|
||||
private static void MoveHoldWhileUseInFlight()
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
WithAuditClock(advance =>
|
||||
{
|
||||
UseAudit.Reset("RynthAi", () => true);
|
||||
MoveAudit.Reset();
|
||||
UseAudit.TrackWorldUses = true;
|
||||
|
||||
Check.True(host.UseFor(CorpseA, "Loot", "test open"), "the corpse use goes out");
|
||||
advance(10);
|
||||
Check.False(host.SetAutoRunBy("Nav", true), "autorun on is held");
|
||||
Check.False(host.TurnToHeadingBy("Nav", 90f), "a heading snap is held");
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "no autorun reached the client");
|
||||
Check.Eq(FakeHost.Turns, 0, "no turn reached the client");
|
||||
Check.True(host.StopCompletelyBy("Arbiter"), "a stop goes through");
|
||||
Check.Eq(FakeHost.Stops, 1, "one stop");
|
||||
host.SetAutoRunBy("Nav", false);
|
||||
Check.Eq(string.Join(",", FakeHost.AutoRunCalls), "False", "autorun off goes through");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains(" held: the server is still answering the use of 0x80068ACE")), 1, "one 'held' line for the use");
|
||||
|
||||
FakeHost.UseDone(0); // the server answered
|
||||
Check.True(host.SetAutoRunBy("Nav", true), "after the UseDone autorun goes out");
|
||||
Check.True(host.TurnToHeadingBy("Nav", 45f), "and turns");
|
||||
|
||||
Check.True(host.UseFor(CorpseB, "Loot", "test open 2"), "a second use");
|
||||
Check.False(host.TurnToHeadingBy("Nav", 50f), "held again");
|
||||
advance(UseAudit.WorldUseInFlightMaxMs); // no answer: the cap releases it
|
||||
Check.True(host.TurnToHeadingBy("Nav", 55f), "released after the cap");
|
||||
|
||||
FakeHost.Uses.Clear();
|
||||
Check.True(host.UseFor(0x80001234, "Loot", "a non-world use (an item)"), "an item use");
|
||||
Check.True(host.TurnToHeadingBy("Nav", 60f), "an item use holds nothing");
|
||||
});
|
||||
}
|
||||
|
||||
private static void MoveHoldOptIn()
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
WithAuditClock(advance =>
|
||||
{
|
||||
UseAudit.Reset("RynthNav", null);
|
||||
MoveAudit.Reset();
|
||||
Check.False(UseAudit.TrackWorldUses, "off by default");
|
||||
host.UseFor(CorpseA, "Nav", "test open");
|
||||
Check.True(host.SetAutoRunBy("Nav", true), "nothing held without the opt-in");
|
||||
Check.True(host.TurnToHeadingBy("Nav", 90f), "turns too");
|
||||
Check.False(UseAudit.WorldUseInFlight(host, out _), "no use is tracked");
|
||||
});
|
||||
}
|
||||
|
||||
// ── Combat's idle peace swap ──────────────────────────────────────────────
|
||||
|
||||
private static void IdlePeaceHeldWhileLooting()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeCalls = true;
|
||||
FakeHost.CombatModeValue = 2; // melee stance, no target: the idle swap would go to peace
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
var host = FakeHost.Create(Player);
|
||||
var s = new LegacyUiSettings { IsMacroRunning = true, EnableCombat = true, PeaceModeWhenIdle = true, MonsterRange = 50 };
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
var combat = new CombatManager(host, s, cache);
|
||||
combat.SetPlayerId(Player);
|
||||
bool looting = true;
|
||||
combat.HoldIdlePeace = () => looting;
|
||||
|
||||
for (int i = 0; i < 5; i++) combat.Think();
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no peace swap while looting has work");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("idle peace-mode swap held")), 1, "said once in the log");
|
||||
|
||||
looting = false;
|
||||
combat.Think();
|
||||
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "looting done: the idle swap to peace goes out");
|
||||
|
||||
combat.HoldIdlePeace = null;
|
||||
FakeHost.CombatModeRequests.Clear();
|
||||
typeof(CombatManager).GetField("_lastPeaceAttempt", Any)!.SetValue(combat, DateTime.MinValue);
|
||||
combat.Think();
|
||||
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "no hold set: as before");
|
||||
}
|
||||
|
||||
private static void LootHoldsIdlePeaceInputs()
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bool Holds() => (bool)bot.Call("LootHoldsIdlePeace")!;
|
||||
Check.False(Holds(), "nothing to loot: no hold");
|
||||
bot.Set("_targetCorpseId", unchecked((int)CorpseA));
|
||||
Check.True(Holds(), "a claimed corpse");
|
||||
bot.Set("_targetCorpseId", 0);
|
||||
bot.Set("_openedContainerId", unchecked((int)CorpseA));
|
||||
Check.True(Holds(), "an open corpse");
|
||||
bot.Set("_openedContainerId", 0);
|
||||
bot.Set("_lastWantLoot", true);
|
||||
Check.True(Holds(), "a corpse waiting in range (the arbiter's wantLoot)");
|
||||
bot.Set("_lastWantLoot", false);
|
||||
WithAuditClock(_ =>
|
||||
{
|
||||
UseAudit.Reset("RynthAi", () => true);
|
||||
UseAudit.TrackWorldUses = true;
|
||||
host.UseFor(CorpseB, "Loot", "test open");
|
||||
Check.True(Holds(), "a corpse use in flight");
|
||||
});
|
||||
Check.False(Holds(), "all clear: no hold");
|
||||
}
|
||||
|
||||
// ── The jump (2026-10-06 afternoon) ───────────────────────────────────────
|
||||
// On ACE the player's jump (Player.HandleActionJump) is the one in-world action that empties the
|
||||
// server's animation queues (the stuck state); the use check jumps at the clean stop and before
|
||||
// each probe.
|
||||
|
||||
private static void WatchProbeJump()
|
||||
{
|
||||
var r = new Rig();
|
||||
int a = unchecked((int)CorpseA), b = unchecked((int)CorpseB);
|
||||
Check.False(r.W.TakeProbeJump(r.T), "normal: no jump");
|
||||
r.RefusedOpen(a); r.RefusedOpen(a); r.RefusedOpen(a);
|
||||
Check.False(r.W.TakeProbeJump(r.T), "retrying: no probe jump (the clean stop jumps itself)");
|
||||
r.RefusedOpen(a);
|
||||
Check.Eq(r.RefusedOpen(b), UseRefusalWatch.Verdict.Stuck, "stuck");
|
||||
Check.False(r.W.TakeProbeJump(r.T), "during the back-off: no jump");
|
||||
r.T = r.W.BackoffUntil;
|
||||
Check.True(r.W.TakeProbeJump(r.T), "the back-off is over: jump before the probe");
|
||||
Check.False(r.W.TakeProbeJump(r.T + 100), "once");
|
||||
Check.Eq(r.RefusedOpen(b), UseRefusalWatch.Verdict.StillStuck, "the probe refused");
|
||||
Check.False(r.W.TakeProbeJump(r.T), "a new back-off: no jump yet");
|
||||
r.T = r.W.BackoffUntil;
|
||||
Check.True(r.W.TakeProbeJump(r.T), "again once the longer back-off is over");
|
||||
r.W.OnOpened(r.T);
|
||||
Check.False(r.W.TakeProbeJump(r.T + UseRefusalWatch.MaxBackoffMs), "after an open: never");
|
||||
}
|
||||
|
||||
/// <summary>The 14:29 server: every open is answered 60 ms later and nothing opens, until the
|
||||
/// first open after a jump (when <paramref name="jumpClears"/>).</summary>
|
||||
private static void StallServer(Bot bot, Func<long> now, Action<long> advance, bool jumpClears, int maxSteps, Func<bool> until)
|
||||
{
|
||||
long answerAt = 0; uint answerFor = 0;
|
||||
for (int steps = 0; steps < maxSteps && !until(); steps++)
|
||||
{
|
||||
int uses = FakeHost.Uses.Count;
|
||||
bot.Tick(BotActivity.Looting);
|
||||
if (FakeHost.Uses.Count > uses) { answerAt = now() + 60; answerFor = FakeHost.Uses.Last(); }
|
||||
advance(100);
|
||||
if (answerAt != 0 && now() >= answerAt)
|
||||
{
|
||||
FakeHost.UseDone(0);
|
||||
if (jumpClears && FakeHost.TapJumps > 0)
|
||||
bot.P.OnViewObjectContents(answerFor);
|
||||
answerAt = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void LootingStallJumpClears()
|
||||
{
|
||||
World();
|
||||
FakeHost.TapJumpCalls = true;
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
int usesAtJump = -1; long jumpAt = 0;
|
||||
StallServer(bot, now, advance, jumpClears: false, maxSteps: 400, until: () =>
|
||||
{
|
||||
if (FakeHost.TapJumps > 0 && usesAtJump < 0) { usesAtJump = FakeHost.Uses.Count; jumpAt = now(); }
|
||||
return usesAtJump >= 0;
|
||||
});
|
||||
Check.Eq(FakeHost.TapJumps, 1, "the clean stop jumps once");
|
||||
Check.Eq(FakeHost.Jumps, 0, "with the keyboard jump, not JumpNonAutonomous (ACE ignores 0xF7C9)");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("one clean stop, a jump")), "logged");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: jump for the retry")), "the jump is logged");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("Use check: facing")), "no facing turn when it jumps");
|
||||
|
||||
// The retry waits for the pause, then the server (cleared by the jump) opens it.
|
||||
long retryAt = 0;
|
||||
StallServer(bot, now, advance, jumpClears: true, maxSteps: 100, until: () =>
|
||||
{
|
||||
if (retryAt == 0 && FakeHost.Uses.Count > usesAtJump) retryAt = now();
|
||||
return bot.Get<int>("_openedContainerId") != 0;
|
||||
});
|
||||
Check.True(retryAt != 0, "a retry went out");
|
||||
Check.True(retryAt - jumpAt >= UseRefusalWatch.CleanStopPauseMs, $"after the pause ({retryAt - jumpAt} ms)");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("after the use check's jump - the jump cleared")), "the open after the jump is logged as the fix");
|
||||
Check.Eq(ChatCount(StuckLine), 0, "the player is never told to relog");
|
||||
Check.Eq(bot.Get<UseRefusalWatch>("_useRefusals").State, UseRefusalWatch.Phase.Normal, "back to normal");
|
||||
});
|
||||
}
|
||||
|
||||
private static void LootingStallJumpBeforeProbe()
|
||||
{
|
||||
World();
|
||||
FakeHost.TapJumpCalls = true;
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
StallServer(bot, now, advance, jumpClears: false, maxSteps: 600, until: () => ChatCount(StuckLine) > 0);
|
||||
Check.Eq(ChatCount(StuckLine), 1, "the jump didn't help here: the player is told once");
|
||||
Check.Eq(FakeHost.TapJumps, 1, "one jump so far (the clean stop)");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("the clean stop, the jump and retry didn't help")), "the verdict says the jump was tried");
|
||||
|
||||
var w = bot.Get<UseRefusalWatch>("_useRefusals");
|
||||
int usesAtStuck = FakeHost.Uses.Count;
|
||||
for (int i = 0; i < 2400; i++) { bot.Tick(BotActivity.Looting); advance(100); } // 4 minutes
|
||||
Check.Eq(FakeHost.TapJumps, 1, "no jump during the back-off");
|
||||
Check.Eq(FakeHost.Uses.Count, usesAtStuck, "no opens during the back-off");
|
||||
|
||||
long probeJumpAt = 0;
|
||||
for (int i = 0; i < 700 && FakeHost.Uses.Count == usesAtStuck; i++)
|
||||
{
|
||||
bot.Tick(BotActivity.Looting);
|
||||
if (probeJumpAt == 0 && FakeHost.TapJumps == 2) probeJumpAt = now();
|
||||
advance(100);
|
||||
}
|
||||
Check.Eq(FakeHost.TapJumps, 2, "a jump before the probe");
|
||||
Check.Eq(FakeHost.Uses.Count, usesAtStuck + 1, "then the probe");
|
||||
Check.True(now() - 100 - probeJumpAt >= UseRefusalWatch.CleanStopPauseMs, "the probe waits the pause after the jump");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: jump before the probe")), "logged");
|
||||
|
||||
// The jump cleared it: the probe opens.
|
||||
bot.P.OnViewObjectContents(FakeHost.Uses.Last());
|
||||
Check.Eq(ChatCount("Objects open again"), 1, "the player is told uses work again");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("the jump cleared")), "and the log says the jump did it");
|
||||
Check.False(w.HoldsOpens(now()), "looting is back on");
|
||||
});
|
||||
}
|
||||
|
||||
private static void NoJumpWhilePacerOutstanding()
|
||||
{
|
||||
World();
|
||||
FakeHost.TapJumpCalls = true;
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
long t = 10_000_000;
|
||||
ActionPacer.Reset();
|
||||
ActionPacer.Enabled = true;
|
||||
ActionPacer.NowMs = () => t;
|
||||
try
|
||||
{
|
||||
ActionPacer.Begin(host, PacedKind.Cast, 0, "Revitalize Self VI", "Buff", FakeHost.UseDoneSeq);
|
||||
Check.False((bool)bot.Call("TryUseCheckJump", t, "test")!, "no jump while the cast is unanswered");
|
||||
Check.Eq(FakeHost.TapJumps, 0, "nothing sent");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: no jump test - the server still owes an answer")), "logged");
|
||||
FakeHost.UseDone(0);
|
||||
t += 50;
|
||||
Check.True((bool)bot.Call("TryUseCheckJump", t, "test")!, "answered: the jump goes");
|
||||
Check.Eq(FakeHost.TapJumps, 1, "one jump");
|
||||
}
|
||||
finally
|
||||
{
|
||||
ActionPacer.Enabled = false;
|
||||
ActionPacer.Reset();
|
||||
ActionPacer.NowMs = () => Environment.TickCount64;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -26,7 +26,9 @@ internal static class VTankLootTests
|
|||
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: Decal's long keys (MaxDamage, Coverage, EquipType, IconOverlay) read the game property", DecalLongKeys);
|
||||
r.Add("loot vtank: double keys LE/GE", DoubleKeys);
|
||||
r.Add("loot vtank: VTank's 0x0A0000xx double keys (AttackBonus, DamageBonus, Variance) read 62/63/22", VTankDoubleKeys);
|
||||
r.Add("loot vtank: object class", ObjectClass);
|
||||
r.Add("loot vtank: value and workmanship requirements", ValueAndWorkmanship);
|
||||
r.Add("loot vtank: damage nodes (min, median, missile, tinked, percent)", DamageNodes);
|
||||
|
|
@ -165,6 +167,33 @@ internal static class VTankLootTests
|
|||
Check.True(M(retail, C(N.LongValKeyE, "20646", type)), "an exact WCID match works too");
|
||||
}
|
||||
|
||||
// 2026-10-07: LootSnobV4's "(2H) Cleaving MAX 350" (Buffed Long Key >= on 218103842) never kept
|
||||
// anything: Decal's synthetic keys were read as STypeInt ids no object has. 336 of its rules
|
||||
// use MaxDamage, 109 Coverage, 83 IconOverlay.
|
||||
private static void DecalLongKeys()
|
||||
{
|
||||
var axe = new Item("Greataxe", AcObjectClass.MeleeWeapon).Int(44, 30).Int(51, 5).Int(48, 41);
|
||||
Check.True(M(axe, C(N.BuffedLongValKeyGE, "25", "218103842")), "MaxDamage 30 >= 25");
|
||||
Check.False(M(axe, C(N.BuffedLongValKeyGE, "31", "218103842")), "MaxDamage 30 < 31");
|
||||
Check.True(M(axe, C(N.LongValKeyGE, "30", "218103842")), "plain Long Key too");
|
||||
Check.True(M(axe, C(N.LongValKeyE, "5", "218103823")), "EquipType = CombatUse (5, two-handed)");
|
||||
Check.True(M(axe, C(N.LongValKeyE, "41", "218103840")), "EquipSkill = WeaponSkill");
|
||||
var shirt = new Item("Shirt", AcObjectClass.Clothing).Int(4, 0x1A);
|
||||
Check.True(M(shirt, C(N.LongValKeyFlagExists, "2", "218103821")), "Coverage flag reads ClothingPriority");
|
||||
Check.False(M(shirt, C(N.LongValKeyFlagExists, "1", "218103821")), "a flag it lacks");
|
||||
Check.Eq(new Item("Stick").Wo.Values(218103820, -7), -7, "an unmapped Decal key (Monarch) answers the default");
|
||||
|
||||
FakeHost.Reset();
|
||||
var host = FakeHost.Create();
|
||||
var cache = new WorldObjectCache(host);
|
||||
const uint Rare = 0x80001101;
|
||||
FakeHost.DataIds[(Rare, 50)] = 0x06006C38;
|
||||
var rare = new WorldObject(unchecked((int)Rare), "Pearl of Blood Drinking", AcObjectClass.Misc) { Cache = cache };
|
||||
Check.Eq(rare.Values(218103849, 0), 27704, "IconOverlay is the overlay's portal index, as Decal gives it");
|
||||
Check.True(M(rare, C(N.LongValKeyE, "27704", "218103849")), "an IconOverlay rule matches");
|
||||
Check.Eq(rare.Values(218103850, -1), -1, "no underlay: the default");
|
||||
}
|
||||
|
||||
private static void DoubleKeys()
|
||||
{
|
||||
var item = new Item("x").Dbl(29, 1.25);
|
||||
|
|
@ -175,6 +204,27 @@ internal static class VTankLootTests
|
|||
Check.True(M(item, C(N.DoubleValKeyGE, "1e0", "29")), "exponent notation parses");
|
||||
}
|
||||
|
||||
// VTank's editor writes the weapon profile's attack/damage mods under Decal's synthetic keys
|
||||
// (uTank2 LootPlugins.DoubleValueKey AttackBonus 0x0A00000C, DamageBonus 0x0A00000E,
|
||||
// Variance 0x0A00000B). LootSnobV4's "(H) Axe (AT +8)" rules are BuffedDoubleValKeyGE
|
||||
// 1.31 on 167772172; read raw the key was never set, so they could not match.
|
||||
private static void VTankDoubleKeys()
|
||||
{
|
||||
var axe = new Item("Axe").Dbl(62, 1.31).Dbl(63, 1.2).Dbl(22, 0.4);
|
||||
const string attack = "167772172", damage = "167772174", variance = "167772171";
|
||||
Check.True(M(axe, C(N.BuffedDoubleValKeyGE, "1.31", attack)), "LootSnob AT rule: attack 1.31 >= 1.31");
|
||||
Check.False(M(axe, C(N.BuffedDoubleValKeyGE, "1.32", attack)), "attack just above");
|
||||
Check.True(M(axe, C(N.DoubleValKeyGE, "1.2", damage)), "DamageBonus reads DamageMod 63");
|
||||
Check.False(M(axe, C(N.DoubleValKeyGE, "1.21", damage)), "not WeaponOffense");
|
||||
Check.True(M(axe, C(N.DoubleValKeyLE, "0.4", variance)), "Variance reads DamageVariance 22");
|
||||
Check.False(M(axe, C(N.DoubleValKeyLE, "0.39", variance)), "variance below");
|
||||
Check.False(M(new Item("Stick"), C(N.DoubleValKeyGE, "0.1", attack)), "no attack mod: reads 0");
|
||||
|
||||
var armor = new Item("Coat").Dbl(13, 1.6).Dbl(19, 0.8);
|
||||
Check.True(M(armor, C(N.DoubleValKeyGE, "1.6", "167772160")), "SlashProt reads ArmorModVsSlash 13");
|
||||
Check.True(M(armor, C(N.DoubleValKeyLE, "0.8", "167772164")), "LightningProt reads ArmorModVsElectric 19");
|
||||
}
|
||||
|
||||
private static void ObjectClass()
|
||||
{
|
||||
Check.True(M(new Item("x", AcObjectClass.Salvage), C(N.ObjectClass, "39")), "salvage is class 39");
|
||||
|
|
@ -199,7 +249,7 @@ internal static class VTankLootTests
|
|||
|
||||
private static void DamageNodes()
|
||||
{
|
||||
var sword = new Item("Sword").Int(54, 40).Dbl(22, 0.5); // min 20, median 30
|
||||
var sword = new Item("Sword").Int(44, 40).Dbl(22, 0.5); // min 20, median 30
|
||||
Check.True(M(sword, C(N.MinDamageGE, "20")), "min 20");
|
||||
Check.False(M(sword, C(N.MinDamageGE, "20.5")), "min above");
|
||||
Check.True(M(sword, C(N.BuffedMedianDamageGE, "30")), "median 30");
|
||||
|
|
@ -211,10 +261,10 @@ internal static class VTankLootTests
|
|||
Check.False(M(nodmg, C(N.BuffedMedianDamageGE, "0")), "no max damage: median fails");
|
||||
Check.False(M(nodmg, C(N.BuffedMissileDamageGE, "0")), "no max damage: missile fails");
|
||||
|
||||
var bow = new Item("Bow").Int(54, 50).Dbl(152, 1.2);
|
||||
var bow = new Item("Bow").Int(44, 50).Dbl(152, 1.2);
|
||||
Check.True(M(bow, C(N.BuffedMissileDamageGE, "60")), "50 * elemental 1.2 = 60");
|
||||
Check.False(M(bow, C(N.BuffedMissileDamageGE, "60.1")), "just above");
|
||||
var weakBow = new Item("Bow").Int(54, 50).Dbl(152, 0.5);
|
||||
var weakBow = new Item("Bow").Int(44, 50).Dbl(152, 0.5);
|
||||
Check.True(M(weakBow, C(N.BuffedMissileDamageGE, "50")), "an elemental bonus below 1 counts as 1");
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -22,9 +22,13 @@ internal static class VitalsTests
|
|||
{
|
||||
r.Add("vitals: Stamina to Health follows its own health line and stamina floor", StaminaToHealthThresholds);
|
||||
r.Add("vitals: profiles without the Stamina to Health keys load today's 30 / 20", StaminaToHealthDefaults);
|
||||
r.Add("vitals: Re-stam To keeps a started recharge going to its line; off = one recharge as before", RestamTo);
|
||||
r.Add("vitals: out of Magic stance a listed stamina potion goes before Revitalize; a caster casts first", StaminaPotionFirst);
|
||||
r.Add("vitals: after a kit, nothing else heals until the kit's result line lands", KitResultWait);
|
||||
r.Add("vitals: Heal Self known only above the tier Life Magic allows (vitae) is still cast", HealAboveAllowedTier);
|
||||
r.Add("vitals: low health wins the arbiter even on a busy tick; backs off when nothing can heal", HealthWinsArbiter);
|
||||
r.Add("vitals: 'You're too busy!' paces vital casts, and a long streak stops the character once", TooBusyVitals);
|
||||
r.Add("vitals: no components for the top level - the next lower level is cast, not the same one again", NoComponentsFallsBack);
|
||||
// Drakkon's death, 2026-10-05 13:43:20 (ops\overnight\2026-10-05-death-fixes.md).
|
||||
r.Add("vitals: a hot reload's login refresh trusts its first read; a real login waits for two equal reads", HotReloadRefresh);
|
||||
r.Add("vitals: RynthAi tells the engine a reload is unsafe while engaged, under a heal line or casting", ReloadBlockerReport);
|
||||
|
|
@ -66,6 +70,42 @@ internal static class VitalsTests
|
|||
Check.Eq(FakeHost.Stops, 1, "only once per streak");
|
||||
}
|
||||
|
||||
// 2026-10-08: with no components for the highest Stamina to Mana / Revitalize / Heal the
|
||||
// character knew, RynthAi kept retrying that one level; it parked the whole family, then
|
||||
// tried the same level again. Now that level is passed over and the next lower one is cast.
|
||||
private static void NoComponentsFallsBack()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
|
||||
var host = FakeHost.Create();
|
||||
var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false };
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 10 };
|
||||
var b = new BuffManager(host, s, sm, vitals);
|
||||
b.SetCharacterSkills(skills);
|
||||
|
||||
Check.True(b.CheckVitals(), "10% mana: Stamina to Mana is cast");
|
||||
int top = FakeHost.Casts[^1].SpellId;
|
||||
b.OnChatWindowText("You don't have all the components for this spell.", 0);
|
||||
for (int i = 0; i < 50 && FakeHost.Casts.Count < 2; i++)
|
||||
{
|
||||
b.CheckVitals();
|
||||
System.Threading.Thread.Sleep(20);
|
||||
}
|
||||
Check.Eq(FakeHost.Casts.Count, 2, "a second cast goes out");
|
||||
int next = FakeHost.Casts[^1].SpellId;
|
||||
Check.True(next != top, $"a different level ({SpellTableStub.GetById(top)?.Name} -> {SpellTableStub.GetById(next)?.Name})");
|
||||
Check.True(SpellTableStub.GetById(next)?.Family == SpellTableStub.GetById(top)?.Family, "the same spell, one level down");
|
||||
}
|
||||
|
||||
// 2026-10-04, "nav and looting have priority over healing, almost dying in packs": the
|
||||
// arbiter only saw a heal on ticks where CheckVitals ran (never while looting kept the client
|
||||
// busy). Health under a line now says "wants vitals" by itself.
|
||||
|
|
@ -147,6 +187,29 @@ internal static class VitalsTests
|
|||
Check.False(BuffManager.IsKitResultLine("bob heals you for 40 health points."), "someone else's kit doesn't");
|
||||
}
|
||||
|
||||
private static void HealAboveAllowedTier()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
int heal6 = SpellTable.Rows.First(r => r.Name == "Heal Self VI").Id;
|
||||
FakeHost.Spellbook.Add((uint)heal6); // the only Heal Self known
|
||||
FakeHost.Skills[(Player, STypeLife)] = (120, 2); // vitae: Life Magic under the tier 6 line
|
||||
var host = FakeHost.Create();
|
||||
var s = new LegacyUiSettings { HealAt = 60, TopOffHP = 60, RestamAt = 0, TopOffStam = 0, GetManaAt = 0, TopOffMana = 0, UsePotions = false };
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
Check.True(sm.GetHighestBuffSpellTier(AcSkillType.LifeMagic) < 6, "the rig: Life Magic 120 allows less than tier 6");
|
||||
var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 30, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
|
||||
var b = new BuffManager(host, s, sm, vitals);
|
||||
b.SetCharacterSkills(skills);
|
||||
Check.True(b.CheckVitals(), "health 30% under Heal At 60%: the vitals step acts");
|
||||
Check.True(FakeHost.Casts.Any(c => c.SpellId == heal6), "Heal Self VI is cast: " + string.Join(",", FakeHost.Casts.Select(c => c.SpellId)));
|
||||
}
|
||||
|
||||
/// <summary>One CheckVitals on a fresh BuffManager; true when it cast a Stamina to Health spell.</summary>
|
||||
private static bool CastsStamToHealth(int healthPct, int staminaPct, System.Action<LegacyUiSettings>? tweak = null)
|
||||
{
|
||||
|
|
@ -186,6 +249,75 @@ internal static class VitalsTests
|
|||
return cast;
|
||||
}
|
||||
|
||||
// Tom, 2026-10-06: a melee character should drink its listed stamina potions before Revitalize
|
||||
// (which means switching the weapon for the wand and back).
|
||||
private static void StaminaPotionFirst()
|
||||
{
|
||||
const uint Tincture = 0x80001234;
|
||||
foreach (int mode in new[] { CombatMode.Melee, CombatMode.Magic })
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeValue = mode;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
|
||||
FakeHost.Names[Tincture] = "Stamina Tincture";
|
||||
var host = FakeHost.Create();
|
||||
var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 0, TopOffMana = 0, RestamAt = 30, TopOffStam = 95, UsePotions = true, EnableBuffing = false };
|
||||
s.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Tincture), Name = "Stamina Tincture", Type = "Stamina" });
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 20, MaxMana = 100, CurrentMana = 100 };
|
||||
var b = new BuffManager(host, s, sm, vitals);
|
||||
b.SetCharacterSkills(skills);
|
||||
b.SetWorldObjectCache(FakeHost.MakeCache(host, Player, new[] { Tincture }));
|
||||
Check.True(b.CheckVitals(), $"mode {mode}: stamina 20% acts");
|
||||
bool drank = FakeHost.Uses.Contains(Tincture);
|
||||
if (mode == CombatMode.Melee)
|
||||
{
|
||||
Check.True(drank, "melee: the tincture is drunk");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "melee: no Revitalize (no wand switch)");
|
||||
}
|
||||
else
|
||||
{
|
||||
Check.False(drank, "caster in Magic stance: no potion first");
|
||||
Check.True(FakeHost.Casts.Count > 0, "caster: Revitalize is cast");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tom, 2026-10-06: one Revitalize often doesn't recover enough stamina.
|
||||
private static void RestamTo()
|
||||
{
|
||||
var s = new LegacyUiSettings { RestamAt = 30, RestamTo = 0, TopOffStam = 95 };
|
||||
bool run = false; int casts = 0;
|
||||
Check.Eq(BuffManager.StaminaLine(true, 25, s, ref run, ref casts), 30, "off: Re-stam At");
|
||||
Check.Eq(BuffManager.StaminaLine(true, 40, s, ref run, ref casts), 30, "off: at 40% no recharge");
|
||||
|
||||
s.RestamTo = 70;
|
||||
Check.Eq(BuffManager.StaminaLine(true, 40, s, ref run, ref casts), 30, "above Re-stam At with no recharge started: nothing new");
|
||||
Check.Eq(BuffManager.StaminaLine(true, 25, s, ref run, ref casts), 70, "under Re-stam At: recharge to 70");
|
||||
casts++;
|
||||
Check.Eq(BuffManager.StaminaLine(true, 45, s, ref run, ref casts), 70, "one cast got it to 45%: still recharging (the second cast)");
|
||||
casts++;
|
||||
Check.Eq(BuffManager.StaminaLine(true, 72, s, ref run, ref casts), 30, "reached 70: done");
|
||||
Check.False(run, "the recharge ended");
|
||||
|
||||
// A recharge that never gains stops after the cap.
|
||||
Check.Eq(BuffManager.StaminaLine(true, 20, s, ref run, ref casts), 70, "new recharge");
|
||||
casts = BuffManager.RestamRunMaxCasts;
|
||||
Check.Eq(BuffManager.StaminaLine(true, 35, s, ref run, ref casts), 30, "cap reached above Re-stam At: back to Re-stam At");
|
||||
|
||||
// Out of combat the top-off line applies, as before.
|
||||
Check.Eq(BuffManager.StaminaLine(false, 50, s, ref run, ref casts), 95, "idle: Top Stam");
|
||||
s.RestamTo = 20;
|
||||
Check.Eq(BuffManager.StaminaLine(true, 25, s, ref run, ref casts), 30, "Re-stam To not above Re-stam At: ignored");
|
||||
}
|
||||
|
||||
private static void StaminaToHealthThresholds()
|
||||
{
|
||||
// Defaults: today's behaviour (30% health, stamina over 20%).
|
||||
|
|
|
|||
327
Tools/RynthCore.RynthAiHostTests/Tests/WallTests.cs
Normal file
327
Tools/RynthCore.RynthAiHostTests/Tests/WallTests.cs
Normal file
|
|
@ -0,0 +1,327 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Wall spells (2026-10-08): a monster rule with Wall on casts its element's wall (picked by spell
|
||||
// category, 229-235) when Wall Range is on and enough monsters are in the wall's path toward the
|
||||
// target. Priority: Ring, then Wall, then Blast, then the base shape; a wall-only rule casts Bolt
|
||||
// between walls. A wall is untargeted (ACE flies it along the caster's facing and never turns the
|
||||
// caster for it), so the bot snaps its heading to the target first and holds the cast until the
|
||||
// new heading has reached the server; already facing, it casts at once without turning. Walls are
|
||||
// area casts for the damage bookkeeping. Old profiles and engine payloads load with walls off.
|
||||
internal static class WallTests
|
||||
{
|
||||
private const uint Player = 0x50000D01;
|
||||
private const int Target = 0x7000A001;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("walls: Ring, then Wall, then Blast, then the base shape; wall-only casts Bolt between walls", ShapePriority);
|
||||
r.Add("walls: each element's wall by category, the tier limit, none for Nether", WallPerElement);
|
||||
r.Add("walls: Wall Range off, too few in the path, or no wall known: the rule's other shape", WallOverride);
|
||||
r.Add("walls: the path is a corridor toward the target, ahead of the caster", WallPathGeometry);
|
||||
r.Add("walls: far off the target, it turns first and casts after the settle; facing it, no turn", WallFacing);
|
||||
r.Add("walls: the cast itself waits for the turn, then goes as an area cast", WallCastThroughAttack);
|
||||
r.Add("walls: UseWall, Wall Range and Min Wall Targets load off / 0 / 3 from old files", OldSettings);
|
||||
}
|
||||
|
||||
private static int Id(string name) => SpellTable.Named(name).Select(r => r.Id).First();
|
||||
private static string NameOf(int id) => id == 0 ? "(none)" : SpellTable.ById(id)?.Name ?? $"#{id}";
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S = new();
|
||||
public readonly CombatManager C;
|
||||
public int InPath = 5;
|
||||
public DateTime Now = new(2026, 10, 8, 12, 0, 0);
|
||||
|
||||
public Rig(int tier, params string[] known)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
foreach (string n in known)
|
||||
foreach (var row in SpellTable.Named(n)) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
int T(int k) => k <= tier ? 0 : 10000; // the no-skills stub reads 250 buffed
|
||||
S.MinSkillLevelTier1 = 0; S.MinSkillLevelTier2 = T(2); S.MinSkillLevelTier3 = T(3); S.MinSkillLevelTier4 = T(4);
|
||||
S.MinSkillLevelTier5 = T(5); S.MinSkillLevelTier6 = T(6); S.MinSkillLevelTier7 = T(7); S.MinSkillLevelTier8 = T(8);
|
||||
S.RingRange = 0;
|
||||
S.WallRange = 20;
|
||||
S.MinWallTargets = 3;
|
||||
// The player at the origin, the target 10 yd north; the player faces north.
|
||||
FakeHost.PlayerPose = (0x0101001Bu, 0f, 0f, 0f);
|
||||
FakeHost.Positions[Player] = FakeHost.PlayerPose;
|
||||
FakeHost.Positions[(uint)Target] = (0x0101001Bu, 0f, 10f, 0f);
|
||||
FakeHost.Names[(uint)Target] = "Drudge Skulker";
|
||||
FakeHost.HeadingDeg = 0;
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = FakeHost.MakeCache(host, Player, new[] { (uint)Target });
|
||||
C = new CombatManager(host, S, cache);
|
||||
C.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, S);
|
||||
sm.InitializeNatively();
|
||||
sm.RefreshKnownSpells();
|
||||
C.SetSpellManager(sm);
|
||||
C.WallPathCountOverride = () => InPath;
|
||||
C.WallClock = () => Now;
|
||||
}
|
||||
|
||||
public (string Spell, string Shape) Cast(string element, MonsterRule rule)
|
||||
{
|
||||
int id = C.FindBestShapedSpell(element, rule, out _, out int shape, arcTargetId: Target);
|
||||
return (NameOf(id), CombatManager.ShapeName(shape));
|
||||
}
|
||||
}
|
||||
|
||||
private static MonsterRule Wall(bool bolt = true) => new() { Name = "Drudge", UseBolt = bolt, UseWall = true };
|
||||
|
||||
private static void ShapePriority()
|
||||
{
|
||||
MonsterRule R(bool ring = false, bool bolt = false, bool blast = false, bool wall = false, bool arc = false)
|
||||
=> new() { UseArc = arc, UseRing = ring, UseBolt = bolt, UseBlast = blast, UseWall = wall };
|
||||
string N(int s) => CombatManager.ShapeName(s);
|
||||
int C(MonsterRule r, bool ringDue, bool wallDue, bool blastConditional = false, bool blastFanMet = false)
|
||||
=> CombatManager.ChooseCastShape(r, blastConditional, blastFanMet, ringDue, wallDue, () => true, out _);
|
||||
|
||||
var all = R(ring: true, bolt: true, blast: true, wall: true);
|
||||
Check.Eq(N(C(all, ringDue: true, wallDue: true, true, true)), "Ring", "all due: Ring");
|
||||
Check.Eq(N(C(all, ringDue: false, wallDue: true, true, true)), "Wall", "wall and blast due: Wall");
|
||||
Check.Eq(N(C(all, ringDue: false, wallDue: false, true, true)), "Blast", "only the blast due: Blast");
|
||||
Check.Eq(N(C(all, ringDue: false, wallDue: false, true, false)), "Bolt", "none due: the base shape (Bolt)");
|
||||
Check.Eq(N(C(R(wall: true), false, true)), "Wall", "wall-only, due: Wall");
|
||||
Check.Eq(N(C(R(wall: true), false, false)), "Bolt", "wall-only, not due: Bolt between walls (like ring-only)");
|
||||
Check.Eq(N(CombatManager.PickBaseShape(R(wall: true))), "Bolt", "wall-only base: Bolt");
|
||||
Check.Eq(N(CombatManager.PickBaseShape(R(wall: true, ring: true))), "Bolt", "ring + wall only: Bolt");
|
||||
Check.Eq(CombatManager.PickBaseShape(R()), -1, "nothing on: still no cast");
|
||||
|
||||
int asked = 0;
|
||||
int s = CombatManager.ChooseCastShape(R(arc: true, wall: true), false, false, false, wallDue: true, () => { asked++; return true; }, out bool g);
|
||||
Check.Eq(N(s), "Wall", "Arc + Wall, wall due: Wall");
|
||||
Check.True(asked == 0 && !g, "a due wall skips the arc test");
|
||||
Check.Eq(N(CombatManager.ChooseCastShape(R(arc: true, wall: true), false, false, false, null, out _)), "Arc",
|
||||
"the old overload (no wall) is unchanged");
|
||||
}
|
||||
|
||||
private static void WallPerElement()
|
||||
{
|
||||
var cases = new (string Element, string Wall)[]
|
||||
{
|
||||
("Acid", "Blistering Creeper"), ("Bludgeon", "Hammering Crawler"), ("Cold", "Foon-Ki's Glacial Floe"),
|
||||
("Lightning", "Os' Wall"), ("Fire", "Slithering Flames"), ("Pierce", "Spike Strafe"),
|
||||
("Blade", "Bed of Blades"), ("Slash", "Bed of Blades"),
|
||||
};
|
||||
string[] retail = cases.Select(c => c.Wall).Distinct().ToArray();
|
||||
foreach (var (element, wall) in cases)
|
||||
{
|
||||
var rig = new Rig(7, retail);
|
||||
Check.Eq(NameOf(rig.C.FindBestWallSpell(element)), wall, $"{element}: {wall} (of all seven known)");
|
||||
Check.Eq(rig.Cast(element, Wall()), (wall, "Wall"), $"{element}: cast as the Wall shape");
|
||||
}
|
||||
var any = new Rig(7, retail);
|
||||
Check.Eq(any.C.FindBestWallSpell("Nether"), 0, "Nether: no walls");
|
||||
Check.Eq(any.Cast("Nether", Wall()).Shape, "?", "Nether, nothing else known: no wall cast");
|
||||
|
||||
// Retail walls are power 200: level 5 by ACE's server formula, castable from tier 5.
|
||||
Check.Eq(SpellDatabase.LevelFromPower(SpellTable.ById(Id("Slithering Flames"))!.Power), 5, "Slithering Flames: level 5 (power 200)");
|
||||
Check.Eq(NameOf(new Rig(5, "Slithering Flames").C.FindBestWallSpell("Fire")), "Slithering Flames", "tier 5: the retail wall");
|
||||
Check.Eq(new Rig(4, "Slithering Flames").C.FindBestWallSpell("Fire"), 0, "tier 4: too hard (the same limit as Flame Bolt V)");
|
||||
|
||||
// Several known in the category: the highest level the tier allows, then the power.
|
||||
var fire = new Rig(8, "Slithering Flames", "Burning Earth", "Flame Whip");
|
||||
Check.Eq(NameOf(fire.C.FindBestWallSpell("Fire")), "Burning Earth", "tier 8: Burning Earth (power 400, level 8)");
|
||||
var fire7 = new Rig(7, "Slithering Flames", "Burning Earth");
|
||||
Check.Eq(NameOf(fire7.C.FindBestWallSpell("Fire")), "Slithering Flames", "tier 7: not the level-8 one");
|
||||
Check.Eq(new Rig(7, "Flame Bolt VI").C.FindBestWallSpell("Fire"), 0, "no wall known: none");
|
||||
|
||||
// The cold snapshot: never guess.
|
||||
FakeHost.Reset();
|
||||
var host = FakeHost.Create(Player);
|
||||
var c = new CombatManager(host, new LegacyUiSettings(), FakeHost.MakeCache(host, Player, Array.Empty<uint>()));
|
||||
var sm = new SpellManager(host, new LegacyUiSettings());
|
||||
sm.InitializeNatively();
|
||||
c.SetSpellManager(sm);
|
||||
Check.Eq(c.FindBestWallSpell("Fire"), 0, "spellbook snapshot cold: no wall");
|
||||
}
|
||||
|
||||
private static void WallOverride()
|
||||
{
|
||||
string[] book = { "Foon-Ki's Glacial Floe", "Frost Bolt VI", "Frost Blast VI", "Frost Arc VI" };
|
||||
var rig = new Rig(7, book);
|
||||
Check.Eq(rig.Cast("Cold", Wall()), ("Foon-Ki's Glacial Floe", "Wall"), "5 in the path (3 needed): the wall");
|
||||
rig.InPath = 2;
|
||||
Check.Eq(rig.Cast("Cold", Wall()), ("Frost Bolt VI", "Bolt"), "2 in the path: Bolt");
|
||||
rig.InPath = 5;
|
||||
rig.S.WallRange = 0;
|
||||
Check.Eq(rig.Cast("Cold", Wall()), ("Frost Bolt VI", "Bolt"), "Wall Range 0: no walls");
|
||||
rig.S.WallRange = 20;
|
||||
Check.Eq(rig.Cast("Cold", new MonsterRule { UseArc = true, UseWall = true }).Shape, "Wall", "Arc + Wall, due: Wall");
|
||||
Check.Eq(rig.Cast("Cold", new MonsterRule { UseBlast = true, UseWall = true, UseBolt = false }).Shape, "Wall", "Blast + Wall, both due: Wall");
|
||||
rig.InPath = 1;
|
||||
Check.Eq(rig.Cast("Cold", new MonsterRule { UseBlast = true, UseWall = true, UseBolt = false }), ("Frost Blast VI", "Blast"),
|
||||
"Blast + Wall, wall not due: Blast");
|
||||
rig.InPath = 5;
|
||||
Check.Eq(rig.Cast("Cold", new MonsterRule { UseBolt = true }), ("Frost Bolt VI", "Bolt"), "Wall off in the rule: unchanged");
|
||||
Check.Eq(rig.C.FindBestShapedSpell("Cold", Wall(), out _, out int probeShape), Id("Frost Bolt VI"),
|
||||
"an element probe (no target) never picks a wall");
|
||||
Check.Eq(CombatManager.ShapeName(probeShape), "Bolt", "probe shape Bolt");
|
||||
|
||||
var noWall = new Rig(7, "Frost Bolt VI");
|
||||
Check.Eq(noWall.Cast("Cold", Wall()), ("Frost Bolt VI", "Bolt"), "no cold wall known: Bolt (the wall isn't due)");
|
||||
|
||||
Check.Eq(CombatManager.ChooseCastShape(new MonsterRule { UseRing = true, UseWall = true }, false, false, true, true, null, out _),
|
||||
CombatManager.ShapeRing, "ring and wall due: Ring");
|
||||
}
|
||||
|
||||
private static void WallPathGeometry()
|
||||
{
|
||||
Check.True(CombatManager.InWallPath(10, 0), "the target itself");
|
||||
Check.True(CombatManager.InWallPath(15, 10), "15 yd, 10 deg off: 2.6 yd aside");
|
||||
Check.False(CombatManager.InWallPath(15, 25), "15 yd, 25 deg off: 6.3 yd aside, outside");
|
||||
Check.True(CombatManager.InWallPath(3, 60), "close, 60 deg off: 2.6 yd aside");
|
||||
Check.False(CombatManager.InWallPath(5, 120), "behind the caster: no");
|
||||
Check.True(CombatManager.InWallPath(5, -30), "the other side too");
|
||||
Check.Near(CombatManager.WallHalfWidth, 4.0, 1e-9, "half width 4 yd (5 projectiles across)");
|
||||
}
|
||||
|
||||
private static void WallFacing()
|
||||
{
|
||||
var rig = new Rig(7, "Slithering Flames");
|
||||
// Facing the target (within 1 degree): cast at once, no turn.
|
||||
FakeHost.HeadingDeg = 0.5f;
|
||||
Check.False(rig.C.HoldForWallFacing(Target), "0.5 deg off: cast now");
|
||||
Check.Eq(FakeHost.Turns, 0, "no turn");
|
||||
|
||||
// 90 degrees off: snap to the target, then hold for the settle.
|
||||
FakeHost.HeadingDeg = 90;
|
||||
Check.True(rig.C.HoldForWallFacing(Target), "90 deg off: hold");
|
||||
Check.Eq(FakeHost.Turns, 1, "one heading snap");
|
||||
Check.Near(FakeHost.HeadingDeg, 0, 0.5, "snapped to the target (north)");
|
||||
rig.Now = rig.Now.AddMilliseconds(500);
|
||||
Check.True(rig.C.HoldForWallFacing(Target), "500 ms later: still settling");
|
||||
rig.Now = rig.Now.AddMilliseconds(CombatManager.WallFaceSettleMs);
|
||||
Check.False(rig.C.HoldForWallFacing(Target), "after the settle: cast");
|
||||
Check.Eq(FakeHost.Turns, 1, "no second turn");
|
||||
|
||||
// Turned, but the target walked far off during the settle: turn again.
|
||||
FakeHost.HeadingDeg = 180;
|
||||
Check.True(rig.C.HoldForWallFacing(Target), "180 deg off: hold");
|
||||
FakeHost.Positions[(uint)Target] = (0x0101001Bu, 10f, 0f, 0f); // now due east
|
||||
rig.Now = rig.Now.AddMilliseconds(CombatManager.WallFaceSettleMs + 1);
|
||||
Check.True(rig.C.HoldForWallFacing(Target), "settled but 90 deg off now: turn again");
|
||||
Check.Eq(FakeHost.Turns, 3, "the second snap");
|
||||
Check.Near(FakeHost.HeadingDeg, 90, 0.5, "to the east");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatCast] wall: facing")), "the turn is logged");
|
||||
|
||||
// The drift allowed after the settle shrinks with distance (1.8 m to the side).
|
||||
Check.Near(CombatManager.WallDriftAllowedDeg(64.0), 1.6, 0.1, "70 yd: about 1.6 degrees");
|
||||
Check.Near(CombatManager.WallDriftAllowedDeg(9.0), 5.0, 0.01, "10 yd: capped at 5 degrees");
|
||||
|
||||
// Always turn: 6 degrees off is a snap too (a wall flies straight).
|
||||
var small = new Rig(7, "Slithering Flames");
|
||||
FakeHost.HeadingDeg = 6;
|
||||
Check.True(small.C.HoldForWallFacing(Target), "6 deg off: turn first");
|
||||
Check.Eq(FakeHost.Turns, 1, "one snap");
|
||||
|
||||
// A target that keeps moving: at most WallFaceMaxSnaps turns, then the wall goes anyway.
|
||||
var chase = new Rig(7, "Slithering Flames");
|
||||
FakeHost.HeadingDeg = 180;
|
||||
Check.True(chase.C.HoldForWallFacing(Target), "first snap");
|
||||
float east = 10f;
|
||||
for (int i = 1; i < CombatManager.WallFaceMaxSnaps; i++)
|
||||
{
|
||||
FakeHost.HeadingDeg = 180; // keeps facing away (the target ran round behind)
|
||||
chase.Now = chase.Now.AddMilliseconds(CombatManager.WallFaceSettleMs + 1);
|
||||
Check.True(chase.C.HoldForWallFacing(Target), $"snap {i + 1}");
|
||||
}
|
||||
FakeHost.HeadingDeg = 180;
|
||||
chase.Now = chase.Now.AddMilliseconds(CombatManager.WallFaceSettleMs + 1);
|
||||
Check.False(chase.C.HoldForWallFacing(Target), "after the last snap: cast anyway");
|
||||
_ = east;
|
||||
}
|
||||
|
||||
private static void WallCastThroughAttack()
|
||||
{
|
||||
var rig = new Rig(7, "Slithering Flames", "Flame Bolt VI");
|
||||
rig.S.MonsterRules.Clear();
|
||||
rig.S.MonsterRules.Add(new MonsterRule { Name = "Drudge", DamageType = "Fire", UseBolt = true, UseWall = true });
|
||||
rig.C.activeTargetId = Target;
|
||||
var target = new WorldObject(Target, "Drudge Skulker");
|
||||
MethodInfo attack = typeof(CombatManager).GetMethod("AttackWithMagic", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
FieldInfo held = typeof(CombatManager).GetField("_wallFaceHeld", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
FieldInfo tier = typeof(CombatManager).GetField("_lastCastTier", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
FieldInfo area = typeof(CombatManager).GetField("_lastCastWasRing", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
FieldInfo resolving = typeof(CombatManager).GetField("_awaitingCastResolution", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
|
||||
FakeHost.HeadingDeg = 270; // facing west, the target is north
|
||||
attack.Invoke(rig.C, new object[] { target });
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "far off: no cast yet");
|
||||
Check.True((bool)held.GetValue(rig.C)!, "the wall is held for its turn");
|
||||
Check.Eq(FakeHost.Turns, 1, "turned first");
|
||||
|
||||
rig.Now = rig.Now.AddMilliseconds(300);
|
||||
attack.Invoke(rig.C, new object[] { target });
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "300 ms later: still no cast (the server catching up)");
|
||||
|
||||
rig.Now = rig.Now.AddMilliseconds(CombatManager.WallFaceSettleMs);
|
||||
attack.Invoke(rig.C, new object[] { target });
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "after the settle: cast");
|
||||
Check.Eq(NameOf(FakeHost.Casts[0].SpellId), "Slithering Flames", "the wall");
|
||||
Check.False((bool)held.GetValue(rig.C)!, "not held");
|
||||
Check.Eq(FakeHost.Turns, 1, "no turn with the cast");
|
||||
Check.True((bool)area.GetValue(rig.C)!, "an area cast for the bookkeeping (like a ring)");
|
||||
Check.Eq((int)tier.GetValue(rig.C)!, -5, "filed with the area tiers: level 5, negative");
|
||||
|
||||
// Already facing: straight to the cast, no turn. (A fresh rig: no cast resolving.)
|
||||
var facing = new Rig(7, "Slithering Flames", "Flame Bolt VI");
|
||||
facing.S.MonsterRules.Add(new MonsterRule { Name = "Drudge", DamageType = "Fire", UseBolt = true, UseWall = true });
|
||||
facing.C.activeTargetId = Target;
|
||||
FakeHost.HeadingDeg = 0;
|
||||
attack.Invoke(facing.C, new object[] { target });
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "facing: cast at once");
|
||||
Check.Eq(NameOf(FakeHost.Casts[0].SpellId), "Slithering Flames", "the wall");
|
||||
Check.Eq(FakeHost.Turns, 0, "no turn");
|
||||
Check.True((bool)resolving.GetValue(facing.C)!, "the cast arms the cadence guard (no turn until it resolves)");
|
||||
|
||||
// A bolt (wall not due) is single-target as before.
|
||||
var bolt = new Rig(7, "Slithering Flames", "Flame Bolt VI");
|
||||
bolt.S.MonsterRules.Add(new MonsterRule { Name = "Drudge", DamageType = "Fire", UseBolt = true, UseWall = true });
|
||||
bolt.C.activeTargetId = Target;
|
||||
bolt.InPath = 1;
|
||||
FakeHost.HeadingDeg = 270;
|
||||
attack.Invoke(bolt.C, new object[] { target });
|
||||
Check.Eq(NameOf(FakeHost.Casts.Single().SpellId), "Flame Bolt VI", "wall not due: the bolt, no turn needed");
|
||||
Check.Eq(FakeHost.Turns, 0, "targeted casts don't turn (the server does)");
|
||||
Check.False((bool)area.GetValue(bolt.C)!, "single-target");
|
||||
Check.Eq((int)tier.GetValue(bolt.C)!, 6, "positive tier");
|
||||
}
|
||||
|
||||
private static void OldSettings()
|
||||
{
|
||||
var old = JsonSerializer.Deserialize("{\"MinRingTargets\":4,\"BlastRange\":10}", RynthAiJsonContext.Default.LegacyUiSettings)!;
|
||||
Check.Eq(old.WallRange, 0, "old profile: Wall Range off");
|
||||
Check.Eq(old.MinWallTargets, 3, "old profile: Min Wall Targets 3");
|
||||
var fresh = new LegacyUiSettings();
|
||||
Check.True(fresh.WallRange == 0 && fresh.MinWallTargets == 3, "new settings: off / 3");
|
||||
|
||||
var bridge = JsonSerializer.Deserialize("{\"MinRingTargets\":4}", RynthAiJsonContext.Default.SettingsBridgePayload)!;
|
||||
Check.True(bridge.WallRange == null && bridge.MinWallTargets == null, "older engine's settings: no wall values (left alone)");
|
||||
var newer = JsonSerializer.Deserialize("{\"WallRange\":15,\"MinWallTargets\":4}", RynthAiJsonContext.Default.SettingsBridgePayload)!;
|
||||
Check.True(newer.WallRange == 15 && newer.MinWallTargets == 4, "an engine with walls: carried");
|
||||
|
||||
const string oldRules = "[{\"Name\":\"Default\",\"Priority\":1,\"UseBolt\":true},{\"Name\":\"Drudge\",\"UseRing\":true,\"UseBlast\":true}]";
|
||||
var rules = JsonSerializer.Deserialize(oldRules, RynthAiJsonContext.Default.MonsterRuleList)!;
|
||||
Check.False(rules[0].UseWall || rules[1].UseWall, "old monster file: Wall off");
|
||||
rules[1].UseWall = true;
|
||||
string json = JsonSerializer.Serialize(rules, RynthAiJsonContext.Default.MonsterRuleList);
|
||||
Check.True(json.Contains("\"UseWall\": true"), "saved with UseWall");
|
||||
var back = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.MonsterRuleList)!;
|
||||
Check.True(back[1].UseWall && !back[0].UseWall, "round trip keeps it");
|
||||
var payload = JsonSerializer.Deserialize("{\"rules\":[{\"Name\":\"Mite\",\"UseWall\":true}]}", RynthAiJsonContext.Default.MonstersBridgePayload)!;
|
||||
Check.True(payload.Rules[0].UseWall, "the engine's rules JSON carries UseWall");
|
||||
}
|
||||
}
|
||||
241
Tools/RynthCore.RynthAiHostTests/Tests/WorldCacheTypedTests.cs
Normal file
241
Tools/RynthCore.RynthAiHostTests/Tests/WorldCacheTypedTests.cs
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Typed world-cache placement (2026-10-05; spotted by Silentkelpie, rynth PR #1). A positioned,
|
||||
// non-creature object with a known item type used to be filed only when it was a weapon, armor,
|
||||
// caster or container, and then always into OUR inventory: other players' wielded gear and
|
||||
// ground-dropped weapons counted as ours, and keys, gems, comps and food on the ground stayed
|
||||
// Unknown and were re-probed every 2 s for good. Now they get the class their type gives and are
|
||||
// filed by who has them. Pinned here: what goes where, that hazards (dynamic or static, typed or
|
||||
// not) still register, that corpses are still found, and the loot classes (scrolls, slot-typed
|
||||
// weapons) on objects that come this way.
|
||||
internal static class WorldCacheTypedTests
|
||||
{
|
||||
private const uint Player = 0x50000E01;
|
||||
private const uint OtherPlayer = 0x50000E99;
|
||||
private const uint Lb = 0xA9B40000;
|
||||
private const uint Here = Lb | 0x1C;
|
||||
private const uint Dungeon = 0x01D90105;
|
||||
|
||||
private const uint TMelee = 0x1, TArmor = 0x2, TFood = 0x20, TMisc = 0x80, TContainer = 0x200, TGem = 0x800,
|
||||
TComps = 0x1000, TWritable = 0x2000, TKey = 0x4000, TManaStone = 0x80000, TLifeStone = 0x10000000;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("world cache: typed ground items get their class and stay on the landscape", GroundItems);
|
||||
r.Add("world cache: another player's wielded gear is neither ours nor a ground item", OtherPlayersGear);
|
||||
r.Add("world cache: our wielded gear and positioned pack / side-pack items are inventory", OwnGear);
|
||||
r.Add("world cache: ground gear is landscape; unreadable ownership keeps the old filing", GroundGearAndUnknownOwnership);
|
||||
r.Add("world cache: hazards still register (dynamic Misc, static, untyped); lava-named gear does not", Hazards);
|
||||
r.Add("world cache: corpses: named at once, and a Container-typed one named late is rescued", Corpses);
|
||||
r.Add("world cache: an Unknown whose type arrives late is filed as the item it is", LateType);
|
||||
r.Add("world cache: scrolls, slot-typed weapons, chests, lifestones; signs stay scenery", LootClasses);
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static uint _next;
|
||||
|
||||
private static void World()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
_next = 0x80310001;
|
||||
FakeHost.Names[Player] = "Cache Tester";
|
||||
FakeHost.Positions[Player] = (Here, 96f, 96f, 0f);
|
||||
FakeHost.PlayerPose = (Here, 96f, 96f, 0f);
|
||||
FakeHost.Containers[Player] = 0; // installs GetObjectOwnershipInfo for every test
|
||||
}
|
||||
|
||||
/// <summary>A positioned non-creature: on the ground (owner null = ownership unreadable).</summary>
|
||||
private static uint Obj(string name, uint type, uint? container = 0, uint? wielder = null, uint cell = Here, uint id = 0)
|
||||
{
|
||||
if (id == 0) id = _next++;
|
||||
if (name.Length > 0) FakeHost.Names[id] = name;
|
||||
FakeHost.Positions[id] = (cell, 97f, 97f, 0f);
|
||||
if (type != 0) FakeHost.ItemTypes[id] = type;
|
||||
if (container != null) FakeHost.Containers[id] = container.Value;
|
||||
if (wielder != null) FakeHost.Wielders[id] = wielder.Value;
|
||||
FakeHost.NotAttackable.Add(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
/// <summary>Classifies <paramref name="ids"/> the way the game does: CreateObject, then ticks.</summary>
|
||||
private static WorldObjectCache Classify(params uint[] ids)
|
||||
{
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
foreach (uint id in ids) cache.OnCreateObject(id);
|
||||
for (int i = 0; i < 12; i++) cache.Tick(); // past the 8 same-tick retries
|
||||
return cache;
|
||||
}
|
||||
|
||||
private static void Reclassify(WorldObjectCache cache)
|
||||
=> typeof(WorldObjectCache).GetMethod("ReclassifyUnknownDynamics", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(cache, null);
|
||||
|
||||
private static AcObjectClass ClassOf(WorldObjectCache c, uint id)
|
||||
=> c.AllKnownObjects().FirstOrDefault(w => w.Id == unchecked((int)id))?.ObjectClass ?? (AcObjectClass)(-1);
|
||||
private static bool InInventory(WorldObjectCache c, uint id) => c.GetInventory().Any(w => w.Id == unchecked((int)id));
|
||||
private static bool OnLandscape(WorldObjectCache c, uint id) => c.GetLandscapeObjects().Any(w => w.Id == unchecked((int)id));
|
||||
|
||||
private static void Where(WorldObjectCache c, uint id, AcObjectClass cls, bool inv, bool land, string what)
|
||||
{
|
||||
Check.Eq(ClassOf(c, id), cls, what + ": class");
|
||||
Check.Eq(InInventory(c, id), inv, what + ": in the inventory");
|
||||
Check.Eq(OnLandscape(c, id), land, what + ": on the landscape");
|
||||
}
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void GroundItems()
|
||||
{
|
||||
World();
|
||||
uint key = Obj("Key to the Black Gate", TKey);
|
||||
uint gem = Obj("Black Opal", TGem);
|
||||
uint comp = Obj("Prismatic Taper", TComps);
|
||||
uint food = Obj("Apple", TFood);
|
||||
uint stone = Obj("Mana Stone", TManaStone);
|
||||
var c = Classify(key, gem, comp, food, stone);
|
||||
Where(c, key, AcObjectClass.Key, false, true, "ground key");
|
||||
Where(c, gem, AcObjectClass.Gem, false, true, "ground gem");
|
||||
Where(c, comp, AcObjectClass.SpellComponent, false, true, "ground comps");
|
||||
Where(c, food, AcObjectClass.Food, false, true, "ground food");
|
||||
Where(c, stone, AcObjectClass.ManaStone, false, true, "ground mana stone");
|
||||
Reclassify(c);
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("stuck Unknown", StringComparison.Ordinal)), "nothing left for the Unknown re-probe");
|
||||
}
|
||||
|
||||
private static void OtherPlayersGear()
|
||||
{
|
||||
World();
|
||||
uint sword = Obj("Fire Tachi", TMelee, container: 0, wielder: OtherPlayer);
|
||||
uint armor = Obj("Amuli Shadow Coat", TArmor, container: 0, wielder: OtherPlayer);
|
||||
var c = Classify(sword, armor);
|
||||
Where(c, sword, AcObjectClass.MeleeWeapon, false, false, "another player's sword");
|
||||
Where(c, armor, AcObjectClass.Armor, false, false, "another player's coat");
|
||||
Check.False(c.GetContainedItems(unchecked((int)Player)).Any(w => w.Id == unchecked((int)sword)), "not one of our items");
|
||||
}
|
||||
|
||||
private static void OwnGear()
|
||||
{
|
||||
World();
|
||||
uint sword = Obj("Fire Tachi", TMelee, container: 0, wielder: Player);
|
||||
uint shield = Obj("Kite Shield", TArmor, container: Player);
|
||||
uint pack = 0x80310F00;
|
||||
FakeHost.Names[pack] = "Pack";
|
||||
FakeHost.ItemTypes[pack] = TContainer;
|
||||
FakeHost.Containers[pack] = Player;
|
||||
uint gem = Obj("Black Opal", TGem, container: pack);
|
||||
var c = Classify(sword, shield, gem);
|
||||
Where(c, sword, AcObjectClass.MeleeWeapon, true, false, "our wielded sword");
|
||||
Where(c, shield, AcObjectClass.Armor, true, false, "our shield");
|
||||
Where(c, gem, AcObjectClass.Gem, true, false, "a gem in our side pack");
|
||||
}
|
||||
|
||||
private static void GroundGearAndUnknownOwnership()
|
||||
{
|
||||
World();
|
||||
uint dropped = Obj("Fire Tachi", TMelee, container: 0);
|
||||
uint unknownSword = Obj("Frost Tachi", TMelee, container: null);
|
||||
uint unknownGem = Obj("Black Opal", TGem, container: null);
|
||||
var c = Classify(dropped, unknownSword, unknownGem);
|
||||
Where(c, dropped, AcObjectClass.MeleeWeapon, false, true, "a sword on the ground");
|
||||
Where(c, unknownSword, AcObjectClass.MeleeWeapon, true, false, "a sword whose owner can't be read (as before)");
|
||||
Where(c, unknownGem, AcObjectClass.Gem, false, true, "a gem whose owner can't be read");
|
||||
}
|
||||
|
||||
private static void Hazards()
|
||||
{
|
||||
World();
|
||||
uint lava = Obj("Lava", TMisc, container: 0, cell: Dungeon);
|
||||
uint lavaUnknownOwner = Obj("Pool of Acid", TMisc, container: null, cell: Dungeon + 1);
|
||||
uint staticAcid = Obj("Pool of Acid", TMisc, container: null, cell: Dungeon + 2, id: 0x71D90002);
|
||||
uint untyped = Obj("Magma", 0, container: null, cell: Dungeon + 3);
|
||||
uint gear = Obj("Lava Gauntlets", TArmor, container: 0, cell: Dungeon + 4);
|
||||
var c = Classify(lava, lavaUnknownOwner, staticAcid, untyped, gear);
|
||||
Check.True(c.IsHazardCell(Dungeon), "a dynamic Misc lava hotspot registers its cell");
|
||||
Where(c, lava, AcObjectClass.Misc, false, true, "the lava hotspot");
|
||||
Check.True(c.IsHazardCell(Dungeon + 1), "a hotspot whose owner can't be read registers");
|
||||
Check.True(c.IsHazardCell(Dungeon + 2), "a static hotspot registers");
|
||||
Where(c, staticAcid, AcObjectClass.Unknown, false, true, "the static hotspot stays scenery");
|
||||
Check.True(c.IsHazardCell(Dungeon + 3), "an untyped hotspot registers");
|
||||
Check.False(c.IsHazardCell(Dungeon + 4), "gauntlets named Lava on the floor are not a hazard (as before)");
|
||||
Check.True(System.IO.Directory.Exists(System.IO.Path.Combine(Program.TempRoot, "DungeonHazards")), "hazards persist to the scratch folder, not C:\\Games");
|
||||
}
|
||||
|
||||
private static void Corpses()
|
||||
{
|
||||
World();
|
||||
uint named = Obj("Corpse of Drudge Skulker", TContainer, container: 0);
|
||||
uint late = Obj("", TContainer, container: 0);
|
||||
var c = Classify(named, late);
|
||||
Where(c, named, AcObjectClass.Corpse, false, true, "a named corpse");
|
||||
Where(c, late, AcObjectClass.Container, false, true, "a nameless container (before its name)");
|
||||
FakeHost.Names[late] = "Corpse of Drudge Ravener";
|
||||
Reclassify(c);
|
||||
Where(c, late, AcObjectClass.Corpse, false, true, "named late: rescued as a corpse");
|
||||
|
||||
// The corpse flag alone, name never matching.
|
||||
World();
|
||||
uint flagged = Obj("Drudge Remains", TContainer, container: 0);
|
||||
FakeHost.Bitfields[flagged] = 0x2000;
|
||||
var c2 = Classify(flagged);
|
||||
Where(c2, flagged, AcObjectClass.Corpse, false, true, "a corpse by its weenie flag");
|
||||
}
|
||||
|
||||
private static void LateType()
|
||||
{
|
||||
World();
|
||||
uint gem = Obj("Black Opal", 0, container: 0);
|
||||
var c = Classify(gem);
|
||||
Where(c, gem, AcObjectClass.Unknown, false, true, "no type yet: Unknown landscape");
|
||||
FakeHost.ItemTypes[gem] = TGem;
|
||||
FakeHost.Logs.Clear();
|
||||
Reclassify(c);
|
||||
Where(c, gem, AcObjectClass.Gem, false, true, "type arrived: a ground gem");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("typed 1 Unknown object", StringComparison.Ordinal)), "logged once");
|
||||
|
||||
// Our own item whose type arrives late goes to the inventory.
|
||||
World();
|
||||
uint mine = Obj("Fire Tachi", 0, container: 0, wielder: Player);
|
||||
var c2 = Classify(mine);
|
||||
FakeHost.ItemTypes[mine] = TMelee;
|
||||
Reclassify(c2);
|
||||
Where(c2, mine, AcObjectClass.MeleeWeapon, true, false, "our sword typed late");
|
||||
|
||||
// A creature still wins: a late Creature type promotes, it is not filed as an item.
|
||||
World();
|
||||
uint mob = Obj("Drudge Skulker", 0, container: 0);
|
||||
var c3 = Classify(mob);
|
||||
FakeHost.ItemTypes[mob] = 0x10;
|
||||
Reclassify(c3);
|
||||
Check.Eq(ClassOf(c3, mob), AcObjectClass.Monster, "a late creature type: Monster");
|
||||
}
|
||||
|
||||
private static void LootClasses()
|
||||
{
|
||||
World();
|
||||
uint scroll = Obj("Scroll of Gift of Essence", TWritable, container: 0);
|
||||
FakeHost.DataIds[(scroll, 28)] = 2001;
|
||||
uint book = Obj("Tattered Journal", TWritable, container: 0); // no "Scroll" name, no spell
|
||||
uint slayer = Obj("Driftwarden Greataxe", TMisc, container: 0);
|
||||
FakeHost.Ints[(slayer, 9)] = 0x00100000; // ValidLocations: melee weapon slot
|
||||
uint chest = Obj("Chest", TContainer, container: null, id: 0x71D90010);
|
||||
uint stone = Obj("Life Stone", TLifeStone, container: null, id: 0x71D90011);
|
||||
uint sign = Obj("Sign", TMisc, container: null, id: 0x71D90012);
|
||||
var c = Classify(scroll, book, slayer, chest, stone, sign);
|
||||
Where(c, scroll, AcObjectClass.Scroll, false, true, "a spell scroll on the ground");
|
||||
Where(c, book, AcObjectClass.Book, false, true, "a journal on the ground");
|
||||
Where(c, slayer, AcObjectClass.MeleeWeapon, false, true, "a Misc-typed weapon with a weapon slot");
|
||||
Where(c, chest, AcObjectClass.Container, false, true, "a static chest");
|
||||
Where(c, stone, AcObjectClass.Lifestone, false, true, "a lifestone");
|
||||
Where(c, sign, AcObjectClass.Unknown, false, true, "a static sign stays scenery");
|
||||
}
|
||||
}
|
||||
|
|
@ -41,4 +41,9 @@
|
|||
<None Include="Fixtures\**\*" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
|
||||
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
131
Tools/RynthCore.TrackerSessionTests/KillCounterTests.cs
Normal file
131
Tools/RynthCore.TrackerSessionTests/KillCounterTests.cs
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.RynthTracker;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.TrackerSessionTests;
|
||||
|
||||
// KillCounter (RynthTracker 0.3.0): one cast, several kills. The events are what the client
|
||||
// sees, in the order it sees them: our damage lines (one per monster a spell hurt), the
|
||||
// server's kill notices, and corpses ("Corpse of X") a few seconds later.
|
||||
internal static partial class Program
|
||||
{
|
||||
private static readonly DateTime T0 = new(2026, 10, 3, 2, 0, 0, DateTimeKind.Utc);
|
||||
private static DateTime At(double seconds) => T0.AddSeconds(seconds);
|
||||
|
||||
private static void Hit(KillCounter k, string line, double t)
|
||||
{
|
||||
Check(CombatText.TryParseOutgoingHit(line, out string victim, out _), $"parses: {line}");
|
||||
k.OnHit(victim, At(t));
|
||||
}
|
||||
|
||||
private static void TestKillCounter()
|
||||
{
|
||||
Console.WriteLine("-- kill counter");
|
||||
|
||||
// ACE ring: every kill gets its notice; the corpses that follow add nothing.
|
||||
{
|
||||
var k = new KillCounter();
|
||||
Hit(k, "You blast Drudge Skulker for 80 points with Flame Ring VI.", 0.0);
|
||||
Hit(k, "You blast Drudge Slinker for 75 points with Flame Ring VI.", 0.1);
|
||||
Hit(k, "You blast Mosswart Worshipper for 70 points with Flame Ring VI.", 0.2);
|
||||
k.OnKillNotice("Drudge Skulker's seared corpse smolders before you!", At(2.0));
|
||||
k.OnKillNotice("You bring Drudge Slinker to a fiery end!", At(2.1));
|
||||
k.OnKillNotice("Mosswart Worshipper is incinerated by your assault!", At(2.2));
|
||||
Eq(k.OnCorpse("Drudge Skulker", At(5.0)), KillCounter.CorpseResult.Notified, "ring: corpse 1 matches its notice");
|
||||
Eq(k.OnCorpse("Drudge Slinker", At(5.1)), KillCounter.CorpseResult.Notified, "ring: corpse 2 matches its notice");
|
||||
Eq(k.OnCorpse("Mosswart Worshipper", At(5.2)), KillCounter.CorpseResult.Notified, "ring: corpse 3 matches its notice");
|
||||
Eq(k.Kills, 3, "ring: three kills, none counted twice");
|
||||
}
|
||||
|
||||
// Conquest chain: the primary's kill has a notice, the extra targets' don't.
|
||||
{
|
||||
var k = new KillCounter();
|
||||
Hit(k, "You blast Drudge Skulker for 120 points with Lightning Chain VI.", 0.0);
|
||||
Hit(k, "You blast Drudge Slinker for 60 points with Lightning Chain VI.", 0.2);
|
||||
Hit(k, "You blast Mosswart Worshipper for 30 points with Lightning Chain VI.", 0.4);
|
||||
k.OnKillNotice("You smite Drudge Skulker mightily!", At(2.0)); // the primary
|
||||
Hit(k, "You blast Mosswart Worshipper for 30 points with Lightning Chain VI.", 2.2);
|
||||
// the Slinker died on that cast with no line and no notice
|
||||
Eq(k.OnCorpse("Drudge Skulker", At(5.0)), KillCounter.CorpseResult.Notified, "chain: the primary's corpse is its notice's");
|
||||
Eq(k.OnCorpse("Drudge Slinker", At(5.1)), KillCounter.CorpseResult.Counted, "chain: the silent extra kill counts from its corpse");
|
||||
Hit(k, "You blast Mosswart Worshipper for 30 points with Lightning Chain VI.", 6.0);
|
||||
Eq(k.OnCorpse("Mosswart Worshipper", At(9.0)), KillCounter.CorpseResult.Counted, "chain: the last extra target too");
|
||||
Eq(k.Kills, 3, "chain: three kills from the chain fight");
|
||||
Eq(k.CorpseKills, 2, "chain: two of them found by their corpse");
|
||||
}
|
||||
|
||||
// A swarm: same-named monsters, two die from one cast, one notice.
|
||||
{
|
||||
var k = new KillCounter();
|
||||
Hit(k, "You blast Olthoi Swarm Soldier for 100 points with Lightning Chain VI.", 0.0);
|
||||
Hit(k, "You blast Olthoi Swarm Soldier for 100 points with Lightning Chain VI.", 0.1);
|
||||
k.OnKillNotice("Olthoi Swarm Soldier's death is preceded by a sharp, stabbing pain!", At(1.5));
|
||||
Eq(k.OnCorpse("Olthoi Swarm Soldier", At(4.0)), KillCounter.CorpseResult.Notified, "swarm: first corpse takes the notice");
|
||||
Eq(k.OnCorpse("Olthoi Swarm Soldier", At(4.1)), KillCounter.CorpseResult.Counted, "swarm: second corpse counts");
|
||||
Eq(k.OnCorpse("Olthoi Swarm Soldier", At(4.2)), KillCounter.CorpseResult.HitNotCounted, "swarm: never more corpses than the volley hit");
|
||||
Eq(k.Kills, 2, "swarm: two kills");
|
||||
}
|
||||
|
||||
// The primary's kill notice and an extra target's line in one volley, same name: the
|
||||
// notice stands for the primary, so the silent twin still counts from its corpse.
|
||||
{
|
||||
var k = new KillCounter();
|
||||
Hit(k, "You blast Olthoi Swarm Soldier for 100 points with Lightning Chain VI.", 0.0); // earlier cast, primary
|
||||
k.OnKillNotice("You slay Olthoi Swarm Soldier viciously enough to impart death several times over!", At(2.0));
|
||||
Hit(k, "You blast Olthoi Swarm Soldier for 60 points with Lightning Chain VI.", 2.1); // the twin, same cast
|
||||
Eq(k.OnCorpse("Olthoi Swarm Soldier", At(5.0)), KillCounter.CorpseResult.Notified, "notice + twin: primary's corpse");
|
||||
Hit(k, "You blast Olthoi Swarm Soldier for 60 points with Lightning Chain VI.", 5.5); // a lone hit later on the twin
|
||||
Eq(k.OnCorpse("Olthoi Swarm Soldier", At(8.0)), KillCounter.CorpseResult.Counted, "notice + twin: the twin counts");
|
||||
Eq(k.Kills, 2, "notice + twin: two kills");
|
||||
}
|
||||
|
||||
// Several casts at the same two monsters are still two monsters (max, not sum).
|
||||
{
|
||||
var k = new KillCounter();
|
||||
for (int cast = 0; cast < 4; cast++)
|
||||
{
|
||||
Hit(k, "You blast Drudge Skulker for 10 points with Flame Ring VI.", cast * 2.0);
|
||||
Hit(k, "You blast Drudge Skulker for 10 points with Flame Ring VI.", cast * 2.0 + 0.1);
|
||||
}
|
||||
Eq(k.OnCorpse("Drudge Skulker", At(9.0)), KillCounter.CorpseResult.Counted, "repeat casts: first corpse");
|
||||
Eq(k.OnCorpse("Drudge Skulker", At(9.1)), KillCounter.CorpseResult.Counted, "repeat casts: second corpse");
|
||||
Eq(k.OnCorpse("Drudge Skulker", At(9.2)), KillCounter.CorpseResult.HitNotCounted, "repeat casts: not a third");
|
||||
}
|
||||
|
||||
// Single-target fighting: a corpse with no notice is someone else's kill, as before.
|
||||
{
|
||||
var k = new KillCounter();
|
||||
Hit(k, "You slash Banderling Scout for 12 points of slashing damage!", 0.0);
|
||||
Hit(k, "You slash Banderling Scout for 14 points of slashing damage!", 1.5);
|
||||
Eq(k.OnCorpse("Banderling Scout", At(4.0)), KillCounter.CorpseResult.HitNotCounted, "single-target: not counted without a notice");
|
||||
Eq(k.OnCorpse("Tusker Guard", At(4.0)), KillCounter.CorpseResult.NotOurs, "a corpse we never hit");
|
||||
Eq(k.Kills, 0, "single-target: no kills");
|
||||
}
|
||||
|
||||
// Lines a second apart are separate casts (a melee swing each), not one volley.
|
||||
{
|
||||
var k = new KillCounter();
|
||||
Hit(k, "You slash Banderling Scout for 12 points of slashing damage!", 0.0);
|
||||
Hit(k, "You slash Banderling Guard for 14 points of slashing damage!", 1.0);
|
||||
Eq(k.OnCorpse("Banderling Guard", At(3.0)), KillCounter.CorpseResult.HitNotCounted, "a second apart is not multi-target");
|
||||
}
|
||||
|
||||
// Expiry: a multi-target hit stops vouching for a corpse after TokenLifeMs.
|
||||
{
|
||||
var k = new KillCounter();
|
||||
Hit(k, "You blast Drudge Skulker for 10 points with Flame Ring VI.", 0.0);
|
||||
Hit(k, "You blast Drudge Slinker for 10 points with Flame Ring VI.", 0.1);
|
||||
Eq(k.OnCorpse("Drudge Slinker", At(0.1 + KillCounter.TokenLifeMs / 1000.0 + 1)), KillCounter.CorpseResult.NotOurs, "an old hit doesn't count");
|
||||
}
|
||||
|
||||
// A notice waits NoticeLifeMs for its corpse, then is forgotten (the kill stays counted).
|
||||
{
|
||||
var k = new KillCounter();
|
||||
k.OnKillNotice("You smite Drudge Skulker mightily!", At(0));
|
||||
Eq(k.OnCorpse("Drudge Skulker", At(KillCounter.NoticeLifeMs / 1000.0 + 1)), KillCounter.CorpseResult.NotOurs, "an old notice is gone");
|
||||
Eq(k.Kills, 1, "the notice's kill stays counted");
|
||||
k.Reset();
|
||||
Eq(k.Kills, 0, "reset clears the count");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -11,7 +11,7 @@ namespace RynthCore.TrackerSessionTests;
|
|||
// Self-contained; fails on zero assertions.
|
||||
//
|
||||
// Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||
internal static class Program
|
||||
internal static partial class Program
|
||||
{
|
||||
private static int _asserts;
|
||||
private static int _fails;
|
||||
|
|
@ -45,6 +45,7 @@ internal static class Program
|
|||
TestFileNames();
|
||||
TestFiles();
|
||||
TestCleanup();
|
||||
TestKillCounter();
|
||||
|
||||
Console.WriteLine($"\n{_asserts} assertions, {_fails} failed.");
|
||||
if (_asserts == 0) { Console.WriteLine("ABORT: zero assertions ran."); return 1; }
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@
|
|||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthTracker\TrackerSessionStore.cs" Link="Linked\TrackerSessionStore.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthTracker\KillCounter.cs" Link="Linked\KillCounter.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\CombatText.cs" Link="Linked\CombatText.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -30,6 +30,8 @@
|
|||
<Compile Include="..\..\Plugins\Shared\RynthAiScriptApi.cs" Link="Plugin\Shared\RynthAiScriptApi.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\UseAudit.cs" Link="Plugin\Shared\UseAudit.cs" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\*.cs" Link="Sdk\%(Filename)%(Extension)" />
|
||||
<!-- The SDK takes CurrentApiVersion from the engine's constant since plugin manifests (API v79). -->
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Sdk\PluginContractVersion.cs" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.PluginCore\*.cs" Link="Sdk\%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
|
||||
|
|
@ -37,4 +39,9 @@
|
|||
<None Include="Scripts\**\*.lua" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- RynthLuaPaths.cs uses the install-folder resolver. -->
|
||||
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -38,4 +38,9 @@
|
|||
<Compile Include="..\..\..\RynthCore\src\RynthCore.StatusAgent\Dat\DxtUtil.cs" Link="Engine\DxtUtil.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- RynthLuaPaths.cs uses the install-folder resolver. -->
|
||||
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -106,6 +106,13 @@ internal static class NavBake
|
|||
/// </summary>
|
||||
public static float AgentMaxClimb = 1.0f;
|
||||
|
||||
/// <summary>
|
||||
/// How far a wall outline may be simplified. 1.3 m was fine inside the old 2 m agent margin;
|
||||
/// with a body-sized radius (0.6 m: gaps under about 4 m no longer close, Shoushi 2026-10-08)
|
||||
/// a 1.3 m simplification could cut a corner through the margin, so it follows the radius.
|
||||
/// </summary>
|
||||
internal static float EdgeMaxError(float radius) => Math.Min(1.3f, radius + 0.15f);
|
||||
|
||||
private static RcNavMeshBuildSettings Settings(float radius, bool tiled, float cellSize)
|
||||
{
|
||||
float slopeDeg = (float)(Math.Acos(TerrainSampler.FloorZ) * 180.0 / Math.PI);
|
||||
|
|
@ -115,7 +122,7 @@ internal static class NavBake
|
|||
agentHeight = 2.0f, agentRadius = radius, agentMaxClimb = AgentMaxClimb, agentMaxSlope = slopeDeg,
|
||||
minRegionSize = 8, mergedRegionSize = 20, partitioning = (int)RcPartition.WATERSHED,
|
||||
filterLowHangingObstacles = true, filterLedgeSpans = true, filterWalkableLowHeightSpans = true,
|
||||
edgeMaxLen = 12f, edgeMaxError = 1.3f, vertsPerPoly = VertsPerPoly, detailSampleDist = 6f, detailSampleMaxError = 1f,
|
||||
edgeMaxLen = 12f, edgeMaxError = EdgeMaxError(radius), vertsPerPoly = VertsPerPoly, detailSampleDist = 6f, detailSampleMaxError = 1f,
|
||||
// The solo bake reads the intermediate results (the .obj export); the tiled bake only
|
||||
// needs the finished navmesh, and keeping every tile's heightfields cost 1.5-2.7 GB a chunk.
|
||||
tiled = tiled, tileSize = tiled ? TiledTileSize : 0, keepInterResults = !tiled, buildAll = true,
|
||||
|
|
|
|||
|
|
@ -37,6 +37,8 @@ internal static class Program
|
|||
Run(nameof(EndToEndAroundAWall), EndToEndAroundAWall);
|
||||
Run(nameof(LandmassesAndSameLand), LandmassesAndSameLand);
|
||||
Run(nameof(PathGoesRoundAPortal), PathGoesRoundAPortal);
|
||||
Run(nameof(TripWalkFromTileFiles), TripWalkFromTileFiles);
|
||||
Run(nameof(RealTripWalk), RealTripWalk);
|
||||
}
|
||||
finally { try { Directory.Delete(_root, true); } catch { } }
|
||||
Console.WriteLine();
|
||||
|
|
@ -385,4 +387,72 @@ internal static class Program
|
|||
double d = Math.Sqrt((nearPt.X - 95) * (nearPt.X - 95) + (nearPt.Z - 96) * (nearPt.Z - 96));
|
||||
Check(nearRef != 0 && d >= PortalAvoid.LiveRadius - 0.01, $"a goal beside the portal snaps to ground outside its circle ({d:F2} u away)");
|
||||
}
|
||||
|
||||
// ── A planned trip's walk, from the tile files (TilePathFinder, on a worker in the plugin) ──
|
||||
|
||||
private static void TripWalkFromTileFiles()
|
||||
{
|
||||
// The wall: from the south of tile 0 to the south of tile 2, the only way is round the north.
|
||||
string dir = Bake("tripwall", (0, 0, 192, 192), (192, 150, 384, 192), (384, 0, 576, 192));
|
||||
BuildGraph(dir, out NavGraph g);
|
||||
var from = new RynthCore.Plugin.RynthNav.WorldPt(100, 20, 0);
|
||||
var to = new RynthCore.Plugin.RynthNav.WorldPt(480, 20, double.NaN);
|
||||
var finder = new TilePathFinder(dir, g, null);
|
||||
var path = finder.Walk(from, to, false, out string note);
|
||||
Check(path != null && path.Count >= 4, $"a path round the wall ({path?.Count} corners; {note})");
|
||||
Check(note == "", "no gaps: " + note);
|
||||
Check(path != null && path.Exists(p => p.Y > 150), "it goes north through the passage");
|
||||
Check(path != null && Math.Abs(path[^1].X - 480) < 3 && Math.Abs(path[^1].Y - 20) < 3, "and ends at the goal");
|
||||
Check(path != null && path.TrueForAll(p => !double.IsNaN(p.H) && Math.Abs(p.H) < 2), "heights from the navmesh");
|
||||
Check(finder.TilesRead >= 3, $"read the tiles it needed ({finder.TilesRead})");
|
||||
var thin = RynthCore.Plugin.RynthNav.TripPathBuilder.Thin(path!);
|
||||
Check(thin.Exists(p => p.Y > 150), "thinned, it still goes round");
|
||||
|
||||
// Without the route graph, a short leg is planned on the tiles alone.
|
||||
var direct = new TilePathFinder(dir, null, null).Walk(from, to, false, out string note2);
|
||||
Check(direct != null && direct.Exists(p => p.Y > 150), "without the graph: the same way round (" + note2 + ")");
|
||||
// No navmesh at the far end: none, and why.
|
||||
var nowhere = new TilePathFinder(dir, g, null).Walk(from, new RynthCore.Plugin.RynthNav.WorldPt(2000, 2000, 0), false, out string why);
|
||||
Check(nowhere == null && why.Length > 0, "no tile at the end: no path (" + why + ")");
|
||||
|
||||
// An Atlas portal on the straight line over open ground: kept out of, unless it's the leg's own.
|
||||
string open = Bake("tripportal", (0, 0, 192, 192));
|
||||
var spot = new[] { new PortalAvoid.Spot(95, 96, PortalAvoid.MapRadius, "Unwanted Portal") };
|
||||
var round = new TilePathFinder(open, null, spot).Walk(new(30, 96, 0), new(160, 96, 0), false, out _);
|
||||
double gap = double.MaxValue;
|
||||
for (int i = 1; round != null && i < round.Count; i++) gap = Math.Min(gap, PortalAvoid.SegmentDistance(95, 96, round[i - 1].X, round[i - 1].Y, round[i].X, round[i].Y));
|
||||
Check(round != null && gap >= PortalAvoid.MapRadius - 0.01, $"the walk keeps out of the portal's circle ({gap:F2} u)");
|
||||
var own = new TilePathFinder(open, null, spot).Walk(new(30, 96, 0), new(95, 96, 0), true, out _);
|
||||
Check(own != null && Math.Abs(own[^1].X - 95) < 3, "walking into that portal: it's the goal, not avoided");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The real map (read only, when it's installed): Holtburg to Lytelthorpe, about 11k yd over
|
||||
/// land, as the path markers and "save as nav route" would work it out. Prints the size and time.
|
||||
/// </summary>
|
||||
private static void RealTripWalk()
|
||||
{
|
||||
string dir = Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData";
|
||||
string graphFile = Path.Combine(dir, NavGraph.FileName);
|
||||
if (!File.Exists(graphFile)) { Console.WriteLine(" (no real NavData here: skipped)"); return; }
|
||||
NavGraph g = NavGraph.Load(graphFile);
|
||||
var from = RynthCore.Plugin.RynthNav.WorldPt.FromMap(42.08, 33.6, double.NaN);
|
||||
var to = RynthCore.Plugin.RynthNav.WorldPt.FromMap(-0.8, 51.2, double.NaN);
|
||||
// Landmasses, as the plugin has them (LoadGraph): Lytelthorpe's centre probes onto a roof,
|
||||
// a landmass of one region; the ground beside it is found instead.
|
||||
g.BuildComponents();
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
var finder = new TilePathFinder(dir, g, null);
|
||||
var path = finder.Walk(from, to, false, out string note);
|
||||
long ms = sw.ElapsedMilliseconds;
|
||||
Check(path != null, "Holtburg to Lytelthorpe on the real navmesh: " + note);
|
||||
if (path == null) return;
|
||||
var thin = RynthCore.Plugin.RynthNav.TripPathBuilder.Thin(path);
|
||||
int corners = RynthCore.Plugin.RynthNav.TripPathBuilder.Thin(path, maxSpacing: 0).Count;
|
||||
double len = 0;
|
||||
for (int i = 1; i < thin.Count; i++) len += thin[i - 1].FlatDistance(thin[i]);
|
||||
Console.WriteLine($" Holtburg -> Lytelthorpe: {path.Count} corners, {corners} kept by thinning, {thin.Count} with a point every {RynthCore.Plugin.RynthNav.TripPathBuilder.MaxSpacing} yd, {len:F0} yd, {finder.TilesRead} tiles read, {ms} ms{(note.Length > 0 ? "; " + note : "")}");
|
||||
Check(len > from.FlatDistance(to) * 0.98 && len < from.FlatDistance(to) * 2.5, $"a sensible length ({len:F0} vs {from.FlatDistance(to):F0} straight)");
|
||||
Check(ms < 30000, $"worked out in reasonable time ({ms} ms)");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,13 @@
|
|||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\PortalAvoid.cs" Link="Linked\PortalAvoid.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\AvoidFilter.cs" Link="Linked\AvoidFilter.cs" />
|
||||
<Compile Include="..\RynthNav.Baker\GraphBuild.cs" Link="Linked\GraphBuild.cs" />
|
||||
<!-- A planned trip's walk from the tile files (TilePathFinder) and what it needs. -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TilePathFinder.cs" Link="Linked\TilePathFinder.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripPlan.cs" Link="Linked\TripPlan.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripPath.cs" Link="Linked\TripPath.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavCoords.cs" Link="Linked\NavCoords.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TownNet.cs" Link="Linked\TownNet.cs" />
|
||||
<Compile Include="..\RynthNav.PortalGraph\PortalRoute.cs" Link="Linked\PortalRoute.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -39,6 +39,10 @@ internal static partial class Program
|
|||
Run(nameof(RecallListColdSpellbook), RecallListColdSpellbook);
|
||||
Run(nameof(RecallMemoryRoundTrip), RecallMemoryRoundTrip);
|
||||
Run(nameof(RecallMessages), RecallMessages);
|
||||
Run(nameof(HandCastOnALifestone), HandCastOnALifestone);
|
||||
Run(nameof(HandCastPortalTie), HandCastPortalTie);
|
||||
Run(nameof(RecallNotLinked), RecallNotLinked);
|
||||
Run(nameof(DungeonLandblocksFromTheAtlas), DungeonLandblocksFromTheAtlas);
|
||||
Run(nameof(AtlasSearchAndBestMatch), AtlasSearchAndBestMatch);
|
||||
Run(nameof(ArrowSingleTarget), ArrowSingleTarget);
|
||||
Run(nameof(ArrowAlongRoute), ArrowAlongRoute);
|
||||
|
|
@ -53,6 +57,7 @@ internal static partial class Program
|
|||
RunTownNet();
|
||||
RunAvoid();
|
||||
RunTravelPlan();
|
||||
RunTripExport();
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(_fails == 0 && _asserts > 0
|
||||
|
|
@ -248,6 +253,128 @@ internal static partial class Program
|
|||
Check(RecallMemory.Classify("", "Tom") == RecallEvent.None, "empty");
|
||||
Check(RecallMemory.SlotFor(RecallEvent.RecallingHome, out var slot) && slot == RecallSlot.House, "house slot");
|
||||
Check(!RecallMemory.SlotFor(RecallEvent.RecallingMarketplace, out _), "marketplace has no slot");
|
||||
// Your spell words (Spellcasting, 17) start a hand cast; the same words typed in local chat don't.
|
||||
Check(RecallMemory.Classify("You say, \"Zojak Ququ\"", "Tom", RecallMemory.ChatTypeSpellcasting) == RecallEvent.OwnSpellWords, "own spell words");
|
||||
Check(RecallMemory.Classify("You say, \"Zojak Ququ\"", "Tom", 2) == RecallEvent.None, "typed in local chat");
|
||||
Check(RecallMemory.Classify("You say, \"Zojak Ququ\"", "Tom") == RecallEvent.None, "chat type unknown");
|
||||
Check(RecallMemory.Classify("Ann says, \"Zojak Ququ\"", "Tom", RecallMemory.ChatTypeSpellcasting) == RecallEvent.None, "someone else casting");
|
||||
}
|
||||
|
||||
// ── A recall cast by hand: which one, from where it landed ───────────────
|
||||
|
||||
private const string Me = "Aelrynth|Tom";
|
||||
|
||||
private static RecallSpot At(double ns, double ew, string label = "") => new() { OnMap = true, Ns = ns, Ew = ew, Label = label };
|
||||
|
||||
private static void HandCastOnALifestone()
|
||||
{
|
||||
var mem = new RecallMemory();
|
||||
var known = new HashSet<int> { RecallPlanner.LifestoneRecall, RecallPlanner.PrimaryPortalTieRecall };
|
||||
var k = RecallPlanner.GuessHandCast(At(42.1, 33.6), atLifestone: true, known, mem, Me, 30, out var slot, out _);
|
||||
Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Lifestone, "on a lifestone: Lifestone Recall");
|
||||
|
||||
mem.Set(Me, RecallSlot.Lifestone, At(42.1, 33.6));
|
||||
k = RecallPlanner.GuessHandCast(At(42.11, 33.6), true, known, mem, Me, 30, out _, out _);
|
||||
Check(k == RecallPlanner.HandCast.Nothing, "the same lifestone again: nothing new");
|
||||
k = RecallPlanner.GuessHandCast(At(-30.0, 70.0), true, known, mem, Me, 30, out slot, out _);
|
||||
Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Lifestone, "tied somewhere else since: learned again");
|
||||
|
||||
k = RecallPlanner.GuessHandCast(At(42.1, 33.6), true, new HashSet<int> { RecallPlanner.PrimaryPortalTieRecall }, new RecallMemory(), Me, 30, out _, out _);
|
||||
Check(k == RecallPlanner.HandCast.Nothing, "no Lifestone Recall in the spellbook: not it");
|
||||
|
||||
// On the @lifestone lifestone with Recall the Sanctuary known: either spell, can't tell.
|
||||
var mem2 = new RecallMemory();
|
||||
mem2.Set(Me, RecallSlot.Sanctuary, At(42.1, 33.6));
|
||||
var known2 = new HashSet<int> { RecallPlanner.LifestoneRecall, RecallPlanner.RecallTheSanctuary };
|
||||
k = RecallPlanner.GuessHandCast(At(42.1, 33.6), true, known2, mem2, Me, 30, out _, out _);
|
||||
Check(k == RecallPlanner.HandCast.Nothing, "Recall the Sanctuary could land there too");
|
||||
k = RecallPlanner.GuessHandCast(At(10, 10), true, null, mem2, Me, 30, out _, out var why);
|
||||
Check(k == RecallPlanner.HandCast.Nothing && why.Contains("spellbook"), "a cold spellbook teaches nothing");
|
||||
}
|
||||
|
||||
private static void HandCastPortalTie()
|
||||
{
|
||||
var oneTie = new HashSet<int> { RecallPlanner.SecondaryPortalTieRecall };
|
||||
var k = RecallPlanner.GuessHandCast(At(-33.5, 72.8), false, oneTie, new RecallMemory(), Me, 30, out var slot, out _);
|
||||
Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Tie2, "the only tie recall known");
|
||||
|
||||
var both = new HashSet<int> { RecallPlanner.PrimaryPortalTieRecall, RecallPlanner.SecondaryPortalTieRecall };
|
||||
k = RecallPlanner.GuessHandCast(At(-33.5, 72.8), false, both, new RecallMemory(), Me, 30, out _, out _);
|
||||
Check(k == RecallPlanner.HandCast.AskTie, "both tie recalls known: ask which");
|
||||
|
||||
var mem = new RecallMemory();
|
||||
mem.Set(Me, RecallSlot.Tie1, At(-33.5, 72.8));
|
||||
k = RecallPlanner.GuessHandCast(At(-33.51, 72.8), false, both, mem, Me, 30, out slot, out _);
|
||||
Check(k == RecallPlanner.HandCast.Nothing && slot == RecallSlot.Tie1, "a known tie's landing: nothing new");
|
||||
|
||||
// Portal Recall: lands where the last portal went (known: nothing; unknown: ask).
|
||||
var withPortalRecall = new HashSet<int> { RecallPlanner.PrimaryPortalTieRecall, RecallPlanner.PortalRecall };
|
||||
var mem2 = new RecallMemory();
|
||||
mem2.Set(Me, RecallSlot.LastPortal, At(12, 34));
|
||||
k = RecallPlanner.GuessHandCast(At(12, 34), false, withPortalRecall, mem2, Me, 30, out _, out _);
|
||||
Check(k == RecallPlanner.HandCast.Nothing, "the last portal's landing: Portal Recall");
|
||||
k = RecallPlanner.GuessHandCast(At(-33.5, 72.8), false, withPortalRecall, mem2, Me, 30, out slot, out _);
|
||||
Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Tie1, "elsewhere, last portal known: the one tie");
|
||||
k = RecallPlanner.GuessHandCast(At(-33.5, 72.8), false, withPortalRecall, new RecallMemory(), Me, 30, out _, out _);
|
||||
Check(k == RecallPlanner.HandCast.AskTie, "last portal unknown: could be Portal Recall, ask");
|
||||
|
||||
k = RecallPlanner.GuessHandCast(At(1, 1), false, new HashSet<int> { RecallPlanner.LifestoneRecall }, new RecallMemory(), Me, 30, out _, out _);
|
||||
Check(k == RecallPlanner.HandCast.Nothing, "off a lifestone with no tie recall: not one RynthNav knows");
|
||||
|
||||
// A dungeon landing (off the map) is learned too, and matched by its label.
|
||||
var dungeon = new RecallSpot { OnMap = false, Label = "a dungeon (landblock 6145)" };
|
||||
k = RecallPlanner.GuessHandCast(dungeon, false, oneTie, new RecallMemory(), Me, 30, out slot, out _);
|
||||
Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Tie2, "a tie into a dungeon");
|
||||
var mem3 = new RecallMemory();
|
||||
mem3.Set(Me, RecallSlot.Tie2, new RecallSpot { OnMap = false, Label = "a dungeon (landblock 6145)" });
|
||||
k = RecallPlanner.GuessHandCast(dungeon, false, oneTie, mem3, Me, 30, out _, out _);
|
||||
Check(k == RecallPlanner.HandCast.Nothing, "the same dungeon again: nothing new");
|
||||
|
||||
// Once learned, the planner uses it.
|
||||
var plannerMem = new RecallMemory();
|
||||
plannerMem.Set(Me, RecallSlot.Tie2, At(-33.5, 72.8, "Shoushi"));
|
||||
var list = RecallPlanner.Build(Atlas.Empty, oneTie, plannerMem, Me, new List<string>());
|
||||
Check(list.Exists(o => o.SpellId == RecallPlanner.SecondaryPortalTieRecall && Math.Abs(o.Ns + 33.5) < 1e-9), "the learned tie is planned");
|
||||
}
|
||||
|
||||
private static void DungeonLandblocksFromTheAtlas()
|
||||
{
|
||||
// A dungeon landblock's tile is its surface (dungeon cells aren't baked): the walk must
|
||||
// know it's in one. Dungeon places and dungeon portal destinations count; a landblock
|
||||
// with places on the map (a town, its cellars) never does.
|
||||
Atlas atlas = Atlas.Parse(@"{""locations"":[
|
||||
{""name"":""Surface"",""type"":""Portal"",""cell"":""000102C8"",""place"":""dungeon"",""dest"":{""cell"":""26E5001D"",""place"":""outdoor"",""ns"":81.68,""ew"":-71.16}},
|
||||
{""name"":""Holtburg Dungeon Portal"",""type"":""Portal"",""cell"":""A9B40021"",""place"":""outdoor"",""ns"":42.0,""ew"":33.0,""dest"":{""cell"":""01F60230"",""place"":""dungeon""}},
|
||||
{""name"":""Shoushi"",""type"":""Town"",""cell"":""DA55001D"",""place"":""outdoor"",""ns"":-33.5,""ew"":72.8},
|
||||
{""name"":""Cellar Vendor"",""type"":""Vendor"",""cell"":""DA550105"",""place"":""dungeon""},
|
||||
{""name"":""Odd"",""type"":""Landmark"",""cell"":""zz"",""place"":""dungeon""}
|
||||
]}");
|
||||
HashSet<uint> d = atlas.DungeonLandblocks();
|
||||
Check(d.Contains(0x0001), "a dungeon place's landblock");
|
||||
Check(d.Contains(0x01F6), "a portal's dungeon destination");
|
||||
Check(!d.Contains(0x26E5) && !d.Contains(0xA9B4), "outdoor landblocks aren't dungeons");
|
||||
Check(!d.Contains(0xDA55), "a town landblock with a dungeon cell isn't one");
|
||||
Check(d.Count == 2, "nothing else (a bad cell is skipped)");
|
||||
}
|
||||
|
||||
private static void RecallNotLinked()
|
||||
{
|
||||
Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkLifestone, 0) == RecallSlot.Lifestone, "no lifestone tie: Lifestone Recall");
|
||||
Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkPortal, RecallPlanner.PrimaryPortalTieRecall) == RecallSlot.Tie1, "no primary tie");
|
||||
Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkPortal, RecallPlanner.SecondaryPortalTieRecall) == RecallSlot.Tie2, "no secondary tie");
|
||||
Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkPortal, RecallPlanner.PortalRecall) == RecallSlot.LastPortal, "no last portal");
|
||||
Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkPortal, 0) == null, "a portal recall cast by hand: can't tell which");
|
||||
Check(RecallPlanner.SlotUnlinked(0x0402, RecallPlanner.LifestoneRecall) == null, "a fizzle isn't a missing tie");
|
||||
Check(RecallPlanner.SpellFor(RecallSlot.Tie2) == RecallPlanner.SecondaryPortalTieRecall && RecallPlanner.SpellFor(RecallSlot.House) == 0, "slot spells");
|
||||
|
||||
var mem = new RecallMemory();
|
||||
mem.Set(Me, RecallSlot.Lifestone, At(42.1, 33.6));
|
||||
int v = mem.Version;
|
||||
mem.Clear(Me, RecallSlot.Lifestone);
|
||||
Check(mem.Get(Me, RecallSlot.Lifestone) == null && mem.Version > v, "forgotten (and saved)");
|
||||
var notes = new List<string>();
|
||||
RecallPlanner.Build(Atlas.Empty, new HashSet<int> { RecallPlanner.LifestoneRecall }, mem, Me, notes);
|
||||
Check(notes.Exists(n => n.Contains("Lifestone Recall") && n.Contains("cast Lifestone Recall once")), "the note says how to teach it");
|
||||
}
|
||||
|
||||
// ── Atlas ────────────────────────────────────────────────────────────────
|
||||
|
|
|
|||
|
|
@ -28,6 +28,14 @@
|
|||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TownNet.cs" Link="Linked\TownNet.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\PortalAvoid.cs" Link="Linked\PortalAvoid.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TravelPlan.cs" Link="Linked\TravelPlan.cs" />
|
||||
<!-- The planned trip, its path, the path markers and "save as nav route" (TripExportTests). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripPlan.cs" Link="Linked\TripPlan.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripPath.cs" Link="Linked\TripPath.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\PathMarkers.cs" Link="Linked\PathMarkers.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavRouteExport.cs" Link="Linked\NavRouteExport.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\Nav3DText.cs" Link="Linked\Nav3DText.cs" />
|
||||
<!-- RynthAi's own nav reader/writer: the saved route is read back the way RynthAi reads it. -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\LegacyUi\NavRouteParser.cs" Link="Linked\NavRouteParser.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
389
Tools/RynthNav.RouteTests/TripExportTests.cs
Normal file
389
Tools/RynthNav.RouteTests/TripExportTests.cs
Normal file
|
|
@ -0,0 +1,389 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthNav;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthNav.RouteTests;
|
||||
|
||||
// A planned trip on the ground and as a RynthAi nav route: the trip's legs (PlannedTrip), the
|
||||
// walking path thinned (TripPathBuilder), the path markers (PathMarkers: what's built, what's drawn,
|
||||
// the next waypoint, when the markers go) and "save as nav route" (NavRouteExport: walks, recalls,
|
||||
// portals and the Town Network as nav steps, read back with RynthAi's own reader; a file that's
|
||||
// there isn't replaced without being asked).
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunTripExport()
|
||||
{
|
||||
Run(nameof(ThinKeepsCornersAndSplitsStraights), ThinKeepsCornersAndSplitsStraights);
|
||||
Run(nameof(StopShortAlongThePath), StopShortAlongThePath);
|
||||
Run(nameof(TripLegsWalkRecallPortal), TripLegsWalkRecallPortal);
|
||||
Run(nameof(TripPathStraightLineWhenNoMesh), TripPathStraightLineWhenNoMesh);
|
||||
Run(nameof(ExportWalkRecallPortalRoundTrip), ExportWalkRecallPortalRoundTrip);
|
||||
Run(nameof(ExportCommandRecallAndDungeonEntrance), ExportCommandRecallAndDungeonEntrance);
|
||||
Run(nameof(ExportTownNetwork), ExportTownNetwork);
|
||||
Run(nameof(ExportStopsAtAStepWithNoNavEquivalent), ExportStopsAtAStepWithNoNavEquivalent);
|
||||
Run(nameof(SaveRefusesToOverwrite), SaveRefusesToOverwrite);
|
||||
Run(nameof(MarkersBuiltFromTheTrip), MarkersBuiltFromTheTrip);
|
||||
Run(nameof(MarkersEmitNearTheCharacter), MarkersEmitNearTheCharacter);
|
||||
Run(nameof(MarkersNextWaypointAdvances), MarkersNextWaypointAdvances);
|
||||
Run(nameof(MarkersClearOffTheTrip), MarkersClearOffTheTrip);
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>A navmesh-like path a→b: a point every 2 yd, swinging 10 yd out round an obstacle halfway.</summary>
|
||||
private static List<WorldPt>? FakeWalk(WorldPt a, WorldPt b, bool intoPortal, out string note)
|
||||
{
|
||||
note = "";
|
||||
var pts = new List<WorldPt>();
|
||||
double len = a.FlatDistance(b);
|
||||
int n = Math.Max(2, (int)(len / 2));
|
||||
double nx = -(b.Y - a.Y) / len, ny = (b.X - a.X) / len; // left of the way
|
||||
for (int i = 0; i <= n; i++)
|
||||
{
|
||||
double t = (double)i / n;
|
||||
double off = 10.0 * Math.Max(0, 1 - Math.Abs(t - 0.5) * 8); // a tent 10 yd high from t=0.375 to 0.625
|
||||
pts.Add(new WorldPt(a.X + (b.X - a.X) * t + nx * off, a.Y + (b.Y - a.Y) * t + ny * off, 5.0));
|
||||
}
|
||||
return pts;
|
||||
}
|
||||
|
||||
private static PlannedTrip Trip(List<RouteStep> steps, double startNs, double startEw, string goal, double goalNs, double goalEw,
|
||||
List<TripRecall>? recalls = null, string enterPortal = "", string enterName = "", bool startOnMap = true, int id = 1)
|
||||
{
|
||||
WorldPt start = WorldPt.FromMap(startNs, startEw, 5.0);
|
||||
uint lb = start.Landblock;
|
||||
uint cell = (lb << 16) | 0x0001;
|
||||
return new PlannedTrip(id, steps, goal, goalNs, goalEw, startOnMap, start, cell, recalls, enterPortal, enterName);
|
||||
}
|
||||
|
||||
private sealed class Recorder : IMarkerSink
|
||||
{
|
||||
public readonly List<(float X, float Y, float Z, float R, uint C)> Rings = new();
|
||||
public readonly List<(float X1, float Y1, float Z1, float X2, float Y2, float Z2, uint C)> Lines = new();
|
||||
public int Tris;
|
||||
public void Ring(float x, float y, float z, float radius, float thickness, uint colorArgb) => Rings.Add((x, y, z, radius, colorArgb));
|
||||
public void Line(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb) => Lines.Add((x1, y1, z1, x2, y2, z2, colorArgb));
|
||||
public void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint colorArgb) => Tris++;
|
||||
}
|
||||
|
||||
// ── Thinning ─────────────────────────────────────────────────────────
|
||||
|
||||
private static void ThinKeepsCornersAndSplitsStraights()
|
||||
{
|
||||
// 100 yd east in 1 yd steps with 0.2 yd wobble, then 50 yd north; heights unknown at first.
|
||||
var raw = new List<WorldPt>();
|
||||
for (int i = 0; i <= 100; i++) raw.Add(new WorldPt(1000 + i, 1000 + (i % 2 == 0 ? 0.2 : -0.2), i < 3 ? double.NaN : 7));
|
||||
for (int i = 1; i <= 50; i++) raw.Add(new WorldPt(1100, 1000 + i, 7));
|
||||
raw.Add(new WorldPt(1100, 1050.1, 7)); // a near duplicate
|
||||
List<WorldPt> thin = TripPathBuilder.Thin(raw);
|
||||
Check(thin.Count < 12, $"151 navmesh points thin to a few ({thin.Count})");
|
||||
Check(thin[0].FlatDistance(raw[0]) < 0.01 && thin[^1].FlatDistance(raw[^1]) < 0.6, "the ends are kept");
|
||||
Check(thin.Any(p => Math.Abs(p.X - 1100) < 0.6 && Math.Abs(p.Y - 1000) < 0.6), "the corner is kept");
|
||||
for (int i = 1; i < thin.Count; i++)
|
||||
Check(thin[i - 1].FlatDistance(thin[i]) <= TripPathBuilder.MaxSpacing + 0.01, $"no stretch longer than {TripPathBuilder.MaxSpacing} yd ({i})");
|
||||
Check(thin.All(p => !double.IsNaN(p.H)), "unknown heights filled from the neighbours");
|
||||
foreach (WorldPt p in raw)
|
||||
{
|
||||
double best = double.MaxValue;
|
||||
for (int i = 1; i < thin.Count; i++) best = Math.Min(best, PlannedTrip.SegmentDistance(p, thin[i - 1], thin[i]));
|
||||
if (best > TripPathBuilder.ThinTolerance + 0.01) { Check(false, $"a dropped point is {best:F2} yd off the thinned path"); break; }
|
||||
}
|
||||
Check(TripPathBuilder.Thin(new List<WorldPt> { new(0, 0, 1), new(0, 100, 1) }).Count == 3, "a 100 yd straight gets a point every 60 yd at most (2 stretches)");
|
||||
}
|
||||
|
||||
private static void StopShortAlongThePath()
|
||||
{
|
||||
var path = new List<WorldPt> { new(0, 0, 1), new(10, 0, 1), new(10, 3, 1) };
|
||||
List<WorldPt> s = TripPathBuilder.StopShort(path, 5);
|
||||
Check(s.Count == 2 && Math.Abs(s[^1].X - 8) < 1e-9 && Math.Abs(s[^1].Y) < 1e-9, "5 yd short, back round the corner");
|
||||
Check(TripPathBuilder.StopShort(path, 20).Count == 1, "shorter than that: only the start");
|
||||
Check(TripPathBuilder.StopShort(path, 0).Count == 3, "0: unchanged");
|
||||
}
|
||||
|
||||
// ── The trip's legs ──────────────────────────────────────────────────
|
||||
|
||||
private static void TripLegsWalkRecallPortal()
|
||||
{
|
||||
var steps = new List<RouteStep>
|
||||
{
|
||||
new(10, 10, false, true, "Lifestone Recall", 0, 20, 20), // cast here, land at 20,20
|
||||
new(20.5, 20, true, false, "Portal to Far", -1, 50, 50), // walk to a portal, land at 50,50
|
||||
new(50.4, 50.3, false, false, "walk"), // walk to the goal
|
||||
};
|
||||
var trip = Trip(steps, 10, 10, "Far Goal", 50.4, 50.3, new List<TripRecall> { new("Lifestone Recall", 1635, "", 13) });
|
||||
Check(trip.WalkFrom[0] == null && trip.Point[0] is WorldPt c && c.FlatDistance(trip.Start) < 0.01, "a recall walks nowhere; it's cast at the start");
|
||||
Check(trip.WalkFrom[1] is WorldPt f1 && Math.Abs(f1.Ns - 20) < 1e-9 && Math.Abs(f1.Ew - 20) < 1e-9, "the next walk starts at the recall's landing");
|
||||
Check(trip.Point[1] is WorldPt p1 && Math.Abs(p1.Ns - 20.5) < 1e-9, "...and ends at the portal");
|
||||
Check(trip.WalkFrom[2] is WorldPt f2 && Math.Abs(f2.Ns - 50) < 1e-9, "the last walk starts at the portal's landing");
|
||||
Check(trip.RecallOf(0)?.SpellId == 1635 && trip.RecallOf(1) == null, "the recall by index");
|
||||
|
||||
// A portal into a dungeon (no landing on the map) and nothing after it: the dungeon goto.
|
||||
var into = Trip(new List<RouteStep> { new(10.2, 10.2, true, false, "Matron Hive") }, 10, 10, "Matron Hive", 10.2, 10.2,
|
||||
enterPortal: "Portal to Matron Hive", enterName: "Matron Hive");
|
||||
Check(into.EndsInEntrance && into.PortalName(0) == "Portal to Matron Hive", "a dungeon goto's portal is the portal object, not the dungeon's name");
|
||||
// No steps: a plain walk to the goal.
|
||||
var plain = Trip(new List<RouteStep>(), 10, 10, "Near", 10.3, 10.1);
|
||||
Check(plain.Count == 1 && plain.WalkFrom[0] != null && !plain.Steps[0].UsePortal, "no steps = one walk");
|
||||
}
|
||||
|
||||
private static void TripPathStraightLineWhenNoMesh()
|
||||
{
|
||||
var trip = Trip(new List<RouteStep> { new(10.5, 10, false, false, "walk") }, 10, 10, "G", 10.5, 10);
|
||||
TripPath p = TripPathBuilder.Build(trip, (WorldPt a, WorldPt b, bool ip, out string note) => { note = "no navmesh at its start"; return null; }, null);
|
||||
Check(p.Walks[0] != null && p.Walks[0]!.Length == 3, $"a straight line, split every 60 yd (120 yd: {p.Walks[0]?.Length})");
|
||||
Check(p.Notes.Count == 1 && p.Notes[0].Contains("step 1") && p.Notes[0].Contains("straight"), "...with a note: " + string.Join("; ", p.Notes));
|
||||
TripPath q = TripPathBuilder.Build(trip, FakeWalk, null);
|
||||
Check(q.Notes.Count == 0 && q.Walks[0]!.Length < 20, $"the navmesh path, thinned ({q.Walks[0]!.Length} points)");
|
||||
Check(q.Walks[0]!.Any(w => PlannedTrip.SegmentDistance(w, trip.Start, trip.Point[0]!.Value) > 9), "it keeps the swing round the obstacle");
|
||||
}
|
||||
|
||||
// ── Save as nav route ────────────────────────────────────────────────
|
||||
|
||||
private static void ExportWalkRecallPortalRoundTrip()
|
||||
{
|
||||
var steps = new List<RouteStep>
|
||||
{
|
||||
new(10, 10, false, true, "Lifestone Recall", 0, 20, 20),
|
||||
new(20.5, 20, true, false, "Portal to Far", -1, 50, 50),
|
||||
new(50.4, 50.3, false, false, "walk"),
|
||||
};
|
||||
var trip = Trip(steps, 10, 10, "Far Goal", 50.4, 50.3, new List<TripRecall> { new("Lifestone Recall", 1635, "", 13) });
|
||||
TripPath path = TripPathBuilder.Build(trip, FakeWalk, null);
|
||||
NavRouteExport.Result r = NavRouteExport.Convert(trip, path, null);
|
||||
Check(r.StoppedAt == -1 && r.StopReason == "", "the whole trip converts: " + r.StopReason);
|
||||
List<NavPoint> pts = r.Route.Points;
|
||||
Check(r.Route.RouteType == NavRouteType.Once, "a Once route");
|
||||
Check(pts[0].Type == NavPointType.Recall && pts[0].SpellId == 1635, "first: the recall spell");
|
||||
int portal = pts.FindIndex(p => p.Type == NavPointType.PortalNPC);
|
||||
Check(portal > 1, "then walking points, then the portal step");
|
||||
Check(pts.Skip(1).Take(portal - 1).All(p => p.Type == NavPointType.Point), "walking legs are Points");
|
||||
Check(portal - 1 < 15, $"thinned: not every navmesh corner ({portal - 1} points for 120 yd with an obstacle)");
|
||||
NavPoint pn = pts[portal];
|
||||
Check(pn.TargetName == "Portal to Far" && pn.ObjectClass == NavRouteExport.PortalObjectClass && pn.IsTie, "the portal by name, VTank's portal class");
|
||||
Check(Math.Abs(pn.PortalExitNS - 20.5) < 1e-6 && Math.Abs(pn.PortalExitEW - 20) < 1e-6, "at the portal's entrance");
|
||||
NavPoint before = pts[portal - 1];
|
||||
double toPortal = NavCoords.Distance(before.NS, before.EW, 20.5, 20);
|
||||
Check(toPortal > NavRouteExport.PortalStopShort - 0.5 && toPortal < 12, $"the walk stops short of the entrance ({toPortal:F1} yd)");
|
||||
Check(pts[^1].Type == NavPointType.Point && NavCoords.Distance(pts[^1].NS, pts[^1].EW, 50.4, 50.3) < 0.5, "the last point is the goal");
|
||||
Check(NavCoords.Distance(pts[portal + 1].NS, pts[portal + 1].EW, 50, 50) < TripPathBuilder.MaxSpacing, "after the portal the walk starts near its landing");
|
||||
Check(pts.Where(p => p.Type == NavPointType.Point).All(p => Math.Abs(p.Z - 5.0 / 240.0) < 1e-9), "heights in nav units (metres / 240)");
|
||||
|
||||
// Read back with RynthAi's own reader.
|
||||
var back = NavRouteParser.LoadFromLines(r.Route.ToLines());
|
||||
Check(back.LoadWarning == null && back.Points.Count == pts.Count && back.RouteType == NavRouteType.Once, "RynthAi reads it back whole");
|
||||
bool same = true;
|
||||
for (int i = 0; i < pts.Count && same; i++)
|
||||
same = back.Points[i].Type == pts[i].Type && Math.Abs(back.Points[i].NS - pts[i].NS) < 1e-9 && Math.Abs(back.Points[i].EW - pts[i].EW) < 1e-9
|
||||
&& back.Points[i].SpellId == pts[i].SpellId && back.Points[i].TargetName == pts[i].TargetName && back.Points[i].ObjectClass == pts[i].ObjectClass;
|
||||
Check(same, "every step the same after the round trip");
|
||||
Check(r.Waypoints + r.Portals + r.Recalls == pts.Count, "the counts add up");
|
||||
}
|
||||
|
||||
private static void ExportCommandRecallAndDungeonEntrance()
|
||||
{
|
||||
var steps = new List<RouteStep>
|
||||
{
|
||||
new(10, 10, false, true, "@lifestone", 0, 20, 20),
|
||||
new(20.3, 20.2, true, false, "Matron Hive"), // Entrance.EndingInPortal labels it with the dungeon
|
||||
};
|
||||
var trip = Trip(steps, 10, 10, "Matron Hive", 20.3, 20.2, new List<TripRecall> { new("@lifestone", 0, "@lifestone", 15) },
|
||||
enterPortal: "Portal to Matron Hive", enterName: "Matron Hive");
|
||||
NavRouteExport.Result r = NavRouteExport.Convert(trip, TripPathBuilder.Build(trip, FakeWalk, null), null);
|
||||
List<NavPoint> pts = r.Route.Points;
|
||||
Check(pts[0].Type == NavPointType.Chat && pts[0].ChatCommand == "@lifestone", "a command recall is a chat step");
|
||||
Check(pts[1].Type == NavPointType.Pause && pts[1].PauseTimeMs == NavRouteExport.CommandRecallPauseMs, "...and a pause for its teleport");
|
||||
Check(pts[^1].Type == NavPointType.PortalNPC && pts[^1].TargetName == "Portal to Matron Hive", "it ends with the dungeon's entrance portal, by the portal's name");
|
||||
Check(r.StoppedAt == -1, "nothing left out");
|
||||
var back = NavRouteParser.LoadFromLines(r.Route.ToLines());
|
||||
Check(back.Points.Count == pts.Count && back.Points[0].ChatCommand == "@lifestone" && back.Points[1].PauseTimeMs == NavRouteExport.CommandRecallPauseMs,
|
||||
"read back by RynthAi");
|
||||
}
|
||||
|
||||
private static void ExportTownNetwork()
|
||||
{
|
||||
TownNet net = TownNet.Parse(SmallTownNet(), out _)!;
|
||||
var steps = PortalRoute.Plan(NoPortals, null, net.Links(90, false, null), 0, 0, 40, 40, out _, out int used);
|
||||
Check(used == 2 && steps.Count == 3 && steps[1].IsHub, "the plan: walk to the entry, the network, walk on");
|
||||
var trip = Trip(steps, 0, 0, "Eastwatch", 40, 40);
|
||||
TripPath path = TripPathBuilder.Build(trip, FakeWalk, net);
|
||||
Check(path.Hub[1] != null && path.Hub[1]!.Length >= 2, "the walk inside comes from townnet.json");
|
||||
NavRouteExport.Result r = NavRouteExport.Convert(trip, path, net);
|
||||
List<NavPoint> pts = r.Route.Points;
|
||||
var portals = pts.Where(p => p.Type == NavPointType.PortalNPC).ToList();
|
||||
Check(r.StoppedAt == -1 && portals.Count == 2, "two portal steps: " + r.StopReason);
|
||||
Check(portals[0].TargetName == "Portal to Town Network" && portals[1].TargetName == "Portal to Eastwatch", "into the network, then the exit by name");
|
||||
int exit = pts.IndexOf(portals[1]), entry = pts.IndexOf(portals[0]);
|
||||
Check(exit - entry >= 2, "waypoints inside the network between them");
|
||||
// Inside: the network's landblock 0x0007 (coordinates the way RynthAi reads a dungeon pose).
|
||||
// The stored walk (60,-70) to (70,-70) to (86.5,-70) is one straight line: thinned to its end,
|
||||
// stopped 2 yd short of the exit portal.
|
||||
NavCoordinateHelper(0x0007016Bu, 84.5, -70, out double ins, out double iew);
|
||||
Check(pts.Skip(entry + 1).Take(exit - entry - 1).Any(p => Math.Abs(p.NS - ins) < 0.001 && Math.Abs(p.EW - iew) < 0.001), "inside points in dungeon coordinates");
|
||||
NavCoordinateHelper(0x0007016Bu, 86.5, -70, out double xns, out double xew);
|
||||
Check(Math.Abs(portals[1].PortalExitNS - xns) < 1e-6 && Math.Abs(portals[1].PortalExitEW - xew) < 1e-6, "the exit portal where it stands");
|
||||
|
||||
// Without townnet.json: stop before the network, say why.
|
||||
NavRouteExport.Result none = NavRouteExport.Convert(trip, TripPathBuilder.Build(trip, FakeWalk, null), null);
|
||||
Check(none.StoppedAt == 1 && none.StopReason.Contains("Town Network"), "no network data: stops at it: " + none.StopReason);
|
||||
Check(none.Route.Points.Count > 0 && none.Route.Points[^1].Type == NavPointType.PortalNPC, "...keeping the walk to the entry portal");
|
||||
}
|
||||
|
||||
private static void NavCoordinateHelper(uint cell, double x, double y, out double ns, out double ew) => NavCoords.FromCell(cell, x, y, out ns, out ew);
|
||||
|
||||
private static void ExportStopsAtAStepWithNoNavEquivalent()
|
||||
{
|
||||
var steps = new List<RouteStep>
|
||||
{
|
||||
new(10.2, 10, false, false, "walk"),
|
||||
new(10.2, 10, false, true, "Some Recall", 3, 20, 20), // index 3: not in the trip's recalls
|
||||
new(20.1, 20, false, false, "walk"),
|
||||
};
|
||||
var trip = Trip(steps, 10, 10, "G", 20.1, 20, new List<TripRecall>());
|
||||
NavRouteExport.Result r = NavRouteExport.Convert(trip, TripPathBuilder.Build(trip, FakeWalk, null), null);
|
||||
Check(r.StoppedAt == 1 && r.StopReason.StartsWith("step 2:") && r.StopReason.Contains("Some Recall"), "stops at the recall it can't cast: " + r.StopReason);
|
||||
Check(r.Route.Points.Count > 0 && r.Route.Points.All(p => p.Type == NavPointType.Point), "the walk before it is kept");
|
||||
|
||||
var other = Trip(steps, 10, 10, "G", 20.1, 20, new List<TripRecall>(), id: 2);
|
||||
NavRouteExport.Result wrong = NavRouteExport.Convert(other, TripPathBuilder.Build(trip, FakeWalk, null), null);
|
||||
Check(wrong.StoppedAt == 0 && wrong.Route.Points.Count == 0, "a path from another trip isn't used");
|
||||
}
|
||||
|
||||
private static void SaveRefusesToOverwrite()
|
||||
{
|
||||
string dir = Path.Combine(Path.GetTempPath(), "rnav-save-" + Guid.NewGuid().ToString("N"));
|
||||
try
|
||||
{
|
||||
var trip = Trip(new List<RouteStep> { new(10.2, 10, false, false, "walk") }, 10, 10, "G", 10.2, 10);
|
||||
NavRouteParser route = NavRouteExport.Convert(trip, TripPathBuilder.Build(trip, FakeWalk, null), null).Route;
|
||||
Check(NavRouteExport.Save(dir, "To G", route, false, out string path, out bool exists, out string err) && !exists && err == "",
|
||||
"a new file is written (the folder made): " + err);
|
||||
string first = File.ReadAllText(path);
|
||||
Check(NavRouteParser.Load(path).Points.Count == route.Points.Count, "RynthAi loads the file");
|
||||
|
||||
var other = new NavRouteParser { RouteType = NavRouteType.Once };
|
||||
other.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 1, EW = 2 });
|
||||
Check(!NavRouteExport.Save(dir, "To G", other, false, out _, out exists, out _) && exists, "the same name again: refused");
|
||||
Check(File.ReadAllText(path) == first, "...and the file is untouched");
|
||||
Check(!File.Exists(path + ".tmp"), "no temporary file left");
|
||||
Check(NavRouteExport.Save(dir, "To G", other, true, out _, out _, out _) && NavRouteParser.Load(path).Points.Count == 1, "overwrite: replaced");
|
||||
|
||||
Check(NavRouteExport.FileName(" To Holtburg.nav ", out _) == "To Holtburg", "a typed name: trimmed, without .nav");
|
||||
Check(NavRouteExport.FileName("a/b", out string e1) == "" && e1.Length > 0, "a path isn't a name");
|
||||
Check(NavRouteExport.FileName("..", out _) == "" && NavRouteExport.FileName("", out _) == "", "nor .. or nothing");
|
||||
Check(NavRouteExport.SafeName("To Lin: \"Town\"?") == "To Lin Town", "a place's name made safe for a file");
|
||||
}
|
||||
finally { try { Directory.Delete(dir, true); } catch { } }
|
||||
}
|
||||
|
||||
// ── Markers ──────────────────────────────────────────────────────────
|
||||
|
||||
private static (PlannedTrip Trip, TripPath Path) MarkerTrip()
|
||||
{
|
||||
var steps = new List<RouteStep>
|
||||
{
|
||||
new(10, 10, false, true, "Lifestone Recall", 0, 20, 20),
|
||||
new(20.5, 20, true, false, "Portal to Far", -1, 50, 50),
|
||||
new(50.4, 50.3, false, false, "walk"),
|
||||
};
|
||||
var trip = Trip(steps, 10, 10, "Far Goal", 50.4, 50.3, new List<TripRecall> { new("Lifestone Recall", 1635, "", 13) });
|
||||
return (trip, TripPathBuilder.Build(trip, FakeWalk, null));
|
||||
}
|
||||
|
||||
private static void MarkersBuiltFromTheTrip()
|
||||
{
|
||||
var (trip, path) = MarkerTrip();
|
||||
MarkerSnapshot bare = PathMarkers.Build(trip, null, null);
|
||||
Check(!bare.HasPath && bare.Marks.Length == 3, $"without the path: the steps' markers only ({bare.Marks.Length})");
|
||||
Check(bare.Marks[0].Kind == MarkKind.Recall && bare.Marks[0].Label.StartsWith("RECALL LIFESTONE") && bare.Marks[0].Label.Length <= PathMarkers.MaxLabelChars,
|
||||
"the recall, where it's cast: " + bare.Marks[0].Label);
|
||||
Check(bare.Marks[1].Kind == MarkKind.Portal && bare.Marks[1].Label.StartsWith("PORTAL"), "the portal at its entrance");
|
||||
Check(bare.Marks[2].Kind == MarkKind.Goal && bare.Marks[2].Label == "FAR GOAL", "the goal");
|
||||
Check(bare.Marks.All(m => !m.LineToNext), "no lines over ground not worked out yet");
|
||||
|
||||
MarkerSnapshot s = PathMarkers.Build(trip, path, null);
|
||||
Check(s.HasPath && s.Marks.Length > 6, $"with the path: the waypoints too ({s.Marks.Length})");
|
||||
int portal = Array.FindIndex(s.Marks, m => m.Kind == MarkKind.Portal);
|
||||
Check(!s.Marks[portal].LineToNext && !s.Marks[0].LineToNext, "no line across a teleport (after the portal, after the recall)");
|
||||
Check(s.Marks[portal - 1].LineToNext && s.Marks[portal - 1].Kind == MarkKind.Waypoint, "a line into the portal");
|
||||
Check(s.Marks.Count(m => m.Kind == MarkKind.Goal) == 1 && s.Marks[^1].Kind == MarkKind.Goal, "the goal last");
|
||||
for (int i = 1; i < s.Marks.Length; i++)
|
||||
if (s.Marks[i].P.FlatDistance(s.Marks[i - 1].P) < 0.99) { Check(false, $"two markers on one spot ({i})"); break; }
|
||||
Check(PathMarkers.Build(trip, TripPathBuilder.Build(Trip(trip.Steps.ToList(), 10, 10, "x", 1, 1, id: 9), FakeWalk, null), null).HasPath == false,
|
||||
"another trip's path isn't drawn");
|
||||
}
|
||||
|
||||
private static void MarkersEmitNearTheCharacter()
|
||||
{
|
||||
var (trip, path) = MarkerTrip();
|
||||
MarkerSnapshot s = PathMarkers.Build(trip, path, null);
|
||||
WorldPt landing = WorldPt.FromMap(20.3, 20); // on the walk from the recall's landing to the portal, 48 yd short of it
|
||||
var rec = new Recorder();
|
||||
int rings = PathMarkers.Emit(s, new MarkerView(landing.X, landing.Y, 5.0, -1, true, true), rec);
|
||||
Check(rings > 3 && rec.Rings.Count == rings, $"rings near the character ({rings})");
|
||||
Check(rec.Lines.Count > 2, "lines between them");
|
||||
Check(rec.Lines[0].C == PathMarkers.GuideColor, "the guide line goes in first");
|
||||
float lx = (float)(landing.X - Math.Floor(landing.X / 192) * 192), lz = (float)(landing.Y - Math.Floor(landing.Y / 192) * 192);
|
||||
Check(Math.Abs(rec.Lines[0].X1 - lx) < 0.01 && Math.Abs(rec.Lines[0].Z1 - lz) < 0.01, "...from the character's feet, in the landblock's frame");
|
||||
Check(rec.Rings.Any(r => r.C == PathMarkers.PortalColor), "the portal in its own colour");
|
||||
Check(rec.Rings.All(r => r.X > -200 && r.X < 400 && r.Z > -200 && r.Z < 400 && Math.Abs(r.Y - 5.1f) < 0.01), "landblock-local, at path height");
|
||||
Check(rec.Tris > 0, "the portal's label drawn (triangles)");
|
||||
Check(!rec.Rings.Any(r => r.C == PathMarkers.GoalColor), "the goal, far away, isn't drawn");
|
||||
|
||||
var off = new Recorder();
|
||||
PathMarkers.Emit(s, new MarkerView(landing.X, landing.Y, 5.0, -1, false, false), off);
|
||||
Check(off.Tris == 0 && off.Lines.All(l => l.C != PathMarkers.GuideColor), "labels and guide off: neither");
|
||||
|
||||
WorldPt far = WorldPt.FromMap(80, 80);
|
||||
var none = new Recorder();
|
||||
Check(PathMarkers.Emit(s, new MarkerView(far.X, far.Y, 0, -1, true, true), none) == 0 && none.Lines.Count == 0, "nothing far from the trip");
|
||||
|
||||
// A long dense walk: at most MaxWaypointRings rings.
|
||||
var many = new List<Mark>();
|
||||
for (int i = 0; i < 200; i++) many.Add(new Mark(new WorldPt(1000 + i, 1000, 1), MarkKind.Waypoint, "", 0, true));
|
||||
var dense = new MarkerSnapshot(5, true, many.ToArray());
|
||||
var cap = new Recorder();
|
||||
PathMarkers.Emit(dense, new MarkerView(1100, 1000, 1, 100, false, false), cap);
|
||||
Check(cap.Rings.Count <= PathMarkers.MaxWaypointRings + 1 && cap.Lines.Count <= PathMarkers.MaxLines, $"capped ({cap.Rings.Count} rings, {cap.Lines.Count} lines)");
|
||||
Check(cap.Rings.Count(r => r.C == PathMarkers.NextColor) == 1, "the next waypoint in red");
|
||||
}
|
||||
|
||||
private static void MarkersNextWaypointAdvances()
|
||||
{
|
||||
var marks = new List<Mark>();
|
||||
for (int i = 0; i <= 10; i++) marks.Add(new Mark(new WorldPt(1000 + i * 10, 1000, 1), MarkKind.Waypoint, "", 0, true));
|
||||
marks.Add(new Mark(new WorldPt(1100, 1010, 1), MarkKind.Portal, "PORTAL X", 0, false));
|
||||
marks.Add(new Mark(new WorldPt(3000, 3000, 1), MarkKind.Goal, "G", 1, false));
|
||||
var s = new MarkerSnapshot(1, true, marks.ToArray());
|
||||
int next = PathMarkers.Advance(s, -1, 0, 1000, 1000);
|
||||
Check(next == 1, $"standing on the first: the next is the second ({next})");
|
||||
next = PathMarkers.Advance(s, next, 0, 1033, 1001);
|
||||
Check(next == 4, $"part way along: the one ahead ({next})");
|
||||
Check(PathMarkers.Advance(s, next, 0, 1005, 1000) == 4, "never back");
|
||||
Check(PathMarkers.Advance(s, next, 0, 1100, 1009) == 11, "at the end: the portal (the step's own marker)");
|
||||
Check(PathMarkers.Advance(s, 11, 1, 2900, 2900) == 12, "next step: its first marker");
|
||||
Check(PathMarkers.Advance(s, 0, 7, 0, 0) == -1, "a step with no markers: none");
|
||||
}
|
||||
|
||||
private static void MarkersClearOffTheTrip()
|
||||
{
|
||||
var (trip, path) = MarkerTrip();
|
||||
uint startLb = (trip.StartCell >> 16) & 0xFFFF;
|
||||
Check(trip.Covers(startLb, path, null), "where it starts");
|
||||
Check(trip.Covers(WorldPt.FromMap(20, 20).Landblock, path, null), "the recall's landing");
|
||||
Check(trip.Covers(WorldPt.FromMap(35, 35).Landblock, path, null) == false, "between the portal and its landing (a teleport) isn't on it");
|
||||
Check(trip.Covers(WorldPt.FromMap(50.2, 50.1).Landblock, path, null), "the last walk");
|
||||
Check(!trip.Covers(WorldPt.FromMap(-60, -60).Landblock, path, null), "a teleport elsewhere isn't");
|
||||
Check(trip.Covers(0, path, null), "portal space (landblock 0) doesn't count against it");
|
||||
|
||||
TownNet net = TownNet.Parse(SmallTownNet(), out _)!;
|
||||
var steps = PortalRoute.Plan(NoPortals, null, net.Links(90, false, null), 0, 0, 40, 40, out _, out _);
|
||||
var hubTrip = Trip(steps, 0, 0, "Eastwatch", 40, 40);
|
||||
Check(hubTrip.Covers(0x0007, null, net.Contains), "inside the Town Network on a trip that takes it");
|
||||
Check(!trip.Covers(0x0007, path, net.Contains), "...but not on one that doesn't");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue