Snapshot for release 2026.10.28.2 (internal 48c46bd)
This commit is contained in:
parent
b23cabc338
commit
636adfcef2
41 changed files with 3402 additions and 120 deletions
|
|
@ -68,6 +68,7 @@ internal static class Program
|
|||
MetaSchedulerTests.Register(runner);
|
||||
NavEngineTests.Register(runner);
|
||||
NavReachTests.Register(runner);
|
||||
NavResumeTests.Register(runner);
|
||||
PatrolDoorwayTests.Register(runner);
|
||||
PatrolSettingsTests.Register(runner);
|
||||
PatrolPocketTests.Register(runner);
|
||||
|
|
@ -143,6 +144,7 @@ internal static class Program
|
|||
HpFailsafeTests.Register(runner);
|
||||
PluginFixTests.Register(runner);
|
||||
BuffChainTests.Register(runner);
|
||||
ShieldBuffTests.Register(runner);
|
||||
LootPacingTests.Register(runner);
|
||||
CorpseCloseTests.Register(runner);
|
||||
VTankHotkeyTests.Register(runner);
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ internal static class NavEngineTests
|
|||
r.Add("nav engine: walks to each waypoint, a Circular route wraps", CircularWraps);
|
||||
r.Add("nav engine: a Linear route turns round at both ends", LinearBounces);
|
||||
r.Add("nav engine: a Linear route keeps its direction through a pause", LinearDirectionSurvivesStop);
|
||||
r.Add("nav engine: a Once route ends, turns nav off, and re-runs from [0]", OnceCompletes);
|
||||
r.Add("nav engine: a Once route ends, turns nav off, stays finished, and the player can re-run it from [0]", OnceCompletes);
|
||||
r.Add("nav engine: closest approach counts as arriving; a pause forgets it", SweepPass);
|
||||
r.Add("nav engine: a pause point waits its time on the clock", PausePoint);
|
||||
r.Add("nav engine: standing still through a pause, the stop is sent once and then once a second (not every tick)", PauseStopsOnce);
|
||||
|
|
@ -223,10 +223,21 @@ internal static class NavEngineTests
|
|||
Check.Eq(nav.Idx, 2, "the index is left past the end");
|
||||
Check.False(FakeHost.AutoRun, "stopped");
|
||||
|
||||
nav.S.EnableNavigation = true; // re-run
|
||||
// A meta or expression switching nav on (a macro start replays "/vt opt set enablenav true"):
|
||||
// the route stays finished, as a finished VTank Once route does (2026-10-28; it re-ran from [0]).
|
||||
nav.S.EnableNavigation = true;
|
||||
nav.Tick();
|
||||
Check.Eq(nav.Idx, 0, "re-enabled: the route restarts from [0]");
|
||||
Check.Eq(LogCount("Once route re-armed"), 1, "logged");
|
||||
Check.Eq(nav.Idx, 2, "nav switched on: still finished");
|
||||
Check.False(nav.S.EnableNavigation, "and nav off again");
|
||||
Check.Eq(LogCount("the Once route is finished"), 1, "logged");
|
||||
|
||||
// The player's Nav switch / Start Navigation (RearmFinishedNavRoute) re-runs it from [0].
|
||||
Check.True(nav.S.RearmFinishedNavRoute(), "the player re-runs it");
|
||||
nav.S.EnableNavigation = true;
|
||||
nav.Tick();
|
||||
Check.Eq(nav.Idx, 0, "re-run from [0]");
|
||||
Check.True(nav.S.EnableNavigation, "nav on");
|
||||
Check.False(nav.S.RearmFinishedNavRoute(), "a route that isn't finished is left alone");
|
||||
}
|
||||
|
||||
private static void SweepPass()
|
||||
|
|
|
|||
402
Tools/RynthCore.RynthAiHostTests/Tests/NavResumeTests.cs
Normal file
402
Tools/RynthCore.RynthAiHostTests/Tests/NavResumeTests.cs
Normal file
|
|
@ -0,0 +1,402 @@
|
|||
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.PluginCore;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
using A = RynthCore.Plugin.RynthAi.LegacyUi.MetaActionType;
|
||||
using C = RynthCore.Plugin.RynthAi.LegacyUi.MetaConditionType;
|
||||
using RT = RynthCore.Plugin.RynthAi.LegacyUi.NavRouteType;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Stopping and starting the macro must not restart the nav (Tom, 2026-10-28: "anything that was a
|
||||
// 'once' instead of linear or circular gets restarted"). Starting the macro re-arms the meta's rules,
|
||||
// so a state's "Always -> Embedded Nav Route" fired again and loaded its route fresh: a Once route
|
||||
// went back to [0], a finished one ran again, a Linear route turned round. Here the meta and the nav
|
||||
// engine run on one settings object in the plugin's tick order (the macro-start closest-waypoint pick,
|
||||
// then nav, then the meta), on a fake clock and a fake character that only moves when told.
|
||||
internal static class NavResumeTests
|
||||
{
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private const double NS0 = 42.0, EW0 = 33.0;
|
||||
private static long _now;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("nav resume: stop + start keeps a meta's Once route on its waypoint (no restart from [0])", OnceKeepsWaypoint);
|
||||
r.Add("nav resume: stop + start keeps a Circular route's waypoint, also with Go To Closest Waypoint off", CircularKeepsWaypoint);
|
||||
r.Add("nav resume: stop + start keeps a Linear route's waypoint and its direction", LinearKeepsDirection);
|
||||
r.Add("nav resume: a finished Once route stays finished across stop + start (a replayed enablenav too)", FinishedOnceStaysFinished);
|
||||
r.Add("nav resume: loading the route again starts it fresh (state entry, edited, another route loaded)", LoadAgainStartsFresh);
|
||||
r.Add("nav resume: a rule that first fires after the start loads its route fresh", FirstFireAfterStartIsFresh);
|
||||
r.Add("nav resume: a replayed /vt nav load or /ra nav load of the running .nav keeps its place; a replayed /ra nav restart is skipped", ChatNavLoadKept);
|
||||
r.Add("nav resume: /ra nav restart runs the route from the top; the player's Nav switch re-runs a finished Once route", RestartCommand);
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────────
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly NavigationEngine E;
|
||||
public readonly MetaManager M;
|
||||
public readonly List<string> Ra = new();
|
||||
public DateTime Now = new(2026, 10, 28, 12, 0, 0);
|
||||
private bool _wasRunning;
|
||||
|
||||
/// <summary>Call FakeHost.Reset() and At(...) first. The first tick is a macro start (as at login).</summary>
|
||||
public Bot(params MetaRule[] rules)
|
||||
{
|
||||
_now = 1_000_000;
|
||||
NavigationEngine.Clock = static () => _now;
|
||||
var host = FakeHost.Create();
|
||||
S = new LegacyUiSettings { IsMacroRunning = true, EnableMeta = true, CurrentState = "Default" };
|
||||
S.MetaRules = rules.ToList();
|
||||
E = new NavigationEngine(host, S);
|
||||
M = new MetaManager(S, host, new PlayerVitalsCache()) { Clock = () => Now };
|
||||
M.SetRaCommandHandler(Ra.Add);
|
||||
}
|
||||
|
||||
/// <summary>One plugin tick: the macro-start closest pick (RynthAiPlugin.OnTick), nav when the
|
||||
/// arbiter would run it, then the meta. <paramref name="metaSeconds"/> moves only the meta's clock.</summary>
|
||||
public void Tick(int ms = 100, double metaSeconds = 0)
|
||||
{
|
||||
_now += ms;
|
||||
Now = Now.AddMilliseconds(ms).AddSeconds(metaSeconds);
|
||||
if (!_wasRunning && S.IsMacroRunning) E.ResumeFromNearestWaypoint();
|
||||
_wasRunning = S.IsMacroRunning;
|
||||
if (S.IsMacroRunning && S.EnableNavigation && S.CurrentRoute.Points.Count > 0) E.Tick();
|
||||
M.Think();
|
||||
}
|
||||
|
||||
public void Ticks(int n) { for (int i = 0; i < n; i++) Tick(); }
|
||||
|
||||
/// <summary>/ra stop, a tick, /ra start, a few ticks.</summary>
|
||||
public void StopStart()
|
||||
{
|
||||
S.IsMacroRunning = false;
|
||||
E.Stop();
|
||||
Ticks(3);
|
||||
S.IsMacroRunning = true;
|
||||
Ticks(3);
|
||||
}
|
||||
|
||||
public int Idx => S.ActiveNavIndex;
|
||||
public int Dir => E.GetStateSnapshot().LinearDir;
|
||||
public string Var(string name) => M.Expressions.Variables.TryGetValue(name, out string? v) ? v : "(unset)";
|
||||
}
|
||||
|
||||
private static void At(double north, double east)
|
||||
=> FakeHost.SetNavPosition(NS0 + north / 240.0, EW0 + east / 240.0);
|
||||
|
||||
private static NavPoint Pt(double north, double east)
|
||||
=> new() { Type = NavPointType.Point, NS = NS0 + north / 240.0, EW = EW0 + east / 240.0 };
|
||||
|
||||
/// <summary>Points every 20 yd due north of the origin, from 0 (or 10 for <paramref name="from10"/>).</summary>
|
||||
private static NavRouteParser Line(RT type, int count, bool from10 = false)
|
||||
{
|
||||
var r = new NavRouteParser { RouteType = type };
|
||||
for (int i = 0; i < count; i++) r.Points.Add(Pt((from10 ? 10 : 0) + i * 20, 0));
|
||||
return r;
|
||||
}
|
||||
|
||||
private static MetaRule Rule(string state, C cond, string condData, A act, string actData)
|
||||
=> new() { State = state, Condition = cond, ConditionData = condData, Action = act, ActionData = actData };
|
||||
|
||||
private static MetaRule EmbedNav(string name, C cond = C.Always, string condData = "")
|
||||
=> Rule("Default", cond, condData, A.EmbeddedNavRoute, name);
|
||||
|
||||
/// <summary>A bot whose meta loads <paramref name="route"/> as "R" with an Always rule; ticked until it runs.</summary>
|
||||
private static Bot Running(NavRouteParser route, params MetaRule[] more)
|
||||
{
|
||||
var bot = new Bot(new[] { EmbedNav("R") }.Concat(more).ToArray());
|
||||
bot.S.EmbeddedNavs["R"] = route.ToLines();
|
||||
bot.Tick();
|
||||
return bot;
|
||||
}
|
||||
|
||||
// ── Stop + start keeps the place ──────────────────────────────────────────
|
||||
|
||||
private static void OnceKeepsWaypoint()
|
||||
{
|
||||
FakeHost.Reset(); At(0, 0);
|
||||
var bot = Running(Line(RT.Once, 4, from10: true)); // [0] 10, [1] 30, [2] 50, [3] 70 yd north
|
||||
Check.Eq(bot.Idx, 0, "the meta loaded the Once route at [0]");
|
||||
var loaded = bot.S.CurrentRoute;
|
||||
At(10, 0); bot.Tick();
|
||||
At(30, 0); bot.Tick();
|
||||
Check.Eq(bot.Idx, 2, "walked on to [2]");
|
||||
At(40, 0); bot.Tick(); // on the leg to [2]
|
||||
|
||||
bot.StopStart();
|
||||
Check.True(ReferenceEquals(bot.S.CurrentRoute, loaded), "the route was not loaded again");
|
||||
Check.Eq(bot.Idx, 2, "still heading for [2] (it went back to [0] before)");
|
||||
Check.True(bot.S.EnableNavigation, "nav on");
|
||||
At(50, 0); bot.Tick();
|
||||
Check.Eq(bot.Idx, 3, "and carries on to [3]");
|
||||
}
|
||||
|
||||
private static void CircularKeepsWaypoint()
|
||||
{
|
||||
FakeHost.Reset(); At(0, 0);
|
||||
var bot = Running(Line(RT.Circular, 4)); // [0] 0, [1] 20, [2] 40, [3] 60
|
||||
bot.Tick();
|
||||
Check.Eq(bot.Idx, 1, "loaded at the nearest point [0], arrived, on to [1]");
|
||||
var loaded = bot.S.CurrentRoute;
|
||||
At(20, 0); bot.Tick();
|
||||
At(32, 0); bot.Tick(); // on the leg to [2]
|
||||
Check.Eq(bot.Idx, 2, "heading for [2]");
|
||||
|
||||
bot.StopStart();
|
||||
Check.True(ReferenceEquals(bot.S.CurrentRoute, loaded), "the route was not loaded again");
|
||||
Check.Eq(bot.Idx, 2, "still heading for [2]");
|
||||
|
||||
// Go To Closest Waypoint off: a loaded Circular route starts at [0], so the old reload sent it
|
||||
// back there; the waypoint is kept even after walking away from the route while stopped.
|
||||
bot.S.NavResumeNearest = false;
|
||||
bot.S.IsMacroRunning = false; bot.E.Stop(); bot.Ticks(2);
|
||||
At(5, 0); bot.Tick();
|
||||
bot.S.IsMacroRunning = true; bot.Ticks(3);
|
||||
Check.Eq(bot.Idx, 2, "option off: kept exactly");
|
||||
Check.True(ReferenceEquals(bot.S.CurrentRoute, loaded), "same route");
|
||||
}
|
||||
|
||||
private static void LinearKeepsDirection()
|
||||
{
|
||||
FakeHost.Reset(); At(0, 0);
|
||||
var bot = Running(Line(RT.Linear, 3)); // [0] 0, [1] 20, [2] 40
|
||||
bot.Tick();
|
||||
At(20, 0); bot.Tick();
|
||||
At(40, 0); bot.Tick();
|
||||
Check.Eq(bot.Idx, 1, "turned round at the end, heading back to [1]");
|
||||
Check.Eq(bot.Dir, -1, "heading back");
|
||||
At(33, 0); bot.Tick(); // on the way back, nearer [2] than [1]
|
||||
|
||||
bot.StopStart();
|
||||
Check.Eq(bot.Idx, 1, "still heading back to [1] (the reload sent it to the nearest point, [2])");
|
||||
Check.Eq(bot.Dir, -1, "direction kept (the reload turned it round)");
|
||||
At(20, 0); bot.Tick();
|
||||
Check.Eq(bot.Idx, 0, "carries on back to [0]");
|
||||
}
|
||||
|
||||
private static void FinishedOnceStaysFinished()
|
||||
{
|
||||
FakeHost.Reset(); At(0, 0);
|
||||
// As the CQ metas do: one Always rule switches nav on and loads the route.
|
||||
var all = Rule("Default", C.Always, "", A.All, "");
|
||||
all.ActionChildren.Add(new MetaRule { Action = A.ChatCommand, ActionData = "/vt opt set enablenav true" });
|
||||
all.ActionChildren.Add(new MetaRule { Action = A.EmbeddedNavRoute, ActionData = "R" });
|
||||
var done = Rule("Default", C.NavrouteEmpty, "", A.ExpressionAction, "setvar[done, getvar[done]+1]");
|
||||
var bot = new Bot(all, done);
|
||||
bot.S.EmbeddedNavs["R"] = Line(RT.Once, 2, from10: true).ToLines();
|
||||
bot.Tick();
|
||||
var loaded = bot.S.CurrentRoute;
|
||||
At(10, 0); bot.Tick();
|
||||
At(30, 0); bot.Tick();
|
||||
bot.Tick();
|
||||
Check.Eq(bot.Idx, 2, "finished: the index is past the end");
|
||||
Check.False(bot.S.EnableNavigation, "the end of a Once route turns nav off");
|
||||
Check.Eq(bot.Var("done"), "1", "Nav route empty fired");
|
||||
|
||||
At(0, 0); bot.Tick(); // walks back to the start
|
||||
bot.StopStart();
|
||||
bot.Ticks(5);
|
||||
Check.True(ReferenceEquals(bot.S.CurrentRoute, loaded), "the route was not loaded again");
|
||||
Check.Eq(bot.Idx, 2, "still finished (it ran again from [0] before)");
|
||||
Check.False(bot.S.EnableNavigation, "nav off again after the replayed enablenav");
|
||||
Check.False(FakeHost.AutoRun, "standing still");
|
||||
Check.Eq(bot.Var("done"), "2", "Nav route empty is true straight away after the start");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("Once route re-armed")), 0, "never re-armed");
|
||||
|
||||
// The engine alone: the macro-start closest pick leaves a finished route alone.
|
||||
bot.E.ResumeFromNearestWaypoint(always: true);
|
||||
Check.Eq(bot.Idx, 2, "the closest-waypoint pick (death recall, hazard escape) keeps it finished");
|
||||
// A meta or expression switching nav on: it stays finished.
|
||||
bot.S.EnableNavigation = true;
|
||||
bot.Ticks(2);
|
||||
Check.Eq(bot.Idx, 2, "nav switched on by a meta: still finished");
|
||||
Check.False(bot.S.EnableNavigation, "and nav off again");
|
||||
}
|
||||
|
||||
// ── Loading again starts fresh ────────────────────────────────────────────
|
||||
|
||||
private static void LoadAgainStartsFresh()
|
||||
{
|
||||
FakeHost.Reset(); At(0, 0);
|
||||
var bot = Running(Line(RT.Once, 4, from10: true));
|
||||
At(10, 0); bot.Tick();
|
||||
At(30, 0); bot.Tick();
|
||||
Check.Eq(bot.Idx, 2, "on [2]");
|
||||
|
||||
// A real state entry (SetMetaState to the state it is in) loads it fresh, as before.
|
||||
var first = bot.S.CurrentRoute;
|
||||
bot.S.ForceStateReset = true;
|
||||
bot.Tick();
|
||||
Check.False(ReferenceEquals(bot.S.CurrentRoute, first), "state entry: loaded again");
|
||||
Check.Eq(bot.Idx, 0, "state entry: a Once route starts at [0]");
|
||||
|
||||
// Edited while stopped: the replay loads the meta's copy fresh.
|
||||
At(10, 0); bot.Tick();
|
||||
At(30, 0); bot.Tick();
|
||||
Check.Eq(bot.Idx, 2, "on [2] again");
|
||||
bot.S.IsMacroRunning = false; bot.E.Stop(); bot.Ticks(2);
|
||||
var edited = bot.S.CurrentRoute;
|
||||
edited.Points.Add(Pt(90, 0));
|
||||
bot.S.IsMacroRunning = true; bot.Ticks(2);
|
||||
Check.False(ReferenceEquals(bot.S.CurrentRoute, edited), "edited: loaded again");
|
||||
Check.Eq(bot.S.CurrentRoute.Points.Count, 4, "from the meta's copy");
|
||||
Check.Eq(bot.Idx, 0, "edited: starts at [0]");
|
||||
|
||||
// Another route loaded while stopped: the meta puts its own back, fresh.
|
||||
bot.S.IsMacroRunning = false; bot.E.Stop(); bot.Ticks(2);
|
||||
bot.S.CurrentRoute = Line(RT.Circular, 2);
|
||||
bot.S.CurrentNavPath = "<embedded:Other>";
|
||||
bot.S.ActiveNavIndex = 1;
|
||||
bot.S.IsMacroRunning = true; bot.Ticks(2);
|
||||
Check.Eq(bot.S.CurrentNavPath, "<embedded:R>", "the meta's route is back");
|
||||
Check.Eq(bot.S.CurrentRoute.RouteType, RT.Once, "Once");
|
||||
Check.Eq(bot.Idx, 0, "at [0]");
|
||||
}
|
||||
|
||||
private static void FirstFireAfterStartIsFresh()
|
||||
{
|
||||
FakeHost.Reset(); At(0, 0);
|
||||
// Rule 2 reloads the same route after 30 s in the state; it hadn't fired when the macro stopped.
|
||||
var bot = Running(Line(RT.Once, 4, from10: true), EmbedNav("R", C.SecondsInState_GE, "30"));
|
||||
At(10, 0); bot.Tick();
|
||||
At(30, 0); bot.Tick();
|
||||
bot.StopStart();
|
||||
Check.Eq(bot.Idx, 2, "the replayed Always rule kept [2]");
|
||||
var kept = bot.S.CurrentRoute;
|
||||
bot.Tick(metaSeconds: 31);
|
||||
Check.False(ReferenceEquals(bot.S.CurrentRoute, kept), "the 30 s rule (a first fire, not a replay) loaded it again");
|
||||
Check.Eq(bot.Idx, 0, "fresh: [0]");
|
||||
}
|
||||
|
||||
private static void ChatNavLoadKept()
|
||||
{
|
||||
FakeHost.Reset(); At(0, 0);
|
||||
string folder = Path.Combine(Program.TempRoot, "nav-resume", "NavProfiles");
|
||||
Directory.CreateDirectory(folder);
|
||||
string path = Path.Combine(folder, "Hive.nav");
|
||||
Line(RT.Once, 4, from10: true).Save(path);
|
||||
|
||||
foreach (string cmd in new[] { "/vt nav load Hive", "/ra nav load Hive.nav" })
|
||||
{
|
||||
var bot = new Bot(Rule("Default", C.Always, "", A.ChatCommand, cmd));
|
||||
bot.M.NavFolder = folder;
|
||||
bot.Tick();
|
||||
Check.Eq(bot.Ra.Count, 1, $"{cmd}: the first start loads it through /ra nav load");
|
||||
// What /ra nav load did (LegacyDashboardRenderer.LoadSelectedNav), then walked to [2].
|
||||
bot.S.CurrentNavPath = path;
|
||||
bot.S.CurrentRoute = NavRouteParser.Load(path);
|
||||
bot.S.ActiveNavIndex = 0;
|
||||
bot.S.EnableNavigation = true;
|
||||
var loaded = bot.S.CurrentRoute;
|
||||
At(10, 0); bot.Tick();
|
||||
At(30, 0); bot.Tick();
|
||||
Check.Eq(bot.Idx, 2, $"{cmd}: on [2]");
|
||||
|
||||
bot.StopStart();
|
||||
Check.Eq(bot.Ra.Count, 1, $"{cmd}: the replay did not load it again");
|
||||
Check.True(ReferenceEquals(bot.S.CurrentRoute, loaded) && bot.Idx == 2, $"{cmd}: still on [2]");
|
||||
|
||||
// The file changed on disk: the replay loads it again, as before.
|
||||
var changed = Line(RT.Once, 5, from10: true);
|
||||
changed.Save(path);
|
||||
bot.StopStart();
|
||||
Check.Eq(bot.Ra.Count, 2, $"{cmd}: a changed file is loaded again");
|
||||
Line(RT.Once, 4, from10: true).Save(path);
|
||||
At(0, 0);
|
||||
}
|
||||
|
||||
// A state that restarts its route on entry: not again for a macro start.
|
||||
var restarter = new Bot(Rule("Default", C.Always, "", A.ChatCommand, "/ra nav restart"));
|
||||
restarter.Tick();
|
||||
Check.Eq(string.Join("|", restarter.Ra), "/ra nav restart", "on entering the state it runs");
|
||||
restarter.StopStart();
|
||||
Check.Eq(restarter.Ra.Count, 1, "a replayed /ra nav restart is not run again");
|
||||
restarter.S.ForceStateReset = true;
|
||||
restarter.Tick();
|
||||
Check.Eq(restarter.Ra.Count, 2, "a real state entry runs it again");
|
||||
}
|
||||
|
||||
// ── /ra nav restart and the player's Nav switch ───────────────────────────
|
||||
|
||||
private static void RestartCommand()
|
||||
{
|
||||
FakeHost.Reset(); At(0, 0);
|
||||
var s = new LegacyUiSettings { IsMacroRunning = true };
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
void Set(string f, object v) => typeof(LegacyDashboardRenderer).GetField(f, Any)!.SetValue(dash, v);
|
||||
Set("_settings", s);
|
||||
Set("_host", FakeHost.Create());
|
||||
Set("_navFiles", new List<string>());
|
||||
Set("_metaFiles", new List<string>());
|
||||
Set("_profileListsLock", new object());
|
||||
// _settingsFilePath stays null: SaveSettings writes nothing.
|
||||
|
||||
var plugin = new RynthAiPlugin();
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi });
|
||||
_now = 1_000_000;
|
||||
NavigationEngine.Clock = static () => _now;
|
||||
var engine = new NavigationEngine(FakeHost.Create(), s);
|
||||
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(plugin, dash);
|
||||
typeof(RynthAiPlugin).GetField("_navigationEngine", Any)!.SetValue(plugin, engine);
|
||||
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 });
|
||||
}
|
||||
void Tick() { _now += 100; engine.Tick(); }
|
||||
|
||||
Ra("/ra nav restart");
|
||||
Check.True(FakeHost.Chat.Exists(l => l.Contains("No nav route loaded to restart")), "nothing loaded: says so");
|
||||
|
||||
// A finished Once route.
|
||||
s.CurrentRoute = Line(RT.Once, 2, from10: true);
|
||||
s.ActiveNavIndex = 2;
|
||||
s.EnableNavigation = false;
|
||||
FakeHost.Chat.Clear();
|
||||
Ra("/ra nav restart");
|
||||
Check.Eq(s.ActiveNavIndex, 0, "restart: back to [0]");
|
||||
Check.True(s.EnableNavigation, "restart: nav on");
|
||||
Check.True(FakeHost.Chat.Exists(l => l.Contains("Nav route restarted from its first point (Once, 2 waypoints)")), "told: " + string.Join(" / ", FakeHost.Chat));
|
||||
Tick();
|
||||
Check.True(FakeHost.AutoRun, "and it walks");
|
||||
|
||||
// A Linear route heading back starts out again.
|
||||
s.CurrentRoute = Line(RT.Linear, 3);
|
||||
s.ActiveNavIndex = 0;
|
||||
At(0, 0); Tick();
|
||||
At(20, 0); Tick();
|
||||
At(40, 0); Tick();
|
||||
Check.Eq(engine.GetStateSnapshot().LinearDir, -1, "Linear heading back");
|
||||
Ra("/ra nav restart");
|
||||
Check.Eq(s.ActiveNavIndex, 0, "Linear restart: [0]");
|
||||
Check.Eq(engine.GetStateSnapshot().LinearDir, 1, "Linear restart: heading out");
|
||||
|
||||
// The player's Nav switch (dashboard, mini remote, phone) re-runs a finished Once route.
|
||||
s.CurrentRoute = Line(RT.Once, 2, from10: true);
|
||||
s.ActiveNavIndex = 2;
|
||||
s.EnableNavigation = false;
|
||||
dash.SetSubsystemEnabled(2, true);
|
||||
Check.Eq(s.ActiveNavIndex, 0, "Nav switch on: a finished Once route runs again from [0]");
|
||||
s.ActiveNavIndex = 1;
|
||||
dash.SetSubsystemEnabled(2, false);
|
||||
dash.SetSubsystemEnabled(2, true);
|
||||
Check.Eq(s.ActiveNavIndex, 1, "Nav switch off and on mid-route: the waypoint is kept");
|
||||
|
||||
FakeHost.Chat.Clear();
|
||||
Ra("/ra nav");
|
||||
Check.True(FakeHost.Chat.Exists(l => l.Contains("/ra nav restart")), "listed in the /ra nav usage");
|
||||
}
|
||||
}
|
||||
564
Tools/RynthCore.RynthAiHostTests/Tests/ShieldBuffTests.cs
Normal file
564
Tools/RynthCore.RynthAiHostTests/Tests/ShieldBuffTests.cs
Normal file
|
|
@ -0,0 +1,564 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The shield's armor spells (BuffManager.Shield.cs, 2026-10-28). Impenetrability and the Banes go
|
||||
// on the player, and ACE puts them on worn armor and a worn shield; but buffing holds a wand, ACE
|
||||
// won't wield one beside a shield, and the wand swap puts the shield into a pack first, so the
|
||||
// listed shield was never buffed. Now: the listed shield in use (in the off hand, or put away for
|
||||
// the wand) gets the armor's spells aimed at it, after the armor, on the armor's timers. Weapon
|
||||
// enchantments never go on it; an unlisted shield or a listed one that was in a pack is left alone;
|
||||
// a shield being moved waits; a refusal at the shield leaves the armor alone.
|
||||
internal static class ShieldBuffTests
|
||||
{
|
||||
private const uint Player = 0x50000E01;
|
||||
private const uint STypeItem = 32;
|
||||
private const uint Sword = 0x80000701, Kite = 0x80000702, Round = 0x80000703;
|
||||
private const int MeleeSlot = 0x00100000, ShieldSlot = 0x00200000;
|
||||
|
||||
private static readonly string[] Armor = { "Impenetrability VI", "Flame Bane VI", "Frost Bane VI" };
|
||||
private const string Aura = "Aura of Blood Drinker Self VI";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("shield buffs: the armor spells, never a weapon enchantment", WhichSpells);
|
||||
r.Add("shield buffs: the listed shield put away for the wand gets Impenetrability and the banes, aimed at it, after the armor", StowedShieldBuffed);
|
||||
r.Add("shield buffs: a shield worn in the off hand (no wand) is buffed; a self-cast line naming it counts for it", WornShieldBuffed);
|
||||
r.Add("shield buffs: no shield listed, an unlisted shield, a listed one already in a pack, or the switch off: nothing goes on a shield", NothingForOtherShields);
|
||||
r.Add("shield buffs: put away for the wand, back in the off hand, then into a pack by combat: no longer the one in use", StowedForgottenWhenBackOn);
|
||||
r.Add("shield buffs: a shield being moved is not cast at until the move settles", MidSwapWaits);
|
||||
r.Add("shield buffs: renewed on the armor's timers (Rebuff With, Also Refresh Under, Force Rebuff)", RenewedLikeArmor);
|
||||
r.Add("shield buffs: a fizzle, a refusal or a late armor line at the shield leaves the armor alone", RefusalsLeaveArmor);
|
||||
r.Add("shield buffs: casts at the shield with no answer, or 'cannot be cast on', rest shield buffing; the armor carries on", NoAnswerParks);
|
||||
r.Add("shield buffs: the shield's timers are saved and loaded with the others", TimersSaved);
|
||||
r.Add("shield buffs: Buff the shield defaults on, loads, saves, copies, is in the settings map", Setting);
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────────
|
||||
|
||||
private static readonly MethodInfo CastSelfBuffs =
|
||||
typeof(BuffManager).GetMethod("CheckAndCastSelfBuffs", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
private const BindingFlags F = BindingFlags.NonPublic | BindingFlags.Instance;
|
||||
|
||||
private static int Id(string name) => SpellTable.Named(name).Select(r => r.Id).FirstOrDefault();
|
||||
private static string NameOf(int id) => SpellTable.ById(id)?.Name ?? $"#{id}";
|
||||
private static int FamilyOf(string name) => SpellTableStub.GetById(Id(name))?.Family ?? 0;
|
||||
private static T Fld<T>(BuffManager b, string name) => (T)typeof(BuffManager).GetField(name, F)!.GetValue(b)!;
|
||||
private static void SetFld(BuffManager b, string name, object v) => typeof(BuffManager).GetField(name, F)!.SetValue(b, v);
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S = new() { EnableBuffing = true };
|
||||
public readonly BuffManager B;
|
||||
public readonly SpellManager Sm;
|
||||
public readonly RynthCoreHost Host;
|
||||
public readonly WeaponSwapGate Gate = new();
|
||||
public long GateMs;
|
||||
public int Stowed;
|
||||
|
||||
/// <summary>Item Magic 300 (tier 6), in Magic stance, knowing Impenetrability, two banes and Blood Drinker.
|
||||
/// A sword and the Kite Shield listed; <paramref name="worn"/>: the Kite Shield in the off hand.</summary>
|
||||
public Rig(bool worn = false, bool listShield = true)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
foreach (string n in Armor.Append(Aura)) foreach (var row in SpellTable.Named(n)) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, STypeItem)] = (300, 2);
|
||||
FakeHost.WeaponCalls = true; // GetCurrentCombatMode answers CombatModeValue
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
Item(Sword, "Long Sword", 0x1, MeleeSlot, combatUse: 1);
|
||||
Item(Kite, "Kite Shield", 0x2, ShieldSlot, combatUse: 4);
|
||||
Item(Round, "Round Shield", 0x2, ShieldSlot, combatUse: 4);
|
||||
if (worn) Wear(Kite);
|
||||
Host = FakeHost.Create(Player);
|
||||
var cache = FakeHost.MakeCache(Host, Player, new[] { Sword, Kite, Round });
|
||||
var skills = new CharacterSkills(Host);
|
||||
skills.SetPlayerId(Player);
|
||||
Sm = new SpellManager(Host, S);
|
||||
Sm.InitializeNatively();
|
||||
Sm.SetCharacterSkills(skills);
|
||||
B = new BuffManager(Host, S, Sm, new PlayerVitalsCache());
|
||||
B.SetCharacterSkills(skills);
|
||||
B.SetWorldObjectCache(cache);
|
||||
Gate.NowMs = () => GateMs;
|
||||
B.SetWeaponSwapGate(Gate);
|
||||
B.ShieldReadMs = 0;
|
||||
B.OffhandStowed = id => Stowed = id;
|
||||
FakeHost.ServerTime = 100_000;
|
||||
List(listShield ? new[] { Sword, Kite } : new[] { Sword });
|
||||
}
|
||||
|
||||
public void List(params uint[] ids) =>
|
||||
S.ItemRules = ids.Select(i => new ItemRule
|
||||
{
|
||||
Id = unchecked((int)i), Name = FakeHost.Names[i], Element = "", ElementSource = "",
|
||||
Action = i == Kite || i == Round ? WeaponList.ShieldAction : "Weapon",
|
||||
}).ToList();
|
||||
|
||||
/// <summary>The wand swap put the Kite Shield into a pack (BuffManager's MoveToPack step).</summary>
|
||||
public void PutAwayForWand()
|
||||
{
|
||||
B.OffhandPutAway(unchecked((int)Kite));
|
||||
Unwear(Kite);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The buff step until it casts nothing, every cast answered as the server would: a cast at the
|
||||
/// player names the armor (and, with <paramref name="alsoOnShield"/>, the worn shield too), a cast
|
||||
/// at a shield names it. Ends the run as the heartbeat does. Returns "spell@target" in order.
|
||||
/// </summary>
|
||||
public List<string> CastAll(Func<string, bool>? alsoOnShield = null, int max = 40)
|
||||
{
|
||||
var sent = new List<string>();
|
||||
for (int i = 0; i < max; i++)
|
||||
{
|
||||
int before = FakeHost.Casts.Count;
|
||||
CastSelfBuffs.Invoke(B, null);
|
||||
if (FakeHost.Casts.Count == before) break;
|
||||
var (target, id) = FakeHost.Casts.Last();
|
||||
string name = NameOf(id);
|
||||
sent.Add($"{name}@{Where(target)}");
|
||||
Answer(target, name, alsoOnShield?.Invoke(name) == true);
|
||||
}
|
||||
EndRun();
|
||||
return sent;
|
||||
}
|
||||
|
||||
public void Answer(uint target, string name, bool alsoOnShield = false)
|
||||
{
|
||||
if (target == Player)
|
||||
{
|
||||
B.OnChatWindowText($"You cast {name} on {(BuffManager.IsItemEnchantment(name) ? "Rune Robe" : "yourself")}", 7);
|
||||
if (alsoOnShield) B.OnChatWindowText($"You cast {name} on Kite Shield, refreshing {name}", 7);
|
||||
}
|
||||
else B.OnChatWindowText($"You cast {name} on {FakeHost.Names[target]}", 7);
|
||||
}
|
||||
|
||||
public void EndRun()
|
||||
{
|
||||
if (!(bool)typeof(BuffManager).GetField("_isForceRebuffing", F)!.GetValue(B)!) return;
|
||||
SetFld(B, "_isForceRebuffing", false);
|
||||
SetFld(B, "_isAutoBatchRebuff", false);
|
||||
typeof(BuffManager).GetMethod("ClearRunFamilies", F)!.Invoke(B, null);
|
||||
}
|
||||
|
||||
public void SetShieldLeft(string spell, double seconds) =>
|
||||
SetLeft(Record("_shieldSpellTimers", BuffManager.ShieldKey(unchecked((int)Kite), FamilyOf(spell))), seconds);
|
||||
|
||||
public void SetArmorLeft(string spell, double seconds) => SetLeft(Record("_itemSpellTimers", FamilyOf(spell)), seconds);
|
||||
|
||||
private static void SetLeft(object rec, double seconds) => rec.GetType().GetField("ExpiresAt")!.SetValue(rec, DateTime.Now.AddSeconds(seconds));
|
||||
|
||||
public object Record(string field, object key) => ((IDictionary)Fld<object>(B, field))[key]!;
|
||||
public bool HasShield(string spell) => ((IDictionary)Fld<object>(B, "_shieldSpellTimers")).Contains(BuffManager.ShieldKey(unchecked((int)Kite), FamilyOf(spell)));
|
||||
public bool HasArmor(string spell) => ((IDictionary)Fld<object>(B, "_itemSpellTimers")).Contains(FamilyOf(spell));
|
||||
}
|
||||
|
||||
private static string Where(uint target) => target == Player ? "player" : FakeHost.Names.TryGetValue(target, out string? n) ? n : $"0x{target:X8}";
|
||||
|
||||
private static void Item(uint id, string name, uint itemType, int validSlots, int combatUse = 0)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.ItemTypes[id] = itemType;
|
||||
FakeHost.Ints[(id, 9)] = validSlots;
|
||||
if (combatUse != 0) FakeHost.Ints[(id, 51)] = combatUse;
|
||||
}
|
||||
|
||||
private static void Wear(uint id) => FakeHost.Ints[(id, 10)] = ShieldSlot;
|
||||
private static void Unwear(uint id) => FakeHost.Ints.Remove((id, 10));
|
||||
|
||||
private static IEnumerable<string> At(List<string> sent, string target) =>
|
||||
sent.Where(s => s.EndsWith("@" + target, StringComparison.Ordinal)).Select(s => s.Substring(0, s.LastIndexOf('@')));
|
||||
|
||||
private static string ArmorAtPlayer => string.Join(", ", Armor);
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void WhichSpells()
|
||||
{
|
||||
foreach (string n in new[] { "Impenetrability VI", "Brogard's Defiance", "Incantation of Impenetrability", "Flame Bane VI",
|
||||
"Swordsman's Bane", "Incantation of Bludgeon Bane", "Acid Bane", "Piercing Bane" })
|
||||
Check.True(BuffManager.IsArmorItemSpell(n), $"an armor spell: {n}");
|
||||
foreach (string n in new[] { "Blood Drinker Self", Aura, "Aura of Infected Caress", "Defender Self", "Aura of Cragstone's Will",
|
||||
"Heart Seeker Self", "Spirit Drinker Self", "Armor Self", "Impregnability Self VI", "Strength Self VI" })
|
||||
Check.False(BuffManager.IsArmorItemSpell(n), $"not an armor spell: {n}");
|
||||
|
||||
Check.Eq(BuffManager.CastTarget("Flame Bane VI on Kite Shield, refreshing Flame Bane V"), "Kite Shield", "the target, before the comma");
|
||||
Check.Eq(BuffManager.CastTarget("Impenetrability VI on Kite Shield"), "Kite Shield", "the target alone");
|
||||
Check.Eq(BuffManager.CastTarget("Strength Self VI"), "", "no target");
|
||||
Check.True(BuffManager.ShieldKey(1, 2) != BuffManager.ShieldKey(2, 1), "the key keeps the shield and the family apart");
|
||||
}
|
||||
|
||||
private static void StowedShieldBuffed()
|
||||
{
|
||||
var rig = new Rig(worn: true);
|
||||
rig.PutAwayForWand(); // what the wand swap does before the first cast
|
||||
Check.Eq(rig.Stowed, unchecked((int)Kite), "combat is still told, so it puts the shield back on");
|
||||
Check.Eq(rig.B.ShieldToBuff(out string where), unchecked((int)Kite), "the shield to buff: " + where);
|
||||
Check.True(rig.B.NeedsAnyBuff(), "nothing on: needs buffs");
|
||||
|
||||
var sent = rig.CastAll();
|
||||
Check.Eq(string.Join(", ", At(sent, "player")), $"{Aura}, {ArmorAtPlayer}", "the character's buffs first, as before");
|
||||
Check.Eq(string.Join(", ", At(sent, "Kite Shield")), ArmorAtPlayer, "then Impenetrability and both banes at the shield");
|
||||
Check.True(sent.Last().EndsWith("@Kite Shield", StringComparison.Ordinal) && sent.FindIndex(s => s.EndsWith("@Kite Shield")) == 4,
|
||||
"the shield's after every cast on the player: " + string.Join(", ", sent));
|
||||
Check.False(FakeHost.Casts.Any(c => c.Target == Kite && NameOf(c.SpellId) == Aura), "Blood Drinker never at the shield");
|
||||
Check.Eq(rig.B.ShieldSpellCount, 3, "three timers on the shield");
|
||||
foreach (string a in Armor) Check.True(rig.HasArmor(a) && rig.HasShield(a), $"{a}: the armor's and the shield's timer");
|
||||
Check.False(rig.B.NeedsAnyBuff(), "all on: nothing due");
|
||||
Check.Eq(rig.CastAll().Count, 0, "and nothing more is cast");
|
||||
|
||||
// Force Rebuff: the armor and the shield again, still no weapon enchantment at it.
|
||||
rig.B.ForceFullRebuff();
|
||||
sent = rig.CastAll();
|
||||
Check.Eq(string.Join(", ", At(sent, "Kite Shield")), ArmorAtPlayer, "Force Rebuff recasts the shield's too");
|
||||
Check.False(FakeHost.Casts.Any(c => c.Target == Kite && !BuffManager.IsArmorItemSpell(NameOf(c.SpellId))), "only armor spells ever at the shield");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[Buff] shield: 0x") && l.Contains("put into a pack for the wand")), "the shield picked is logged");
|
||||
}
|
||||
|
||||
private static void WornShieldBuffed()
|
||||
{
|
||||
// Magic without a wand: the shield stays on, the self-cast's lines don't name it.
|
||||
var rig = new Rig(worn: true);
|
||||
Check.Eq(rig.B.ShieldToBuff(out string where), unchecked((int)Kite), "the worn shield: " + where);
|
||||
Check.Eq(where, "in the off hand", "in the off hand");
|
||||
var sent = rig.CastAll();
|
||||
Check.Eq(string.Join(", ", At(sent, "Kite Shield")), ArmorAtPlayer, "each armor spell aimed at the worn shield");
|
||||
|
||||
// The server's self-cast reached the worn shield: its line names it. Flame Bane's shield line
|
||||
// comes after the armor's, Impenetrability's before (the self-cast still resolves by it).
|
||||
var both = new Rig(worn: true);
|
||||
sent = both.CastAll(alsoOnShield: n => n == "Flame Bane VI");
|
||||
Check.Eq(string.Join(", ", At(sent, "Kite Shield")), "Impenetrability VI, Frost Bane VI", "Flame Bane's line named the shield: only the other two are cast at it");
|
||||
Check.True(both.HasShield("Flame Bane VI") && both.HasArmor("Flame Bane VI"), "that line counts for the shield, and the armor's line for the armor");
|
||||
|
||||
var first = new Rig(worn: true);
|
||||
first.B.ForceFullRebuff();
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
int before = FakeHost.Casts.Count;
|
||||
CastSelfBuffs.Invoke(first.B, null);
|
||||
if (FakeHost.Casts.Count == before) break;
|
||||
var (target, id) = FakeHost.Casts.Last();
|
||||
string name = NameOf(id);
|
||||
if (target == Player && name == "Impenetrability VI")
|
||||
{
|
||||
first.B.OnChatWindowText("You cast Impenetrability VI on Kite Shield", 7); // the shield's line first
|
||||
Check.Eq(first.B.PendingSpellId, 0, "the self-cast is resolved by the shield's line too");
|
||||
first.B.OnChatWindowText("You cast Impenetrability VI on Rune Robe", 7);
|
||||
}
|
||||
else first.Answer(target, name);
|
||||
}
|
||||
first.EndRun();
|
||||
Check.True(first.HasShield("Impenetrability VI") && first.HasArmor("Impenetrability VI"), "both timers");
|
||||
Check.False(FakeHost.Casts.Any(c => c.Target == Kite && NameOf(c.SpellId) == "Impenetrability VI"), "Impenetrability isn't cast at the shield again");
|
||||
}
|
||||
|
||||
private static void NothingForOtherShields()
|
||||
{
|
||||
// The baseline: no shield listed (a worn one), exactly the casts there always were.
|
||||
var none = new Rig(worn: true, listShield: false);
|
||||
var sent = none.CastAll();
|
||||
Check.Eq(string.Join(", ", sent), $"{Aura}@player, " + string.Join(", ", Armor.Select(a => a + "@player")), "no shield listed: the same casts as before");
|
||||
Check.Eq(none.B.ShieldToBuff(out _), 0, "no shield to buff");
|
||||
Check.False(none.B.NeedsAnyBuff(), "and nothing due");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("[Buff] shield:")), "nothing logged about shields");
|
||||
|
||||
// An unlisted shield worn, the listed one in a pack and never put away by buffing.
|
||||
var unlisted = new Rig();
|
||||
Wear(Round);
|
||||
sent = unlisted.CastAll();
|
||||
Check.Eq(At(sent, "Round Shield").Count() + At(sent, "Kite Shield").Count(), 0, "nothing at the unlisted worn shield, nor the listed one in a pack");
|
||||
Check.Eq(unlisted.B.ShieldToBuff(out string why), 0, "none to buff: " + why);
|
||||
Check.True(why.Contains("in a pack"), "the reason says it is in a pack");
|
||||
Check.False(unlisted.B.NeedsAnyBuff(), "nothing due: a shield in a pack doesn't hold Buffing");
|
||||
|
||||
// A shield filed with the Weapon action is still a listed shield.
|
||||
var asWeapon = new Rig(worn: true);
|
||||
asWeapon.S.ItemRules = new List<ItemRule>
|
||||
{
|
||||
new() { Id = unchecked((int)Sword), Name = "Long Sword", Action = "Weapon", Element = "", ElementSource = "" },
|
||||
new() { Id = unchecked((int)Kite), Name = "Kite Shield", Action = "Weapon", Element = "", ElementSource = "" },
|
||||
};
|
||||
Check.Eq(asWeapon.B.ShieldToBuff(out _), unchecked((int)Kite), "a shield listed as a weapon is the listed shield");
|
||||
|
||||
// Buff the shield off.
|
||||
var off = new Rig(worn: true);
|
||||
off.S.BuffShield = false;
|
||||
sent = off.CastAll();
|
||||
Check.Eq(At(sent, "Kite Shield").Count(), 0, "switch off: nothing at the shield");
|
||||
Check.Eq(string.Join(", ", At(sent, "player")), $"{Aura}, {ArmorAtPlayer}", "the armor as always");
|
||||
Check.False(off.B.NeedsAnyBuff(), "and nothing due");
|
||||
|
||||
// Banes unticked for the armor are unticked for the shield.
|
||||
var unticked = new Rig(worn: true);
|
||||
unticked.S.SetBuffEnabled("Flame Bane", false);
|
||||
sent = unticked.CastAll();
|
||||
Check.Eq(string.Join(", ", At(sent, "Kite Shield")), "Impenetrability VI, Frost Bane VI", "an unticked bane goes on neither");
|
||||
Check.False(At(sent, "player").Contains("Flame Bane VI"), "(nor the armor)");
|
||||
}
|
||||
|
||||
private static void StowedForgottenWhenBackOn()
|
||||
{
|
||||
var rig = new Rig(worn: true);
|
||||
rig.PutAwayForWand();
|
||||
Wear(Kite); // combat put it back on
|
||||
Check.Eq(rig.B.ShieldToBuff(out _), unchecked((int)Kite), "in the off hand");
|
||||
Unwear(Kite); // still within the grace: a stow just sent
|
||||
Check.Eq(rig.B.ShieldToBuff(out string where), unchecked((int)Kite), "a sighting right after the stow doesn't forget it: " + where);
|
||||
|
||||
Wear(Kite);
|
||||
SetFld(rig.B, "_stowedShieldAt", DateTime.Now.AddSeconds(-30));
|
||||
Check.Eq(rig.B.ShieldToBuff(out _), unchecked((int)Kite), "back in the off hand for a while");
|
||||
Unwear(Kite); // combat took it off for a two-hander
|
||||
Check.Eq(rig.B.ShieldToBuff(out where), 0, "then in a pack by combat's hand: not the one in use (" + where + ")");
|
||||
rig.PutAwayForWand();
|
||||
Check.Eq(rig.B.ShieldToBuff(out _), unchecked((int)Kite), "put away for the wand again: buffed again");
|
||||
}
|
||||
|
||||
private static void MidSwapWaits()
|
||||
{
|
||||
var rig = new Rig(worn: true);
|
||||
rig.PutAwayForWand();
|
||||
// Combat's off-hand move of the shield, just claimed (the gate waits MinIntervalMs for it).
|
||||
rig.GateMs = 1000;
|
||||
Check.True(rig.Gate.TryBeginSwap("combat-offhand"), "a swap claimed");
|
||||
rig.Gate.NoteMove(unchecked((int)Kite), wieldedNow: false);
|
||||
var sent = rig.CastAll();
|
||||
Check.Eq(At(sent, "Kite Shield").Count(), 0, "nothing at the shield while it moves");
|
||||
Check.Eq(string.Join(", ", At(sent, "player")), $"{Aura}, {ArmorAtPlayer}", "the character's buffs don't wait");
|
||||
Check.True((bool)CastSelfBuffs.Invoke(rig.B, null)!, "the step holds the tick (not done)");
|
||||
Check.True(rig.B.LastBuffSkipReason.Contains("being moved"), "and says why: " + rig.B.LastBuffSkipReason);
|
||||
rig.EndRun();
|
||||
Check.True(rig.B.NeedsAnyBuff(), "the shield is still due");
|
||||
|
||||
rig.GateMs = 1000 + rig.Gate.MinIntervalMs + 1; // the move has settled
|
||||
sent = rig.CastAll();
|
||||
Check.Eq(string.Join(", ", At(sent, "Kite Shield")), ArmorAtPlayer, "settled: the shield's spells go");
|
||||
|
||||
// A multi-step swap holding the gate: wait; released: go.
|
||||
var held = new Rig(worn: true);
|
||||
held.PutAwayForWand();
|
||||
held.Gate.Hold("combat-fight-swap", 60_000);
|
||||
sent = held.CastAll();
|
||||
Check.Eq(At(sent, "Kite Shield").Count(), 0, "a held swap: nothing at the shield");
|
||||
held.Gate.Release("combat-fight-swap", 0);
|
||||
sent = held.CastAll();
|
||||
Check.Eq(string.Join(", ", At(sent, "Kite Shield")), ArmorAtPlayer, "released: the shield's spells go");
|
||||
}
|
||||
|
||||
private static void RenewedLikeArmor()
|
||||
{
|
||||
var rig = new Rig(worn: true);
|
||||
rig.PutAwayForWand();
|
||||
rig.CastAll();
|
||||
foreach (string a in Armor)
|
||||
{
|
||||
object s = rig.Record("_shieldSpellTimers", BuffManager.ShieldKey(unchecked((int)Kite), FamilyOf(a)));
|
||||
object m = rig.Record("_itemSpellTimers", FamilyOf(a));
|
||||
double Len(object rec) => ((DateTime)rec.GetType().GetField("ExpiresAt")!.GetValue(rec)! - (DateTime)rec.GetType().GetField("CastAt")!.GetValue(rec)!).TotalSeconds;
|
||||
Check.Near(Len(s), Len(m), 0.5, $"{a}: the shield's timer is as long as the armor's");
|
||||
Check.Near(Len(s), 2700, 0.5, $"{a}: 45 minutes at level 6");
|
||||
}
|
||||
Check.False(rig.B.NeedsAnyBuff(), "all on");
|
||||
|
||||
// The shield's Flame Bane under Rebuff With (300 s): due on its own, and only it is recast.
|
||||
rig.SetShieldLeft("Flame Bane VI", 100);
|
||||
Check.True(rig.B.NeedsAnyBuff(), "the shield's bane running out: due, like the armor's");
|
||||
var sent = rig.CastAll();
|
||||
Check.Eq(string.Join(", ", sent), "Flame Bane VI@Kite Shield", "only that one, at the shield");
|
||||
|
||||
// The armor's Frost Bane under Rebuff With, the shield's under Also Refresh Under (1200 s): they land together.
|
||||
rig.SetArmorLeft("Frost Bane VI", 100);
|
||||
rig.SetShieldLeft("Frost Bane VI", 1000);
|
||||
sent = rig.CastAll();
|
||||
Check.Eq(string.Join(", ", sent), "Frost Bane VI@player, Frost Bane VI@Kite Shield", "the batch tops off the shield's with the armor's");
|
||||
|
||||
// Under Also Refresh Under alone starts nothing, as for the armor.
|
||||
rig.SetShieldLeft("Impenetrability VI", 1000);
|
||||
Check.False(rig.B.NeedsAnyBuff(), "1000 s left is no reason to buff");
|
||||
rig.S.RebuffSecondsRemaining = 1100;
|
||||
Check.True(rig.B.NeedsAnyBuff(), "with Rebuff With 1100 it is");
|
||||
rig.S.RebuffSecondsRemaining = 300;
|
||||
|
||||
// A death (the player's registry empties) forgets the shield's, as the armor's.
|
||||
FakeHost.Enchantments.Clear();
|
||||
FakeHost.Enchantments.Add(((uint)Id("Strength Self I"), FakeHost.ServerTime + 3000)); // something on, then nothing
|
||||
rig.B.RefreshFromLiveMemory();
|
||||
FakeHost.Enchantments.Clear();
|
||||
rig.B.RefreshFromLiveMemory();
|
||||
Check.Eq(rig.B.ShieldSpellCount, 0, "a death clears the shield's timers");
|
||||
Check.True(rig.B.NeedsAnyBuff(), "and they are due again");
|
||||
}
|
||||
|
||||
/// <summary>Runs the step until a cast at the Kite Shield is pending (everything else answered); its spell.</summary>
|
||||
private static string ToFirstShieldCast(Rig rig)
|
||||
{
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
int before = FakeHost.Casts.Count;
|
||||
CastSelfBuffs.Invoke(rig.B, null);
|
||||
if (FakeHost.Casts.Count == before) return "";
|
||||
var (target, id) = FakeHost.Casts.Last();
|
||||
if (target == Kite) return NameOf(id);
|
||||
rig.Answer(target, NameOf(id));
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private static Dictionary<int, DateTime> ArmorParks(Rig rig) => Fld<Dictionary<int, DateTime>>(rig.B, "_buffFailCooldownUntil");
|
||||
|
||||
private static void RefusalsLeaveArmor()
|
||||
{
|
||||
var rig = new Rig(worn: true);
|
||||
rig.PutAwayForWand();
|
||||
rig.B.ForceFullRebuff();
|
||||
string first = ToFirstShieldCast(rig);
|
||||
Check.Eq(first, "Impenetrability VI", "the first cast at the shield");
|
||||
|
||||
// A late armor line of the same family while the shield's cast waits: the armor's, pending kept.
|
||||
rig.B.OnChatWindowText("You cast Impenetrability VI on Rune Robe", 7);
|
||||
Check.Eq(rig.B.PendingSpellId, Id("Impenetrability VI"), "the shield's cast still waits for its own line");
|
||||
Check.False(rig.HasShield("Impenetrability VI"), "the armor's line doesn't count for the shield");
|
||||
|
||||
// A fizzle at the shield: the armor's timer stays, the shield's spell goes again.
|
||||
rig.B.OnChatWindowText("Your spell fizzled.", 7);
|
||||
Check.Eq(rig.B.PendingSpellId, 0, "the fizzle ends the cast");
|
||||
Check.True(rig.HasArmor("Impenetrability VI"), "the armor's Impenetrability is still on");
|
||||
Check.Eq(ToFirstShieldCast(rig), "Impenetrability VI", "and it is cast at the shield again");
|
||||
|
||||
// No components, at the shield: it rests on the shield only; the next bane goes at it.
|
||||
rig.B.OnChatWindowText("You don't have all the components for this spell.", 7);
|
||||
Check.True(rig.HasArmor("Impenetrability VI"), "the armor's timer stays");
|
||||
Check.False(ArmorParks(rig).ContainsKey(FamilyOf("Impenetrability VI")), "the armor's family isn't parked");
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("Skipping Impenetrability VI on the shield")), "the chat line says on the shield");
|
||||
Check.Eq(ToFirstShieldCast(rig), "Flame Bane VI", "the next spell goes at the shield");
|
||||
rig.Answer(Kite, "Flame Bane VI");
|
||||
|
||||
// Not enough mana at the shield: the same, the armor's family untouched.
|
||||
Check.Eq(ToFirstShieldCast(rig), "Frost Bane VI", "Frost Bane at the shield");
|
||||
rig.B.OnChatWindowText("You don't have enough Mana to cast this spell.", 7);
|
||||
Check.Eq(rig.B.PendingSpellId, 0, "the mana refusal ends it");
|
||||
Check.True(rig.HasArmor("Frost Bane VI"), "the armor's Frost Bane stays");
|
||||
Check.False(ArmorParks(rig).ContainsKey(FamilyOf("Frost Bane VI")), "nor is the armor's family rested");
|
||||
|
||||
// Too busy at the shield: the armor's timer stays.
|
||||
var busy = new Rig(worn: true);
|
||||
busy.PutAwayForWand();
|
||||
Check.Eq(ToFirstShieldCast(busy), "Impenetrability VI", "a cast at the shield");
|
||||
busy.B.OnChatWindowText("You're too busy!", 7);
|
||||
Check.Eq(busy.B.PendingSpellId, 0, "too busy: no longer pending");
|
||||
Check.True(busy.HasArmor("Impenetrability VI"), "the armor's timer stays");
|
||||
}
|
||||
|
||||
private static void NoAnswerParks()
|
||||
{
|
||||
var rig = new Rig(worn: true);
|
||||
rig.PutAwayForWand();
|
||||
rig.S.IsMacroRunning = true;
|
||||
rig.S.SpellCastIntervalMs = 0;
|
||||
DateTime t0 = new DateTime(2026, 10, 28, 12, 0, 0), now = t0;
|
||||
rig.B.Clock = () => now;
|
||||
rig.B.MarkLiveBuffsReadyForTests();
|
||||
FakeHost.Enchantments.Add(((uint)Id("Strength Self I"), FakeHost.ServerTime + 3000)); // a registry with something on
|
||||
rig.B.RefreshFromLiveMemory();
|
||||
|
||||
// The heartbeat, every cast at the player answered, the shield's never.
|
||||
int shieldSends = 0;
|
||||
for (int i = 0; i < 80; i++)
|
||||
{
|
||||
now = now.AddSeconds(3);
|
||||
int before = FakeHost.Casts.Count;
|
||||
rig.B.OnHeartbeat();
|
||||
if (FakeHost.Casts.Count == before)
|
||||
{
|
||||
if (rig.B.PendingSpellId != 0 && FakeHost.Casts.Count > 0 && FakeHost.Casts.Last().Target == Kite)
|
||||
SetFld(rig.B, "_lastCastAttempt", DateTime.Now.AddSeconds(-6)); // its give-up reached
|
||||
continue;
|
||||
}
|
||||
var (target, id) = FakeHost.Casts.Last();
|
||||
if (target == Kite) { shieldSends++; continue; }
|
||||
rig.Answer(target, NameOf(id));
|
||||
}
|
||||
Check.Eq(shieldSends, BuffManager.ShieldNoShowsToPark, $"{BuffManager.ShieldNoShowsToPark} casts at the shield, no more");
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("Not buffing the shield 'Kite Shield'")), "the rest is said in chat");
|
||||
Check.False(rig.B.NeedsAnyBuff(), "parked: the shield doesn't hold Buffing");
|
||||
Check.Eq(ArmorParks(rig).Count, 0, "no armor family parked");
|
||||
Check.Eq(Fld<Dictionary<int, int>>(rig.B, "_silentNoShowCounts").Count, 0, "no armor no-show strikes");
|
||||
Check.Eq(rig.Sm.UnresolvableSpellIds.Count, 0, "no spell blacklisted (it just went on the armor)");
|
||||
Check.True(Armor.All(rig.HasArmor), "the armor got everything");
|
||||
|
||||
// "cannot be cast on" (ACE IsInvalidTarget) parks it at once.
|
||||
var invalid = new Rig(worn: true);
|
||||
invalid.PutAwayForWand();
|
||||
Check.Eq(ToFirstShieldCast(invalid), "Impenetrability VI", "a cast at the shield");
|
||||
invalid.B.OnChatWindowText("Impenetrability VI cannot be cast on Kite Shield.", 7);
|
||||
Check.Eq(invalid.B.PendingSpellId, 0, "it ends the cast");
|
||||
invalid.EndRun();
|
||||
Check.False(invalid.B.NeedsAnyBuff(), "the shield rests");
|
||||
Check.Eq(invalid.CastAll().Count, 0, "nothing more at it");
|
||||
invalid.B.ForceFullRebuff();
|
||||
Check.Eq(string.Join(", ", At(invalid.CastAll(), "Kite Shield")), ArmorAtPlayer, "Force Rebuff gives it a fresh try");
|
||||
|
||||
// The same line with nothing aimed at a shield changes nothing.
|
||||
var other = new Rig(worn: true, listShield: false);
|
||||
other.B.OnChatWindowText("Impenetrability VI cannot be cast on Kite Shield.", 7);
|
||||
Check.True(other.B.NeedsAnyBuff(), "no shield cast pending: the line is not read");
|
||||
}
|
||||
|
||||
private static void TimersSaved()
|
||||
{
|
||||
string folder = Path.Combine(Program.TempRoot, "shieldbuff");
|
||||
Directory.CreateDirectory(folder);
|
||||
var rig = new Rig(worn: true);
|
||||
rig.B.SetTimerPath(folder);
|
||||
rig.PutAwayForWand();
|
||||
rig.CastAll();
|
||||
string[] lines = File.ReadAllLines(Path.Combine(folder, "bufftimers.txt"));
|
||||
Check.Eq(lines.Count(l => l.StartsWith("shield|", StringComparison.Ordinal)), 3, "three shield lines");
|
||||
Check.Eq(lines.Count(l => l.StartsWith("item|", StringComparison.Ordinal)), 4, "and the four item lines (the armor's and the aura)");
|
||||
|
||||
var again = new Rig(worn: true);
|
||||
again.PutAwayForWand();
|
||||
again.B.SetTimerPath(folder);
|
||||
Check.Eq(again.B.ShieldSpellCount, 3, "loaded back");
|
||||
Check.True(Armor.All(again.HasArmor), "with the armor's");
|
||||
Check.Eq(again.CastAll().Count, 0, "nothing due after the reload");
|
||||
}
|
||||
|
||||
private static void Setting()
|
||||
{
|
||||
Check.True(new LegacyUiSettings().BuffShield, "a new profile: on");
|
||||
var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true,\"RebuffSecondsRemaining\":300}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(old != null && old.BuffShield, "a profile saved before the setting: on");
|
||||
var off = JsonSerializer.Deserialize(
|
||||
JsonSerializer.Serialize(new LegacyUiSettings { BuffShield = false }, RynthAiJsonContext.Default.LegacyUiSettings),
|
||||
RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(off != null && !off.BuffShield, "off is saved and loaded");
|
||||
|
||||
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
var dst = new LegacyUiSettings();
|
||||
copy.Invoke(null, new object[] { new LegacyUiSettings { BuffShield = false }, dst });
|
||||
Check.False(dst.BuffShield, "a profile with it off loads off");
|
||||
copy.Invoke(null, new object[] { old!, dst });
|
||||
Check.True(dst.BuffShield, "an old profile loads on");
|
||||
|
||||
var live = new LegacyUiSettings();
|
||||
var map = ExpressionTests.Engine(settings: live).BuildSettingsMapPublic();
|
||||
Check.True(map.TryGetValue("BuffShield", out var entry), "BuffShield is in the settings map");
|
||||
Check.Eq(entry.Get(), "1", "reads on");
|
||||
entry.Set("0");
|
||||
Check.False(live.BuffShield, "and sets off");
|
||||
}
|
||||
}
|
||||
|
|
@ -125,8 +125,8 @@ namespace RynthDefective.Tests
|
|||
int saves = b.R.Saves;
|
||||
string m = b.S.SetIndependent(true);
|
||||
Check(b.S.Settings.IndependentBar && b.R.Saves > saves, "turned on, saved");
|
||||
Eq(b.S.CopyOffer, 5, "the offer counts the game's slots with an item (not the spell)");
|
||||
Check(m.Contains("independent") && m.Contains("5 items") && m.Contains("offers to copy"), "and says so: " + m);
|
||||
Eq(b.S.CopyOffer, 6, "the offer counts the game's slots with an item or a spell");
|
||||
Check(m.Contains("independent") && m.Contains("6 shortcuts") && m.Contains("offers to copy"), "and says so: " + m);
|
||||
Check(b.S.Data.Slots[0].Item!.Id == own1.Id && b.S.Data.Slots[1].Item!.Id == own2.Id && b.S.Data.Slots[2].Empty,
|
||||
"turning it on copies nothing by itself");
|
||||
|
||||
|
|
@ -135,7 +135,7 @@ namespace RynthDefective.Tests
|
|||
List<DefSlot> s = b.S.Data.Slots;
|
||||
Check(s[0].Item?.Id == kit.Id && s[1].Item?.Id == potion.Id && s[4].Item?.Id == sword.Id, "the game's items are in own 1, 2, 5");
|
||||
Check(s[0].Mode == UseMode.Auto && s[0].Item!.Name == "Peerless Healing Kit" && s[0].Item!.Wcid == 628, "copied with their identity, automatic use");
|
||||
Check(s[6].Empty, "a spell can't be copied: the slot stays empty");
|
||||
Check(s[6].IsSpell && s[6].SpellId == 1234 && s[6].Item == null, "a spell goes in as a spell slot");
|
||||
Check(s[8].Item?.Name == "Lucky Gold Letter" && s[8].Item!.Id == 0x7200_0099u, "an item the pack read missed goes by the name the client knows");
|
||||
Check(s[9].Empty, "one nobody can name stays empty");
|
||||
Check(s[2].Empty && s[3].Empty && s[17].Empty, "the game's empty slots stay empty");
|
||||
|
|
@ -143,7 +143,7 @@ namespace RynthDefective.Tests
|
|||
Check(s.Skip(20).All(x => x.Empty), "nothing past them");
|
||||
Eq(s.Count, DefSettings.SlotsMax, "still 42 own slots");
|
||||
Check(b.Bound.Count == 2 && b.Bound.Contains((19, "F9")) && b.Bound.Contains((19, "Ctrl+F9")), "own 1's keys follow it to 19: " + string.Join(";", b.Bound));
|
||||
Check(m.Contains("Copied 4") && m.Contains("2 couldn't") && m.Contains("2 slots moved") && m.Contains("2 keys"), "and it says what it did: " + m);
|
||||
Check(m.Contains("Copied 5") && m.Contains("1 couldn't") && m.Contains("2 slots moved") && m.Contains("2 keys"), "and it says what it did: " + m);
|
||||
for (int n = 1; n <= 20; n++)
|
||||
{
|
||||
// The independent bar shows what the usual one did: bar N is own N.
|
||||
|
|
|
|||
|
|
@ -65,6 +65,15 @@ namespace RynthDefective.Tests
|
|||
Run("use: a kit on yourself, answered by UseDone", UseKit);
|
||||
Run("use: one at a time, the newest wish wins, a held key queues once", UseQueue);
|
||||
Run("use: busy, animating and RynthAi waiting hold a request, then it gives up", UseBusy);
|
||||
Run("busy rule: a leftover count, our own use, animation, a count that just changed", BusyRuleDecisions);
|
||||
Run("use: a busy count left by a death or a login doesn't hold the bar", UseStaleBusy);
|
||||
Run("use: 'You're too busy' from the server: one more try", UseTooBusyRetry);
|
||||
Run("spells: the table's names and flags, the name search", SpellTableAndSearch);
|
||||
Run("spells: whom a cast goes to", SpellCastTarget);
|
||||
Run("spells: a slot casts, Magic mode first, refusals", SpellUse);
|
||||
Run("spells: putting a spell in a slot (by id, by name), the command", SpellSession);
|
||||
Run("store: a spell slot saved and read; files from before read unchanged", SpellStore);
|
||||
Run("window: a spell slot on the script-window bar and in its editor", SpellWindow);
|
||||
Run("use: no UseDone, the quiet release and the time limit", UseUnanswered);
|
||||
Run("use: a slot whose object is gone uses the next of its name", UseRebind);
|
||||
Run("use: by name, missing items, target needed", UseByNameAndTargets);
|
||||
|
|
@ -196,7 +205,9 @@ namespace RynthDefective.Tests
|
|||
public bool InWorld { get; set; } = true;
|
||||
public uint PlayerId => Me;
|
||||
public uint SelectedId { get; set; }
|
||||
public bool ClientBusy { get; set; }
|
||||
public int BusyCount { get; set; }
|
||||
/// <summary>The busy count above zero (1) or idle; set BusyCount for a count of its own.</summary>
|
||||
public bool ClientBusy { get => BusyCount > 0; set => BusyCount = value ? Math.Max(1, BusyCount) : 0; }
|
||||
public bool Animating { get; set; }
|
||||
public bool? BotWaitingOnServer { get; set; }
|
||||
public bool? BotMacroRunning { get; set; }
|
||||
|
|
@ -204,11 +215,14 @@ namespace RynthDefective.Tests
|
|||
public int CombatMode { get; set; } = Stance.NonCombat;
|
||||
public int RefusalSeq { get; set; }
|
||||
public uint RefusedObject;
|
||||
/// <summary>The error of the newest UseDone (Answer sets it).</summary>
|
||||
public uint LastUseDoneError;
|
||||
public List<CarriedItem> Inventory = new();
|
||||
public bool RefuseSends;
|
||||
public readonly List<string> Sent = new();
|
||||
|
||||
public bool RefusalNamed(uint objectId) => RefusedObject == objectId;
|
||||
public uint UseDoneError(int seqAtSend) => UseDoneSeq == seqAtSend + 1 ? LastUseDoneError : 0;
|
||||
public IReadOnlyList<CarriedItem> Items() => Inventory;
|
||||
public CarriedItem? Live(uint id) => Inventory.FirstOrDefault(i => i.Id == id);
|
||||
|
||||
|
|
@ -229,12 +243,30 @@ namespace RynthDefective.Tests
|
|||
public bool SetCombatMode(int mode)
|
||||
{
|
||||
Sent.Add("mode " + mode);
|
||||
CombatMode = mode;
|
||||
if (!ModeRefused) CombatMode = mode;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The client asked for a mode but stays where it is (a weapon that can't cast in hand).</summary>
|
||||
public bool ModeRefused;
|
||||
public bool CanCast { get; set; } = true;
|
||||
/// <summary>The spells the character knows; null = the spellbook can't be read.</summary>
|
||||
public HashSet<uint>? Known;
|
||||
public bool? KnowsSpell(uint spellId) => Known == null ? null : Known.Contains(spellId);
|
||||
|
||||
public bool CastSpell(uint target, uint spellId)
|
||||
{
|
||||
if (RefuseSends) return false;
|
||||
Sent.Add($"cast {spellId} {(target == Me ? "me" : target.ToString("X"))}");
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Advance(long ms) => NowMs += ms;
|
||||
public void Answer() => UseDoneSeq++;
|
||||
public void Answer(uint error = 0)
|
||||
{
|
||||
UseDoneSeq++;
|
||||
LastUseDoneError = error;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Harness
|
||||
|
|
|
|||
|
|
@ -44,5 +44,9 @@
|
|||
<Compile Include="..\..\Plugins\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthUi\RynthIcons.cs" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- The plugin's spell table, under the name the plugin reads it by (spell slots). -->
|
||||
<EmbeddedResource Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Combat\SpellData.txt" LogicalName="RynthDefective.SpellData.txt" Link="Shared\SpellData.txt" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
292
Tools/RynthDefective.Tests/SpellTests.cs
Normal file
292
Tools/RynthDefective.Tests/SpellTests.cs
Normal file
|
|
@ -0,0 +1,292 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Engine.UI.ScriptWindows;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
using RynthCore.Plugin.RynthDefective.Use;
|
||||
|
||||
namespace RynthDefective.Tests
|
||||
{
|
||||
// Spell slots (2026-10-28): the spell table and search, whom a cast goes to, a slot's cast through
|
||||
// the use controller (Magic mode first, the refusals), putting a spell in a slot, the file.
|
||||
internal static partial class Program
|
||||
{
|
||||
private const uint HealSelf = 6, HealOther = 5, FlameBolt = 27, FrostBolt = 28, LifestoneRecall = 1635;
|
||||
|
||||
private static void SpellTableAndSearch()
|
||||
{
|
||||
Check(SpellTable.Count > 5000, "the table is in the plugin: " + SpellTable.Count);
|
||||
Check(SpellTable.TryGet(HealSelf, out SpellInfo hs) && hs.Name == "Heal Self I" && hs.SelfTargeted && !hs.Harmful, "Heal Self I: on yourself, not harmful");
|
||||
Check(SpellTable.TryGet(HealOther, out SpellInfo ho) && ho.Name == "Heal Other I" && !ho.SelfTargeted && !ho.Harmful, "Heal Other I: targeted, helpful");
|
||||
Check(SpellTable.TryGet(FlameBolt, out SpellInfo fb) && fb.Name == "Flame Bolt I" && fb.Harmful && !fb.SelfTargeted, "Flame Bolt I: harmful");
|
||||
Check(SpellTable.TryGet(LifestoneRecall, out SpellInfo ls) && ls.SelfTargeted, "Lifestone Recall: on yourself");
|
||||
Eq(SpellTable.Name(999_999), "Spell 999999", "a spell the table doesn't have goes by number");
|
||||
|
||||
Dictionary<uint, SpellInfo> parsed = SpellTable.Parse(new StringReader(
|
||||
"x\ty\n0\tZero\n7\t \n12\tSome Spell\t1\t1\tw\t-1\t1\tFalse\tTrue\tTrue\n13\tShort\n"));
|
||||
Check(parsed.Count == 2 && parsed[12].Harmful && parsed[12].SelfTargeted && !parsed[13].Harmful && !parsed[13].SelfTargeted,
|
||||
"odd lines are skipped; a short line has no flags");
|
||||
|
||||
SpellInfo[] known = SpellTable.Known(new uint[] { FlameBolt, HealSelf, HealOther, HealSelf, 0, 999_999 });
|
||||
Eq(string.Join("|", known.Select(k => k.Name)), "Flame Bolt I|Heal Other I|Heal Self I|Spell 999999", "the character's spells A-Z, once each");
|
||||
|
||||
SpellInfo[] list = SpellTable.Known(new uint[] { HealSelf, HealOther, FlameBolt, FrostBolt, LifestoneRecall });
|
||||
List<SpellInfo> r = SpellTable.Search(list, "heal self i", 10, out int total);
|
||||
Check(total == 1 && r[0].Id == HealSelf, "the exact name, any case");
|
||||
r = SpellTable.Search(list, "Heal", 10, out total);
|
||||
Eq(string.Join("|", r.Select(x => x.Name)), "Heal Other I|Heal Self I", "names starting with it");
|
||||
r = SpellTable.Search(list, "bolt", 10, out total);
|
||||
Eq(string.Join("|", r.Select(x => x.Name)), "Flame Bolt I|Frost Bolt I", "a word anywhere");
|
||||
r = SpellTable.Search(list, "frost i", 10, out total);
|
||||
Check(total == 1 && r[0].Id == FrostBolt, "every word of it");
|
||||
r = SpellTable.Search(list, "", 3, out total);
|
||||
Check(r.Count == 3 && total == 5, "blank: all of them, at most the limit");
|
||||
SpellTable.Search(list, "zzz", 10, out total);
|
||||
Eq(total, 0, "nothing matches");
|
||||
}
|
||||
|
||||
private static void SpellCastTarget()
|
||||
{
|
||||
var self = new SpellInfo(HealSelf, "Heal Self I", true, false);
|
||||
var helpful = new SpellInfo(HealOther, "Heal Other I", false, false);
|
||||
var harmful = new SpellInfo(FlameBolt, "Flame Bolt I", false, true);
|
||||
const uint mob = 0x8000_1234u;
|
||||
|
||||
Eq(SpellTargeting.Decide(self, mob, Me, out uint t, out _), CastAt.Yourself, "a self spell goes on you, whatever is selected");
|
||||
Eq(t, Me, "on you");
|
||||
Eq(SpellTargeting.Decide(helpful, mob, Me, out t, out _), CastAt.Selection, "a targeted spell goes on the selection");
|
||||
Eq(t, mob, "the selected object");
|
||||
Eq(SpellTargeting.Decide(helpful, 0, Me, out t, out _), CastAt.Yourself, "a helpful one with nothing selected: on you");
|
||||
Eq(t, Me, "on you");
|
||||
Eq(SpellTargeting.Decide(helpful, Me, Me, out t, out _), CastAt.Yourself, "with yourself selected: on you");
|
||||
Eq(SpellTargeting.Decide(harmful, mob, Me, out t, out _), CastAt.Selection, "a harmful one on the selected monster");
|
||||
Eq(t, mob, "the monster");
|
||||
Eq(SpellTargeting.Decide(harmful, 0, Me, out t, out string why), CastAt.Refused, "a harmful one with nothing selected: refused");
|
||||
Check(t == 0 && why.Contains("select a target"), "and says to select one: " + why);
|
||||
Eq(SpellTargeting.Decide(harmful, Me, Me, out _, out why), CastAt.Refused, "a harmful one at yourself: refused");
|
||||
Check(why.Contains("monster"), "says to select a monster: " + why);
|
||||
Eq(SpellTargeting.Decide(null, mob, Me, out t, out _), CastAt.Selection, "a spell the table doesn't know: on the selection");
|
||||
Eq(SpellTargeting.Decide(null, 0, Me, out t, out _), CastAt.Yourself, "else on you");
|
||||
Eq(SpellTargeting.Decide(self, 0, 0, out _, out why), CastAt.Refused, "no character yet: refused");
|
||||
Check(SpellTargeting.Describe(self) == "cast on you" && SpellTargeting.Describe(harmful).Contains("selected target")
|
||||
&& SpellTargeting.Describe(helpful).Contains("or on you"), "the tooltip words");
|
||||
}
|
||||
|
||||
private static Harness Caster(params uint[] known)
|
||||
{
|
||||
Harness h = With();
|
||||
h.World.Known = new HashSet<uint>(known);
|
||||
return h;
|
||||
}
|
||||
|
||||
private static bool Cast(Harness h, uint spell, string name) =>
|
||||
h.Use.Request(UseRequest.Cast(spell, name, "slot", h.World.NowMs));
|
||||
|
||||
private static void SpellUse()
|
||||
{
|
||||
// From peace: Magic mode first, the cast once the stance has settled, answered by UseDone.
|
||||
Harness h = Caster(HealSelf, HealOther, FlameBolt);
|
||||
Check(Cast(h, HealSelf, "Heal Self I"), "queued");
|
||||
h.Tick();
|
||||
Eq(string.Join("|", h.World.Sent), "mode 8", "at peace: Magic mode first");
|
||||
Check(h.Use.InFlight && h.Said.Last().Contains("Magic mode"), "in flight, and says so: " + string.Join(";", h.Said));
|
||||
h.Tick(500);
|
||||
h.Tick(500);
|
||||
Eq(h.World.Sent.Count, 1, "the stance settles first");
|
||||
h.Tick(400);
|
||||
Eq(string.Join("|", h.World.Sent), "mode 8|cast 6 me", "then the cast, on you");
|
||||
Eq(h.Said.Last(), "Casting Heal Self I...", "status");
|
||||
Check(h.Use.InFlight && h.Use.InvolvesSpell(HealSelf), "waiting for the server's answer");
|
||||
Check(!Cast(h, HealSelf, "Heal Self I") || h.Use.HasPending, "pressed again during the cast: one more, once");
|
||||
Check(!Cast(h, HealSelf, "Heal Self I"), "a held key queues once");
|
||||
h.World.Answer();
|
||||
h.Tick(100);
|
||||
Check(!h.Use.InFlight, "answered");
|
||||
h.Tick(300);
|
||||
Eq(h.World.Sent.Last(), "cast 6 me", "the second press casts again, Magic mode already in place");
|
||||
|
||||
// Already in Magic: cast at once. A harmful spell on the selected monster.
|
||||
h = Caster(FlameBolt);
|
||||
h.World.CombatMode = Stance.Magic;
|
||||
h.World.SelectedId = 0x1234;
|
||||
Cast(h, FlameBolt, "Flame Bolt I");
|
||||
h.Tick();
|
||||
Eq(string.Join("|", h.World.Sent), "cast 27 1234", "in Magic already: cast on the selection at once");
|
||||
Eq(h.Said.Last(), "Casting Flame Bolt I on the selection...", "status");
|
||||
|
||||
// Refusals: nothing selected for a harmful spell, a spell the character doesn't know, no casting at all.
|
||||
h = Caster(FlameBolt);
|
||||
h.World.CombatMode = Stance.Magic;
|
||||
Cast(h, FlameBolt, "Flame Bolt I");
|
||||
h.Tick();
|
||||
Check(h.World.Sent.Count == 0 && !h.Use.InFlight && h.Warned.Count == 1 && h.Warned[0] == "Flame Bolt I: not cast, select a target first.",
|
||||
"a war spell with nothing selected: refused, said: " + string.Join(";", h.Warned));
|
||||
h = Caster(HealSelf);
|
||||
Cast(h, FlameBolt, "Flame Bolt I");
|
||||
h.Tick();
|
||||
Check(h.World.Sent.Count == 0 && h.Warned.Count == 1 && h.Warned[0] == "Flame Bolt I: not cast, you don't know that spell.",
|
||||
"a spell the character doesn't know: refused, no mode change: " + string.Join(";", h.Warned));
|
||||
h = With();
|
||||
h.World.Known = null; // the spellbook can't be read: the server decides
|
||||
h.World.CombatMode = Stance.Magic;
|
||||
Cast(h, HealSelf, "Heal Self I");
|
||||
h.Tick();
|
||||
Eq(string.Join("|", h.World.Sent), "cast 6 me", "spellbook unreadable: cast anyway");
|
||||
h = Caster(HealSelf);
|
||||
h.World.CanCast = false;
|
||||
Cast(h, HealSelf, "Heal Self I");
|
||||
h.Tick();
|
||||
Check(h.World.Sent.Count == 0 && h.Warned.Count == 1 && h.Warned[0].Contains("can't cast"), "an engine that can't cast: said");
|
||||
h = Caster(HealSelf);
|
||||
h.World.CombatMode = Stance.Magic;
|
||||
h.World.RefuseSends = true;
|
||||
Cast(h, HealSelf, "Heal Self I");
|
||||
h.Tick();
|
||||
Check(!h.Use.InFlight && h.Warned.Count == 1 && h.Warned[0].Contains("didn't take the cast"), "the client turns the cast away: said, not waited on");
|
||||
|
||||
// Magic mode never comes (a sword in hand): asked once, then said, nothing cast.
|
||||
h = Caster(HealSelf);
|
||||
h.World.CombatMode = Stance.Melee;
|
||||
h.World.ModeRefused = true;
|
||||
Cast(h, HealSelf, "Heal Self I");
|
||||
h.Tick();
|
||||
h.Ticks(3, 1000);
|
||||
Check(h.Use.InFlight && h.Warned.Count == 0, "still waiting for the stance");
|
||||
h.Tick(1100);
|
||||
Check(!h.Use.InFlight && h.Warned.Count == 1 && h.Warned[0].Contains("didn't go into magic mode (melee now)"), "the stance never came: said: " + string.Join(";", h.Warned));
|
||||
Eq(string.Join("|", h.World.Sent), "mode 8", "asked once, never cast");
|
||||
|
||||
// The busy rules hold a cast like a use; "too busy" from the server gets one more try.
|
||||
h = Caster(HealSelf);
|
||||
h.World.CombatMode = Stance.Magic;
|
||||
h.Tick();
|
||||
h.World.BusyCount = 1;
|
||||
Cast(h, HealSelf, "Heal Self I");
|
||||
h.Ticks(2, 1000);
|
||||
Eq(h.World.Sent.Count, 0, "a busy count that just rose holds the cast");
|
||||
h.World.BusyCount = 0;
|
||||
h.Tick(100);
|
||||
Eq(string.Join("|", h.World.Sent), "cast 6 me", "and it goes once the character is free");
|
||||
h.World.Answer(UseController.TooBusyError);
|
||||
h.Tick(100);
|
||||
h.Tick(1100);
|
||||
Eq(string.Join("|", h.World.Sent), "cast 6 me|cast 6 me", "'too busy': cast once more a second later");
|
||||
Check(h.Logged.Any(l => l.Contains("the one more try")), "logged as the retry");
|
||||
h.World.Answer(UseController.TooBusyError);
|
||||
h.Tick(100);
|
||||
Check(h.Warned.Count == 1 && h.Warned[0].Contains("not cast, the server says the character is busy"), "twice: said: " + string.Join(";", h.Warned));
|
||||
}
|
||||
|
||||
private static void SpellSession()
|
||||
{
|
||||
var rig = new Rig("spells");
|
||||
IReadOnlyList<SpellInfo> known = SpellTable.Known(new uint[] { HealSelf, HealOther, FlameBolt, FrostBolt, LifestoneRecall });
|
||||
rig.S.KnownSpells = () => known;
|
||||
|
||||
string m = rig.S.SetSpell(3, HealSelf);
|
||||
DefSlot s3 = rig.S.Data.Slots[2];
|
||||
Check(s3.IsSpell && s3.SpellId == HealSelf && s3.SpellName == "Heal Self I" && !s3.Empty && s3.Item == null, "slot 3 casts Heal Self I");
|
||||
Check(m.Contains("Slot 3: Heal Self I") && m.Contains("cast on you"), "and says how: " + m);
|
||||
Check(rig.Saves > 0, "saved");
|
||||
Eq(s3.Label, "Heal Self I", "its label");
|
||||
|
||||
m = rig.S.SetSpell(4, 2000);
|
||||
Check(rig.S.Data.Slots[3].Empty && m.Contains("don't know"), "a spell the character doesn't know: refused: " + m);
|
||||
rig.S.KnownSpells = () => Array.Empty<SpellInfo>();
|
||||
m = rig.S.SetSpell(4, 2000);
|
||||
Check(rig.S.Data.Slots[3].SpellId == 2000, "the spellbook unreadable: taken (the cast is refused then if it must be): " + m);
|
||||
rig.S.KnownSpells = () => known;
|
||||
|
||||
m = rig.S.SetSpellFromName(5, "frost bolt i");
|
||||
Check(rig.S.Data.Slots[4].SpellId == FrostBolt, "by name, any case: " + m);
|
||||
m = rig.S.SetSpellFromName(6, "bolt");
|
||||
Check(rig.S.Data.Slots[5].Empty && m.Contains("2 of your spells match 'bolt'") && m.Contains("Flame Bolt I, Frost Bolt I"), "two match: says which: " + m);
|
||||
m = rig.S.SetSpellFromName(6, "lifestone");
|
||||
Check(rig.S.Data.Slots[5].SpellId == LifestoneRecall, "one starts with it: " + m);
|
||||
m = rig.S.SetSpellFromName(7, "nothing like it");
|
||||
Check(rig.S.Data.Slots[6].Empty && m.Contains("no spell named"), "none: " + m);
|
||||
rig.S.KnownSpells = () => Array.Empty<SpellInfo>();
|
||||
Check(rig.S.SetSpellFromName(7, "heal").Contains("can't be read"), "by name needs the spellbook");
|
||||
rig.S.KnownSpells = () => known;
|
||||
|
||||
Check(rig.S.UseSlot(3) == null && rig.S.Use.Pending?.Spell == HealSelf && rig.S.Use.Pending.Label == "Heal Self I", "pressing a spell slot asks for its cast");
|
||||
Check(rig.S.UseSlot(8)!.Contains("empty"), "an empty slot says so");
|
||||
|
||||
m = rig.S.BindKey(5, "F9", byName: true);
|
||||
Check(m.Contains("holds a spell") && rig.Chat.Count == 0, "a spell slot binds by slot only: " + m);
|
||||
|
||||
rig.Inv = new List<CarriedItem> { Kit(10) };
|
||||
rig.S.SetSlot(3, Kit(10));
|
||||
Check(rig.S.Data.Slots[2].Item?.Id == 10 && rig.S.Data.Slots[2].SpellId == 0 && !rig.S.Data.Slots[2].IsSpell, "an item over a spell: the spell is gone");
|
||||
DefSlot clone = rig.S.Data.Slots[4].Clone();
|
||||
Check(clone.SpellId == FrostBolt && clone.SpellName == "Frost Bolt I", "a copy keeps the spell");
|
||||
rig.S.ClearSlot(5);
|
||||
Check(rig.S.Data.Slots[4].Empty, "cleared");
|
||||
|
||||
DefCommand c = DefCommandParser.Parse("spell 3 Heal Self VI");
|
||||
Check(c.Verb == DefVerb.Spell && c.Slot == 3 && c.Text == "Heal Self VI", "/rdef spell 3 Heal Self VI");
|
||||
Check(DefCommandParser.Parse("spell 3").Verb == DefVerb.Error && DefCommandParser.Parse("spell x Heal").Verb == DefVerb.Error
|
||||
&& DefCommandParser.Parse("spell").Verb == DefVerb.Error, "a slot and a name are needed");
|
||||
}
|
||||
|
||||
private static void SpellWindow()
|
||||
{
|
||||
// The script-window bar (engines without the Shortcuts bar): a spell slot is a picture, else its initials.
|
||||
Windows w = Stocked("bar-spell");
|
||||
w.S.Data.Slots[5] = new DefSlot { SpellId = HealSelf, SpellName = "Heal Self I" };
|
||||
w.DrawBar();
|
||||
ParsedWindow bar = ParseAll(w.Host, "bar with a spell", out _).First(p => p.Key == "RynthDefective/Bar");
|
||||
Eq(CountOps(bar, ScriptOp.ImageButton), 5, "the four items and the spell drawn as pictures");
|
||||
Eq(CountOps(bar, ScriptOp.Button), 3 + 3, "three empty slots and the toolbar");
|
||||
Check(w.BarText.Contains("Heal Self I, a spell.") && w.BarText.Contains("cast on you"), "its tooltip says what it casts");
|
||||
|
||||
Windows t = Stocked("bar-spell-text", icons: false);
|
||||
t.S.Data.Slots[5] = new DefSlot { SpellId = HealSelf, SpellName = "Heal Self I" };
|
||||
t.DrawBar();
|
||||
ParseAll(t.Host, "bar with a spell, no pictures", out _);
|
||||
Check(t.BarText.Contains("HSI"), "no pictures: its initials");
|
||||
|
||||
// The editor on the spell slot.
|
||||
w.Bar.EditOpen = true;
|
||||
w.Bar.Editor.Select(6);
|
||||
w.DrawBar();
|
||||
ParseAll(w.Host, "editor on a spell slot", out _);
|
||||
Check(w.BarText.Contains("Slot 6: Heal Self I") && w.BarText.Contains("6. Heal Self I") && w.BarText.Contains("A spell: pressing the slot has it cast on you"),
|
||||
"the editor names the spell and how it is cast");
|
||||
Check(!w.BarText.Contains("Pressing it") && w.BarText.Contains("Bind to this slot"), "no item use setting; the key controls stay");
|
||||
}
|
||||
|
||||
private static void SpellStore()
|
||||
{
|
||||
var st = new DefStore(Path.Combine(_temp, "spells"));
|
||||
var d = new DefData();
|
||||
d.Slots[0].Item = ItemRef.From(Kit(0x7100_0001u));
|
||||
d.Slots[1] = new DefSlot { SpellId = HealSelf, SpellName = "Heal Self I" };
|
||||
d.Slots[2] = new DefSlot { SpellId = 987_654, SpellName = "A Server's Own Spell" };
|
||||
Check(st.Save("S", "Spells", d) == null, "saved");
|
||||
DefData r = st.Load("S", "Spells", out string? problem);
|
||||
Check(problem == null, "read");
|
||||
Check(r.Slots[1].IsSpell && r.Slots[1].SpellId == HealSelf && r.Slots[1].Label == "Heal Self I" && r.Slots[1].Mode == UseMode.Auto, "a spell slot comes back");
|
||||
Check(r.Slots[2].SpellId == 987_654 && r.Slots[2].Label == "A Server's Own Spell", "a spell the table doesn't know keeps its saved name");
|
||||
Check(r.Slots[0].Item?.Name == "Peerless Healing Kit" && r.Slots[0].SpellId == 0 && r.Slots[3].Empty, "the item slot and the empty ones as they were");
|
||||
Eq(DefStore.ToJson(r), DefStore.ToJson(d), "writing what was read gives the same file");
|
||||
|
||||
// A file from before spell slots: read unchanged, written back the same.
|
||||
const string old = "{\n \"version\": 1,\n \"slots\": [\n {\n \"item\": {\n \"id\": 5,\n \"name\": \"Kit\"\n },\n \"mode\": 2\n },\n {\n \"mode\": 0\n }\n ]\n}";
|
||||
DefData o = DefStore.Parse(System.Text.Json.JsonDocument.Parse(old).RootElement);
|
||||
Check(o.Slots[0].Item?.Name == "Kit" && o.Slots[0].Mode == UseMode.OnSelf && o.Slots[0].SpellId == 0 && o.Slots.Skip(1).All(x => x.Empty),
|
||||
"an old file: the item, its mode, no spells");
|
||||
Check(!DefStore.ToJson(o).Contains("\"spell\""), "and no spell is written for it");
|
||||
|
||||
// Hand-edited oddities: an item wins over a spell; a spell with no id, or not an object, is nothing.
|
||||
const string odd = "{\"slots\":[{\"item\":{\"id\":5,\"name\":\"Kit\"},\"spell\":{\"id\":6,\"name\":\"Heal Self I\"}},"
|
||||
+ "{\"spell\":{\"id\":0,\"name\":\"X\"}},{\"spell\":6},{\"spell\":{\"id\":6}},{\"spell\":{\"id\":-3,\"name\":\"Y\"}}]}";
|
||||
DefData x = DefStore.Parse(System.Text.Json.JsonDocument.Parse(odd).RootElement);
|
||||
Check(x.Slots[0].Item?.Name == "Kit" && x.Slots[0].SpellId == 0, "an item and a spell in one slot: the item");
|
||||
Check(x.Slots[1].Empty && x.Slots[2].Empty && x.Slots[4].Empty, "no id, not an object, a negative id: empty");
|
||||
Check(x.Slots[3].SpellId == HealSelf && x.Slots[3].Label == "Heal Self I", "an id with no name: named by the table");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -75,19 +75,38 @@ namespace RynthDefective.Tests
|
|||
{
|
||||
Harness h = With(Kit(0x10));
|
||||
ItemRef kit = ItemRef.From(Kit(0x10));
|
||||
h.World.ClientBusy = true;
|
||||
// A count that keeps moving is an action under way (the player's own, another plugin's): it holds.
|
||||
h.Tick(); // the first look: idle
|
||||
h.Slot(kit);
|
||||
h.Ticks(5, 1000);
|
||||
Eq(h.World.Sent.Count, 0, "the client's busy count holds it");
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
h.World.BusyCount = 1 + (i % 2);
|
||||
h.Tick(1000);
|
||||
}
|
||||
Eq(h.World.Sent.Count, 0, "a moving busy count holds it");
|
||||
Check(h.Use.HasPending && h.Warned.Count == 0, "still waiting inside the limit");
|
||||
h.Ticks(2, 1000);
|
||||
h.World.BusyCount = 2;
|
||||
h.Tick(1000);
|
||||
Check(!h.Use.HasPending && h.Warned.Count == 1 && h.Warned[0] == "Peerless Healing Kit: not used, the character is busy.", "past the limit it gives up and says why: " + string.Join(";", h.Warned));
|
||||
Eq(h.World.Sent.Count, 0, "and sent nothing");
|
||||
|
||||
h = With(Kit(0x10));
|
||||
h.World.Animating = true;
|
||||
h.Slot(kit);
|
||||
h.Ticks(7, 1000);
|
||||
Check(h.Warned.Count == 1 && h.Warned[0].Contains("an animation is playing"), "a gesture holds it: " + string.Join(";", h.Warned));
|
||||
h.Ticks(3, 1000);
|
||||
Eq(h.World.Sent.Count, 0, "a gesture holds it");
|
||||
h.World.Animating = false;
|
||||
h.Tick(100);
|
||||
Eq(h.World.Sent.Count, 1, "and it goes when the gesture ends");
|
||||
|
||||
h = With(Kit(0x10));
|
||||
h.World.Animating = true;
|
||||
h.Slot(kit);
|
||||
h.Ticks(4, 1000);
|
||||
Eq(h.World.Sent.Count, 0, "a gesture 3 s long still holds it");
|
||||
h.Tick(1000);
|
||||
Check(h.World.Sent.Count == 1 && h.Warned.Count == 0, "one that never ends (a stuck motion queue) is let go after 4 s");
|
||||
Eq(h.Logged.Count(l => l.Contains("'animating' for")), 1, "logged once");
|
||||
|
||||
h = With(Kit(0x10));
|
||||
h.World.BotWaitingOnServer = true;
|
||||
|
|
@ -115,6 +134,168 @@ namespace RynthDefective.Tests
|
|||
Eq(h.World.Sent.Count, 1, "no RynthAi: nothing to wait for");
|
||||
}
|
||||
|
||||
private static BusyFacts Facts(int count = 0, long steady = 0, int leftover = 0, long own = long.MaxValue / 4,
|
||||
bool anim = false, long animMs = 0, bool? bot = null, long botMs = 0) =>
|
||||
new(count, steady, leftover, own, anim, animMs, bot, botMs);
|
||||
|
||||
private static void BusyRuleDecisions()
|
||||
{
|
||||
Eq(BusyRule.Decide(Facts(), out BusyStale st), BusyHold.None, "idle: send");
|
||||
Eq(st, BusyStale.None, "nothing ignored");
|
||||
|
||||
Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000), out st), BusyHold.None, "busy with nothing in flight for longer than the bound: send");
|
||||
Eq(st, BusyStale.Count, "the count was ignored as a leftover");
|
||||
Eq(BusyRule.Decide(Facts(count: 1, steady: BusyRule.CountTrustMs), out _), BusyHold.None, "exactly the bound: a leftover");
|
||||
Eq(BusyRule.Decide(Facts(count: 1, steady: BusyRule.CountTrustMs - 1), out _), BusyHold.Busy, "just under it: still trusted");
|
||||
|
||||
Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, own: 500), out _), BusyHold.Busy, "busy just after our own use: wait");
|
||||
Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, own: BusyRule.OwnTrustMs), out _), BusyHold.None, "our own use long enough ago: a leftover");
|
||||
|
||||
Eq(BusyRule.Decide(Facts(anim: true, animMs: 300), out _), BusyHold.Animation, "animating: wait");
|
||||
Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, anim: true, animMs: 300), out _), BusyHold.Animation, "animating holds over a leftover count");
|
||||
Eq(BusyRule.Decide(Facts(anim: true, animMs: BusyRule.AnimationMaxMs), out st), BusyHold.None, "a gesture past the bound is a stuck motion queue");
|
||||
Eq(st, BusyStale.Animation, "and ignored as such");
|
||||
Eq(BusyRule.Decide(Facts(count: 1, steady: 200, anim: true, animMs: 9000), out _), BusyHold.Busy, "a stuck gesture doesn't hide a fresh count");
|
||||
|
||||
Eq(BusyRule.Decide(Facts(count: 1, steady: 200), out _), BusyHold.Busy, "a count that just changed: wait");
|
||||
Eq(BusyRule.Decide(Facts(count: 3, steady: 200, leftover: 2), out _), BusyHold.Busy, "a count that just rose above the leftover: wait");
|
||||
Eq(BusyRule.Decide(Facts(count: 2, steady: 200, leftover: 2), out st), BusyHold.None, "back at the leftover (our use answered): holds nothing though it just moved");
|
||||
Eq(st, BusyStale.Count, "the leftover is still a leftover");
|
||||
Eq(BusyRule.Decide(Facts(count: 3, steady: 5000, leftover: 2), out st), BusyHold.None, "above the leftover but unchanged for longer than the bound: a bigger leftover");
|
||||
Eq(st, BusyStale.Count, "ignored");
|
||||
|
||||
Eq(BusyRule.Decide(Facts(bot: true, botMs: 1000), out _), BusyHold.Bot, "RynthAi waiting on the server, fresh: wait");
|
||||
Eq(BusyRule.Decide(Facts(bot: true, botMs: BusyRule.BotTrustMs), out st), BusyHold.None, "RynthAi's bit longer than its own action limits: send");
|
||||
Eq(st, BusyStale.Bot, "ignored");
|
||||
Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, bot: true, botMs: 10_000), out st), BusyHold.None, "RynthAi's copy of a leftover count (its macro off after a death)");
|
||||
Eq(st, BusyStale.Count | BusyStale.Bot, "both ignored");
|
||||
Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, bot: true, botMs: BusyRule.CountTrustMs), out _), BusyHold.None, "with a leftover count the bit gets the count's bound");
|
||||
Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, bot: true, botMs: 1000), out _), BusyHold.Bot, "a bit that just came on holds even over a leftover (RynthAi just sent something)");
|
||||
Eq(BusyRule.Decide(Facts(bot: false, botMs: 50), out _), BusyHold.None, "RynthAi idle");
|
||||
}
|
||||
|
||||
private static void UseStaleBusy()
|
||||
{
|
||||
ItemRef kit = ItemRef.From(Kit(0x10));
|
||||
|
||||
// A login with a count the last session left: nothing moves it.
|
||||
Harness h = With(Kit(0x10));
|
||||
h.World.BusyCount = 2;
|
||||
h.Tick(); // the first look
|
||||
h.Slot(kit);
|
||||
h.Ticks(3, 1000);
|
||||
Eq(h.World.Sent.Count, 0, "right after the first look the count may be real: held");
|
||||
h.Tick(1000);
|
||||
Eq(string.Join("|", h.World.Sent), "useon 10 me", "unchanged for 4 s with nothing in flight: a leftover, the kit goes");
|
||||
Eq(h.Warned.Count, 0, "no warning");
|
||||
Eq(h.Logged.Count(l => l.Contains("busy count has read 2")), 1, "the leftover is logged once");
|
||||
Check(h.Logged.Any(l => l.Contains("left alone")), "and the log says the count isn't touched");
|
||||
Eq(h.Use.Busy.Leftover, 2, "2 is the leftover");
|
||||
|
||||
// Our own kit raises it; the answer brings it back to the leftover; the next kit goes at once.
|
||||
h.World.BusyCount = 3;
|
||||
h.Tick(100);
|
||||
Check(h.Use.InFlight, "our kit is in flight");
|
||||
h.World.BusyCount = 2;
|
||||
h.World.Answer();
|
||||
h.Tick(100);
|
||||
Check(!h.Use.InFlight, "answered");
|
||||
h.Slot(kit);
|
||||
h.Tick(300);
|
||||
Eq(h.World.Sent.Count, 2, "the next kit goes at once: the count is back at the leftover");
|
||||
Eq(h.Logged.Count(l => l.Contains("busy count has read")), 1, "nothing new logged");
|
||||
h.World.Answer();
|
||||
h.Tick(100);
|
||||
|
||||
// Something else raises it above the leftover: real again, until it too sits unchanged.
|
||||
h.World.BusyCount = 3;
|
||||
h.Tick(300);
|
||||
h.Slot(kit);
|
||||
h.Ticks(3, 1000);
|
||||
Eq(h.World.Sent.Count, 2, "a count above the leftover that just rose holds the kit");
|
||||
h.Tick(1000);
|
||||
Eq(h.World.Sent.Count, 3, "until it has sat unchanged for 4 s too");
|
||||
Eq(h.Logged.Count(l => l.Contains("busy count has read 3")), 1, "a bigger leftover gets its own line");
|
||||
h.World.Answer();
|
||||
h.Tick(100);
|
||||
h.World.BusyCount = 0;
|
||||
h.Tick(100);
|
||||
Eq(h.Use.Busy.Leftover, 0, "idle again: no leftover");
|
||||
|
||||
// A death: the count and RynthAi's copy of it sit through the death portal.
|
||||
h = With(Kit(0x10));
|
||||
h.World.BusyCount = 1;
|
||||
h.World.BotWaitingOnServer = true;
|
||||
h.Tick();
|
||||
h.World.InWorld = false;
|
||||
h.Ticks(8, 1000);
|
||||
h.World.InWorld = true;
|
||||
h.Slot(kit);
|
||||
h.Tick(100);
|
||||
Eq(string.Join("|", h.World.Sent), "useon 10 me", "landed: the count and RynthAi's bit that sat through the portal hold nothing");
|
||||
Check(h.Logged.Any(l => l.Contains("RynthAi has read 'waiting on the server'")), "RynthAi's bit is logged as ignored too");
|
||||
|
||||
// A request made in the portal is dropped and said so.
|
||||
h = With(Kit(0x10));
|
||||
h.World.InWorld = false;
|
||||
h.Slot(kit);
|
||||
h.Tick();
|
||||
Check(!h.Use.HasPending && h.World.Sent.Count == 0 && h.Warned.Count == 1 && h.Warned[0].Contains("portal space"), "a key in portal space: not used, and says why: " + string.Join(";", h.Warned));
|
||||
|
||||
// A login starts the clocks again (ResetSession), portal space doesn't.
|
||||
h = With(Kit(0x10));
|
||||
h.World.BusyCount = 1;
|
||||
h.Tick();
|
||||
h.Ticks(6, 1000);
|
||||
h.Use.ResetSession();
|
||||
h.Slot(kit);
|
||||
h.Tick(100);
|
||||
Eq(h.World.Sent.Count, 0, "after a login the count is new again: held for now");
|
||||
}
|
||||
|
||||
private static void UseTooBusyRetry()
|
||||
{
|
||||
ItemRef kit = ItemRef.From(Kit(0x10));
|
||||
Harness h = With(Kit(0x10));
|
||||
h.Slot(kit);
|
||||
h.Tick();
|
||||
Eq(h.World.Sent.Count, 1, "sent");
|
||||
h.World.Answer(UseController.TooBusyError);
|
||||
h.Tick(100);
|
||||
Check(!h.Use.InFlight && h.Use.HasPending, "answered 'too busy': queued once more");
|
||||
h.Tick(500);
|
||||
Eq(h.World.Sent.Count, 1, "not straight away");
|
||||
h.Tick(600);
|
||||
Eq(h.World.Sent.Count, 2, "a second later, sent again");
|
||||
Check(h.Logged.Any(l => l.Contains("one more try")), "the log says it is the retry");
|
||||
h.World.Answer(UseController.TooBusyError);
|
||||
h.Tick(100);
|
||||
Check(!h.Use.InFlight && !h.Use.HasPending && h.Warned.Count == 1 && h.Warned[0].Contains("the server says the character is busy"),
|
||||
"busy again: said once, not retried again: " + string.Join(";", h.Warned));
|
||||
h.Ticks(5, 1000);
|
||||
Eq(h.World.Sent.Count, 2, "no loop");
|
||||
|
||||
// Another answer: no retry.
|
||||
h = With(Kit(0x10));
|
||||
h.Slot(kit);
|
||||
h.Tick();
|
||||
h.World.Answer(0x0402);
|
||||
h.Tick(100);
|
||||
h.Ticks(3, 1000);
|
||||
Check(h.World.Sent.Count == 1 && !h.Use.HasPending, "another error is not retried");
|
||||
|
||||
// A newer request while the first was in flight wins over the retry.
|
||||
h = With(Kit(0x10), Potion(0x20));
|
||||
h.Slot(kit);
|
||||
h.Tick();
|
||||
h.Slot(ItemRef.From(Potion(0x20)));
|
||||
h.World.Answer(UseController.TooBusyError);
|
||||
h.Tick(100);
|
||||
Check(h.Use.Pending?.Item?.Name == "Health Potion", "the newest wish wins over the retry");
|
||||
h.Tick(1100);
|
||||
Eq(string.Join("|", h.World.Sent), "useon 10 me|use 20", "the potion goes, the kit isn't sent again");
|
||||
}
|
||||
|
||||
private static void UseUnanswered()
|
||||
{
|
||||
Harness h = With(Potion(0x20));
|
||||
|
|
|
|||
Loading…
Reference in a new issue