RynthSuite as of 2026-12-02 (internal 152e13d): release 2026.12.1.1
This commit is contained in:
parent
e8e4228d15
commit
6b5a9c7e99
65 changed files with 3920 additions and 237 deletions
|
|
@ -55,6 +55,8 @@ internal static class Program
|
|||
// Appraised creatures are saved to C:\Games\RynthSuite\RynthAi\CreatureData\creatures.json.
|
||||
LiveCreatureFolder = RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder;
|
||||
RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder = Path.Combine(TempRoot, "CreatureData");
|
||||
// /ub equip create writes an equipment profile into C:\Games\RynthSuite\RynthAi\LootProfiles.
|
||||
RynthCore.Plugin.RynthAi.RynthAiPlugin.UbEquipFolder = Path.Combine(TempRoot, "UbEquip");
|
||||
|
||||
// Spell names (item spells, spell expiry by name) come from the plugin's embedded table.
|
||||
SpellDatabase.Load();
|
||||
|
|
@ -77,6 +79,7 @@ internal static class Program
|
|||
MagItemDescriberTests.Register(runner);
|
||||
ExpressionTests.Register(runner);
|
||||
MetaTests.Register(runner);
|
||||
MetaCommandAuditTests.Register(runner);
|
||||
SelfTestMetaTests.Register(runner);
|
||||
NoKillTests.Register(runner);
|
||||
MetaSchedulerTests.Register(runner);
|
||||
|
|
@ -161,6 +164,7 @@ internal static class Program
|
|||
LootAddItemTests.Register(runner);
|
||||
GiveTests.Register(runner);
|
||||
UbCompatTests.Register(runner);
|
||||
UbInventoryTests.Register(runner);
|
||||
MetaAuditTests.Register(runner);
|
||||
MetaSampleCompatTests.Register(runner);
|
||||
IdRefusalTests.Register(runner);
|
||||
|
|
@ -240,6 +244,7 @@ internal static class Program
|
|||
ProfileButtonTests.Register(runner);
|
||||
MonsterProfileTests.Register(runner);
|
||||
ProfileStartTests.Register(runner);
|
||||
NamedLayoutRowTests.Register(runner);
|
||||
GiveProfileTests.Register(runner);
|
||||
TinkerTests.Register(runner);
|
||||
KitRunnerTests.Register(runner);
|
||||
|
|
@ -258,6 +263,7 @@ AmmoAutoPluginTests.Register(runner);
|
|||
CommandReplyTests.Register(runner);
|
||||
MonsterStatsTests.Register(runner);
|
||||
MetaSaveTests.Register(runner);
|
||||
MetaEmbedNavTests.Register(runner);
|
||||
MetaResumeTests.Register(runner);
|
||||
FellowOpenTests.Register(runner);
|
||||
WieldBanTests.Register(runner);
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ internal static unsafe class AutoConfirmCraftTests
|
|||
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);
|
||||
r.Add("/ub prepclick yes [ms] arms a Yes for the next yes/no prompt (5-60 s); no disarms (R-20261125-144721-b49a)", UbPrepClick);
|
||||
r.Add("/ub prepclick yes [seconds] arms a Yes for the next yes/no prompt (15 s by default, 5 s-5 min); no and stop disarm (R-20261125-144721-b49a, 12-01 audit)", UbPrepClick);
|
||||
}
|
||||
|
||||
// ── The fake engine's confirmation calls (static: function pointers can't capture) ──────────
|
||||
|
|
@ -146,15 +146,22 @@ internal static unsafe class AutoConfirmCraftTests
|
|||
|
||||
Check.True(Run("/ub prepclick yes 100"), "taken");
|
||||
Check.Eq(ArmCalls.Count, 1, "one arm");
|
||||
Check.Eq(ArmCalls[0], (RynthCoreHost.ConfirmationKind.YesNo, 0, RynthAiPlugin.PrepClickMinMs), "a Yes for the next yes/no prompt, 100 ms raised to 5 s");
|
||||
Check.Eq(ArmCalls[0], (RynthCoreHost.ConfirmationKind.YesNo, 0, 100_000), "a Yes for the next yes/no prompt within 100 s (UtilityBelt's seconds)");
|
||||
Check.Eq(Prompt(0, RynthCoreHost.ConfirmationKind.YesNo), RynthCoreHost.ConfirmationOutcome.Accepted, "the prompt is answered Yes");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("no RynthAi equivalent")), "no longer 'ignored'");
|
||||
|
||||
Run("/ub prepclick yes");
|
||||
Check.Eq(ArmCalls[^1].Timeout, RynthAiPlugin.PrepClickDefaultMs, "no number: 15 s");
|
||||
Run("/ub prepclick yes 2");
|
||||
Check.Eq(ArmCalls[^1].Timeout, RynthAiPlugin.PrepClickMinMs, "2 s raised to 5 s (metas send it again before each hand-in)");
|
||||
Run("/ub prepclick yes 999999");
|
||||
Check.Eq(ArmCalls[^1].Timeout, RynthAiPlugin.PrepClickMaxMs, "at most 60 s");
|
||||
Check.Eq(ArmCalls[^1].Timeout, RynthAiPlugin.PrepClickMaxMs, "at most 5 min");
|
||||
Run("/ub prepclick no");
|
||||
Check.Eq(ArmCalls[^1].Timeout, 0, "no: disarmed");
|
||||
Check.Eq(Prompt(0, RynthCoreHost.ConfirmationKind.YesNo), RynthCoreHost.ConfirmationOutcome.Shown, "the next prompt is left to the client");
|
||||
Run("/ub prepclick yes 30");
|
||||
Check.True(Run("/ub prepclick stop"), "stop: taken (it answered with the usage before)");
|
||||
Check.Eq(ArmCalls[^1].Timeout, 0, "stop: disarmed");
|
||||
}
|
||||
finally { TickIsolationTests.Done(); FakeHost.ConfigureApi = null; }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -55,6 +55,7 @@ internal static class CombatHookTests
|
|||
r.Add("blacklist: casts answered 'too busy' (UseDone 0x1D) are not no-damage casts (answered 0: the target is dropped)", RefusedCastsNotJudged);
|
||||
r.Add("ghost (R-20261115-172110-9e6a): two casts answered 'target not acquired' (UseDone 0x42C) mark the target a ghost and stop the casting", NotAcquiredMarksGhost);
|
||||
r.Add("out of range (R-20261119-155301-121a): a cast answered 'Out of Range!' (UseDone 0x550) drops the target until it comes 3 m nearer", OutOfRangeDropsTarget);
|
||||
r.Add("out of range (R-20261201-190034-03c5): the target dropped in the tick's answer check gets no debuff cast at target 0 that tick", DroppedTargetNoDebuff);
|
||||
r.Add("blacklist (2026-11-15): melee landing nothing across a building's wall (one inside, one out) keeps the target off 5 min; elsewhere the usual timeout", AcrossWallBlacklistLonger);
|
||||
r.Add("loot jump: Think sends no cast while in the air after a loot jump; it casts on the landing, or at the cap", LootJumpHoldsAttack);
|
||||
r.Add("loot jump: a swing refused in the air (WeenieError 0x4EB) is not a no-damage attack (without it: a miss)", MeleeInAirNotJudged);
|
||||
|
|
@ -1092,6 +1093,41 @@ internal static class CombatHookTests
|
|||
// hourglass going round), never dropping it.
|
||||
// 2026.11.15.3: an Olthoi Hive Warrior 88 m off, every Incantation of Force Arc at it answered UseDone
|
||||
// 0x550 about 60 ms after the send, and combat cast again at once (1,027 casts since the last kill).
|
||||
// R-20261201-190034-03c5 (Conquest): a bolt answered 'Out of Range!', Think's answer check dropped the target, and
|
||||
// the same tick's attack still cast Imperil, at target 0: the client refused it locally, nothing reached the server,
|
||||
// and combat waited 7 s for an answer, jumped, went to Peace: about 13 s stood still.
|
||||
private static void DroppedTargetNoDebuff() => Guard(() =>
|
||||
{
|
||||
var rig = new AttackRig(setup: () =>
|
||||
{
|
||||
FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true;
|
||||
foreach (var row in SpellTable.Named("Imperil Other VI")) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
});
|
||||
rig.S.EnableRaycasting = false;
|
||||
rig.Attack();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "the bolt goes out");
|
||||
rig.S.MonsterRules[0].Imperil = true; // the next cast would be a debuff
|
||||
FakeHost.UseDone(CombatManager.MissileOutOfRangeErr);
|
||||
SetField(rig.C, "_pendingOffensiveCastAt", DateTime.Now.AddSeconds(-5));
|
||||
CallPrivate(rig.C, "JudgePendingOffensiveCast"); // Think's answer check, before the attack
|
||||
Check.Eq(rig.C.activeTargetId, 0, "'Out of Range!': the target is dropped");
|
||||
rig.Attack();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "no debuff goes out in the same tick: " + string.Join(", ", FakeHost.Casts.Select(c => $"{NameOf(c.SpellId)}@0x{c.Target:X8}")));
|
||||
Check.False(FakeHost.Casts.Any(c => c.Target == 0), "nothing is ever cast at target 0");
|
||||
|
||||
// Control: with the target still locked the debuff goes, at the target.
|
||||
var ok = new AttackRig(setup: () =>
|
||||
{
|
||||
FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true;
|
||||
foreach (var row in SpellTable.Named("Imperil Other VI")) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
});
|
||||
ok.S.EnableRaycasting = false;
|
||||
ok.S.MonsterRules[0].Imperil = true;
|
||||
ok.Attack();
|
||||
Check.Eq(ok.LastCast, "Imperil Other VI", "with the target locked: Imperil first");
|
||||
Check.Eq(FakeHost.Casts[^1].Target, (uint)Target, "at the target");
|
||||
});
|
||||
|
||||
private static void OutOfRangeDropsTarget() => Guard(() =>
|
||||
{
|
||||
var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; });
|
||||
|
|
|
|||
|
|
@ -57,6 +57,9 @@ internal static class CommandReplyTests
|
|||
new("/ra navhud off", null, K.Act),
|
||||
new("/ra navtrail on", null, K.Act),
|
||||
new("/ra navtrail clear", null, K.Act),
|
||||
// No trail in the rig (breadcrumbs come from walking): route|back fail here, as they say how to get one.
|
||||
new(null, "/ra navtrail route", K.Act),
|
||||
new(null, "/ra navtrail back", K.Act),
|
||||
new("/ra navoverlay off", null, K.Act),
|
||||
new("/ra debug off", null, K.Act),
|
||||
new("/ra lootcheck off", "/ra lootcheck", K.Act),
|
||||
|
|
@ -327,6 +330,7 @@ internal static class CommandReplyTests
|
|||
new(null, "/mt vendor sell", K.Act),
|
||||
new(null, "/mt vendor buy", K.Act),
|
||||
new("/mt autopack", null, K.Act),
|
||||
new(null, "/mt attack_melee banana", K.Act), // Mag-Tools (2026-12-01); this rig has no attack call
|
||||
new("/mt click ok", "/mt click", K.Act),
|
||||
new("/mt click 10 20", "/mt click banana", K.Act),
|
||||
new("/mt movement w 0", "/mt movement", K.Act),
|
||||
|
|
@ -424,6 +428,8 @@ internal static class CommandReplyTests
|
|||
new("/ub combatstate peace", "/ub combatstate", K.Act),
|
||||
new("/ub cast 1234", "/ub cast", K.Act),
|
||||
new("/ub equip Sharp Sword", "/ub equip", K.Act),
|
||||
new("/ub equip list", "/ub equip load", K.Query), // UtilityBelt's equipment profiles (2026-12-01)
|
||||
new(null, "/ub autosalvage banana", K.Act),
|
||||
new("/ub drop Faran Robe", "/ub drop", K.Act),
|
||||
new("/ub select Faran Robe", "/ub select", K.Act),
|
||||
new("/ub loot Gem", "/ub loot", K.Act),
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ internal static class ExpressionTests
|
|||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("expressions (R-20261201-211257-d2be, -4871): createlist[...] (UtilityBelt's name) makes a list; listcontains[...] == 0 is a number", LandblockListReports);
|
||||
r.Add("expr: safety - var files point at the scratch folder", VarPathsRedirected);
|
||||
r.Add("expr: arithmetic and precedence", Arithmetic);
|
||||
r.Add("expr: unary minus, negative and hex literals", UnaryAndLiterals);
|
||||
|
|
@ -1105,6 +1106,30 @@ internal static class ExpressionTests
|
|||
|
||||
// ── UtilityBelt reference audit ──────────────────────────────────────────
|
||||
|
||||
// R-20261201-211257-d2be / R-20261201-211007-4871 (Coldeve, a meta author): a landblock list made with
|
||||
// UtilityBelt's createlist[...] and checked with listcontains[...] == 0.
|
||||
private static void LandblockListReports()
|
||||
{
|
||||
var e = Engine();
|
||||
Is(e, "setvar[lbs, createlist[2271412224,2271477760,2305163264]]", "[2271412224,2271477760,2305163264]");
|
||||
Is(e, "listcount[getvar[lbs]]", "3");
|
||||
Is(e, "listcontains[getvar[lbs], 2271477760]", "1");
|
||||
Is(e, "listcontains[getvar[lbs], 2271477760] == 0", "0");
|
||||
Is(e, "listcontains[getvar[lbs], 5] == 0", "1");
|
||||
Is(e, "listcontains[getvar[lbs], 2271477760]==1", "1");
|
||||
// The report's own line (getvar's ] in the wrong place): still a number, never the text back.
|
||||
string r = e.Evaluate("listcontains[getvar[lbs, getplayerlandblock[]]] == 0");
|
||||
Check.True(r == "0" || r == "1", "the report's line gives a number: '" + r + "'");
|
||||
// As in game: the list never made (createlist unknown then), so the variable is empty or unset.
|
||||
e.Evaluate("setvar[nosuch, nosuchfunction[1,2]]"); // set, to empty, as an unknown function left it
|
||||
foreach (string line in new[] { "listcontains[getvar[nosuch, getplayerlandblock[]]] == 0", "listcontains[getvar[nosuch], getplayerlandblock[]] == 0",
|
||||
"listcontains[getvar[nosuch, getplayerlandblock[]]]" })
|
||||
{
|
||||
string v = e.Evaluate(line);
|
||||
Check.True(v == "0" || v == "1", $"'{line}' gives a number: '{v}'");
|
||||
}
|
||||
}
|
||||
|
||||
private static void DocSemicolon()
|
||||
{
|
||||
var e = Engine();
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ internal static class ManaStoneChoiceTests
|
|||
r.Add("mana stones: in a fight, worn gear that runs low is still refilled (armor without mana drops its spells)", RefillInFight);
|
||||
r.Add("eternal charge: tapping is ignored while it is in the pack, and applies again when it leaves", EternalIgnoresTapping);
|
||||
r.Add("eternal charge: a use with no answer is tried again in 20 s, not 5 minutes", EternalRetriesSoon);
|
||||
r.Add("eternal charge (11-30): one only the pack walk has (not in the cache yet) refills worn gear, tapping on or off", EternalOnlyInPackWalk);
|
||||
r.Add("mana tap with macro off (on by default): the macro stopped, stones still refill gear and drain tap loot", TapWithMacroOff);
|
||||
r.Add("mana tap with macro off, unticked: nothing while the macro is stopped; it starts with the macro", NoTapWithMacroOffUnticked);
|
||||
}
|
||||
|
|
@ -100,6 +101,21 @@ internal static class ManaStoneChoiceTests
|
|||
Check.Eq(rig.OnRing.Count, 1, "tapping applies again: the item is drained");
|
||||
}
|
||||
|
||||
// 11-30: gear at 30-46% for an hour with "eternal=True needs=True" and "no charged stone is known":
|
||||
// the Eternal Mana Charge was in the client's pack lists but not in the cache, and the stone search
|
||||
// read the cache alone.
|
||||
private static void EternalOnlyInPackWalk()
|
||||
{
|
||||
foreach (bool tapping in new[] { true, false })
|
||||
{
|
||||
using var rig = new Rig(tapping, new (uint, int?)[] { (ChargeA, null) }, stoneName: EternalCharge, maceMana: 0, contents: true,
|
||||
before: ids => ids.Remove(ChargeA));
|
||||
Check.False(rig.C.AllKnownObjects().Any(o => o.Id == unchecked((int)ChargeA)), "the cache doesn't know the charge");
|
||||
rig.Run(1000);
|
||||
Check.Eq(rig.OnPlayer.Count, 1, $"tapping {(tapping ? "on" : "off")}: the charge goes on the gear");
|
||||
}
|
||||
}
|
||||
|
||||
private static void EternalRetriesSoon()
|
||||
{
|
||||
using var rig = new Rig(tapping: false, new (uint, int?)[] { (ChargeA, null) }, stoneName: EternalCharge, maceMana: 0);
|
||||
|
|
@ -635,12 +651,23 @@ internal static class ManaStoneChoiceTests
|
|||
rig.Chat("The Mana Stone gives 2,000 points of mana to the following items: Khanda-handled Mace.\nYour items are fully charged.");
|
||||
rig.Run(60_000);
|
||||
Check.Eq(rig.OnPlayer.Count, 2, "fully charged: no stone for a while though the mace still reads 0%");
|
||||
rig.Run(70_000);
|
||||
Check.Eq(rig.OnPlayer.Count, 3, "after the hold the stale read is tried once more");
|
||||
// R-20261201-171624-0bcf: the stale read asked for a stone every 2 minutes, each "fully charged".
|
||||
rig.Run(600_000);
|
||||
Check.Eq(rig.OnPlayer.Count, 2, "after the hold too: the server's 'fully charged' stands while the read is the same stale one");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("fullPerServer=1")), "the gear check says so");
|
||||
// A newer appraisal is real again: the mace really at 10%.
|
||||
FakeHost.Ints[(Mace, CurManaKey)] = 500;
|
||||
rig.Run(5000);
|
||||
Check.Eq(rig.OnPlayer.Count, 3, "a newer read (10%) refills");
|
||||
Check.Eq(rig.OnPlayer[2], StoneC, "with stone C");
|
||||
rig.Chat("You have no items equipped that need mana.");
|
||||
rig.Run(60_000);
|
||||
Check.Eq(rig.OnPlayer.Count, 3, "the server says nothing needs mana: held again, C kept");
|
||||
rig.Chat("The Mana Stone gives 1,000 points of mana to the following items: Khanda-handled Mace.\nYour items are fully charged.");
|
||||
rig.Run(600_000);
|
||||
Check.Eq(rig.OnPlayer.Count, 3, "full again: nothing more though the read says 10%");
|
||||
// The server's own word that the gear is low beats the kept read.
|
||||
FakeHost.Ints[(StoneA, CurManaKey)] = 2900; // stone A read again (a newer read): charged
|
||||
rig.Chat("Your Khanda-handled Mace is low on Mana.");
|
||||
rig.Run(5000);
|
||||
Check.Eq(rig.OnPlayer.Count, 4, "'low on Mana': refilled whatever the kept read");
|
||||
}
|
||||
|
||||
private static void UnreadableStoneIdentified()
|
||||
|
|
|
|||
254
Tools/RynthCore.RynthAiHostTests/Tests/MetaCommandAuditTests.cs
Normal file
254
Tools/RynthCore.RynthAiHostTests/Tests/MetaCommandAuditTests.cs
Normal file
|
|
@ -0,0 +1,254 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
using C = RynthCore.Plugin.RynthAi.LegacyUi.MetaConditionType;
|
||||
using A = RynthCore.Plugin.RynthAi.LegacyUi.MetaActionType;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The 2026-12-01 command audit, wave 2: /vt verbs and VTank options that were accepted but did
|
||||
// nothing, or the wrong thing. Each line runs as a meta's chat command.
|
||||
internal static class MetaCommandAuditTests
|
||||
{
|
||||
private const uint Player = 0x50000A71;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("meta action (12-01 audit 2): /vt settings load|save, /vt meta save, /vt loot save go to RynthAi's profile verbs", ProfileVerbs);
|
||||
r.Add("meta action (12-01 audit 2): VTank options with a RynthAi setting set it (LootOnlyRareCorpses, TargetSelectMethod, ...)", VtOptions);
|
||||
r.Add("ub opt / mt opt (12-01 audit 2): UtilityBelt and Mag-Tools option names with a RynthAi setting set it", UbMtOptions);
|
||||
r.Add("mt attack_melee (12-01 audit 2): melee mode first, then one attack on the selected or closest monster", MtAttackMelee);
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S = new() { IsMacroRunning = true, EnableMeta = true, CurrentState = "Default" };
|
||||
public readonly MetaManager M;
|
||||
public readonly List<string> Ra = new();
|
||||
|
||||
public Rig()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
M = new MetaManager(S, FakeHost.Create(), new PlayerVitalsCache());
|
||||
M.SetPlayerId(Player);
|
||||
M.SetRaCommandHandler(Ra.Add);
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="line"/> as a meta's chat command (one rule, one tick).</summary>
|
||||
public void Run(string line)
|
||||
{
|
||||
S.MetaRules = new List<MetaRule> { new() { State = S.CurrentState, Condition = C.Always, Action = A.ChatCommand, ActionData = line } };
|
||||
S.ForceStateReset = true;
|
||||
M.Think();
|
||||
}
|
||||
}
|
||||
|
||||
private static void ProfileVerbs()
|
||||
{
|
||||
var rig = new Rig();
|
||||
// VTank's shared settings profiles are RynthAi's character profiles (it has no other kind).
|
||||
rig.Run("/vt settings load Hunting");
|
||||
Check.True(rig.Ra.Contains("/ra settings loadchar Hunting"), "/vt settings load -> /ra settings loadchar");
|
||||
rig.Run("/vt settings save After Buffs");
|
||||
Check.True(rig.Ra.Contains("/ra settings savechar After Buffs"), "/vt settings save -> /ra settings savechar, spaces kept");
|
||||
rig.Run("/vt settings loadchar Banes");
|
||||
Check.True(rig.Ra.Contains("/ra settings loadchar Banes"), "loadchar as before");
|
||||
int before = rig.Ra.Count;
|
||||
rig.Run("/vt settings banana Hunting");
|
||||
Check.Eq(rig.Ra.Count, before, "another settings verb is still ignored");
|
||||
|
||||
rig.Run("/vt meta save My Meta");
|
||||
Check.True(rig.Ra.Contains("/ra meta saveas My Meta"), "/vt meta save -> /ra meta saveas");
|
||||
|
||||
rig.S.CurrentLootPath = @"X:\RynthAi\LootProfiles\Main Loot.utl";
|
||||
rig.Run("/vt loot save Copy Of Loot");
|
||||
Check.True(rig.Ra.Contains("/ra loot saveas Copy Of Loot"), "/vt loot save -> /ra loot saveas (a copy, then looted with)");
|
||||
before = rig.Ra.Count;
|
||||
rig.Run("/vt loot save main loot");
|
||||
Check.Eq(rig.Ra.Count, before, "the loot profile in use's own name: nothing to copy");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Main Loot.utl is the loot profile in use")), "said (in the log, a meta's line)");
|
||||
rig.Run("/vt loot save Main Loot.utl");
|
||||
Check.Eq(rig.Ra.Count, before, "with the extension too");
|
||||
|
||||
Check.True(MetaManager.VtUsageFor("/vt meta").Contains("load|save"), "the usage names save");
|
||||
}
|
||||
|
||||
private static void VtOptions()
|
||||
{
|
||||
var rig = new Rig();
|
||||
var s = rig.S;
|
||||
s.MineOnly = false;
|
||||
rig.Run("/vt opt set LootOnlyRareCorpses true");
|
||||
Check.True(s.LootOnlyRareCorpses, "LootOnlyRareCorpses is RynthAi's Loot Only Rare Corpses");
|
||||
Check.False(s.MineOnly, "not MineOnly, which nothing reads");
|
||||
rig.Run("/vt opt set lootonlyrarecorpses false");
|
||||
Check.False(s.LootOnlyRareCorpses, "and off");
|
||||
|
||||
rig.Run("/vt opt set CorpeApproachRange-Min 0.0125");
|
||||
Check.Near(s.CorpseApproachRangeMin, 3, 1e-3, "VTank's misspelt CorpeApproachRange-Min: landblock units to 3 yd");
|
||||
rig.Run("/vt opt set BlacklistMonsterAttemptCount 6");
|
||||
Check.Eq(s.BlacklistAttempts, 6, "BlacklistMonsterAttemptCount -> BlacklistAttempts");
|
||||
s.ManaTapMacroOff = true;
|
||||
rig.Run("/vt opt set ManaChargesWhenOff false");
|
||||
Check.False(s.ManaTapMacroOff, "ManaChargesWhenOff -> mana tapping with the macro off");
|
||||
rig.Run("/vt opt set ManaTankMinimumMana 4000");
|
||||
Check.Eq(s.ManaTapMinMana, 4000, "ManaTankMinimumMana -> ManaTapMinMana");
|
||||
rig.Run("/vt opt set Recharge-Helper-Stam 35");
|
||||
Check.Eq(s.RestamOthersAt, 35, "Recharge-Helper-Stam -> Re-stam Others");
|
||||
rig.Run("/vt opt set Recharge-Helper-Mana 25");
|
||||
Check.Eq(s.InfuseOthersAt, 25, "Recharge-Helper-Mana -> Infuse Others");
|
||||
rig.Run("/vt opt set Recharge-Helper-HitP 45");
|
||||
Check.Eq(s.HealOthersAt, 45, "Recharge-Helper-HitP -> Heal Others");
|
||||
|
||||
// TargetSelectMethod: 1 range = Closest, 2 angle = Least turning, 3 both: no RynthAi mode, kept.
|
||||
s.TargetSelection = 0;
|
||||
rig.Run("/vt opt set TargetSelectMethod 1");
|
||||
Check.Eq(s.TargetSelection, 1, "1 (range) -> Closest");
|
||||
rig.Run("/vt opt set TargetSelectMethod 2");
|
||||
Check.Eq(s.TargetSelection, 3, "2 (angle) -> Least turning");
|
||||
rig.Run("/vt opt set TargetSelectMethod 3");
|
||||
Check.Eq(s.TargetSelection, 3, "3 (both) leaves Targeting as it is");
|
||||
s.TargetSelection = 0;
|
||||
FakeHost.Chat.Clear();
|
||||
rig.M.TryHandleVtCommand("/vt opt get TargetSelectMethod");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("TargetSelectMethod = 3")), "with no VTank mode in use it reads back as set");
|
||||
|
||||
// DebuffEachFirst: 3 All = debuff every monster first, 1 One = off, 2 Priority: kept.
|
||||
rig.Run("/vt opt set DebuffEachFirst 3");
|
||||
Check.True(s.DebuffAllBeforeAttacking, "3 (all) -> Debuff every monster in range before attacking");
|
||||
rig.Run("/vt opt set DebuffEachFirst 1");
|
||||
Check.False(s.DebuffAllBeforeAttacking, "1 (one) -> off");
|
||||
rig.Run("/vt opt set DebuffEachFirst 2");
|
||||
Check.False(s.DebuffAllBeforeAttacking, "2 (priority) leaves it as it is");
|
||||
|
||||
// One that stays only stored: NavFarStopRange (VTank stops nav; RynthAi detours back instead).
|
||||
float offTrack = s.NavOffTrackYards;
|
||||
rig.Run("/vt opt set NavFarStopRange 0.5");
|
||||
Check.Eq(s.NavOffTrackYards, offTrack, "NavFarStopRange doesn't touch the off-track detour distance");
|
||||
}
|
||||
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
private static void UbMtOptions()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var p = new RynthAiPlugin();
|
||||
var s = new LegacyUiSettings();
|
||||
var host = FakeHost.Create(playerId: Player);
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
|
||||
void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(p, v);
|
||||
Set("_dashboard", dash);
|
||||
var m = new MetaManager(s, host, new PlayerVitalsCache());
|
||||
Set("_metaManager", m);
|
||||
Set("_playerId", Player);
|
||||
Set("_initialized", true);
|
||||
Set("_loginComplete", true);
|
||||
bool Ub(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleUbCommand", Any)!.Invoke(p, new object[] { line })!;
|
||||
bool Mt(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMtCommand", Any)!.Invoke(p, new object[] { line })!;
|
||||
|
||||
s.EnableAutocram = false;
|
||||
Check.True(Ub("/ub opt set InventoryManager.AutoCram true"), "/ub opt set InventoryManager.AutoCram");
|
||||
Check.True(s.EnableAutocram, "-> RynthAi's autocram");
|
||||
s.EnableAutostack = true;
|
||||
Ub("/ub opt toggle InventoryManager.AutoStack");
|
||||
Check.False(s.EnableAutostack, "/ub opt toggle takes UtilityBelt's name too");
|
||||
|
||||
s.AutoVendorEnabled = false;
|
||||
Mt("/mt opt set AutoBuySell.Enabled true");
|
||||
Check.True(s.AutoVendorEnabled, "Mag-Tools AutoBuySell.Enabled -> AutoVendor");
|
||||
s.LootChestsMacroOff = true;
|
||||
Mt("/mt opt set Looting.AutoLootChests false");
|
||||
Check.False(s.LootChestsMacroOff, "Looting.AutoLootChests -> Pickup with macro off");
|
||||
s.LootOwnCorpse = true;
|
||||
Mt("/mt opt set Looting.AutoLootMyCorpse false");
|
||||
Check.False(s.LootOwnCorpse, "Looting.AutoLootMyCorpse -> Loot own corpse");
|
||||
Mt("/mt opt set InventoryManagement.AetheriaRevealer true");
|
||||
Check.True(s.UnboxAetheriaWhenIdle, "AetheriaRevealer -> Unbox Aetheria When Idle");
|
||||
s.AutoConfirmCraft = false;
|
||||
s.AutoConfirmCraftPercent = 80;
|
||||
Mt("/mt opt set Tinkering.AutoClickYes true");
|
||||
Check.True(s.AutoConfirmCraft && s.AutoConfirmCraftPercent == 100, "Tinkering.AutoClickYes -> Auto-confirm crafting at 100%");
|
||||
FakeHost.Chat.Clear();
|
||||
Mt("/mt opt get Tinkering.AutoClickYes");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("Tinkering.AutoClickYes = 1")), "reads back");
|
||||
Mt("/mt opt set Tinkering.AutoClickYes false");
|
||||
Check.False(s.AutoConfirmCraft, "and off");
|
||||
|
||||
// Store-only names are still kept for metas, and say so.
|
||||
FakeHost.Chat.Clear();
|
||||
Mt("/mt opt set InventoryManagement.KeyRinger true");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("kept only for metas to read")), "KeyRinger: no RynthAi setting, kept");
|
||||
}
|
||||
|
||||
private const uint Lb = 0xA9B40000, NearMob = 0x80000771, FarMob = 0x80000772;
|
||||
|
||||
private static void MtAttackMelee()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = FakeHost.CombatModeCalls = FakeHost.AttackSendCalls = true;
|
||||
FakeHost.Names[Player] = "Attacker";
|
||||
FakeHost.PlayerIdValue = Player;
|
||||
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
foreach (var (id, name, y) in new[] { (NearMob, "Drudge Skulker", 98f), (FarMob, "Drudge Ravener", 110f) })
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Positions[id] = (Lb | 0x1C, 96f, y, 0f);
|
||||
FakeHost.ItemTypes[id] = 0x10;
|
||||
}
|
||||
var p = new RynthAiPlugin();
|
||||
var s = new LegacyUiSettings { MeleeAttackHeight = 2, MeleeAttackPower = 60 };
|
||||
var host = FakeHost.Create(playerId: Player);
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
|
||||
void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(p, v);
|
||||
Set("_dashboard", dash);
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
cache.Tick();
|
||||
foreach (uint id in new[] { NearMob, FarMob }) _ = cache[unchecked((int)id)];
|
||||
Set("_objectCache", cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_initialized", true);
|
||||
Set("_loginComplete", true);
|
||||
bool Mt(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMtCommand", Any)!.Invoke(p, new object[] { line })!;
|
||||
|
||||
// Peace mode: the first call goes to melee mode and attacks nothing.
|
||||
FakeHost.CombatModeValue = 1;
|
||||
Check.True(Mt("/mt attack_melee"), "/mt attack_melee is handled (it was unknown)");
|
||||
Check.True(FakeHost.CombatModeRequests.Contains(2), "out of melee mode: melee mode first");
|
||||
Check.Eq(FakeHost.AttackCalls.Count, 0, "no attack yet");
|
||||
|
||||
// Melee mode, nothing selected: the closest monster, once, at the settings' height and power.
|
||||
FakeHost.CombatModeValue = 2;
|
||||
Mt("/mt attack_melee");
|
||||
Check.Eq(FakeHost.AttackCalls.Count, 1, "one attack");
|
||||
Check.Eq(FakeHost.AttackCalls[0].Target, NearMob, "on the closest monster");
|
||||
Check.Eq(FakeHost.AttackCalls[0].Height, 1, "High (RynthAi 2) is AC's height 1");
|
||||
Check.Near(FakeHost.AttackCalls[0].Power, 0.6, 1e-3, "at the melee attack power");
|
||||
|
||||
// A selected monster is attacked, unless "closest" is given.
|
||||
FakeHost.SelectedItem = FarMob;
|
||||
Mt("/mt attack_melee");
|
||||
Check.Eq(FakeHost.AttackCalls[^1].Target, FarMob, "the selected monster");
|
||||
Mt("/mt attack_melee closest");
|
||||
Check.Eq(FakeHost.AttackCalls[^1].Target, NearMob, "closest: the closest one, whatever is selected");
|
||||
|
||||
Check.True(Mt("/mt attack_melee banana"), "a wrong word is handled");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("Usage: /mt attack_melee")), "with the usage");
|
||||
}
|
||||
}
|
||||
343
Tools/RynthCore.RynthAiHostTests/Tests/MetaEmbedNavTests.cs
Normal file
343
Tools/RynthCore.RynthAiHostTests/Tests/MetaEmbedNavTests.cs
Normal file
|
|
@ -0,0 +1,343 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Meta;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-11-30 hot fix: embedded nav routes in metas only loaded a nav file; they should embed the
|
||||
// loaded route, so the meta still works with the .nav file deleted. The Meta panel's route picker stored a NavProfiles file
|
||||
// name and the meta was saved without the route, so the meta read the file at run time; and in a meta
|
||||
// with any NAVDATA block, a rule naming a route without one was blanked on load (no route at all).
|
||||
// Scratch folders only: the meta's NavProfiles is redirected through MetaSaver.NavFolder.
|
||||
internal static class MetaEmbedNavTests
|
||||
{
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private static readonly DateTime T0 = new(2026, 11, 30, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("meta embed nav: a route picked in the Meta panel is written inside the .af and runs with its .nav deleted", PickEmbeds);
|
||||
r.Add("meta embed nav: re-picking takes the file's newer route; other edits keep the meta's copy", RepickRefreshes);
|
||||
r.Add("meta embed nav: an older .af naming a NavProfiles route gets it written in on load (other blocks kept)", LoadEmbedsOldMeta);
|
||||
r.Add("meta embed nav: a rule naming a route with no NAVDATA block keeps its name on load (was blanked)", ParserKeepsFileRef);
|
||||
r.Add("meta embed nav: Patrol, Camp and [None] with no file, and an empty .nav, are not embedded", PseudoRoutesNotEmbedded);
|
||||
r.Add("meta embed loaded: a recorded route never saved goes in as 'Route N' and runs with no file; the nav is the meta's now", EmbedLoadedUnsaved);
|
||||
r.Add("meta embed loaded: a loaded .nav goes in under its own name, the loaded copy (not the file), in a DoAll too", EmbedLoadedFileRoute);
|
||||
r.Add("meta embed loaded: a route a feature built (patrol, hunt) isn't embedded; the snapshot and chat say why", EmbedLoadedRefusesGenerated);
|
||||
r.Add("meta embed loaded: the generated mark survives a hot-reload resume", MadeBySurvivesResume);
|
||||
}
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static string Dir(string name)
|
||||
{
|
||||
string dir = Path.Combine(Program.TempRoot, "meta-embednav", name);
|
||||
if (Directory.Exists(dir))
|
||||
{
|
||||
foreach (string f in Directory.GetFiles(dir, "*", SearchOption.AllDirectories)) File.SetAttributes(f, FileAttributes.Normal);
|
||||
Directory.Delete(dir, recursive: true);
|
||||
}
|
||||
Directory.CreateDirectory(Path.Combine(dir, "NavProfiles"));
|
||||
return dir;
|
||||
}
|
||||
|
||||
private static string NavDir(string dir) => Path.Combine(dir, "NavProfiles");
|
||||
|
||||
private static void WriteNav(string dir, string name, int points)
|
||||
{
|
||||
var lines = new List<string> { "uTank2 NAV 1.2", "1", points.ToString() };
|
||||
for (int i = 0; i < points; i++)
|
||||
lines.AddRange(new[] { "0", (30 + i).ToString(), (40 + i).ToString(), "0", "0" });
|
||||
File.WriteAllLines(Path.Combine(NavDir(dir), name + ".nav"), lines);
|
||||
}
|
||||
|
||||
private static LegacyMetaUi MetaUi(LegacyDashboardRenderer dash) =>
|
||||
(LegacyMetaUi)typeof(LegacyDashboardRenderer).GetField("_metaUi", Any)!.GetValue(dash)!;
|
||||
|
||||
private static MetaSaver Saver(LegacyDashboardRenderer dash) =>
|
||||
(MetaSaver)typeof(LegacyDashboardRenderer).GetField("_metaSaver", Any)!.GetValue(dash)!;
|
||||
|
||||
/// <summary>A dashboard whose meta NavProfiles is <paramref name="dir"/>\NavProfiles, with <paramref name="path"/> loaded.</summary>
|
||||
private static LegacyDashboardRenderer Dash(string dir, string path)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
DataWriteGuard.Reset();
|
||||
var dash = new LegacyDashboardRenderer(FakeHost.Create());
|
||||
Saver(dash).NavFolder = () => NavDir(dir);
|
||||
var ui = MetaUi(dash);
|
||||
Check.True(ui.LoadMacroFile(path), "loads: " + ui.LastLoadStatus);
|
||||
return dash;
|
||||
}
|
||||
|
||||
private static string RuleJson(int action, string data) =>
|
||||
"{\"State\":\"Default\",\"Condition\":" + (int)MetaConditionType.Always + ",\"ConditionData\":\"\",\"Action\":" + action +
|
||||
",\"ActionData\":\"" + data + "\",\"Children\":[],\"ActionChildren\":[],\"Enabled\":true,\"Name\":\"\",\"LastFiredMs\":0}";
|
||||
|
||||
private static string EmbedNavJson(string route) => RuleJson((int)MetaActionType.EmbeddedNavRoute, route);
|
||||
|
||||
private static void Send(LegacyDashboardRenderer dash, string op, int index, string rule)
|
||||
{
|
||||
dash.HandleMetaCommand("{\"Op\":\"" + op + "\",\"Index\":" + index + ",\"Value\":\"\",\"Path\":\"\",\"Text\":\"\",\"Rule\":" + rule + "}");
|
||||
dash.DrainMetaCommands();
|
||||
}
|
||||
|
||||
private static int Points(IDictionary<string, List<string>> navs, string name) =>
|
||||
navs.TryGetValue(name, out var lines) ? NavRouteParser.LoadFromLines(lines).Points.Count : -1;
|
||||
|
||||
/// <summary>Runs <paramref name="settings"/>' meta for one tick the way the bot does, NavProfiles in <paramref name="navFolder"/>.</summary>
|
||||
private static void RunMeta(LegacyUiSettings settings, string navFolder)
|
||||
{
|
||||
FakeHost.PlayerPose = (0xA9B4001Cu, 96f, 96f, 0f);
|
||||
settings.IsMacroRunning = true;
|
||||
settings.EnableMeta = true;
|
||||
settings.CurrentState = "Default";
|
||||
settings.ForceStateReset = true;
|
||||
var m = new MetaManager(settings, FakeHost.Create(), new PlayerVitalsCache()) { Clock = () => T0, NavFolder = navFolder };
|
||||
m.Think();
|
||||
}
|
||||
|
||||
// ── tests ────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void PickEmbeds()
|
||||
{
|
||||
string dir = Dir("pick");
|
||||
string path = Path.Combine(dir, "farm.af");
|
||||
File.WriteAllText(path, "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tChat {/say one}\n~~ }\n");
|
||||
WriteNav(dir, "Hunt", 3);
|
||||
var dash = Dash(dir, path);
|
||||
|
||||
// The Meta panel picks "Hunt" (a NavProfiles file) for rule 1's Embedded Nav Route.
|
||||
Send(dash, "update_rule", 0, EmbedNavJson("Hunt"));
|
||||
Check.Eq(Points(dash.Settings.EmbeddedNavs, "Hunt"), 3, "the route is in the meta in memory");
|
||||
string text = File.ReadAllText(path);
|
||||
Check.True(text.Contains("NAVDATA: Hunt "), "the .af carries the route: " + text);
|
||||
|
||||
// The file goes; the meta still has it.
|
||||
File.Delete(Path.Combine(NavDir(dir), "Hunt.nav"));
|
||||
var back = AfFileParser.Load(path);
|
||||
Check.Eq(back.Rules[0].ActionData, "Hunt", "the rule still names it");
|
||||
Check.Eq(Points(back.EmbeddedNavs, "Hunt"), 3, "the route reads back from the .af with its points");
|
||||
|
||||
var s = new LegacyUiSettings();
|
||||
s.MetaRules = back.Rules;
|
||||
foreach (var kv in back.EmbeddedNavs) s.EmbeddedNavs[kv.Key] = kv.Value;
|
||||
FakeHost.Reset();
|
||||
RunMeta(s, NavDir(dir));
|
||||
Check.Eq(s.CurrentRoute.Points.Count, 3, "the meta runs the route with no .nav on disk");
|
||||
Check.Eq(s.CurrentNavPath, "<embedded:Hunt>", "...from inside the meta");
|
||||
Check.False(FakeHost.Chat.Exists(c => c.Contains("Route missing")), "no 'Route missing'");
|
||||
}
|
||||
|
||||
private static void RepickRefreshes()
|
||||
{
|
||||
string dir = Dir("repick");
|
||||
string path = Path.Combine(dir, "farm.af");
|
||||
File.WriteAllText(path, "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tChat {/say one}\n~~ }\n");
|
||||
WriteNav(dir, "Hunt", 3);
|
||||
var dash = Dash(dir, path);
|
||||
Send(dash, "update_rule", 0, EmbedNavJson("Hunt"));
|
||||
Check.Eq(Points(dash.Settings.EmbeddedNavs, "Hunt"), 3, "first pick: 3 points");
|
||||
|
||||
// The route is re-recorded on disk. An edit that keeps the route (the rule's name here) keeps the meta's copy.
|
||||
WriteNav(dir, "Hunt", 5);
|
||||
Send(dash, "update_rule", 0, EmbedNavJson("Hunt").Replace("\"Name\":\"\"", "\"Name\":\"go hunt\""));
|
||||
Check.Eq(Points(dash.Settings.EmbeddedNavs, "Hunt"), 3, "an edit that doesn't change the route keeps the embedded copy");
|
||||
|
||||
// Picking it again (another action, then the route) takes the file as it is now.
|
||||
Send(dash, "update_rule", 0, RuleJson((int)MetaActionType.ChatCommand, "/say two"));
|
||||
Send(dash, "update_rule", 0, EmbedNavJson("Hunt"));
|
||||
Check.Eq(Points(dash.Settings.EmbeddedNavs, "Hunt"), 5, "a fresh pick copies the newer file");
|
||||
Check.Eq(Points(AfFileParser.Load(path).EmbeddedNavs, "Hunt"), 5, "...and the .af has it");
|
||||
|
||||
// A new rule picking a route copies it too.
|
||||
WriteNav(dir, "Bank Run", 2);
|
||||
Send(dash, "add_rule", -1, EmbedNavJson("Bank Run"));
|
||||
Check.Eq(Points(AfFileParser.Load(path).EmbeddedNavs, "Bank Run"), 2, "add_rule: a route name with a space is embedded and reads back");
|
||||
}
|
||||
|
||||
private static void LoadEmbedsOldMeta()
|
||||
{
|
||||
string dir = Dir("load");
|
||||
string path = Path.Combine(dir, "old.af");
|
||||
// Written before the fix: rule 1 names a NavProfiles route, rule 2 a route the meta carries.
|
||||
File.WriteAllText(path,
|
||||
"STATE: {Default} ~~ {\n" +
|
||||
"\tIF:\tAlways\n\t\tDO:\tEmbedNav Hunt {[none]}\n" +
|
||||
"\tIF:\tNever\n\t\tDO:\tEmbedNav Other {[none]}\n" +
|
||||
"~~ }\n" +
|
||||
"NAVDATA: Other 8 ~~ {\nuTank2 NAV 1.2\n1\n1\n0\n10\n20\n0\n0\n~~ }\n");
|
||||
WriteNav(dir, "Hunt", 4);
|
||||
var dash = Dash(dir, path);
|
||||
Check.Eq(dash.Settings.MetaRules[0].ActionData, "Hunt", "the rule keeps its route name");
|
||||
Check.Eq(Points(dash.Settings.EmbeddedNavs, "Hunt"), 4, "the file route is in the meta after the load");
|
||||
|
||||
File.Delete(Path.Combine(NavDir(dir), "Hunt.nav"));
|
||||
var back = AfFileParser.Load(path);
|
||||
Check.Eq(Points(back.EmbeddedNavs, "Hunt"), 4, "the load wrote it into the .af");
|
||||
Check.Eq(Points(back.EmbeddedNavs, "Other"), 1, "the route it already carried is kept");
|
||||
Check.Eq(back.Rules.Count, 2, "both rules kept");
|
||||
|
||||
// A read-only .af isn't written by a load.
|
||||
string ro = Path.Combine(dir, "readonly.af");
|
||||
File.WriteAllText(ro, "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tEmbedNav Hunt2 {[none]}\n~~ }\n");
|
||||
WriteNav(dir, "Hunt2", 2);
|
||||
File.SetAttributes(ro, FileAttributes.ReadOnly);
|
||||
var dash2 = Dash(dir, ro);
|
||||
Check.Eq(Points(dash2.Settings.EmbeddedNavs, "Hunt2"), 2, "read-only: the route is still embedded in memory");
|
||||
Check.False(File.ReadAllText(ro).Contains("NAVDATA"), "read-only: the file isn't written on load");
|
||||
File.SetAttributes(ro, FileAttributes.Normal);
|
||||
}
|
||||
|
||||
private static void ParserKeepsFileRef()
|
||||
{
|
||||
var m = AfFileParser.LoadFromText(
|
||||
"STATE: {Default} ~~ {\n" +
|
||||
"\tIF:\tAlways\n\t\tDO:\tDoAll\n\t\t\t\tEmbedNav Hunt {[none]}\n\t\t\t\tEmbedNav Empty {[none]}\n" +
|
||||
"\tIF:\tNever\n\t\tDO:\tEmbedNav Other {[none]}\n" +
|
||||
"~~ }\n" +
|
||||
"NAVDATA: Other 8 ~~ {\nuTank2 NAV 1.2\n1\n1\n0\n10\n20\n0\n0\n~~ }\n" +
|
||||
"NAVDATA: Empty 3 ~~ {\nuTank2 NAV 1.2\n1\n0\n~~ }\n");
|
||||
var doAll = m.Rules[0].ActionChildren;
|
||||
Check.Eq(doAll[0].ActionData, "Hunt", "a route with no block keeps its name (a NavProfiles route)");
|
||||
Check.Eq(doAll[1].ActionData, "", "a route whose block is empty is still cleared");
|
||||
Check.Eq(m.Rules[1].ActionData, "Other", "an embedded route is untouched");
|
||||
}
|
||||
|
||||
// ── "Embed loaded" (the Meta panel's button) ─────────────────────────────
|
||||
|
||||
private static NavRouteParser Route(int points, string madeBy = "")
|
||||
{
|
||||
var route = new NavRouteParser { RouteType = NavRouteType.Circular, MadeBy = madeBy };
|
||||
for (int i = 0; i < points; i++)
|
||||
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 40 + i, EW = 30 + i, Z = 0 });
|
||||
return route;
|
||||
}
|
||||
|
||||
/// <summary>The snapshot's loadedRoute, as the engine panel reads it.</summary>
|
||||
private static (string Name, int Points, string Note) Loaded(LegacyDashboardRenderer dash)
|
||||
{
|
||||
using var doc = System.Text.Json.JsonDocument.Parse(dash.BuildMetaJson());
|
||||
var e = doc.RootElement.GetProperty("loadedRoute");
|
||||
return (e.GetProperty("name").GetString() ?? "", e.GetProperty("points").GetInt32(), e.GetProperty("note").GetString() ?? "");
|
||||
}
|
||||
|
||||
private static string Marked(string name) => name + MetaNavEmbedding.LoadedMarker;
|
||||
|
||||
private static void EmbedLoadedUnsaved()
|
||||
{
|
||||
string dir = Dir("loaded-unsaved");
|
||||
string path = Path.Combine(dir, "farm.af");
|
||||
File.WriteAllText(path, "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tChat {/say one}\n~~ }\n");
|
||||
WriteNav(dir, "Route 1", 2); // NavProfiles has a "Route 1": the new name skips it
|
||||
var dash = Dash(dir, path);
|
||||
dash.Settings.CurrentRoute = Route(4); // recorded in the nav editor, never saved
|
||||
dash.Settings.CurrentNavPath = string.Empty;
|
||||
|
||||
var loaded = Loaded(dash);
|
||||
Check.Eq(loaded.Note, "", "embeddable");
|
||||
Check.Eq(loaded.Name, "Route 2", "a new name no file or meta route has");
|
||||
Check.Eq(loaded.Points, 4, "its points");
|
||||
|
||||
Send(dash, "update_rule", 0, EmbedNavJson(Marked(loaded.Name)));
|
||||
Check.Eq(dash.Settings.MetaRules[0].ActionData, "Route 2", "the rule keeps the plain name (the marker is gone)");
|
||||
Check.Eq(Points(dash.Settings.EmbeddedNavs, "Route 2"), 4, "the route in memory went in");
|
||||
Check.Eq(dash.Settings.CurrentNavPath, "<embedded:Route 2>", "the loaded route is the meta's route now");
|
||||
Check.Eq(Loaded(dash).Name, "Route 2", "the button now names that route (no second copy)");
|
||||
|
||||
var back = AfFileParser.Load(path);
|
||||
Check.True(File.ReadAllText(path).Contains("NAVDATA: Route 2 "), "written into the .af");
|
||||
Check.False(File.ReadAllText(path).Contains(MetaNavEmbedding.LoadedMarker), "no marker in the file");
|
||||
var s = new LegacyUiSettings();
|
||||
s.MetaRules = back.Rules;
|
||||
foreach (var kv in back.EmbeddedNavs) s.EmbeddedNavs[kv.Key] = kv.Value;
|
||||
FakeHost.Reset();
|
||||
RunMeta(s, NavDir(dir));
|
||||
Check.Eq(s.CurrentRoute.Points.Count, 4, "the meta runs it; it never had a file");
|
||||
}
|
||||
|
||||
private static void EmbedLoadedFileRoute()
|
||||
{
|
||||
string dir = Dir("loaded-file");
|
||||
string path = Path.Combine(dir, "farm.af");
|
||||
File.WriteAllText(path, "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tChat {/say one}\n~~ }\n");
|
||||
WriteNav(dir, "Hunt", 3);
|
||||
var dash = Dash(dir, path);
|
||||
string navPath = Path.Combine(NavDir(dir), "Hunt.nav");
|
||||
dash.Settings.CurrentNavPath = navPath;
|
||||
dash.Settings.CurrentRoute = Route(6); // the loaded copy, edited since the file was written
|
||||
|
||||
var loaded = Loaded(dash);
|
||||
Check.Eq(loaded.Name, "Hunt", "a .nav's own name");
|
||||
// Inside a DoAll, as a second step.
|
||||
string doAll = "{\"State\":\"Default\",\"Condition\":" + (int)MetaConditionType.Always + ",\"ConditionData\":\"\",\"Action\":" + (int)MetaActionType.All +
|
||||
",\"ActionData\":\"\",\"Children\":[],\"ActionChildren\":[" + RuleJson((int)MetaActionType.ChatCommand, "/say go") + "," + EmbedNavJson(Marked("Hunt")) +
|
||||
"],\"Enabled\":true,\"Name\":\"\",\"LastFiredMs\":0}";
|
||||
Send(dash, "update_rule", 0, doAll);
|
||||
Check.Eq(dash.Settings.MetaRules[0].ActionChildren[1].ActionData, "Hunt", "the DoAll step keeps the plain name");
|
||||
Check.Eq(Points(dash.Settings.EmbeddedNavs, "Hunt"), 6, "the loaded copy went in, not the file's 3 points");
|
||||
Check.Eq(dash.Settings.CurrentNavPath, navPath, "a file route stays the file's");
|
||||
Check.Eq(Points(AfFileParser.Load(path).EmbeddedNavs, "Hunt"), 6, "...and the .af has it");
|
||||
}
|
||||
|
||||
private static void EmbedLoadedRefusesGenerated()
|
||||
{
|
||||
string dir = Dir("loaded-generated");
|
||||
string path = Path.Combine(dir, "farm.af");
|
||||
File.WriteAllText(path, "STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tChat {/say one}\n~~ }\n");
|
||||
var dash = Dash(dir, path);
|
||||
|
||||
dash.Settings.CurrentRoute = new NavRouteParser();
|
||||
dash.Settings.CurrentNavPath = string.Empty;
|
||||
Check.True(Loaded(dash).Note.Contains("No nav route"), "nothing loaded: " + Loaded(dash).Note);
|
||||
|
||||
// /ra dunnav leaves the old file path while its route runs: the mark is what counts.
|
||||
dash.Settings.CurrentNavPath = Path.Combine(NavDir(dir), "Hunt.nav");
|
||||
dash.Settings.CurrentRoute = Route(9, "the dungeon patrol");
|
||||
var loaded = Loaded(dash);
|
||||
Check.True(loaded.Name == "" && loaded.Note.Contains("the dungeon patrol"), "the snapshot says why: " + loaded.Note);
|
||||
|
||||
Send(dash, "update_rule", 0, EmbedNavJson(Marked("Hunt")));
|
||||
Check.Eq(dash.Settings.EmbeddedNavs.Count, 0, "nothing embedded");
|
||||
Check.Eq(dash.Settings.MetaRules[0].ActionData, "Hunt", "the rule has the plain name, no marker");
|
||||
Check.True(FakeHost.Chat.Exists(c => c.Contains("wasn't embedded") && c.Contains("the dungeon patrol")), "chat says why");
|
||||
|
||||
dash.Settings.CurrentNavPath = "<navheading>";
|
||||
dash.Settings.CurrentRoute = Route(2);
|
||||
Check.True(Loaded(dash).Note.Length > 0, "a <navheading> route isn't a nav route");
|
||||
}
|
||||
|
||||
private static void MadeBySurvivesResume()
|
||||
{
|
||||
var s = new MetaResumeState { RouteLines = Route(3).ToLines(), RouteMadeBy = "the hunt", NavPath = "", State = "Default" };
|
||||
string text = MetaResumeStore.Serialize(s);
|
||||
Check.True(MetaResumeStore.TryParse(text, out MetaResumeState back), "reads back");
|
||||
Check.Eq(back.RouteMadeBy, "the hunt", "the mark is kept");
|
||||
}
|
||||
|
||||
private static void PseudoRoutesNotEmbedded()
|
||||
{
|
||||
string dir = Dir("pseudo");
|
||||
WriteNav(dir, "Blank", 0);
|
||||
var rules = new List<MetaRule>();
|
||||
foreach (string r in new[] { "Patrol", "Camp", "[None]", "Blank", "NotThere", "..\\farm" })
|
||||
rules.Add(new MetaRule { State = "Default", Condition = MetaConditionType.Always, Action = MetaActionType.EmbeddedNavRoute, ActionData = r });
|
||||
File.WriteAllLines(Path.Combine(dir, "farm.nav"), new[] { "uTank2 NAV 1.2", "1", "1", "0", "1", "2", "0", "0" });
|
||||
var navs = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
|
||||
var added = MetaNavEmbedding.EmbedMissing(rules, navs, NavDir(dir));
|
||||
Check.Eq(added.Count, 0, "nothing embedded: " + string.Join(", ", added));
|
||||
Check.Eq(navs.Count, 0, "no routes");
|
||||
|
||||
// A Patrol.nav that exists is a real route (MetaManager runs it): that one is embedded.
|
||||
WriteNav(dir, "Patrol", 2);
|
||||
added = MetaNavEmbedding.EmbedMissing(rules, navs, NavDir(dir));
|
||||
Check.Eq(string.Join(",", added), "Patrol", "a real Patrol.nav is embedded");
|
||||
}
|
||||
}
|
||||
|
|
@ -46,6 +46,7 @@ internal static class MetaTests
|
|||
r.Add("meta: need-to-buff with no buff manager, unknown condition types", NeedToBuffAndUnknown);
|
||||
r.Add("meta action: chat commands, /ra, /vt and /mt", ChatCommands);
|
||||
r.Add("meta action: the /vt verbs and options the metas use that were missing (2026-10-17)", VtPortedVerbs);
|
||||
r.Add("meta action (12-01 command audit): reverseroute true|false sets the direction, query says it; addnavjump; SwitchWandToDebuff leaves dispel items alone", VtCommandAudit);
|
||||
r.Add("meta action: SetMetaState, CallMetaState and ReturnFromCall", CallReturn);
|
||||
r.Add("meta action: All runs every child in order", AllAction);
|
||||
r.Add("meta action: embedded nav route", EmbeddedNav);
|
||||
|
|
@ -924,6 +925,43 @@ internal static class MetaTests
|
|||
Check.Eq(reversed.S.ActiveNavIndex, 2, "index mirrored");
|
||||
}
|
||||
|
||||
// 2026-12-01 command audit (every command a meta sends must work, or metas break): commands taken
|
||||
// but done wrong. reverseroute flipped on every call whatever its true/false; addnavjump wasn't known;
|
||||
// SwitchWandToDebuff switched dispel items on.
|
||||
private static void VtCommandAudit()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var rig = new Rig(FakeHost.Create(), Player);
|
||||
rig.S.CurrentRoute = NavRouteParser.LoadFromLines(NavLines(2,
|
||||
(0, 1, 1, NoTrailer), (0, 2, 2, NoTrailer), (0, 3, 3, NoTrailer)));
|
||||
rig.S.ActiveNavIndex = 0;
|
||||
RunAction(rig, A.ChatCommand, "/vt reverseroute true");
|
||||
Check.Near(rig.S.CurrentRoute.Points[0].EW, 3, 1e-9, "true: reversed");
|
||||
RunAction(rig, A.ChatCommand, "/vt reverseroute true");
|
||||
Check.Near(rig.S.CurrentRoute.Points[0].EW, 3, 1e-9, "true again (each state entry): still reversed, not flipped back");
|
||||
Check.True(rig.M.RouteReversed, "it knows it is reversed");
|
||||
RunAction(rig, A.ChatCommand, "/vt reverseroute false");
|
||||
Check.Near(rig.S.CurrentRoute.Points[0].EW, 1, 1e-9, "false: the file's own order");
|
||||
RunAction(rig, A.ChatCommand, "/vt reverseroute false");
|
||||
Check.Near(rig.S.CurrentRoute.Points[0].EW, 1, 1e-9, "false again: unchanged");
|
||||
RunAction(rig, A.ChatCommand, "/vt reverseroute");
|
||||
Check.Near(rig.S.CurrentRoute.Points[0].EW, 3, 1e-9, "no argument: the other way");
|
||||
Check.True(rig.M.TryHandleVtCommand("/vt reverseroutequery"), "reverseroutequery is taken");
|
||||
rig.S.CurrentRoute = NavRouteParser.LoadFromLines(NavLines(2, (0, 5, 5, NoTrailer), (0, 6, 6, NoTrailer)));
|
||||
Check.False(rig.M.RouteReversed, "a route newly loaded is in its own order");
|
||||
RunAction(rig, A.ChatCommand, "/vt reverseroute false");
|
||||
Check.Near(rig.S.CurrentRoute.Points[0].EW, 5, 1e-9, "false on the new route: left as it is");
|
||||
|
||||
RunAction(rig, A.ChatCommand, "/vt addnavjump 270 true 650");
|
||||
Check.True(rig.Ra.Contains("/ra nav addjump 650 shift heading 270"), "/vt addnavjump -> /ra nav addjump with the heading: " + string.Join(" | ", rig.Ra));
|
||||
RunAction(rig, A.ChatCommand, "/vt addnavjump 90 false 2000");
|
||||
Check.True(rig.Ra.Contains("/ra nav addjump 1000 heading 90"), "held 1000 ms at most, no shift");
|
||||
|
||||
rig.S.UseDispelItems = false;
|
||||
RunAction(rig, A.ChatCommand, "/vt opt set SwitchWandToDebuff true");
|
||||
Check.False(rig.S.UseDispelItems, "SwitchWandToDebuff no longer turns dispel items on");
|
||||
}
|
||||
|
||||
// /vt verbs and options found in ub-IT and the metas on disk (universalremote.met, SASocietyTasks.met,
|
||||
// FoundryIzexi.met, DerethExploration (1).met) that RynthAi didn't handle.
|
||||
private static void VtPortedVerbs()
|
||||
|
|
|
|||
114
Tools/RynthCore.RynthAiHostTests/Tests/NamedLayoutRowTests.cs
Normal file
114
Tools/RynthCore.RynthAiHostTests/Tests/NamedLayoutRowTests.cs
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Named window layouts in the Loaded files drawer (2026-12-01, report R-20261127-150927-7938; named
|
||||
// layouts, in the files drawer). The engine keeps them
|
||||
// (/rc layout save|load|delete <name>); the LAYOUT row lists the folder, loads a pick, and its "..." saves,
|
||||
// saves as, renames and deletes. Here against a test folder, never the PC's real layouts.
|
||||
internal static class NamedLayoutRowTests
|
||||
{
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("named layouts (R-20261127 7938): the LAYOUT row lists the saved layouts, loads a pick and remembers it per character", ListAndLoad);
|
||||
r.Add("named layouts: Save, Save As (asks before replacing), Rename and Delete; names checked as the engine does", Verbs);
|
||||
}
|
||||
|
||||
private static (LegacyDashboardRenderer Dash, string Root, string Char) Rig(string name)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var host = FakeHost.Create();
|
||||
var dash = new LegacyDashboardRenderer(host);
|
||||
string root = Path.Combine(Program.TempRoot, "layouts-" + name);
|
||||
string saved = Path.Combine(root, "_saved");
|
||||
string charFolder = Path.Combine(root, "char");
|
||||
Directory.CreateDirectory(saved);
|
||||
Directory.CreateDirectory(charFolder);
|
||||
LegacyDashboardRenderer.LayoutsFolderForTests = saved;
|
||||
typeof(LegacyDashboardRenderer).GetField("_charFolder", Any)!.SetValue(dash, charFolder);
|
||||
return (dash, saved, charFolder);
|
||||
}
|
||||
|
||||
private static void Saved(string folder, string name)
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(folder, name));
|
||||
File.WriteAllText(Path.Combine(folder, name, "panel_state.txt"), "x\n");
|
||||
}
|
||||
|
||||
private static void ListAndLoad()
|
||||
{
|
||||
var (dash, saved, charFolder) = Rig("list");
|
||||
try
|
||||
{
|
||||
Saved(saved, "Raid");
|
||||
Saved(saved, "Mule");
|
||||
Directory.CreateDirectory(Path.Combine(saved, "_deleted", "Old"));
|
||||
Directory.CreateDirectory(Path.Combine(saved, "Empty")); // no panel_state.txt: not a layout
|
||||
dash.RefreshLayoutFiles();
|
||||
DashboardFiles f = dash.ReadDashboardFiles();
|
||||
Check.True(f.Layouts != null && f.Layouts.SequenceEqual(new[] { "Mule", "Raid" }), "listed, sorted, _deleted and empty folders left out: " + string.Join(",", f.Layouts ?? Array.Empty<string>()));
|
||||
Check.Eq(f.LayoutName, "None", "none in use yet");
|
||||
|
||||
dash.SelectProfileAtIndex(5, 1); // Raid
|
||||
Check.True(FakeHost.ChatCommands.Contains("/rc layout load Raid"), "a pick loads it through the engine: " + string.Join(" | ", FakeHost.ChatCommands));
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("Loading the layout 'Raid'")), "and says so");
|
||||
f = dash.ReadDashboardFiles();
|
||||
Check.True(f.LayoutName == "Raid" && f.LayoutIdx == 1, $"the row shows it ({f.LayoutName}, {f.LayoutIdx})");
|
||||
Check.Eq(File.ReadAllText(Path.Combine(charFolder, "layout.txt")).Trim(), "Raid", "remembered beside the character's profiles");
|
||||
|
||||
var again = new LegacyDashboardRenderer(FakeHost.Create());
|
||||
typeof(LegacyDashboardRenderer).GetField("_charFolder", Any)!.SetValue(again, charFolder);
|
||||
typeof(LegacyDashboardRenderer).GetMethod("ReadLayoutName", Any)!.Invoke(again, null);
|
||||
Check.Eq(again.LayoutName, "Raid", "read back at the next login");
|
||||
Check.True(again.ProfileInfo(ProfileKind.Layout).HasFile, "the menu has a layout in use");
|
||||
}
|
||||
finally { LegacyDashboardRenderer.LayoutsFolderForTests = null; }
|
||||
}
|
||||
|
||||
private static void Verbs()
|
||||
{
|
||||
var (dash, saved, _) = Rig("verbs");
|
||||
try
|
||||
{
|
||||
ProfileResult r = dash.LayoutAction(ProfileVerb.Save, null, false);
|
||||
Check.False(r.Ok, "Save with no layout in use: says to use Save As");
|
||||
r = dash.LayoutAction(ProfileVerb.SaveAs, "a/b", false);
|
||||
Check.True(!r.Ok && r.Text.Contains("can't be in a layout name"), "a bad name: said why: " + r.Text);
|
||||
Check.Eq(FakeHost.ChatCommands.Count, 0, "nothing sent for either");
|
||||
|
||||
r = dash.LayoutAction(ProfileVerb.SaveAs, "Raid Setup", false);
|
||||
Check.True(r.Ok && FakeHost.ChatCommands.Contains("/rc layout save Raid Setup"), "Save As: the engine saves it: " + r.Text);
|
||||
Check.Eq(dash.LayoutName, "Raid Setup", "and it is the one in use");
|
||||
Saved(saved, "Raid Setup"); // what the engine's save leaves
|
||||
|
||||
r = dash.LayoutAction(ProfileVerb.Save, null, false);
|
||||
Check.True(r.Ok && FakeHost.ChatCommands.Count(c => c == "/rc layout save Raid Setup") == 2, "Save: into the one in use");
|
||||
|
||||
Saved(saved, "Other");
|
||||
r = dash.LayoutAction(ProfileVerb.SaveAs, "Other", false);
|
||||
Check.True(!r.Ok && r.NeedsReplace, "Save As onto another layout asks first");
|
||||
r = dash.LayoutAction(ProfileVerb.SaveAs, "Other", true);
|
||||
Check.True(r.Ok && FakeHost.ChatCommands.Contains("/rc layout save Other"), "and replaces it on the yes");
|
||||
|
||||
r = dash.LayoutAction(ProfileVerb.Rename, "Raid", false);
|
||||
Check.True(r.Ok && Directory.Exists(Path.Combine(saved, "Raid")) && !Directory.Exists(Path.Combine(saved, "Other")),
|
||||
"Rename moves the layout's folder: " + r.Text);
|
||||
Check.Eq(dash.LayoutName, "Raid", "the renamed one is in use");
|
||||
r = dash.LayoutAction(ProfileVerb.Rename, "Raid Setup", false);
|
||||
Check.True(!r.Ok && r.Text.Contains("already"), "not onto another layout");
|
||||
|
||||
r = dash.LayoutAction(ProfileVerb.Delete, null, false);
|
||||
Check.True(r.Ok && FakeHost.ChatCommands.Contains("/rc layout delete Raid"), "Delete: the engine moves it aside: " + r.Text);
|
||||
Check.Eq(dash.LayoutName, string.Empty, "none in use after");
|
||||
}
|
||||
finally { LegacyDashboardRenderer.LayoutsFolderForTests = null; }
|
||||
}
|
||||
}
|
||||
|
|
@ -12,6 +12,107 @@ internal static class NavHeadingTests
|
|||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("navheading: RynthNav's corners become a Once route in nav coordinates, doorways kept", CornersToRoute);
|
||||
r.Add("navheading: a step that goes takes no detour", PlainStepGoes);
|
||||
r.Add("navheading: a goal in a rock or cliff face: the same heading, closer", GoalOffMapPulledBack);
|
||||
r.Add("navheading: no walkable ground ahead at any distance: the way round at 45°", OffMapAheadGoesRound);
|
||||
r.Add("navheading: no way to the goal (NoPath): closer, not a straight line", NoPathPulledBack);
|
||||
r.Add("navheading: nothing walkable on any goal: straight, saying why", NothingWalkable);
|
||||
r.Add("navheading: RynthNav not loaded: straight at once", RynthNavMissing);
|
||||
r.Add("navheading: a blocked step keeps to the side the last one took", KeepsSide);
|
||||
}
|
||||
|
||||
// A fake RynthNav for PlanHeading: `walkable(goal)` says Ok (a straight path to it), NoMesh, NoPath, or a short
|
||||
// Partial path that gets nowhere (blocked). Heading 0 = north (+y), 90 = east (+x); the character stands at 0,0.
|
||||
private static readonly OutdoorHunt.Vec At = new(0, 0, 0);
|
||||
private static double Yd(OutdoorHunt.Vec v) => Math.Sqrt(v.X * v.X + v.Y * v.Y) / 1.0;
|
||||
private static double BearingOf(OutdoorHunt.Vec v)
|
||||
{
|
||||
double b = Math.Atan2(v.X, v.Y) * 180 / Math.PI;
|
||||
return b < 0 ? b + 360 : b;
|
||||
}
|
||||
private static OutdoorHunt.PathResult Ok(OutdoorHunt.Vec goal) =>
|
||||
new(OutdoorHunt.PathStatus.Ok, new[] { goal }, Yd(goal), 0);
|
||||
private static OutdoorHunt.PathResult Fail(OutdoorHunt.PathStatus s) =>
|
||||
new(s, Array.Empty<OutdoorHunt.Vec>(), 0, 0);
|
||||
private static OutdoorHunt.PathResult Stuck() =>
|
||||
new(OutdoorHunt.PathStatus.Partial, new[] { new OutdoorHunt.Vec(0, 1, 0) }, 1, 0);
|
||||
|
||||
// PlanHeading works in world units; the tests treat them as yards (only ratios and bearings matter).
|
||||
private static void PlainStepGoes()
|
||||
{
|
||||
var plan = RynthAiPlugin.PlanHeading(At, 0, 50, 0, g => Ok(g));
|
||||
Check.True(plan.Found, "found");
|
||||
Check.True(plan.Detour == "", $"no detour note, got '{plan.Detour}'");
|
||||
Check.True(Math.Abs(Yd(plan.Path.Corners[^1]) - 50) < 0.01, "the full 50");
|
||||
Check.True(plan.Side == 0, "no side taken");
|
||||
}
|
||||
|
||||
private static void GoalOffMapPulledBack()
|
||||
{
|
||||
// A rock face from 40 yd on: goals past it are off the mesh.
|
||||
int calls = 0;
|
||||
var plan = RynthAiPlugin.PlanHeading(At, 0, 50, 0, g => { calls++; return Yd(g) > 40 ? Fail(OutdoorHunt.PathStatus.NoMesh) : Ok(g); });
|
||||
Check.True(plan.Found, "found");
|
||||
Check.True(Math.Abs(Yd(plan.Path.Corners[^1]) - 30) < 0.01, $"30 yd (60% of 50), got {Yd(plan.Path.Corners[^1]):0.0}");
|
||||
Check.True(Math.Abs(BearingOf(plan.Path.Corners[^1])) < 0.01, "still north");
|
||||
Check.True(plan.Detour.Contains("off walkable ground"), $"says why, got '{plan.Detour}'");
|
||||
Check.True(calls == 2, $"the 50 yd goal, then 30 (calls {calls})");
|
||||
}
|
||||
|
||||
private static void OffMapAheadGoesRound()
|
||||
{
|
||||
// A cliff ahead (north, any distance) and to the left: only the north-east is walkable.
|
||||
var plan = RynthAiPlugin.PlanHeading(At, 0, 50, 0, g =>
|
||||
{
|
||||
double b = BearingOf(g);
|
||||
return b > 30 && b < 60 ? Ok(g) : Fail(OutdoorHunt.PathStatus.NoMesh);
|
||||
});
|
||||
Check.True(plan.Found, "found a way round");
|
||||
Check.True(Math.Abs(BearingOf(plan.Path.Corners[^1]) - 45) < 0.01, "45° right");
|
||||
Check.True(plan.Detour.Contains("45° right"), $"says so, got '{plan.Detour}'");
|
||||
Check.True(plan.Side == 1, "the right side is kept from now on");
|
||||
}
|
||||
|
||||
private static void NoPathPulledBack()
|
||||
{
|
||||
var plan = RynthAiPlugin.PlanHeading(At, 90, 50, 0, g => Yd(g) > 20 ? Fail(OutdoorHunt.PathStatus.NoPath) : Ok(g));
|
||||
Check.True(plan.Found, "found");
|
||||
Check.True(Math.Abs(Yd(plan.Path.Corners[^1]) - 15) < 0.01, $"15 yd (30% of 50), got {Yd(plan.Path.Corners[^1]):0.0}");
|
||||
Check.True(Math.Abs(BearingOf(plan.Path.Corners[^1]) - 90) < 0.01, "still east");
|
||||
}
|
||||
|
||||
private static void NothingWalkable()
|
||||
{
|
||||
int calls = 0;
|
||||
var plan = RynthAiPlugin.PlanHeading(At, 0, 50, 0, g => { calls++; return Fail(OutdoorHunt.PathStatus.NoMesh); });
|
||||
Check.True(!plan.Found, "nothing found");
|
||||
Check.True(plan.Straight.Contains("no walkable ground"), $"says why, got '{plan.Straight}'");
|
||||
Check.True(calls > 7, $"every goal tried, closer ones too (calls {calls})");
|
||||
}
|
||||
|
||||
private static void RynthNavMissing()
|
||||
{
|
||||
int calls = 0;
|
||||
var plan = RynthAiPlugin.PlanHeading(At, 0, 50, 0, g => { calls++; return Fail(OutdoorHunt.PathStatus.Unavailable); });
|
||||
Check.True(!plan.Found, "nothing found");
|
||||
Check.True(plan.Straight.Contains("isn't loaded"), $"says why, got '{plan.Straight}'");
|
||||
Check.True(calls == 1, $"asked once (calls {calls})");
|
||||
}
|
||||
|
||||
private static void KeepsSide()
|
||||
{
|
||||
// Ahead is blocked at every distance (a path that gets nowhere); both 45° sides are open. The last detour
|
||||
// went left: this one goes left too.
|
||||
Func<OutdoorHunt.Vec, OutdoorHunt.PathResult> nav = g =>
|
||||
{
|
||||
double b = BearingOf(g);
|
||||
return (b < 1 || b > 359) ? Stuck() : Ok(g);
|
||||
};
|
||||
var left = RynthAiPlugin.PlanHeading(At, 0, 50, -1, nav);
|
||||
Check.True(left.Found && Math.Abs(BearingOf(left.Path.Corners[^1]) - 315) < 0.01, "45° left, as the last step");
|
||||
Check.True(left.Side == -1, "left kept");
|
||||
var none = RynthAiPlugin.PlanHeading(At, 0, 50, 0, nav);
|
||||
Check.True(none.Found && Math.Abs(BearingOf(none.Path.Corners[^1]) - 45) < 0.01, "no side yet: the first way round (right)");
|
||||
}
|
||||
|
||||
private static double World(double navUnits) => (navUnits * 10.0 + 1019.5) * 24.0;
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ internal static class NavJumpStepTests
|
|||
r.Add("nav jump step: /ra nav addjump adds a Jump where you stand, facing your way, held 300 ms (or as asked), saved to the file", AddJump);
|
||||
r.Add("nav jump step: while recording, no point is laid until you have jumped and landed", RecordingHolds);
|
||||
r.Add("nav jump step: ranav[] gives the route's name, place on it, type and whether a Once route ended", RaNav);
|
||||
r.Add("nav trail (R-20261129 0574): /ra navtrail route|back makes the breadcrumb trail the route; too short or off says how", TrailToRoute);
|
||||
}
|
||||
|
||||
private static DunRouteTests.Rig Rig(string folder, out string navPath)
|
||||
|
|
@ -100,6 +101,54 @@ internal static class NavJumpStepTests
|
|||
$"never still (a long fall): let go after {NavBreadcrumbTracker.JumpHoldMaxMs} ms ({at - t0})");
|
||||
}
|
||||
|
||||
// R-20261129-210845-0574: "an option to have a nav route made from your breadcrumbs". The Nav panel's
|
||||
// Tools menu had it (Walk it again / Walk it back); /ra navtrail route|back [name] does it from chat.
|
||||
// A name saves NavProfiles\<name>.nav through Save As; not used here (the tests share the real folder).
|
||||
private static void TrailToRoute()
|
||||
{
|
||||
var rig = Rig("NavProfiles-trail", out string navPath);
|
||||
var dash = (LegacyDashboardRenderer)rig.Get("_dashboard")!;
|
||||
var t = new NavBreadcrumbTracker(new RynthCore.PluginSdk.RynthCoreHost(FakeHost.LastApi), rig.S, _ => null, _ => { });
|
||||
dash.NavBreadcrumbs = t;
|
||||
// The rig's dashboard is built bare: what login and the constructor set in game.
|
||||
typeof(LegacyDashboardRenderer).GetField("_navFolder", Any)!.SetValue(dash, Path.GetDirectoryName(navPath));
|
||||
foreach (var (f, v) in new (string, object)[] { ("_profileListsLock", new object()), ("_navFiles", new System.Collections.Generic.List<string>()) })
|
||||
{
|
||||
var fi = typeof(LegacyDashboardRenderer).GetField(f, Any)!;
|
||||
if (fi.GetValue(dash) == null) fi.SetValue(dash, v);
|
||||
}
|
||||
rig.S.NavOverlay.TrackBreadcrumbs = false;
|
||||
|
||||
var said = rig.Typed("/ra navtrail route");
|
||||
Check.True(said.Any(l => l.Contains("No trail") && l.Contains("/ra navtrail on")), "no trail, Breadcrumbs off: says how: " + string.Join(" | ", said));
|
||||
Check.Eq(rig.S.CurrentNavPath, navPath, "the loaded route is left alone");
|
||||
|
||||
var crumbs = new[]
|
||||
{
|
||||
new NavCrumb(10.0, 20.0, 0f, true),
|
||||
new NavCrumb(10.1, 20.0, 0f, false),
|
||||
new NavCrumb(10.2, 20.0, 0f, false),
|
||||
new NavCrumb(10.3, 20.1, 0f, false),
|
||||
};
|
||||
typeof(NavBreadcrumbTracker).GetField("_snapshot", Any)!.SetValue(t, crumbs);
|
||||
rig.S.NavOverlay.RecordSpacingYards = 1;
|
||||
|
||||
said = rig.Typed("/ra navtrail route");
|
||||
var pts = rig.S.CurrentRoute.Points;
|
||||
Check.True(said.Any(l => l.Contains("Trail route created") && l.Contains("(unsaved)")), "made, unsaved: " + string.Join(" | ", said));
|
||||
Check.True(pts.Count >= 2 && Math.Abs(pts[0].NS - 10.0) < 1e-9 && Math.Abs(pts[^1].NS - 10.3) < 1e-9, "walked again: first crumb first");
|
||||
Check.Eq(rig.S.CurrentNavPath, string.Empty, "a new route, not the loaded file");
|
||||
Check.True(File.Exists(navPath) && NavRouteParser.Load(navPath).Points.Count == 1, "the loaded file on disk is unchanged");
|
||||
|
||||
said = rig.Typed("/ra navtrail back");
|
||||
pts = rig.S.CurrentRoute.Points;
|
||||
Check.True(said.Any(l => l.Contains("Backtrack route created")), "backtrack said: " + string.Join(" | ", said));
|
||||
Check.True(Math.Abs(pts[0].NS - 10.3) < 1e-9 && Math.Abs(pts[^1].NS - 10.0) < 1e-9, "walked back: last crumb first");
|
||||
|
||||
said = rig.Typed("/ra navtrail");
|
||||
Check.True(said.Any(l => l.Contains("/ra navtrail route [name]")), "the status line tells how: " + string.Join(" | ", said));
|
||||
}
|
||||
|
||||
private static void RaNav()
|
||||
{
|
||||
var rig = Rig("NavProfiles-ranav", out _);
|
||||
|
|
|
|||
|
|
@ -24,6 +24,10 @@ internal static class OutdoorHuntTests
|
|||
r.Add("hunt fence (\"here and there nav takes him outside\"): a walk round the outside is no walk; from outside, a walk back in is", FenceWalk);
|
||||
r.Add("hunt: plans again when the monster moves, the walk runs out, or a while passes; not every tick", Replan);
|
||||
r.Add("hunt: nothing in range: it waits where it is (no walk back to the start); Hunt Radius defaults to anywhere", WaitsWhereItIs);
|
||||
r.Add("hunt roam (R-20261127 32e4): nothing in range: walks to the nearest part of the area not seen, keeps walking, a monster ends it", RoamWalks);
|
||||
r.Add("hunt roam: walks the whole Hunt Radius, never outside it, then waits; looks again after 5 min", RoamCoversArea);
|
||||
r.Add("hunt roam: a part no walk gets to, or a walk stopping short, is left out; the rest is still roamed", RoamUnreachable);
|
||||
r.Add("hunt roam: inside the fence only; Hunt Radius anywhere roams Hunt Range round the start; on by default (and the setting)", RoamFenceAndDefaults);
|
||||
r.Add("hunt: /ra hunt range|radius answer and cap; status and stop don't toggle it; panel opens the window", Commands);
|
||||
r.Add("hunt: the target dies: the next one; no pathfinder: it stands", NextAndNoPathfinder);
|
||||
r.Add("hunt: the settings round-trip with the rest (saved, copied, engine payload)", Settings);
|
||||
|
|
@ -317,7 +321,7 @@ internal static class OutdoorHuntTests
|
|||
private static void FloorApartLeftOut()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var h = new OutdoorHunt();
|
||||
var h = new OutdoorHunt { Roam = false };
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
var up = new OutdoorHunt.Vec(1006, 1000, 3.3);
|
||||
|
|
@ -351,7 +355,7 @@ internal static class OutdoorHuntTests
|
|||
private static void TooFarRoundForIt()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RangeYd = 300 }; // Hunt Range big enough that 2x it allows the walk
|
||||
var h = new OutdoorHunt { RangeYd = 300, Roam = false }; // Hunt Range big enough that 2x it allows the walk
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
nav.Overrides[(1068, 1000)] = new(OutdoorHunt.PathStatus.Ok, new[] { V(1000, 1150), V(1068, 1150), V(1068, 1000) }, 425, 0);
|
||||
|
|
@ -639,13 +643,13 @@ internal static class OutdoorHuntTests
|
|||
// An open-world Thread's circle, its fence 50 yd round (1000, 1000): a monster past it is no pick, even nearer.
|
||||
private static void FenceHunt()
|
||||
{
|
||||
var h = new OutdoorHunt { RangeYd = 100, Fence = p => (p.X - 1000) * (p.X - 1000) + (p.Y - 1000) * (p.Y - 1000) <= 50 * 50 };
|
||||
var h = new OutdoorHunt { Roam = false, RangeYd = 100, Fence = p => (p.X - 1000) * (p.X - 1000) + (p.Y - 1000) * (p.Y - 1000) <= 50 * 50 };
|
||||
var me = V(1040, 1000);
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
var d = h.Tick(T0, me, true, Sorted(C(1, 1060, 1000, me), C(2, 1000, 1030, me)), nav.Path);
|
||||
Check.Eq(d.TargetId, 2, "the one 60 yd from the middle is outside the fence (20 yd off); the one inside is walked to");
|
||||
var h2 = new OutdoorHunt { RangeYd = 100, Fence = p => (p.X - 1000) * (p.X - 1000) + (p.Y - 1000) * (p.Y - 1000) <= 50 * 50 };
|
||||
var h2 = new OutdoorHunt { Roam = false, RangeYd = 100, Fence = p => (p.X - 1000) * (p.X - 1000) + (p.Y - 1000) * (p.Y - 1000) <= 50 * 50 };
|
||||
h2.Start(T0, me);
|
||||
var d2 = h2.Tick(T0, me, true, Sorted(C(1, 1060, 1000, me), C(3, 1090, 1000, me)), nav.Path);
|
||||
Check.Eq(d2.TargetId, 0, "every monster outside it: no pick");
|
||||
|
|
@ -796,7 +800,7 @@ internal static class OutdoorHuntTests
|
|||
private static void WaitsWhereItIs()
|
||||
{
|
||||
var start = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RadiusYd = 100 };
|
||||
var h = new OutdoorHunt { RadiusYd = 100, Roam = false }; // roaming off: waits (RoamTests for on)
|
||||
h.Start(T0, start);
|
||||
var nav = new Nav();
|
||||
var me = V(1060, 1000);
|
||||
|
|
@ -813,6 +817,126 @@ internal static class OutdoorHuntTests
|
|||
Check.Eq(new OutdoorHunt().RadiusYd, 0.0, "Hunt Radius defaults to 0 (anywhere)");
|
||||
}
|
||||
|
||||
// ── Roaming (2026-12-01, report R-20261127-181056-32e4: "would be ideal to map out the area and continue
|
||||
// running around the place for more mobs not just stop when it cant see any"; it should move around
|
||||
// the Hunt Radius) ──
|
||||
|
||||
/// <summary>Ticks the hunt with no monsters, walking each walk to its end; the walks' ends, in order.</summary>
|
||||
private static List<OutdoorHunt.Vec> RoamAll(OutdoorHunt h, Nav nav, ref OutdoorHunt.Vec me, ref DateTime t, int maxWalks = 200)
|
||||
{
|
||||
var ends = new List<OutdoorHunt.Vec>();
|
||||
bool done = true;
|
||||
for (int i = 0; i < maxWalks * 3 && ends.Count < maxWalks; i++)
|
||||
{
|
||||
t = t.AddSeconds(1.1);
|
||||
var d = h.Tick(t, me, done, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
if (d.Act == OutdoorHunt.Act.Walk && d.Corners != null)
|
||||
{
|
||||
me = d.Corners[^1];
|
||||
ends.Add(me);
|
||||
done = true; // the next tick: arrived
|
||||
}
|
||||
else if (d.Act == OutdoorHunt.Act.Idle) break;
|
||||
}
|
||||
return ends;
|
||||
}
|
||||
|
||||
private static void RoamWalks()
|
||||
{
|
||||
var start = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RadiusYd = 100 };
|
||||
h.Start(T0, start);
|
||||
var nav = new Nav();
|
||||
var d = h.Tick(T0, start, true, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Walk, "nothing in range: it walks on");
|
||||
Check.True(h.Roaming && d.TargetId == 0, "roaming, no monster target");
|
||||
Check.True(h.Note.Contains("roaming to"), "says so: " + h.Note);
|
||||
Check.True(d.Corners![^1].FlatDistanceTo(start) <= h.RoamCellYd * 1.5, "to a part right next to the start (nearest first)");
|
||||
int calls = nav.Calls;
|
||||
d = h.Tick(T0.AddSeconds(0.4), start, false, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.None, "on the way: keeps walking (not stopped between picks)");
|
||||
d = h.Tick(T0.AddSeconds(1.5), start, false, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.None, "a pick with still nothing in range: keeps walking, no new walk");
|
||||
Check.Eq(nav.Calls, calls, "no path asked for while on the way");
|
||||
var me = V(1010, 990);
|
||||
d = h.Tick(T0.AddSeconds(3), me, false, Sorted(C(7, 1040, 990, me)), nav.Path);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.TargetId == 7, $"a monster comes in range: hunted ({d.Act} {d.TargetId})");
|
||||
Check.False(h.Roaming, "the roam is over");
|
||||
Check.True(h.PendingNotes.Any(n => n.Contains("the roam ends")), "said so");
|
||||
}
|
||||
|
||||
private static void RoamCoversArea()
|
||||
{
|
||||
var start = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RadiusYd = 100 };
|
||||
h.Start(T0, start);
|
||||
var nav = new Nav();
|
||||
var me = start;
|
||||
var t = T0;
|
||||
var ends = RoamAll(h, nav, ref me, ref t);
|
||||
Check.True(ends.Count >= 10, $"it walks round the area ({ends.Count} walks)");
|
||||
Check.True(ends.All(e => e.FlatDistanceTo(start) <= h.RadiusYd), "never outside Hunt Radius");
|
||||
var seen = new HashSet<(int, int)>(ends.Select(e => h.RoamSquareOf(e)));
|
||||
seen.Add(h.RoamSquareOf(start));
|
||||
Check.Eq(h.RoamSquaresToSee(t, me).Count, 0, "every part of the area seen");
|
||||
Check.True(h.Note.Contains("whole area") && h.Note.Contains("waiting here"), "then waits, and says why: " + h.Note);
|
||||
var d = h.Tick(t.AddSeconds(2), me, true, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Idle, "all seen lately: stands");
|
||||
t = t.AddSeconds(h.RoamRevisitSec + 5);
|
||||
d = h.Tick(t, me, true, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Walk, "5 min on: it looks round again (respawns)");
|
||||
}
|
||||
|
||||
private static void RoamUnreachable()
|
||||
{
|
||||
var start = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RadiusYd = 60 };
|
||||
h.Start(T0, start);
|
||||
var nav = new Nav();
|
||||
// The nearest part's centre: a wall in the way, every walk to it ends 30 yd short.
|
||||
var first = h.RoamSquaresToSee(T0, start)[0];
|
||||
var goal = h.RoamSquareCentre(first, start.Z + 30);
|
||||
nav.Walls[(goal.X, goal.Y)] = (V(goal.X - 30, goal.Y), 30);
|
||||
var d = h.Tick(T0, start, true, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Walk, "it still roams");
|
||||
Check.True(h.RoamSquareOf(d.Corners![^1]) != first, "but not to the part no walk gets to");
|
||||
Check.False(h.RoamSquaresToSee(T0, start).Contains(first), "that part is left out");
|
||||
|
||||
// A walk that stops short (blocked on the way): its part is left out too.
|
||||
var target = d.Corners[^1];
|
||||
var sq = h.RoamSquareOf(target);
|
||||
var shortOf = V(start.X + (target.X - start.X) * 0.1, start.Y + (target.Y - start.Y) * 0.1);
|
||||
d = h.Tick(T0.AddSeconds(1.2), shortOf, true, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.True(h.PendingNotes.Any(n => n.Contains("stopped") && n.Contains("left out")), "said: " + string.Join(" | ", h.PendingNotes));
|
||||
Check.False(h.RoamSquaresToSee(T0.AddSeconds(1.2), shortOf).Contains(sq), "the part it couldn't get to is left out");
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Walk, "and it goes on to another part");
|
||||
}
|
||||
|
||||
private static void RoamFenceAndDefaults()
|
||||
{
|
||||
var start = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RadiusYd = 200, Fence = p => p.X >= 1000 }; // only the east half
|
||||
h.Start(T0, start);
|
||||
var nav = new Nav();
|
||||
var me = start;
|
||||
var t = T0;
|
||||
var ends = RoamAll(h, nav, ref me, ref t);
|
||||
Check.True(ends.Count > 0 && ends.All(e => e.X >= 1000 - h.RoamCellYd * 0.5), "only inside the fence");
|
||||
|
||||
var any = new OutdoorHunt { RadiusYd = 0, RangeYd = 150 };
|
||||
any.Start(T0, start);
|
||||
Check.Eq(any.RoamRadiusYd, 150.0, "Hunt Radius anywhere: it roams Hunt Range round the start");
|
||||
me = start; t = T0;
|
||||
ends = RoamAll(any, new Nav(), ref me, ref t);
|
||||
Check.True(ends.Count > 0 && ends.All(e => e.FlatDistanceTo(start) <= 150), "and never farther");
|
||||
|
||||
var big = new OutdoorHunt { RadiusYd = 2000 };
|
||||
Check.True(big.RoamCellYd > big.RoamCellMinYd, $"a big area has bigger parts ({big.RoamCellYd:0} yd), not thousands of them");
|
||||
|
||||
Check.True(new OutdoorHunt().Roam, "roaming is on by default");
|
||||
Check.True(new LegacyUiSettings().OutdoorHuntRoam, "and so is the setting");
|
||||
}
|
||||
|
||||
// Tom 10-23: "/mt opt set" gave no answer, and "/ra hunt status" toggled the hunt (the command read
|
||||
// the word "hunt" as its argument). The /ra hunt settings answer, and status/stop don't start it.
|
||||
private static void Commands()
|
||||
|
|
|
|||
|
|
@ -18,8 +18,10 @@ namespace RynthCore.RynthAiHostTests.Tests;
|
|||
// idle moments. With it on and the bot idle (no fight target, no monster within Monster Range, no
|
||||
// corpse to loot, no salvage), a rebuff starts once a buff has Rebuff With + the margin (default 2
|
||||
// minutes) left. The regular rebuff is unchanged; an early top-off never starts in a fight and stops
|
||||
// when one begins; margin 0 adds nothing. Since 2026-11-20 no buff cast starts in a fight at all (the
|
||||
// owner: "clear the mobs nearby before we rebuff"), except a Force Buff the player asked for.
|
||||
// when one begins; margin 0 adds nothing. 2026-11-20 to 2026-12-01 no buff cast started in a fight at all.
|
||||
// 2026-12-01: once under the set timer, the rebuff starts regardless, and the idle timer is higher and for
|
||||
// quiet moments: when a monster comes, the fight goes on until a buff reaches the regular timer. So at or under Rebuff With (or dispelled) a buff goes now, fight or not; only health under
|
||||
// Heal At in a fight holds it back.
|
||||
internal static class RebuffWhenIdleTests
|
||||
{
|
||||
private const uint Player = 0x50000F01;
|
||||
|
|
@ -31,9 +33,10 @@ internal static class RebuffWhenIdleTests
|
|||
{
|
||||
r.Add("rebuff when idle: idle, a buff inside Rebuff With + the margin is rebuffed early", IdleInsideMarginRebuffed);
|
||||
r.Add("rebuff when idle: in a fight, a buff inside the margin but over Rebuff With is not rebuffed", FightInsideMarginWaits);
|
||||
r.Add("rebuff when idle: in a fight, a buff at or under Rebuff With (or dispelled) waits for the fight's end, then is rebuffed (2026-11-20)", FightRegularRebuff);
|
||||
r.Add("rebuff: a fight that never ends (constant respawn): after 2 min of waiting a full pass goes in it, never under Heal At (R-20261125-130039-e3bc)", FightThatNeverEnds);
|
||||
r.Add("rebuff when idle: a rebuff run under way when a monster comes: the cast sent resolves, the rest waits for the fight's end", RunPausesForFight);
|
||||
r.Add("rebuff (2026-12-01): in a fight, a buff at or under Rebuff With (or dispelled) is rebuffed right away", FightRegularRebuff);
|
||||
r.Add("rebuff: a fight that never ends (constant respawn): rebuffed at Rebuff With at once, never under Heal At (R-20261125-130039-e3bc)", FightThatNeverEnds);
|
||||
r.Add("rebuff (2026-12-01): a regular rebuff run under way when a monster comes carries on in the fight", RunGoesOnInFight);
|
||||
r.Add("rebuff (2026-12-01): Recast dispelled buffs in a fight off: a dispelled buff waits for the fight's end, a buff at Rebuff With still goes and takes it along; the setting is saved, loaded, bridged, mapped", DispelOption);
|
||||
r.Add("rabuffsdue[seconds]: how many buffs a rebuff with that line would cast (a dispelled one too); -1 with buffing off or no buff manager; asking casts nothing", BuffsDueCount);
|
||||
r.Add("rebuff when idle: margin 0, or the option off, adds nothing", MarginZeroAddsNothing);
|
||||
r.Add("rebuff when idle: an early top-off under way stops when a fight starts (the cast sent resolves); the regular rules take over", EarlyRunStopsForFight);
|
||||
|
|
@ -185,21 +188,32 @@ internal static class RebuffWhenIdleTests
|
|||
Check.Eq(Show(rig.Beats(5)), Strength, "the fight over: topped off then");
|
||||
}
|
||||
|
||||
// 2026-11-20 (Thread 0x5C47: two buffs dispelled mid-fight, recast with a Rager on him, dead 4 s later): "clear
|
||||
// the mobs nearby before we rebuff". Due in a fight, a buff waits for the fight's end, then goes.
|
||||
// 2026-12-01: once under the set timer, the rebuff starts regardless. (2026-11-20 to 12-01 it waited for the fight's end.)
|
||||
private static void FightRegularRebuff()
|
||||
{
|
||||
var low = new Rig(rebuffWhenIdle: true) { Idle = false };
|
||||
low.Live((Strength, 290), (Willpower, 3000)); // under Rebuff With 300
|
||||
Check.True(low.B.NeedsAnyBuff(), "290 s left: due, fight or not");
|
||||
Check.Eq(low.Arbiter(), BotActivity.Combat, "in a fight combat keeps the tick");
|
||||
Check.Eq(Show(low.Beats(5)), "(none)", "nothing cast in the fight");
|
||||
Check.Eq(low.Logged("[Buff] buffs wait: a fight; they go on once the fight is over"), 1, "the wait is logged once");
|
||||
low.Idle = true;
|
||||
Check.Eq(low.Arbiter(), BotActivity.Buffing, "the fight over: buffing has it");
|
||||
Check.Eq(Show(low.Beats(5)), Strength, "and rebuffs");
|
||||
Check.Eq(low.Logged("[Buff] buffs go on: the fight is over"), 1, "the end is logged");
|
||||
Check.False(low.B.BuffsWaitForFight(), "nothing holds it in the fight");
|
||||
Check.Eq(low.Arbiter(), BotActivity.Buffing, "buffing takes the tick in the fight");
|
||||
Check.Eq(Show(low.Beats(5)), Strength, "rebuffed in the fight (Willpower, 3000 s left, left alone)");
|
||||
Check.Eq(low.Logged("[Buff] rebuffing in the fight (a fight): a buff is at or under Rebuff With (300 s)"), 1, "logged once");
|
||||
Check.Eq(low.Logged("[Buff] buffs wait"), 0, "no wait");
|
||||
Check.Eq(low.B.IdleTopOffRuns, 0, "a regular run, not an early top-off");
|
||||
Check.Eq(low.Arbiter(), BotActivity.Combat, "then combat has it");
|
||||
|
||||
// 2026-12-01: when one buff reaches the timer, everything with under 20 minutes left is rebuffed too, so
|
||||
// it isn't forever switching to a wand: the run takes every buff under Also Refresh Under
|
||||
// (RebuffTopOffSecondsRemaining, default 1200 s), in a fight too.
|
||||
Check.Eq(low.S.RebuffTopOffSecondsRemaining, 1200, "Also Refresh Under defaults to 20 minutes");
|
||||
var batch = new Rig(rebuffWhenIdle: false) { Idle = false };
|
||||
batch.Live((Strength, 290), (Willpower, 1100)); // Willpower: over Rebuff With, under 20 minutes
|
||||
var both = batch.Beats(6);
|
||||
Check.True(both.Contains(Strength) && both.Contains(Willpower), "in a fight, one buff at Rebuff With takes the one under 20 minutes along: " + Show(both));
|
||||
Check.Eq(Show(batch.Beats(5)), "(none)", "then nothing more");
|
||||
var single = new Rig(rebuffWhenIdle: false) { Idle = false };
|
||||
single.Live((Strength, 290), (Willpower, 1300)); // Willpower: over 20 minutes
|
||||
Check.Eq(Show(single.Beats(6)), Strength, "a buff with over 20 minutes left is left alone");
|
||||
|
||||
var dispel = new Rig(rebuffWhenIdle: true);
|
||||
dispel.Live((Strength, 3000), (Willpower, 3000));
|
||||
|
|
@ -207,25 +221,34 @@ internal static class RebuffWhenIdleTests
|
|||
dispel.Idle = false;
|
||||
dispel.Dispel(Strength);
|
||||
Check.True(dispel.B.NeedsAnyBuff(), "a buff dispelled mid-fight is due");
|
||||
Check.Eq(dispel.Arbiter(), BotActivity.Combat, "but combat keeps the tick");
|
||||
Check.Eq(Show(dispel.Beats(5)), "(none)", "not recast while the fight goes on");
|
||||
dispel.Idle = true;
|
||||
Check.Eq(Show(dispel.Beats(5)), Strength, "recast once the monsters nearby are dead");
|
||||
Check.Eq(dispel.Arbiter(), BotActivity.Buffing, "and goes in the fight");
|
||||
Check.Eq(Show(dispel.Beats(5)), Strength, "recast right away");
|
||||
|
||||
var off = new Rig(rebuffWhenIdle: false) { Idle = false };
|
||||
off.Live((Strength, 290), (Willpower, 3000));
|
||||
Check.Eq(Show(off.Beats(5)), "(none)", "the same with the option off: nothing in the fight");
|
||||
off.Idle = true;
|
||||
Check.Eq(Show(off.Beats(5)), Strength, "then rebuffed");
|
||||
Check.Eq(Show(off.Beats(5)), Strength, "the same with the option off");
|
||||
|
||||
// Fighting with every buff up isn't a wait: nothing is logged.
|
||||
// Under Heal At in the fight: the heals first, the buff once health is back over it.
|
||||
var hurt = new Rig(rebuffWhenIdle: false) { Idle = false };
|
||||
hurt.S.HealAt = 60;
|
||||
hurt.Live((Strength, 290), (Willpower, 3000));
|
||||
SetHealth(hurt, 50);
|
||||
Check.True(hurt.B.BuffsWaitForFight(), "50% under Heal At 60% in a fight: it waits");
|
||||
Check.Eq(Show(hurt.Beats(5)), "(none)", "nothing cast");
|
||||
Check.Eq(hurt.Logged("[Buff] buffs wait: a fight, health 50% under Heal At 60%"), 1, "the wait is logged once");
|
||||
SetHealth(hurt, 90);
|
||||
Check.Eq(Show(hurt.Beats(5)), Strength, "back over Heal At, the fight still on: rebuffed");
|
||||
Check.Eq(hurt.Logged("[Buff] buffs go on: health 90%, back over Heal At"), 1, "the end is logged");
|
||||
|
||||
// Fighting with every buff up: nothing is logged.
|
||||
var up = new Rig(rebuffWhenIdle: false) { Idle = false };
|
||||
up.Live((Strength, 3000), (Willpower, 3000));
|
||||
up.Beats(5);
|
||||
Check.Eq(up.Logged("[Buff] buffs wait"), 0, "no wait logged with nothing due");
|
||||
Check.Eq(up.Logged("[Buff] buffs wait") + up.Logged("[Buff] rebuffing in the fight"), 0, "nothing logged with nothing due");
|
||||
}
|
||||
|
||||
// Conquest, constant respawn, Monster Range 10: buffs waited almost 7 hours, ran out, and the character died.
|
||||
// Conquest, constant respawn, Monster Range 10: buffs waited almost 7 hours for the fight's end, ran out, and the
|
||||
// character died. Now nothing waits for the fight's end at all.
|
||||
private static void FightThatNeverEnds()
|
||||
{
|
||||
var rig = new Rig(rebuffWhenIdle: false) { Idle = false };
|
||||
|
|
@ -235,23 +258,17 @@ internal static class RebuffWhenIdleTests
|
|||
rig.Live((Strength, 2900), (Willpower, 3000));
|
||||
rig.Beats(2);
|
||||
rig.Live((Strength, 290), (Willpower, 3000));
|
||||
Check.Eq(Show(rig.Beats(110)), "(none)", "110 s of an unbroken fight: Strength (290 s left) still waits");
|
||||
Check.Eq(rig.Logged("[Buff] buffs wait: a fight"), 1, "the wait is logged once");
|
||||
Check.Eq(rig.Arbiter(), BotActivity.Combat, "combat keeps the tick meanwhile");
|
||||
Check.Eq(Show(rig.Beats(20)), Strength, "past 2 min: the pass goes in the fight and Strength is rebuffed");
|
||||
Check.Eq(rig.Logged("for a fight that doesn't end"), 1, "the pass is logged");
|
||||
Check.Eq(Show(rig.Beats(10)), "(none)", "nothing more to cast");
|
||||
Check.Eq(rig.Logged("the rebuff pass in the fight is done (nothing left to cast)"), 1, "its end is logged");
|
||||
Check.Eq(Show(rig.Beats(5)), Strength, "an unbroken fight: Strength (290 s left) is rebuffed at once");
|
||||
Check.Eq(Show(rig.Beats(120)), "(none)", "nothing more to cast");
|
||||
|
||||
// Under Heal At the pass never starts.
|
||||
// Under Heal At it never goes.
|
||||
var hurt = new Rig(rebuffWhenIdle: false) { Idle = false };
|
||||
RynthClock.TestNow = () => hurt.Now;
|
||||
hurt.S.HealAt = 50;
|
||||
hurt.Live((Strength, 2900), (Willpower, 3000));
|
||||
hurt.Beats(2);
|
||||
hurt.Live((Strength, 290), (Willpower, 3000));
|
||||
var v = (PlayerVitalsCache)typeof(BuffManager).GetField("_vitals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(hurt.B)!;
|
||||
v.CurrentHealth = 30;
|
||||
SetHealth(hurt, 30);
|
||||
Check.Eq(Show(hurt.Beats(150)), "(none)", "health 30% under Heal At 50%: no buff cast however long the fight");
|
||||
}
|
||||
finally { RynthClock.TestNow = null; }
|
||||
|
|
@ -279,22 +296,77 @@ internal static class RebuffWhenIdleTests
|
|||
Check.Eq(m.Expressions.Evaluate("rabuffsdue[1200]"), "-1", "buffing off: -1");
|
||||
}
|
||||
|
||||
// A rebuff run under way when a monster comes: the cast in flight resolves, the next waits for the fight's end.
|
||||
private static void RunPausesForFight()
|
||||
// A regular rebuff run under way when a monster comes: it carries on (2026-12-01; it used to wait for the fight's end).
|
||||
private static void RunGoesOnInFight()
|
||||
{
|
||||
var rig = new Rig(rebuffWhenIdle: false);
|
||||
rig.Live((Strength, 200), (Willpower, 250)); // both under Rebuff With: one run
|
||||
string first = rig.Beat(answer: false);
|
||||
Check.True(first == Strength || first == Willpower, $"the run starts ('{first}', hold: {rig.B.LastBuffSkipReason})");
|
||||
rig.Idle = false; // a monster comes
|
||||
Check.Eq(rig.Arbiter(), BotActivity.Buffing, "the cast in flight keeps the slot until it resolves");
|
||||
rig.Answer(first);
|
||||
Check.Eq(rig.Arbiter(), BotActivity.Combat, "then combat has it");
|
||||
Check.Eq(Show(rig.Beats(10)), "(none)", "nothing more is cast in the fight");
|
||||
Check.True(rig.Running, "the run is held, not ended");
|
||||
Check.Eq(rig.Arbiter(), BotActivity.Buffing, "the run keeps the tick in the fight");
|
||||
Check.Eq(Show(rig.Beats(5)), first == Strength ? Willpower : Strength, "and finishes");
|
||||
Check.False(rig.Running, "then ends");
|
||||
Check.Eq(rig.Arbiter(), BotActivity.Combat, "combat has it");
|
||||
}
|
||||
|
||||
// 2026-12-01: recasting dispelled buffs mid-fight is an option.
|
||||
private static void DispelOption()
|
||||
{
|
||||
var rig = new Rig(rebuffWhenIdle: false);
|
||||
Check.True(rig.S.RecastDispelledInFight, "on by default");
|
||||
rig.S.RecastDispelledInFight = false;
|
||||
rig.Live((Strength, 3000), (Willpower, 3000));
|
||||
rig.Beats(2);
|
||||
rig.Idle = false;
|
||||
rig.Dispel(Strength);
|
||||
Check.True(rig.B.NeedsAnyBuff(), "dispelled: due");
|
||||
Check.True(rig.B.BuffsWaitForFight(), "option off: it waits in the fight");
|
||||
Check.Eq(rig.Arbiter(), BotActivity.Combat, "combat keeps the tick");
|
||||
Check.Eq(Show(rig.Beats(5)), "(none)", "not recast in the fight");
|
||||
Check.Eq(rig.Logged("a dispelled buff waits for the fight's end"), 1, "the wait is logged once");
|
||||
rig.Idle = true;
|
||||
Check.Eq(Show(rig.Beats(5)), first == Strength ? Willpower : Strength, "the fight over: the run carries on");
|
||||
Check.False(rig.Running, "and ends");
|
||||
Check.Eq(Show(rig.Beats(5)), Strength, "the fight over: recast");
|
||||
|
||||
// A buff at Rebuff With still goes in the fight, and the run takes the dispelled one along.
|
||||
var both = new Rig(rebuffWhenIdle: false);
|
||||
both.S.RecastDispelledInFight = false;
|
||||
both.Live((Strength, 3000), (Willpower, 3000));
|
||||
both.Beats(2);
|
||||
both.Idle = false;
|
||||
both.Dispel(Strength);
|
||||
both.Beats(3);
|
||||
both.Live((Willpower, 290));
|
||||
var sent = both.Beats(6);
|
||||
Check.True(sent.Contains(Willpower) && sent.Contains(Strength), "Willpower at Rebuff With goes in the fight, Strength with it: " + Show(sent));
|
||||
|
||||
// Option on (the default): recast in the fight.
|
||||
var on = new Rig(rebuffWhenIdle: false);
|
||||
on.Live((Strength, 3000), (Willpower, 3000));
|
||||
on.Beats(2);
|
||||
on.Idle = false;
|
||||
on.Dispel(Strength);
|
||||
Check.Eq(Show(on.Beats(5)), Strength, "option on: recast in the fight");
|
||||
|
||||
// Saved, loaded, bridged, in the settings map.
|
||||
var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true,\"RebuffSecondsRemaining\":300}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(old != null && old.RecastDispelledInFight, "a profile saved before the setting: on");
|
||||
var off = JsonSerializer.Deserialize(
|
||||
JsonSerializer.Serialize(new LegacyUiSettings { RecastDispelledInFight = false }, RynthAiJsonContext.Default.LegacyUiSettings),
|
||||
RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(off != null && !off.RecastDispelledInFight, "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 { RecastDispelledInFight = false }, dst });
|
||||
Check.False(dst.RecastDispelledInFight, "a profile with it off loads off");
|
||||
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(payload != null && payload.RecastDispelledInFight == null, "an older engine's payload has no value (left alone)");
|
||||
var live = new LegacyUiSettings();
|
||||
var map = ExpressionTests.Engine(settings: live).BuildSettingsMapPublic();
|
||||
Check.True(map.TryGetValue("RecastDispelledInFight", out var entry), "in the settings map");
|
||||
entry.Set("0");
|
||||
Check.False(live.RecastDispelledInFight, "and sets off");
|
||||
}
|
||||
|
||||
private static void MarginZeroAddsNothing()
|
||||
|
|
@ -334,13 +406,14 @@ internal static class RebuffWhenIdleTests
|
|||
Check.Eq(Show(rig.Beats(10)), "(none)", "nothing more is cast in the fight");
|
||||
Check.Eq(rig.Logged("the early top-off stops"), 1, "logged once");
|
||||
|
||||
// The regular rules take over: the other buff dropping under Rebuff With waits for the fight's end (2026-11-20).
|
||||
// The regular rules take over: the other buff, still over Rebuff With, waits; once it drops under, it goes in
|
||||
// the fight (2026-12-01: the fight goes on until a buff reaches the regular timer).
|
||||
string other = first == Strength ? Willpower : Strength;
|
||||
rig.Live((first, 2700), (other, 350));
|
||||
Check.Eq(Show(rig.Beats(5)), "(none)", "350 s left in the fight, over Rebuff With 300: it waits");
|
||||
rig.Live((first, 2700), (other, 290));
|
||||
Check.Eq(Show(rig.Beats(5)), "(none)", "under Rebuff With in the fight: it waits");
|
||||
rig.Idle = true;
|
||||
Check.Eq(Show(rig.Beats(5)), other, "the fight over: rebuffed as usual");
|
||||
rig.Idle = false;
|
||||
Check.Eq(Show(rig.Beats(5)), other, "under Rebuff With: rebuffed in the fight");
|
||||
Check.Eq(rig.B.IdleTopOffRuns, 1, "that was a regular run");
|
||||
|
||||
// And an early run interrupted with the other buff still inside the margin finishes when idle again.
|
||||
var again = new Rig(rebuffWhenIdle: true);
|
||||
|
|
|
|||
291
Tools/RynthCore.RynthAiHostTests/Tests/UbInventoryTests.cs
Normal file
291
Tools/RynthCore.RynthAiHostTests/Tests/UbInventoryTests.cs
Normal file
|
|
@ -0,0 +1,291 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Loot.VTank;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// /ub equip list|load|test|create and /ub autosalvage [force] (2026-12-01 command audit): equip went on
|
||||
// to /mt equip ("Item not found: load ...") so a meta's armor or weapon swap did nothing; autosalvage
|
||||
// was accepted and ignored. Both judge the carried items by a loot profile's rules.
|
||||
internal static class UbInventoryTests
|
||||
{
|
||||
private const uint Player = 0x50000F71;
|
||||
private const uint WornRobe = 0x80287101, HelmA = 0x80287102, HelmB = 0x80287103;
|
||||
private const uint Ring1 = 0x80287104, Ring2 = 0x80287105, Ring3 = 0x80287106;
|
||||
private const uint Sword = 0x80287107, Bow = 0x80287108, Junk = 0x80287109;
|
||||
private const uint Scrap1 = 0x8028710A, Tinked = 0x8028710B, Imbued = 0x8028710C, Unknown = 0x8028710D, WornScrap = 0x8028710E;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("ub equip: the plan puts one item in each slot (two rings, one weapon) and keeps what is worn", PlanSlots);
|
||||
r.Add("ub equip: load wields the profile's carried items one at a time, never a worn one; test only says", LoadAndTest);
|
||||
r.Add("ub equip: create writes the worn items as a profile, never over a file; list names it", CreateAndList);
|
||||
r.Add("ub equip: '/ub equip <item name>' still wields that item (the /mt equip it was)", ByNameStillWorks);
|
||||
r.Add("ub autosalvage: lists without force; force queues the Salvage items, never worn, tinkered or imbued", AutoSalvage);
|
||||
r.Add("ub count profile: counts against the named profile without making it the one looting uses", CountProfileKeepsLootProfile);
|
||||
r.Add("ub autosalvage: an item its rule needs identified is identified first", AutoSalvageWaitsForId);
|
||||
}
|
||||
|
||||
private static string Folder => Path.Combine(Program.TempRoot, "UbEquip");
|
||||
|
||||
private sealed class World
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new();
|
||||
public long Now = 1_000_000;
|
||||
public readonly WorldObjectCache Cache;
|
||||
|
||||
public World(params (uint Id, string Name, int Slots, uint WornAt)[] items)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true; // UseObject, and GetObjectWielderInfo answering from Wielded
|
||||
FakeHost.WeaponCalls = true; // RequestId and HasAppraisalData
|
||||
FakeHost.Names[Player] = "Equipper";
|
||||
FakeHost.PlayerIdValue = Player;
|
||||
foreach (var (id, name, slots, wornAt) in items)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Containers[id] = Player;
|
||||
FakeHost.ItemTypes[id] = slots != 0 ? 0x2u : 0x1u;
|
||||
if (slots != 0) FakeHost.Ints[(id, 9)] = slots; // ValidLocations
|
||||
if (wornAt != 0) FakeHost.Wielded[id] = wornAt;
|
||||
FakeHost.Appraised.Add(id);
|
||||
}
|
||||
var host = FakeHost.Create(playerId: Player);
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_initialized", true);
|
||||
Set("_loginComplete", true);
|
||||
Set("_salvageManager", new RynthCore.Plugin.RynthAi.Loot.SalvageManager(host, S, Cache));
|
||||
foreach (var it in items) Cache.OnCreateObject(it.Id);
|
||||
Cache.Tick();
|
||||
P.UbInvClock = () => Now;
|
||||
RynthAiPlugin.UbEquipFolder = Folder;
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public object? Get(string f) => typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P);
|
||||
public bool Ub(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleUbCommand", Any)!.Invoke(P, new object[] { line })!;
|
||||
public void Tick(long advanceMs)
|
||||
{
|
||||
Now += advanceMs;
|
||||
typeof(RynthAiPlugin).GetMethod("TickUbInventoryJobs", Any)!.Invoke(P, null);
|
||||
}
|
||||
public bool ChatHas(string text) => FakeHost.Chat.Any(c => c.Contains(text, StringComparison.OrdinalIgnoreCase));
|
||||
public int SalvageQueued => ((RynthCore.Plugin.RynthAi.Loot.SalvageManager)Get("_salvageManager")!).GetStateSnapshot().QueueCount;
|
||||
}
|
||||
|
||||
private static VTankLootRule Rule(string name, VTankLootAction action, params VTankLootCondition[] conds)
|
||||
{
|
||||
var r = new VTankLootRule { Name = name, Action = action, CustomExpression = string.Empty };
|
||||
r.Conditions.AddRange(conds);
|
||||
return r;
|
||||
}
|
||||
|
||||
private static VTankLootCondition NameIs(string pattern) => new(VTankNodeTypes.StringValueMatch, "0", new[] { pattern, "1" });
|
||||
|
||||
private static string WriteProfile(string fileName, params VTankLootRule[] rules)
|
||||
{
|
||||
Directory.CreateDirectory(Folder);
|
||||
var p = new VTankLootProfile();
|
||||
p.Rules.AddRange(rules);
|
||||
string path = Path.Combine(Folder, fileName);
|
||||
VTankLootWriter.Save(p, path);
|
||||
return path;
|
||||
}
|
||||
|
||||
private static void PlanSlots()
|
||||
{
|
||||
const int Head = 0x1, Fingers = 0x000C0000;
|
||||
var plan = UbEquipPlan.Plan(new[]
|
||||
{
|
||||
new UbEquipPlan.Item(1, "Helm A", Head, false, 0, 0),
|
||||
new UbEquipPlan.Item(2, "Helm B", Head, false, 0, 1),
|
||||
new UbEquipPlan.Item(3, "Ring 1", Fingers, false, 0, 2),
|
||||
new UbEquipPlan.Item(4, "Ring 2", Fingers, false, 0, 3),
|
||||
new UbEquipPlan.Item(5, "Ring 3", Fingers, false, 0, 4),
|
||||
new UbEquipPlan.Item(6, "Sword", UbEquipPlan.MeleeWeapon, false, 0, 5),
|
||||
new UbEquipPlan.Item(7, "Bow", UbEquipPlan.MissileWeapon, false, 0, 6),
|
||||
new UbEquipPlan.Item(8, "Robe", 0x2, true, 0x2, 7),
|
||||
new UbEquipPlan.Item(9, "Coat", 0x2, false, 0, 8),
|
||||
new UbEquipPlan.Item(10, "Pea", 0, false, 0, 9),
|
||||
});
|
||||
Check.Eq(string.Join(",", plan.Equip.Select(i => i.Name)), "Helm A,Ring 1,Ring 2,Sword", "first helm, two rings, one weapon");
|
||||
Check.Eq(string.Join(",", plan.AlreadyWorn.Select(i => i.Name)), "Robe", "the worn robe stays");
|
||||
Check.Eq(string.Join(",", plan.Skipped.Select(s => s.Item.Name)), "Helm B,Ring 3,Bow,Coat,Pea", "the rest is left out");
|
||||
|
||||
// A worn ring keeps its finger: one more ring fits, not two.
|
||||
var rings = UbEquipPlan.Plan(new[]
|
||||
{
|
||||
new UbEquipPlan.Item(1, "Worn Ring", Fingers, true, 0x00040000, 0),
|
||||
new UbEquipPlan.Item(2, "Ring 2", Fingers, false, 0, 1),
|
||||
new UbEquipPlan.Item(3, "Ring 3", Fingers, false, 0, 2),
|
||||
});
|
||||
Check.Eq(rings.Equip.Count, 1, "one free finger");
|
||||
// Worn with its slot unknown: kept, and it takes no slot by guess.
|
||||
var unknown = UbEquipPlan.Plan(new[]
|
||||
{
|
||||
new UbEquipPlan.Item(1, "Worn Thing", Head, true, 0, 0),
|
||||
new UbEquipPlan.Item(2, "Helm", Head, false, 0, 1),
|
||||
});
|
||||
Check.True(unknown.AlreadyWorn.Count == 1 && unknown.Equip.Count == 1, "worn with no known slot: kept, nothing blocked");
|
||||
}
|
||||
|
||||
private static World EquipWorld() => new(
|
||||
(WornRobe, "Faran Robe", 0x2, 0x2),
|
||||
(HelmA, "Helm of A", 0x1, 0),
|
||||
(HelmB, "Helm of B", 0x1, 0),
|
||||
(Ring1, "Ring", 0x000C0000, 0),
|
||||
(Ring2, "Ring", 0x000C0000, 0),
|
||||
(Ring3, "Ring", 0x000C0000, 0),
|
||||
(Sword, "Sword", UbEquipPlan.MeleeWeapon, 0),
|
||||
(Bow, "Bow", UbEquipPlan.MissileWeapon, 0),
|
||||
(Junk, "Junk Hat", 0x1, 0));
|
||||
|
||||
private static void LoadAndTest()
|
||||
{
|
||||
WriteProfile("melee.utl",
|
||||
Rule("Robe", VTankLootAction.Keep, NameIs("^Faran Robe$")),
|
||||
Rule("Helm A", VTankLootAction.Keep, NameIs("^Helm of A$")),
|
||||
Rule("Helms", VTankLootAction.Keep, NameIs("^Helm of")),
|
||||
Rule("Rings", VTankLootAction.Keep, NameIs("^Ring$")),
|
||||
Rule("Sword", VTankLootAction.Keep, NameIs("^Sword$")),
|
||||
Rule("Bow", VTankLootAction.Keep, NameIs("^Bow$")),
|
||||
Rule("Junk", VTankLootAction.Sell, NameIs("^Junk")));
|
||||
|
||||
var w = EquipWorld();
|
||||
Check.True(w.Ub("/ub equip test melee"), "/ub equip test is handled");
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "test wields nothing");
|
||||
Check.True(w.ChatHas("would equip") && w.ChatHas("Helm of A") && w.ChatHas("already worn: Faran Robe"), "test says what would go on");
|
||||
|
||||
Check.True(w.Ub("/ub equip load melee.utl"), "/ub equip load is handled (a name with .utl)");
|
||||
Check.Eq(FakeHost.Uses.Count, 1, "the first wield goes at once");
|
||||
for (int i = 0; i < 10; i++) w.Tick(RynthAiPlugin.UbEquipSpacingMs);
|
||||
var used = FakeHost.Uses.ToList();
|
||||
Check.Eq(used.Count, 4, "helm, two rings, the sword: one item a slot");
|
||||
Check.True(used.Contains(HelmA) && !used.Contains(HelmB), "the helm of the first rule that takes one");
|
||||
Check.Eq(used.Count(u => u is Ring1 or Ring2 or Ring3), 2, "two rings of three");
|
||||
Check.True(used.Contains(Sword) && !used.Contains(Bow), "one weapon: the earlier rule's");
|
||||
Check.False(used.Contains(WornRobe), "the worn robe is never used (that would take it off)");
|
||||
Check.False(used.Contains(Junk), "a Sell rule's item isn't equipped");
|
||||
// Nothing went on in the fake: the check after the last wield says so.
|
||||
w.Tick(RynthAiPlugin.UbEquipSettleMs);
|
||||
Check.True(w.ChatHas("equipped 0 of 4"), "after the wields: how many went on");
|
||||
|
||||
Check.True(w.Ub("/ub equip load nosuchprofile"), "a missing profile is handled");
|
||||
Check.True(w.ChatHas("no profile 'nosuchprofile'"), "and said");
|
||||
Check.True(w.Ub("/ub equip load"), "no name: handled");
|
||||
Check.True(w.ChatHas("Usage: /ub equip"), "with the usage");
|
||||
}
|
||||
|
||||
private static void CreateAndList()
|
||||
{
|
||||
var w = EquipWorld();
|
||||
FakeHost.Wielded[HelmA] = 0x1;
|
||||
Check.True(w.Ub("/ub equip create mysuit"), "/ub equip create is handled");
|
||||
string path = Path.Combine(Folder, "mysuit.utl");
|
||||
Check.True(File.Exists(path), "mysuit.utl written in the equipment folder");
|
||||
VTankLootProfile p = VTankLootParser.Load(path);
|
||||
Check.Eq(p.Rules.Count, 2, "a rule for each worn item");
|
||||
Check.True(p.Rules.All(r => r.Action == VTankLootAction.Keep), "Keep rules");
|
||||
|
||||
// The profile made from the worn items takes them (and nothing else).
|
||||
FakeHost.Uses.Clear();
|
||||
FakeHost.Chat.Clear();
|
||||
Check.True(w.Ub("/ub equip test mysuit"), "test the new profile");
|
||||
Check.True(w.ChatHas("nothing to equip") && w.ChatHas("Faran Robe") && w.ChatHas("Helm of A"), "both already worn, nothing else");
|
||||
|
||||
DateTime before = File.GetLastWriteTimeUtc(path);
|
||||
Check.True(w.Ub("/ub equip create mysuit"), "again");
|
||||
Check.True(w.ChatHas("already exists"), "never over an existing file");
|
||||
Check.Eq(File.GetLastWriteTimeUtc(path), before, "the file is untouched");
|
||||
|
||||
FakeHost.Chat.Clear();
|
||||
Check.True(w.Ub("/ub equip list"), "/ub equip list");
|
||||
Check.True(w.ChatHas("mysuit.utl"), "lists it");
|
||||
}
|
||||
|
||||
private static void ByNameStillWorks()
|
||||
{
|
||||
var w = EquipWorld();
|
||||
Check.True(w.Ub("/ub equip Helm of B"), "/ub equip <item name> is handled");
|
||||
Check.True(FakeHost.Uses.Count == 1 && FakeHost.Uses[0] == HelmB, "it wields that item, as /mt equip did");
|
||||
}
|
||||
|
||||
private static World SalvageWorld() => new(
|
||||
(Scrap1, "Iron Scrap Sword", 0, 0),
|
||||
(Tinked, "Iron Tinked Sword", 0, 0),
|
||||
(Imbued, "Iron Imbued Sword", 0, 0),
|
||||
(WornScrap, "Iron Worn Sword", UbEquipPlan.MeleeWeapon, UbEquipPlan.MeleeWeapon),
|
||||
(Junk, "Junk Hat", 0x1, 0));
|
||||
|
||||
private static void AutoSalvage()
|
||||
{
|
||||
string path = WriteProfile("salv.utl",
|
||||
Rule("Iron", VTankLootAction.Salvage, NameIs("^Iron")),
|
||||
Rule("Junk", VTankLootAction.Sell, NameIs("^Junk")));
|
||||
var w = SalvageWorld();
|
||||
FakeHost.Ints[(Tinked, 171)] = 2; // NumTimesTinkered
|
||||
FakeHost.Ints[(Imbued, 179)] = 0x1; // ImbuedEffect
|
||||
Check.True(w.Ub("/ub autosalvage"), "no loot profile in use: handled");
|
||||
Check.True(w.ChatHas("no loot profile in use"), "and said");
|
||||
|
||||
w.S.CurrentLootPath = path;
|
||||
FakeHost.Chat.Clear();
|
||||
Check.True(w.Ub("/ub autosalvage"), "/ub autosalvage");
|
||||
Check.True(w.ChatHas("1 item(s) would be salvaged: Iron Scrap Sword"), "lists the one item it would salvage");
|
||||
Check.True(w.ChatHas("Iron Tinked Sword (tinkered)") && w.ChatHas("Iron Imbued Sword (imbued)"), "says why the others are left");
|
||||
Check.Eq(w.SalvageQueued, 0, "without force nothing is salvaged");
|
||||
|
||||
Check.True(w.Ub("/ub autosalvage force"), "/ub autosalvage force");
|
||||
Check.Eq(w.SalvageQueued, 1, "force queues the one item");
|
||||
Check.True(w.ChatHas("salvaging 1 item(s): Iron Scrap Sword"), "and says so");
|
||||
Check.True(w.Ub("/ub autosalvage banana"), "a wrong word is handled");
|
||||
Check.True(w.ChatHas("Usage: /ub autosalvage"), "with the usage");
|
||||
}
|
||||
|
||||
private static void AutoSalvageWaitsForId()
|
||||
{
|
||||
string path = WriteProfile("salvid.utl", Rule("Iron", VTankLootAction.Salvage, NameIs("^Iron")));
|
||||
var w = new World((Unknown, "Iron Unknown Sword", 0, 0));
|
||||
FakeHost.Appraised.Remove(Unknown);
|
||||
w.S.CurrentLootPath = path;
|
||||
Check.True(w.Ub("/ub autosalvage force"), "handled");
|
||||
Check.True(w.ChatHas("identifying 1 item(s) first"), "it identifies the item first");
|
||||
Check.Eq(w.SalvageQueued, 0, "nothing queued yet");
|
||||
w.Tick(RynthAiPlugin.UbIdSpacingMs);
|
||||
Check.True(FakeHost.IdRequests.Contains(Unknown), "the identify is sent");
|
||||
FakeHost.Appraised.Add(Unknown);
|
||||
w.Tick(100);
|
||||
Check.Eq(w.SalvageQueued, 1, "once identified, it is salvaged");
|
||||
}
|
||||
|
||||
// 2026-12-01 command audit: /ub count profile <name> loaded the profile through TryLoadLootProfile, which
|
||||
// also made it the profile looting uses, so a meta counting against another profile switched its looting.
|
||||
private static void CountProfileKeepsLootProfile()
|
||||
{
|
||||
string inUse = WriteProfile("inuse.utl", Rule("Keep all", VTankLootAction.Keep, NameIs(".")));
|
||||
string other = WriteProfile("count.utl", Rule("Iron", VTankLootAction.Keep, NameIs("^Iron")));
|
||||
var w = SalvageWorld();
|
||||
w.S.CurrentLootPath = inUse;
|
||||
Check.True(w.Ub("/ub count profile " + other), "/ub count profile");
|
||||
Check.True(w.ChatHas("matching count.utl"), "it counts against that profile");
|
||||
Check.Eq(w.S.CurrentLootPath, inUse, "the loot profile in use is unchanged");
|
||||
}
|
||||
}
|
||||
|
|
@ -144,9 +144,9 @@ internal static class VitalWandGateTests
|
|||
SetVitals(b, 54, 100, 100);
|
||||
Check.True(b.BuffsWaitForFight(), "54% under Heal At 60% in a fight: buffs wait");
|
||||
Check.True(b.BuffsWaitForFight(), "still waiting");
|
||||
// Since 2026-11-20 the fight alone holds them ("clear the mobs nearby before we rebuff").
|
||||
// 2026-11-20 to 12-01 the fight alone held them; since 2026-12-01 only Heal At does ("rebuff starts regardless").
|
||||
SetVitals(b, 70, 100, 100);
|
||||
Check.True(b.BuffsWaitForFight(), "back over Heal At, the fight still on: buffs still wait");
|
||||
Check.False(b.BuffsWaitForFight(), "back over Heal At, the fight still on: buffs go");
|
||||
SetVitals(b, 40, 100, 100);
|
||||
b.InCombatOverride = () => false;
|
||||
Check.False(b.BuffsWaitForFight(), "out of a fight: buffs go on even under Heal At");
|
||||
|
|
|
|||
|
|
@ -140,6 +140,14 @@ namespace RynthDefective.Tests
|
|||
DefCommand bad = DefCommandParser.Parse("daynight soon");
|
||||
Check(bad.Verb == DefVerb.Error && bad.Error.Contains("Usage", StringComparison.Ordinal), "a wrong word: the usage");
|
||||
Check(DefCommandParser.Usage.Contains("daynight", StringComparison.Ordinal), "in the usage");
|
||||
// Its background (2026-12-01): clear by default, the dark box on request.
|
||||
Eq(DefCommandParser.Parse("daynight clear").Text, "clear", "daynight clear");
|
||||
Eq(DefCommandParser.Parse("daynight transparent").Text, "clear", "transparent = clear");
|
||||
Eq(DefCommandParser.Parse("daynight box").Text, "box", "daynight box");
|
||||
Check(DefCommandParser.Usage.Contains("daynight [show|hide|clear|box]", StringComparison.Ordinal), "clear and box in the usage");
|
||||
Check(!new DefSettings().DayNightBox, "a clear background by default (and for a settings file from before)");
|
||||
Check(DefReplies.DayNightLook(false).Text.Contains("clear background", StringComparison.Ordinal), "clear: said so");
|
||||
Check(DefReplies.DayNightLook(true).Text.Contains("dark box", StringComparison.Ordinal), "box: said so");
|
||||
|
||||
DerethNow dusk = DerethClock.At(RawAt(5715));
|
||||
Eq(DefReplies.DayNight(1, dusk), (true, "Day/Night timer shown. Night now (Evensong); day in 1h 4m of real time."), "shown, with the time");
|
||||
|
|
|
|||
|
|
@ -106,6 +106,7 @@ namespace RynthDefective.Tests
|
|||
("qty", DefVerb.Quantity), ("qty 25", DefVerb.Quantity), ("split", DefVerb.Split), ("split 25 into Sack", DefVerb.Split),
|
||||
("give 10", DefVerb.Give), ("buy 25 Mana Scarab", DefVerb.Buy), ("buy max", DefVerb.Buy),
|
||||
("daynight", DefVerb.DayNight), ("daynight show", DefVerb.DayNight), ("daynight hide", DefVerb.DayNight),
|
||||
("daynight clear", DefVerb.DayNight), ("daynight box", DefVerb.DayNight),
|
||||
("bars", DefVerb.Bars), ("bars add", DefVerb.Bars), ("bars remove 2", DefVerb.Bars), ("bars slots 2 12", DefVerb.Bars),
|
||||
("bars show 3", DefVerb.Bars), ("shortcuts clearbusy on", DefVerb.Shortcuts), ("shortcuts clearbusy", DefVerb.Shortcuts),
|
||||
("appraisal", DefVerb.Appraisal), ("appraisal pin", DefVerb.Appraisal), ("appraisal popout", DefVerb.Appraisal), ("examine 0x80001234", DefVerb.Appraisal),
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ internal static unsafe class Program
|
|||
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");
|
||||
if ((filter.Length == 0 || "workers".Contains(filter, StringComparison.OrdinalIgnoreCase)) && !CheckWorkers()) failed.Add("worker coroutines");
|
||||
try
|
||||
{
|
||||
foreach (string file in scripts)
|
||||
|
|
@ -214,6 +215,71 @@ internal static unsafe class Program
|
|||
return allOk;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Worker coroutines (LuaScriptHost): MoonSharp makes ~1 MB of stacks per coroutine (2 MB in
|
||||
/// this 64-bit test), so a coroutine per handler call made a 194-line /myquests read cost a
|
||||
/// chat-handling script ~200 MB and got a script stopped by the memory guard (2026-11-30).
|
||||
/// 300 chat lines through two handlers (one that errors every 50th line, one that sleeps
|
||||
/// every 100th) must all arrive, reuse a handful of workers, and allocate far less than
|
||||
/// 600 coroutines would.
|
||||
/// </summary>
|
||||
private static bool CheckWorkers()
|
||||
{
|
||||
const string name = "workerpool";
|
||||
const string code = @"
|
||||
seen, slept, errs = 0, 0, 0
|
||||
game.World.OnChatText.Add(function(e)
|
||||
seen = seen + 1
|
||||
if e.Message:find('boom', 1, true) then errs = errs + 1; error('boom (expected)') end
|
||||
end)
|
||||
game.World.OnChatText.Add(function(e)
|
||||
if e.Message:find('nap', 1, true) then sleep(30); slept = slept + 1 end
|
||||
end)
|
||||
while true do sleep(200); print('seen=' .. seen .. ' slept=' .. slept) end";
|
||||
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 worker coroutines: no plugin"); return false; }
|
||||
RynthLuaPlugin plugin = runtime.Plugin;
|
||||
bool ok;
|
||||
try
|
||||
{
|
||||
plugin.OnLoginComplete();
|
||||
for (int i = 0; i < 3; i++) Tick(plugin);
|
||||
Directory.CreateDirectory(RynthLuaPaths.Scripts);
|
||||
File.WriteAllText(Path.Combine(RynthLuaPaths.Scripts, name + ".lua"), code);
|
||||
string? err = plugin.StartScript(name);
|
||||
for (int i = 0; i < 5; i++) Tick(plugin);
|
||||
int before = plugin.ScriptWorkersCreated(name);
|
||||
long alloc0 = GC.GetAllocatedBytesForCurrentThread();
|
||||
for (int i = 1; i <= 300; i++)
|
||||
{
|
||||
int eat = 0;
|
||||
plugin.OnChatWindowText($"line {i}" + (i % 50 == 0 ? " boom" : "") + (i % 100 == 0 ? " nap" : ""), 0, ref eat);
|
||||
if (i % 20 == 0) Tick(plugin);
|
||||
}
|
||||
var sw = Stopwatch.StartNew();
|
||||
while (sw.ElapsedMilliseconds < 2000) { Tick(plugin); Thread.Sleep(1); }
|
||||
long allocMb = (GC.GetAllocatedBytesForCurrentThread() - alloc0) >> 20;
|
||||
int made = plugin.ScriptWorkersCreated(name) - before;
|
||||
string console = plugin.ScriptConsoleText(name);
|
||||
string[] lines = console.Split('\n');
|
||||
int boom = lines.Count(l => l.Contains("boom (expected)", StringComparison.Ordinal));
|
||||
bool loaded = plugin.ScriptIsLoaded(name);
|
||||
string last = lines.LastOrDefault(l => l.StartsWith("seen=", StringComparison.Ordinal))?.Trim() ?? "(no count)";
|
||||
// 300 lines x 2 handlers = 600 threads; errors (6) and sleepers drop or hold workers, the rest reuse.
|
||||
ok = err == null && loaded && boom == 6 && last == "seen=300 slept=3" && made > 0 && made <= 40 && allocMb < 200;
|
||||
Console.WriteLine($"{(ok ? "PASS" : "FAIL")} worker coroutines: 600 handler calls made {made} workers, {allocMb} MB allocated, {boom} handler errors, {last}, {(loaded ? "running" : "stopped")}{(err != null ? ", start error: " + err : "")}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { plugin.StopScript(name); } catch { }
|
||||
runtime.Shutdown();
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
private static void Tick(RynthLuaPlugin plugin)
|
||||
{
|
||||
FakeWorld.W.Step();
|
||||
|
|
|
|||
|
|
@ -107,6 +107,7 @@ namespace RynthLua.ScriptWindowsTests
|
|||
Run("engine parser: truncated, bit-flipped and random submits", ParserFuzz);
|
||||
Run("events into results", Events);
|
||||
Run("Lua: Phase 0 imgui functions and the bench", LuaBench);
|
||||
Run("Lua: hud passes reuse one worker coroutine", HudPassWorkers);
|
||||
Run("Lua: every MVP imgui function, with events", LuaMvpFunctions);
|
||||
Run("Lua: SetNextWindow* by ImGuiCond", LuaWindowCalls);
|
||||
Run("Lua: errors (unsupported, refused, outside a pass)", LuaErrors);
|
||||
|
|
@ -835,6 +836,70 @@ namespace RynthLua.ScriptWindowsTests
|
|||
Check(msg.Type == DataType.String && msg.String.Contains("only work inside a hud's OnRender"), "ImGui outside a pass: " + msg.ToPrintString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hud passes run on pooled worker coroutines (LuaScriptHost): a new MoonSharp coroutine is
|
||||
/// ~1 MB, and a pass every 50 ms made one each time (2026-11-30: a script's 20/s window,
|
||||
/// then a script stopped by the memory guard). 50 good passes take one worker; a pass
|
||||
/// that runs too long, sleeps or errors drops its worker, and the next good pass still draws.
|
||||
/// </summary>
|
||||
private static void HudPassWorkers()
|
||||
{
|
||||
var plugin = new RynthLuaPlugin();
|
||||
ScriptHud? hud = null;
|
||||
var host = new LuaScriptHost(_ => { }, (s, h) => LibraryImGuiValues.Register(s));
|
||||
var ctx = new ScriptContext("hud-workers", null, string.Empty, new ScriptManifest(), host);
|
||||
hud = new ScriptHud(ctx, "Bench", "RynthLua/hud-workers/Bench", ctx.Event("Hud:Bench:OnRender"), ctx.Event("Hud:Bench:OnPreRender"));
|
||||
HudsByHash(plugin)[hud.Hash] = hud;
|
||||
Huds(plugin).Add(hud);
|
||||
host.ResolveModule = (s, name) =>
|
||||
{
|
||||
if (name == "imgui") return CreateImGuiModule(plugin, s);
|
||||
if (name != "views") return null;
|
||||
var fake = new Table(s);
|
||||
fake["OnRender"] = hud.OnRender.CreateTable(s);
|
||||
var huds = new Table(s);
|
||||
huds["CreateHud"] = DynValue.NewCallback((c, a) => DynValue.NewTable(fake));
|
||||
var views = new Table(s);
|
||||
views["Huds"] = DynValue.NewTable(huds);
|
||||
return DynValue.NewTable(views);
|
||||
};
|
||||
host.Run(@"
|
||||
local ImGui = require('imgui'); local views = require('views')
|
||||
mode, passes = 'ok', 0
|
||||
views.Huds.CreateHud('Bench').OnRender.Add(function()
|
||||
passes = passes + 1
|
||||
if mode == 'long' then local x = 0 for i = 1, 10000000 do x = x + i end end
|
||||
if mode == 'sleep' then sleep(10) end
|
||||
if mode == 'error' then error('bad pass') end
|
||||
ImGui.Text('pass ' .. passes)
|
||||
end)", "hud-workers");
|
||||
host.Tick(System.Diagnostics.Stopwatch.GetTimestamp() + System.Diagnostics.Stopwatch.Frequency);
|
||||
Check(host.Loaded, "script loaded: " + host.ConsoleText());
|
||||
|
||||
int made0 = host.WorkersCreated;
|
||||
long alloc0 = GC.GetAllocatedBytesForCurrentThread();
|
||||
for (int i = 0; i < 50; i++) RunPass(plugin, hud);
|
||||
long allocMb = (GC.GetAllocatedBytesForCurrentThread() - alloc0) >> 20;
|
||||
Check(hud.LastError == null, "50 passes ok: " + hud.LastError);
|
||||
Check(host.WorkersCreated - made0 <= 1, $"50 passes, {host.WorkersCreated - made0} new worker(s)");
|
||||
Check(allocMb < 40, $"50 passes allocated {allocMb} MB (a coroutine each was ~100 MB in a 64-bit test)");
|
||||
|
||||
foreach (string bad in new[] { "long", "sleep", "error" })
|
||||
{
|
||||
host.Lua!.Globals["mode"] = bad;
|
||||
RunPass(plugin, hud);
|
||||
Check(hud.LastError != null, $"{bad} pass fails: {hud.LastError}");
|
||||
host.Lua!.Globals["mode"] = "ok";
|
||||
RunPass(plugin, hud);
|
||||
DisplayList l = ParseOne(hud);
|
||||
double n = host.Lua!.Globals.Get("passes").Number;
|
||||
Check(hud.LastError == null && l.OpCount > 0 && S(l, l.Ops[0].Str, l.Ops[0].StrLen) == "pass " + n,
|
||||
$"after a {bad} pass the next one draws 'pass {n}': {hud.LastError}");
|
||||
}
|
||||
Check(host.Loaded, "still running");
|
||||
host.Stop();
|
||||
}
|
||||
|
||||
// ── Lua harness for the imgui module ────────────────────────────
|
||||
|
||||
private sealed class LuaHud
|
||||
|
|
|
|||
Loading…
Reference in a new issue