RynthSuite as of 2026-11-12 (internal b899791): release 2026.11.12.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
16b6531ede
commit
b48c49f76e
110 changed files with 12476 additions and 340 deletions
|
|
@ -269,6 +269,8 @@ internal static unsafe class FakeHost
|
|||
public static bool PluginCommandCalls;
|
||||
/// <summary>What SendPluginCommand answers: true = delivered (the target plugin is loaded).</summary>
|
||||
public static bool PluginCommandDelivered = true;
|
||||
/// <summary>When set, answers each SendPluginCommand (plugin, action, value) instead of <see cref="PluginCommandDelivered"/>.</summary>
|
||||
public static Func<string, string, string, bool>? PluginCommandAnswer;
|
||||
/// <summary>Every SendPluginCommand (plugin, action, value), in order.</summary>
|
||||
public static readonly List<(string Plugin, string Action, string Value)> PluginCommands = new();
|
||||
/// <summary>For each <see cref="PluginCommands"/> entry, how many chat lines were written before it (call order).</summary>
|
||||
|
|
@ -342,7 +344,7 @@ internal static unsafe class FakeHost
|
|||
CloseContainerCalls = false; Closes.Clear(); GroundContainer = 0;
|
||||
SelectedItem = 0;
|
||||
UseOnCalls = false; UsesOn.Clear();
|
||||
PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear(); PluginCommandChatCounts.Clear();
|
||||
PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommandAnswer = null; PluginCommands.Clear(); PluginCommandChatCounts.Clear();
|
||||
TradeVendorCalls = false; TradeActions.Clear(); VendorSells.Clear(); VendorBuys.Clear();
|
||||
CombatModeCalls = false; CombatModeRequests.Clear(); CombatModeRefuse = false; CombatModeRefusals = 0;
|
||||
BusyCalls = false; ForceResets = 0; BusyStateValue = 0;
|
||||
|
|
@ -648,7 +650,8 @@ internal static unsafe class FakeHost
|
|||
{
|
||||
PluginCommands.Add((Marshal.PtrToStringAnsi(plugin) ?? "", Marshal.PtrToStringAnsi(action) ?? "", Marshal.PtrToStringAnsi(value) ?? ""));
|
||||
PluginCommandChatCounts.Add(Chat.Count);
|
||||
return PluginCommandDelivered ? 1 : 0;
|
||||
var (p, a, v) = PluginCommands[^1];
|
||||
return (PluginCommandAnswer?.Invoke(p, a, v) ?? PluginCommandDelivered) ? 1 : 0;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
|
|
|
|||
|
|
@ -70,6 +70,7 @@ internal static class Program
|
|||
LootRaresModeTests.Register(runner);
|
||||
LootChatLineTests.Register(runner);
|
||||
ItemInfoTextColorTests.Register(runner);
|
||||
ItemInfoPartColorTests.Register(runner);
|
||||
LootSurveyTests.Register(runner);
|
||||
PropertyDumpTests.Register(runner);
|
||||
T11LootTests.Register(runner);
|
||||
|
|
@ -88,6 +89,7 @@ internal static class Program
|
|||
PatrolPortalTests.Register(runner);
|
||||
DunRouteTests.Register(runner);
|
||||
BuffTests.Register(runner);
|
||||
BuffItemsTests.Register(runner);
|
||||
SpellCatalogTests.Register(runner);
|
||||
CombatMathTests.Register(runner);
|
||||
WeaponTests.Register(runner);
|
||||
|
|
@ -98,6 +100,7 @@ internal static class Program
|
|||
OffhandTests.Register(runner);
|
||||
HandSwapTests.Register(runner);
|
||||
OutdoorHuntTests.Register(runner);
|
||||
HuntOnLoginTests.Register(runner);
|
||||
HuntBuildingTests.Register(runner);
|
||||
FloodPerfTests.Register(runner);
|
||||
LootSalvageTests.Register(runner);
|
||||
|
|
@ -109,6 +112,7 @@ internal static class Program
|
|||
LootNothingLineTests.Register(runner);
|
||||
ChestLootTests.Register(runner);
|
||||
ItemToolTests.Register(runner);
|
||||
TimedCommandsTests.Register(runner);
|
||||
VanishedItemTests.Register(runner);
|
||||
KitUsedUpTests.Register(runner);
|
||||
VitalWandGateTests.Register(runner);
|
||||
|
|
@ -199,10 +203,13 @@ internal static class Program
|
|||
SaveFailureTests.Register(runner);
|
||||
EnvironmentImpactTests.Register(runner);
|
||||
SkCombatAddonTests.Register(runner);
|
||||
DirtyFightingRotationTests.Register(runner);
|
||||
DoorTests.Register(runner);
|
||||
ServerPolicyTests.Register(runner);
|
||||
PatrolModeTests.Register(runner);
|
||||
BlankLoadTests.Register(runner);
|
||||
CallStateRepairTests.Register(runner);
|
||||
ProfileButtonTests.Register(runner);
|
||||
GiveProfileTests.Register(runner);
|
||||
TinkerTests.Register(runner);
|
||||
LauncherSwapTests.Register(runner);
|
||||
|
|
@ -214,12 +221,14 @@ internal static class Program
|
|||
TickIsolationTests.Register(runner);
|
||||
ChoresInFightTests.Register(runner);
|
||||
AetheriaUnboxTests.Register(runner);
|
||||
AutoConfirmCraftTests.Register(runner);
|
||||
CommandReplyTests.Register(runner);
|
||||
MonsterStatsTests.Register(runner);
|
||||
MetaSaveTests.Register(runner);
|
||||
MetaResumeTests.Register(runner);
|
||||
FellowOpenTests.Register(runner);
|
||||
WieldBanTests.Register(runner);
|
||||
ActiveGearTests.Register(runner);
|
||||
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -67,6 +67,9 @@
|
|||
RynthAi exactly what the engine sends (engine 2026-10-13). -->
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Compatibility\PropertyWire.cs" Link="Engine\PropertyWire.cs" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Compatibility\ObjectPropertyRecord.cs" Link="Engine\ObjectPropertyRecord.cs" />
|
||||
<!-- The engine's confirmation arms (v85 one-shot, v97 sticky; pure), so the auto-confirm tests'
|
||||
fake engine answers prompts by the engine's own rules (engine 2026-11-11). -->
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Compatibility\ConfirmationArmPolicy.cs" Link="Engine\ConfirmationArmPolicy.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
196
Tools/RynthCore.RynthAiHostTests/Tests/ActiveGearTests.cs
Normal file
196
Tools/RynthCore.RynthAiHostTests/Tests/ActiveGearTests.cs
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.UI.Sections;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.ActiveGear;
|
||||
using RynthCore.Plugin.RynthAi.Huds;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The Active Gear window and /ra gear (RynthAiPlugin.ActiveGear.cs) on the fake engine: what is
|
||||
// worn (the v87 tracker), each item's appraisal (spells, mana, rate, when identified), the
|
||||
// player's endless enchantments, the summary line /ra gear says, Check items' identifies, and the
|
||||
// window in the sections manifest without a bar button.
|
||||
internal static class ActiveGearTests
|
||||
{
|
||||
private const uint Player = 0x50000F31, Ring = 0x80000F01, Amulet = 0x80000F02, Coat = 0x80000F03, Sword = 0x80000F04;
|
||||
private const int LeftRing = 0x00040000, Neck = 0x00008000, CoatMask = 0x00000200 | 0x00000400 | 0x00000800, MeleeMask = 0x00100000;
|
||||
private const uint MajorStrength = 2576, Impen = 1483;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("active gear: /ra gear says the summary and opens the window", Summary);
|
||||
r.Add("active gear: /ra gear list, check (unidentified first, gently) and a wrong option", ListCheckAndUsage);
|
||||
r.Add("active gear: the window is in the manifest with no bar button", Manifest);
|
||||
}
|
||||
|
||||
private static readonly List<(string Key, int Mode)> PanelCalls = new();
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static uint FakeUiColor(int token) => 0xFFFFFFFF;
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static IntPtr FakeUiFont(int font) => IntPtr.Zero;
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static unsafe int FakeSetPanelOpen(byte* key, int mode)
|
||||
{
|
||||
PanelCalls.Add((Marshal.PtrToStringUTF8((IntPtr)key) ?? "", mode));
|
||||
return mode == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static unsafe void PluginWindows(ref RynthCoreApiNative api)
|
||||
{
|
||||
api.Version = Math.Max(api.Version, 89u);
|
||||
api.GetUiColorFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, uint>)&FakeUiColor;
|
||||
api.GetUiFontFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, IntPtr>)&FakeUiFont;
|
||||
api.SetPanelOpenFn = (IntPtr)(delegate* unmanaged[Cdecl]<byte*, int, int>)&FakeSetPanelOpen;
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
|
||||
public Rig()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
PanelCalls.Clear();
|
||||
EquippedState.Invalidate();
|
||||
FakeHost.ConfigureApi = PluginWindows;
|
||||
FakeHost.EquippedCalls = true;
|
||||
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
|
||||
FakeHost.TargetCalls = true; // GetLastIdTime
|
||||
FakeHost.Names[Player] = "Tester";
|
||||
long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
|
||||
// A ring whose cantrip is on the player: 370 mana at 0.5 a second is 12 minutes and some.
|
||||
Item(Ring, "Ring of Testing", LeftRing, spells: new[] { MajorStrength }, cur: 370, max: 2000, rate: -0.5, idAt: now);
|
||||
FakeHost.Enchantments.Add((MajorStrength, double.MaxValue));
|
||||
// A coat out of mana.
|
||||
Item(Coat, "Test Coat", CoatMask, spells: new[] { Impen }, cur: 0, max: 1000, rate: -0.2, idAt: now);
|
||||
// An amulet never identified.
|
||||
FakeHost.Names[Amulet] = "Test Amulet";
|
||||
FakeHost.Equipped[Amulet] = Neck;
|
||||
// A plain sword: identified, no spells, no mana: not listed.
|
||||
FakeHost.Names[Sword] = "Plain Sword";
|
||||
FakeHost.Equipped[Sword] = MeleeMask;
|
||||
FakeHost.Appraised.Add(Sword);
|
||||
|
||||
RynthCoreHost host = FakeHost.Create(playerId: Player);
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
foreach (uint id in new[] { Ring, Amulet, Coat, Sword }) _ = cache[unchecked((int)id)];
|
||||
Set("_objectCache", cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_initialized", true);
|
||||
Set("_loginComplete", true);
|
||||
}
|
||||
|
||||
private static void Item(uint id, string name, int slot, uint[] spells, int cur, int max, double rate, long idAt)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Equipped[id] = unchecked((uint)slot);
|
||||
FakeHost.Appraised.Add(id);
|
||||
FakeHost.SpellIds[id] = spells;
|
||||
FakeHost.Ints[(id, 107)] = cur;
|
||||
FakeHost.Ints[(id, 108)] = max;
|
||||
FakeHost.Doubles[(id, 5)] = rate;
|
||||
FakeHost.IdTimes[id] = idAt;
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public object? Call(string method, params object?[] args) => typeof(RynthAiPlugin).GetMethod(method, Any)!.Invoke(P, args);
|
||||
|
||||
public List<string> Typed(string line)
|
||||
{
|
||||
int before = FakeHost.Chat.Count;
|
||||
int eat = 0;
|
||||
P.OnChatBarEnter(line, ref eat);
|
||||
return FakeHost.Chat.Skip(before).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
private static string Show(List<string> lines) => string.Join(" | ", lines);
|
||||
|
||||
private static void Summary()
|
||||
{
|
||||
var rig = new Rig();
|
||||
List<string> lines = rig.Typed("/ra gear");
|
||||
Check.Eq(lines.Count, 1, "one line: " + Show(lines));
|
||||
Check.True(lines.Count == 1 && lines[0].Contains("1 of 3 items active, 1 unknown, off: Chest (out of mana), lowest: Left Ring 12 min"),
|
||||
"the summary: " + Show(lines));
|
||||
Check.True(lines.Count == 1 && lines[0].Contains("Active Gear window open"), "says the window opened: " + Show(lines));
|
||||
Check.True(PanelCalls.Count > 0 && PanelCalls[^1] == (RynthAiPlugin.ActiveGearTitle, (int)RynthPanelOpen.Open), "opened by its panel key");
|
||||
|
||||
ActiveGearView view = rig.P.ActiveGearViewForTests;
|
||||
Check.Eq(view.Rows.Length, 3, "ring, coat, amulet; the plain sword isn't listed");
|
||||
Check.True(view.Rows.All(r => r.Id != unchecked((int)Sword)), "no sword row");
|
||||
ActiveGearRow ring = view.Rows.Single(r => r.Id == unchecked((int)Ring));
|
||||
Check.Eq(ring.Verdict.Active, GearActive.Yes, "ring on");
|
||||
Check.Eq(ring.SlotName, "Left Ring", "ring slot");
|
||||
Check.Eq(ActiveGearText.Mana(ring), "370 / 2,000", "ring mana");
|
||||
ActiveGearRow amulet = view.Rows.Single(r => r.Id == unchecked((int)Amulet));
|
||||
Check.Eq(amulet.Verdict.Active, GearActive.Unknown, "amulet unknown");
|
||||
Check.Eq(ActiveGearText.Mana(amulet), "?", "amulet mana unknown");
|
||||
Check.Eq(view.Rows[0].Id, unchecked((int)Coat), "armor listed first");
|
||||
|
||||
lines = rig.Typed("/ra gear hide");
|
||||
Check.True(lines.Count == 1 && lines[0].Contains("closed"), "hide replies: " + Show(lines));
|
||||
}
|
||||
|
||||
private static void ListCheckAndUsage()
|
||||
{
|
||||
var rig = new Rig();
|
||||
List<string> lines = rig.Typed("/ra gear list");
|
||||
Check.Eq(lines.Count, 4, "summary + 3 items: " + Show(lines));
|
||||
Check.True(lines.Any(l => l.Contains("Left Ring, Ring of Testing: Yes") && l.Contains("12 min left") && l.Contains("1/1 spells on")), Show(lines));
|
||||
Check.True(lines.Any(l => l.Contains("Chest, Test Coat: No (out of mana)")), Show(lines));
|
||||
Check.True(lines.Any(l => l.Contains("Neck, Test Amulet: ? (not identified yet)")), Show(lines));
|
||||
|
||||
rig.Call("TickActiveGear"); // the worn items tracked
|
||||
FakeHost.IdRequests.Clear();
|
||||
lines = rig.Typed("/ra gear check");
|
||||
Check.True(lines.Count == 1 && lines[0].Contains("identifying 3 worn items"), "check replies: " + Show(lines));
|
||||
rig.Call("TickActiveGear");
|
||||
Check.Eq(FakeHost.IdRequests.Count, 1, "one identify at a time");
|
||||
Check.True(FakeHost.IdRequests.Count == 1 && FakeHost.IdRequests[0] == Amulet, "the unidentified one first");
|
||||
rig.Call("TickActiveGear");
|
||||
Check.Eq(FakeHost.IdRequests.Count, 1, "the next waits its 1.5 s");
|
||||
|
||||
lines = rig.Typed("/ra gear sideways");
|
||||
Check.True(lines.Count == 1 && lines[0].Contains("unknown option") && lines[0].Contains(RynthAiPlugin.ActiveGearUsage), "usage: " + Show(lines));
|
||||
|
||||
// Without the object cache (before the world loads) it says why instead of an empty summary.
|
||||
rig.Set("_objectCache", null);
|
||||
lines = rig.Typed("/ra gear");
|
||||
Check.True(lines.Count == 1 && lines[0].Contains("not in the world"), "not ready: it says why: " + Show(lines));
|
||||
}
|
||||
|
||||
private static void Manifest()
|
||||
{
|
||||
string json = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, dashboard: true, monsterStats: true, activeGear: true);
|
||||
SectionManifest m = SectionManifestParser.Parse("RynthAi", json, out string error);
|
||||
Check.Eq(error, string.Empty, "no parse error");
|
||||
Check.Eq(m.Windows.Length, 3, "dashboard, Monster Stats, Active Gear");
|
||||
SectionWindowDecl w = m.Windows.Single(x => x.Id == "activegear");
|
||||
Check.Eq(w.Title, RynthAiPlugin.ActiveGearTitle, "title (its panel key)");
|
||||
Check.Eq(w.Surface, "window:activegear", "the surface PluginExports.RenderEmbed draws");
|
||||
Check.False(w.Bar, "no bar button");
|
||||
Check.False(w.TakeOver || w.Frameless, "the engine's frame");
|
||||
Check.True(w.Width >= w.MinWidth && w.Height >= w.MinHeight, "sizes");
|
||||
|
||||
SectionManifest alone = SectionManifestParser.Parse("RynthAi",
|
||||
SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, activeGear: true), out error);
|
||||
Check.True(error.Length == 0 && alone.Windows.Length == 1 && alone.Windows[0].Id == "activegear", "alone");
|
||||
}
|
||||
}
|
||||
405
Tools/RynthCore.RynthAiHostTests/Tests/AutoConfirmCraftTests.cs
Normal file
405
Tools/RynthCore.RynthAiHostTests/Tests/AutoConfirmCraftTests.cs
Normal file
|
|
@ -0,0 +1,405 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Auto-confirm crafting (a players' request, 2026-11-11: "auto confirm on 100% tinker and crafting
|
||||
// chance"). RynthAi keeps the engine's sticky CraftInteraction answer armed (plugin API v97): Yes at
|
||||
// the threshold, a lower chance shows AC's dialog, never a No. The fake engine here answers prompts
|
||||
// with the engine's own rules (ConfirmationArmPolicy.cs, linked), two slots: the one-shot that the
|
||||
// tinker runner arms per step goes first and never disturbs the sticky arm.
|
||||
internal static unsafe class AutoConfirmCraftTests
|
||||
{
|
||||
private const uint Craft = RynthCoreHost.ConfirmationKind.CraftInteraction;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private const uint Player = 0x50000F61;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("autoconfirm: on keeps a sticky Yes-at-100 arm, re-armed before it runs out; off drops it", ArmsAndReArms);
|
||||
r.Add("autoconfirm: 100% is answered with one chat line; below the threshold AC's dialog shows, no line, never a No", AnswersAndLines);
|
||||
r.Add("autoconfirm: the tinker runner's one-shot goes first, its disarm and re-arms never fight the sticky arm", NeverFightsTheRunner);
|
||||
r.Add("autoconfirm: an engine before v97 - nothing armed, the reason in the status and the command", OldEngine);
|
||||
r.Add("autoconfirm: the threshold is clamped to 50-100 and a change re-arms at once", Threshold);
|
||||
r.Add("autoconfirm: logout releases the arm", Logout);
|
||||
r.Add("autoconfirm: settings - off at 100 by default, saved, copied, sent to the engine face as nullable fields", Settings);
|
||||
r.Add("autoconfirm: /ra autoconfirm on|off|<percent>|status always answers", Command);
|
||||
}
|
||||
|
||||
// ── The fake engine's confirmation calls (static: function pointers can't capture) ──────────
|
||||
|
||||
private static ConfirmationArm _oneShot, _sticky;
|
||||
private static long _now;
|
||||
private static int _seq, _lastPercent = -1, _lastOutcome;
|
||||
private static uint _lastType;
|
||||
private static readonly List<(uint Type, int Min, int Timeout)> ArmCalls = new();
|
||||
|
||||
private static void ResetEngine()
|
||||
{
|
||||
_oneShot = default;
|
||||
_sticky = default;
|
||||
_now = 1_000_000;
|
||||
_seq = 0;
|
||||
_lastPercent = -1;
|
||||
_lastOutcome = 0;
|
||||
_lastType = 0;
|
||||
ArmCalls.Clear();
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int FakeArm(uint type, int minPercent, int timeoutMs)
|
||||
{
|
||||
ArmCalls.Add((type, minPercent, timeoutMs));
|
||||
return ConfirmationArmPolicy.Apply(ref _oneShot, ref _sticky, type, minPercent, timeoutMs, _now, available: true);
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int FakeLast(uint* type, uint* contextId, int* percent, int* outcome, int* ageMs)
|
||||
{
|
||||
if (type != null) *type = _lastType;
|
||||
if (contextId != null) *contextId = 0x1234;
|
||||
if (percent != null) *percent = _lastPercent;
|
||||
if (outcome != null) *outcome = _lastOutcome;
|
||||
if (ageMs != null) *ageMs = 0;
|
||||
return _seq;
|
||||
}
|
||||
|
||||
/// <summary>The server's prompt reaches the engine; returns the outcome code (as GetLastConfirmation reports it).</summary>
|
||||
private static int Prompt(int percent, uint type = Craft)
|
||||
{
|
||||
var v = ConfirmationArmPolicy.Decide(ref _oneShot, ref _sticky, type, percent, _now);
|
||||
_seq++;
|
||||
_lastType = type;
|
||||
_lastPercent = percent;
|
||||
_lastOutcome = v switch
|
||||
{
|
||||
ConfirmationArmPolicy.Verdict.Accept => RynthCoreHost.ConfirmationOutcome.Accepted,
|
||||
ConfirmationArmPolicy.Verdict.Decline => RynthCoreHost.ConfirmationOutcome.Declined,
|
||||
ConfirmationArmPolicy.Verdict.AcceptSticky => RynthCoreHost.ConfirmationOutcome.AcceptedSticky,
|
||||
_ => RynthCoreHost.ConfirmationOutcome.Shown,
|
||||
};
|
||||
return _lastOutcome;
|
||||
}
|
||||
|
||||
/// <summary>A host whose confirmation calls are the fake engine's, reporting <paramref name="version"/>.</summary>
|
||||
private static RynthCoreHost Host(uint version = RynthCoreHost.CurrentApiVersion, bool calls = true)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
ResetEngine();
|
||||
FakeHost.ConfigureApi = (ref RynthCoreApiNative api) =>
|
||||
{
|
||||
api.Version = version;
|
||||
if (!calls) return;
|
||||
api.ArmConfirmationFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int, int>)&FakeArm;
|
||||
api.GetLastConfirmationFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, uint*, int*, int*, int*, int>)&FakeLast;
|
||||
};
|
||||
try { return FakeHost.Create(); }
|
||||
finally { FakeHost.ConfigureApi = null; }
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S = new() { AutoConfirmCraft = true };
|
||||
public readonly List<string> Lines = new();
|
||||
public readonly CraftAutoConfirm A;
|
||||
public Rig(RynthCoreHost host)
|
||||
{
|
||||
A = new CraftAutoConfirm(() => host, () => S, Lines.Add);
|
||||
}
|
||||
public void Tick(long advanceMs = 0)
|
||||
{
|
||||
_now += advanceMs;
|
||||
A.Tick(_now);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ArmsAndReArms()
|
||||
{
|
||||
var rig = new Rig(Host());
|
||||
rig.Tick();
|
||||
Check.True(rig.A.Supported, "a v97 engine supports it");
|
||||
Check.True(rig.A.Armed && _sticky.Armed, "on: the sticky arm is up");
|
||||
Check.Eq(_sticky.MinPercent, 100, "at 100%");
|
||||
Check.Eq(_sticky.Type, Craft, "for craft prompts");
|
||||
Check.Eq(ArmCalls.Count, 1, "one arm call");
|
||||
Check.Eq(ArmCalls[0].Min, 100 | RynthCoreHost.ConfirmationArmFlags.LeaveBelow, "with the leave-below flag");
|
||||
Check.Eq(ArmCalls[0].Timeout, CraftAutoConfirm.ArmTimeoutMs, "for the arm's life");
|
||||
Check.True(CraftAutoConfirm.RearmAfterMs < CraftAutoConfirm.ArmTimeoutMs / 2, "re-armed well inside its life");
|
||||
Check.False(_oneShot.Armed, "the one-shot slot is not used");
|
||||
|
||||
for (int i = 0; i < 10; i++) rig.Tick(100);
|
||||
Check.Eq(ArmCalls.Count, 1, "no call every tick");
|
||||
rig.Tick(CraftAutoConfirm.RearmAfterMs);
|
||||
Check.Eq(ArmCalls.Count, 2, "re-armed after RearmAfterMs");
|
||||
long until = _sticky.Until;
|
||||
Check.True(until - _now == CraftAutoConfirm.ArmTimeoutMs, "the re-arm pushes the timeout out");
|
||||
// Ticking for ten minutes: never lapses.
|
||||
bool lapsed = false;
|
||||
for (int i = 0; i < 600; i++) { rig.Tick(1_000); lapsed |= !_sticky.Armed || _now > _sticky.Until; }
|
||||
Check.False(lapsed, "never lapses while on");
|
||||
|
||||
rig.S.AutoConfirmCraft = false;
|
||||
rig.Tick(100);
|
||||
Check.False(_sticky.Armed, "off: the engine's sticky arm is dropped");
|
||||
Check.False(rig.A.Armed, "and RynthAi knows");
|
||||
Check.Eq(ArmCalls.Last().Min, RynthCoreHost.ConfirmationArmFlags.LeaveBelow, "the drop is the sticky disarm (the flag)");
|
||||
Check.Eq(ArmCalls.Last().Timeout, 0, "with timeout 0");
|
||||
int calls = ArmCalls.Count;
|
||||
rig.Tick(CraftAutoConfirm.RearmAfterMs * 3);
|
||||
Check.Eq(ArmCalls.Count, calls, "off: no more calls");
|
||||
Check.Eq(rig.A.Status, "off", "status off");
|
||||
|
||||
rig.S.AutoConfirmCraft = true;
|
||||
rig.Tick(100);
|
||||
Check.True(_sticky.Armed, "on again: armed at once");
|
||||
}
|
||||
|
||||
private static void AnswersAndLines()
|
||||
{
|
||||
var rig = new Rig(Host());
|
||||
rig.Tick();
|
||||
Check.Eq(Prompt(100), RynthCoreHost.ConfirmationOutcome.AcceptedSticky, "100%: Yes without the dialog");
|
||||
rig.Tick(16);
|
||||
Check.Eq(rig.Lines.Count, 1, "one chat line");
|
||||
Check.Eq(rig.Lines.FirstOrDefault() ?? "", "[RynthAi] Auto-confirmed: 100% chance", "the line");
|
||||
rig.Tick(16);
|
||||
Check.Eq(rig.Lines.Count, 1, "said once, not every tick");
|
||||
|
||||
Check.Eq(Prompt(99), RynthCoreHost.ConfirmationOutcome.Shown, "99%: AC's dialog");
|
||||
rig.Tick(16);
|
||||
Check.Eq(rig.Lines.Count, 1, "no line for a prompt below the threshold");
|
||||
Check.True(_sticky.Armed && rig.A.Armed, "still armed");
|
||||
Check.Eq(Prompt(-1), RynthCoreHost.ConfirmationOutcome.Shown, "a prompt without a percent: AC's dialog");
|
||||
Check.Eq(Prompt(100, RynthCoreHost.ConfirmationKind.YesNo), RynthCoreHost.ConfirmationOutcome.Shown, "another kind of prompt: AC's dialog");
|
||||
rig.Tick(16);
|
||||
Check.Eq(rig.Lines.Count, 1, "no line for those");
|
||||
|
||||
bool anyNo = false;
|
||||
for (int pct = 0; pct <= 100; pct++) anyNo |= Prompt(pct) == RynthCoreHost.ConfirmationOutcome.Declined;
|
||||
Check.False(anyNo, "never a No, at any chance");
|
||||
|
||||
Prompt(100);
|
||||
rig.Tick(16);
|
||||
Prompt(100);
|
||||
rig.Tick(16);
|
||||
Check.Eq(rig.Lines.Count, 3, "a line per confirmed craft (repeated crafts)");
|
||||
Check.Eq(rig.A.AcceptedCount, 3, "counted");
|
||||
|
||||
// Prompts from before RynthAi was looking are not reported.
|
||||
var late = new Rig(Host());
|
||||
Prompt(100); // nothing armed yet: AC's dialog
|
||||
_lastOutcome = RynthCoreHost.ConfirmationOutcome.AcceptedSticky; // even if it had been a sticky Yes
|
||||
late.Tick();
|
||||
Check.Eq(late.Lines.Count, 0, "the first look only takes the sequence number");
|
||||
}
|
||||
|
||||
private static void NeverFightsTheRunner()
|
||||
{
|
||||
var host = Host();
|
||||
var rig = new Rig(host);
|
||||
rig.Tick();
|
||||
Check.True(_sticky.Armed, "sticky arm up");
|
||||
|
||||
// A tinker step: TinkerRunner arms its one-shot (Yes at the tab's Min chance %, else No) for 15 s.
|
||||
rig.Tick(CraftAutoConfirm.RearmAfterMs - 1_000);
|
||||
Check.Eq(host.ArmConfirmation(Craft, 70, 15_000), 1, "the runner's one-shot arms");
|
||||
Check.True(_oneShot.Armed && _sticky.Armed, "both armed");
|
||||
// RynthAi re-arms in the middle of the step: the step's one-shot stays as the runner left it.
|
||||
int calls = ArmCalls.Count;
|
||||
rig.Tick(2_000);
|
||||
Check.Eq(ArmCalls.Count, calls + 1, "RynthAi re-armed during the step");
|
||||
Check.True(_oneShot.Armed && _oneShot.MinPercent == 70, "a sticky re-arm leaves the runner's one-shot");
|
||||
Check.Eq(Prompt(60), RynthCoreHost.ConfirmationOutcome.Declined, "the step's prompt follows the runner's rule (60% under 70: No)");
|
||||
rig.Tick(16);
|
||||
Check.Eq(rig.Lines.Count, 0, "the runner's answer is not reported as an auto-confirm");
|
||||
Check.True(_sticky.Armed, "the sticky arm is untouched");
|
||||
|
||||
Check.Eq(host.ArmConfirmation(Craft, 70, 15_000), 1, "next step");
|
||||
Check.Eq(Prompt(100), RynthCoreHost.ConfirmationOutcome.Accepted, "the runner's Yes is its own (outcome Accepted)");
|
||||
rig.Tick(16);
|
||||
Check.Eq(rig.Lines.Count, 0, "still no auto-confirm line");
|
||||
|
||||
// The runner stops mid-step and disarms its one-shot (ArmConfirmation(type, 0, 0)).
|
||||
Check.Eq(host.ArmConfirmation(Craft, 70, 15_000), 1, "a step");
|
||||
Check.Eq(host.ArmConfirmation(Craft, 0, 0), 1, "the runner's disarm");
|
||||
Check.False(_oneShot.Armed, "the one-shot is gone");
|
||||
Check.True(_sticky.Armed, "the sticky arm is still there after the run");
|
||||
rig.Tick(16);
|
||||
Check.True(rig.A.Armed, "RynthAi still has it");
|
||||
Check.Eq(Prompt(100), RynthCoreHost.ConfirmationOutcome.AcceptedSticky, "a hand-made 100% craft after the run: auto-confirmed");
|
||||
rig.Tick(16);
|
||||
Check.Eq(rig.Lines.Count, 1, "with its line");
|
||||
Check.Eq(Prompt(50), RynthCoreHost.ConfirmationOutcome.Shown, "a hand-made 50% craft: AC's dialog");
|
||||
|
||||
// Turning it off never touches a runner's one-shot.
|
||||
Check.Eq(host.ArmConfirmation(Craft, 70, 15_000), 1, "a step");
|
||||
rig.S.AutoConfirmCraft = false;
|
||||
rig.Tick(16);
|
||||
Check.False(_sticky.Armed, "off: the sticky arm is gone");
|
||||
Check.True(_oneShot.Armed && _oneShot.MinPercent == 70, "the runner's one-shot is still there");
|
||||
}
|
||||
|
||||
private static void OldEngine()
|
||||
{
|
||||
foreach (uint version in new uint[] { 85, 95, 96 })
|
||||
{
|
||||
var rig = new Rig(Host(version));
|
||||
rig.Tick();
|
||||
Check.False(rig.A.Supported, $"v{version}: not supported");
|
||||
Check.False(rig.A.Armed, $"v{version}: nothing armed");
|
||||
Check.Eq(ArmCalls.Count, 0, $"v{version}: the engine is not called (its disarm would clear another plugin's one-shot)");
|
||||
Check.True(rig.A.Status.Contains("plugin API 97"), $"v{version}: the status says why: {rig.A.Status}");
|
||||
rig.S.AutoConfirmCraft = false;
|
||||
rig.Tick(16);
|
||||
Check.Eq(ArmCalls.Count, 0, $"v{version}: turning it off calls nothing");
|
||||
}
|
||||
var none = new Rig(Host(RynthCoreHost.CurrentApiVersion, calls: false));
|
||||
none.Tick();
|
||||
Check.False(none.A.Supported, "no confirmation calls at all: not supported");
|
||||
}
|
||||
|
||||
private static void Threshold()
|
||||
{
|
||||
Check.Eq(CraftAutoConfirm.ClampPercent(0), 50, "0 -> 50");
|
||||
Check.Eq(CraftAutoConfirm.ClampPercent(49), 50, "49 -> 50");
|
||||
Check.Eq(CraftAutoConfirm.ClampPercent(75), 75, "75");
|
||||
Check.Eq(CraftAutoConfirm.ClampPercent(150), 100, "150 -> 100");
|
||||
var rig = new Rig(Host());
|
||||
rig.S.AutoConfirmCraftPercent = 90;
|
||||
rig.Tick();
|
||||
Check.Eq(_sticky.MinPercent, 90, "armed at 90");
|
||||
Check.Eq(Prompt(92), RynthCoreHost.ConfirmationOutcome.AcceptedSticky, "92% at 90: Yes");
|
||||
rig.Tick(16);
|
||||
Check.Eq(rig.Lines.LastOrDefault() ?? "", "[RynthAi] Auto-confirmed: 92% chance", "the line says the chance");
|
||||
rig.S.AutoConfirmCraftPercent = 100;
|
||||
rig.Tick(16);
|
||||
Check.Eq(_sticky.MinPercent, 100, "a change re-arms at once");
|
||||
rig.S.AutoConfirmCraftPercent = 10;
|
||||
rig.Tick(16);
|
||||
Check.Eq(_sticky.MinPercent, 50, "a saved value under 50 arms at 50");
|
||||
}
|
||||
|
||||
private static void Logout()
|
||||
{
|
||||
var rig = new Rig(Host());
|
||||
rig.Tick();
|
||||
Check.True(_sticky.Armed, "armed");
|
||||
rig.A.Release();
|
||||
Check.False(_sticky.Armed, "logout drops the engine's arm");
|
||||
Check.False(rig.A.Armed, "and RynthAi's");
|
||||
}
|
||||
|
||||
private static void Settings()
|
||||
{
|
||||
var d = new LegacyUiSettings();
|
||||
Check.False(d.AutoConfirmCraft, "off by default");
|
||||
Check.Eq(d.AutoConfirmCraftPercent, 100, "100% by default");
|
||||
var old = JsonSerializer.Deserialize("{\"EnableAutostack\":true}", RynthAiJsonContext.Default.LegacyUiSettings)!;
|
||||
Check.False(old.AutoConfirmCraft, "a profile from before the setting: off");
|
||||
Check.Eq(old.AutoConfirmCraftPercent, 100, "and 100%");
|
||||
var saved = JsonSerializer.Deserialize(
|
||||
JsonSerializer.Serialize(new LegacyUiSettings { AutoConfirmCraft = true, AutoConfirmCraftPercent = 80 }, RynthAiJsonContext.Default.LegacyUiSettings),
|
||||
RynthAiJsonContext.Default.LegacyUiSettings)!;
|
||||
Check.True(saved.AutoConfirmCraft, "on saves and loads");
|
||||
Check.Eq(saved.AutoConfirmCraftPercent, 80, "the percent saves and loads");
|
||||
|
||||
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
var dst = new LegacyUiSettings();
|
||||
copy.Invoke(null, new object[] { new LegacyUiSettings { AutoConfirmCraft = true, AutoConfirmCraftPercent = 70 }, dst });
|
||||
Check.True(dst.AutoConfirmCraft, "a profile switch copies it");
|
||||
Check.Eq(dst.AutoConfirmCraftPercent, 70, "and the percent");
|
||||
|
||||
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(payload != null && payload.AutoConfirmCraft == null && payload.AutoConfirmCraftPercent == null, "an older engine's payload has no value");
|
||||
var s = new LegacyUiSettings { AutoConfirmCraft = true, AutoConfirmCraftPercent = 90 };
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", Any)!.SetValue(dash, new LegacyAdvancedSettingsUi(s));
|
||||
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(sent != null && sent.AutoConfirmCraft == true && sent.AutoConfirmCraftPercent == 90, "sent to the engine face");
|
||||
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
|
||||
Check.True(s.AutoConfirmCraft, "an engine save without the fields leaves them");
|
||||
Check.Eq(s.AutoConfirmCraftPercent, 90, "(the percent too)");
|
||||
dash.ApplySettingsJson("{\"AutoConfirmCraft\":false,\"AutoConfirmCraftPercent\":20}");
|
||||
Check.False(s.AutoConfirmCraft, "an engine save with it sets it");
|
||||
Check.Eq(s.AutoConfirmCraftPercent, 50, "a percent under 50 is clamped");
|
||||
}
|
||||
|
||||
// ── /ra autoconfirm ──────────────────────────────────────────────────────
|
||||
|
||||
private static (RynthAiPlugin P, LegacyUiSettings S) Plugin(uint version)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
ResetEngine();
|
||||
FakeHost.Names[Player] = "Tester";
|
||||
FakeHost.ConfigureApi = (ref RynthCoreApiNative api) =>
|
||||
{
|
||||
api.Version = version;
|
||||
api.ArmConfirmationFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int, int>)&FakeArm;
|
||||
api.GetLastConfirmationFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, uint*, int*, int*, int*, int>)&FakeLast;
|
||||
};
|
||||
try { FakeHost.Create(playerId: Player); }
|
||||
finally { FakeHost.ConfigureApi = null; }
|
||||
var p = new RynthAiPlugin();
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
|
||||
var s = new LegacyUiSettings();
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
|
||||
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(p, dash);
|
||||
return (p, s);
|
||||
}
|
||||
|
||||
private static string Say(RynthAiPlugin p, string line)
|
||||
{
|
||||
FakeHost.Chat.Clear();
|
||||
typeof(RynthAiPlugin).GetMethod("HandleAutoConfirmCommand", Any)!.Invoke(p, new object[] { line.Split(' ') });
|
||||
return string.Join(" | ", FakeHost.Chat);
|
||||
}
|
||||
|
||||
private static void Command()
|
||||
{
|
||||
var (p, s) = Plugin(RynthCoreHost.CurrentApiVersion);
|
||||
string r = Say(p, "/ra autoconfirm");
|
||||
Check.True(r.Contains("Auto-confirm crafting: off"), "status (the default): off: " + r);
|
||||
r = Say(p, "/ra autoconfirm on");
|
||||
Check.True(s.AutoConfirmCraft, "on turns it on");
|
||||
Check.True(r.Contains("on, Yes at 100% or better"), "and says the value now: " + r);
|
||||
r = Say(p, "/ra autoconfirm status");
|
||||
Check.True(r.Contains("on, Yes at 100%"), "status: on: " + r);
|
||||
r = Say(p, "/ra autoconfirm 90%");
|
||||
Check.Eq(s.AutoConfirmCraftPercent, 90, "a percent sets it");
|
||||
Check.True(r.Contains("Yes at 90%"), "and says so: " + r);
|
||||
r = Say(p, "/ra autoconfirm 30");
|
||||
Check.Eq(s.AutoConfirmCraftPercent, 90, "30 is refused");
|
||||
Check.True(r.Contains("50-100") && r.Contains("Usage"), "with the range and the usage: " + r);
|
||||
r = Say(p, "/ra autoconfirm banana");
|
||||
Check.True(r.Contains("unknown option") && r.Contains("Usage"), "an unknown word: why and the usage: " + r);
|
||||
r = Say(p, "/ra autoconfirm off");
|
||||
Check.False(s.AutoConfirmCraft, "off turns it off");
|
||||
Check.True(r.Contains("off"), "and says so: " + r);
|
||||
|
||||
var (oldP, oldS) = Plugin(96);
|
||||
r = Say(oldP, "/ra autoconfirm on");
|
||||
Check.False(oldS.AutoConfirmCraft, "an older engine: on is refused");
|
||||
Check.True(r.Contains("plugin API 97"), "with the reason: " + r);
|
||||
r = Say(oldP, "/ra autoconfirm 90");
|
||||
Check.True(r.Contains("plugin API 97") && oldS.AutoConfirmCraftPercent == 100, "a percent too, nothing changed: " + r);
|
||||
r = Say(oldP, "/ra autoconfirm");
|
||||
Check.True(r.Contains("plugin API 97"), "status says why: " + r);
|
||||
}
|
||||
}
|
||||
235
Tools/RynthCore.RynthAiHostTests/Tests/BuffItemsTests.cs
Normal file
235
Tools/RynthCore.RynthAiHostTests/Tests/BuffItemsTests.cs
Normal file
|
|
@ -0,0 +1,235 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Buff items (Use Buff Items, BuffManager.BuffItems.cs) on the fake engine: a blocked built-in is
|
||||
// never used, a custom item's spell is read from the item (data id 28, else its appraisal) and its
|
||||
// buff is matched against the enchantments, one with no spell is used on its repeat time, only
|
||||
// pack items are used, and the lists are saved, loaded, copied and bridged like DisabledBuffs.
|
||||
internal static class BuffItemsTests
|
||||
{
|
||||
private const uint Player = 0x50000B01;
|
||||
private const uint Benediction = 0x80001001, Favor = 0x80001002, Elixir = 0x80001003, Gem = 0x80001004, Unappraised = 0x80001005;
|
||||
private const uint ElixirSpell = 1; // Strength Other I: a buff with a duration in the spell catalog
|
||||
private const BindingFlags Priv = BindingFlags.NonPublic | BindingFlags.Instance;
|
||||
private static readonly MethodInfo TryUse = typeof(BuffManager).GetMethod("TryUseBuffItems", Priv)!;
|
||||
private static readonly FieldInfo LastCheck = typeof(BuffManager).GetField("_lastBuffItemCheck", Priv)!;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("buff items (host): a blocked built-in isn't used, an allowed one is, only while its buff is off", BlockedBuiltIn);
|
||||
r.Add("buff items (host): a custom item's spell is read from the item; its buff on/off decides", CustomItemSpell);
|
||||
r.Add("buff items (host): an item with no spell is used on its repeat time; none in the pack, none used", TimerAndPack);
|
||||
r.Add("buff items (host): Add selected item / add by name / an unappraised item asks for its appraisal", AddPaths);
|
||||
r.Add("buff items (host): the lists default empty, save, load, copy and bridge (absent = unchanged)", ListsSetting);
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S = new() { UseBuffItems = true, EnableBuffing = false };
|
||||
public readonly BuffManager B;
|
||||
public readonly RynthCoreHost Host;
|
||||
public DateTime Now = new(2026, 11, 11, 12, 0, 0);
|
||||
|
||||
public Rig(Action? setup = null)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true; // UseObject and RequestId
|
||||
FakeHost.Names[Benediction] = "Asheron's Benediction";
|
||||
FakeHost.Names[Favor] = "Blackmoor's Favor";
|
||||
FakeHost.Names[Elixir] = "Elixir of the Hunt";
|
||||
FakeHost.Names[Gem] = "Gem of Waking";
|
||||
FakeHost.DataIds[(Elixir, 28)] = ElixirSpell; // the spell its use casts (CreateObject header)
|
||||
FakeHost.SpellIds[Gem] = Array.Empty<uint>(); // appraised: casts nothing
|
||||
setup?.Invoke();
|
||||
Host = FakeHost.Create(Player);
|
||||
var skills = new CharacterSkills(Host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(Host, S);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
B = new BuffManager(Host, S, sm, new PlayerVitalsCache());
|
||||
B.SetCharacterSkills(skills);
|
||||
var ids = FakeHost.Names.Keys.ToArray();
|
||||
B.SetWorldObjectCache(FakeHost.MakeCache(Host, Player, ids));
|
||||
RynthClock.TestNow = () => Now;
|
||||
}
|
||||
|
||||
/// <summary>One buff-item check, 3 s after the last one; the ids used in it.</summary>
|
||||
public List<uint> Check(params uint[] enchantments)
|
||||
{
|
||||
FakeHost.Enchantments.Clear();
|
||||
foreach (uint e in enchantments) FakeHost.Enchantments.Add((e, double.MaxValue));
|
||||
Now = Now.AddSeconds(3.1);
|
||||
int before = FakeHost.Uses.Count;
|
||||
TryUse.Invoke(B, null);
|
||||
return FakeHost.Uses.Skip(before).ToList();
|
||||
}
|
||||
|
||||
public void Wait(double seconds) => Now = Now.AddSeconds(seconds);
|
||||
}
|
||||
|
||||
private static void Run(Action body)
|
||||
{
|
||||
try { body(); }
|
||||
finally { RynthClock.TestNow = null; }
|
||||
}
|
||||
|
||||
private static void BlockedBuiltIn() => Run(() =>
|
||||
{
|
||||
var rig = new Rig();
|
||||
rig.S.CustomBuffItems = new List<CustomBuffItem>();
|
||||
rig.S.SetBuffItemAllowed("Asheron's Benediction", false, out _);
|
||||
var used = rig.Check();
|
||||
Check.True(used.SequenceEqual(new[] { Favor }), $"Benediction blocked: Favor is used ({string.Join(",", used.Select(u => u.ToString("X")))})");
|
||||
rig.Wait(20);
|
||||
used = rig.Check(3811);
|
||||
Check.Eq(used.Count, 0, "Favor's buff on, Benediction blocked: nothing used");
|
||||
rig.S.SetBuffItemAllowed("asheron's benediction", true, out _);
|
||||
used = rig.Check(3811);
|
||||
Check.True(used.SequenceEqual(new[] { Benediction }), "allowed again: Benediction is used");
|
||||
|
||||
rig.S.UseBuffItems = false;
|
||||
rig.Wait(60);
|
||||
Check.Eq(rig.Check().Count, 0, "Use Buff Items off: nothing at all");
|
||||
});
|
||||
|
||||
private static void CustomItemSpell() => Run(() =>
|
||||
{
|
||||
var rig = new Rig();
|
||||
rig.S.SetBuffItemAllowed("Asheron's Benediction", false, out _);
|
||||
rig.S.SetBuffItemAllowed("Blackmoor's Favor", false, out _);
|
||||
rig.S.AddCustomBuffItem("Elixir of the Hunt", null, out _); // by name: spells not read yet
|
||||
var used = rig.Check();
|
||||
Check.True(used.SequenceEqual(new[] { Elixir }), "its spell is read from the item (data id 28) and its buff is off: used");
|
||||
var item = rig.S.CustomBuffItems.Single();
|
||||
Check.True(item.SpellsRead && item.SpellIds.SequenceEqual(new[] { ElixirSpell }), "the spell is kept on the item (saved)");
|
||||
rig.Wait(20);
|
||||
Check.Eq(rig.Check(ElixirSpell).Count, 0, "its buff on: not used again");
|
||||
rig.Wait(60);
|
||||
Check.Eq(rig.Check(ElixirSpell).Count, 0, "still on a minute later: not used");
|
||||
Check.True(rig.Check().SequenceEqual(new[] { Elixir }), "the buff ran out: used again");
|
||||
|
||||
item = rig.S.CustomBuffItems.Single();
|
||||
rig.S.SetBuffItemAllowed(item.Name, false, out _);
|
||||
rig.Wait(20);
|
||||
Check.Eq(rig.Check().Count, 0, "blocked: never used");
|
||||
});
|
||||
|
||||
private static void TimerAndPack() => Run(() =>
|
||||
{
|
||||
var rig = new Rig();
|
||||
rig.S.SetBuffItemAllowed("Asheron's Benediction", false, out _);
|
||||
rig.S.SetBuffItemAllowed("Blackmoor's Favor", false, out _);
|
||||
rig.S.AddCustomBuffItem("Gem of Waking", null, out var gem);
|
||||
gem!.RepeatMinutes = 30;
|
||||
rig.S.AddCustomBuffItem("Potion Not Carried", null, out _);
|
||||
var used = rig.Check();
|
||||
Check.True(used.SequenceEqual(new[] { Gem }), "an appraised item that casts nothing: used on its timer");
|
||||
var saved = rig.S.CustomBuffItems.First(c => c.Name == "Gem of Waking");
|
||||
Check.True(saved.SpellsRead && saved.SpellIds.Count == 0 && saved.LastUsedUtc != null, "read as no spell; the use is kept");
|
||||
Check.Eq(rig.Check().Count, 0, "3 s later: not again");
|
||||
// The repeat time counts on the saved UTC time (a reload keeps it): put it 29 min back.
|
||||
saved.LastUsedUtc = DateTime.UtcNow.AddMinutes(-29);
|
||||
rig.Wait(20);
|
||||
Check.Eq(rig.Check().Count, 0, "29 min after the last use: not yet");
|
||||
saved.LastUsedUtc = DateTime.UtcNow.AddMinutes(-31);
|
||||
Check.True(rig.Check().SequenceEqual(new[] { Gem }), "31 min: used again");
|
||||
Check.False(FakeHost.Uses.Any(u => !FakeHost.Names.ContainsKey(u)), "nothing outside the pack was ever used");
|
||||
});
|
||||
|
||||
private static void AddPaths() => Run(() =>
|
||||
{
|
||||
var rig = new Rig(() => FakeHost.Names[Unappraised] = "Odd Draught");
|
||||
FakeHost.SelectedItem = Elixir;
|
||||
Check.True(rig.B.AddSelectedBuffItem(out string reply), "Add selected item: added");
|
||||
Check.True(reply.Contains("Elixir of the Hunt") && reply.Contains("its buff counts as on"), $"says how it is checked: {reply}");
|
||||
var elixir = BuffItemRules.FindCustom(rig.S.CustomBuffItems, "elixir of the hunt");
|
||||
Check.True(elixir != null && elixir.SpellsRead && elixir.SpellIds.SequenceEqual(new[] { ElixirSpell }), "with its spell");
|
||||
|
||||
FakeHost.SelectedItem = Benediction;
|
||||
Check.False(rig.B.AddSelectedBuffItem(out reply), "a built-in is refused");
|
||||
Check.True(reply.Contains("built in"), reply);
|
||||
FakeHost.SelectedItem = 0;
|
||||
Check.False(rig.B.AddSelectedBuffItem(out reply), "nothing selected");
|
||||
Check.True(reply.Contains("nothing selected"), reply);
|
||||
|
||||
Check.True(rig.B.AddBuffItemByName("gem of waking", out reply), "add by name, in the pack");
|
||||
Check.True(BuffItemRules.FindCustom(rig.S.CustomBuffItems, "Gem of Waking") is { SpellsRead: true, SpellIds.Count: 0 } && reply.Contains("used every"),
|
||||
$"its own spelling, read as no spell: the timer ({reply})");
|
||||
|
||||
int idsBefore = FakeHost.IdRequests.Count;
|
||||
Check.True(rig.B.AddBuffItemByName("Odd Draught", out reply), "an item with no spell header and no appraisal");
|
||||
Check.True(BuffItemRules.FindCustom(rig.S.CustomBuffItems, "Odd Draught") is { SpellsRead: false }, "added with its spell not read");
|
||||
Check.Eq(FakeHost.IdRequests.Count, idsBefore + 1, "its appraisal is asked for");
|
||||
Check.True(reply.Contains("read from the item"), reply);
|
||||
|
||||
Check.True(rig.B.AddBuffItemByName("Not In My Pack", out reply), "a name not in the pack is added");
|
||||
Check.True(BuffItemRules.FindCustom(rig.S.CustomBuffItems, "Not In My Pack") is { SpellsRead: false }, "spells read later");
|
||||
|
||||
var rows = rig.B.DescribeBuffItems();
|
||||
Check.Eq(rows.Count, 3 + 4, "the list: three built-ins and four of the player's");
|
||||
Check.True(rows.First(r => r.Name == "Not In My Pack").Status == "not in your pack", "a missing item says so");
|
||||
Check.True(rows.First(r => r.Name == "Odd Draught").Status == "reading its spell", "the unappraised one waits");
|
||||
});
|
||||
|
||||
private static void ListsSetting()
|
||||
{
|
||||
var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true,\"UseBuffItems\":true}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(old != null && old.BlockedBuffItems.Count == 0 && old.CustomBuffItems.Count == 0, "a profile saved before the setting: all built-ins allowed, none added");
|
||||
var nul = JsonSerializer.Deserialize("{\"BlockedBuffItems\":null,\"CustomBuffItems\":null}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(nul != null && nul.BlockedBuffItems.Count == 0 && nul.CustomBuffItems.Count == 0, "null lists load empty");
|
||||
|
||||
var some = new LegacyUiSettings();
|
||||
some.SetBuffItemAllowed("Blackmoor's Favor", false, out _);
|
||||
some.AddCustomBuffItem("Elixir of the Hunt", new uint[] { ElixirSpell }, out var e);
|
||||
e!.RepeatMinutes = 45;
|
||||
e.LastUsedUtc = new DateTime(2026, 11, 11, 18, 0, 0, DateTimeKind.Utc);
|
||||
some.AddCustomBuffItem("Gem of Waking", null, out _);
|
||||
some.SetBuffItemAllowed("Gem of Waking", false, out _);
|
||||
string json = JsonSerializer.Serialize(some, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
var back = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!;
|
||||
Check.True(back.BlockedBuffItems.SequenceEqual(new[] { "Blackmoor's Favor" }), "the blocked built-in is saved and loaded");
|
||||
var be = BuffItemRules.FindCustom(back.CustomBuffItems, "Elixir of the Hunt");
|
||||
Check.True(be != null && be.Allowed && be.SpellsRead && be.SpellIds.SequenceEqual(new[] { ElixirSpell }) && be.RepeatMinutes == 45
|
||||
&& be.LastUsedUtc == e.LastUsedUtc, "a custom item with its spell, repeat time and last use");
|
||||
Check.True(BuffItemRules.FindCustom(back.CustomBuffItems, "Gem of Waking") is { Allowed: false, SpellsRead: false }, "a blocked, unread one");
|
||||
|
||||
// Profile switch/load copies them (CopySettings is the hand-written field list).
|
||||
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
var dst = new LegacyUiSettings();
|
||||
copy.Invoke(null, new object[] { some, dst });
|
||||
Check.True(dst.BlockedBuffItems.Count == 1 && dst.CustomBuffItems.Count == 2, "a profile with them loads them");
|
||||
Check.False(ReferenceEquals(dst.CustomBuffItems[0], some.CustomBuffItems[0]), "as copies, not the other profile's objects");
|
||||
copy.Invoke(null, new object[] { old!, dst });
|
||||
Check.True(dst.BlockedBuffItems.Count == 0 && dst.CustomBuffItems.Count == 0, "an old profile loads none");
|
||||
|
||||
// The settings bridge: sent, and an engine save without the fields leaves them alone.
|
||||
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(payload != null && payload.BlockedBuffItems == null && payload.CustomBuffItems == null, "an engine payload without them has none");
|
||||
var s = new LegacyUiSettings();
|
||||
s.SetBuffItemAllowed("Asheron's Benediction", false, out _);
|
||||
s.AddCustomBuffItem("Elixir of the Hunt", new uint[] { ElixirSpell }, out _);
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Priv)!.SetValue(dash, true);
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Priv)!.SetValue(dash, s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", Priv)!.SetValue(dash, new LegacyAdvancedSettingsUi(s));
|
||||
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(sent?.BlockedBuffItems != null && sent.BlockedBuffItems.SequenceEqual(new[] { "Asheron's Benediction" }), "the blocked list is sent");
|
||||
Check.True(sent?.CustomBuffItems is { Count: 1 } list && list[0].Name == "Elixir of the Hunt", "the custom list is sent");
|
||||
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
|
||||
Check.True(s.BlockedBuffItems.Count == 1 && s.CustomBuffItems.Count == 1, "a save without them leaves them alone");
|
||||
dash.ApplySettingsJson("{\"BlockedBuffItems\":[],\"CustomBuffItems\":[]}");
|
||||
Check.True(s.BlockedBuffItems.Count == 0 && s.CustomBuffItems.Count == 0, "a save with empty lists clears them");
|
||||
}
|
||||
}
|
||||
519
Tools/RynthCore.RynthAiHostTests/Tests/CallStateRepairTests.cs
Normal file
519
Tools/RynthCore.RynthAiHostTests/Tests/CallStateRepairTests.cs
Normal file
|
|
@ -0,0 +1,519 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Meta;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-11-11: CallState rules that lost their target. Before 34b7d45e (2026-09-30) the .met parser
|
||||
// left a CallState's target empty and the .af writer saved it as "CallState {} {<its own state>}"
|
||||
// ("{Default}" inside a DoAll); such a rule fires, calls nothing and the meta never leaves the
|
||||
// state. A load now says so in chat, and Repair from .met fills the targets and return states
|
||||
// from the .met of the same name, matched by order within each state (CallStateRepair).
|
||||
// Everything is written under the runner's scratch folder.
|
||||
internal static class CallStateRepairTests
|
||||
{
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("callstate: empty targets are found, nested DoAll ones too (an old .af as written)", Detection);
|
||||
r.Add("callstate: the .met next to the .af (or above it inside MetaFiles) is found", FindsMet);
|
||||
r.Add("callstate: repair by order fills targets and return states, nested ones included", RepairMatches);
|
||||
r.Add("callstate: repair is refused, nothing changed, when a state's counts differ or it isn't in the .met", RepairRefused);
|
||||
r.Add("callstate: a repaired meta writes and parses back with its targets and return states", RoundTrip);
|
||||
r.Add("callstate: loading a broken .af warns in chat once; Repair from .met backs up, writes and reloads", LoadWarnsAndRepairs);
|
||||
r.Add("callstate: without a .met the warning says so and repair changes nothing", NoMet);
|
||||
r.Add("callstate: /ra meta repair replies either way", RepairCommand);
|
||||
string? sample = Environment.GetEnvironmentVariable("RYNTH_CALLSTATE_SAMPLE");
|
||||
if (!string.IsNullOrEmpty(sample) && Directory.Exists(sample))
|
||||
r.Add("callstate: sample metas (RYNTH_CALLSTATE_SAMPLE)", () => Sample(sample));
|
||||
}
|
||||
|
||||
// ── A hand-built VTank .met ──────────────────────────────────────────
|
||||
|
||||
/// <summary>One action of a .met row: VTank's action type and its data lines.</summary>
|
||||
private sealed record Act(int Type, string[] Data);
|
||||
|
||||
private static Act Call(string to, string ret) => new(5, new[] { "TABLE", "2", "k", "v", "n", "n", "2", "s", "st", "s", to, "s", "ret", "s", ret });
|
||||
private static Act Chat(string text) => new(2, new[] { "s", text });
|
||||
private static Act SetState(string state) => new(1, new[] { "s", state });
|
||||
private static Act DoAll(params Act[] children)
|
||||
{
|
||||
var data = new List<string> { "TABLE", "2", "K", "V", "n", "n", children.Length.ToString() };
|
||||
foreach (Act c in children) { data.Add("i"); data.Add(c.Type.ToString()); data.AddRange(c.Data); }
|
||||
return new Act(3, data.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>A .met of Always rules, one per (state, action), in this order.</summary>
|
||||
private static string MetText(params (string State, Act Action)[] rows)
|
||||
{
|
||||
var lines = new List<string> { "1", "CondAct", "5", "CType", "AType", "CData", "AData", "State", "n", "n", "n", "n", "n", rows.Length.ToString() };
|
||||
foreach (var (state, act) in rows)
|
||||
{
|
||||
lines.AddRange(new[] { "i", "1", "i", act.Type.ToString(), "i", "0" });
|
||||
lines.AddRange(act.Data);
|
||||
lines.Add("s");
|
||||
lines.Add(state);
|
||||
}
|
||||
return string.Join("\r\n", lines) + "\r\n";
|
||||
}
|
||||
|
||||
/// <summary>The fixture: calls at the top, inside a DoAll and inside a DoAll inside a DoAll.</summary>
|
||||
private static string FixtureMet() => MetText(
|
||||
("Default", SetState("20_Upper")),
|
||||
("20_Upper", Chat("/vt nav load upper")),
|
||||
("20_Upper", Call("90_Stone", "21_West")),
|
||||
("21_West", DoAll(Chat("/ra start"), Call("90_Stone", "22_North"))),
|
||||
("22_North", DoAll(Chat("/ra stop"), DoAll(Call("91_Turnin", "99_Done"), Chat("x"))) ),
|
||||
("22_North", Call("90_Stone", "")), // VTank's ret empty: the calling state
|
||||
("90_Stone", new Act(6, new[] { "i", "0" }))); // Return
|
||||
|
||||
private static string Scratch(string name)
|
||||
{
|
||||
string dir = Path.Combine(Program.TempRoot, "callstate", name);
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
|
||||
Directory.CreateDirectory(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
private static LoadedMeta LoadMet(string name, string text)
|
||||
{
|
||||
string path = Path.Combine(Scratch("met-" + name), name + ".met");
|
||||
File.WriteAllText(path, text);
|
||||
return MetFileParser.Load(path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What an older RynthAi saved for <paramref name="met"/>: its parser left every CallState target
|
||||
/// (and return state) empty, and its writer filled the return with the rule's State. Nested DoAll
|
||||
/// children have State "Default" from the .met parser, so theirs came out as {Default}.
|
||||
/// </summary>
|
||||
private static string BrokenAfText(LoadedMeta met)
|
||||
{
|
||||
static void Clear(MetaRule r)
|
||||
{
|
||||
if (r.Action == MetaActionType.CallMetaState) { r.ActionData = ""; r.CallReturnState = ""; }
|
||||
foreach (MetaRule c in r.ActionChildren) Clear(c);
|
||||
}
|
||||
foreach (MetaRule r in met.Rules) Clear(r);
|
||||
return AfFileWriter.SaveToString(met.Rules, met.EmbeddedNavs);
|
||||
}
|
||||
|
||||
private static List<MetaRule> Calls(IEnumerable<MetaRule> rules, string state)
|
||||
=> CallStateRepair.CallStatesByState(rules).First(s => s.State == state).Calls;
|
||||
|
||||
// ── Tests ────────────────────────────────────────────────────────────
|
||||
|
||||
private static void Detection()
|
||||
{
|
||||
// As the older RynthAi wrote it (a top-level call, one in a DoAll, one in a DoAll in a DoAll).
|
||||
LoadedMeta m = AfFileParser.LoadFromText(string.Join("\n", new[]
|
||||
{
|
||||
"STATE: {20_Upper} ~~ {",
|
||||
"\tIF:\tAlways",
|
||||
"\t\tDO:\tCallState {} {20_Upper}",
|
||||
"\tIF:\tAlways",
|
||||
"\t\tDO:\tCallState {90_Stone} {21_West}",
|
||||
"~~ }",
|
||||
"STATE: {21_West} ~~ {",
|
||||
"\tIF:\tAlways",
|
||||
"\t\tDO:\tDoAll",
|
||||
"\t\t\t\t\tChat {/ra start}",
|
||||
"\t\t\t\t\tCallState {} {Default}",
|
||||
"\t\t\t\t\tDoAll",
|
||||
"\t\t\t\t\t\tCallState {} {Default}",
|
||||
"~~ }",
|
||||
}));
|
||||
Check.Eq(m.Warnings.Count, 0, "parses cleanly: " + string.Join(" | ", m.Warnings));
|
||||
Check.Eq(m.Rules.Count, 3, "three rules");
|
||||
Check.Eq(m.Rules[0].ActionData, "", "CallState {} reads as an empty target");
|
||||
Check.True(CallStateRepair.IsEmptyTarget(m.Rules[0]), "...which is an empty target");
|
||||
Check.False(CallStateRepair.IsEmptyTarget(m.Rules[1]), "a call with a target is fine");
|
||||
|
||||
var empty = CallStateRepair.EmptyTargets(m.Rules);
|
||||
Check.Eq(string.Join(",", empty.Select(e => $"{e.State}={e.Count}")), "20_Upper=1,21_West=2", "per state, nested DoAll ones counted");
|
||||
Check.Eq(CallStateRepair.CountEmpty(m.Rules), 3, "three in all");
|
||||
Check.Eq(Calls(m.Rules, "21_West").Count, 2, "depth first: both nested calls");
|
||||
|
||||
// A target from an expression that is only spaces is still nothing to call; other actions don't count.
|
||||
var rules = new List<MetaRule>
|
||||
{
|
||||
new() { State = "A", Action = MetaActionType.CallMetaState, ActionData = " " },
|
||||
new() { State = "A", Action = MetaActionType.SetMetaState, ActionData = "" },
|
||||
new() { State = "A", Action = MetaActionType.All }, // an empty DoAll
|
||||
};
|
||||
Check.Eq(CallStateRepair.CountEmpty(rules), 1, "blank target counts, an empty SetState or DoAll doesn't");
|
||||
Check.Eq(CallStateRepair.CountEmpty(new List<MetaRule>()), 0, "no rules, nothing");
|
||||
|
||||
// The chat line.
|
||||
string withMet = CallStateRepair.WarningLine("aeth.af", 15, @"C:\x\MetaFiles\aeth.met");
|
||||
Check.True(withMet.StartsWith("[RynthAi] aeth.af: 15 CallState rules have no state to call."), "names the file and count: " + withMet);
|
||||
Check.True(withMet.Contains("saved by an older RynthAi") && withMet.Contains("Load the original .met instead")
|
||||
&& withMet.Contains("Repair from .met") && withMet.Contains("aeth.met"), "says why and both ways out");
|
||||
string one = CallStateRepair.WarningLine("x.af", 1, null);
|
||||
Check.True(one.Contains("1 CallState rule has no state"), "singular");
|
||||
Check.True(one.Contains("No x.met is next to it") && !one.Contains("Repair from .met"), "no .met: says so, offers no repair: " + one);
|
||||
}
|
||||
|
||||
private static void FindsMet()
|
||||
{
|
||||
string root = Scratch("find");
|
||||
string metas = Path.Combine(root, "MetaFiles");
|
||||
string sub = Path.Combine(metas, "Server", "Char");
|
||||
Directory.CreateDirectory(sub);
|
||||
|
||||
string af = Path.Combine(metas, "Farm.af");
|
||||
Check.Null(CallStateRepair.FindSourceMet(af), "no .met: null");
|
||||
File.WriteAllText(Path.Combine(metas, "Farm.met"), "x");
|
||||
Check.Eq(CallStateRepair.FindSourceMet(af), Path.Combine(metas, "Farm.met"), "next to it");
|
||||
Check.True(CallStateRepair.FindSourceMet(Path.Combine(metas, "farm.AF")) is string s && s.EndsWith("Farm.met", StringComparison.OrdinalIgnoreCase), "names ignore case");
|
||||
|
||||
string subAf = Path.Combine(sub, "Farm.af");
|
||||
Check.Eq(CallStateRepair.FindSourceMet(subAf), Path.Combine(metas, "Farm.met"), "in a subfolder of MetaFiles: MetaFiles' .met");
|
||||
File.WriteAllText(Path.Combine(sub, "Farm.met"), "x");
|
||||
Check.Eq(CallStateRepair.FindSourceMet(subAf), Path.Combine(sub, "Farm.met"), "its own folder first");
|
||||
|
||||
// Outside MetaFiles only its own folder counts (nothing above MetaFiles either).
|
||||
File.WriteAllText(Path.Combine(root, "Other.met"), "x");
|
||||
string outside = Path.Combine(root, "elsewhere");
|
||||
Directory.CreateDirectory(outside);
|
||||
Check.Null(CallStateRepair.FindSourceMet(Path.Combine(outside, "Other.af")), "not from the folder above an outside .af");
|
||||
Check.Null(CallStateRepair.FindSourceMet(Path.Combine(metas, "Other.af")), "not above MetaFiles");
|
||||
Check.Null(CallStateRepair.FindSourceMet(""), "no path");
|
||||
}
|
||||
|
||||
private static void RepairMatches()
|
||||
{
|
||||
LoadedMeta met = LoadMet("match", FixtureMet());
|
||||
Check.Eq(met.Warnings.Count, 0, ".met parses: " + string.Join(" | ", met.Warnings));
|
||||
Check.Eq(met.Rules.Count, 7, "seven rules");
|
||||
|
||||
LoadedMeta broken = AfFileParser.LoadFromText(BrokenAfText(LoadMet("match2", FixtureMet())));
|
||||
Check.Eq(CallStateRepair.CountEmpty(broken.Rules), 4, "the old .af: all four calls empty");
|
||||
// What the old writer did to the return states.
|
||||
Check.Eq(Calls(broken.Rules, "20_Upper")[0].CallReturnState, "20_Upper", "top level: its own state");
|
||||
Check.Eq(Calls(broken.Rules, "21_West")[0].CallReturnState, "Default", "in a DoAll: Default");
|
||||
|
||||
CallStateRepair.Result r = CallStateRepair.Repair(broken.Rules, met.Rules);
|
||||
Check.True(r.Ok, "repaired: " + r.Why);
|
||||
Check.Eq(r.Filled, 4, "four filled");
|
||||
Check.Eq(r.States, 3, "in three states");
|
||||
Check.Eq(CallStateRepair.CountEmpty(broken.Rules), 0, "none left");
|
||||
|
||||
MetaRule up = Calls(broken.Rules, "20_Upper")[0];
|
||||
Check.Eq(up.ActionData, "90_Stone", "top level: target");
|
||||
Check.Eq(up.CallReturnState, "21_West", "top level: the .met's return state, not its own");
|
||||
MetaRule west = Calls(broken.Rules, "21_West")[0];
|
||||
Check.Eq(west.ActionData, "90_Stone", "in a DoAll: target");
|
||||
Check.Eq(west.CallReturnState, "22_North", "in a DoAll: return state (was Default)");
|
||||
var north = Calls(broken.Rules, "22_North");
|
||||
Check.Eq(north.Count, 2, "22_North: two calls");
|
||||
Check.Eq(north[0].ActionData + ">" + north[0].CallReturnState, "91_Turnin>99_Done", "in a DoAll in a DoAll, first in order");
|
||||
Check.Eq(north[1].ActionData + ">" + north[1].CallReturnState, "90_Stone>22_North", "the .met's empty return: the calling state");
|
||||
Check.True(r.Details.Any(d => d.StartsWith("22_North: 91_Turnin (return 99_Done), 90_Stone (return 22_North)")), "details name what went where: " + string.Join(" | ", r.Details));
|
||||
|
||||
// A call that already has a target is left alone (hand-fixed since), the rest still filled.
|
||||
LoadedMeta partly = AfFileParser.LoadFromText(BrokenAfText(LoadMet("match3", FixtureMet())));
|
||||
MetaRule fixedByHand = Calls(partly.Rules, "22_North")[1];
|
||||
fixedByHand.ActionData = "Elsewhere";
|
||||
fixedByHand.CallReturnState = "Back";
|
||||
r = CallStateRepair.Repair(partly.Rules, met.Rules);
|
||||
Check.True(r.Ok, "partly repaired by hand: still repairs");
|
||||
Check.Eq(r.Filled, 3, "three filled");
|
||||
Check.Eq(fixedByHand.ActionData + ">" + fixedByHand.CallReturnState, "Elsewhere>Back", "the hand-set one is kept");
|
||||
|
||||
// Nothing to do.
|
||||
r = CallStateRepair.Repair(partly.Rules, met.Rules);
|
||||
Check.False(r.Ok, "a second repair has nothing to do");
|
||||
Check.Eq(r.Why, "no CallState rule is missing its target", "and says so");
|
||||
}
|
||||
|
||||
private static void RepairRefused()
|
||||
{
|
||||
LoadedMeta met = LoadMet("refuse", FixtureMet());
|
||||
|
||||
// The .af lost a CallState in 22_North (edited since): that state's counts differ.
|
||||
LoadedMeta af = AfFileParser.LoadFromText(BrokenAfText(LoadMet("refuse2", FixtureMet())));
|
||||
af.Rules.RemoveAll(x => x.State == "22_North" && x.Action == MetaActionType.CallMetaState);
|
||||
string before = AfFileWriter.SaveToString(af.Rules, af.EmbeddedNavs);
|
||||
CallStateRepair.Result r = CallStateRepair.Repair(af.Rules, met.Rules);
|
||||
Check.False(r.Ok, "refused");
|
||||
Check.True(r.Why.Contains("state '22_North' has 1 CallState rule in the .af and 2 in the .met"), "says which state and the counts: " + r.Why);
|
||||
Check.True(r.Why.Contains("nothing was changed"), "and that nothing changed");
|
||||
Check.Eq(r.Filled, 0, "none filled");
|
||||
Check.Eq(AfFileWriter.SaveToString(af.Rules, af.EmbeddedNavs), before, "the rules are as they were (other states too)");
|
||||
Check.Eq(CallStateRepair.CountEmpty(af.Rules), 3, "the other states' calls still empty");
|
||||
|
||||
// More calls in the .af than in the .met.
|
||||
af = AfFileParser.LoadFromText(BrokenAfText(LoadMet("refuse3", FixtureMet())));
|
||||
af.Rules.Add(new MetaRule { State = "20_Upper", Condition = MetaConditionType.Always, Action = MetaActionType.CallMetaState });
|
||||
r = CallStateRepair.Repair(af.Rules, met.Rules);
|
||||
Check.False(r.Ok, "an extra call: refused");
|
||||
Check.True(r.Why.Contains("state '20_Upper' has 2 CallState rules in the .af and 1 in the .met"), r.Why);
|
||||
|
||||
// A state the .met doesn't have.
|
||||
af = AfFileParser.LoadFromText(BrokenAfText(LoadMet("refuse4", FixtureMet())));
|
||||
foreach (MetaRule x in af.Rules.Where(x => x.State == "21_West")) x.State = "21_Renamed";
|
||||
r = CallStateRepair.Repair(af.Rules, met.Rules);
|
||||
Check.False(r.Ok, "a renamed state: refused");
|
||||
Check.True(r.Why.Contains("state '21_Renamed' isn't in the .met"), r.Why);
|
||||
Check.Eq(CallStateRepair.CountEmpty(af.Rules), 4, "nothing filled anywhere");
|
||||
|
||||
// The .met's own call is empty too (it came from somewhere else broken).
|
||||
LoadedMeta emptyMet = LoadMet("refuse5", MetText(("A", Call("", "A"))));
|
||||
var one = new List<MetaRule> { new() { State = "A", Action = MetaActionType.CallMetaState } };
|
||||
r = CallStateRepair.Repair(one, emptyMet.Rules);
|
||||
Check.False(r.Ok, "the .met has no target either: refused");
|
||||
Check.True(r.Why.Contains("CallState 1 has no target in the .met either"), r.Why);
|
||||
}
|
||||
|
||||
private static void RoundTrip()
|
||||
{
|
||||
LoadedMeta met = LoadMet("roundtrip", FixtureMet());
|
||||
LoadedMeta af = AfFileParser.LoadFromText(BrokenAfText(LoadMet("roundtrip2", FixtureMet())));
|
||||
Check.True(CallStateRepair.Repair(af.Rules, met.Rules).Ok, "repaired");
|
||||
|
||||
string text = AfFileWriter.SaveToString(af.Rules, af.EmbeddedNavs);
|
||||
Check.True(text.Contains("CallState {90_Stone} {21_West}"), "written: top level");
|
||||
Check.True(text.Contains("CallState {91_Turnin} {99_Done}"), "written: nested");
|
||||
Check.False(text.Contains("CallState {}"), "no empty target written");
|
||||
|
||||
LoadedMeta back = AfFileParser.LoadFromText(text);
|
||||
Check.Eq(back.Warnings.Count, 0, "parses cleanly");
|
||||
Check.Eq(back.Rules.Count, af.Rules.Count, "every rule back");
|
||||
Check.Eq(CallStateRepair.CountEmpty(back.Rules), 0, "no empty targets after a reload");
|
||||
string Pairs(IEnumerable<MetaRule> rules) => string.Join(" | ",
|
||||
CallStateRepair.CallStatesByState(rules).SelectMany(s => s.Calls.Select(c => $"{s.State}:{c.ActionData}>{c.CallReturnState}")));
|
||||
Check.Eq(Pairs(back.Rules), Pairs(af.Rules), "same targets and return states");
|
||||
Check.Eq(Pairs(back.Rules),
|
||||
"20_Upper:90_Stone>21_West | 21_West:90_Stone>22_North | 22_North:91_Turnin>99_Done | 22_North:90_Stone>22_North",
|
||||
"as in the .met");
|
||||
Check.Eq(AfFileWriter.SaveToString(back.Rules, back.EmbeddedNavs), text, "writes back the same");
|
||||
}
|
||||
|
||||
private static void LoadWarnsAndRepairs()
|
||||
{
|
||||
DataWriteGuard.Reset();
|
||||
string metas = Path.Combine(Scratch("load"), "MetaFiles");
|
||||
Directory.CreateDirectory(metas);
|
||||
string metPath = Path.Combine(metas, "Tower.met");
|
||||
string afPath = Path.Combine(metas, "Tower.af");
|
||||
File.WriteAllText(metPath, FixtureMet());
|
||||
File.WriteAllText(afPath, BrokenAfText(MetFileParser.Load(metPath)));
|
||||
byte[] brokenBytes = File.ReadAllBytes(afPath);
|
||||
byte[] metBytes = File.ReadAllBytes(metPath);
|
||||
|
||||
var log = new List<string>();
|
||||
var settings = new LegacyUiSettings();
|
||||
var ui = new LegacyMetaUi(settings, new List<string>()) { Log = log.Add };
|
||||
Check.True(ui.LoadMacroFile(afPath), "the broken .af loads: " + ui.LastLoadStatus);
|
||||
Check.Eq(ui.PendingNotices, 1, "one chat line waits");
|
||||
var chat = new List<string>();
|
||||
ui.DrainNotices(l => { chat.Add(l); return true; });
|
||||
Check.Eq(chat.Count, 1, "one line posted");
|
||||
Check.True(chat[0].StartsWith("[RynthAi] Tower.af: 4 CallState rules have no state to call.") && chat[0].Contains("Tower.met"), "the warning: " + string.Join(" / ", chat));
|
||||
Check.Eq(ui.PendingNotices, 0, "nothing left");
|
||||
Check.True(log.Any(l => l.Contains("state '22_North' has 2 CallState rules with no state to call")), "the log names each state: " + string.Join(" / ", log));
|
||||
Check.True(log.Any(l => l.Contains("state '20_Upper' has 1 CallState rule with")), "...every one");
|
||||
Check.Eq(ui.EmptyCallStatesNow(out string? found), 4, "the window sees four");
|
||||
Check.Eq(found, metPath, "...and the .met to repair from");
|
||||
|
||||
// A refused write: the host is busy (a line it doesn't take waits for the next tick).
|
||||
ui.LoadMacroFile(afPath);
|
||||
int tries = 0;
|
||||
ui.DrainNotices(_ => { tries++; return false; });
|
||||
Check.Eq(ui.PendingNotices, 1, "a refused line waits");
|
||||
ui.DrainNotices(l => { tries++; return true; });
|
||||
Check.Eq(ui.PendingNotices, 0, "and goes out on a later tick");
|
||||
Check.Eq(tries, 2, "offered once per tick");
|
||||
|
||||
// An unsaved edit in memory is not thrown away by the reload.
|
||||
settings.MetaUnsaved = true;
|
||||
Check.False(ui.RepairFromMet(out string reply), "refused with an unsaved edit");
|
||||
Check.True(reply.StartsWith("[RynthAi] Can't repair Tower.af: your last change"), reply);
|
||||
settings.MetaUnsaved = false;
|
||||
|
||||
settings.CurrentState = "21_West";
|
||||
Check.True(ui.RepairFromMet(out reply), "repaired: " + reply);
|
||||
Check.True(reply.StartsWith("[RynthAi] Repaired Tower.af: 4 CallState rules in 3 states filled from Tower.met, and loaded it again"), reply);
|
||||
string[] backups = Directory.GetFiles(metas, "Tower.af.bak-*");
|
||||
Check.Eq(backups.Length, 1, "one backup copy next to it");
|
||||
if (backups.Length == 1)
|
||||
{
|
||||
Check.True(System.Text.RegularExpressions.Regex.IsMatch(Path.GetFileName(backups[0]), @"^Tower\.af\.bak-\d{8}-\d{6}$"), "named <name>.af.bak-yyyyMMdd-HHmmss: " + backups[0]);
|
||||
Check.True(((ReadOnlySpan<byte>)File.ReadAllBytes(backups[0])).SequenceEqual(brokenBytes), "the backup is the file as it was");
|
||||
Check.True(reply.Contains(Path.GetFileName(backups[0])), "the reply names it");
|
||||
}
|
||||
Check.True(((ReadOnlySpan<byte>)File.ReadAllBytes(metPath)).SequenceEqual(metBytes), "the .met is never written");
|
||||
LoadedMeta onDisk = AfFileParser.Load(afPath);
|
||||
Check.Eq(CallStateRepair.CountEmpty(onDisk.Rules), 0, "the .af on disk has its targets");
|
||||
Check.Eq(Calls(onDisk.Rules, "21_West")[0].CallReturnState, "22_North", "...and return states");
|
||||
Check.Eq(CallStateRepair.CountEmpty(settings.MetaRules), 0, "the loaded rules are the repaired ones");
|
||||
Check.Eq(settings.CurrentMetaPath, afPath, "still the .af");
|
||||
Check.Eq(settings.CurrentState, "Default", "loaded again: starts over");
|
||||
Check.True(settings.ForceStateReset, "state reset forced");
|
||||
Check.Eq(ui.PendingNotices, 0, "the reload has nothing to warn about");
|
||||
Check.Eq(ui.EmptyCallStatesNow(out _), 0, "the window has nothing to repair");
|
||||
Check.True(ui.StatusLine.StartsWith("[RynthAi] Repaired Tower.af"), "the status line says so");
|
||||
Check.Eq(DataWriteGuard.PendingCount, 0, "no save problem reported");
|
||||
|
||||
// Again: nothing to do, nothing written.
|
||||
DateTime stamp = File.GetLastWriteTimeUtc(afPath);
|
||||
Check.False(ui.RepairFromMet(out reply), "a second repair does nothing");
|
||||
Check.True(reply.StartsWith("[RynthAi] No CallState rule in Tower.af is missing its target"), reply);
|
||||
Check.Eq(File.GetLastWriteTimeUtc(afPath), stamp, "not rewritten");
|
||||
Check.Eq(Directory.GetFiles(metas, "Tower.af.bak-*").Length, 1, "no second backup");
|
||||
|
||||
// A mismatch from the window: refused, file and folder unchanged.
|
||||
File.WriteAllText(afPath, BrokenAfText(MetFileParser.Load(metPath)).Replace("STATE: {22_North}", "STATE: {22_Elsewhere}"));
|
||||
byte[] mismatch = File.ReadAllBytes(afPath);
|
||||
Check.True(ui.LoadMacroFile(afPath), "a mismatched .af loads");
|
||||
Check.False(ui.RepairFromMet(out reply), "refused");
|
||||
Check.True(reply.StartsWith("[RynthAi] Can't repair Tower.af: the .met doesn't match the .af (state '22_Elsewhere' isn't in the .met)"), reply);
|
||||
Check.True(((ReadOnlySpan<byte>)File.ReadAllBytes(afPath)).SequenceEqual(mismatch), "file unchanged");
|
||||
Check.Eq(Directory.GetFiles(metas, "Tower.af.bak-*").Length, 1, "no backup made for a refusal");
|
||||
Check.True(log.Any(l => l.Contains("refused") && l.Contains("22_Elsewhere")), "the refusal is logged");
|
||||
|
||||
// A .met loaded directly: nothing to check, no warning.
|
||||
Check.True(ui.LoadMacroFile(metPath), "the .met loads");
|
||||
Check.Eq(ui.EmptyCallStatesNow(out _), 0, "a .met has its targets");
|
||||
Check.False(ui.RepairFromMet(out reply), "repair refuses a .met");
|
||||
Check.True(reply.Contains("only an .af can be repaired"), reply);
|
||||
}
|
||||
|
||||
private static void NoMet()
|
||||
{
|
||||
string metas = Path.Combine(Scratch("nomet"), "MetaFiles");
|
||||
Directory.CreateDirectory(metas);
|
||||
string afPath = Path.Combine(metas, "Lonely.af");
|
||||
File.WriteAllText(afPath, BrokenAfText(LoadMet("nomet-src", FixtureMet())));
|
||||
byte[] before = File.ReadAllBytes(afPath);
|
||||
|
||||
var settings = new LegacyUiSettings();
|
||||
var ui = new LegacyMetaUi(settings, new List<string>());
|
||||
Check.True(ui.LoadMacroFile(afPath), "loads");
|
||||
var chat = new List<string>();
|
||||
ui.DrainNotices(l => { chat.Add(l); return true; });
|
||||
Check.Eq(chat.Count, 1, "one warning");
|
||||
Check.True(chat.Count == 1 && chat[0].Contains("4 CallState rules have no state to call") && chat[0].Contains("No Lonely.met is next to it"), "says there's no .met: " + string.Join(" / ", chat));
|
||||
Check.Eq(ui.EmptyCallStatesNow(out string? met), 4, "the window still counts them");
|
||||
Check.Null(met, "...with no .met (no Repair button)");
|
||||
Check.False(ui.RepairFromMet(out string reply), "repair refused");
|
||||
Check.True(reply.StartsWith("[RynthAi] Can't repair Lonely.af: there is no Lonely.met next to it."), reply);
|
||||
Check.True(((ReadOnlySpan<byte>)File.ReadAllBytes(afPath)).SequenceEqual(before), "file unchanged");
|
||||
Check.Eq(Directory.GetFiles(metas).Length, 1, "no backup, nothing else written");
|
||||
|
||||
// A healthy .af: no warning at all.
|
||||
string good = Path.Combine(metas, "Good.af");
|
||||
File.WriteAllText(good, "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tCallState {B} {Default}\n~~ }\n");
|
||||
Check.True(ui.LoadMacroFile(good), "a healthy .af loads");
|
||||
Check.Eq(ui.PendingNotices, 0, "no warning for it");
|
||||
}
|
||||
|
||||
private static void RepairCommand()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
DataWriteGuard.Reset();
|
||||
string metas = Path.Combine(Scratch("command"), "MetaFiles");
|
||||
Directory.CreateDirectory(metas);
|
||||
string metPath = Path.Combine(metas, "Cmd.met");
|
||||
string afPath = Path.Combine(metas, "Cmd.af");
|
||||
File.WriteAllText(metPath, FixtureMet());
|
||||
File.WriteAllText(afPath, BrokenAfText(MetFileParser.Load(metPath)));
|
||||
|
||||
var settings = new LegacyUiSettings();
|
||||
var navFiles = new List<string>();
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
void Set(string f, object v) => typeof(LegacyDashboardRenderer).GetField(f, Any)!.SetValue(dash, v);
|
||||
Set("_profileLoaded", true);
|
||||
Set("_settings", settings);
|
||||
Set("_host", FakeHost.Create());
|
||||
Set("_metaFolder", metas);
|
||||
Set("_navFiles", navFiles);
|
||||
Set("_metaFiles", new List<string>());
|
||||
Set("_profileListsLock", new object());
|
||||
Set("_metaUi", new LegacyMetaUi(settings, navFiles));
|
||||
|
||||
var plugin = new RynthAiPlugin();
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi });
|
||||
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(plugin, dash);
|
||||
MethodInfo dispatch = typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!;
|
||||
void Ra(string line)
|
||||
{
|
||||
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
dispatch.Invoke(plugin, new object[] { parts[1].ToLowerInvariant(), parts, 0 });
|
||||
}
|
||||
string Said() => string.Join(" / ", FakeHost.Chat);
|
||||
|
||||
Ra("/ra meta repair");
|
||||
Check.True(FakeHost.Chat.Exists(l => l.Contains("Can't repair the meta: no meta is loaded")), "no meta loaded: says so: " + Said());
|
||||
FakeHost.Chat.Clear();
|
||||
|
||||
Ra("/ra meta load Cmd");
|
||||
Check.True(FakeHost.Chat.Exists(l => l.Contains("Loaded meta 'Cmd'")), "loaded: " + Said());
|
||||
FakeHost.Chat.Clear();
|
||||
Ra("/ra meta repair now");
|
||||
Check.True(FakeHost.Chat.Exists(l => l.Contains("Usage: /ra meta repair")), "extra words: usage: " + Said());
|
||||
FakeHost.Chat.Clear();
|
||||
Ra("/ra meta repair");
|
||||
Check.True(FakeHost.Chat.Exists(l => l.StartsWith("[RynthAi] Repaired Cmd.af: 4 CallState rules in 3 states")), "repaired: " + Said());
|
||||
Check.Eq(CallStateRepair.CountEmpty(settings.MetaRules), 0, "the loaded meta has its targets");
|
||||
FakeHost.Chat.Clear();
|
||||
Ra("/ra meta repair");
|
||||
Check.True(FakeHost.Chat.Exists(l => l.Contains("nothing to repair")), "again: nothing to repair: " + Said());
|
||||
FakeHost.Chat.Clear();
|
||||
Ra("/ra meta");
|
||||
Check.True(FakeHost.Chat.Exists(l => l.Contains("/ra meta") && l.Contains("| repair")), "the verb list names repair: " + Said());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opt-in: a folder with real metas (copies; never the live install). For each <name>.af with a
|
||||
/// <name>.met beside it, the repair must fill every empty target; when <name>.reference.af is
|
||||
/// there too (repaired by hand), every state's CallState targets and return states must match it.
|
||||
/// </summary>
|
||||
private static void Sample(string dir)
|
||||
{
|
||||
string work = Scratch("sample");
|
||||
int checkedAny = 0;
|
||||
foreach (string af in Directory.GetFiles(dir, "*.af"))
|
||||
{
|
||||
if (af.EndsWith(".reference.af", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
string stem = Path.GetFileNameWithoutExtension(af);
|
||||
string met = Path.Combine(dir, stem + ".met");
|
||||
if (!File.Exists(met)) continue;
|
||||
string copyAf = Path.Combine(work, stem + ".af");
|
||||
File.Copy(af, copyAf, overwrite: true);
|
||||
File.Copy(met, Path.Combine(work, stem + ".met"), overwrite: true);
|
||||
|
||||
var settings = new LegacyUiSettings();
|
||||
var ui = new LegacyMetaUi(settings, new List<string>());
|
||||
Check.True(ui.LoadMacroFile(copyAf), $"{stem}: loads");
|
||||
int empty = ui.EmptyCallStatesNow(out string? found);
|
||||
Check.True(empty > 0, $"{stem}: has empty CallState targets ({empty})");
|
||||
Check.NotNull(found, $"{stem}: the .met is found");
|
||||
Check.True(ui.RepairFromMet(out string reply), $"{stem}: {reply}");
|
||||
Check.Eq(CallStateRepair.CountEmpty(AfFileParser.Load(copyAf).Rules), 0, $"{stem}: no empty target left");
|
||||
Console.WriteLine(" " + reply);
|
||||
|
||||
string reference = Path.Combine(dir, stem + ".reference.af");
|
||||
if (File.Exists(reference))
|
||||
{
|
||||
static string Pairs(IEnumerable<MetaRule> rules) => string.Join("\n",
|
||||
CallStateRepair.CallStatesByState(rules).SelectMany(s => s.Calls.Select(c => $"{s.State}:{c.ActionData}>{c.CallReturnState}")));
|
||||
Check.Eq(Pairs(AfFileParser.Load(copyAf).Rules), Pairs(AfFileParser.Load(reference).Rules), $"{stem}: matches the hand-repaired copy");
|
||||
}
|
||||
checkedAny++;
|
||||
}
|
||||
Check.True(checkedAny > 0, "found an .af with its .met in " + dir);
|
||||
}
|
||||
}
|
||||
|
|
@ -47,7 +47,11 @@ internal static class ChestLootTests
|
|||
r.Add("chest loot: a salvage-only item is left when no UST is carried, as on corpses", SalvageWithoutUstLeft);
|
||||
r.Add("chest loot: opened mid-fight it waits for combat, then is looted if still open", ChestWaitsForCombat);
|
||||
r.Add("chest loot: an open chest is looted before a fight further than 5 yd off (a chest closes when you walk away)", OpenChestBeforeDistantFight);
|
||||
r.Add("chest loot: closed by the player mid-loot -> session ends, chest not reopened", ClosedMidLootNotReopened);
|
||||
r.Add("chest loot: closed mid-loot -> the looter opens it again and takes the rest", ClosedMidLootReopened);
|
||||
r.Add("chest loot: a chest that keeps closing is opened again twice in a minute, then left", ReopenIsBounded);
|
||||
r.Add("chest loot: a chest the player opened with the macro off is not reopened when it closes", ManualChestNotReopened);
|
||||
r.Add("chest loot: an open chest that closes before the looter gets to it (a fight had the tick) is opened again", ClosedBeforeTakenReopened);
|
||||
r.Add("chest loot: no jump-loot from a chest (a hop can take the character out of its use radius)", NoJumpLootFromChest);
|
||||
r.Add("chest loot: a chest gets 2 minutes (not the 12 s corpse timeout), restarted by each pickup", ChestTimeoutLongAndRestarted);
|
||||
}
|
||||
|
||||
|
|
@ -533,7 +537,13 @@ internal static class ChestLootTests
|
|||
Check.False((bool)close.Call("IsOpenChestTurn", true, true)!, "a monster at the chest is fought first");
|
||||
}
|
||||
|
||||
private static void ClosedMidLootNotReopened()
|
||||
private static int ChestUses() => FakeHost.Uses.Count(u => u == Chest);
|
||||
|
||||
// 2026-11-12: the client closes a container once the character is outside its use radius at its
|
||||
// once-a-second check (a jump-loot hop, the walk back for the next item, a step toward a monster).
|
||||
// 8 of 134 chest loots in a week of logs ended that way with items left; a corpse was reopened,
|
||||
// a chest was not.
|
||||
private static void ClosedMidLootReopened()
|
||||
{
|
||||
BaseWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
|
|
@ -543,14 +553,138 @@ internal static class ChestLootTests
|
|||
bot.TickUntil(() => bot.Moved(Gem));
|
||||
Check.True(bot.Moved(Gem), "the gem's move is sent");
|
||||
|
||||
// The player closes it before the gem arrives.
|
||||
// The chest closes before the gem arrives.
|
||||
bot.ServerCloses(Chest);
|
||||
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "the session ends");
|
||||
bot.TickFor(300);
|
||||
Check.False(FakeHost.Uses.Contains(Chest), "the chest is never reopened by the looter");
|
||||
Check.Eq(bot.Get<uint>("_lastChestLootedId"), 0u, "a chest closed mid-loot doesn't count as looted");
|
||||
Check.Eq(FakeHost.Closes.Count, 0, "nothing to close: it is closed already");
|
||||
Check.False(bot.Marked(Chest), "and not marked: opening it again loots it");
|
||||
Check.Eq(bot.Get<uint>("_lastChestLootedId"), 0u, "a chest closed mid-loot doesn't count as looted (a meta opens it again)");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("before looting finished")), "logged");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("before looting finished; opening it again (1 of 2)")), "logged");
|
||||
Check.True(bot.HasLootWork(), "the chest to open again is loot work: Looting keeps the tick");
|
||||
bot.Tick();
|
||||
Check.Eq(ChestUses(), 0, "not at once: the close settles first");
|
||||
|
||||
bot.TickUntil(() => ChestUses() > 0);
|
||||
Check.Eq(ChestUses(), 1, "then the looter uses the chest to open it again");
|
||||
bot.TickFor(200);
|
||||
Check.Eq(ChestUses(), 1, "one use, not one a tick, while it waits for the chest to open");
|
||||
Check.Eq(bot.Get<int>("_targetCorpseId"), 0, "and nothing else is claimed meanwhile");
|
||||
|
||||
// It opens: the gem is still in it and is taken, then the chest is closed as usual.
|
||||
int movesBefore = FakeHost.ExternalMoves.Count;
|
||||
bot.ServerOpens(Chest);
|
||||
bot.TickUntil(() => FakeHost.ExternalMoves.Count > movesBefore);
|
||||
Check.True(FakeHost.ExternalMoves.Count > movesBefore, "the gem's move is sent again");
|
||||
FakeHost.Containers[Gem] = Player;
|
||||
bot.TickUntil(() => FakeHost.Closes.Count > 0);
|
||||
Check.Eq(FakeHost.Closes.Count, 1, "closed when done");
|
||||
Check.Eq(bot.Get<uint>("_lastChestLootedId"), Chest, "now it counts as looted to the end");
|
||||
Check.False(bot.Moved(Spoon), "the spoon is still left");
|
||||
Check.False(bot.Marked(Chest), "and the chest is still never marked");
|
||||
Check.Eq(ChestUses(), 1, "no further use");
|
||||
}
|
||||
|
||||
private static void ReopenIsBounded()
|
||||
{
|
||||
BaseWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bot.Create(Chest, Gem, Spoon);
|
||||
bot.ServerOpens(Chest);
|
||||
bot.TickUntil(() => bot.Moved(Gem));
|
||||
|
||||
// It closes mid-loot, is opened again, and closes again: twice.
|
||||
for (int round = 1; round <= RynthAiPlugin.ChestReopenMax; round++)
|
||||
{
|
||||
bot.ServerCloses(Chest);
|
||||
bot.TickUntil(() => ChestUses() >= round);
|
||||
Check.Eq(ChestUses(), round, $"close {round}: the looter opens it again");
|
||||
bot.ServerOpens(Chest);
|
||||
bot.TickUntil(() => bot.Get<int>("_openedContainerId") != 0);
|
||||
Check.Eq(bot.Get<int>("_openedContainerId"), unchecked((int)Chest), $"close {round}: and takes it again");
|
||||
}
|
||||
|
||||
// The third close in a minute: left alone.
|
||||
bot.ServerCloses(Chest);
|
||||
bot.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 400);
|
||||
Check.Eq(ChestUses(), RynthAiPlugin.ChestReopenMax, "no third use");
|
||||
Check.False(bot.HasLootWork(), "and nothing left to do");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("so it is left")), "logged");
|
||||
}
|
||||
|
||||
private static void ManualChestNotReopened()
|
||||
{
|
||||
BaseWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bot.S.IsMacroRunning = false; // Pickup with macro off takes the chest the player opened
|
||||
bot.Create(Chest, Gem, Spoon);
|
||||
bot.ServerOpens(Chest);
|
||||
bot.TickUntil(() => bot.Moved(Gem));
|
||||
Check.True(bot.Moved(Gem), "the gem's move is sent");
|
||||
|
||||
bot.ServerCloses(Chest); // the player closes it
|
||||
bot.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 400);
|
||||
Check.Eq(ChestUses(), 0, "the player's chest is the player's to close: never reopened");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("not reopening it")), "logged as before");
|
||||
}
|
||||
|
||||
// The 2026-11-11 20:02 case: a meta opened a cache while the looter was on a corpse; the corpse's
|
||||
// open closed the cache untouched. Here a fight holds the tick instead: same thing, never taken.
|
||||
private static void ClosedBeforeTakenReopened()
|
||||
{
|
||||
BaseWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bot.Create(Chest, Gem, Spoon);
|
||||
bot.ServerOpens(Chest);
|
||||
bot.TickFor(150, BotActivity.Combat);
|
||||
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "open, but the looter hasn't taken it");
|
||||
|
||||
bot.ServerCloses(Chest);
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("before the looter got to it; opening it again (1 of 2)")), "booked and logged");
|
||||
bot.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 200, BotActivity.Combat);
|
||||
Check.Eq(ChestUses(), 0, "no use while the fight has the tick");
|
||||
|
||||
bot.TickUntil(() => ChestUses() > 0);
|
||||
Check.Eq(ChestUses(), 1, "used once Looting has the tick");
|
||||
bot.ServerOpens(Chest);
|
||||
LootGemAndFinish(bot, Gem);
|
||||
Check.Eq(FakeHost.Closes.Count, 1, "looted and closed");
|
||||
Check.Eq(bot.Get<uint>("_lastChestLootedId"), Chest, "and counts as looted to the end");
|
||||
|
||||
// Looting off: a chest that closes books nothing.
|
||||
BaseWorld();
|
||||
var bot2 = new Bot(FakeHost.Create(Player));
|
||||
bot2.S.LootChestsMacroOff = false;
|
||||
bot2.S.EnableLooting = false;
|
||||
bot2.Create(Chest, Gem, Spoon);
|
||||
bot2.ServerOpens(Chest);
|
||||
bot2.TickFor(100);
|
||||
bot2.ServerCloses(Chest);
|
||||
bot2.S.EnableLooting = true;
|
||||
bot2.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 300);
|
||||
Check.Eq(ChestUses(), 0, "Looting was off when it closed: not reopened");
|
||||
}
|
||||
|
||||
private static void NoJumpLootFromChest()
|
||||
{
|
||||
BaseWorld();
|
||||
FakeHost.TapJumpCalls = true;
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bot.S.LootJumpEnabled = true;
|
||||
bot.Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
|
||||
bot.Create(Chest, Gem, Spoon);
|
||||
bot.ServerOpens(Chest);
|
||||
bot.TickUntil(() => bot.Get<int>("_openedContainerId") != 0);
|
||||
|
||||
Check.False((bool)bot.Call("ShouldJumpLoot", bot.S)!, "no jump-loot while the open container is a chest");
|
||||
bot.Set("_lootChestId", 0);
|
||||
Check.True((bool)bot.Call("ShouldJumpLoot", bot.S)!, "control: the same state with a corpse open jumps");
|
||||
bot.Set("_lootChestId", unchecked((int)Chest));
|
||||
|
||||
LootGemAndFinish(bot, Gem);
|
||||
Check.True(bot.Moved(Gem), "the gem is taken");
|
||||
Check.Eq(FakeHost.TapJumps, 0, "and no jump was sent for it");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -96,6 +96,9 @@ internal static class CommandReplyTests
|
|||
new("/ra cast 1234", "/ra cast banana", K.Act),
|
||||
new("/ra targetlock off", null, K.Act),
|
||||
new("/ra fightselected off", "/ra fightselected banana", K.Act),
|
||||
new("/ra dfheight on", "/ra dfheight banana", K.Act),
|
||||
new("/ra dfheight off", null, K.Act),
|
||||
new("/ra dfheight window", null, K.Act),
|
||||
new("/ra meleelow", null, K.Act),
|
||||
new("/ra meleemid", null, K.Act),
|
||||
new("/ra meleehigh", null, K.Act),
|
||||
|
|
@ -165,11 +168,16 @@ internal static class CommandReplyTests
|
|||
new(null, "/ra mstats show", K.Act), // this rig's engine has no plugin windows: says so
|
||||
new("/ra aetheria off", "/ra aetheria banana", K.Act),
|
||||
new(null, "/ra aetheria unbox", K.Act), // nothing coalesced in this rig's pack: says so
|
||||
new("/ra autoconfirm off", "/ra autoconfirm banana", K.Act),
|
||||
new(null, "/ra autoconfirm 30", K.Act), // under 50: the range and the usage
|
||||
new(null, "/ra autoconfirm on", K.Act), // this rig's engine has no confirmation answers: says why
|
||||
new(null, "/ra nosuchverb", K.Act),
|
||||
// ── /ra: output asked for ──
|
||||
new("/ra help", null, K.Query),
|
||||
new("/ra aetheria", null, K.Query),
|
||||
new("/ra aetheria status", null, K.Query),
|
||||
new("/ra autoconfirm", null, K.Query),
|
||||
new("/ra autoconfirm status", null, K.Query),
|
||||
new("/ra", null, K.Query),
|
||||
new("/ra version", null, K.Query),
|
||||
new("/ra server", null, K.Query),
|
||||
|
|
@ -198,6 +206,8 @@ internal static class CommandReplyTests
|
|||
new("/ra combat", null, K.Query),
|
||||
new("/ra mstats list", "/ra mstats Nobody Here At All", K.Query),
|
||||
new("/ra mstats help", null, K.Query),
|
||||
new("/ra dfheight status", null, K.Query),
|
||||
new("/ra dfheight", null, K.Query),
|
||||
new("/ra why", null, K.Query),
|
||||
new("/ra ghosts", null, K.Query),
|
||||
new("/ra ghost", null, K.Query),
|
||||
|
|
|
|||
|
|
@ -0,0 +1,181 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The Dirty Fighting rotation through CombatManager (CombatManager.DirtyFighting.cs): the height each
|
||||
// melee attack is sent at follows this character's "Dirty Fighting! ..." landing lines for the target
|
||||
// being fought, High, then Medium, then Low, then the chosen default; with the rotation off or Dirty
|
||||
// Fighting untrained the fixed Melee Attack Height goes out exactly as before. The pure choice and the
|
||||
// expiry timing are RynthCore.RynthAiTests' DirtyFightingHeightTests.
|
||||
internal static class DirtyFightingRotationTests
|
||||
{
|
||||
private const uint Player = 0x50000F71;
|
||||
private const uint Lb = 0xA9B40000;
|
||||
private const uint Mob = 0x80000471, Other = 0x80000472;
|
||||
private const uint DfSkill = 52, HeavySkill = 44;
|
||||
// The game's attack heights (what the server is sent): High 1, Medium 2, Low 3.
|
||||
private const int AcHigh = 1, AcMedium = 2, AcLow = 3;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("dfheight rotation: High, then Medium, then Low, then the default as each effect lands", RotationFollowsLandings);
|
||||
r.Add("dfheight rotation: off, or Dirty Fighting untrained, sends the fixed Melee Attack Height", FixedWhenOffOrUntrained);
|
||||
r.Add("dfheight rotation: a landing on another monster, or by someone else, isn't counted", OtherLandingsIgnored);
|
||||
r.Add("dfheight rotation: the settings ride the Settings bridge; a sender without them leaves them alone", SettingsBridge);
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly CombatManager C;
|
||||
|
||||
public Rig(Action<LegacyUiSettings> set, int dfTraining = 2)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.AttackSendCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Melee;
|
||||
Place(Player, "Me", 96, 96, creature: false);
|
||||
Place(Mob, "Drudge Skulker", 96, 99);
|
||||
Place(Other, "Drudge Slinker", 110, 110);
|
||||
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
FakeHost.HeadingDeg = 0;
|
||||
FakeHost.Skills[(Player, DfSkill)] = (300, dfTraining);
|
||||
FakeHost.Skills[(Player, HeavySkill)] = (300, 3);
|
||||
S = new LegacyUiSettings { MonsterRange = 50, IsMacroRunning = true, EnableCombat = true, MeleeAttackHeight = 1 };
|
||||
set(S);
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = FakeHost.MakeCache(host, Player, new[] { Mob, Other });
|
||||
C = new CombatManager(host, S, cache);
|
||||
C.SetPlayerId(Player);
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
C.SetCharacterSkills(skills);
|
||||
C.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
|
||||
C.ScanNearbyTargets();
|
||||
C.HandleCombatTrigger();
|
||||
FakeHost.AttackCalls.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Thinks until an attack reaches the server; its height (-1 if none in 30 ticks).</summary>
|
||||
public int NextHeight()
|
||||
{
|
||||
int before = FakeHost.AttackCalls.Count;
|
||||
for (int i = 0; i < 30 && FakeHost.AttackCalls.Count == before; i++)
|
||||
{
|
||||
LastAttackCmd.SetValue(C, DateTime.MinValue);
|
||||
C.Think();
|
||||
}
|
||||
return FakeHost.AttackCalls.Count > before ? FakeHost.AttackCalls[^1].Height : -1;
|
||||
}
|
||||
|
||||
private static readonly FieldInfo LastAttackCmd = typeof(CombatManager).GetField("lastAttackCmd", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
}
|
||||
|
||||
private static void Place(uint id, string name, float x, float y, bool creature = true)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f);
|
||||
if (creature) FakeHost.ItemTypes[id] = 0x10;
|
||||
}
|
||||
|
||||
private static string Landing(string spell, string target = "Drudge Skulker", string who = "Me") =>
|
||||
$"Dirty Fighting! {who} delivers a {spell} to {target}!";
|
||||
|
||||
private static void RotationFollowsLandings()
|
||||
{
|
||||
var rig = new Rig(s => { s.DfHeightRotation = true; s.DfDefaultHeight = 0; }); // then Low
|
||||
Check.Eq(rig.NextHeight(), AcHigh, "a fresh target: High first");
|
||||
Check.Eq(rig.NextHeight(), AcHigh, "nothing landed yet: High again");
|
||||
rig.C.NoteDirtyFightingChat(Landing("Blinding Blow"));
|
||||
rig.C.NoteDirtyFightingChat(Landing("Traumatic Blow"));
|
||||
Check.Eq(rig.NextHeight(), AcMedium, "High's effects landed: Medium for the bleed");
|
||||
rig.C.NoteDirtyFightingChat(Landing("Bleeding Blow"));
|
||||
Check.Eq(rig.NextHeight(), AcLow, "bleeding: Low next");
|
||||
rig.C.NoteDirtyFightingChat(Landing("Unbalancing Blow"));
|
||||
Check.Eq(rig.NextHeight(), AcLow, "all three on: the default (Low)");
|
||||
|
||||
var toFixed = new Rig(s => { s.DfHeightRotation = true; s.DfDefaultHeight = -1; s.MeleeAttackHeight = 2; s.DfHeightOrder = "LMH"; });
|
||||
Check.Eq(toFixed.NextHeight(), AcLow, "order LMH: Low first");
|
||||
toFixed.C.NoteDirtyFightingChat(Landing("Unbalancing Assault"));
|
||||
toFixed.C.NoteDirtyFightingChat(Landing("Bleeding Assault"));
|
||||
toFixed.C.NoteDirtyFightingChat(Landing("Blinding Assault"));
|
||||
Check.Eq(toFixed.NextHeight(), AcHigh, "all on, default = the Melee Attack Height (High)");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[DFHeight]") && l.Contains("landed on")), "landings are logged");
|
||||
|
||||
string status = toFixed.C.DirtyFightingStatus();
|
||||
Check.True(status.Contains("Target 'Drudge Skulker'") && status.Contains("Low 20 s"), "status shows the target's effects: " + status);
|
||||
Check.True(status.Contains("about 25% per hit"), "status shows the chance: " + status);
|
||||
}
|
||||
|
||||
private static void FixedWhenOffOrUntrained()
|
||||
{
|
||||
var off = new Rig(s => { s.DfHeightRotation = false; s.MeleeAttackHeight = 0; });
|
||||
Check.Eq(off.NextHeight(), AcLow, "rotation off: the fixed height (Low)");
|
||||
off.C.NoteDirtyFightingChat(Landing("Unbalancing Blow"));
|
||||
Check.Eq(off.NextHeight(), AcLow, "rotation off: landings change nothing");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("attacking")), "rotation off: no height choice logged");
|
||||
|
||||
var untrained = new Rig(s => { s.DfHeightRotation = true; s.MeleeAttackHeight = 1; }, dfTraining: 1);
|
||||
Check.Eq(untrained.NextHeight(), AcMedium, "Dirty Fighting untrained: the fixed height (Medium)");
|
||||
Check.True(untrained.C.DirtyFightingStatus().Contains("not trained"), "status says it isn't trained");
|
||||
}
|
||||
|
||||
private static void OtherLandingsIgnored()
|
||||
{
|
||||
var rig = new Rig(s => { s.DfHeightRotation = true; s.DfDefaultHeight = 0; });
|
||||
Check.Eq(rig.NextHeight(), AcHigh, "High first");
|
||||
rig.C.NoteDirtyFightingChat(Landing("Blinding Blow", target: "Drudge Slinker"));
|
||||
Check.Eq(rig.NextHeight(), AcHigh, "a landing on a monster not being fought: still High");
|
||||
rig.C.NoteDirtyFightingChat(Landing("Blinding Blow", who: "Someone Else"));
|
||||
Check.Eq(rig.NextHeight(), AcHigh, "another attacker's landing: still High");
|
||||
rig.C.NoteDirtyFightingChat(Landing("Blinding Blow", target: "Me", who: "Drudge Skulker"));
|
||||
Check.Eq(rig.NextHeight(), AcHigh, "the monster's landing on this character: still High");
|
||||
rig.C.NoteDirtyFightingChat("Someone says, \"" + Landing("Blinding Blow") + "\"");
|
||||
Check.Eq(rig.NextHeight(), AcHigh, "the words said in chat: still High");
|
||||
}
|
||||
|
||||
/// <summary>A dashboard stand-in with its profile in memory (as SkCombatAddonTests builds one).</summary>
|
||||
private static LegacyDashboardRenderer Dash(LegacyUiSettings s)
|
||||
{
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(dash, true);
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)!
|
||||
.SetValue(dash, new LegacyAdvancedSettingsUi(s));
|
||||
return dash;
|
||||
}
|
||||
|
||||
private static void SettingsBridge()
|
||||
{
|
||||
var s = new LegacyUiSettings { DfHeightRotation = true, DfHeightOrder = "MLH", DfDefaultHeight = 2 };
|
||||
var dash = Dash(s);
|
||||
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!;
|
||||
Check.True(sent.DfHeightRotation == true && sent.DfHeightOrder == "MLH" && sent.DfDefaultHeight == 2,
|
||||
"the bridge carries the three settings");
|
||||
|
||||
dash.ApplySettingsJson("{\"HealAt\":50}");
|
||||
Check.True(s.DfHeightRotation, "a sender without them: rotation kept");
|
||||
Check.Eq(s.DfHeightOrder, "MLH", "order kept");
|
||||
Check.Eq(s.DfDefaultHeight, 2, "default kept");
|
||||
|
||||
dash.ApplySettingsJson("{\"DfHeightRotation\":false,\"DfHeightOrder\":\"bad\",\"DfDefaultHeight\":9}");
|
||||
Check.False(s.DfHeightRotation, "rotation set off");
|
||||
Check.Eq(s.DfHeightOrder, "HML", "a bad order normalizes to HML");
|
||||
Check.Eq(s.DfDefaultHeight, 2, "an out-of-range default is clamped");
|
||||
|
||||
var fresh = new LegacyUiSettings();
|
||||
Check.False(fresh.DfHeightRotation, "off by default");
|
||||
Check.Eq(fresh.DfHeightOrder, "HML", "High, Medium, Low by default");
|
||||
Check.Eq(fresh.DfDefaultHeight, -1, "default height = the Attack Height setting");
|
||||
}
|
||||
}
|
||||
|
|
@ -44,6 +44,12 @@ internal static class HandSwapTests
|
|||
r.Add("a monster with the wand in hand: peace, the Sceptre out, both Hand Wraps on, then Melee (no client use)", FightFromWand);
|
||||
r.Add("a monster with the wand in hand, burst: the Sceptre out and both Hand Wraps on in one tick", FightFromWandBurst);
|
||||
r.Add("a monster with the wand in hand: a fight swap that fails leaves that weapon to the client's own swap", FightSwapFallsBack);
|
||||
r.Add("wand to wand (hunt report 11-07): the next monster's caster goes in through peace, then Magic (no client use, no bare-hands stance)", WandToWandFromMagic);
|
||||
r.Add("wand to wand from peace (Peace Mode When Idle between targets): the old caster out, the new one in, then Magic; no peace request", WandToWandFromPeace);
|
||||
r.Add("wand to wand: the swap tracker records the swap (no swap straight back for the same fight)", WandToWandTracked);
|
||||
r.Add("WandSwapRules.UseHandsSwap: a swap away from a caster goes through peace, a caster wanted too", UseHandsSwapRules);
|
||||
r.Add("WandSwapRules.EquipCastHoldMs: the first cast waits for the stance after a wield, never past the old 3 s", EquipCastHoldRules);
|
||||
r.Add("equip gate: held while the stance settles, then the cast goes; one log line per wield", EquipGateHolds);
|
||||
r.Add("weapons back burst: peace, the Sceptre out and both Hand Wraps on in one tick, then Melee", RearmBurst);
|
||||
r.Add("weapons back burst: the quiet check reads BuffManager's mode change, not combat's late one (Drakkon 23:06-23:21)", RearmBurstQuietFromBuff);
|
||||
r.Add("Fast Weapon Swap: on by default, an old saved off (the opt-in name) loads on, an untick since stays off", OnByDefault);
|
||||
|
|
@ -522,7 +528,7 @@ internal static class HandSwapTests
|
|||
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!;
|
||||
public double SimMs;
|
||||
|
||||
public CombatRig(bool putCalls = false)
|
||||
public CombatRig(bool putCalls = false, bool secondWand = false)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.PutCalls = putCalls;
|
||||
|
|
@ -531,7 +537,7 @@ internal static class HandSwapTests
|
|||
FakeHost.EquippedCalls = true;
|
||||
FakeHost.CombatModeCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
foreach (var (id, name, type, slots) in new[] { (Acid, "Acid Hand Wraps", 0x1u, Melee), (Frost, "Frost Hand Wraps", 0x1u, Melee), (Sceptre, "Sceptre", 0x8000u, Held) })
|
||||
foreach (var (id, name, type, slots) in new[] { (Acid, "Acid Hand Wraps", 0x1u, Melee), (Frost, "Frost Hand Wraps", 0x1u, Melee), (Sceptre, "Sceptre", 0x8000u, Held), (OtherWand, "Fire Wand", 0x8000u, Held) })
|
||||
{
|
||||
FakeHost.Names[id] = name; FakeHost.ItemTypes[id] = type; FakeHost.Ints[(id, 9)] = slots;
|
||||
}
|
||||
|
|
@ -543,7 +549,8 @@ internal static class HandSwapTests
|
|||
new() { Id = I(Frost), Name = "Frost Hand Wraps", Element = "", ElementSource = "", Action = "Weapon" },
|
||||
new() { Id = I(Sceptre), Name = "Sceptre", Element = "", ElementSource = "", Action = "Weapon" },
|
||||
};
|
||||
var cache = FakeHost.MakeCache(host, Player, new[] { Acid, Frost, Sceptre });
|
||||
if (secondWand) S.ItemRules.Add(new() { Id = I(OtherWand), Name = "Fire Wand", Element = "Fire", ElementSource = "", Action = "Weapon" });
|
||||
var cache = FakeHost.MakeCache(host, Player, secondWand ? new[] { Acid, Frost, Sceptre, OtherWand } : new[] { Acid, Frost, Sceptre });
|
||||
C = new CombatManager(host, S, cache);
|
||||
C.SetPlayerId(Player);
|
||||
C.OpenPackOverride = () => I(Player);
|
||||
|
|
@ -683,6 +690,139 @@ internal static class HandSwapTests
|
|||
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
|
||||
}
|
||||
|
||||
// ── Caster to caster (2026-11-11, WandSwapRules) ──────────────────────────
|
||||
|
||||
/// <summary>A wand fight: the Sceptre in hand, the Default rule's weapon the Fire Wand, war magic usable.</summary>
|
||||
private static CombatRig WandFightRig(bool fromPeace)
|
||||
{
|
||||
var rig = new CombatRig(secondWand: true);
|
||||
rig.C.CanCastOverride = _ => true;
|
||||
rig.S.MonsterRules = new List<MonsterRule> { new() { Name = "Default", WeaponId = I(OtherWand) } };
|
||||
rig.C.LastVitalCastAt = () => DateTime.MinValue; // no weapons back pending
|
||||
rig.C.SwapBurstEnabled = () => false;
|
||||
if (fromPeace) FakeHost.CombatModeValue = CombatMode.NonCombat;
|
||||
rig.Fighting();
|
||||
return rig;
|
||||
}
|
||||
|
||||
private static string Trail() => string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("[EquipDiag]")).TakeLast(20));
|
||||
|
||||
private static void WandToWandFromMagic()
|
||||
{
|
||||
try
|
||||
{
|
||||
var rig = WandFightRig(fromPeace: false);
|
||||
double ready = rig.Fight(3000);
|
||||
Check.True(ready > 0, "ready to cast within 3 s: " + Trail());
|
||||
Check.False(FakeHost.Uses.Any(), "no use (the client's own use of a caster in Magic plays a forced change to bare hands): "
|
||||
+ string.Join(",", FakeHost.Uses.Select(u => $"{u:X8}")));
|
||||
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1,8", "peace, then Magic; nothing else");
|
||||
Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0].Id == Sceptre, "the Sceptre into the pack");
|
||||
Check.True(FakeHost.Wields.Count == 1 && FakeHost.Wields[0] == (OtherWand, (uint)Held),
|
||||
"the Fire Wand into the Held slot: " + string.Join(", ", FakeHost.Wields.Select(w => $"{w.Id:X8}@{w.Mask:X}")));
|
||||
Check.True(rig.Logged("weapons for the fight in hand"), "the swap's time and steps are logged: " + Trail());
|
||||
Check.True(rig.Logged("weapons for the fight: Magic mode"), "the Magic request is logged: " + Trail());
|
||||
Check.Eq(FakeHost.CombatModeValue, CombatMode.Magic, "in Magic mode");
|
||||
Check.True(ready <= 1000, $"ready {ready:0} ms in (one peace leg and one Magic leg)");
|
||||
Console.WriteLine($" (simulated: caster to caster, ready to cast {ready:0} ms in)");
|
||||
Check.Eq(rig.Gate.HeldBy, "", "the gate is free");
|
||||
}
|
||||
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
|
||||
}
|
||||
|
||||
private static void WandToWandFromPeace()
|
||||
{
|
||||
try
|
||||
{
|
||||
var rig = WandFightRig(fromPeace: true);
|
||||
double ready = rig.Fight(3000);
|
||||
Check.True(ready > 0, "ready to cast within 3 s: " + Trail());
|
||||
Check.False(FakeHost.Uses.Any(), "no use");
|
||||
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", "Magic once the Fire Wand is in (no Magic beside the use, no peace)");
|
||||
Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0].Id == Sceptre, "the Sceptre into the pack (answered at once in peace)");
|
||||
Check.True(FakeHost.Wields.Count == 1 && FakeHost.Wields[0] == (OtherWand, (uint)Held), "the Fire Wand into the Held slot");
|
||||
Check.True(ready <= 900, $"ready {ready:0} ms in");
|
||||
Check.Eq(rig.Gate.HeldBy, "", "the gate is free");
|
||||
}
|
||||
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
|
||||
}
|
||||
|
||||
private static void WandToWandTracked()
|
||||
{
|
||||
try
|
||||
{
|
||||
var rig = WandFightRig(fromPeace: false);
|
||||
Check.True(rig.Fight(3000) > 0, "the swap finished: " + Trail());
|
||||
var step = rig.C.SwapTracker.Next(I(Sceptre), I(OtherWand), RynthClock.Now, forKey: rig.Target.Id);
|
||||
Check.Eq(step, WeaponSwapTracker.Step.Hold, "the Sceptre straight back for the same fight: held");
|
||||
Check.Eq(rig.C.SwapTracker.HoldReason, "just swapped away from it", "as for the client's own use");
|
||||
}
|
||||
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
|
||||
}
|
||||
|
||||
private static void UseHandsSwapRules()
|
||||
{
|
||||
const int MagicKind = CombatMode.Magic, MeleeKind = CombatMode.Melee;
|
||||
Check.True(WandSwapRules.UseHandsSwap(true, true, 1, 2, MagicKind), "a caster in hand, another weapon wanted (a caster or not): through peace");
|
||||
Check.False(WandSwapRules.UseHandsSwap(false, true, 1, 2, MagicKind), "Fast Weapon Swap off: the old route");
|
||||
Check.False(WandSwapRules.UseHandsSwap(true, false, 1, 2, MagicKind), "the swap tracker held it: no swap");
|
||||
Check.False(WandSwapRules.UseHandsSwap(true, true, 1, 1, MagicKind), "the wanted caster is in hand: no swap");
|
||||
Check.False(WandSwapRules.UseHandsSwap(true, true, 0, 2, 0), "nothing in hand: combat's own wield");
|
||||
Check.False(WandSwapRules.UseHandsSwap(true, true, 1, 2, MeleeKind), "a melee weapon in hand: combat's own swap, as before");
|
||||
Check.False(WandSwapRules.UseHandsSwap(true, true, 1, 0, MagicKind), "nothing chosen");
|
||||
}
|
||||
|
||||
private static void EquipCastHoldRules()
|
||||
{
|
||||
static double H(double equip, double change, double request) => WandSwapRules.EquipCastHoldMs(equip, change, request);
|
||||
Check.Eq(H(-1, -1, -1), 0.0, "no wield seen: no wait");
|
||||
Check.Eq(H(3000, -1, -1), 0.0, "the old 3 s are up: no wait");
|
||||
Check.Eq(H(500, 4000, -1), 2500.0, "no stance change seen since the wield: the old wait (the client may not have caught up)");
|
||||
Check.Eq(H(500, -1, -1), 2500.0, "never a stance change seen: the old wait");
|
||||
Check.Eq(H(800, 100, -1), 200.0, "the server's own change to Magic 100 ms ago: 300 ms after it");
|
||||
Check.Eq(H(800, 400, -1), 200.0, "Magic read for 400 ms, the wield 800 ms ago: 1 s after the wield");
|
||||
Check.Eq(H(1100, 400, -1), 0.0, "1.1 s after the wield, Magic read for 400 ms: cast now");
|
||||
Check.Eq(H(800, 400, 600), 400.0, "our own Magic request 600 ms ago: 1 s after it");
|
||||
Check.Eq(H(1200, 400, 1100), 0.0, "request 1.1 s ago, Magic read for 400 ms: cast now");
|
||||
Check.Eq(H(800, 400, 900), 200.0, "a stance request from before the wield doesn't count: 1 s after the wield");
|
||||
Check.Eq(H(2900, 50, 60), 100.0, "never past the old 3 s");
|
||||
}
|
||||
|
||||
private static void EquipGateHolds()
|
||||
{
|
||||
try
|
||||
{
|
||||
var rig = WandFightRig(fromPeace: false);
|
||||
const System.Reflection.BindingFlags NP = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
||||
var holds = typeof(CombatManager).GetMethod("EquipCastHoldsNow", NP)!;
|
||||
void Set(string field, DateTime v) => typeof(CombatManager).GetField(field, NP)!.SetValue(rig.C, v);
|
||||
bool Held() => (bool)typeof(CombatManager).GetField("_equipGateHeld", NP)!.GetValue(rig.C)!;
|
||||
bool Holds() => (bool)holds.Invoke(rig.C, null)!;
|
||||
int Lines() => FakeHost.Logs.Count(l => l.Contains("[CombatCast] equip-gate"));
|
||||
DateTime now = RynthClock.Now;
|
||||
Set("_lastEquipTime", now.AddMilliseconds(-700));
|
||||
Set("_cmModeChangedAt", now.AddMilliseconds(-100)); // the client read Magic 100 ms ago
|
||||
Set("lastStanceAttempt", now.AddMilliseconds(-600)); // our Magic request 600 ms ago
|
||||
Check.True(Holds(), "held: the stance is still settling");
|
||||
Check.True(Held(), "the tick is marked held (not an attack)");
|
||||
Holds();
|
||||
Check.Eq(Lines(), 1, "one line per wield");
|
||||
|
||||
Set("_lastEquipTime", now.AddMilliseconds(-1500));
|
||||
Set("_cmModeChangedAt", now.AddMilliseconds(-400));
|
||||
Set("lastStanceAttempt", now.AddMilliseconds(-1200));
|
||||
Check.False(Holds(), "Magic read for 400 ms, 1.2 s after the request: the cast goes (the old gate: 1.5 s more)");
|
||||
|
||||
Set("_cmModeChangedAt", now.AddSeconds(-20)); // combat's own read is old...
|
||||
rig.C.LastModeChangeAt = () => now.AddMilliseconds(-400); // ...BuffManager's every-heartbeat read is fresh
|
||||
Check.False(Holds(), "the freshest mode-change read counts");
|
||||
rig.C.LastModeChangeAt = null;
|
||||
Check.True(Holds(), "no change seen since the wield: the old 3 s");
|
||||
Check.Eq(Lines(), 2, "a new wield, a new line");
|
||||
}
|
||||
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
|
||||
}
|
||||
|
||||
private static void RearmThroughPeace()
|
||||
{
|
||||
try
|
||||
|
|
|
|||
161
Tools/RynthCore.RynthAiHostTests/Tests/HuntOnLoginTests.cs
Normal file
161
Tools/RynthCore.RynthAiHostTests/Tests/HuntOnLoginTests.cs
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
using System;
|
||||
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;
|
||||
|
||||
// Hunt On Login (2026-11-11): the Outdoor Hunt starts once the character is in the world, as Patrol On
|
||||
// Login starts the Dungeon Patrol. One or the other; the same checks as the Hunt button.
|
||||
internal static class HuntOnLoginTests
|
||||
{
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("hunt on login: Patrol On Login and Hunt On Login are one choice; both on: the one that fits the place", Choice);
|
||||
r.Add("hunt on login: the start checks run in order, each only once the ones before passed; chat says why", StartChecks);
|
||||
r.Add("hunt on login: no position or no RynthNav at login: it doesn't start, says why (Hunt On Login), the macro stays off", LoginRefused);
|
||||
r.Add("hunt on login: /ra hunt login answers, sets it, clears Patrol On Login, and says why not with the usage", Command);
|
||||
r.Add("hunt on login: HuntOnLogin round-trips (saved, copied, engine payload); the engine ticking Patrol On Login clears it", Setting);
|
||||
}
|
||||
|
||||
private static void Choice()
|
||||
{
|
||||
Check.Eq(LoginAutoStart.Choose(false, false, false), LoginAutoStart.Start.None, "neither: nothing");
|
||||
Check.Eq(LoginAutoStart.Choose(true, false, false), LoginAutoStart.Start.Patrol, "patrol only: the patrol (it says why itself outdoors)");
|
||||
Check.Eq(LoginAutoStart.Choose(false, true, true), LoginAutoStart.Start.Hunt, "hunt only: the hunt (it says why itself in a dungeon)");
|
||||
Check.Eq(LoginAutoStart.Choose(true, true, true), LoginAutoStart.Start.Patrol, "both, in a dungeon: the patrol");
|
||||
Check.Eq(LoginAutoStart.Choose(true, true, false), LoginAutoStart.Start.Hunt, "both, outdoors: the hunt");
|
||||
|
||||
Check.Eq(LoginAutoStart.Exclusive(false, false, false, true), (false, true), "hunt ticked");
|
||||
Check.Eq(LoginAutoStart.Exclusive(true, false, true, true), (false, true), "hunt ticked clears patrol");
|
||||
Check.Eq(LoginAutoStart.Exclusive(false, true, true, true), (true, false), "patrol ticked clears hunt");
|
||||
Check.Eq(LoginAutoStart.Exclusive(true, false, false, false), (false, false), "patrol unticked: hunt stays off");
|
||||
Check.Eq(LoginAutoStart.Exclusive(true, true, true, false), (true, false), "hunt unticked: patrol stays as it was");
|
||||
Check.Eq(LoginAutoStart.Exclusive(false, false, true, true), (true, false), "both ticked in one change: the patrol");
|
||||
Check.Eq(LoginAutoStart.Exclusive(true, true, true, true), (true, true), "nothing changed: left as it is");
|
||||
}
|
||||
|
||||
private static void StartChecks()
|
||||
{
|
||||
int asked = 0;
|
||||
Func<bool> Yes() => () => { asked++; return true; };
|
||||
Func<bool> No() => () => { asked++; return false; };
|
||||
Check.Eq(OutdoorHunt.WhyNoStart(false, true, Yes(), Yes(), Yes()), OutdoorHunt.StartBlock.NoSettings, "no settings first");
|
||||
Check.Eq(OutdoorHunt.WhyNoStart(true, false, Yes(), Yes(), Yes()), OutdoorHunt.StartBlock.NoPosition, "then a position");
|
||||
Check.Eq(asked, 0, "nothing else asked before those pass");
|
||||
Check.Eq(OutdoorHunt.WhyNoStart(true, true, Yes(), Yes(), Yes()), OutdoorHunt.StartBlock.InDungeon, "then the dungeon");
|
||||
Check.Eq(asked, 1, "only the dungeon asked");
|
||||
asked = 0;
|
||||
Check.Eq(OutdoorHunt.WhyNoStart(true, true, No(), Yes(), Yes()), OutdoorHunt.StartBlock.UnknownBuilding, "then the building");
|
||||
Check.Eq(asked, 2, "RynthNav not asked");
|
||||
Check.Eq(OutdoorHunt.WhyNoStart(true, true, No(), No(), Yes()), OutdoorHunt.StartBlock.NoRynthNav, "then RynthNav");
|
||||
Check.Eq(OutdoorHunt.WhyNoStart(true, true, No(), No(), No()), OutdoorHunt.StartBlock.None, "all passed: it can start");
|
||||
foreach (OutdoorHunt.StartBlock b in Enum.GetValues(typeof(OutdoorHunt.StartBlock)))
|
||||
Check.True(b == OutdoorHunt.StartBlock.None ? OutdoorHunt.StartBlockText(b).Length == 0 : OutdoorHunt.StartBlockText(b).Length > 10,
|
||||
$"{b}: a reason in words");
|
||||
Check.True(OutdoorHunt.StartBlockText(OutdoorHunt.StartBlock.NoRynthNav).Contains("RynthNav"), "no RynthNav says so");
|
||||
}
|
||||
|
||||
private static (RynthAiPlugin P, LegacyDashboardRenderer Dash, Action<string> Ra, Func<string> All) Rig()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var host = FakeHost.Create();
|
||||
var p = new RynthAiPlugin();
|
||||
typeof(RynthCore.PluginCore.RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
|
||||
var dash = new LegacyDashboardRenderer(host);
|
||||
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(p, dash);
|
||||
var chat = FakeHost.Chat;
|
||||
void Ra(string line)
|
||||
{
|
||||
chat.Clear();
|
||||
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(p, new object[] { parts[1].ToLowerInvariant(), parts, 0 });
|
||||
}
|
||||
return (p, dash, Ra, () => string.Join(" | ", chat));
|
||||
}
|
||||
|
||||
private static void LoginRefused()
|
||||
{
|
||||
var (p, dash, _, All) = Rig();
|
||||
var start = typeof(RynthAiPlugin).GetMethod("StartHunt", Any)!;
|
||||
FakeHost.HasPose = false;
|
||||
FakeHost.Chat.Clear();
|
||||
start.Invoke(p, new object[] { true });
|
||||
Check.False(p.HuntActive, "no position: not started");
|
||||
Check.True(All().Contains(RynthAiPlugin.HuntOnLoginRefusedPrefix.Trim()) && All().Contains("no position yet"), "says Hunt On Login and why: " + All());
|
||||
|
||||
// Outdoors, with a position, but no RynthNav on this host: the Hunt button's own check refuses it.
|
||||
FakeHost.HasPose = true;
|
||||
FakeHost.PlayerPose = (0xA9B40021u, 100f, 100f, 50f);
|
||||
FakeHost.Chat.Clear();
|
||||
start.Invoke(p, new object[] { true });
|
||||
Check.False(p.HuntActive, "no RynthNav: not started");
|
||||
Check.False(dash.Settings.IsMacroRunning, "and the macro isn't turned on");
|
||||
Check.True(All().Contains("Hunt On Login") && All().Contains("needs RynthNav"), "says why: " + All());
|
||||
|
||||
// The Hunt button's own wording is unchanged.
|
||||
FakeHost.Chat.Clear();
|
||||
start.Invoke(p, new object[] { false });
|
||||
Check.True(All().StartsWith("[RynthAi] Outdoor hunt needs RynthNav") && !All().Contains("Hunt On Login"), "the button says it as before: " + All());
|
||||
}
|
||||
|
||||
private static void Command()
|
||||
{
|
||||
var (_, dash, Ra, All) = Rig();
|
||||
var s = dash.Settings;
|
||||
Ra("/ra hunt login");
|
||||
Check.True(All().Contains("Hunt On Login: off") && All().Contains(RynthAiPlugin.HuntLoginUsage), "no word: off, and the usage: " + All());
|
||||
s.PatrolOnLogin = true;
|
||||
Ra("/ra hunt login on");
|
||||
Check.True(s.HuntOnLogin && !s.PatrolOnLogin, "on, and Patrol On Login off");
|
||||
Check.True(All().Contains("Hunt On Login set: on") && All().Contains("Patrol On Login is off now"), "and says both: " + All());
|
||||
Ra("/ra hunt login on");
|
||||
Check.False(All().Contains("Patrol On Login is off now"), "patrol was already off: not said again: " + All());
|
||||
Ra("/ra hunt login maybe");
|
||||
Check.True(s.HuntOnLogin, "an unknown word changes nothing");
|
||||
Check.True(All().Contains("isn't on or off") && All().Contains("on now") && All().Contains("Usage: " + RynthAiPlugin.HuntLoginUsage),
|
||||
"why, what it is, the usage: " + All());
|
||||
Ra("/ra hunt login off");
|
||||
Check.True(!s.HuntOnLogin && !s.PatrolOnLogin, "off; patrol stays off");
|
||||
Check.True(All().Contains("Hunt On Login set: off"), "and says so: " + All());
|
||||
Ra("/ra hunt nonsense");
|
||||
Check.True(All().Contains(RynthAiPlugin.HuntLoginUsage), "the hunt's usage lists it: " + All());
|
||||
}
|
||||
|
||||
private static void Setting()
|
||||
{
|
||||
Check.False(new LegacyUiSettings().HuntOnLogin, "off by default");
|
||||
var ctx = RynthAiJsonContext.Default.LegacyUiSettings;
|
||||
var saved = JsonSerializer.Deserialize(JsonSerializer.Serialize(new LegacyUiSettings { HuntOnLogin = true }, ctx), ctx)!;
|
||||
Check.True(saved.HuntOnLogin, "saved");
|
||||
var live = new LegacyUiSettings();
|
||||
typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)!
|
||||
.Invoke(null, new object[] { saved, live });
|
||||
Check.True(live.HuntOnLogin, "copied");
|
||||
var old = JsonSerializer.Deserialize("{\"PatrolOnLogin\":true}", ctx)!;
|
||||
Check.True(old.PatrolOnLogin && !old.HuntOnLogin, "a profile from before the setting: off, its patrol kept");
|
||||
|
||||
var s = new LegacyUiSettings { HuntOnLogin = true };
|
||||
var dash = (LegacyDashboardRenderer)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", F)!.SetValue(dash, true);
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", F)!.SetValue(dash, s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", F)!.SetValue(dash, new LegacyAdvancedSettingsUi(s));
|
||||
string json = dash.BuildSettingsJson();
|
||||
using (var doc = JsonDocument.Parse(json))
|
||||
Check.True(doc.RootElement.TryGetProperty("HuntOnLogin", out var he) && he.GetBoolean(), "sent to the engine as \"HuntOnLogin\"");
|
||||
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
|
||||
Check.True(s.HuntOnLogin && !s.PatrolOnLogin, "an engine without it leaves it alone");
|
||||
dash.ApplySettingsJson("{\"PatrolOnLogin\":true}");
|
||||
Check.True(s.PatrolOnLogin && !s.HuntOnLogin, "the engine ticking Patrol On Login clears Hunt On Login");
|
||||
dash.ApplySettingsJson("{\"HuntOnLogin\":true}");
|
||||
Check.True(s.HuntOnLogin && !s.PatrolOnLogin, "HuntOnLogin sent: on, and Patrol On Login off");
|
||||
dash.ApplySettingsJson("{\"HuntOnLogin\":false}");
|
||||
Check.True(!s.HuntOnLogin && !s.PatrolOnLogin, "and off");
|
||||
}
|
||||
}
|
||||
301
Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoPartColorTests.cs
Normal file
301
Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoPartColorTests.cs
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-11-11, a player asked for the one-line item info with each part (name, set, damage,
|
||||
// spells, value ...) in its own colour. "Colour each part" sends the parts' ranges just before the
|
||||
// line (SendPluginCommand "RynthCore.Chat" nextspans, engine UI/Data/ChatOwnColors.cs), after the
|
||||
// whole-line Info text colour, so an engine without runs still shows the line in that colour.
|
||||
internal static class ItemInfoPartColorTests
|
||||
{
|
||||
private const uint Player = 0x50000E52;
|
||||
private const uint Sword = 0x80266101;
|
||||
private const uint ItemTypeMelee = 0x1;
|
||||
private const string Target = "RynthCore.Chat";
|
||||
private const string Prefix = "[RynthAi Item] ";
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("item info parts: off by default, nothing asked, the line as before", DefaultOff);
|
||||
r.Add("item info parts: on, one-line: the ranges asked for just before the line", OneLine);
|
||||
r.Add("item info parts: with Info text colour, the colour first and then the ranges", WithTextColor);
|
||||
r.Add("item info parts: the pet-style layout is left alone", PetLayout);
|
||||
r.Add("item info parts: an engine without runs is asked once; the line keeps one colour", OlderEngine);
|
||||
r.Add("item info parts: a refused payload is logged, not taken for an older engine", RefusedPayload);
|
||||
r.Add("item info parts: the Test button", TestButton);
|
||||
r.Add("item info parts: saved with the profile, reset, the settings map, /ra iteminfo parts", Settings);
|
||||
}
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new();
|
||||
|
||||
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("_profileLoaded", Any)!.SetValue(dash, true);
|
||||
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(Sword);
|
||||
cache.OnCreateObject(Player);
|
||||
cache.Tick();
|
||||
S.ItemInfoSettings.Layout = MagItemInfoSettings.LayoutOneLine;
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public void Call(string method, params object[] args) => typeof(RynthAiPlugin).GetMethod(method, Any, null,
|
||||
args.Select(a => a.GetType()).ToArray(), null)!.Invoke(P, args);
|
||||
public void Print() => Call("PrintItemInfo", unchecked((int)Sword), true);
|
||||
public void Cmd(params string[] words) => Call("HandleItemInfoCommand", new object[] { new[] { "ra", "iteminfo" }.Concat(words).ToArray() });
|
||||
}
|
||||
|
||||
/// <summary>A gold long sword with a set, a spell, damage, workmanship, value and burden.</summary>
|
||||
private static Bot World(Func<string, string, string, bool>? answer = null)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.PluginCommandCalls = true;
|
||||
FakeHost.PluginCommandAnswer = answer;
|
||||
FakeHost.Names[Player] = "Colour Tester";
|
||||
FakeHost.Names[Sword] = "Long Sword";
|
||||
FakeHost.ItemTypes[Sword] = ItemTypeMelee;
|
||||
FakeHost.Containers[Sword] = Player;
|
||||
foreach (var (k, v) in new (uint, int)[] { (1, (int)ItemTypeMelee), (19, 9000), (5, 300), (131, 60), (105, 6), (353, 2), (45, 1), (44, 236), (265, 13) })
|
||||
FakeHost.Ints[(Sword, k)] = v;
|
||||
FakeHost.SpellIds[Sword] = new[] { (uint)SpellDatabase.GetIdByName("Legendary Blood Thirst") };
|
||||
FakeHost.Appraised.Add(Sword);
|
||||
var bot = new Bot(FakeHost.Create(Player));
|
||||
bot.S.ItemInfoSettings.ShowValueAndBurden = true;
|
||||
return bot;
|
||||
}
|
||||
|
||||
private static List<int> ItemLines() =>
|
||||
Enumerable.Range(0, FakeHost.Chat.Count).Where(i => FakeHost.Chat[i].StartsWith(Prefix, StringComparison.Ordinal)).ToList();
|
||||
|
||||
private static List<int> Asks(string action) =>
|
||||
Enumerable.Range(0, FakeHost.PluginCommands.Count)
|
||||
.Where(i => FakeHost.PluginCommands[i].Plugin == Target && FakeHost.PluginCommands[i].Action == action).ToList();
|
||||
|
||||
private static string All() => string.Join(" | ", FakeHost.Chat) + " || " + string.Join(" | ", FakeHost.PluginCommands);
|
||||
|
||||
/// <summary>The payload's ranges as (text, colour) in <paramref name="line"/>; null if a range doesn't fit.</summary>
|
||||
private static List<(string Text, string Color)>? Read(string payload, string line)
|
||||
{
|
||||
var list = new List<(string, string)>();
|
||||
foreach (string run in payload.Split(';'))
|
||||
{
|
||||
string[] f = run.Split(':');
|
||||
if (f.Length != 3) return null;
|
||||
int start = int.Parse(f[0]), len = int.Parse(f[1]);
|
||||
if (start < 0 || len < 1 || start + len > line.Length) return null;
|
||||
list.Add((line.Substring(start, len), "#" + f[2]));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static void DefaultOff()
|
||||
{
|
||||
Check.False(new MagItemInfoSettings().PartColors, "off by default");
|
||||
Bot bot = World();
|
||||
bot.Print();
|
||||
Check.Eq(ItemLines().Count, 1, "one line: " + All());
|
||||
Check.Eq(FakeHost.PluginCommands.Count, 0, "nothing sent to the engine");
|
||||
}
|
||||
|
||||
private static void OneLine()
|
||||
{
|
||||
Bot bot = World();
|
||||
bot.Print();
|
||||
string plain = FakeHost.Chat[ItemLines().Single()];
|
||||
|
||||
bot = World();
|
||||
bot.S.ItemInfoSettings.PartColors = true;
|
||||
bot.Print();
|
||||
List<int> lines = ItemLines();
|
||||
Check.Eq(lines.Count, 1, "one line: " + All());
|
||||
string line = FakeHost.Chat[lines[0]];
|
||||
Check.Eq(line, plain, "the same text as without part colours");
|
||||
Check.Eq(FakeHost.ChatTypes[lines[0]], 1, "in its chat type");
|
||||
List<int> asks = Asks("nextspans");
|
||||
Check.Eq(asks.Count, 1, "the ranges asked for once: " + All());
|
||||
Check.Eq(Asks("nextcolor").Count, 0, "no Info text colour set: no nextcolor");
|
||||
if (asks.Count != 1) return;
|
||||
Check.Eq(FakeHost.PluginCommandChatCounts[asks[0]], lines[0], "just before the line");
|
||||
var runs = Read(FakeHost.PluginCommands[asks[0]].Value, line);
|
||||
Check.NotNull(runs, "every range inside the line: " + FakeHost.PluginCommands[asks[0]].Value);
|
||||
if (runs == null) return;
|
||||
Check.True(runs[0].Text.StartsWith("Gold Long Sword", StringComparison.Ordinal), "the first range is the name: " + runs[0].Text);
|
||||
Check.Eq(runs[0].Color, ItemInfoPartColors.ColorOf(ItemInfoPart.Name), "in the name's colour");
|
||||
Check.True(runs.Any(r => r.Text == "Legendary Blood Thirst" && r.Color == ItemInfoPartColors.ColorOf(ItemInfoPart.Spells)), "the spell in the spells' colour: " + string.Join(" | ", runs));
|
||||
Check.True(runs.Any(r => r.Text == "Craft 6" && r.Color == ItemInfoPartColors.ColorOf(ItemInfoPart.Craft)), "workmanship in its colour");
|
||||
Check.True(runs.Any(r => r.Text == "Value 9,000, BU 300" && r.Color == ItemInfoPartColors.ColorOf(ItemInfoPart.ValueBurden)), "value and burden, one range");
|
||||
Check.True(runs.Any(r => r.Color == ItemInfoPartColors.ColorOf(ItemInfoPart.Set)), "the set in its colour");
|
||||
Check.True(runs.All(r => !r.Text.StartsWith("[RynthAi", StringComparison.Ordinal)), "the prefix keeps the line's colour");
|
||||
}
|
||||
|
||||
private static void WithTextColor()
|
||||
{
|
||||
Bot bot = World();
|
||||
bot.S.ItemInfoSettings.PartColors = true;
|
||||
bot.S.ItemInfoSettings.TextColor = "#EE921E";
|
||||
bot.Print();
|
||||
int line = ItemLines().Single();
|
||||
List<int> colours = Asks("nextcolor"), spans = Asks("nextspans");
|
||||
Check.Eq(colours.Count, 1, "the whole-line colour once: " + All());
|
||||
Check.Eq(spans.Count, 1, "the ranges once");
|
||||
if (colours.Count == 1 && spans.Count == 1)
|
||||
{
|
||||
Check.True(colours[0] < spans[0], "the colour first (an engine without runs still uses it)");
|
||||
Check.Eq(FakeHost.PluginCommands[colours[0]].Value, "#EE921E", "the Info text colour");
|
||||
Check.Eq(FakeHost.PluginCommandChatCounts[spans[0]], line, "both just before the line");
|
||||
}
|
||||
}
|
||||
|
||||
private static void PetLayout()
|
||||
{
|
||||
Bot bot = World();
|
||||
bot.S.ItemInfoSettings.PartColors = true;
|
||||
bot.S.ItemInfoSettings.Layout = MagItemInfoSettings.LayoutPetLines;
|
||||
bot.Print();
|
||||
Check.True(ItemLines().Count >= 2, "pet-style lines: " + All());
|
||||
Check.Eq(Asks("nextspans").Count, 0, "no ranges for them");
|
||||
}
|
||||
|
||||
private static void OlderEngine()
|
||||
{
|
||||
// An engine from 2026-11-05..11-10: "nextcolor" yes, "nextspans" (and its "none") no.
|
||||
Bot bot = World((p, a, v) => p == Target && a == "nextcolor");
|
||||
bot.S.ItemInfoSettings.PartColors = true;
|
||||
bot.S.ItemInfoSettings.TextColor = "#EE921E";
|
||||
bot.Print();
|
||||
bot.Print();
|
||||
Check.Eq(ItemLines().Count, 2, "both lines written: " + All());
|
||||
Check.Eq(Asks("nextcolor").Count, 2, "each still in the Info text colour");
|
||||
List<int> spans = Asks("nextspans");
|
||||
Check.Eq(spans.Count, 2, "asked once, plus the \"none\" that tells why");
|
||||
if (spans.Count == 2) Check.Eq(FakeHost.PluginCommands[spans[1]].Value, "none", "the second ask is \"none\"");
|
||||
Check.True(Asks("nextcolor").All(i => FakeHost.PluginCommandChatCounts[i] == 0 || FakeHost.PluginCommandChatCounts[i] == ItemLines()[1]),
|
||||
"the colour asked for just before each line");
|
||||
|
||||
// An engine before 2026-11-05 (no "RynthCore.Chat" at all): nextcolor refused, no runs asked.
|
||||
bot = World((p, a, v) => false);
|
||||
bot.S.ItemInfoSettings.PartColors = true;
|
||||
bot.S.ItemInfoSettings.TextColor = "#EE921E";
|
||||
bot.Print();
|
||||
bot.Print();
|
||||
Check.Eq(ItemLines().Count, 2, "both lines written");
|
||||
Check.Eq(Asks("nextcolor").Count, 1, "the colour asked once");
|
||||
Check.Eq(Asks("nextspans").Count, 0, "no runs asked of an engine without line colours");
|
||||
|
||||
// Same, with no Info text colour: the ranges are asked once (and "none"), then never.
|
||||
bot = World((p, a, v) => false);
|
||||
bot.S.ItemInfoSettings.PartColors = true;
|
||||
bot.Print();
|
||||
bot.Print();
|
||||
Check.Eq(ItemLines().Count, 2, "both lines written (the chat type's colour)");
|
||||
Check.Eq(Asks("nextspans").Count, 2, "asked once, plus \"none\"");
|
||||
}
|
||||
|
||||
private static void RefusedPayload()
|
||||
{
|
||||
// The engine knows "nextspans" but refuses this payload: logged, still on for the next line.
|
||||
Bot bot = World((p, a, v) => a != "nextspans" || v == "none");
|
||||
bot.S.ItemInfoSettings.PartColors = true;
|
||||
bot.Print();
|
||||
bot.Print();
|
||||
Check.Eq(ItemLines().Count, 2, "both lines written: " + All());
|
||||
Check.Eq(Asks("nextspans").Count, 4, "each line asks (and \"none\"): not taken for an older engine");
|
||||
}
|
||||
|
||||
private static void TestButton()
|
||||
{
|
||||
Bot bot = World();
|
||||
bot.S.ItemInfoSettings.PartColors = true;
|
||||
bot.Call("TestItemInfoPartColors");
|
||||
string line = FakeHost.Chat.LastOrDefault() ?? "";
|
||||
Check.True(line.StartsWith(Prefix + "Name, Set, ", StringComparison.Ordinal), "a sample line naming the parts: " + line);
|
||||
Check.Eq(FakeHost.ChatTypes.LastOrDefault(), 1, "in the Item Info chat type");
|
||||
List<int> spans = Asks("nextspans");
|
||||
Check.Eq(spans.Count, 1, "with the ranges: " + All());
|
||||
if (spans.Count != 1) return;
|
||||
var runs = Read(FakeHost.PluginCommands[spans[0]].Value, line);
|
||||
Check.NotNull(runs, "inside the line");
|
||||
if (runs == null) return;
|
||||
Check.Eq(runs.Count, ItemInfoPartColors.Defaults.Length, "one per part");
|
||||
Check.True(runs.Select(r => r.Text).SequenceEqual(ItemInfoPartColors.Defaults.Select(d => d.Label)), "each part's label");
|
||||
Check.True(runs.Select(r => r.Color).SequenceEqual(ItemInfoPartColors.Defaults.Select(d => d.Color)), "in its colour");
|
||||
}
|
||||
|
||||
private static void Settings()
|
||||
{
|
||||
var saved = new LegacyUiSettings();
|
||||
saved.ItemInfoSettings.PartColors = true;
|
||||
string json = JsonSerializer.Serialize(saved, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
var live = new LegacyUiSettings();
|
||||
typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.Static | Any)!
|
||||
.Invoke(null, new object[] { JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!, live });
|
||||
Check.True(live.ItemInfoSettings.PartColors, "survives a save and load");
|
||||
Check.Eq(JsonSerializer.Serialize(live, RynthAiJsonContext.Default.LegacyUiSettings), json, "and saves back unchanged");
|
||||
|
||||
var doc = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject();
|
||||
var info = doc[doc.Select(kv => kv.Key).Single(k => k.Equals("ItemInfoSettings", StringComparison.OrdinalIgnoreCase))]!.AsObject();
|
||||
string? key = info.Select(kv => kv.Key).SingleOrDefault(k => k.Equals("PartColors", StringComparison.OrdinalIgnoreCase));
|
||||
Check.True(key != null, "the field is in the profile JSON");
|
||||
if (key != null) info.Remove(key);
|
||||
var old = new LegacyUiSettings();
|
||||
typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.Static | Any)!
|
||||
.Invoke(null, new object[] { JsonSerializer.Deserialize(doc.ToJsonString(), RynthAiJsonContext.Default.LegacyUiSettings)!, old });
|
||||
Check.False(old.ItemInfoSettings.PartColors, "a profile without it: off");
|
||||
|
||||
var s = new MagItemInfoSettings { PartColors = true };
|
||||
s.ResetToDefaults();
|
||||
Check.False(s.PartColors, "reset: off");
|
||||
|
||||
var mapSettings = new LegacyUiSettings();
|
||||
var e = ExpressionTests.Engine(settings: mapSettings);
|
||||
e.Evaluate("rasetsetting[ItemInfoPartColors, 1]");
|
||||
Check.True(mapSettings.ItemInfoSettings.PartColors, "set through the settings map");
|
||||
Check.Eq(e.Evaluate("ragetsetting[ItemInfoPartColors]"), "1", "map reads it");
|
||||
e.Evaluate("rasetsetting[ItemInfoPartColors, 0]");
|
||||
Check.False(mapSettings.ItemInfoSettings.PartColors, "off through the map");
|
||||
|
||||
Bot bot = World();
|
||||
bot.Cmd("parts", "on");
|
||||
Check.True(bot.S.ItemInfoSettings.PartColors, "/ra iteminfo parts on");
|
||||
Check.True(FakeHost.Chat.Any(c => c == "[RynthAi] Item info colour per part: ON"), "replies with the value: " + All());
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Cmd("parts");
|
||||
Check.True(FakeHost.Chat.Any(c => c == "[RynthAi] Item info colour per part: ON"), "no argument: says the value now");
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Cmd("parts", "maybe");
|
||||
Check.True(bot.S.ItemInfoSettings.PartColors, "a bad argument changes nothing");
|
||||
Check.True(FakeHost.Chat.Any(c => c == "[RynthAi] Usage: /ra iteminfo parts on|off"), "and gets the usage: " + All());
|
||||
FakeHost.Chat.Clear();
|
||||
bot.S.ItemInfoSettings.Layout = MagItemInfoSettings.LayoutPetLines;
|
||||
bot.Cmd("parts", "on");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("the one-line layout only")), "on with the pet layout: says it needs the one-line layout");
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Cmd("parts", "off");
|
||||
Check.False(bot.S.ItemInfoSettings.PartColors, "/ra iteminfo parts off");
|
||||
Check.True(FakeHost.Chat.Any(c => c == "[RynthAi] Item info colour per part: OFF"), "replies off");
|
||||
}
|
||||
}
|
||||
|
|
@ -64,7 +64,7 @@ internal static class LootCorpseTests
|
|||
r.Add("corpse close: an abandoned open corpse is closed once", AbandonedCorpseClosed);
|
||||
r.Add("corpse close: stopping the macro mid-loot closes the open corpse, not marked completed", MacroStopClosesCorpse);
|
||||
r.Add("loot pacing: a pickup waits for the last bend-down, and no retry is timed while it plays", PickupWaitsForAnimation);
|
||||
r.Add("loot: a pack that takes none of an item's tries is left out; the item tries another, else looting stops", RefusingPackIsLeftOut);
|
||||
r.Add("loot: the main pack, the only place loot can go, takes none of an item's tries: judged full, the item given up, and one item's mark goes with it", RefusingPackIsLeftOut);
|
||||
r.Add("loot pacing: no pickup (first or retry) while the server owes an answer to a cast; it goes on the UseDone", PickupWaitsForCastAnswer);
|
||||
r.Add("corpse close: not while the last item is between the corpse and the pack - it closes once the item is in the inventory", CloseWaitsForInventory);
|
||||
r.Add("loot pacing: an item merged into a stack in the pack is confirmed without the 4 s arrival wait", MergedPickupConfirmedQuickly);
|
||||
|
|
@ -981,7 +981,7 @@ internal static class LootCorpseTests
|
|||
int seen = 0;
|
||||
var refuseAt = new List<long>();
|
||||
long end = Environment.TickCount64 + 6000;
|
||||
while (Environment.TickCount64 < end && !FakeHost.Logs.Any(l => l.Contains("no pack has a free slot")))
|
||||
while (Environment.TickCount64 < end && !FakeHost.Logs.Any(l => l.Contains("pickup failed")))
|
||||
{
|
||||
for (; seen < FakeHost.ExternalMoves.Count; seen++)
|
||||
if (FakeHost.ExternalMoves[seen].Id == Gem) refuseAt.Add(Environment.TickCount64 + 800);
|
||||
|
|
@ -993,12 +993,19 @@ internal static class LootCorpseTests
|
|||
bot.Tick(BotActivity.Looting);
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
// 2026-11-12: loot goes only to the main pack (the client takes nothing from a corpse straight
|
||||
// into a side pack), so one item refused there may be the server refusing the item (a pickup
|
||||
// timer), not the pack: it is given up and its mark goes with it. A second item refused
|
||||
// there keeps the mark (LootRetryTimingTests.FullMainPackRefusals).
|
||||
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 3, "three tries into the main pack, each after the last one's refusal");
|
||||
Check.True(FakeHost.ExternalMoves.Where(m => m.Id == Gem).All(m => m.Target == Player), "all into the main pack");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("took none of 3 tries") && l.Contains("trying another pack")), "the refusing pack is left out, said once");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("no pack has a free slot")), "no other pack: the corpse is left");
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("Pack full")), "and the player is told");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("pickup failed")), "not three more wasted tries into the same pack");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("the main pack took none of 3 tries") && l.Contains("treating it as full") && l.Contains("nowhere else to put it")),
|
||||
"the refusing pack is judged full, and there is nowhere else to go, said once");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("took none of 3 tries")), 1, "said once");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("pickup failed for")), "the gem is given up after its three tries, not sent round again");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("the only place loot can go")), "one item's refusals: its mark goes with it");
|
||||
Check.False(bot.Get<RynthCore.Plugin.RynthAi.Loot.PackRefusals>("_packRefusals").IsRefused(unchecked((int)Player), Environment.TickCount64),
|
||||
"so the main pack is not left out for the next item");
|
||||
}
|
||||
|
||||
// A pickup sent while Bloodstone Bolt VII was unanswered came back
|
||||
|
|
|
|||
|
|
@ -41,8 +41,9 @@ internal static class LootRetryTimingTests
|
|||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("loot retry (R-20261029-122319-321f): with 1.7 s answers no move is resent while one is out, no pack is marked full, every item lands", SlowServerNoFalseFull);
|
||||
r.Add("loot retry (R-20261029-122319-321f): a full main pack's refusals after the pickup count as tries (no free resends) and mark it full; the items go to the side pack", FullMainPackRefusals);
|
||||
r.Add("loot retry (R-20261029-122319-321f): unanswered moves are retried only after the answer wait; their pack marks end with the item, the next item starts fresh", UnansweredMovesDontPoison);
|
||||
r.Add("loot retry (R-20261029-122319-321f): a full main pack's refusals after the pickup count as tries (no free resends); a second item refused there keeps it marked full; nothing goes to a side pack", FullMainPackRefusals);
|
||||
r.Add("loot retry (R-20261029-122319-321f): unanswered moves are retried only after the answer wait, three tries, then given up (no side-pack round); their pack marks end with the item, the next item starts fresh", UnansweredMovesDontPoison);
|
||||
r.Add("loot pickup, main pack full (2026-11-12 'You must first pick up the Silver Pea'): a pea joins the stack you carry, a gem is left at once with one chat line, nothing is aimed at a side pack, the corpse completes", FullMainPackPeaJoinsGemLeft);
|
||||
r.Add("loot retry (R-20261029-122319-321f): an item that lands late, after its pack was given up on, un-marks that pack", LateLandingUnmarks);
|
||||
r.Add("loot retry (R-20261029-122319-321f): a refusal on arrival is 'too busy' (free resend), one after the pickup is the pack's answer", RefusalTiming);
|
||||
r.Add("loot retry (R-20261029-122319-321f): the answer wait grows with the server's measured answers, within 4-8 s", AnswerWaitAdapts);
|
||||
|
|
@ -390,17 +391,22 @@ internal static class LootRetryTimingTests
|
|||
|
||||
Run(bot, () => bot.Completed, 60_000);
|
||||
|
||||
// The real client takes nothing from a corpse straight into a side pack ("You must first pick
|
||||
// up the X", nothing sent, 2026-11-12), so the main pack is the only place to try.
|
||||
var mapMoves = FakeHost.ExternalMoves.Where(m => m.Id == Map).ToList();
|
||||
Check.Eq(mapMoves.Count(m => m.Target == Player), 3, "three tries into the main pack (each refused after the pickup ran), no free resends");
|
||||
Check.False(Logged("as too busy"), "a refusal after the pickup is not taken for 'too busy'");
|
||||
Check.True(Logged("the main pack took none of 3 tries") && Logged("the server refused 3 after the pickup ran") && Logged("treating it as full"),
|
||||
"the main pack is judged full on the server's refusals");
|
||||
Check.True(mapMoves.Last().Target == SidePack && sim.Landed.Any(l => l.Id == Map && l.Pack == SidePack), "then the map goes into the side pack and lands");
|
||||
Check.True(FakeHost.ExternalMoves.Where(m => m.Id == G2).All(m => m.Target == SidePack), "the next item goes straight to the side pack");
|
||||
Check.True(sim.Landed.Any(l => l.Id == G2), "and lands");
|
||||
Check.True(bot.Refusals.IsConfirmed(unchecked((int)Player), _now), "the main pack stays marked (confirmed by the server)");
|
||||
Check.False(bot.Refusals.IsRefused(unchecked((int)SidePack), _now), "the side pack is not marked");
|
||||
Check.True(Logged("pickup failed for 0x80263111"), "then the map is given up: there is nowhere else to put it");
|
||||
Check.True(Logged("the only place loot can go") && Logged("no longer treated as full (unless another item is refused there too)"),
|
||||
"one item's refusals alone could be the item's, not the pack's: its mark goes with it");
|
||||
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == G2 && m.Target == Player), 3, "the next item tries the main pack too, and is refused three times");
|
||||
Check.True(bot.Refusals.IsConfirmed(unchecked((int)Player), _now), "a second item refused there: the main pack stays marked (it is the pack)");
|
||||
Check.True(FakeHost.ExternalMoves.All(m => m.Target != SidePack), "no move ever goes to the side pack");
|
||||
Check.False(sim.Landed.Any(), "nothing lands: the server's main pack is full");
|
||||
Check.Eq(sim.LocalRefused, 0, "no move sent while another was unanswered");
|
||||
Check.True(bot.Completed, "the corpse completes");
|
||||
});
|
||||
|
||||
// ── 3. Moves the server never answers ─────────────────────────────────────
|
||||
|
|
@ -415,13 +421,14 @@ internal static class LootRetryTimingTests
|
|||
var sends = Run(bot, () => bot.Completed, 90_000).Where(s => s.Id == Lost).ToList();
|
||||
|
||||
var lostMoves = FakeHost.ExternalMoves.Where(m => m.Id == Lost).ToList();
|
||||
Check.Eq(lostMoves.Count, 6, "three tries into the main pack, three into the side pack");
|
||||
Check.Eq(lostMoves.Count, 3, "three tries into the main pack, and no round into the side pack (the client refuses that from a corpse)");
|
||||
Check.True(lostMoves.All(m => m.Target == Player), "all of them into the main pack");
|
||||
var gaps = sends.Zip(sends.Skip(1), (a, b) => b.At - a.At).ToList();
|
||||
Check.True(gaps.Count > 0 && gaps.All(g => g >= RynthAiPlugin.PickupAnswerWaitMinMs - TickMs),
|
||||
$"each retry only after the answer wait ({string.Join(", ", gaps)} ms)");
|
||||
Check.True(Logged("trying another pack for this item only"), "the main pack is left out for this item only");
|
||||
Check.False(Logged("trying another pack"), "no other pack to try");
|
||||
Check.False(Logged("treating it as full"), "no pack is judged full on unanswered tries");
|
||||
Check.True(Logged("pickup failed for 0x80263121"), "the item is given up after the second round");
|
||||
Check.True(Logged("pickup failed for 0x80263121"), "the item is given up after its three tries");
|
||||
Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now), "the main pack's mark ended with the item");
|
||||
Check.False(bot.Refusals.IsRefused(unchecked((int)SidePack), _now), "so did the side pack's");
|
||||
Check.True(FakeHost.ExternalMoves.Where(m => m.Id == Next).All(m => m.Target == Player), "the next item goes into the main pack again");
|
||||
|
|
@ -430,24 +437,72 @@ internal static class LootRetryTimingTests
|
|||
Check.False(Logged("no pack has a free slot"), "looting does not stop for want of a pack");
|
||||
});
|
||||
|
||||
// ── 3b. The main pack is full by the client's own count ───────────────────
|
||||
// 2026-11-12, Drakkon on DreamWeave (and R-20261112-110130-5d71): the main pack filled at 07:35,
|
||||
// the looter aimed every pickup at a side pack, the client refused each one ("You must first
|
||||
// pick up the Silver Pea", nothing sent), and each item waited out 3 + 3 unanswered tries and
|
||||
// was left: 48 peas and maps in two hours, the bot stuck on one corpse after another.
|
||||
|
||||
private static void FullMainPackPeaJoinsGemLeft() => Clocked(() =>
|
||||
{
|
||||
const uint Gem = 0x80263171, Pea = 0x80263172, PeaStack = 0x80263173, JunkBase = 0x80264000;
|
||||
World(sidePack: true, Gem, Pea);
|
||||
FakeHost.Names[Pea] = "Silver Pea";
|
||||
FakeHost.Ints[(Pea, 11)] = 100; // MaxStackSize
|
||||
FakeHost.Ints[(Pea, 12)] = 1; // StackCount
|
||||
FakeHost.Names[PeaStack] = "Silver Pea"; // the stack you carry, in the side pack
|
||||
FakeHost.ItemTypes[PeaStack] = ItemTypeGem;
|
||||
FakeHost.Ints[(PeaStack, 11)] = 100;
|
||||
FakeHost.Ints[(PeaStack, 12)] = 40;
|
||||
FakeHost.Containers[PeaStack] = SidePack;
|
||||
var ids = new List<uint> { Gem, Pea, PeaStack };
|
||||
for (uint i = 0; i < 102; i++) // a full main pack
|
||||
{
|
||||
uint j = JunkBase + i;
|
||||
FakeHost.Names[j] = $"Junk {i}";
|
||||
FakeHost.ItemTypes[j] = 0x80;
|
||||
FakeHost.Containers[j] = Player;
|
||||
ids.Add(j);
|
||||
}
|
||||
var sim = new SlowAce();
|
||||
var bot = Open(sim, sidePack: true, ids.ToArray());
|
||||
|
||||
long started = _now;
|
||||
Run(bot, () => bot.Completed, 60_000);
|
||||
|
||||
Check.True(FakeHost.ExternalMoves.All(m => m.Target != SidePack), "no pickup is aimed at the side pack (the client would refuse it)");
|
||||
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 0, "the gem is not sent at all: the main pack has no slot and it joins no stack");
|
||||
Check.True(Logged("leaving 'Gem 113' 0x80263171") && Logged("the main pack is full"), "the gem is left, and the log says why");
|
||||
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Pea), 1, "the pea is sent once");
|
||||
Check.True(FakeHost.ExternalMoves.Where(m => m.Id == Pea).All(m => m.Target == Player), "aimed at the main pack: the client joins it to your stack");
|
||||
Check.True(sim.Landed.Any(l => l.Id == Pea), "and it lands");
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("Main pack full")), 1, "one chat line says the main pack is full and loot is left");
|
||||
Check.False(Logged("pickup failed"), "nothing is waited out and given up");
|
||||
Check.False(Logged("no pack has a free slot"), "and looting doesn't stop: the side pack has room");
|
||||
Check.True(bot.Completed, "the corpse completes");
|
||||
Check.True(_now - started < 10_000, $"quickly ({_now - started} ms), not after 3 + 3 tries per item");
|
||||
});
|
||||
|
||||
// ── 4. A late landing ─────────────────────────────────────────────────────
|
||||
|
||||
private static void LateLandingUnmarks() => Clocked(() =>
|
||||
{
|
||||
const uint Slow = 0x80263131, Next = 0x80263132;
|
||||
World(sidePack: true, Slow, Next);
|
||||
// One item: with no side-pack round (the client takes nothing from a corpse straight into one)
|
||||
// it is given up at its third unanswered try, before the late answer; a second item would be
|
||||
// the server's next pickup then and the late one would be refused as too busy.
|
||||
const uint Slow = 0x80263131;
|
||||
World(sidePack: true, Slow);
|
||||
var sim = new SlowAce();
|
||||
sim.Lag[Slow] = 12_500; // a lag spike: the server takes up the first move 12.5 s late
|
||||
var bot = Open(sim, sidePack: true, Slow, Next);
|
||||
var bot = Open(sim, sidePack: true, Slow);
|
||||
|
||||
Run(bot, () => bot.Completed, 90_000);
|
||||
Run(bot, () => bot.Completed && sim.Landed.Any(l => l.Id == Slow), 90_000);
|
||||
Run(bot, () => Logged("after it was given up"), 3_000);
|
||||
|
||||
Check.True(sim.Landed.Any(l => l.Id == Slow && l.Pack == Player), "the first move lands in the main pack, late");
|
||||
Check.True(Logged("trying another pack for this item only"), "after three unanswered tries the main pack was left out for the item");
|
||||
Check.True(Logged("0x80263131 landed in the main pack; it has room after all and is no longer treated as full"), "the late landing un-marks the main pack");
|
||||
Check.True(Logged("pickup failed for 0x80263131"), "after three unanswered tries the item was given up (no side-pack round)");
|
||||
Check.True(Logged("0x80263131 landed in the main pack") && Logged("after it was given up"), "the late landing is seen and logged");
|
||||
Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now), "the main pack is not marked");
|
||||
Check.True(sim.Landed.Any(l => l.Id == Next), "the next item lands too");
|
||||
Check.False(Logged("pickup failed for 0x80263132"), "the next item is not given up on");
|
||||
Check.False(Logged("no pack has a free slot"), "looting does not stop");
|
||||
Check.Eq((long)bot.Call("PickupAnswerWaitMs")!, RynthAiPlugin.PickupAnswerWaitMinMs,
|
||||
"the lag spike's late answer (to an earlier, timed-out send) does not stretch the answer wait");
|
||||
|
|
@ -661,10 +716,10 @@ internal static class LootRetryTimingTests
|
|||
|
||||
var mapMoves = FakeHost.ExternalMoves.Where(m => m.Id == QuestMap).ToList();
|
||||
Check.Eq(mapMoves.Count(m => m.Target == Player), 3, "three tries into the main pack");
|
||||
Check.Eq(mapMoves.Count(m => m.Target == SidePack), 3, "three into the side pack");
|
||||
Check.Eq(mapMoves.Count(m => m.Target == SidePack), 0, "none into the side pack (the client refuses that from a corpse)");
|
||||
Check.True(Logged("pickup failed for 0x80263151"), "then the map is given up");
|
||||
Check.True(Logged("it is refusing the item, not the packs") && Logged("the main pack and pack 0x80263001 are no longer treated as full"),
|
||||
"both marks go with the map");
|
||||
Check.True(Logged("the only place loot can go") && Logged("the main pack is no longer treated as full"),
|
||||
"the main pack is the only place it could go, and its mark goes with the map");
|
||||
Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now) || bot.Refusals.IsRefused(unchecked((int)SidePack), _now), "no pack marked");
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == G2) && FakeHost.ExternalMoves.Where(m => m.Id == G2).All(m => m.Target == Player), "the next item goes into the main pack");
|
||||
Check.True(sim.Landed.Any(l => l.Id == G2 && l.Pack == Player), "and lands");
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ using System.Linq;
|
|||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Loot;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
|
|
@ -34,7 +35,7 @@ internal static class LootSalvageTests
|
|||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("loot pickup: a corpse item is moved into the main pack, never used (no get-and-wield)", PickupMovesNeverUses);
|
||||
r.Add("loot pickup: a full main pack sends the item to a side pack with room", PickupFullMainPackGoesToSidePack);
|
||||
r.Add("loot pickup: a full main pack never sends an item to a side pack (the client refuses that from a corpse); a stack you carry is still joined, anything else is left", PickupFullMainPackNeverSidePack);
|
||||
r.Add("loot pickup: no move call -> wearables are left, other items are used", PickupWithoutMoveCall);
|
||||
r.Add("salvage: a worn item is left alone and never taken off", SalvageLeavesWornItem);
|
||||
r.Add("salvage: a corpse's items go in one batch and all are salvaged", SalvageOneBatch);
|
||||
|
|
@ -82,7 +83,12 @@ internal static class LootSalvageTests
|
|||
Check.Eq(FakeHost.Wields.Count, 0, "no WieldItem");
|
||||
}
|
||||
|
||||
private static void PickupFullMainPackGoesToSidePack()
|
||||
// 2026-11-12: with the main pack full the looter aimed pickups at a side pack, and the client
|
||||
// refused every one ("You must first pick up the Silver Pea", nothing sent): 75 in a week of
|
||||
// logs, none landed, each item waited out 3 + 3 tries and was left.
|
||||
private const uint PeaInPack = 0x80262E01, Pea = 0x80262E02, SpareMain = 0x80262E03;
|
||||
|
||||
private static (RynthCoreHost Host, WorldObjectCache Cache) FullMainPack(bool sideRoom, bool peaStack)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true;
|
||||
|
|
@ -97,20 +103,60 @@ internal static class LootSalvageTests
|
|||
}
|
||||
FakeHost.Names[SidePack] = "Backpack";
|
||||
FakeHost.ItemTypes[SidePack] = ItemTypeContainer;
|
||||
FakeHost.Ints[(SidePack, 6)] = 24; // ItemsCapacity
|
||||
FakeHost.Ints[(SidePack, 6)] = sideRoom ? 24 : 1; // ItemsCapacity
|
||||
FakeHost.Containers[SidePack] = Player;
|
||||
ids.Add(SidePack);
|
||||
if (peaStack)
|
||||
{
|
||||
// The pea stack lives in the side pack (RynthSort's "Pea" rule), with room for more.
|
||||
FakeHost.Names[PeaInPack] = "Silver Pea";
|
||||
FakeHost.ItemTypes[PeaInPack] = 0x1000; // spell component
|
||||
FakeHost.Ints[(PeaInPack, 11)] = 100; // MaxStackSize
|
||||
FakeHost.Ints[(PeaInPack, 12)] = 40; // StackCount
|
||||
FakeHost.Containers[PeaInPack] = SidePack;
|
||||
ids.Add(PeaInPack);
|
||||
}
|
||||
else if (!sideRoom)
|
||||
{
|
||||
FakeHost.Names[SpareMain] = "Junk side";
|
||||
FakeHost.ItemTypes[SpareMain] = ItemTypeGem;
|
||||
FakeHost.Containers[SpareMain] = SidePack; // the one slot taken
|
||||
ids.Add(SpareMain);
|
||||
}
|
||||
FakeHost.Names[Ring] = "Gold Ring";
|
||||
FakeHost.ItemTypes[Ring] = ItemTypeJewelry;
|
||||
ids.Add(Ring);
|
||||
FakeHost.Names[Pea] = "Silver Pea";
|
||||
FakeHost.ItemTypes[Pea] = 0x1000;
|
||||
FakeHost.Ints[(Pea, 11)] = 100;
|
||||
FakeHost.Ints[(Pea, 12)] = 1;
|
||||
ids.Add(Pea);
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = FakeHost.MakeCache(host, Player, ids);
|
||||
return (host, FakeHost.MakeCache(host, Player, ids));
|
||||
}
|
||||
|
||||
var result = LootPickup.Send(host, cache, Ring, Player, out uint dest);
|
||||
private static void PickupFullMainPackNeverSidePack()
|
||||
{
|
||||
var (host, cache) = FullMainPack(sideRoom: true, peaStack: true);
|
||||
|
||||
Check.Eq(result, LootPickupResult.Moved, "a move was sent");
|
||||
Check.Eq(dest, SidePack, "the main pack is full: the side pack");
|
||||
Check.Eq(LootPickup.Send(host, cache, Ring, Player, out uint dest), LootPickupResult.MainPackFull,
|
||||
"a ring with the main pack full and room in a side pack: left (MainPackFull)");
|
||||
Check.Eq(dest, 0u, "no destination");
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 0, "and no move sent, least of all into the side pack");
|
||||
|
||||
Check.Eq(LootPickup.Send(host, cache, Pea, Player, out dest), LootPickupResult.Moved,
|
||||
"a Silver Pea joins the stack you carry: sent");
|
||||
Check.Eq(dest, Player, "aimed at the main pack: the client joins it to the stack in the side pack");
|
||||
Check.True(FakeHost.ExternalMoves.All(m => m.Target != SidePack), "never aimed at the side pack");
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "no UseObject");
|
||||
|
||||
var (host2, cache2) = FullMainPack(sideRoom: true, peaStack: false);
|
||||
Check.Eq(LootPickup.Send(host2, cache2, Pea, Player, out _), LootPickupResult.MainPackFull,
|
||||
"a pea with no stack to join, main pack full: left too");
|
||||
|
||||
var (host3, cache3) = FullMainPack(sideRoom: false, peaStack: false);
|
||||
Check.Eq(LootPickup.Send(host3, cache3, Ring, Player, out _), LootPickupResult.NoRoom,
|
||||
"no room in any pack: NoRoom, as before");
|
||||
}
|
||||
|
||||
private static void PickupWithoutMoveCall()
|
||||
|
|
|
|||
413
Tools/RynthCore.RynthAiHostTests/Tests/ProfileButtonTests.cs
Normal file
413
Tools/RynthCore.RynthAiHostTests/Tests/ProfileButtonTests.cs
Normal file
|
|
@ -0,0 +1,413 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Loot.VTank;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-11-11: the Loaded files drawer's profile buttons (Save, Save As, New, Rename, Move to
|
||||
// Deleted, Open folder) and their /ra verbs. The name and path helpers (ProfileFileOps), then each
|
||||
// kind through the dashboard: settings profiles, navs, metas, loot profiles, and the Spells window's
|
||||
// buff profile Delete. Nothing is ever deleted: a removed profile goes to the Deleted folder beside
|
||||
// it, and a file replaced by Save As has its old copy kept there first. Scratch folders only (the
|
||||
// dashboard's NavProfiles / MetaFiles / LootProfiles fields and ProfilesBase are pointed at them).
|
||||
internal static class ProfileButtonTests
|
||||
{
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("profile buttons: Save As names are tidied and unsafe ones refused", NameSanitising);
|
||||
r.Add("profile buttons: replace detection: another existing file only, never the file in use", OverwriteDetection);
|
||||
r.Add("profile buttons: Move to Deleted moves (never deletes), names never collide", MoveToDeleted);
|
||||
r.Add("profile buttons: Save As over another file keeps its old copy in Deleted", CopyToDeleted);
|
||||
r.Add("profile buttons: rename refuses a name taken, allows a change of case", RenameHelper);
|
||||
r.Add("profile buttons: settings Save As / replace / rename / Move to Deleted", SettingsProfiles);
|
||||
r.Add("profile buttons: nav New / Save As asks before replacing / rename / Move to Deleted", NavProfiles);
|
||||
r.Add("profile buttons: meta New / Save As / replace / rename / Move to Deleted", MetaProfiles);
|
||||
r.Add("profile buttons: loot Save As copies, New checks the name, rename, Move to Deleted", LootProfiles);
|
||||
r.Add("profile buttons: the Spells window's Delete moves the buff profile to Deleted", BuffDelete);
|
||||
r.Add("profile buttons: the /ra verbs reply (worked, or why and the usage)", CommandsReply);
|
||||
}
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static string Dir(string name)
|
||||
{
|
||||
string dir = Path.Combine(Program.TempRoot, "profile-buttons", name);
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
|
||||
Directory.CreateDirectory(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
private static int AllFiles(string dir) => Directory.GetFiles(dir, "*", SearchOption.AllDirectories).Length;
|
||||
|
||||
private static string[] DeletedFiles(string folder)
|
||||
{
|
||||
string d = Path.Combine(folder, ProfileFileOps.DeletedFolderName);
|
||||
return Directory.Exists(d) ? Directory.GetFiles(d).Select(Path.GetFileName).ToArray()! : Array.Empty<string>();
|
||||
}
|
||||
|
||||
/// <summary>A dashboard whose nav, meta and loot folders are scratch folders under <paramref name="root"/>.</summary>
|
||||
private static LegacyDashboardRenderer Dash(string root, out LegacyUiSettings s)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
DataWriteGuard.Reset();
|
||||
var dash = new LegacyDashboardRenderer(FakeHost.Create());
|
||||
foreach (var (field, sub) in new[] { ("_navFolder", "NavProfiles"), ("_metaFolder", "MetaFiles"), ("_lootFolder", "LootProfiles") })
|
||||
{
|
||||
string folder = Path.Combine(root, sub);
|
||||
Directory.CreateDirectory(folder);
|
||||
typeof(LegacyDashboardRenderer).GetField(field, Any)!.SetValue(dash, folder);
|
||||
}
|
||||
s = (LegacyUiSettings)typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.GetValue(dash)!;
|
||||
return dash;
|
||||
}
|
||||
|
||||
// ── ProfileFileOps ───────────────────────────────────────────────────────
|
||||
|
||||
private static void NameSanitising()
|
||||
{
|
||||
Check.Null(ProfileFileOps.CleanName(" \"Night Farm.nav\" ", LegacyDashboardRenderer.NavExtensions, out string n), "quotes, spaces and .nav are fine");
|
||||
Check.Eq(n, "Night Farm", "tidied");
|
||||
Check.Null(ProfileFileOps.CleanName("Loot.v2.utl", LegacyDashboardRenderer.LootExtensions, out n), "dots inside are fine");
|
||||
Check.Eq(n, "Loot.v2", "only the known extension is dropped");
|
||||
Check.Null(ProfileFileOps.CleanName("farm.AF", LegacyDashboardRenderer.MetaExtensions, out n), "extension case");
|
||||
Check.Eq(n, "farm", "farm");
|
||||
foreach (string bad in new[] { "", " ", "a/b", "..\\x", "..", "a:b", "what?", "con", "LPT1", "x.", new string('a', 130) })
|
||||
Check.NotNull(ProfileFileOps.CleanName(bad, LegacyDashboardRenderer.NavExtensions, out _), $"refused: '{bad}'");
|
||||
Check.True(LegacyDashboardRenderer.IsReservedSettingsName("Monsters"), "monsters.json is RynthAi's own");
|
||||
Check.True(LegacyDashboardRenderer.IsReservedSettingsName("metamanager"), "metamanager.json is RynthAi's own");
|
||||
Check.False(LegacyDashboardRenderer.IsReservedSettingsName("Hunting"), "a plain name is not");
|
||||
}
|
||||
|
||||
private static void OverwriteDetection()
|
||||
{
|
||||
string dir = Dir("overwrite");
|
||||
string a = Path.Combine(dir, "a.nav"), b = Path.Combine(dir, "b.nav"), c = Path.Combine(dir, "c.nav");
|
||||
File.WriteAllText(a, "a");
|
||||
File.WriteAllText(b, "b");
|
||||
Check.True(ProfileFileOps.WouldReplace(b, a), "another file that exists");
|
||||
Check.False(ProfileFileOps.WouldReplace(a, a), "the file in use is a plain save");
|
||||
Check.False(ProfileFileOps.WouldReplace(Path.Combine(dir, "A.NAV"), a), "the file in use, another case");
|
||||
Check.False(ProfileFileOps.WouldReplace(c, a), "a name not taken");
|
||||
Check.True(ProfileFileOps.WouldReplace(b, string.Empty), "nothing in use: an existing file is still replaced");
|
||||
}
|
||||
|
||||
private static void MoveToDeleted()
|
||||
{
|
||||
string dir = Dir("move");
|
||||
string path = Path.Combine(dir, "farm.nav");
|
||||
File.WriteAllText(path, "route");
|
||||
var when = new DateTime(2026, 11, 11, 15, 30, 12);
|
||||
Check.Eq(Path.GetFileName(ProfileFileOps.DeletedPathFor(path, when)), "farm.2026-11-11_153012.nav", "the time before the extension");
|
||||
Check.True(ProfileFileOps.MoveToDeleted(path, when, out string moved, out string error), "moved: " + error);
|
||||
Check.False(File.Exists(path), "gone from its folder");
|
||||
Check.Eq(File.ReadAllText(moved), "route", "the same file in Deleted");
|
||||
Check.Eq(Path.GetDirectoryName(moved), Path.Combine(dir, "Deleted"), "in <folder>\\Deleted");
|
||||
Check.Eq(Directory.GetFiles(dir, "*.nav").Length, 0, "the picker's folder no longer lists it");
|
||||
|
||||
// The same name at the same second: a second copy, never over the first.
|
||||
File.WriteAllText(path, "route 2");
|
||||
Check.True(ProfileFileOps.MoveToDeleted(path, when, out string moved2, out _), "second move");
|
||||
Check.Eq(Path.GetFileName(moved2), "farm.2026-11-11_153012 (2).nav", "numbered");
|
||||
Check.Eq(File.ReadAllText(moved), "route", "the first copy kept");
|
||||
Check.Eq(AllFiles(dir), 2, "nothing lost");
|
||||
|
||||
Check.False(ProfileFileOps.MoveToDeleted(path, when, out _, out error), "a file that isn't there");
|
||||
Check.True(error.Contains("isn't there"), "says why: " + error);
|
||||
}
|
||||
|
||||
private static void CopyToDeleted()
|
||||
{
|
||||
string dir = Dir("copy");
|
||||
string path = Path.Combine(dir, "farm.af");
|
||||
File.WriteAllText(path, "old");
|
||||
Check.True(ProfileFileOps.CopyToDeleted(path, new DateTime(2026, 11, 11, 9, 0, 0), out string copy, out string error), "kept: " + error);
|
||||
Check.Eq(File.ReadAllText(copy), "old", "the old copy");
|
||||
Check.True(File.Exists(path), "the file itself stays (it is saved over next)");
|
||||
Check.True(ProfileFileOps.CopyToDeleted(Path.Combine(dir, "none.af"), DateTime.Now, out copy, out _), "nothing to keep is fine");
|
||||
Check.Eq(copy, string.Empty, "and keeps nothing");
|
||||
}
|
||||
|
||||
private static void RenameHelper()
|
||||
{
|
||||
string dir = Dir("rename");
|
||||
string a = Path.Combine(dir, "farm.nav"), b = Path.Combine(dir, "hunt.nav");
|
||||
File.WriteAllText(a, "a");
|
||||
File.WriteAllText(b, "b");
|
||||
Check.False(ProfileFileOps.Rename(a, b, out string error), "a name taken");
|
||||
Check.True(error.Contains("already exists"), error);
|
||||
Check.Eq(File.ReadAllText(b), "b", "the other file untouched");
|
||||
Check.True(ProfileFileOps.Rename(a, Path.Combine(dir, "Farm.nav"), out error), "a change of case: " + error);
|
||||
Check.Eq(Path.GetFileName(Directory.GetFiles(dir, "farm.nav").Single()), "Farm.nav", "the new case is on disk");
|
||||
Check.False(ProfileFileOps.Rename(Path.Combine(dir, "Farm.nav"), Path.Combine(dir, "Farm.nav"), out _), "the same name");
|
||||
Check.Eq(AllFiles(dir), 2, "nothing lost");
|
||||
}
|
||||
|
||||
// ── Settings profiles ────────────────────────────────────────────────────
|
||||
|
||||
private static void SettingsProfiles()
|
||||
{
|
||||
string root = Dir("settings");
|
||||
LegacyDashboardRenderer.ProfilesBase = Path.Combine(root, "SettingsProfiles");
|
||||
LegacyDashboardRenderer.MonstersBase = Path.Combine(root, "MonsterProfiles");
|
||||
string? buffs = BuffProfileStore.FolderOverride;
|
||||
BuffProfileStore.FolderOverride = Path.Combine(root, "BuffProfiles");
|
||||
try
|
||||
{
|
||||
FakeHost.WorldName = "TestWorld";
|
||||
var dash = Dash(root, out var s);
|
||||
FakeHost.WorldName = "TestWorld";
|
||||
dash.LoadSettings("Tester");
|
||||
string dir = Path.Combine(LegacyDashboardRenderer.ProfilesBase, "TestWorld", "Tester");
|
||||
|
||||
ProfileResult r = dash.SaveProfileNow(ProfileKind.Settings);
|
||||
Check.True(r.Ok && File.Exists(Path.Combine(dir, "Default.json")), "Save writes Default.json: " + r.Text);
|
||||
|
||||
r = dash.SaveProfileAs(ProfileKind.Settings, "monsters", replace: false);
|
||||
Check.False(r.Ok, "a name RynthAi keeps for itself is refused");
|
||||
Check.True(r.Text.Contains("monsters.json"), r.Text);
|
||||
Check.False(dash.SaveProfileAs(ProfileKind.Settings, "a/b", replace: false).Ok, "a folder in the name is refused");
|
||||
|
||||
s.MonsterRange = 33;
|
||||
r = dash.SaveProfileAs(ProfileKind.Settings, "Farm", replace: false);
|
||||
Check.True(r.Ok, "Save As: " + r.Text);
|
||||
Check.Eq(s.SelectedProfile, "Farm", "Farm is in use");
|
||||
Check.True(File.Exists(Path.Combine(dir, "Farm.json")), "Farm.json");
|
||||
Check.True(dash.ReadDashboardFiles().Profiles.Contains("Farm"), "listed");
|
||||
|
||||
// Back to Default; Save As Farm again asks first and writes nothing.
|
||||
dash.SelectProfileAtIndex(3, Array.IndexOf(dash.ReadDashboardFiles().Profiles, "Default"));
|
||||
Check.Eq(s.SelectedProfile, "Default", "Default again");
|
||||
string farmBefore = File.ReadAllText(Path.Combine(dir, "Farm.json"));
|
||||
r = dash.SaveProfileAs(ProfileKind.Settings, "Farm", replace: false);
|
||||
Check.True(r.NeedsReplace && !r.Ok, "asks before replacing: " + r.Text);
|
||||
Check.Eq(File.ReadAllText(Path.Combine(dir, "Farm.json")), farmBefore, "Farm untouched");
|
||||
Check.Eq(DeletedFiles(dir).Length, 0, "nothing kept yet");
|
||||
r = dash.SaveProfileAs(ProfileKind.Settings, "Farm", replace: true);
|
||||
Check.True(r.Ok, "replaced: " + r.Text);
|
||||
Check.Eq(DeletedFiles(dir).Length, 1, "the old Farm kept in Deleted");
|
||||
Check.Eq(File.ReadAllText(Path.Combine(dir, "Deleted", DeletedFiles(dir)[0])), farmBefore, "the old Farm's content");
|
||||
|
||||
Check.Eq(s.SelectedProfile, "Farm", "Save As puts the replaced profile in use");
|
||||
dash.SelectProfileAtIndex(3, Array.IndexOf(dash.ReadDashboardFiles().Profiles, "Default"));
|
||||
Check.False(dash.RenameProfile(ProfileKind.Settings, "Other").Ok, "Default keeps its name");
|
||||
Check.False(File.Exists(Path.Combine(dir, "Other.json")), "nothing renamed");
|
||||
dash.SelectProfileAtIndex(3, Array.IndexOf(dash.ReadDashboardFiles().Profiles, "Farm"));
|
||||
Check.Eq(s.SelectedProfile, "Farm", "Farm again");
|
||||
Check.False(dash.RenameProfile(ProfileKind.Settings, "Default").Ok, "nothing can be renamed to Default");
|
||||
r = dash.RenameProfile(ProfileKind.Settings, "Hunt");
|
||||
Check.True(r.Ok, "rename: " + r.Text);
|
||||
Check.Eq(s.SelectedProfile, "Hunt", "Hunt in use");
|
||||
Check.False(File.Exists(Path.Combine(dir, "Farm.json")), "Farm.json renamed");
|
||||
Check.True(File.Exists(Path.Combine(dir, "Hunt.json")), "Hunt.json");
|
||||
Check.Eq(File.ReadAllText(Path.Combine(dir, "active_profile.txt")), "Hunt", "the active-profile marker follows");
|
||||
|
||||
r = dash.DeleteProfile(ProfileKind.Settings);
|
||||
Check.True(r.Ok, "move to Deleted: " + r.Text);
|
||||
Check.Eq(s.SelectedProfile, "Default", "back on Default");
|
||||
Check.False(File.Exists(Path.Combine(dir, "Hunt.json")), "Hunt.json out of the list's folder");
|
||||
Check.True(DeletedFiles(dir).Any(f => f.StartsWith("Hunt.", StringComparison.Ordinal)), "Hunt in Deleted");
|
||||
Check.False(dash.ReadDashboardFiles().Profiles.Contains("Hunt"), "not listed");
|
||||
|
||||
Check.False(dash.DeleteProfile(ProfileKind.Settings).Ok, "Default is never moved");
|
||||
Check.False(dash.RenameProfile(ProfileKind.Settings, "Main").Ok, "Default keeps its name");
|
||||
Check.True(File.Exists(Path.Combine(dir, "Default.json")), "Default.json stays");
|
||||
}
|
||||
finally { BuffProfileStore.FolderOverride = buffs; }
|
||||
}
|
||||
|
||||
// ── Navs ─────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void NavProfiles()
|
||||
{
|
||||
string root = Dir("nav");
|
||||
var dash = Dash(root, out var s);
|
||||
string navs = Path.Combine(root, "NavProfiles");
|
||||
|
||||
ProfileResult r = dash.NewProfile(ProfileKind.Nav, "Loop");
|
||||
Check.True(r.Ok, "New: " + r.Text);
|
||||
Check.Eq(s.CurrentNavPath, Path.Combine(navs, "Loop.nav"), "Loop is loaded");
|
||||
Check.False(dash.NewProfile(ProfileKind.Nav, "loop.nav").Ok, "New never opens an existing nav");
|
||||
|
||||
// Save As onto another nav asks first; nothing is written. (The write itself is SaveRoute,
|
||||
// which saves to the install's NavProfiles, so it isn't run here.)
|
||||
File.WriteAllText(Path.Combine(navs, "Other.nav"), "keep me");
|
||||
r = dash.SaveProfileAs(ProfileKind.Nav, "Other", replace: false);
|
||||
Check.True(r.NeedsReplace, "asks: " + r.Text);
|
||||
Check.Eq(File.ReadAllText(Path.Combine(navs, "Other.nav")), "keep me", "Other untouched");
|
||||
Check.Eq(DeletedFiles(navs).Length, 0, "nothing kept yet");
|
||||
|
||||
Check.False(dash.RenameProfile(ProfileKind.Nav, "Other").Ok, "rename onto a taken name is refused");
|
||||
r = dash.RenameProfile(ProfileKind.Nav, "Ring");
|
||||
Check.True(r.Ok, "rename: " + r.Text);
|
||||
Check.Eq(s.CurrentNavPath, Path.Combine(navs, "Ring.nav"), "Ring stays loaded");
|
||||
Check.True(dash.NavFileNames().Contains("Ring") && !dash.NavFileNames().Contains("Loop"), "the list follows");
|
||||
|
||||
s.CurrentRoute.Points.Add(new NavPoint { NS = 1, EW = 2 });
|
||||
r = dash.DeleteProfile(ProfileKind.Nav);
|
||||
Check.True(r.Ok, "move to Deleted: " + r.Text);
|
||||
Check.Eq(s.CurrentNavPath, string.Empty, "no nav in use");
|
||||
Check.Eq(s.CurrentRoute.Points.Count, 0, "the route is cleared, as picking None");
|
||||
Check.False(dash.NavFileNames().Contains("Ring"), "not listed");
|
||||
Check.True(DeletedFiles(navs).Single().StartsWith("Ring.", StringComparison.Ordinal), "Ring in NavProfiles\\Deleted");
|
||||
Check.False(dash.DeleteProfile(ProfileKind.Nav).Ok, "nothing in use: nothing to move");
|
||||
Check.True(File.Exists(Path.Combine(navs, "Other.nav")), "Other is never touched");
|
||||
}
|
||||
|
||||
// ── Metas ────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void MetaProfiles()
|
||||
{
|
||||
string root = Dir("meta");
|
||||
var dash = Dash(root, out var s);
|
||||
string metas = Path.Combine(root, "MetaFiles");
|
||||
|
||||
ProfileResult r = dash.NewProfile(ProfileKind.Meta, "Farm");
|
||||
Check.True(r.Ok, "New: " + r.Text);
|
||||
Check.Eq(s.CurrentMetaPath, Path.Combine(metas, "Farm.af"), "Farm.af in use");
|
||||
Check.False(dash.NewProfile(ProfileKind.Meta, "Farm").Ok, "New never opens an existing meta");
|
||||
|
||||
r = dash.SaveProfileAs(ProfileKind.Meta, "Copy", replace: false);
|
||||
Check.True(r.Ok, "Save As: " + r.Text);
|
||||
Check.Eq(s.CurrentMetaPath, Path.Combine(metas, "Copy.af"), "Copy.af in use");
|
||||
Check.True(File.Exists(Path.Combine(metas, "Copy.af")), "written");
|
||||
|
||||
string farmBefore = File.ReadAllText(Path.Combine(metas, "Farm.af"));
|
||||
r = dash.SaveProfileAs(ProfileKind.Meta, "Farm", replace: false);
|
||||
Check.True(r.NeedsReplace, "asks before replacing Farm: " + r.Text);
|
||||
r = dash.SaveProfileAs(ProfileKind.Meta, "Farm", replace: true);
|
||||
Check.True(r.Ok, "replaced: " + r.Text);
|
||||
Check.Eq(File.ReadAllText(Path.Combine(metas, "Deleted", DeletedFiles(metas).Single())), farmBefore, "Farm's old copy kept");
|
||||
|
||||
r = dash.SaveProfileNow(ProfileKind.Meta);
|
||||
Check.True(r.Ok, "Save: " + r.Text);
|
||||
|
||||
r = dash.RenameProfile(ProfileKind.Meta, "Run.af");
|
||||
Check.True(r.Ok, "rename: " + r.Text);
|
||||
Check.Eq(s.CurrentMetaPath, Path.Combine(metas, "Run.af"), "Run.af in use");
|
||||
Check.True(dash.MetaFileNames().Contains("Run.af") && !dash.MetaFileNames().Contains("Farm.af"), "the list follows");
|
||||
|
||||
r = dash.DeleteProfile(ProfileKind.Meta);
|
||||
Check.True(r.Ok, "move to Deleted: " + r.Text);
|
||||
Check.Eq(s.CurrentMetaPath, string.Empty, "no meta in use");
|
||||
Check.Eq(s.MetaRules.Count, 0, "unloaded, as picking None");
|
||||
Check.Eq(DeletedFiles(metas).Length, 2, "Farm's old copy and Run");
|
||||
Check.True(File.Exists(Path.Combine(metas, "Copy.af")), "Copy untouched");
|
||||
Check.False(dash.SaveProfileNow(ProfileKind.Meta).Ok, "no file: Save says to use Save As");
|
||||
}
|
||||
|
||||
// ── Loot profiles ────────────────────────────────────────────────────────
|
||||
|
||||
private static void LootProfiles()
|
||||
{
|
||||
string root = Dir("loot");
|
||||
var dash = Dash(root, out var s);
|
||||
string loot = Path.Combine(root, "LootProfiles");
|
||||
|
||||
Check.False(dash.SaveProfileAs(ProfileKind.Loot, "Copy", replace: false).Ok, "no loot profile in use: nothing to copy");
|
||||
|
||||
string snob = Path.Combine(loot, "Snob.utl");
|
||||
VTankLootWriter.Save(new VTankLootProfile(), snob);
|
||||
s.CurrentLootPath = snob;
|
||||
ProfileResult r = dash.SaveProfileAs(ProfileKind.Loot, "Snob Copy.utl", replace: false);
|
||||
Check.True(r.Ok, "Save As copies: " + r.Text);
|
||||
string copy = Path.Combine(loot, "Snob Copy.utl");
|
||||
Check.Eq(s.CurrentLootPath, copy, "the copy is in use");
|
||||
Check.Eq(File.ReadAllText(copy), File.ReadAllText(snob), "the same rules");
|
||||
Check.True(dash.ReadDashboardFiles().Loots.Contains("Snob Copy.utl"), "listed");
|
||||
Check.True(dash.SaveProfileAs(ProfileKind.Loot, "Snob", replace: false).NeedsReplace, "asks before replacing Snob");
|
||||
|
||||
Check.NotNull(dash.NewLootProfilePath("Snob", out _), "New refuses a name taken");
|
||||
Check.Null(dash.NewLootProfilePath("Fresh", out string fresh), "a free name");
|
||||
Check.Eq(fresh, Path.Combine(loot, "Fresh.utl"), "a .utl in LootProfiles");
|
||||
Check.False(File.Exists(fresh), "nothing written (the Loot Editor's Save creates it)");
|
||||
|
||||
r = dash.RenameProfile(ProfileKind.Loot, "Mine");
|
||||
Check.True(r.Ok, "rename: " + r.Text);
|
||||
Check.Eq(s.CurrentLootPath, Path.Combine(loot, "Mine.utl"), "Mine.utl in use");
|
||||
|
||||
r = dash.DeleteProfile(ProfileKind.Loot);
|
||||
Check.True(r.Ok, "move to Deleted: " + r.Text);
|
||||
Check.Eq(s.CurrentLootPath, string.Empty, "no loot profile in use");
|
||||
Check.Eq(s.LootProfileIdx, 0, "the picker shows None");
|
||||
Check.True(DeletedFiles(loot).Single().StartsWith("Mine.", StringComparison.Ordinal), "Mine in LootProfiles\\Deleted");
|
||||
Check.True(File.Exists(snob), "Snob untouched");
|
||||
}
|
||||
|
||||
// ── Buff profiles (the Spells window) ────────────────────────────────────
|
||||
|
||||
private static void BuffDelete()
|
||||
{
|
||||
string root = Dir("buffs");
|
||||
string? previous = BuffProfileStore.FolderOverride;
|
||||
BuffProfileStore.FolderOverride = root;
|
||||
try
|
||||
{
|
||||
string path = BuffProfileStore.PathFor("Mage");
|
||||
BuffProfileStore.Save(new BuffProfile { Name = "Mage" }, path);
|
||||
Check.True(BuffProfileStore.Delete(path), "Delete works");
|
||||
Check.Eq(BuffProfileStore.ListFileNames().Count, 0, "off the list");
|
||||
Check.True(DeletedFiles(root).Single().StartsWith("Mage.", StringComparison.Ordinal), "kept in BuffProfiles\\Deleted");
|
||||
Check.False(BuffProfileStore.Delete(path), "a file that isn't there");
|
||||
}
|
||||
finally { BuffProfileStore.FolderOverride = previous; }
|
||||
}
|
||||
|
||||
// ── The /ra verbs ────────────────────────────────────────────────────────
|
||||
|
||||
private static void CommandsReply()
|
||||
{
|
||||
string root = Dir("commands");
|
||||
var dash = Dash(root, out var s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
|
||||
var plugin = new RynthAiPlugin();
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi });
|
||||
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(plugin, dash);
|
||||
MethodInfo dispatch = typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!;
|
||||
string Ra(string line)
|
||||
{
|
||||
FakeHost.Chat.Clear();
|
||||
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
dispatch.Invoke(plugin, new object[] { parts[1].ToLowerInvariant(), parts, 0 });
|
||||
return string.Join(" / ", FakeHost.Chat);
|
||||
}
|
||||
|
||||
string chat = Ra("/ra nav new Loop");
|
||||
Check.True(chat.Contains("Created new nav 'Loop'"), "/ra nav new: " + chat);
|
||||
chat = Ra("/ra nav rename");
|
||||
Check.True(chat.Contains("needs a name") && chat.Contains("Usage: /ra nav"), "no name: why + usage: " + chat);
|
||||
chat = Ra("/ra nav rename Ring");
|
||||
Check.True(chat.Contains("Renamed Loop.nav to Ring.nav"), "/ra nav rename: " + chat);
|
||||
chat = Ra("/ra nav delete");
|
||||
Check.True(chat.Contains("Moved Ring.nav to NavProfiles\\Deleted"), "/ra nav delete: " + chat);
|
||||
chat = Ra("/ra nav delete");
|
||||
Check.True(chat.Contains("No nav file in use") && chat.Contains("Usage:"), "nothing to move: why + usage: " + chat);
|
||||
|
||||
chat = Ra("/ra meta new Farm");
|
||||
Check.True(chat.Contains("Created new meta 'Farm'"), "/ra meta new: " + chat);
|
||||
File.WriteAllText(Path.Combine(root, "MetaFiles", "Taken.af"), RynthCore.Plugin.RynthAi.Meta.AfFileWriter.BlankMetaText());
|
||||
chat = Ra("/ra meta saveas Taken");
|
||||
Check.True(chat.Contains("commands never replace a file"), "saveas never replaces: " + chat);
|
||||
chat = Ra("/ra meta saveas Night Run");
|
||||
Check.True(chat.Contains("Saved the meta as Night Run.af"), "/ra meta saveas: " + chat);
|
||||
Check.Eq(s.CurrentMetaPath, Path.Combine(root, "MetaFiles", "Night Run.af"), "a name with a space");
|
||||
chat = Ra("/ra meta bogus");
|
||||
Check.True(chat.Contains("Unknown /ra meta verb") && chat.Contains("saveas <name>"), "the usage lists the new verbs: " + chat);
|
||||
|
||||
chat = Ra("/ra loot saveas Copy");
|
||||
Check.True(chat.Contains("No loot profile in use to copy") && chat.Contains("Usage: /ra loot"), "/ra loot saveas: " + chat);
|
||||
chat = Ra("/ra settings rename X");
|
||||
Check.True(chat.Contains("No settings profile file in use") || chat.Contains("Default"), "/ra settings rename before login: " + chat);
|
||||
chat = Ra("/ra settings");
|
||||
Check.True(chat.Contains("Usage: /ra settings") && chat.Contains("saveas"), "/ra settings usage: " + chat);
|
||||
}
|
||||
}
|
||||
|
|
@ -46,6 +46,7 @@ internal static class ProfileLoadTests
|
|||
mutated = null;
|
||||
if (name == nameof(LegacyUiSettings.OffhandDefault)) { mutated = "Shield"; return true; } // must parse as an OffhandMode
|
||||
if (name == nameof(LegacyUiSettings.NavLabelMode)) { mutated = 1; return true; } // NavLabelModes.Clamp: 0..2
|
||||
if (name == nameof(LegacyUiSettings.DfHeightOrder)) { mutated = "LMH"; return true; } // must be one of the six orders
|
||||
if (type == typeof(bool)) { mutated = !(bool)value!; return true; }
|
||||
if (type == typeof(int)) { mutated = (int)value! + 3; return true; } // +3: MovementMode 1/2 map back to 0
|
||||
if (type == typeof(long)) { mutated = (long)value! + 3; return true; }
|
||||
|
|
|
|||
417
Tools/RynthCore.RynthAiHostTests/Tests/TimedCommandsTests.cs
Normal file
417
Tools/RynthCore.RynthAiHostTests/Tests/TimedCommandsTests.cs
Normal file
|
|
@ -0,0 +1,417 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.Huds;
|
||||
using RynthCore.Plugin.RynthAi.TimedCommands;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Timed commands (2026-11-03, players asked for MagTools' periodic commands): chat commands sent every
|
||||
// N seconds (minutes until 2026-11-12; old files are converted), from three lists (this character, this
|
||||
// server, all characters) kept beside the settings profiles. The file format, the folders, when each runs
|
||||
// (first delay, interval, one a second, never in portal space, macro only, no backlog), /ra timed and the
|
||||
// window in the sections manifest (no bar button).
|
||||
internal static class TimedCommandsTests
|
||||
{
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private const long Min = 60_000;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("timed commands: the file round-trips in seconds (version 2); bad values are clamped, missing ones default (on, 600 s)", FileRoundTrip);
|
||||
r.Add("timed commands: an old file in minutes (version 1) loads as seconds (x60) and the next save writes seconds", OldMinutesFile);
|
||||
r.Add("timed commands: the three lists load from the character's, the server's and the base folder, and save only what changed", Folders);
|
||||
r.Add("timed commands: the first run after the first delay (or one interval), then every interval", FirstDelayThenInterval);
|
||||
r.Add("timed commands: every second works (one a second, shared fairly); a 0 typed in the box never means every tick", ShortIntervals);
|
||||
r.Add("timed commands: one a second; never before the world, in portal space or (macro only) with the macro off; no backlog", Gates);
|
||||
r.Add("timed commands: off and empty never run; turned on again it waits a full delay; all three lists run", OffEmptyAndScopes);
|
||||
r.Add("timed commands: the interval text in seconds, with minutes and hours for long ones", EveryText);
|
||||
r.Add("timed commands: /ra timed add, list, off, on, run and remove (each replies) for this character, server and all", ChatCommand);
|
||||
r.Add("timed commands: the window is in the sections manifest without a bar button, only when asked for", Manifest);
|
||||
r.Add("timed commands: the dashboard's options menu entry and /ra timed show|hide open and close the window", WindowToggle);
|
||||
}
|
||||
|
||||
private static readonly List<(string Key, int Mode)> PanelCalls = new();
|
||||
|
||||
[System.Runtime.InteropServices.UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })]
|
||||
private static unsafe int FakeSetPanelOpen(byte* key, int mode)
|
||||
{
|
||||
PanelCalls.Add((System.Runtime.InteropServices.Marshal.PtrToStringUTF8((IntPtr)key) ?? "", mode));
|
||||
return mode == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static unsafe void PanelApi(ref RynthCoreApiNative api)
|
||||
{
|
||||
api.Version = Math.Max(api.Version, 89u);
|
||||
api.SetPanelOpenFn = (IntPtr)(delegate* unmanaged[Cdecl]<byte*, int, int>)&FakeSetPanelOpen;
|
||||
}
|
||||
|
||||
private static void WindowToggle()
|
||||
{
|
||||
try
|
||||
{
|
||||
FakeHost.Reset();
|
||||
PanelCalls.Clear();
|
||||
FakeHost.ConfigureApi = PanelApi;
|
||||
FakeHost.Create(0x50000F77);
|
||||
var p = new RynthAiPlugin();
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
|
||||
|
||||
// What the dashboard's ⋯ > Timed commands runs (queued to the tick by RynthAiPlugin.Dashboard.cs).
|
||||
typeof(RynthAiPlugin).GetMethod("ToggleTimedCommandsWindow", Any)!.Invoke(p, null);
|
||||
Check.Eq(PanelCalls.Count, 1, "one call to the engine");
|
||||
Check.True(PanelCalls[0].Key == RynthAiPlugin.TimedCommandsTitle && PanelCalls[0].Mode == (int)RynthPanelOpen.Toggle,
|
||||
"toggles the Timed Commands window (" + PanelCalls[0] + ")");
|
||||
|
||||
MethodInfo handle = typeof(RynthAiPlugin).GetMethod("HandleTimedCommand", Any)!;
|
||||
string Say(string line)
|
||||
{
|
||||
int before = FakeHost.Chat.Count;
|
||||
handle.Invoke(p, new object[] { line.Split(' ', StringSplitOptions.RemoveEmptyEntries) });
|
||||
return string.Join(" | ", FakeHost.Chat.Skip(before));
|
||||
}
|
||||
Check.True(Say("/ra timed show").Contains("Timed Commands window open"), "/ra timed show opens it");
|
||||
Check.Eq(PanelCalls[^1].Mode, (int)RynthPanelOpen.Open, "with Open");
|
||||
Check.True(Say("/ra timed hide").Contains("Timed Commands window closed"), "/ra timed hide closes it");
|
||||
Check.Eq(PanelCalls[^1].Mode, (int)RynthPanelOpen.Close, "with Close");
|
||||
}
|
||||
finally { FakeHost.ConfigureApi = null; }
|
||||
}
|
||||
|
||||
private static TimedCommandSet Loaded(params (TimedScope Scope, TimedCommand Cmd)[] cmds)
|
||||
{
|
||||
string root = Path.Combine(Path.GetTempPath(), "rynth-timed-" + Guid.NewGuid().ToString("N"));
|
||||
var set = new TimedCommandSet();
|
||||
set.Load(Path.Combine(root, "SettingsProfiles", "Server One", "Hero"));
|
||||
lock (set.Sync)
|
||||
foreach (var (scope, cmd) in cmds) set.List(scope).Add(cmd);
|
||||
return set;
|
||||
}
|
||||
|
||||
/// <summary>A command every <paramref name="seconds"/>, first run <paramref name="first"/> seconds after login.</summary>
|
||||
private static TimedCommand Cmd(string text, int seconds, int first = 0, bool macroOnly = false, bool on = true) =>
|
||||
new() { Command = text, Seconds = seconds, FirstAfter = first, MacroOnly = macroOnly, Enabled = on };
|
||||
|
||||
private static TimedRunState At(long ms, bool inWorld = true, bool portal = false, bool macro = true) =>
|
||||
new(ms, inWorld, portal, macro);
|
||||
|
||||
private static string? Next(TimedCommandScheduler s, TimedCommandSet set, TimedRunState st) =>
|
||||
s.TryNext(set, in st, out string c, out _) ? c : null;
|
||||
|
||||
// ── File ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static void FileRoundTrip()
|
||||
{
|
||||
var list = new List<TimedCommand> { Cmd("/b", 60), Cmd("/ra timed run 2", 1, first: 3, macroOnly: true, on: false) };
|
||||
string json = TimedCommandSet.Serialize(list);
|
||||
using (var doc = System.Text.Json.JsonDocument.Parse(json))
|
||||
{
|
||||
Check.Eq(doc.RootElement.GetProperty("version").GetInt32(), 2, "the file is version 2");
|
||||
var first = doc.RootElement.GetProperty("commands")[0];
|
||||
Check.True(first.GetProperty("seconds").GetInt32() == 60 && first.GetProperty("firstAfterSeconds").GetInt32() == 0,
|
||||
"written as seconds and firstAfterSeconds");
|
||||
Check.False(first.TryGetProperty("minutes", out _) || first.TryGetProperty("firstAfter", out _), "no minutes keys any more");
|
||||
}
|
||||
List<TimedCommand> back = TimedCommandSet.Parse(json);
|
||||
Check.Eq(back.Count, 2, "two commands back");
|
||||
Check.True(back[0].Command == "/b" && back[0].Seconds == 60 && back[0].FirstAfter == 0 && back[0].Enabled && !back[0].MacroOnly, "the first as written");
|
||||
Check.True(back[1].Command == "/ra timed run 2" && back[1].Seconds == 1 && back[1].FirstAfter == 3 && !back[1].Enabled && back[1].MacroOnly,
|
||||
"the second as written (every second, off, macro only, first after 3 s)");
|
||||
|
||||
List<TimedCommand> odd = TimedCommandSet.Parse(
|
||||
"{\"version\":2,\"commands\":[{\"command\":\" /e wave \\n\"},{\"command\":\"/b\",\"seconds\":0,\"firstAfterSeconds\":-5}," +
|
||||
"{\"seconds\":999999,\"firstAfterSeconds\":999999},{\"seconds\":\"x\",\"firstAfterSeconds\":2.6},7]}");
|
||||
Check.Eq(odd.Count, 4, "four objects (a number in the array is skipped)");
|
||||
Check.True(odd[0].Command == "/e wave" && odd[0].Seconds == 600 && odd[0].FirstAfter == 0 && odd[0].Enabled && !odd[0].MacroOnly,
|
||||
"missing fields: every 600 s, on; the text trimmed");
|
||||
Check.True(odd[1].Seconds == TimedCommand.MinSeconds && odd[1].FirstAfter == 0, "too short is 1 s; a negative first delay is 0");
|
||||
Check.True(odd[2].Seconds == TimedCommand.MaxSeconds && odd[2].FirstAfter == TimedCommand.MaxSeconds && odd[2].Command.Length == 0,
|
||||
"too long is a day (86400 s) for both; no command is empty");
|
||||
Check.True(odd[3].Seconds == 600 && odd[3].FirstAfter == 3, "not a number: the default; a fraction rounds to whole seconds");
|
||||
Check.Eq(TimedCommandSet.Parse("[1,2]").Count, 0, "not an object: nothing");
|
||||
Check.Eq(TimedCommand.CleanCommand(new string('x', 300)).Length, TimedCommand.MaxLength, "a command is cut at 200 characters");
|
||||
Check.Eq(new TimedCommand().Seconds, 600, "a new command: every 600 s");
|
||||
}
|
||||
|
||||
private static void OldMinutesFile()
|
||||
{
|
||||
List<TimedCommand> old = TimedCommandSet.Parse(
|
||||
"{\"version\":1,\"commands\":[{\"command\":\"/b\",\"minutes\":10,\"firstAfter\":2,\"enabled\":true,\"macroOnly\":false}," +
|
||||
"{\"command\":\"/q\",\"minutes\":0.25,\"firstAfter\":0},{\"command\":\"/d\",\"minutes\":1440,\"firstAfter\":0.5},{\"command\":\"/t\",\"minutes\":0.01}]}");
|
||||
Check.Eq(old.Count, 4, "four old commands");
|
||||
Check.True(old[0].Seconds == 600 && old[0].FirstAfter == 120, "10 min, first after 2 -> 600 s, first after 120 s");
|
||||
Check.True(old[1].Seconds == 15 && old[1].FirstAfter == 0, "0.25 min -> 15 s");
|
||||
Check.True(old[2].Seconds == 86400 && old[2].FirstAfter == 30, "a day -> 86400 s; first after 0.5 min -> 30 s");
|
||||
Check.Eq(old[3].Seconds, 1, "0.01 min (0.6 s) -> 1 s, the shortest");
|
||||
|
||||
List<TimedCommand> both = TimedCommandSet.Parse("{\"commands\":[{\"command\":\"/b\",\"seconds\":45,\"minutes\":10,\"firstAfterSeconds\":5,\"firstAfter\":3}]}");
|
||||
Check.True(both[0].Seconds == 45 && both[0].FirstAfter == 5, "with both keys the seconds win");
|
||||
|
||||
string root = Path.Combine(Path.GetTempPath(), "rynth-timed-" + Guid.NewGuid().ToString("N"));
|
||||
string hero = Path.Combine(root, "SettingsProfiles", "Server One", "Hero");
|
||||
Directory.CreateDirectory(hero);
|
||||
try
|
||||
{
|
||||
string file = Path.Combine(hero, TimedCommandSet.FileName);
|
||||
File.WriteAllText(file, "{\"version\":1,\"commands\":[{\"command\":\"/b\",\"minutes\":5,\"firstAfter\":1,\"enabled\":true,\"macroOnly\":true}]}");
|
||||
var set = new TimedCommandSet();
|
||||
set.Load(hero);
|
||||
lock (set.Sync)
|
||||
{
|
||||
TimedCommand c = set.List(TimedScope.Character).Single();
|
||||
Check.True(c.Seconds == 300 && c.FirstAfter == 60 && c.MacroOnly, "loaded from the old file as 300 s, first after 60 s");
|
||||
set.MarkChanged(TimedScope.Character, 1);
|
||||
}
|
||||
set.SaveDirty();
|
||||
string saved = File.ReadAllText(file);
|
||||
Check.True(saved.Contains("\"version\": 2") && saved.Contains("\"seconds\": 300") && saved.Contains("\"firstAfterSeconds\": 60"),
|
||||
"the next save writes version 2 in seconds (" + saved.Replace('\n', ' ') + ")");
|
||||
Check.False(saved.Contains("\"minutes\""), "and no minutes key");
|
||||
var again = new TimedCommandSet();
|
||||
again.Load(hero);
|
||||
lock (again.Sync) Check.Eq(again.List(TimedScope.Character).Single().Seconds, 300, "read back: still 300 s (not converted twice)");
|
||||
}
|
||||
finally { try { Directory.Delete(root, true); } catch { } }
|
||||
}
|
||||
|
||||
private static void Folders()
|
||||
{
|
||||
string root = Path.Combine(Path.GetTempPath(), "rynth-timed-" + Guid.NewGuid().ToString("N"));
|
||||
string baseDir = Path.Combine(root, "SettingsProfiles"), server = Path.Combine(baseDir, "Server One"), hero = Path.Combine(server, "Hero");
|
||||
Directory.CreateDirectory(hero);
|
||||
try
|
||||
{
|
||||
File.WriteAllText(Path.Combine(hero, TimedCommandSet.FileName), TimedCommandSet.Serialize(new[] { Cmd("/hero", 300) }));
|
||||
File.WriteAllText(Path.Combine(server, TimedCommandSet.FileName), TimedCommandSet.Serialize(new[] { Cmd("/server", 360), Cmd("/server2", 420) }));
|
||||
File.WriteAllText(Path.Combine(baseDir, TimedCommandSet.FileName), TimedCommandSet.Serialize(new[] { Cmd("/all", 480) }));
|
||||
var set = new TimedCommandSet();
|
||||
var problems = new List<string>();
|
||||
set.Load(hero, problems);
|
||||
Check.Eq(problems.Count, 0, "no problems");
|
||||
Check.True(set.Loaded && set.Character == "Hero" && set.Server == "Server One", "the character and server from the folders");
|
||||
lock (set.Sync)
|
||||
{
|
||||
Check.Eq(set.List(TimedScope.Character).Single().Command, "/hero", "this character's list");
|
||||
Check.Eq(string.Join(",", set.List(TimedScope.Server).Select(c => c.Command)), "/server,/server2", "the server's list");
|
||||
Check.Eq(set.List(TimedScope.All).Single().Command, "/all", "every character's list");
|
||||
set.List(TimedScope.Server).RemoveAt(0);
|
||||
set.MarkChanged(TimedScope.Server, 1);
|
||||
}
|
||||
DateTime heroTime = File.GetLastWriteTimeUtc(Path.Combine(hero, TimedCommandSet.FileName));
|
||||
set.SaveDirty();
|
||||
Check.False(set.AnyDirty, "saved");
|
||||
Check.Eq(TimedCommandSet.Parse(File.ReadAllText(Path.Combine(server, TimedCommandSet.FileName))).Single().Command, "/server2", "the server file has the edit");
|
||||
Check.Eq(File.GetLastWriteTimeUtc(Path.Combine(hero, TimedCommandSet.FileName)), heroTime, "the character's file is untouched");
|
||||
|
||||
var other = new TimedCommandSet();
|
||||
other.Load(Path.Combine(server, "Sidekick"));
|
||||
lock (other.Sync)
|
||||
{
|
||||
Check.Eq(other.List(TimedScope.Character).Count, 0, "another character: its own (empty) list");
|
||||
Check.Eq(other.List(TimedScope.Server).Single().Command, "/server2", "the same server list");
|
||||
Check.Eq(other.List(TimedScope.All).Single().Command, "/all", "the same all-characters list");
|
||||
}
|
||||
|
||||
File.WriteAllText(Path.Combine(baseDir, TimedCommandSet.FileName), "{ not json");
|
||||
var broken = new TimedCommandSet();
|
||||
broken.Load(hero, problems);
|
||||
Check.True(problems.Count == 1 && problems[0].Contains("all characters"), "a broken file is reported, by its list");
|
||||
lock (broken.Sync) Check.Eq(broken.List(TimedScope.Character).Count, 1, "the other lists still load");
|
||||
broken.Unload();
|
||||
Check.False(broken.Loaded, "unloaded at logout");
|
||||
}
|
||||
finally { try { Directory.Delete(root, true); } catch { } }
|
||||
}
|
||||
|
||||
// ── Scheduler ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void FirstDelayThenInterval()
|
||||
{
|
||||
var set = Loaded((TimedScope.Character, Cmd("/b", 60)), (TimedScope.Character, Cmd("/hello", 600, first: 120)));
|
||||
var s = new TimedCommandScheduler();
|
||||
const long t0 = 1_000_000;
|
||||
s.OnLogin(set, t0);
|
||||
Check.Eq(Next(s, set, At(t0)), null, "nothing at login");
|
||||
Check.Eq(Next(s, set, At(t0 + Min - 1)), null, "the 1-minute one: not before a minute");
|
||||
Check.Eq(Next(s, set, At(t0 + Min)), "/b", "the 1-minute one at a minute");
|
||||
Check.Eq(Next(s, set, At(t0 + 2 * Min - 1)), null, "then not before the next minute");
|
||||
Check.Eq(Next(s, set, At(t0 + 2 * Min)), "/b", "at two minutes: /b first (it was due first in the list)");
|
||||
Check.Eq(Next(s, set, At(t0 + 2 * Min + 500)), null, "the first-after-2 one waits a second after it");
|
||||
Check.Eq(Next(s, set, At(t0 + 2 * Min + 1000)), "/hello", "then the one with First after 2");
|
||||
Check.Eq(Next(s, set, At(t0 + 11 * Min)), "/b", "the 1-minute one again (once, no backlog of nine)");
|
||||
Check.Eq(Next(s, set, At(t0 + 11 * Min + 1000)), null, "nothing piled up behind it");
|
||||
Check.Eq(Next(s, set, At(t0 + 12 * Min + 1000)), "/b", "both due: the one that waited longest first (/b, due at 12:00)");
|
||||
Check.Eq(Next(s, set, At(t0 + 12 * Min + 2000)), "/hello", "/hello every 10 minutes from its first run");
|
||||
|
||||
var sec = Loaded((TimedScope.Character, Cmd("/s", 7, first: 3)));
|
||||
var s2 = new TimedCommandScheduler();
|
||||
s2.OnLogin(sec, 0);
|
||||
Check.Eq(Next(s2, sec, At(2999)), null, "first after 3 s: not at 2.999 s");
|
||||
Check.Eq(Next(s2, sec, At(3000)), "/s", "at 3 s");
|
||||
Check.Eq(Next(s2, sec, At(9999)), null, "every 7 s: not at 9.999 s");
|
||||
Check.Eq(Next(s2, sec, At(10_000)), "/s", "at 10 s");
|
||||
}
|
||||
|
||||
private static void ShortIntervals()
|
||||
{
|
||||
var set = Loaded((TimedScope.Character, Cmd("/a", 1)), (TimedScope.Character, Cmd("/b", 1)));
|
||||
var s = new TimedCommandScheduler();
|
||||
s.OnLogin(set, 0);
|
||||
var sent = new List<string>();
|
||||
for (long t = 0; t <= 6000; t += 100)
|
||||
if (Next(s, set, At(t)) is { } c) sent.Add(t + ":" + c);
|
||||
Check.Eq(string.Join(",", sent), "1000:/a,2000:/b,3000:/a,4000:/b,5000:/a,6000:/b",
|
||||
"two every-second commands: one a second between them, taking turns");
|
||||
|
||||
TimedCommand typing = Cmd("/t", 600);
|
||||
var one = Loaded((TimedScope.Character, typing));
|
||||
var s3 = new TimedCommandScheduler();
|
||||
s3.OnLogin(one, 0);
|
||||
lock (one.Sync) { typing.Seconds = 0; typing.NextDueMs = 0; } // the box mid-edit (cleared, not left yet)
|
||||
Check.Eq(Next(s3, one, At(500)), null, "a 0 in the box is treated as 1 s, not every tick");
|
||||
Check.Eq(Next(s3, one, At(1500)), "/t", "it goes at 1 s");
|
||||
Check.Eq(Next(s3, one, At(2000)), null, "and not again at once");
|
||||
Check.Eq(TimedCommandScheduler.IntervalMs(Cmd("/x", 86400)), 86_400_000L, "a day in ms");
|
||||
}
|
||||
|
||||
private static void EveryText()
|
||||
{
|
||||
Check.Eq(Cmd("/x", 30).EveryText(), "every 30 s", "under a minute: seconds only");
|
||||
Check.Eq(Cmd("/x", 60).EveryText(), "every 60 s (1 min)", "a minute");
|
||||
Check.Eq(Cmd("/x", 90).EveryText(), "every 90 s (1 min 30 s)", "a minute and a half");
|
||||
Check.Eq(Cmd("/x", 600).EveryText(), "every 600 s (10 min)", "ten minutes");
|
||||
Check.Eq(Cmd("/x", 5400).EveryText(), "every 5400 s (1 h 30 min)", "an hour and a half");
|
||||
Check.Eq(Cmd("/x", 86400).EveryText(), "every 86400 s (24 h)", "a day");
|
||||
Check.Eq(TimedCommand.Duration(1), "1 s", "Duration: one second");
|
||||
}
|
||||
|
||||
private static void Gates()
|
||||
{
|
||||
var set = Loaded((TimedScope.Character, Cmd("/b", 60)), (TimedScope.Character, Cmd("/macro", 60, macroOnly: true)));
|
||||
var s = new TimedCommandScheduler();
|
||||
s.OnLogin(set, 0);
|
||||
Check.Eq(Next(s, set, At(Min, inWorld: false)), null, "not in the world: nothing");
|
||||
Check.Eq(Next(s, set, At(Min, portal: true, macro: false)), null, "in portal space: nothing");
|
||||
Check.Eq(Next(s, set, At(30 * Min, macro: false)), "/b", "out of the portal (half an hour later): /b once");
|
||||
Check.Eq(Next(s, set, At(30 * Min + 2000, macro: false)), null, "the macro-only one waits while the macro is stopped, and /b is not due");
|
||||
Check.Eq(Next(s, set, At(30 * Min + 3000, macro: true)), "/macro", "the macro starts: it goes");
|
||||
Check.Eq(Next(s, set, At(30 * Min + 3500)), null, "nothing more");
|
||||
Check.Eq(Next(s, set, At(31 * Min)), "/b", "/b a minute after its last run");
|
||||
|
||||
var empty = new TimedCommandSet();
|
||||
Check.Eq(Next(s, empty, At(99 * Min)), null, "no lists loaded (before the settings folder is known): nothing");
|
||||
}
|
||||
|
||||
private static void OffEmptyAndScopes()
|
||||
{
|
||||
TimedCommand off = Cmd("/off", 60, on: false), blank = Cmd("", 60);
|
||||
var set = Loaded((TimedScope.Character, off), (TimedScope.Character, blank),
|
||||
(TimedScope.Server, Cmd("/server", 60)), (TimedScope.All, Cmd("/all", 60)));
|
||||
var s = new TimedCommandScheduler();
|
||||
s.OnLogin(set, 0);
|
||||
var sent = new List<string>();
|
||||
for (long t = Min; t < Min + 5000; t += 250)
|
||||
if (Next(s, set, At(t)) is { } c) sent.Add(c);
|
||||
Check.Eq(string.Join(",", sent), "/server,/all", "the server's and every character's lists run; off and empty don't");
|
||||
lock (set.Sync)
|
||||
{
|
||||
set.List(TimedScope.Server)[0].Enabled = false; // out of the way of the next checks
|
||||
set.List(TimedScope.All)[0].Enabled = false;
|
||||
off.Enabled = true;
|
||||
}
|
||||
Check.Eq(Next(s, set, At(5 * Min)), null, "turned on at 5 min: it starts a full interval from now");
|
||||
Check.Eq(Next(s, set, At(6 * Min)), "/off", "a minute later it runs");
|
||||
Check.Eq(TimedCommandScheduler.NextText(Cmd("/x", 300, macroOnly: true), 0, macroRunning: false), "waits for the macro", "the window's Next: waiting for the macro");
|
||||
TimedCommand due = Cmd("/x", 300);
|
||||
due.NextDueMs = 1000 + 90_000;
|
||||
Check.Eq(TimedCommandScheduler.NextText(due, 1000, true), "in 1:30", "the window's Next: in m:ss");
|
||||
}
|
||||
|
||||
// ── /ra timed ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void ChatCommand()
|
||||
{
|
||||
string root = Path.Combine(Path.GetTempPath(), "rynth-timed-" + Guid.NewGuid().ToString("N"));
|
||||
try
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.Create(0x50000F77);
|
||||
var p = new RynthAiPlugin();
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
|
||||
var set = (TimedCommandSet)typeof(RynthAiPlugin).GetField("_timed", Any)!.GetValue(p)!;
|
||||
MethodInfo handle = typeof(RynthAiPlugin).GetMethod("HandleTimedCommand", Any)!;
|
||||
string Say(string line)
|
||||
{
|
||||
int before = FakeHost.Chat.Count;
|
||||
handle.Invoke(p, new object[] { line.Split(' ', StringSplitOptions.RemoveEmptyEntries) });
|
||||
return string.Join(" | ", FakeHost.Chat.Skip(before));
|
||||
}
|
||||
|
||||
Check.True(Say("/ra timed list").Contains("load once you are in the world"), "before the lists load: it says why");
|
||||
set.Load(Path.Combine(root, "SettingsProfiles", "Server One", "Hero"));
|
||||
|
||||
Check.True(Say("/ra timed list").Contains("No timed commands for this character"), "an empty list says so");
|
||||
string add = Say("/ra timed add 300 /e waves hello");
|
||||
Check.True(add.Contains("Timed command 1 for this character: /e waves hello - every 300 s (5 min), first in 300 s (5 min)"),
|
||||
"add replies with the command, in seconds (" + add + ")");
|
||||
lock (set.Sync) Check.Eq(set.List(TimedScope.Character)[0].Seconds, 300, "add takes seconds");
|
||||
Check.True(File.Exists(Path.Combine(root, "SettingsProfiles", "Server One", "Hero", TimedCommandSet.FileName)), "and saves the character's file");
|
||||
Check.True(Say("/ra timed server add 30 /b").Contains("for this server: /b - every 30 s"), "server add (30 s)");
|
||||
Check.True(File.Exists(Path.Combine(root, "SettingsProfiles", "Server One", TimedCommandSet.FileName)), "saved in the server's folder");
|
||||
Check.True(Say("/ra timed all add 3600 /ra status").Contains("for all characters: /ra status - every 3600 s (1 h)"), "all add (an hour)");
|
||||
Check.True(File.Exists(Path.Combine(root, "SettingsProfiles", TimedCommandSet.FileName)), "saved in the base folder");
|
||||
Check.True(Say("/ra timed add 1 /e nod").Contains("every 1 s"), "every second is allowed");
|
||||
Check.True(Say("/ra timed remove 2").Contains("Removed timed command 2"), "(removed again)");
|
||||
|
||||
string list = Say("/ra timed list");
|
||||
Check.True(list.Contains("Timed commands for this character (1)") && list.Contains("1. /e waves hello - every 300 s (5 min)"), "list shows it (" + list + ")");
|
||||
Check.True(Say("/ra timed off 1").Contains("Timed command 1 for this character off: /e waves hello"), "off replies");
|
||||
lock (set.Sync) Check.False(set.List(TimedScope.Character)[0].Enabled, "and it is off");
|
||||
Check.True(Say("/ra timed list").Contains("off"), "list says off");
|
||||
Check.True(Say("/ra timed on 1").Contains("on: /e waves hello"), "on replies");
|
||||
Check.True(Say("/ra timed off 7").Contains("There is no timed command 7"), "a number past the list says so");
|
||||
Check.True(Say("/ra timed add x /b").Contains("Usage: /ra timed add <seconds 1-86400>"), "a bad interval gives the usage");
|
||||
Check.True(Say("/ra timed add 0 /b").Contains("Usage: /ra timed add <seconds"), "0 s is too short");
|
||||
Check.True(Say("/ra timed add 86401 /b").Contains("Usage: /ra timed add <seconds"), "over a day is too long");
|
||||
Check.True(Say("/ra timed add 0.5 /b").Contains("Usage: /ra timed add <seconds"), "whole seconds only");
|
||||
lock (set.Sync) Check.Eq(set.List(TimedScope.Character).Count, 1, "none of those added anything");
|
||||
Check.True(Say("/ra timed add 5").Contains("Usage"), "no command gives the usage");
|
||||
Check.True(Say("/ra timed frob").Contains("Usage: /ra timed"), "an unknown word gives the usage");
|
||||
|
||||
FakeHost.ChatCommands.Clear();
|
||||
string run = Say("/ra timed run 1");
|
||||
Check.True(run.Contains("Ran timed command 1 for this character: /e waves hello"), "run replies");
|
||||
Check.True(FakeHost.ChatCommands.Contains("/e waves hello"), "and the command went to the chat parser (" + string.Join(",", FakeHost.ChatCommands) + ")");
|
||||
|
||||
Check.True(Say("/ra timed server remove 1").Contains("Removed timed command 1 for this server: /b"), "remove replies");
|
||||
lock (set.Sync) Check.Eq(set.List(TimedScope.Server).Count, 0, "and it is gone");
|
||||
Check.True(Say("/ra timed show").Length > 0, "show replies (either way)");
|
||||
}
|
||||
finally { try { Directory.Delete(root, true); } catch { } }
|
||||
}
|
||||
|
||||
private static void Manifest()
|
||||
{
|
||||
string without = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections);
|
||||
Check.False(without.Contains("timedcommands"), "not asked for: not there");
|
||||
string with = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, timedCommands: true);
|
||||
using var doc = System.Text.Json.JsonDocument.Parse(with);
|
||||
var win = doc.RootElement.GetProperty("windows").EnumerateArray().Single();
|
||||
Check.Eq(win.GetProperty("id").GetString(), "timedcommands", "the window's id");
|
||||
Check.Eq(win.GetProperty("title").GetString(), RynthAiPlugin.TimedCommandsTitle, "its title");
|
||||
Check.Eq(win.GetProperty("surface").GetString(), RynthAiPlugin.TimedCommandsSurface, "its surface");
|
||||
Check.False(win.GetProperty("bar").GetBoolean(), "no bar button (the dashboard's options menu and /ra timed show open it)");
|
||||
Check.False(win.TryGetProperty("barMenu", out _), "and no bar menu");
|
||||
Check.True(win.GetProperty("icon").GetString()!.Length > 0, "an icon for its header");
|
||||
string both = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, monsterStats: true, timedCommands: true);
|
||||
using var doc2 = System.Text.Json.JsonDocument.Parse(both);
|
||||
Check.Eq(doc2.RootElement.GetProperty("windows").GetArrayLength(), 2, "with Monster Stats too: both windows");
|
||||
}
|
||||
}
|
||||
|
|
@ -17,10 +17,14 @@ internal static class Program
|
|||
NavRouteParserTests.Register(runner);
|
||||
NavFormatTests.Register(runner);
|
||||
CombatStallWatchdogTests.Register(runner);
|
||||
DirtyFightingHeightTests.Register(runner);
|
||||
CreatureWeaknessTests.Register(runner);
|
||||
MonsterDamageTierTests.Register(runner);
|
||||
LootBaselineTests.Register(runner);
|
||||
ChatClassifierTests.Register(runner);
|
||||
BuffItemPickerTests.Register(runner);
|
||||
GearActivationTests.Register(runner);
|
||||
ItemInfoPartColorsTests.Register(runner);
|
||||
return runner.Run("RynthAi tests", args.Length > 0 ? args[0] : null);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,10 @@
|
|||
<!-- Combat: the melee/missile stall ladder (pure timing state, time passed in). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Combat\CombatStallWatchdog.cs" Link="Linked\CombatStallWatchdog.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Combat\PointBlankFacing.cs" Link="Linked\PointBlankFacing.cs" />
|
||||
<!-- Buff items: which buff item to use now, and the list edits (System only). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Combat\BuffItemPicker.cs" Link="Linked\BuffItemPicker.cs" />
|
||||
<!-- Combat: the Dirty Fighting rotation's height choice and landing-line parser (System only). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Combat\DirtyFightingHeights.cs" Link="Linked\DirtyFightingHeights.cs" />
|
||||
<!-- Weapon weakness selection: element ranking per monster. Its only outside reference is
|
||||
CreatureProfileStore.Folder (the user override folder), faked in Fakes\. -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\CreatureData\CreatureWeakness.cs" Link="Linked\CreatureWeakness.cs" />
|
||||
|
|
@ -31,8 +35,12 @@
|
|||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\CreatureData\ShieldFacing.cs" Link="Linked\ShieldFacing.cs" />
|
||||
<!-- Loot: the measured loot-timer baseline and its [LootSettings] log line. -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\LootBaseline.cs" Link="Linked\LootBaseline.cs" />
|
||||
<!-- Active Gear: is a worn item's magic on, and its mana's time left (System only). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\ActiveGear\GearActivation.cs" Link="Linked\GearActivation.cs" />
|
||||
<!-- RynthChat: the channel classifier (no dependencies). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthChat\ChatClassifier.cs" Link="Linked\ChatClassifier.cs" />
|
||||
<!-- Item info: per-part colours of the one-line layout (System only). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\ItemInfo\ItemInfoPartColors.cs" Link="Linked\ItemInfoPartColors.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
249
Tools/RynthCore.RynthAiTests/Tests/BuffItemPickerTests.cs
Normal file
249
Tools/RynthCore.RynthAiTests/Tests/BuffItemPickerTests.cs
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiTests.Tests;
|
||||
|
||||
// Buff items (Combat/BuffItemPicker.cs): which item buffing uses now. The built-ins can be blocked,
|
||||
// the player's own items are matched by their spells or, with none to check, a repeat time; only
|
||||
// items in the pack are picked; never the same item within 15 s; two uses whose buff never showed
|
||||
// rest the item 10 minutes. Times are passed in.
|
||||
internal static class BuffItemPickerTests
|
||||
{
|
||||
private static readonly DateTime T0 = new(2026, 11, 11, 12, 0, 0, DateTimeKind.Local);
|
||||
private static readonly DateTime U0 = new(2026, 11, 11, 18, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly HashSet<uint> NoBuffs = new();
|
||||
|
||||
private const uint Benediction = 3810, LesserBenediction = 4024, Favor = 3811, CustomSpell = 6123;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("buff items: a built-in whose buff is off is used, one that is on is not", BuiltInOnOff);
|
||||
r.Add("buff items: a blocked built-in is never used, the next item is", BlockedBuiltIn);
|
||||
r.Add("buff items: a custom item is matched by its spells (buff on / off)", CustomBuffOnOff);
|
||||
r.Add("buff items: an item not in the pack is never picked", MissingFromPack);
|
||||
r.Add("buff items: no spell to check - the repeat timer, kept across reloads", FallbackTimer);
|
||||
r.Add("buff items: a custom item whose spells aren't read yet waits", SpellsNotReadWait);
|
||||
r.Add("buff items: 15 s between uses of one item, the other Benediction counts as used", RetryGuardAndShared);
|
||||
r.Add("buff items: two uses whose buff never showed rest the item 10 min", RestAfterTwoUses);
|
||||
r.Add("buff items: allow / block / add / remove make new lists", ListEdits);
|
||||
r.Add("buff items: what the list says for each line", Describe);
|
||||
}
|
||||
|
||||
private static List<BuffItemInPack> Pack(params (int Id, string Name)[] items)
|
||||
{
|
||||
var p = new List<BuffItemInPack>();
|
||||
foreach (var (id, name) in items) p.Add(new BuffItemInPack(id, name));
|
||||
return p;
|
||||
}
|
||||
|
||||
private static HashSet<uint> On(params uint[] ids) => new(ids);
|
||||
|
||||
private static CustomBuffItem Custom(string name, uint[]? spells, int repeat = 60, bool allowed = true) => new()
|
||||
{
|
||||
Name = name,
|
||||
Allowed = allowed,
|
||||
SpellIds = spells != null ? new List<uint>(spells) : new List<uint>(),
|
||||
SpellsRead = spells != null,
|
||||
RepeatMinutes = repeat,
|
||||
};
|
||||
|
||||
private static void BuiltInOnOff()
|
||||
{
|
||||
var entries = BuffItemEntry.Build(null, null);
|
||||
Check.Eq(entries.Count, 3, "three built-ins");
|
||||
var pick = new BuffItemPicker().Choose(entries, Pack((7, "Blackmoor's Favor")), NoBuffs, T0, U0);
|
||||
Check.True(pick is { ItemId: 7 }, "Favor's buff is off: use it");
|
||||
Check.True(pick?.Entry.BuiltIn == true, "the built-in line");
|
||||
|
||||
var none = new BuffItemPicker().Choose(entries, Pack((7, "Blackmoor's Favor")), On(Favor), T0, U0);
|
||||
Check.Null(none, "Favor's buff is on: nothing");
|
||||
var lesser = new BuffItemPicker().Choose(entries, Pack((8, "asheron's lesser benediction")), On(Benediction), T0, U0);
|
||||
Check.Null(lesser, "the Lesser Benediction counts as on with the full one's spell (and names match without case)");
|
||||
}
|
||||
|
||||
private static void BlockedBuiltIn()
|
||||
{
|
||||
var entries = BuffItemEntry.Build(new List<string> { "Asheron's Benediction" }, null);
|
||||
var pack = Pack((1, "Asheron's Benediction"), (2, "Blackmoor's Favor"));
|
||||
var pick = new BuffItemPicker().Choose(entries, pack, NoBuffs, T0, U0);
|
||||
Check.True(pick is { ItemId: 2 }, "the blocked Benediction is skipped, Favor goes");
|
||||
|
||||
var onlyBlocked = new BuffItemPicker().Choose(entries, Pack((1, "Asheron's Benediction")), NoBuffs, T0, U0);
|
||||
Check.Null(onlyBlocked, "only the blocked one in the pack: nothing");
|
||||
Check.False(BuffItemEntry.Find(entries, "asheron's benediction")!.Allowed, "listed, not allowed");
|
||||
}
|
||||
|
||||
private static void CustomBuffOnOff()
|
||||
{
|
||||
var customs = new List<CustomBuffItem> { Custom("Elixir of the Hunt", new[] { CustomSpell }) };
|
||||
var entries = BuffItemEntry.Build(null, customs);
|
||||
var pack = Pack((5, "Elixir of the Hunt"));
|
||||
var pick = new BuffItemPicker().Choose(entries, pack, NoBuffs, T0, U0);
|
||||
Check.True(pick is { ItemId: 5 }, "its spell isn't on: use it");
|
||||
Check.True(pick?.Entry.Custom == customs[0], "the custom line");
|
||||
Check.Null(new BuffItemPicker().Choose(entries, pack, On(CustomSpell), T0, U0), "its spell is on: nothing");
|
||||
Check.True(new BuffItemPicker().Choose(entries, pack, On(CustomSpell + 1), T0, U0) is { ItemId: 5 }, "another spell on: still used");
|
||||
|
||||
customs[0].Allowed = false;
|
||||
Check.Null(new BuffItemPicker().Choose(BuffItemEntry.Build(null, customs), pack, NoBuffs, T0, U0), "a blocked custom item: nothing");
|
||||
}
|
||||
|
||||
private static void MissingFromPack()
|
||||
{
|
||||
var customs = new List<CustomBuffItem> { Custom("Elixir of the Hunt", new[] { CustomSpell }), Custom("Timer Gem", Array.Empty<uint>()) };
|
||||
var entries = BuffItemEntry.Build(null, customs);
|
||||
Check.Null(new BuffItemPicker().Choose(entries, Pack(), NoBuffs, T0, U0), "an empty pack: nothing");
|
||||
Check.Null(new BuffItemPicker().Choose(entries, Pack((9, "Mana Potion"), (10, "Elixir of the Hunter")), NoBuffs, T0, U0),
|
||||
"only other items (a longer name doesn't match): nothing");
|
||||
var pick = new BuffItemPicker().Choose(entries, Pack((9, "Mana Potion"), (11, "Timer Gem")), NoBuffs, T0, U0);
|
||||
Check.True(pick is { ItemId: 11 }, "the one that is in the pack goes");
|
||||
}
|
||||
|
||||
private static void FallbackTimer()
|
||||
{
|
||||
var gem = Custom("Timer Gem", Array.Empty<uint>(), repeat: 30);
|
||||
var customs = new List<CustomBuffItem> { gem };
|
||||
var entries = BuffItemEntry.Build(null, customs);
|
||||
var pack = Pack((3, "Timer Gem"));
|
||||
var picker = new BuffItemPicker();
|
||||
|
||||
Check.True(entries[3].UsesTimer, "no spell to check: the timer");
|
||||
var first = picker.Choose(entries, pack, On(Favor, CustomSpell), T0, U0);
|
||||
Check.True(first is { ItemId: 3 }, "never used: used now, whatever buffs are on");
|
||||
picker.NoteUsed(first!.Value, entries, T0, U0);
|
||||
Check.Eq(gem.LastUsedUtc, (DateTime?)U0, "the use is kept on the item (saved with the profile)");
|
||||
|
||||
Check.Null(picker.Choose(entries, pack, NoBuffs, T0.AddMinutes(29), U0.AddMinutes(29)), "29 min later: not yet");
|
||||
Check.True(picker.Choose(entries, pack, NoBuffs, T0.AddMinutes(30), U0.AddMinutes(30)) is { ItemId: 3 }, "30 min later: due");
|
||||
|
||||
// A reload: a new picker, the item's saved last use still counts.
|
||||
var reloaded = new BuffItemPicker();
|
||||
var entries2 = BuffItemEntry.Build(null, customs);
|
||||
Check.Null(reloaded.Choose(entries2, pack, NoBuffs, T0.AddMinutes(5), U0.AddMinutes(5)), "after a reload the timer still runs (5 min in)");
|
||||
|
||||
// A use that didn't go out doesn't start the timer.
|
||||
var gem2 = Custom("Other Gem", Array.Empty<uint>(), repeat: 30);
|
||||
var e3 = BuffItemEntry.Build(null, new List<CustomBuffItem> { gem2 });
|
||||
var p3 = new BuffItemPicker();
|
||||
var c3 = p3.Choose(e3, Pack((4, "Other Gem")), NoBuffs, T0, U0);
|
||||
p3.NoteUsed(c3!.Value, e3, T0, U0, sent: false);
|
||||
Check.Null(gem2.LastUsedUtc, "not sent: no last use");
|
||||
Check.Null(p3.Choose(e3, Pack((4, "Other Gem")), NoBuffs, T0.AddSeconds(10), U0.AddSeconds(10)), "but not again within 15 s");
|
||||
Check.True(p3.Choose(e3, Pack((4, "Other Gem")), NoBuffs, T0.AddSeconds(16), U0.AddSeconds(16)) is { ItemId: 4 }, "tried again after 15 s");
|
||||
|
||||
Check.Eq(BuffItemRules.ClampRepeatMinutes(0), 1, "repeat at least 1 min");
|
||||
Check.Eq(BuffItemRules.ClampRepeatMinutes(1_000_000), BuffItemRules.MaxRepeatMinutes, "and at most a week");
|
||||
}
|
||||
|
||||
private static void SpellsNotReadWait()
|
||||
{
|
||||
var byName = Custom("Unknown Potion", null);
|
||||
var entries = BuffItemEntry.Build(null, new List<CustomBuffItem> { byName });
|
||||
Check.False(entries[3].SpellsKnown, "added by name: spells not read");
|
||||
Check.Null(new BuffItemPicker().Choose(entries, Pack((6, "Unknown Potion")), NoBuffs, T0, U0),
|
||||
"not read yet: not used (no use on a guess)");
|
||||
}
|
||||
|
||||
private static void RetryGuardAndShared()
|
||||
{
|
||||
var entries = BuffItemEntry.Build(null, null);
|
||||
var pack = Pack((1, "Asheron's Benediction"), (2, "Asheron's Lesser Benediction"));
|
||||
var picker = new BuffItemPicker();
|
||||
var c = picker.Choose(entries, pack, NoBuffs, T0, U0);
|
||||
Check.True(c is { ItemId: 1 }, "the first in the pack");
|
||||
picker.NoteUsed(c!.Value, entries, T0, U0);
|
||||
Check.Null(picker.Choose(entries, pack, NoBuffs, T0.AddSeconds(14), U0.AddSeconds(14)),
|
||||
"14 s later: neither (the Lesser shares the spell, so it counts as used too)");
|
||||
Check.True(picker.Choose(entries, pack, NoBuffs, T0.AddSeconds(15), U0.AddSeconds(15)) is { ItemId: 1 }, "15 s later: again");
|
||||
|
||||
var withFavor = Pack((1, "Asheron's Benediction"), (3, "Blackmoor's Favor"));
|
||||
var p2 = new BuffItemPicker();
|
||||
p2.NoteUsed(p2.Choose(entries, withFavor, NoBuffs, T0, U0)!.Value, entries, T0, U0);
|
||||
Check.True(p2.Choose(entries, withFavor, NoBuffs, T0.AddSeconds(3), U0.AddSeconds(3)) is { ItemId: 3 },
|
||||
"another buff's item isn't held by it (Favor next check)");
|
||||
}
|
||||
|
||||
private static void RestAfterTwoUses()
|
||||
{
|
||||
var potion = Custom("Potion of Might", new[] { CustomSpell });
|
||||
var entries = BuffItemEntry.Build(null, new List<CustomBuffItem> { potion });
|
||||
var pack = Pack((5, "Potion of Might"));
|
||||
var picker = new BuffItemPicker();
|
||||
DateTime t = T0;
|
||||
for (int i = 0; i < BuffItemRules.UsesBeforeRest; i++)
|
||||
{
|
||||
var c = picker.Choose(entries, pack, NoBuffs, t, U0);
|
||||
Check.True(c is { ItemId: 5 }, $"use {i + 1}");
|
||||
picker.NoteUsed(c!.Value, entries, t, U0);
|
||||
t = t.AddSeconds(16);
|
||||
}
|
||||
Check.Null(picker.Choose(entries, pack, NoBuffs, t, U0), "a third use with no buff ever: rested");
|
||||
var notes = picker.TakeNotes();
|
||||
Check.Eq(notes.Count, 1, "the player is told once");
|
||||
Check.True(notes.Count == 1 && notes[0].Contains("Potion of Might") && notes[0].Contains("10 minutes"), "with the item and the wait");
|
||||
Check.Null(picker.Choose(entries, pack, NoBuffs, t.AddMinutes(9), U0), "9 min into the rest: nothing");
|
||||
Check.True(picker.Choose(entries, pack, NoBuffs, t.AddMinutes(10), U0) is { ItemId: 5 }, "after 10 min: tried again");
|
||||
|
||||
// A buff that shows resets the count.
|
||||
var p2 = new BuffItemPicker();
|
||||
p2.NoteUsed(p2.Choose(entries, pack, NoBuffs, T0, U0)!.Value, entries, T0, U0);
|
||||
Check.Null(p2.Choose(entries, pack, On(CustomSpell), T0.AddSeconds(20), U0), "its buff landed");
|
||||
p2.NoteUsed(p2.Choose(entries, pack, NoBuffs, T0.AddMinutes(60), U0)!.Value, entries, T0.AddMinutes(60), U0);
|
||||
Check.True(p2.Choose(entries, pack, NoBuffs, T0.AddMinutes(60).AddSeconds(16), U0) is { ItemId: 5 },
|
||||
"an hour later its first miss isn't counted with the old one: used again");
|
||||
}
|
||||
|
||||
private static void ListEdits()
|
||||
{
|
||||
var blocked = new List<string>();
|
||||
var customs = new List<CustomBuffItem>();
|
||||
|
||||
var r = BuffItemRules.SetAllowed(blocked, customs, "blackmoor's favor", false, out var nb, out var nc, out string shown);
|
||||
Check.Eq(r, BuffItemRules.EditResult.Changed, "block a built-in");
|
||||
Check.Eq(shown, "Blackmoor's Favor", "its own spelling");
|
||||
Check.True(nb.Count == 1 && blocked.Count == 0, "a new blocked list; the old one is untouched");
|
||||
Check.Eq(BuffItemRules.SetAllowed(nb, nc, "Blackmoor's Favor", false, out _, out _, out _), BuffItemRules.EditResult.Unchanged, "blocking again: unchanged");
|
||||
Check.Eq(BuffItemRules.SetAllowed(nb, nc, "Blackmoor's Favor", true, out var nb2, out _, out _), BuffItemRules.EditResult.Changed, "allow it again");
|
||||
Check.Eq(nb2.Count, 0, "the blocked list is empty again");
|
||||
Check.Eq(BuffItemRules.SetAllowed(blocked, customs, "Nothing Like It", true, out _, out _, out _), BuffItemRules.EditResult.NotFound, "an unknown name");
|
||||
|
||||
Check.Eq(BuffItemRules.Add(customs, " Elixir of the Hunt ", null, out var c1, out var added), BuffItemRules.EditResult.Added, "add by name");
|
||||
Check.True(c1.Count == 1 && customs.Count == 0 && added!.Name == "Elixir of the Hunt" && !added.SpellsRead && added.Allowed,
|
||||
"a new list, trimmed name, allowed, spells not read");
|
||||
Check.Eq(BuffItemRules.Add(c1, "elixir of the hunt", null, out _, out _), BuffItemRules.EditResult.AlreadyListed, "the same name again");
|
||||
Check.Eq(BuffItemRules.Add(c1, "Elixir of the Hunt", new uint[] { CustomSpell }, out var c2, out var upd), BuffItemRules.EditResult.Updated, "added again from the item: spells refreshed");
|
||||
Check.True(upd!.SpellsRead && upd.SpellIds.Count == 1 && !c1[0].SpellsRead, "on a copy; the old list's item is untouched");
|
||||
Check.Eq(BuffItemRules.Add(c2, "Asheron's Benediction", null, out _, out _), BuffItemRules.EditResult.BuiltIn, "a built-in name is refused");
|
||||
Check.Eq(BuffItemRules.Add(c2, " ", null, out _, out _), BuffItemRules.EditResult.EmptyName, "no name");
|
||||
|
||||
Check.Eq(BuffItemRules.SetAllowed(nb, c2, "ELIXIR OF THE HUNT", false, out _, out var c3, out _), BuffItemRules.EditResult.Changed, "block a custom item");
|
||||
Check.True(!c3[0].Allowed && c2[0].Allowed, "on a copy");
|
||||
|
||||
Check.Eq(BuffItemRules.Remove(c3, "Asheron's Benediction", out _, out _), BuffItemRules.EditResult.BuiltIn, "a built-in can't be removed");
|
||||
Check.Eq(BuffItemRules.Remove(c3, "elixir of the hunt", out var c4, out string removed), BuffItemRules.EditResult.Removed, "remove a custom item");
|
||||
Check.True(c4.Count == 0 && c3.Count == 1 && removed == "Elixir of the Hunt", "a new list");
|
||||
Check.Eq(BuffItemRules.Remove(c4, "Elixir of the Hunt", out _, out _), BuffItemRules.EditResult.NotFound, "already gone");
|
||||
|
||||
// A custom item named like a built-in (a hand-edited profile) is not listed twice.
|
||||
var odd = BuffItemEntry.Build(null, new List<CustomBuffItem> { Custom("Blackmoor's Favor", null) });
|
||||
Check.Eq(odd.Count, 3, "a custom copy of a built-in name is ignored");
|
||||
}
|
||||
|
||||
private static void Describe()
|
||||
{
|
||||
var gem = Custom("Timer Gem", Array.Empty<uint>(), repeat: 30);
|
||||
var entries = BuffItemEntry.Build(new List<string> { "Blackmoor's Favor" }, new List<CustomBuffItem> { gem, Custom("Unread", null) });
|
||||
var p = new BuffItemPicker();
|
||||
BuffItemEntry Get(string n) => BuffItemEntry.Find(entries, n)!;
|
||||
Check.Eq(p.Describe(Get("Blackmoor's Favor"), 1, NoBuffs, T0, U0), "blocked", "blocked");
|
||||
Check.Eq(p.Describe(Get("Asheron's Benediction"), 0, NoBuffs, T0, U0), "not in your pack", "missing");
|
||||
Check.Eq(p.Describe(Get("Asheron's Benediction"), 1, On(LesserBenediction), T0, U0), "buff on", "on");
|
||||
Check.Eq(p.Describe(Get("Asheron's Benediction"), 1, NoBuffs, T0, U0), "buff off: used at the next check", "off");
|
||||
Check.Eq(p.Describe(Get("Unread"), 1, NoBuffs, T0, U0), "reading its spell", "unread");
|
||||
Check.True(p.Describe(Get("Timer Gem"), 1, NoBuffs, T0, U0).Contains("used now, then every 30 min"), "timer, never used");
|
||||
gem.LastUsedUtc = U0;
|
||||
Check.True(p.Describe(Get("Timer Gem"), 1, NoBuffs, T0, U0.AddMinutes(10)).Contains("next in 20 min"), "timer, 10 min after a use");
|
||||
}
|
||||
}
|
||||
165
Tools/RynthCore.RynthAiTests/Tests/DirtyFightingHeightTests.cs
Normal file
165
Tools/RynthCore.RynthAiTests/Tests/DirtyFightingHeightTests.cs
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
using DF = RynthCore.Plugin.RynthAi.DirtyFightingHeights;
|
||||
|
||||
namespace RynthCore.RynthAiTests.Tests;
|
||||
|
||||
// The Dirty Fighting rotation's height choice (Combat/DirtyFightingHeights.cs): each attack aims at the
|
||||
// first height in the order whose effect is missing or about to run out, then at the default height once
|
||||
// all three are on; off, or with Dirty Fighting untrained, the fixed Attack Height. Time is passed in.
|
||||
internal static class DirtyFightingHeightTests
|
||||
{
|
||||
private static readonly DateTime T0 = new(2026, 11, 11, 12, 0, 0, DateTimeKind.Utc);
|
||||
private const int FixedMedium = DF.Medium;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("dfheight: a fresh target gets the first height in the order", FreshTarget);
|
||||
r.Add("dfheight: partly debuffed goes to the next missing height", PartlyDebuffed);
|
||||
r.Add("dfheight: all three on uses the default height", AllOnDefault);
|
||||
r.Add("dfheight: an effect near its end is re-applied", ExpiryReapplies);
|
||||
r.Add("dfheight: untrained or off keeps the fixed height", UntrainedFixed);
|
||||
r.Add("dfheight: other orders and bad order text", Orders);
|
||||
r.Add("dfheight: landing lines are parsed, others' and chat are not", ParseLanding);
|
||||
r.Add("dfheight: chance per hit", Chance);
|
||||
r.Add("dfheight: tracker keeps targets apart and copies", Tracker);
|
||||
}
|
||||
|
||||
private static int Pick(DfTargetEffects? fx, DateTime now, string order = "HML", int def = DF.DefaultIsFixedHeight,
|
||||
bool on = true, bool trained = true, int fixedHeight = FixedMedium)
|
||||
=> DF.Choose(on, trained, fixedHeight, order, def, fx, now);
|
||||
|
||||
private static void FreshTarget()
|
||||
{
|
||||
Check.Eq(Pick(null, T0), DF.High, "nothing known about it: High first");
|
||||
Check.Eq(Pick(new DfTargetEffects(), T0), DF.High, "an empty record: High first");
|
||||
}
|
||||
|
||||
private static void PartlyDebuffed()
|
||||
{
|
||||
var fx = new DfTargetEffects();
|
||||
fx.Landed(DF.High, T0);
|
||||
Check.Eq(Pick(fx, T0.AddSeconds(1)), DF.Medium, "High on: Medium (the bleed) next");
|
||||
fx.Landed(DF.Medium, T0.AddSeconds(2));
|
||||
Check.Eq(Pick(fx, T0.AddSeconds(3)), DF.Low, "High and Medium on: Low next");
|
||||
|
||||
var onlyLow = new DfTargetEffects();
|
||||
onlyLow.Landed(DF.Low, T0);
|
||||
Check.Eq(Pick(onlyLow, T0.AddSeconds(1)), DF.High, "only Low on: back to High, the first missing");
|
||||
onlyLow.Landed(DF.High, T0.AddSeconds(1));
|
||||
Check.Eq(Pick(onlyLow, T0.AddSeconds(2)), DF.Medium, "High and Low on: Medium");
|
||||
}
|
||||
|
||||
private static void AllOnDefault()
|
||||
{
|
||||
var fx = new DfTargetEffects();
|
||||
fx.Landed(DF.High, T0);
|
||||
fx.Landed(DF.Medium, T0);
|
||||
fx.Landed(DF.Low, T0);
|
||||
DateTime now = T0.AddSeconds(2);
|
||||
Check.Eq(Pick(fx, now, def: DF.Low), DF.Low, "all on, default Low: Low");
|
||||
Check.Eq(Pick(fx, now, def: DF.High), DF.High, "all on, default High: High");
|
||||
Check.Eq(Pick(fx, now, def: DF.DefaultIsFixedHeight, fixedHeight: DF.Medium), DF.Medium,
|
||||
"all on, default = the Attack Height setting (Medium)");
|
||||
Check.Eq(Pick(fx, now, def: DF.DefaultIsFixedHeight, fixedHeight: DF.Low), DF.Low,
|
||||
"all on, default = the Attack Height setting (Low)");
|
||||
Check.Eq(Pick(fx, now, def: 7, fixedHeight: DF.Medium), DF.Medium, "a bad default falls back to the fixed height");
|
||||
}
|
||||
|
||||
private static void ExpiryReapplies()
|
||||
{
|
||||
var fx = new DfTargetEffects();
|
||||
fx.Landed(DF.High, T0);
|
||||
fx.Landed(DF.Medium, T0.AddSeconds(4));
|
||||
fx.Landed(DF.Low, T0.AddSeconds(8));
|
||||
Check.Eq(Pick(fx, T0.AddSeconds(10), def: DF.Low), DF.Low, "all on: the default");
|
||||
// High ran 20 s from T0; 5 s before its end it counts as missing.
|
||||
Check.Eq(Pick(fx, T0.AddSeconds(14.9), def: DF.Low), DF.Low, "High has 5.1 s left: still the default");
|
||||
Check.Eq(Pick(fx, T0.AddSeconds(15.1), def: DF.Low), DF.High, "High has 4.9 s left: back to High");
|
||||
Check.Eq(Pick(fx, T0.AddSeconds(25), def: DF.Low), DF.High, "High ran out: High");
|
||||
fx.Landed(DF.High, T0.AddSeconds(16)); // a landing refreshes it to a full 20 s
|
||||
Check.Eq(Pick(fx, T0.AddSeconds(19.5), def: DF.Low), DF.Medium, "High refreshed; Medium (4 s + 20 s) is due at 19 s");
|
||||
Check.True(fx.IsOn(DF.High, T0.AddSeconds(35.9)), "the refreshed High lasts to 36 s");
|
||||
Check.False(fx.IsOn(DF.High, T0.AddSeconds(36.1)), "and not past it");
|
||||
}
|
||||
|
||||
private static void UntrainedFixed()
|
||||
{
|
||||
Check.Eq(Pick(null, T0, trained: false), FixedMedium, "untrained: the fixed height");
|
||||
Check.Eq(Pick(null, T0, trained: false, fixedHeight: DF.Low), DF.Low, "untrained: the fixed height (Low)");
|
||||
Check.Eq(Pick(null, T0, on: false), FixedMedium, "rotation off: the fixed height");
|
||||
Check.Eq(Pick(null, T0, on: false, fixedHeight: 9), DF.High, "a fixed height out of range is clamped");
|
||||
}
|
||||
|
||||
private static void Orders()
|
||||
{
|
||||
Check.Eq(Pick(null, T0, order: "LMH"), DF.Low, "LMH: Low first");
|
||||
Check.Eq(Pick(null, T0, order: "mhl"), DF.Medium, "lower case works: Medium first");
|
||||
var fx = new DfTargetEffects();
|
||||
fx.Landed(DF.Medium, T0);
|
||||
Check.Eq(Pick(fx, T0, order: "MLH"), DF.Low, "MLH with Medium on: Low");
|
||||
Check.Eq(Pick(null, T0, order: "HHL"), DF.High, "a repeated letter is not an order: High, Medium, Low");
|
||||
Check.Eq(Pick(null, T0, order: null!), DF.High, "no order: the default");
|
||||
Check.Eq(DF.NormalizeOrder("xyz"), "HML", "junk normalizes to HML");
|
||||
Check.Eq(DF.OrderLabel("HML"), "High, Medium, Low", "label");
|
||||
Check.Eq(DF.OrderLabel("LHM"), "Low, High, Medium", "label of LHM");
|
||||
Check.Eq(DF.OrderChoices.Length, 6, "six orders");
|
||||
}
|
||||
|
||||
private static void ParseLanding()
|
||||
{
|
||||
Check.True(DF.TryParseLanding("Dirty Fighting! Bob delivers a Blinding Blow to Drudge Skulker!", "Bob", out int h, out string t), "Blinding Blow");
|
||||
Check.Eq(h, DF.High, "Blinding is High");
|
||||
Check.Eq(t, "Drudge Skulker", "target name");
|
||||
Check.True(DF.TryParseLanding("Dirty Fighting! Bob delivers a Traumatic Assault to Drudge!\n", "Bob", out h, out _), "Traumatic Assault (specialized), trailing newline");
|
||||
Check.Eq(h, DF.High, "Traumatic is High");
|
||||
Check.True(DF.TryParseLanding("Dirty Fighting! Bob delivers a Bleeding Blow to Drudge!", "Bob", out h, out _), "Bleeding");
|
||||
Check.Eq(h, DF.Medium, "Bleeding is Medium");
|
||||
Check.True(DF.TryParseLanding("Dirty Fighting! Bob delivers an Unbalancing Assault to Mu-miyah Grave Robber!", "Bob", out h, out t), "an Unbalancing");
|
||||
Check.Eq(h, DF.Low, "Unbalancing is Low");
|
||||
Check.Eq(t, "Mu-miyah Grave Robber", "hyphenated target");
|
||||
Check.True(DF.TryParseLanding("Dirty Fighting! Sir Bob the Bold delivers a Bleeding Blow to Ward to the North!", "Sir Bob the Bold", out h, out t), "names with spaces and ' to '");
|
||||
Check.Eq(t, "Ward to the North", "target with ' to ' in it");
|
||||
|
||||
Check.False(DF.TryParseLanding("Dirty Fighting! Drudge delivers a Blinding Blow to Bob!", "Bob", out _, out _), "a monster's on me: not mine");
|
||||
Check.False(DF.TryParseLanding("Dirty Fighting! Bobby delivers a Blinding Blow to Drudge!", "Bob", out _, out _), "another player whose name starts the same");
|
||||
Check.False(DF.TryParseLanding("Bob says, \"Dirty Fighting! Bob delivers a Blinding Blow to Drudge!\"", "Bob", out _, out _), "said in chat");
|
||||
Check.False(DF.TryParseLanding("Dirty Fighting! Bob delivers a Fancy Kick to Drudge!", "Bob", out _, out _), "unknown spell");
|
||||
Check.False(DF.TryParseLanding("Dirty Fighting! Bob delivers a Blinding Blow to !", "Bob", out _, out _), "no target");
|
||||
Check.False(DF.TryParseLanding("You hit Drudge for 40 points of slashing damage!", "Bob", out _, out _), "a hit line");
|
||||
Check.False(DF.TryParseLanding("Dirty Fighting! Bob delivers a Blinding Blow to Drudge!", "", out _, out _), "own name unknown");
|
||||
}
|
||||
|
||||
private static void Chance()
|
||||
{
|
||||
Check.Eq(DF.ChancePerHit(true, 300, 300), 0.25, "equal skills: 25%");
|
||||
Check.Eq(DF.ChancePerHit(true, 400, 300), 0.25, "Dirty Fighting higher: 25%");
|
||||
Check.Eq(DF.ChancePerHit(true, 150, 300), 0.125, "half the weapon skill: 12.5%");
|
||||
Check.Eq(DF.ChancePerHit(false, 300, 300), 0.0, "untrained: 0");
|
||||
Check.Eq(DF.ChancePerHit(true, 100, 0), 0.25, "weapon skill unknown: 25%");
|
||||
}
|
||||
|
||||
private static void Tracker()
|
||||
{
|
||||
var tr = new DirtyFightingTracker();
|
||||
Check.True(tr.Get(1) == null, "nothing on target 1 yet");
|
||||
tr.Landed(1, DF.High, T0);
|
||||
tr.Landed(2, DF.Low, T0);
|
||||
Check.True(tr.Get(1)!.IsOn(DF.High, T0.AddSeconds(1)), "target 1 has High");
|
||||
Check.False(tr.Get(1)!.IsOn(DF.Low, T0.AddSeconds(1)), "target 1 has no Low");
|
||||
Check.True(tr.Get(2)!.IsOn(DF.Low, T0.AddSeconds(1)), "target 2 has Low");
|
||||
var copy = tr.Get(1)!;
|
||||
copy.Landed(DF.Low, T0);
|
||||
Check.False(tr.Get(1)!.IsOn(DF.Low, T0.AddSeconds(1)), "Get returns a copy");
|
||||
Check.Eq(tr.Get(1)!.Describe("HML", T0.AddSeconds(1)), "High 19 s, Medium off, Low off", "describe in order");
|
||||
tr.Landed(0, DF.High, T0);
|
||||
tr.Landed(3, 5, T0);
|
||||
Check.Eq(tr.Count, 2, "no target id, or a bad height: ignored");
|
||||
for (int id = 10; id < 200; id++) tr.Landed(id, DF.Medium, T0.AddSeconds(id));
|
||||
Check.True(tr.Count <= 64, "at most 64 targets kept");
|
||||
Check.True(tr.Get(199) != null, "the newest kept");
|
||||
tr.Forget(199);
|
||||
Check.True(tr.Get(199) == null, "forgotten");
|
||||
}
|
||||
}
|
||||
251
Tools/RynthCore.RynthAiTests/Tests/GearActivationTests.cs
Normal file
251
Tools/RynthCore.RynthAiTests/Tests/GearActivationTests.cs
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.ActiveGear;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiTests.Tests;
|
||||
|
||||
// The Active Gear window's logic (ActiveGear/GearActivation.cs): whether a worn item's magic is on
|
||||
// (its spell on the player with no end time, or marked on the item in its appraisal), why not
|
||||
// (out of mana, Arcane Lore, activation skill), unknown when it can't be told, and the time its
|
||||
// mana lasts at its rate less the read's age.
|
||||
internal static class GearActivationTests
|
||||
{
|
||||
private const int MajorStrength = 2576, MajorEndurance = 2577, Impen = 1483;
|
||||
private const int LeftRing = 0x00040000, Neck = 0x00008000, CoatMask = 0x00000200 | 0x00000400 | 0x00000800 | 0x00001000;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("active gear: a spell on the player with no end time is active", ActiveOnPlayer);
|
||||
r.Add("active gear: a spell marked on the item itself (bit 31) is active", ActiveOnItem);
|
||||
r.Add("active gear: mana 0 and no spell seen is off, out of mana", ManaZero);
|
||||
r.Add("active gear: too little Arcane Lore is off, with the numbers", ArcaneLore);
|
||||
r.Add("active gear: too little activation skill is off, named", ActivationSkill);
|
||||
r.Add("active gear: a fresh appraisal from while worn with no spell seen is off", InactiveFresh);
|
||||
r.Add("active gear: not identified, an appraisal from before it was worn, or no enchantment read is unknown", Unknown);
|
||||
r.Add("active gear: a spell seen only in an old appraisal that has since run dry is unknown", StaleItemSide);
|
||||
r.Add("active gear: time left is mana over the rate, less the read's age", TimeLeftMath);
|
||||
r.Add("active gear: time words", TimeWords);
|
||||
r.Add("active gear: slots, listing, and the summary line", SummaryLine);
|
||||
r.Add("active gear: a proc spell (cloak, aetheria, cast on strike) isn't looked for on the wearer", ProcSpells);
|
||||
}
|
||||
|
||||
private static GearFacts Ring(params uint[] spells) => new()
|
||||
{
|
||||
Name = "Ring",
|
||||
Slot = LeftRing,
|
||||
Identified = true,
|
||||
RawSpellIds = spells,
|
||||
CurMana = 1800,
|
||||
MaxMana = 2000,
|
||||
ManaRate = -0.5,
|
||||
ReadAgeSeconds = 60,
|
||||
WornForSeconds = 3600,
|
||||
EnchantmentsReadable = true,
|
||||
PlayerItemSpells = new HashSet<int>(),
|
||||
};
|
||||
|
||||
private static void ActiveOnPlayer()
|
||||
{
|
||||
GearFacts f = Ring(MajorStrength, MajorEndurance) with { PlayerItemSpells = new HashSet<int> { MajorStrength, MajorEndurance } };
|
||||
GearVerdict v = GearActivation.Judge(f);
|
||||
Check.Eq(v.Active, GearActive.Yes, "both spells on the player");
|
||||
Check.Eq(v.Reason, string.Empty, "no reason when every spell is seen");
|
||||
Check.Eq(v.SpellsOn, 2, "two on");
|
||||
|
||||
v = GearActivation.Judge(f with { PlayerItemSpells = new HashSet<int> { MajorStrength } });
|
||||
Check.Eq(v.Active, GearActive.Yes, "one of two is enough");
|
||||
Check.Eq(v.Reason, "1 of 2 spells seen", v.Reason);
|
||||
Check.True(v.SpellOn[0] && !v.SpellOn[1], "which one is on");
|
||||
|
||||
// A stale mana read of 0 doesn't beat a spell seen live on the player (a stone refilled it since).
|
||||
v = GearActivation.Judge(f with { CurMana = 0 });
|
||||
Check.Eq(v.Active, GearActive.Yes, "live enchantment wins over a stale 0");
|
||||
Check.True(v.Reason.Contains("older"), v.Reason);
|
||||
|
||||
// The enchantment list is only trusted when it could be read.
|
||||
v = GearActivation.Judge(f with { EnchantmentsReadable = false });
|
||||
Check.Eq(v.Active, GearActive.Unknown, "unreadable list: unknown");
|
||||
}
|
||||
|
||||
private static void ActiveOnItem()
|
||||
{
|
||||
// Armor: its own spell (Impenetrability) is on the item: the book lists it, and again with bit 31.
|
||||
GearFacts f = Ring(Impen, Impen | GearActivation.ActiveOnItemBit) with { Slot = CoatMask, Name = "Coat" };
|
||||
GearVerdict v = GearActivation.Judge(f);
|
||||
Check.Eq(v.Active, GearActive.Yes, "on the item");
|
||||
Check.Eq(v.SpellIds.Count, 1, "the marked copy isn't a second spell");
|
||||
Check.Eq(v.SpellIds[0], Impen, "bit 31 stripped");
|
||||
|
||||
// An enchantment someone else cast on the item isn't one of its spells and doesn't make it active.
|
||||
v = GearActivation.Judge(Ring(Impen, 1616u | GearActivation.ActiveOnItemBit) with { CurMana = 0 });
|
||||
Check.Eq(v.Active, GearActive.No, "a foreign enchantment on the item doesn't count");
|
||||
Check.Eq(v.SpellIds.Count, 1, "only its own spell listed");
|
||||
}
|
||||
|
||||
private static void ManaZero()
|
||||
{
|
||||
GearVerdict v = GearActivation.Judge(Ring(MajorStrength) with { CurMana = 0 });
|
||||
Check.Eq(v.Active, GearActive.No, "mana 0");
|
||||
Check.Eq(v.Reason, "out of mana", v.Reason);
|
||||
Check.Eq(v.ManaPercent, 0, "0%");
|
||||
Check.Eq(v.SecondsLeft, 0.0, "no time left");
|
||||
}
|
||||
|
||||
private static void ArcaneLore()
|
||||
{
|
||||
GearVerdict v = GearActivation.Judge(Ring(MajorStrength) with { ArcaneLoreNeeded = 300, ArcaneLore = 250 });
|
||||
Check.Eq(v.Active, GearActive.No, "lore too low");
|
||||
Check.Eq(v.Reason, "needs Arcane Lore 300, you have 250", v.Reason);
|
||||
// Enough lore: no reason to be off from it (and the item is fresh with nothing seen: off for that reason).
|
||||
v = GearActivation.Judge(Ring(MajorStrength) with { ArcaneLoreNeeded = 300, ArcaneLore = 320 });
|
||||
Check.Eq(v.Reason, "none of its spells is on you or on it", v.Reason);
|
||||
// Lore unread: not used.
|
||||
v = GearActivation.Judge(Ring(MajorStrength) with { ArcaneLoreNeeded = 300, ArcaneLore = null, WornForSeconds = null });
|
||||
Check.Eq(v.Active, GearActive.Unknown, "lore unread, worn time unknown: unknown");
|
||||
}
|
||||
|
||||
private static void ActivationSkill()
|
||||
{
|
||||
GearVerdict v = GearActivation.Judge(Ring(MajorStrength) with { ActivationSkillName = "Heavy Weapons", ActivationLevel = 375, ActivationSkill = 300 });
|
||||
Check.Eq(v.Active, GearActive.No, "skill too low");
|
||||
Check.Eq(v.Reason, "needs Heavy Weapons 375, you have 300", v.Reason);
|
||||
}
|
||||
|
||||
private static void InactiveFresh()
|
||||
{
|
||||
// Identified a minute ago, worn for an hour, nothing on: off.
|
||||
GearVerdict v = GearActivation.Judge(Ring(MajorStrength));
|
||||
Check.Eq(v.Active, GearActive.No, "fresh read, nothing seen");
|
||||
Check.Eq(v.SpellsOn, 0, "none on");
|
||||
}
|
||||
|
||||
private static void Unknown()
|
||||
{
|
||||
GearVerdict v = GearActivation.Judge(new GearFacts { Name = "Amulet", Slot = Neck, Identified = false, EnchantmentsReadable = true });
|
||||
Check.Eq(v.Active, GearActive.Unknown, "not identified");
|
||||
Check.Eq(v.Reason, "not identified yet", v.Reason);
|
||||
Check.Eq(v.SecondsLeft, null, "no time left for an unread item");
|
||||
Check.Eq(v.ManaPercent, null, "no mana for an unread item");
|
||||
|
||||
// Identified in the pack an hour ago, worn for ten minutes: its on-the-item spells weren't listed then.
|
||||
v = GearActivation.Judge(Ring(Impen) with { ReadAgeSeconds = 3600, WornForSeconds = 600 });
|
||||
Check.Eq(v.Active, GearActive.Unknown, "appraisal older than wearing it");
|
||||
Check.True(v.Reason.Contains("Check items"), v.Reason);
|
||||
|
||||
v = GearActivation.Judge(Ring(MajorStrength) with { ReadAgeSeconds = null });
|
||||
Check.Eq(v.Active, GearActive.Unknown, "no appraisal time: unknown");
|
||||
|
||||
v = GearActivation.Judge(Ring(MajorStrength) with { EnchantmentsReadable = false });
|
||||
Check.Eq(v.Reason, "your enchantments can't be read yet", v.Reason);
|
||||
|
||||
v = GearActivation.Judge(Ring() with { MaxMana = 500 });
|
||||
Check.Eq(v.Reason, "no spells read", v.Reason);
|
||||
}
|
||||
|
||||
private static void StaleItemSide()
|
||||
{
|
||||
// Seen only via the appraisal's bit-31 list, and the estimate says its mana ran out since.
|
||||
GearFacts f = Ring(Impen, Impen | GearActivation.ActiveOnItemBit) with { CurMana = 100, ManaRate = -0.1, ReadAgeSeconds = 5000 };
|
||||
GearVerdict v = GearActivation.Judge(f);
|
||||
Check.Eq(v.Active, GearActive.Unknown, "may have run dry");
|
||||
Check.True(v.Reason.Contains("run out"), v.Reason);
|
||||
// Seen live on the player: still yes whatever the estimate.
|
||||
v = GearActivation.Judge(Ring(MajorStrength) with { CurMana = 100, ManaRate = -0.1, ReadAgeSeconds = 5000, PlayerItemSpells = new HashSet<int> { MajorStrength } });
|
||||
Check.Eq(v.Active, GearActive.Yes, "live wins");
|
||||
}
|
||||
|
||||
private static void TimeLeftMath()
|
||||
{
|
||||
Check.Near(GearActivation.SecondsLeft(1800, -0.5, 0) ?? -1, 3600, 1e-9, "1800 mana at 0.5/s = 1 h");
|
||||
Check.Near(GearActivation.SecondsLeft(1800, -0.5, 600) ?? -1, 3000, 1e-9, "less the read's 10 minutes");
|
||||
Check.Near(GearActivation.SecondsLeft(1800, 0.5, null) ?? -1, 3600, 1e-9, "a positive rate counts the same; unknown age = 0");
|
||||
Check.Eq(GearActivation.SecondsLeft(100, -0.5, 1000), 0.0, "never below 0");
|
||||
Check.Eq(GearActivation.SecondsLeft(1800, 0, 0), null, "no rate: no estimate");
|
||||
Check.Eq(GearActivation.SecondsLeft(1800, null, 0), null, "rate unread: no estimate");
|
||||
Check.Eq(GearActivation.SecondsLeft(null, -0.5, 0), null, "mana unread: no estimate");
|
||||
Check.Eq(GearActivation.SecondsLeft(1800, double.NaN, 0), null, "NaN rate: no estimate");
|
||||
|
||||
GearVerdict v = GearActivation.Judge(Ring(MajorStrength) with { PlayerItemSpells = new HashSet<int> { MajorStrength } });
|
||||
Check.Near(v.SecondsLeft ?? -1, 1800 / 0.5 - 60, 1e-9, "the verdict carries it");
|
||||
Check.Eq(v.ManaPercent, 90, "1800 of 2000");
|
||||
}
|
||||
|
||||
private static void TimeWords()
|
||||
{
|
||||
Check.Eq(GearActivation.TimeText(null), "-", "none");
|
||||
Check.Eq(GearActivation.TimeText(0), "0 min", "zero");
|
||||
Check.Eq(GearActivation.TimeText(30), "<1 min", "under a minute");
|
||||
Check.Eq(GearActivation.TimeText(12 * 60 + 59), "12 min", "minutes, floored");
|
||||
Check.Eq(GearActivation.TimeText(3 * 3600), "3 h", "whole hours");
|
||||
Check.Eq(GearActivation.TimeText(3 * 3600 + 5 * 60), "3 h 5 min", "hours and minutes");
|
||||
Check.Eq(GearActivation.TimeText(52 * 3600), "2 d 4 h", "days");
|
||||
}
|
||||
|
||||
private static void SummaryLine()
|
||||
{
|
||||
Check.Eq(GearActivation.SlotName(LeftRing), "Left Ring", "ring");
|
||||
Check.Eq(GearActivation.SlotName(CoatMask), "Chest", "a coat is chest armor");
|
||||
Check.Eq(GearActivation.SlotName(0), "Worn", "no slot");
|
||||
Check.True(GearActivation.SlotOrder(CoatMask) < GearActivation.SlotOrder(LeftRing), "armor before jewelry");
|
||||
|
||||
Check.True(GearActivation.Listed(new GearFacts { Identified = false }), "unidentified items are listed (they may have spells)");
|
||||
Check.False(GearActivation.Listed(new GearFacts { Identified = true }), "no spells, no mana: not listed");
|
||||
Check.True(GearActivation.Listed(Ring(MajorStrength)), "spells: listed");
|
||||
Check.False(GearActivation.Listed(new GearFacts { Identified = false, Slot = GearActivation.AmmoSlot }), "arrows: never listed");
|
||||
|
||||
var on = new HashSet<int> { MajorStrength };
|
||||
GearFacts ring = Ring(MajorStrength) with { PlayerItemSpells = on, CurMana = 360, ManaRate = -0.5, ReadAgeSeconds = 0 }; // 12 min
|
||||
GearFacts neck = Ring(MajorStrength) with { Slot = Neck, PlayerItemSpells = on, CurMana = 1800 }; // ~1 h
|
||||
var items = new List<(GearFacts, GearVerdict)> { (ring, GearActivation.Judge(ring)), (neck, GearActivation.Judge(neck)) };
|
||||
Check.Eq(GearActivation.Summary(items), "2 of 2 items active, lowest: Left Ring 12 min", "all on");
|
||||
|
||||
GearFacts dry = Ring(MajorEndurance) with { Slot = CoatMask, CurMana = 0 };
|
||||
GearFacts unid = new() { Name = "Amulet", Slot = Neck };
|
||||
items.Add((dry, GearActivation.Judge(dry)));
|
||||
items.Add((unid, GearActivation.Judge(unid)));
|
||||
Check.Eq(GearActivation.Summary(items), "2 of 4 items active, 1 unknown, off: Chest (out of mana), lowest: Left Ring 12 min", "mixed");
|
||||
|
||||
Check.Eq(GearActivation.Summary(new List<(GearFacts, GearVerdict)>()), "No worn items with spells.", "nothing worn");
|
||||
|
||||
// Without rates the lowest is by mana.
|
||||
GearFacts noRate = Ring(MajorStrength) with { PlayerItemSpells = on, ManaRate = null, CurMana = 100 };
|
||||
Check.Eq(GearActivation.Summary(new List<(GearFacts, GearVerdict)> { (noRate, GearActivation.Judge(noRate)) }),
|
||||
"1 of 1 item active, lowest: Left Ring 5% mana", "by mana");
|
||||
}
|
||||
|
||||
private static void ProcSpells()
|
||||
{
|
||||
const int Surge = 5753, CastOnStrike = 3020, Cloak = 0x08000000, BlueAetheria = 0x10000000, MeleeSlot = 0x00100000;
|
||||
// A cloak: its proc in the spell book, no mana, nothing on the wearer. On.
|
||||
GearFacts cloak = Ring((uint)Surge) with { Name = "Cloak", Slot = Cloak, CurMana = null, MaxMana = null, ManaRate = null };
|
||||
GearVerdict v = GearActivation.Judge(cloak);
|
||||
Check.Eq(v.Active, GearActive.Yes, "cloak by slot");
|
||||
Check.Eq(v.Reason, "casts its spell when it triggers", v.Reason);
|
||||
Check.True(v.SpellOn.Count == 1 && v.SpellOn[0], "the proc shows on");
|
||||
|
||||
// Aetheria with ProcSpell read.
|
||||
v = GearActivation.Judge(cloak with { Slot = BlueAetheria, ProcSpellId = Surge });
|
||||
Check.Eq(v.Active, GearActive.Yes, "aetheria by ProcSpell");
|
||||
|
||||
// Requirements still count: too little Arcane Lore is off.
|
||||
v = GearActivation.Judge(cloak with { ArcaneLoreNeeded = 300, ArcaneLore = 200 });
|
||||
Check.Eq(v.Active, GearActive.No, "lore still counts");
|
||||
|
||||
// A weapon with a cast on strike and a wield spell: the wield spell decides, the proc isn't counted.
|
||||
GearFacts weapon = Ring((uint)MajorStrength, (uint)CastOnStrike) with { Name = "Sword", Slot = MeleeSlot, ProcSpellId = CastOnStrike,
|
||||
PlayerItemSpells = new HashSet<int> { MajorStrength } };
|
||||
v = GearActivation.Judge(weapon);
|
||||
Check.Eq(v.Active, GearActive.Yes, "weapon on");
|
||||
Check.Eq(v.Reason, string.Empty, "every spell that can be seen is seen: " + v.Reason);
|
||||
Check.True(v.SpellOn[0] && v.SpellOn[1], "both show on");
|
||||
v = GearActivation.Judge(weapon with { PlayerItemSpells = new HashSet<int>() });
|
||||
Check.Eq(v.Active, GearActive.No, "the wield spell not on is still off");
|
||||
|
||||
// Not a proc slot and no ProcSpell: a lone spell is still looked for.
|
||||
v = GearActivation.Judge(Ring((uint)Surge));
|
||||
Check.Eq(v.Active, GearActive.No, "a ring's lone spell isn't a proc");
|
||||
// A ProcSpell that isn't in the book is ignored.
|
||||
v = GearActivation.Judge(Ring((uint)MajorStrength) with { ProcSpellId = Surge });
|
||||
Check.Eq(v.Active, GearActive.No, "a ProcSpell not in the book changes nothing");
|
||||
}
|
||||
}
|
||||
143
Tools/RynthCore.RynthAiTests/Tests/ItemInfoPartColorsTests.cs
Normal file
143
Tools/RynthCore.RynthAiTests/Tests/ItemInfoPartColorsTests.cs
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiTests.Tests;
|
||||
|
||||
// 2026-11-11, per-part colours for the one-line item info (ItemInfo/ItemInfoPartColors.cs): the
|
||||
// line's (part, text) pieces become character ranges, then the engine's "nextspans" payload
|
||||
// ("start:length:RRGGBB;..."). The prefix and the ", " between parts stay uncoloured.
|
||||
internal static class ItemInfoPartColorsTests
|
||||
{
|
||||
private const string Prefix = "[RynthAi Item] ";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("item info parts: every part has a colour, None has none", Colours);
|
||||
r.Add("item info parts: ranges after the prefix, the commas between parts left out", Ranges);
|
||||
r.Add("item info parts: one part's pieces next to each other make one range", SamePartJoined);
|
||||
r.Add("item info parts: empty pieces and uncoloured text", EmptyAndUncoloured);
|
||||
r.Add("item info parts: at most 32 ranges", Cap);
|
||||
r.Add("item info parts: the nextspans payload", Payload);
|
||||
r.Add("item info parts: the sample line shows every part", Sample);
|
||||
}
|
||||
|
||||
private static List<(ItemInfoPart Part, string Text)> Sword() => new()
|
||||
{
|
||||
(ItemInfoPart.Name, "Gold Long Sword (Slash Heavy)"),
|
||||
(ItemInfoPart.None, ", "), (ItemInfoPart.Set, "Noble Relic Set"),
|
||||
(ItemInfoPart.None, ", "), (ItemInfoPart.Special, "CS"),
|
||||
(ItemInfoPart.None, ", "), (ItemInfoPart.Stats, "152-236"),
|
||||
(ItemInfoPart.None, ", "), (ItemInfoPart.Stats, "0.35v"),
|
||||
(ItemInfoPart.None, ", "), (ItemInfoPart.Bonus, "+18%a"),
|
||||
(ItemInfoPart.None, ", "), (ItemInfoPart.Spells, "Legendary Blood Thirst"),
|
||||
(ItemInfoPart.None, ", "), (ItemInfoPart.Spells, "Epic Strength"),
|
||||
(ItemInfoPart.None, ", "), (ItemInfoPart.Requirements, "Wield Lvl 180"),
|
||||
(ItemInfoPart.None, ", "), (ItemInfoPart.Craft, "Craft 8"),
|
||||
(ItemInfoPart.None, ", "), (ItemInfoPart.ValueBurden, "Value 9,000"),
|
||||
(ItemInfoPart.None, ", "), (ItemInfoPart.ValueBurden, "BU 300"),
|
||||
};
|
||||
|
||||
private static void Colours()
|
||||
{
|
||||
foreach (ItemInfoPart p in System.Enum.GetValues<ItemInfoPart>())
|
||||
{
|
||||
string c = ItemInfoPartColors.ColorOf(p);
|
||||
if (p == ItemInfoPart.None) Check.Eq(c, "", "None keeps the line's colour");
|
||||
else Check.True(c.Length == 7 && c[0] == '#' && c[1..].All(System.Uri.IsHexDigit), $"{p}: a #RRGGBB colour ({c})");
|
||||
}
|
||||
Check.Eq(ItemInfoPartColors.Defaults.Select(d => d.Part).Distinct().Count(), ItemInfoPartColors.Defaults.Length, "each part listed once");
|
||||
Check.Eq(ItemInfoPartColors.Defaults.Length, System.Enum.GetValues<ItemInfoPart>().Length - 1, "every part but None listed");
|
||||
Check.True(ItemInfoPartColors.Defaults.All(d => d.Label.Length > 0), "every part has a label");
|
||||
}
|
||||
|
||||
private static void Ranges()
|
||||
{
|
||||
var pieces = Sword();
|
||||
string line = Prefix + ItemInfoPartColors.Join(pieces);
|
||||
var ranges = ItemInfoPartColors.Ranges(pieces, Prefix.Length);
|
||||
Check.Eq(ranges[0].Start, Prefix.Length, "the first range starts after the prefix");
|
||||
Check.Eq(line.Substring(ranges[0].Start, ranges[0].Length), "Gold Long Sword (Slash Heavy)", "the name");
|
||||
Check.Eq(ranges[0].Color, ItemInfoPartColors.ColorOf(ItemInfoPart.Name), "in the name's colour");
|
||||
Check.Eq(line.Substring(ranges[1].Start, ranges[1].Length), "Noble Relic Set", "the set, without the comma before it");
|
||||
Check.Eq(ranges[1].Color, ItemInfoPartColors.ColorOf(ItemInfoPart.Set), "in the set's colour");
|
||||
var texts = ranges.Select(r => line.Substring(r.Start, r.Length)).ToList();
|
||||
Check.True(texts.All(t => !t.StartsWith(",") && !t.StartsWith(" ") && !t.EndsWith(",") && !t.EndsWith(" ")), "no range starts or ends on a separator: " + string.Join(" | ", texts));
|
||||
for (int i = 1; i < ranges.Count; i++)
|
||||
Check.True(ranges[i].Start >= ranges[i - 1].Start + ranges[i - 1].Length, "ranges in order, not overlapping");
|
||||
Check.True(ranges.All(r => r.Start + r.Length <= line.Length), "every range inside the line");
|
||||
}
|
||||
|
||||
private static void SamePartJoined()
|
||||
{
|
||||
var pieces = Sword();
|
||||
string line = ItemInfoPartColors.Join(pieces);
|
||||
var ranges = ItemInfoPartColors.Ranges(pieces);
|
||||
var texts = ranges.Select(r => line.Substring(r.Start, r.Length)).ToList();
|
||||
Check.True(texts.Contains("152-236, 0.35v"), "damage and variance: one range, the comma inside it: " + string.Join(" | ", texts));
|
||||
Check.True(texts.Contains("Legendary Blood Thirst, Epic Strength"), "two spells: one range");
|
||||
Check.True(texts.Contains("Value 9,000, BU 300"), "value and burden: one range");
|
||||
Check.Eq(ranges.Count, 9, "name, set, imbue, damage, bonus, spells, requirement, craft, value / burden: 9 ranges");
|
||||
}
|
||||
|
||||
private static void EmptyAndUncoloured()
|
||||
{
|
||||
Check.Eq(ItemInfoPartColors.Ranges(new List<(ItemInfoPart, string)>()).Count, 0, "no pieces: no ranges");
|
||||
var pieces = new List<(ItemInfoPart Part, string Text)>
|
||||
{
|
||||
(ItemInfoPart.Name, "Sword"), (ItemInfoPart.Set, ""), (ItemInfoPart.None, ", "), (ItemInfoPart.None, "Keys: 3"),
|
||||
(ItemInfoPart.None, ", "), (ItemInfoPart.Name, "Again"),
|
||||
};
|
||||
var ranges = ItemInfoPartColors.Ranges(pieces, 4);
|
||||
Check.Eq(ranges.Count, 2, "an empty piece adds nothing; uncoloured text (not a separator) splits a part");
|
||||
Check.Eq(ranges[0], (4, 5, ItemInfoPartColors.ColorOf(ItemInfoPart.Name)), "the first name");
|
||||
Check.Eq(ranges[1].Start, 4 + "Sword, Keys: 3, ".Length, "the second, after the uncoloured text");
|
||||
Check.Eq(ItemInfoPartColors.Ranges(new List<(ItemInfoPart, string)> { (ItemInfoPart.None, "plain") }).Count, 0, "uncoloured only: none");
|
||||
Check.Eq(ItemInfoPartColors.Ranges(new List<(ItemInfoPart, string)> { (ItemInfoPart.Name, "x") }, -5)[0].Start, 0, "a negative offset counts as 0");
|
||||
}
|
||||
|
||||
private static void Cap()
|
||||
{
|
||||
var pieces = new List<(ItemInfoPart Part, string Text)>();
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
if (i > 0) pieces.Add((ItemInfoPart.None, ", "));
|
||||
pieces.Add((i % 2 == 0 ? ItemInfoPart.Spells : ItemInfoPart.Stats, "p" + i));
|
||||
}
|
||||
var ranges = ItemInfoPartColors.Ranges(pieces);
|
||||
Check.Eq(ranges.Count, ItemInfoPartColors.MaxSpans, "50 alternating parts: the first 32 ranges");
|
||||
Check.Eq(ItemInfoPartColors.Payload(ranges, ItemInfoPartColors.Join(pieces).Length).Split(';').Length, 32, "all of them in the payload");
|
||||
}
|
||||
|
||||
private static void Payload()
|
||||
{
|
||||
var ranges = new List<(int, int, string)> { (15, 5, "#E6B450"), (22, 3, "80FF7F") };
|
||||
Check.Eq(ItemInfoPartColors.Payload(ranges, 25), "15:5:E6B450;22:3:80FF7F", "start:length:RRGGBB joined by ';', no '#'");
|
||||
Check.Eq(ItemInfoPartColors.Payload(new List<(int, int, string)>(), 10), "", "no ranges: empty");
|
||||
Check.Eq(ItemInfoPartColors.Payload(ranges, 24), "", "a range past the line's end: none (the engine would refuse it)");
|
||||
Check.Eq(ItemInfoPartColors.Payload(new List<(int, int, string)> { (5, 5, "#FFFFFF"), (7, 2, "#FFFFFF") }, 20), "", "overlapping: none");
|
||||
Check.Eq(ItemInfoPartColors.Payload(new List<(int, int, string)> { (0, 0, "#FFFFFF") }, 20), "", "an empty range: none");
|
||||
Check.Eq(ItemInfoPartColors.Payload(new List<(int, int, string)> { (0, 2, "#FFF") }, 20), "", "a short colour: none");
|
||||
|
||||
var pieces = Sword();
|
||||
string line = Prefix + ItemInfoPartColors.Join(pieces) + " (not identified)";
|
||||
string payload = ItemInfoPartColors.Payload(ItemInfoPartColors.Ranges(pieces, Prefix.Length), line.Length);
|
||||
Check.True(payload.Length > 0 && payload.StartsWith($"{Prefix.Length}:29:E6B450;"), "a real line's payload: " + payload);
|
||||
Check.True(payload.Length < 1024, "well under the engine's 1,024 characters");
|
||||
Check.Eq(ItemInfoPartColors.NextSpansAction, "nextspans", "the action the engine takes");
|
||||
}
|
||||
|
||||
private static void Sample()
|
||||
{
|
||||
var pieces = ItemInfoPartColors.SamplePieces();
|
||||
string line = ItemInfoPartColors.Join(pieces);
|
||||
var ranges = ItemInfoPartColors.Ranges(pieces);
|
||||
Check.Eq(ranges.Count, ItemInfoPartColors.Defaults.Length, "one range per part");
|
||||
for (int i = 0; i < ranges.Count; i++)
|
||||
{
|
||||
Check.Eq(line.Substring(ranges[i].Start, ranges[i].Length), ItemInfoPartColors.Defaults[i].Label, $"part {i}: its label");
|
||||
Check.Eq(ranges[i].Color, ItemInfoPartColors.Defaults[i].Color, $"part {i}: its colour");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -20,6 +20,7 @@ internal static partial class Program
|
|||
TestServerProfileBankLum();
|
||||
TestChatFallbackUntilBank();
|
||||
TestAelrynthAndRetailLum();
|
||||
TestBankAndAelBankedCountOnce();
|
||||
TestLumLast5Min();
|
||||
TestKillsAndXpPerKill();
|
||||
TestDeaths();
|
||||
|
|
@ -157,6 +158,21 @@ internal static partial class Program
|
|||
Eq(retail.LumTotal, 280L, "retail: rises count, spending doesn't");
|
||||
}
|
||||
|
||||
// DreamWeave (2026-11-12): a bank reading AND Aelrynth's auto-banked total (9102), both rising with
|
||||
// the same earned lum. Lum/hr read 1.62M, twice the real rate: the bank alone counts.
|
||||
private static void TestBankAndAelBankedCountOnce()
|
||||
{
|
||||
var s = new SessionStats();
|
||||
s.Reset(S0);
|
||||
s.Sample(new SessionSample(1, 5_000, 70_000_000, 0, 0, null), S0);
|
||||
s.Sample(new SessionSample(1, 5_000, 70_400_000, 400_000, 0, null), S0.AddSeconds(60));
|
||||
Eq(s.LumTotal, 400_000L, "bank + 9102: the lum counts once");
|
||||
s.Sample(new SessionSample(1, 25_000, 70_380_000, 400_000, 20_000, null), S0.AddSeconds(61));
|
||||
Eq(s.LumTotal, 400_000L, "bank + 9103: a draw (bank down, character up) isn't income or a loss");
|
||||
s.Sample(new SessionSample(1, 25_000, 70_680_000, 700_000, 20_000, null), S0.AddSeconds(120));
|
||||
Eq(s.LumTotal, 700_000L, "bank + 9102: the next rise counts once too");
|
||||
Check(Math.Abs(s.View(S0.AddSeconds(120)).LumPerHour - 700_000L * 30) < 1, "the rate is the bank's");
|
||||
}
|
||||
private static void TestLumLast5Min()
|
||||
{
|
||||
var s = new SessionStats();
|
||||
|
|
|
|||
|
|
@ -40,6 +40,7 @@ internal static unsafe class Program
|
|||
int passed = 0, checks = 0;
|
||||
var failed = new List<string>();
|
||||
if (filter.Length == 0 && !CheckBuiltInVerbsMatchSwitch()) failed.Add("built-in /lua verbs");
|
||||
if ((filter.Length == 0 || "memoryguard".Contains(filter, StringComparison.OrdinalIgnoreCase)) && !CheckMemoryGuard()) failed.Add("memory guard");
|
||||
try
|
||||
{
|
||||
foreach (string file in scripts)
|
||||
|
|
@ -165,6 +166,54 @@ internal static unsafe class Program
|
|||
return Directory.Exists(beside) ? beside : Path.Combine(AppContext.BaseDirectory, "Scripts");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The memory guard (LuaScriptHost.ChargeAllocation): a script that allocates fast is stopped
|
||||
/// with a message, and a quiet one keeps running. Three scripts, each in a fresh plugin: one
|
||||
/// that makes a 400 MB string in one go (the one-run limit), one that keeps 2 MB strings
|
||||
/// (the 5-second limit), and one that sleeps (must still be running after 3 s).
|
||||
/// </summary>
|
||||
private static bool CheckMemoryGuard()
|
||||
{
|
||||
var cases = new (string Name, string Code, bool MustStop, string Said)[]
|
||||
{
|
||||
// One string.rep can't be stopped part-way, so it has a size cap: a plain Lua error.
|
||||
("memhog_rep", "local s = string.rep('x', 200000000) print(#s)", true, "string.rep: the result would be"),
|
||||
("memhog_window", "local t = {} while true do t[#t + 1] = string.rep('y', 1000000) .. #t end", true, "was stopped: it used"),
|
||||
("memhog_table", "local t = {} local i = 0 while true do i = i + 1 t[i] = { i, i, i } end", true, "was stopped: it used"),
|
||||
("memquiet", "while true do local s = string.rep('z', 1000) sleep(50) end", false, "was stopped: it used"),
|
||||
};
|
||||
bool allOk = true;
|
||||
foreach (var c in cases)
|
||||
{
|
||||
FakeWorld.W = new FakeWorld();
|
||||
Harness.Reset();
|
||||
RynthCoreApiNative api = FakeHost.Build();
|
||||
var runtime = new RynthPluginRuntime<RynthLuaPlugin>();
|
||||
if (runtime.Init(&api) != 0 || runtime.Plugin == null) { Console.WriteLine($"FAIL memory guard {c.Name}: no plugin"); allOk = false; continue; }
|
||||
RynthLuaPlugin plugin = runtime.Plugin;
|
||||
plugin.OnLoginComplete();
|
||||
for (int i = 0; i < 3; i++) Tick(plugin);
|
||||
Directory.CreateDirectory(RynthLuaPaths.Scripts);
|
||||
File.WriteAllText(Path.Combine(RynthLuaPaths.Scripts, c.Name + ".lua"), c.Code);
|
||||
string? err = plugin.StartScript(c.Name);
|
||||
var sw = Stopwatch.StartNew();
|
||||
long limitMs = c.MustStop ? 20_000 : 3_000;
|
||||
while (err == null && plugin.ScriptIsLoaded(c.Name) && sw.ElapsedMilliseconds < limitMs) { Tick(plugin); Thread.Sleep(1); }
|
||||
bool loaded = plugin.ScriptIsLoaded(c.Name);
|
||||
string console = plugin.ScriptConsoleText(c.Name);
|
||||
bool said = console.Contains(c.Said, StringComparison.Ordinal);
|
||||
bool ok = err == null && (c.MustStop ? (!loaded && said) : (loaded && !said));
|
||||
string lastLine = console.Trim().Split('\n').LastOrDefault() ?? string.Empty;
|
||||
Console.WriteLine($"{(ok ? "PASS" : "FAIL")} memory guard {c.Name} ({sw.ElapsedMilliseconds} ms, {(loaded ? "running" : "stopped")}){(ok ? "" : ": " + (err ?? lastLine))}");
|
||||
if (ok && c.MustStop) Console.WriteLine(" " + console.Split('\n').First(l => l.Contains(c.Said, StringComparison.Ordinal)).Trim());
|
||||
try { plugin.StopScript(c.Name); } catch { }
|
||||
runtime.Shutdown();
|
||||
GC.Collect();
|
||||
allOk &= ok;
|
||||
}
|
||||
return allOk;
|
||||
}
|
||||
|
||||
private static void Tick(RynthLuaPlugin plugin)
|
||||
{
|
||||
FakeWorld.W.Step();
|
||||
|
|
|
|||
Loading…
Reference in a new issue