diff --git a/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/PropertyDump.cs b/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/PropertyDump.cs new file mode 100644 index 0000000..a26fd44 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/PropertyDump.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using RynthCore.Plugin.RynthAi.Meta; + +namespace RynthCore.Plugin.RynthAi.Diagnostics; + +/// +/// What /ub propertydump (= /vt propertydump = /ra dumpprops, the PropertyDump hotkey) prints for +/// one object. Filled from the engine's v84 GetObjectProperties (every key the client holds), or on +/// an older engine from per-key reads of every named key plus the old fixed ranges. +/// +internal sealed class PropertyDumpData +{ + public uint Id; + public string Name = ""; + public uint Wcid; + public string ObjectClass = ""; + public int ObjectClassValue; + public bool IsPlayer; + public bool HasIdData; + /// Unix seconds of the last identify; 0 never. + public long LastIdTime; + /// False: an engine before v84, so only the keys probed one by one are listed. + public bool Complete; + + public readonly Dictionary Ints = new(); + public readonly Dictionary Int64s = new(); + public readonly Dictionary Bools = new(); + public readonly Dictionary Floats = new(); + public readonly Dictionary Strings = new(); + public readonly Dictionary DataIds = new(); + public readonly Dictionary InstanceIds = new(); + public readonly List Spells = new(); + + public int PropertyCount => Ints.Count + Int64s.Count + Bools.Count + Floats.Count + Strings.Count + + DataIds.Count + InstanceIds.Count; +} + +/// +/// The dump's text, laid out like UtilityBelt's propertydump (a header, then one section per +/// property type, entries sorted by name, then the spell book) so the two can be compared line by +/// line: " Name (key) = value", unknown keys as their number, data and instance ids in hex. +/// Pure: no host, no game; RynthAiHostTests checks it. +/// +internal static class PropertyDump +{ + /// Lines posted to chat per plugin tick (the rest follow on the next ticks). + public const int ChatLinesPerTick = 25; + + /// Where the full dump is written (RynthAi\Logs); tests point it at a scratch folder. + internal static string? FolderOverride; + public static string Folder => FolderOverride ?? Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "Logs"); + + public static List Format(PropertyDumpData d, Func spellName, Func objectName) + { + var lines = new List(); + string name = d.Name.Length > 0 ? d.Name : (d.Strings.TryGetValue(1, out string? n) ? n : "?"); + lines.Add($"Property Dump for {name}"); + lines.Add($"Id = {d.Id} (0x{d.Id:X8})"); + if (d.Wcid != 0) lines.Add($"Type (wcid) = {d.Wcid}"); + lines.Add($"Name = {name}"); + if (d.ObjectClass.Length > 0) lines.Add($"ObjectClass = {d.ObjectClass} ({d.ObjectClassValue})"); + if (d.Ints.TryGetValue(1, out int itemType)) lines.Add($"Category = {itemType} (0x{itemType:X8})"); + if (d.InstanceIds.TryGetValue(2, out uint container)) lines.Add($"Container = 0x{container:X8}{Who(container, objectName)}"); + if (d.InstanceIds.TryGetValue(3, out uint wielder)) lines.Add($"Wielder = 0x{wielder:X8}{Who(wielder, objectName)}"); + lines.Add($"HasIdData = {(d.HasIdData ? "True" : "False")}"); + lines.Add(d.LastIdTime > 0 + ? $"LastIdTime = {d.LastIdTime} ({DateTimeOffset.FromUnixTimeSeconds(d.LastIdTime).ToLocalTime():yyyy-MM-dd HH:mm:ss})" + : "LastIdTime = 0"); + lines.Add($"SpellCount = {d.Spells.Count}"); + + Section(lines, "String Values", d.Strings, PropertyNames.GetStringName, v => v); + Section(lines, "Int Values", d.Ints, PropertyNames.GetIntName, v => v.ToString(CultureInfo.InvariantCulture)); + Section(lines, "Int64 Values", d.Int64s, PropertyNames.GetInt64Name, v => v.ToString(CultureInfo.InvariantCulture)); + Section(lines, "Bool Values", d.Bools, PropertyNames.GetBoolName, v => v ? "True" : "False"); + Section(lines, "Float Values", d.Floats, PropertyNames.GetFloatName, v => v.ToString("R", CultureInfo.InvariantCulture)); + Section(lines, "DataId Values", d.DataIds, PropertyNames.GetDataIdName, v => $"0x{v:X8}"); + Section(lines, "InstanceId Values", d.InstanceIds, PropertyNames.GetInstanceIdName, v => $"0x{v:X8}{Who(v, objectName)}"); + + if (d.Spells.Count > 0) + { + lines.Add($"Spells ({d.Spells.Count}):"); + foreach (uint s in d.Spells) + lines.Add($" {spellName(s)} ({s})"); + } + + lines.Add($"Total: {d.PropertyCount} properties ({d.Strings.Count} string, {d.Ints.Count} int, {d.Int64s.Count} int64, " + + $"{d.Bools.Count} bool, {d.Floats.Count} float, {d.DataIds.Count} data id, {d.InstanceIds.Count} instance id), " + + $"{d.Spells.Count} spell(s)."); + if (!d.Complete) + lines.Add("Older RynthCore engine (before plugin API 84): only the keys asked one by one are listed. Update RynthCore for every key."); + if (!d.HasIdData && !d.IsPlayer) + lines.Add("Not identified: only what the client gets without an appraisal is listed."); + return lines; + } + + // One section, only when it has entries (as UtilityBelt): named keys by name, then unknown keys by number. + private static void Section(List lines, string title, Dictionary values, + Func nameOf, Func show) + { + if (values.Count == 0) return; + lines.Add(title + ":"); + foreach (var kv in values + .Select(kv => (kv.Key, kv.Value, Name: nameOf(kv.Key))) + .OrderBy(e => e.Name == null ? 1 : 0) + .ThenBy(e => e.Name, StringComparer.Ordinal) + .ThenBy(e => e.Key)) + lines.Add(kv.Name != null + ? $" {kv.Name} ({kv.Key}) = {show(kv.Value)}" + : $" {kv.Key} = {show(kv.Value)}"); + } + + private static string Who(uint id, Func objectName) + { + if (id == 0) return ""; + string? n = objectName(id); + return string.IsNullOrEmpty(n) ? "" : $" ({n})"; + } + + /// propertydump-<name>-<yyyyMMdd-HHmmss>.txt, the name cut to safe characters. + public static string FileName(string name, DateTime when) + { + var sb = new StringBuilder(); + foreach (char c in name) + { + if (sb.Length >= 40) break; + sb.Append(char.IsLetterOrDigit(c) || c is '-' or '_' ? c : (c == ' ' ? '_' : '\0')); + } + string safe = sb.ToString().Replace("\0", "").Trim('_'); + if (safe.Length == 0) safe = "object"; + return $"propertydump-{safe}-{when:yyyyMMdd-HHmmss}.txt"; + } + + /// Probe lists for an engine before v84: every named key plus the old fixed ranges. + public static IEnumerable ProbeKeys(IEnumerable named, uint rangeEnd) + { + var set = new SortedSet(named); + for (uint i = 0; i <= rangeEnd; i++) set.Add(i); + return set; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs b/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs index c142b16..ffb4b95 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs @@ -2,19 +2,46 @@ // DoorInteractionController.cs — partial class RynthAiPlugin // // Detects closed doors while the macro is running and automatically opens them. -// Optionally uses lockpicks from the Consumable Items list if the door is -// locked (UseObject fails to open it). +// Optionally uses lockpicks from the Consumable Items list on a door the server +// says is locked. // -// State machine: None → Opening → CheckingResult → Unlocking → RetryOpen → Cooldown +// State machine: +// None -> Pending (a use waits for its turn) -> Opening (the use is out) -> +// Settling (the server answered; the door gets a moment to swing) -> done, +// or back to Pending for another use, or Unlocking (a lockpick is out) -> Pending, +// or Cooldown. // // Two ways in: the proximity scan (OpenDoors setting, nearest closed door in // range), and a requested door (RequestDoorOpen): the nav engine's recovery // detour asks for the closed door on its next leg. A requested door is opened // even with OpenDoors off, since the detour was planned through that doorway. +// +// The rules (2026-10-13, a mage on DreamWeave: "doors aren't opening"; 13 doors, +// 5 timeouts, 3 lockpick cooldowns with no locked door anywhere): +// * One door use at a time, sent only when nothing else is waiting for the server +// (ActionPacer.MayStart: no unanswered use/cast/stance change, no animation, the +// stop before it settled) and the client isn't busy (up to DoorBusyWaitMaxMs: +// the busy count only drives AC's cursor and reads 1 for seconds after a slow +// cast or a portal, BusyCountHooks' watchdog clears it after 5 s). The old code +// sent the use at once (busy=1) and again after 3 s with the first still +// unanswered: on ACE a second use restarts the server's walk to the door, and a +// use of a door that just opened closes it again. +// * The server walks the character to the door before it opens it: the answer +// (UseDone) took 0.3-3.7 s in that log, so the use is given DoorAnswerMaxMs +// before it counts as lost. A door that reads open ends it at once, whatever +// the wait, so a door that opens is never waited on. +// * "Locked" only when the server says so: ACE answers a locked door with the +// transient text "The door is locked!" (Door.ActOnUse), which RynthAi gets as a +// server message (API v78) or a chat line. A door still closed after an answered +// use is used again (DoorMaxAttempts), never picked. +// * Nothing while in portal space or for DoorPostPortalMs after it: two of the +// log's false "locked" doors were targeted inside portal space (busy=1 from the +// portal), their uses lost to the teleport. // ============================================================================ using System; using System.Linq; +using System.Text.RegularExpressions; using RynthCore.Plugin.RynthAi.LegacyUi; using RynthCore.Plugin.Shared; @@ -23,31 +50,61 @@ namespace RynthCore.Plugin.RynthAi; public sealed partial class RynthAiPlugin { private int _doorTargetId; - private long _doorActionAt; - private int _doorAttempts; - private bool _doorPausedNav; + private long _doorActionAt; // when the current state started (Pending: when the use was wanted) + private int _doorAttempts; // door uses that came back with the door still closed + private int _doorPicks; // lockpicks used on the current door private DoorState _doorState = DoorState.None; private long _doorLastDiagAt; private int _doorRequestedId; // asked for by the nav recovery detour; taken on the next idle tick private bool _doorTargetRequested; // the current target came from a request + private bool _doorWantLockpick; // Pending sends a lockpick (the server said locked), not an open + private long _doorSentAt; // when the last door use / lockpick went out + private int _doorSeqAtSend; // the UseDone count read just before it went out + private uint _doorAnswerErr; // the error of the UseDone that answered it (0 = done) + private bool _doorWaitLogged; // one "waits" line per Pending + private long _doorLastPortalAt = long.MinValue / 2; + + // "The door is locked!" (ACE Door.ActOnUse, a transient string): when it last arrived. + private long _doorLockedSaidAt = long.MinValue / 2; // Doors we've already opened — skip for 60s so we don't re-target them private readonly System.Collections.Generic.Dictionary _doorOpenedRecently = new(); + // Locked doors we can't pick (no lockpick, Auto Unlock off, out of picks) — skip a while + private readonly System.Collections.Generic.Dictionary _doorLockedRecently = new(); - private const long DoorBusyTimeoutMs = 3000; - private const long DoorResultSettleMs = 1200; // a use is not judged "didn't open" sooner (below DoorBusyTimeoutMs) + /// Clock (ms) for the door logic; tests replace it. + internal static Func DoorClock = static () => Environment.TickCount64; + + /// A use with no answer this long is taken as lost (the longest answer in the 10-13 log was 3.7 s; + /// ActionPacer gives a world use 5 s). + private const long DoorAnswerMaxMs = 6000; + /// After the server's answer, the door gets this long to read open before the use counts as failed. + private const long DoorOpenSettleMs = 1200; + /// A use waits for the client's busy count to read 0 at most this long (see the header). + private const long DoorBusyWaitMaxMs = 2500; + /// A use that can't go out this long (something else keeps the server busy) gives up for now. + private const long DoorSendWaitMaxMs = 10000; + /// No door is targeted for this long after portal space. + private const long DoorPostPortalMs = 1500; private const long DoorCooldownMs = 5000; private const long DoorOpenedSkipMs = 60000; + private const long DoorLockedSkipMs = 30000; private const int DoorMaxAttempts = 3; + private const int DoorMaxPicks = 3; + private const uint DoorTooBusyErr = 0x1D; private const float YardsToMeters = 0.9144f; + // ACE: "The door is locked!"; other servers name the door ("The Gate is locked."). Server text only. + private static readonly Regex DoorLockedText = new(@"^\s*the\s.+\sis\s+locked\s*[.!]?\s*$", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); + private enum DoorState { None, + Pending, Opening, - CheckingResult, + Settling, Unlocking, - RetryOpen, Cooldown } @@ -66,27 +123,35 @@ public sealed partial class RynthAiPlugin return false; } - long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + long now = DoorClock(); - // Clean up stale entries from the recently-opened dict - if (_doorOpenedRecently.Count > 0) + PruneDoorSkips(_doorOpenedRecently, now, DoorOpenedSkipMs); + PruneDoorSkips(_doorLockedRecently, now, DoorLockedSkipMs); + + // Portal space: the server drops a use sent now, and the client's busy count reads 1 for the + // portal. Whatever was under way is forgotten; nothing new starts until a moment after it. + if (ActionPacer.IsPortaling(Host)) { - var expired = _doorOpenedRecently - .Where(kv => now - kv.Value >= DoorOpenedSkipMs) - .Select(kv => kv.Key).ToList(); - foreach (var key in expired) - _doorOpenedRecently.Remove(key); + _doorLastPortalAt = now; + if (_doorState != DoorState.None) + { + Host.Log($"[RynthAi] Door: portal space - dropping 0x{(uint)_doorTargetId:X8} (the server drops a use sent now)"); + ResetDoorState(); + } + return false; } // ── Idle: scan for a nearby closed door ───────────────────────────── if (_doorState == DoorState.None) { + if (now - _doorLastPortalAt < DoorPostPortalMs) return false; + int doorId = 0; if (_doorRequestedId != 0) { int req = _doorRequestedId; _doorRequestedId = 0; - if (!IsDoorOpen(req)) + if (!IsDoorOpen(req) && !_doorLockedRecently.ContainsKey(req)) { doorId = req; _doorTargetRequested = true; @@ -99,118 +164,82 @@ public sealed partial class RynthAiPlugin string why = _doorTargetRequested ? " (asked for by the nav detour)" : ""; Host.Log($"[RynthAi] Door: targeting 0x{(uint)doorId:X8}{why} (state={GetDoorStateDebug(doorId)}, busy={_busyCount})"); _doorTargetId = doorId; - _doorState = DoorState.Opening; _doorAttempts = 0; - _doorActionAt = now; + _doorPicks = 0; + _doorWantLockpick = false; _navigationEngine?.Stop(); if (Host.HasStopCompletely) Host.StopCompletelyBy("Door"); - _doorPausedNav = true; - Host.UseFor(unchecked((uint)doorId), "Door", - _doorTargetRequested ? "the nav detour asked to open this door" : $"Open Doors: closed door within {settings.OpenDoorRange:0} yd"); - return true; - } - - // ── Timeout guard (only for action-waiting states) ──────────────── - if (_doorState is DoorState.Opening or DoorState.Unlocking or DoorState.RetryOpen - && now - _doorActionAt > DoorBusyTimeoutMs) - { - // Check if the door opened while we were waiting (slow state propagation) - if (IsDoorOpen(_doorTargetId)) - { - Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} opened (late detect) — ready for next"); - MarkDoorOpenedAndReset(now); - return false; - } - - _doorAttempts++; - if (_doorAttempts >= DoorMaxAttempts) - { - Host.Log($"[RynthAi] Door: max attempts ({DoorMaxAttempts}) for 0x{(uint)_doorTargetId:X8}, cooldown"); - _doorState = DoorState.Cooldown; - _doorActionAt = now; - return true; - } - Host.Log($"[RynthAi] Door: timeout in {_doorState}, retry #{_doorAttempts} for 0x{(uint)_doorTargetId:X8} (busy={_busyCount})"); - _doorState = DoorState.Opening; - _doorActionAt = now; - Host.UseFor(unchecked((uint)_doorTargetId), "Door", $"retry #{_doorAttempts}: the door didn't open in {DoorBusyTimeoutMs} ms"); + // The use goes once the stop has settled and nothing else waits for the server. + EnterDoorPending(now); return true; } switch (_doorState) { + case DoorState.Pending: + return TickDoorPending(settings, now); + case DoorState.Opening: - if (_busyCount > 0) return true; + { if (IsDoorOpen(_doorTargetId)) { - Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} opened OK — ready for next"); + Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} opened OK after {now - _doorSentAt} ms — ready for next"); MarkDoorOpenedAndReset(now); return false; } - // The use is queued for AC's main thread and the server answers later: the - // busy count was still 0 when this read "not open" ~45 ms after the use - // (2026-10-02 logs), every time. Give the door time to swing first. - if (now - _doorActionAt < DoorResultSettleMs) return true; - Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} not open after use ({GetDoorStateDebug(_doorTargetId)}), checking result"); - _doorState = DoorState.CheckingResult; - _doorActionAt = now; + if (DoorSaidLocked()) + return OnDoorLocked(settings, now); + if (DoorUseAnswered(out uint err)) + { + _doorAnswerErr = err; + _doorState = DoorState.Settling; + _doorActionAt = now; + return true; + } + if (now - _doorSentAt >= DoorAnswerMaxMs) + { + Host.Log($"[RynthAi] Door: no answer from the server to the use of 0x{(uint)_doorTargetId:X8} in {now - _doorSentAt} ms (busy={_busyCount})"); + return DoorUseFailed(now, "the server never answered the use"); + } return true; + } - case DoorState.CheckingResult: - if (!settings.AutoUnlockDoors) + case DoorState.Settling: + { + if (IsDoorOpen(_doorTargetId)) { - Host.Log("[RynthAi] Door: not open & auto-unlock off, cooldown"); - _doorState = DoorState.Cooldown; - _doorActionAt = now; - return true; + Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} opened OK after {now - _doorSentAt} ms — ready for next"); + MarkDoorOpenedAndReset(now); + return false; } - var lockpick = FindLockpickInConsumables(); - if (lockpick == null) - { - Host.Log("[RynthAi] Door: locked but no lockpick in consumables, cooldown"); - _doorState = DoorState.Cooldown; - _doorActionAt = now; - return true; - } - Host.Log($"[RynthAi] Door: using lockpick {lockpick.Name} on 0x{(uint)_doorTargetId:X8}"); - _doorState = DoorState.Unlocking; - _doorActionAt = now; - Host.UseOnFor(unchecked((uint)lockpick.Id), unchecked((uint)_doorTargetId), "Door", "Auto Unlock Doors: lockpick on a door that didn't open"); - return true; + if (DoorSaidLocked()) + return OnDoorLocked(settings, now); + if (_doorAnswerErr == DoorTooBusyErr) + return DoorUseFailed(now, "the server answered 'too busy' (0x1D)"); + if (now - _doorActionAt < DoorOpenSettleMs) return true; + Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} not open {now - _doorSentAt} ms after the use ({GetDoorStateDebug(_doorTargetId)}, answer err=0x{_doorAnswerErr:X}); no 'locked' from the server"); + return DoorUseFailed(now, "still closed after the server's answer"); + } case DoorState.Unlocking: - if (_busyCount > 0) return true; - Host.Log($"[RynthAi] Door: unlock done, retrying open 0x{(uint)_doorTargetId:X8}"); - _doorState = DoorState.RetryOpen; - _doorActionAt = now; - Host.UseFor(unchecked((uint)_doorTargetId), "Door", "open again after the lockpick"); - return true; - - case DoorState.RetryOpen: - if (_busyCount > 0) return true; + { if (IsDoorOpen(_doorTargetId)) { Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} unlocked & opened OK — ready for next"); MarkDoorOpenedAndReset(now); return false; } - if (now - _doorActionAt < DoorResultSettleMs) return true; - _doorAttempts++; - if (_doorAttempts >= DoorMaxAttempts) - { - Host.Log($"[RynthAi] Door: max attempts after unlock for 0x{(uint)_doorTargetId:X8}, cooldown"); - _doorState = DoorState.Cooldown; - _doorActionAt = now; - } - else - { - _doorState = DoorState.Opening; - _doorActionAt = now; - Host.UseFor(unchecked((uint)_doorTargetId), "Door", $"still closed after the lockpick, try {_doorAttempts + 1}"); - } + bool answered = DoorUseAnswered(out _); + if (!answered && now - _doorSentAt < DoorAnswerMaxMs) return true; + Host.Log(answered + ? $"[RynthAi] Door: lockpick answered, opening 0x{(uint)_doorTargetId:X8} again" + : $"[RynthAi] Door: no answer to the lockpick in {now - _doorSentAt} ms, opening 0x{(uint)_doorTargetId:X8} again"); + _doorWantLockpick = false; + EnterDoorPending(now); return true; + } case DoorState.Cooldown: if (now - _doorActionAt >= DoorCooldownMs) @@ -224,6 +253,194 @@ public sealed partial class RynthAiPlugin return false; } + /// A door use (or a lockpick) is wanted: it goes when lets it. + private void EnterDoorPending(long now) + { + _doorState = DoorState.Pending; + _doorActionAt = now; + _doorWaitLogged = false; + } + + /// Sends the wanted use once nothing else waits for the server; true while the door holds nav. + private bool TickDoorPending(LegacyUiSettings settings, long now) + { + // Open already (another player, or the last use's swing showed late): never use it again, + // a use of an open door closes it. + if (IsDoorOpen(_doorTargetId)) + { + Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} reads open — ready for next"); + MarkDoorOpenedAndReset(now); + return false; + } + + long waited = now - _doorActionAt; + if (!DoorMayUseNow(waited, out string why)) + { + if (waited >= DoorSendWaitMaxMs) + { + Host.Log($"[RynthAi] Door: couldn't use 0x{(uint)_doorTargetId:X8} for {waited} ms ({why}), cooldown"); + EnterDoorCooldown(now); + return true; + } + if (!_doorWaitLogged) + { + _doorWaitLogged = true; + Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} waits: {why}"); + } + return true; + } + + int seqBefore = ActionPacer.UseDoneSeqNow(Host); + bool sent; + if (_doorWantLockpick) + { + var lockpick = FindLockpickInConsumables(); + if (lockpick == null) + { + Host.Log("[RynthAi] Door: the lockpick is gone, cooldown"); + EnterDoorCooldown(now, locked: true); + return true; + } + Host.Log($"[RynthAi] Door: using lockpick {lockpick.Name} on 0x{(uint)_doorTargetId:X8}"); + sent = Host.UseOnFor(unchecked((uint)lockpick.Id), unchecked((uint)_doorTargetId), "Door", "Auto Unlock Doors: the server says this door is locked"); + if (sent) { _doorPicks++; _doorState = DoorState.Unlocking; } + } + else + { + string reason = _doorAttempts > 0 + ? $"try {_doorAttempts + 1}: still closed after the last use" + : _doorPicks > 0 ? "open after the lockpick" + : _doorTargetRequested ? "the nav detour asked to open this door" + : $"Open Doors: closed door within {settings.OpenDoorRange:0} yd"; + sent = Host.UseFor(unchecked((uint)_doorTargetId), "Door", reason); + if (sent) _doorState = DoorState.Opening; + } + + if (!sent) + { + // Held (salvage panel), or the engine refused it: try again on a later tick. + if (waited >= DoorSendWaitMaxMs) + { + Host.Log($"[RynthAi] Door: the use of 0x{(uint)_doorTargetId:X8} didn't go out for {waited} ms, cooldown"); + EnterDoorCooldown(now); + } + return true; + } + + _doorSentAt = now; + _doorActionAt = now; + _doorSeqAtSend = seqBefore; + _doorAnswerErr = 0; + _doorLockedSaidAt = long.MinValue / 2; // only a "locked" answer to THIS use counts + return true; + } + + /// May a door use go out now? No while another server action is unanswered, the character + /// animates or its stop hasn't settled (ActionPacer), nor while the client reads busy (up to + /// DoorBusyWaitMaxMs). + private bool DoorMayUseNow(long waited, out string why) + { + if (!ActionPacer.MayStart(Host, "Door", HealNeed.None, out why)) + return false; + if (_busyCount > 0 && waited < DoorBusyWaitMaxMs) + { + why = $"the client is busy ({_busyCount})"; + return false; + } + why = ""; + return true; + } + + /// The server answered the last door use / lockpick (a UseDone since it went out); err = its error. + private bool DoorUseAnswered(out uint err) + { + err = 0; + try + { + if (!Host.HasUseDoneSeq) + return DoorClock() - _doorSentAt >= ActionPacer.NoUseDoneFallbackMs; // no UseDone on this engine + int seq = Host.GetUseDoneSeq(); + if (seq == _doorSeqAtSend) return false; + if (Host.TryGetLastUseDone(out int ls, out uint le) && ls == _doorSeqAtSend + 1) err = le; + return true; + } + catch { return false; } + } + + /// The server said "locked" since the last door use went out. + private bool DoorSaidLocked() => _doorLockedSaidAt >= _doorSentAt; + + /// A door use came back with the door still closed: use it again, or give up for now. + private bool DoorUseFailed(long now, string why) + { + _doorAttempts++; + if (_doorAttempts >= DoorMaxAttempts) + { + Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} still closed after {_doorAttempts} uses ({why}), cooldown"); + EnterDoorCooldown(now); + return true; + } + Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} {why} - using it again (try {_doorAttempts + 1} of {DoorMaxAttempts})"); + EnterDoorPending(now); + return true; + } + + /// The server said the door is locked: a lockpick if allowed and carried, else leave it for a while. + private bool OnDoorLocked(LegacyUiSettings settings, long now) + { + if (!settings.AutoUnlockDoors) + { + Host.Log($"[RynthAi] Door: the server says 0x{(uint)_doorTargetId:X8} is locked; Auto Unlock Doors is off, cooldown"); + EnterDoorCooldown(now, locked: true); + return true; + } + if (_doorPicks >= DoorMaxPicks) + { + Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} still locked after {_doorPicks} lockpick(s), cooldown"); + EnterDoorCooldown(now, locked: true); + return true; + } + var lockpick = FindLockpickInConsumables(); + if (lockpick == null) + { + Host.Log($"[RynthAi] Door: the server says 0x{(uint)_doorTargetId:X8} is locked but there's no lockpick in consumables, cooldown"); + EnterDoorCooldown(now, locked: true); + return true; + } + Host.Log($"[RynthAi] Door: the server says 0x{(uint)_doorTargetId:X8} is locked - lockpick next"); + _doorWantLockpick = true; + EnterDoorPending(now); + return true; + } + + private void EnterDoorCooldown(long now, bool locked = false) + { + if (locked && _doorTargetId != 0) _doorLockedRecently[_doorTargetId] = now; + _doorState = DoorState.Cooldown; + _doorActionAt = now; + } + + /// + /// Server text (a transient string from the server-message stream, or a chat line): remembers a + /// "The door is locked!" for the door logic. Called from both, so whichever the client delivers + /// first counts. + /// + internal void NoteDoorServerText(string? text) + { + if (string.IsNullOrEmpty(text) || text.Length > 120) return; + if (!DoorLockedText.IsMatch(text)) return; + _doorLockedSaidAt = DoorClock(); + if (_doorState is DoorState.Opening or DoorState.Settling) + Host.Log($"[RynthAi] Door: server says \"{text.Trim()}\" (0x{(uint)_doorTargetId:X8})"); + } + + private static void PruneDoorSkips(System.Collections.Generic.Dictionary skips, long now, long forMs) + { + if (skips.Count == 0) return; + foreach (int key in skips.Where(kv => now - kv.Value >= forMs).Select(kv => kv.Key).ToList()) + skips.Remove(key); + } + private void MarkDoorOpenedAndReset(long now) { _doorOpenedRecently[_doorTargetId] = now; @@ -235,7 +452,8 @@ public sealed partial class RynthAiPlugin _doorTargetId = 0; _doorState = DoorState.None; _doorAttempts = 0; - _doorPausedNav = false; + _doorPicks = 0; + _doorWantLockpick = false; _doorTargetRequested = false; } @@ -299,7 +517,7 @@ public sealed partial class RynthAiPlugin double bestDist = double.MaxValue; bool hasBitfield = Host.HasGetObjectBitfield; - int totalLandscape = 0, doorsFound = 0, openSkipped = 0, recentSkipped = 0; + int totalLandscape = 0, doorsFound = 0, openSkipped = 0, recentSkipped = 0, lockedSkipped = 0; foreach (var wo in _objectCache.GetLandscapeObjects()) { @@ -331,6 +549,13 @@ public sealed partial class RynthAiPlugin continue; } + // Skip locked doors we couldn't pick + if (_doorLockedRecently.ContainsKey(wo.Id)) + { + lockedSkipped++; + continue; + } + // Skip already-open doors if (IsDoorOpen(wo.Id)) { @@ -349,7 +574,7 @@ public sealed partial class RynthAiPlugin if (bestId == 0 && doorsFound > 0 && (now - _doorLastDiagAt) >= 5000) { _doorLastDiagAt = now; - Host.Log($"[RynthAi] Door scan: {totalLandscape} landscape, {doorsFound} doors, {openSkipped} open, {recentSkipped} recent-skip, range={rangeMeters:F1}m"); + Host.Log($"[RynthAi] Door scan: {totalLandscape} landscape, {doorsFound} doors, {openSkipped} open, {recentSkipped} recent-skip, {lockedSkipped} locked-skip, range={rangeMeters:F1}m"); } return bestId; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index fb8958f..2ac5958 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -2340,12 +2340,20 @@ internal sealed partial class LegacyDashboardRenderer /// Writes an edited route back to its file (or the meta's embedded nav). public void AutoSaveRoute() => _navigationUi.TryAutoSaveNav(); - /// /ra nav load <name>. Returns the chat line. + /// + /// /ra nav load <name> (and /vt nav load). Returns the chat line. No such nav in + /// NavProfiles: a blank one (Circular, no points) is created and loaded, as VTank's + /// "/vt nav load newroute" does, so a route can be recorded into it (2026-10-13). + /// public string LoadNavByName(string name) { + ProfileFileResult r = NewProfileFiles.FindOrCreateNav(_navFolder, name, out string want, out _, out string error); + if (r == ProfileFileResult.Rejected) + return $"[RynthAi] Can't use '{want}' as a nav name: {error}."; + if (r == ProfileFileResult.Failed) + return $"[RynthAi] Couldn't create nav '{want}': {error}"; + RefreshNavFiles(); - string want = name.Trim(); - if (want.EndsWith(".nav", StringComparison.OrdinalIgnoreCase)) want = want[..^4].TrimEnd(); int idx; lock (_profileListsLock) idx = _navFiles.FindIndex(f => f != "None" && f.Equals(want, StringComparison.OrdinalIgnoreCase)); @@ -2353,7 +2361,54 @@ internal sealed partial class LegacyDashboardRenderer _selectedNavIdx = idx; LoadSelectedNav(); SaveSettings(); - return $"[RynthAi] Loaded {want} ({_settings.CurrentRoute.Points.Count} waypoints)."; + return r == ProfileFileResult.Created + ? $"[RynthAi] Created new nav '{want}' (empty, {NewProfileFiles.BlankNavType}) and loaded it." + : $"[RynthAi] Loaded {want} ({_settings.CurrentRoute.Points.Count} waypoints)."; + } + + /// + /// /ra meta load <name> and /vt meta load <name> (one implementation). Returns the + /// chat line. <name>.af, else <name>.met, in MetaFiles; when neither exists a blank + /// <name>.af (one state "Default", no rules) is created and loaded: the old rules are + /// cleared and the meta starts in Default (VTank's "load makes a new one", 2026-10-13). + /// : /ra meta new <name> (an existing meta is left alone). + /// + public string LoadMetaByName(string name, bool createOnly = false) + { + ProfileFileResult r = NewProfileFiles.FindOrCreateMeta(_metaFolder, name, out string want, out string path, out string error, createOnly); + switch (r) + { + case ProfileFileResult.Rejected: + return $"[RynthAi] Can't use '{want}' as a meta name: {error}."; + case ProfileFileResult.Failed: + return $"[RynthAi] Couldn't create meta '{want}': {error}"; + case ProfileFileResult.Exists: + return $"[RynthAi] Meta '{Path.GetFileName(path)}' already exists. /ra meta load {want} loads it."; + } + + if (!_metaUi.LoadMacroFile(path)) + { + string why = _metaUi.LastLoadStatus.Length > 0 ? _metaUi.LastLoadStatus : "no rules loaded"; + return $"[RynthAi] Meta '{want}' not loaded: {why}"; + } + _metaUi.RefreshFileListIfShown(); + RefreshMetaFiles(); // MetaProfileIdx follows the loaded file + SaveSettings(); + if (r == ProfileFileResult.Created) + return $"[RynthAi] Created new meta '{want}' (one state '{AfFileWriter.BlankState}', no rules) and loaded it."; + int rules, navs; + lock (_settings.MetaRulesLock) { rules = _settings.MetaRules.Count; navs = _settings.EmbeddedNavs.Count; } + var warnings = _metaUi.LastLoadWarnings; + return $"[RynthAi] Loaded meta '{want}': {rules} rules, {navs} navs" + + (warnings.Count > 0 ? $" — {warnings.Count} warning(s): {warnings[0]}" : ""); + } + + /// /ra meta list: the metas in MetaFiles (file names, with extension). + public List MetaFileNames() + { + RefreshMetaFiles(); + lock (_profileListsLock) + return _metaFiles.FindAll(f => f != "None"); } /// /ra nav list: the .nav files in NavProfiles. diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs index b55ec10..a30f278 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs @@ -1178,7 +1178,9 @@ internal sealed class LegacyMetaUi } LastLoadWarnings = loaded.Warnings; - if (loaded.Rules.Count == 0) + // A blank meta (a state, no rules) loads: it clears the old rules. Anything else + // without rules (a profile, an empty file) is refused as before. + if (loaded.Rules.Count == 0 && !loaded.IsBlank) { _statusMessage = loaded.Warnings.Count > 0 ? $"No rules parsed — {loaded.Warnings.Count} warning(s): {loaded.Warnings[0]}" @@ -1218,6 +1220,15 @@ internal sealed class LegacyMetaUi /// The status line of the last load (why it failed, or what it loaded). internal string LastLoadStatus => _statusMessage ?? string.Empty; + /// + /// Lists MetaFiles again once the panel has listed it (a meta /ra meta load just created shows + /// in the picker, selected). Before the panel's first draw it lists itself then. + /// + internal void RefreshFileListIfShown() + { + if (_macroFiles.Count > 0) RefreshMacroFileList(); + } + private void TryAutoSaveMeta() { diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NewProfileFiles.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NewProfileFiles.cs new file mode 100644 index 0000000..60cc93b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NewProfileFiles.cs @@ -0,0 +1,155 @@ +using System; +using System.Collections.Generic; +using System.IO; +using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi.LegacyUi; + +/// What / did. +internal enum ProfileFileResult +{ + /// The file exists; nothing was written. + Found, + /// There was no such file: a blank one was written. + Created, + /// The name can't be a file name (the error says why); nothing was written. + Rejected, + /// The blank file couldn't be written (the error says why and the fix). + Failed, + /// Create only (/ra meta new): the file already exists; nothing was written. + Exists, +} + +/// +/// "Load makes a new one", as in VTank (2026-10-13): /ra nav load <name> (and /vt nav load) +/// and /ra meta load <name> (and /vt meta load) create a blank <name> when there is no +/// such file, then load it, so a route can be recorded into it or rules added to it. Here: the +/// name a player typed, made into a file name (or why it can't be one), the lookup in the data +/// folder and the blank files. Writes go through , so a folder the +/// client can't write is reported with the reason and the fix. +/// +internal static class NewProfileFiles +{ + public static readonly string[] NavExtensions = { ".nav" }; + public static readonly string[] MetaExtensions = { ".af", ".met" }; + + /// The route type of a blank nav: VTank's default for a new route. + public const NavRouteType BlankNavType = NavRouteType.Circular; + + /// Longest name accepted (well inside MAX_PATH with the folder). + public const int MaxNameLength = 120; + + private static readonly HashSet ReservedNames = new(StringComparer.OrdinalIgnoreCase) + { + "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", + "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", + "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", + }; + + /// + /// The name as typed, tidied: whitespace trimmed, surrounding quotes dropped, one of + /// stripped ("farm.af" -> "farm"). Not checked: use + /// before using it as a file name. is the + /// extension that was given (with its dot, lower case), else empty. + /// + public static string Tidy(string? raw, IReadOnlyList extensions, out string extension) + { + extension = string.Empty; + string s = (raw ?? string.Empty).Trim(); + if (s.Length >= 2 && (s[0] == '"' || s[0] == '\'') && s[^1] == s[0]) + s = s[1..^1].Trim(); + s = s.Trim('"').Trim(); + foreach (string ext in extensions) + { + if (s.Length > ext.Length && s.EndsWith(ext, StringComparison.OrdinalIgnoreCase)) + { + extension = ext.ToLowerInvariant(); + s = s[..^ext.Length].TrimEnd(); + break; + } + } + return s; + } + + /// Null when (tidied) is safe as a file name in a data folder, else why not. + public static string? Validate(string name) + { + if (string.IsNullOrWhiteSpace(name)) return "no name given"; + if (name.IndexOf('/') >= 0 || name.IndexOf('\\') >= 0) return "no folders, just a name"; + if (name.Contains("..", StringComparison.Ordinal)) return "\"..\" isn't allowed in a name"; + if (name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) return "a file name can't contain \\ / : * ? \" < > |"; + if (name.EndsWith('.') || name.EndsWith(' ')) return "a file name can't end with a dot or a space"; + if (name.Length > MaxNameLength) return $"longer than {MaxNameLength} characters"; + int dot = name.IndexOf('.'); + string stem = (dot >= 0 ? name[..dot] : name).TrimEnd(); + if (ReservedNames.Contains(stem)) return $"\"{stem}\" is a name Windows reserves"; + return null; + } + + /// The empty route a new nav starts as. + public static NavRouteParser BlankNav() => new() { RouteType = BlankNavType }; + + /// + /// \<name>.nav for the name typed: found, or created blank + /// (VTank format: header, route type Circular, 0 points). is the tidied + /// name, the file (empty when rejected), why + /// it was rejected or couldn't be written. + /// + public static ProfileFileResult FindOrCreateNav(string folder, string? raw, + out string name, out string path, out string error) + { + name = Tidy(raw, NavExtensions, out _); + path = string.Empty; + error = Validate(name) ?? string.Empty; + if (error.Length > 0) return ProfileFileResult.Rejected; + + path = Path.Combine(folder, name + ".nav"); + if (File.Exists(path)) return ProfileFileResult.Found; + + string target = path; + NavRouteParser route = BlankNav(); + if (!DataWriteGuard.TrySave("the new nav", target, () => route.Save(target), out error, callerShows: true)) + return ProfileFileResult.Failed; + return ProfileFileResult.Created; + } + + /// + /// The meta for the name typed in : the extension given first + /// ("farm.met"), else <name>.af, else <name>.met; when there is none, <name>.af + /// is created blank (one state "Default", no rules). (/ra meta new): + /// an existing file is and nothing is written. + /// + public static ProfileFileResult FindOrCreateMeta(string folder, string? raw, + out string name, out string path, out string error, bool createOnly = false) + { + name = Tidy(raw, MetaExtensions, out string given); + path = string.Empty; + error = Validate(name) ?? string.Empty; + if (error.Length > 0) return ProfileFileResult.Rejected; + + var order = new List(3); + if (given.Length > 0) order.Add(given); + foreach (string e in MetaExtensions) + if (!order.Contains(e)) order.Add(e); + foreach (string e in order) + { + string candidate = Path.Combine(folder, name + e); + if (File.Exists(candidate)) + { + path = candidate; + return createOnly ? ProfileFileResult.Exists : ProfileFileResult.Found; + } + } + + path = Path.Combine(folder, name + ".af"); // a .met can't be written: new metas are .af + string target = path; + if (!DataWriteGuard.TrySave("the new meta", target, () => + { + Directory.CreateDirectory(Path.GetDirectoryName(target) ?? "."); + File.WriteAllText(target, AfFileWriter.BlankMetaText()); + }, out error, callerShows: true)) + return ProfileFileResult.Failed; + return ProfileFileResult.Created; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileParser.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileParser.cs index 14c9462..631b261 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileParser.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileParser.cs @@ -63,6 +63,7 @@ internal static class AfFileParser if (trimmed.StartsWith("STATE:")) { + result.DeclaredStates.Add(ExtractBraceContent(lines[idx], out _)); ParseState(lines, ref idx, result.Rules); } else if (trimmed.StartsWith("NAVDATA:")) @@ -565,17 +566,11 @@ internal static class AfFileParser case MetaActionType.EmbeddedNavRoute: { // EmbedNav navname {type/filename} + // (metaf: EmbedNav tag {name} {transform}; the tag names the NAV block.) + // Stray brackets go ("None]" from VTank's "[None]"), the same as on the NAV keys. int braceStart = rest.IndexOf('{'); - if (braceStart >= 0) - { - string navName = rest.Substring(0, braceStart).Trim(); - // Store nav name as ActionData — will be resolved later - rule.ActionData = navName; - } - else - { - rule.ActionData = rest.Trim(); - } + string navName = braceStart >= 0 ? rest.Substring(0, braceStart) : rest; + rule.ActionData = EmbedNavName.Clean(navName); break; } @@ -653,6 +648,7 @@ internal static class AfFileParser if (idx < lines.Length && lines[idx].Trim() == "~~ }") idx++; // consume closer + name = EmbedNavName.Clean(name); if (!string.IsNullOrEmpty(name) && navLines.Count >= 3) navRoutes[name] = navLines; } @@ -670,7 +666,7 @@ internal static class AfFileParser // Parse "navname type" string[] parts = afterNav.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); - string navName = parts.Length > 0 ? parts[0] : ""; + string navName = EmbedNavName.Clean(parts.Length > 0 ? parts[0] : ""); string navType = parts.Length > 1 ? parts[1] : "circular"; idx++; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs index 975678b..270a24e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs @@ -47,6 +47,14 @@ internal static class AfFileWriter var navNames = new HashSet(StringComparer.OrdinalIgnoreCase); CollectNavNames(rules, navNames); + // No rules: an empty "Default" state, so the file is still a meta that loads (a blank + // meta that had its last rule deleted). An empty file is refused as "no rules" (2026-10-13). + if (grouped.Count == 0) + { + WriteBlankState(writer); + return; + } + // Write states foreach (var group in grouped) { @@ -64,6 +72,26 @@ internal static class AfFileWriter } } + /// The state a blank meta has. + public const string BlankState = "Default"; + + /// + /// A blank meta: one state, , with no rules. What /ra meta load and + /// /vt meta load create for a name that doesn't exist (VTank's "load makes a new one"). + /// + public static string BlankMetaText() + { + using var writer = new StringWriter(CultureInfo.InvariantCulture); + WriteBlankState(writer); + return writer.ToString(); + } + + private static void WriteBlankState(TextWriter writer) + { + writer.WriteLine($"STATE: {{{BlankState}}} ~~ {{"); + writer.WriteLine("~~ }"); + } + // ── Rule writing ──────────────────────────────────────────────────────── /// A rule name on one line (it is written as a "~~ @name" comment line). diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/EmbedNavName.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/EmbedNavName.cs new file mode 100644 index 0000000..671cb0f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/EmbedNavName.cs @@ -0,0 +1,57 @@ +using System; + +namespace RynthCore.Plugin.RynthAi.Meta; + +/// +/// The name an Embedded Nav Route action and an embedded route share (2026-10-13). +/// +/// VTank shows a route that has no file name as "[None]". A player's meta reached RynthAi with +/// that name broken into "None]" on both the action and its route (log: "EmbedNav: loaded 'None]' +/// (1 pts)"), and an action naming "[None]" with no route behind it went looking for a nav file +/// called "[None].nav" and reported "Route missing". Every reader cleans names the same way: +/// whitespace, and brackets that wrap the whole name or have no partner ("[None]", "None]", +/// "[None" -> "None"). Brackets inside a name ("Hive [East]") are kept. +/// +/// "None" itself is not "no route": VTank stores a route that was recorded but never saved under +/// "[None]" with all its points (a 213-point one in S_Tusks.met, a one-point hunt spot in CQ metas) +/// and loads it. Only a None with nothing behind it means "no embedded nav": MetaManager then keeps +/// the current route. +/// +internal static class EmbedNavName +{ + public const string None = "None"; + + /// The name without surrounding whitespace and stray or wrapping brackets. + public static string Clean(string? name) + { + string s = (name ?? string.Empty).Trim(); + for (int guard = 0; guard < 4 && s.Length > 0; guard++) + { + bool open = s[0] == '[', close = s[^1] == ']'; + if (open && close && s.Length >= 2 && Balanced(s, 1, s.Length - 1)) + s = s.Substring(1, s.Length - 2).Trim(); // "[None]" + else if (close && s.IndexOf('[') < 0) + s = s.Substring(0, s.Length - 1).Trim(); // "None]" + else if (open && s.IndexOf(']') < 0) + s = s.Substring(1).Trim(); // "[None" + else + break; + } + return s; + } + + /// VTank's name for a route with no file name ("[None]", any case, stray brackets too). + public static bool IsNone(string? name) => string.Equals(Clean(name), None, StringComparison.OrdinalIgnoreCase); + + /// True when s[from..to) has no ']' before its '[' (so "[a] [b]" is not unwrapped to "a] [b"). + private static bool Balanced(string s, int from, int to) + { + int depth = 0; + for (int i = from; i < to; i++) + { + if (s[i] == '[') depth++; + else if (s[i] == ']' && --depth < 0) return false; + } + return depth == 0; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/LoadedMeta.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/LoadedMeta.cs index af33344..36f9402 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/LoadedMeta.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/LoadedMeta.cs @@ -23,6 +23,20 @@ internal sealed class LoadedMeta /// public List Warnings { get; } = new(); + /// + /// Every "STATE: {name}" the .af declares, in file order, including states with no rules + /// (a .met has no empty states: its states only exist through rules, so this stays empty). + /// + public List DeclaredStates { get; } = new(); + + /// + /// A blank meta: it declares a state, has no rules and parsed cleanly (what + /// /ra meta load and /vt meta load create for a name that doesn't exist, 2026-10-13). + /// It is loaded like any meta (the old rules are cleared), where a file with no rules + /// and no state (a profile, an empty file) is still refused. + /// + public bool IsBlank => Rules.Count == 0 && DeclaredStates.Count > 0 && Warnings.Count == 0; + /// /// The state a freshly loaded meta starts in. VTank always starts a meta in /// "Default"; RynthAi used the first rule's state, and its writer sorts @@ -37,7 +51,11 @@ internal sealed class LoadedMeta foreach (var r in Rules) if (string.Equals(r.State, "Default", StringComparison.OrdinalIgnoreCase)) return r.State; - return Rules.Count > 0 ? Rules[0].State : "Default"; + if (Rules.Count > 0) return Rules[0].State; + foreach (string s in DeclaredStates) + if (string.Equals(s, "Default", StringComparison.OrdinalIgnoreCase)) + return s; + return DeclaredStates.Count > 0 ? DeclaredStates[0] : "Default"; } } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs index 0365ae2..0bebed8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs @@ -900,12 +900,24 @@ internal sealed class MetaManager RynthLog.Write(LogCat.Meta, "[Meta] EmbedNav: empty ActionData, ignored"); break; } - string routeName = rule.ActionData.Split(';')[0]; + string routeName = EmbedNavName.Clean(rule.ActionData.Split(';')[0]); int priorPoints = _settings.CurrentRoute?.Points?.Count ?? 0; try { // Embedded nav routes live in memory alongside the loaded meta. + // A key saved before names were cleaned ("None]", "[None]") still matches. + if (!_settings.EmbeddedNavs.ContainsKey(routeName)) + { + foreach (var key in _settings.EmbeddedNavs.Keys) + { + if (string.Equals(EmbedNavName.Clean(key), routeName, StringComparison.OrdinalIgnoreCase)) + { + routeName = key; + break; + } + } + } // If the direct key misses, try normalizing legacy names // like "nav0__MatronHive1_nav" → "MatronHive1". if (!_settings.EmbeddedNavs.ContainsKey(routeName)) @@ -938,6 +950,20 @@ internal sealed class MetaManager break; } + // VTank's "[None]" with no route behind it (no embedded route of that name, or an + // empty one) is an empty nav route, as in VTank: the current route is cleared, and no + // "None.nav" is looked for. A [None] route WITH points is a real route VTank loads + // (see EmbedNavName). + if (EmbedNavName.IsNone(routeName) + && (!_settings.EmbeddedNavs.TryGetValue(routeName, out var noneLines) || NavRouteParser.LoadFromLines(noneLines).Points.Count == 0)) + { + _settings.CurrentNavPath = string.Empty; + _settings.CurrentRoute = new NavRouteParser(); + _settings.ActiveNavIndex = 0; + RynthLog.Write(LogCat.Meta, $"[Meta] EmbedNav: [None] - empty route (was {priorPoints} pts)"); + break; + } + if (_settings.EmbeddedNavs.TryGetValue(routeName, out var embedded)) { var newRoute = NavRouteParser.LoadFromLines(embedded); @@ -1145,50 +1171,13 @@ internal sealed class MetaManager return true; } - // /vt meta load — load a meta file from MetaFiles folder + // /vt meta load — the same load as /ra meta load (LegacyDashboardRenderer.LoadMetaByName): + // a meta in MetaFiles, or, when there is none by that name, a new blank one (2026-10-13). if (sub == "meta" && parts.Length >= 4 && parts[2].Equals("load", StringComparison.OrdinalIgnoreCase)) { string name = string.Join(" ", parts, 3, parts.Length - 3); - string metaDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles"); - string afPath = Path.Combine(metaDir, name + ".af"); - string metPath = Path.Combine(metaDir, name + ".met"); - - string loadPath = File.Exists(afPath) ? afPath : File.Exists(metPath) ? metPath : ""; - if (!string.IsNullOrEmpty(loadPath)) - { - try - { - LoadedMeta loaded = loadPath.EndsWith(".met", StringComparison.OrdinalIgnoreCase) - ? MetFileParser.Load(loadPath) - : AfFileParser.Load(loadPath); - if (loaded.Rules.Count > 0) - { - _settings.MetaRules = loaded.Rules; - _settings.EmbeddedNavs.Clear(); - foreach (var kvp in loaded.EmbeddedNavs) - _settings.EmbeddedNavs[kvp.Key] = kvp.Value; - _settings.CurrentState = loaded.StartState; - _settings.ForceStateReset = true; - _settings.MetaCallStackReset = true; - _settings.CurrentMetaPath = loadPath; - _host.WriteToChat( - $"[RynthAi] Loaded meta '{name}': {loaded.Rules.Count} rules, {loaded.EmbeddedNavs.Count} navs" - + (loaded.Warnings.Count > 0 ? $" — {loaded.Warnings.Count} warning(s): {loaded.Warnings[0]}" : ""), 1); - } - else - { - _host.WriteToChat( - $"[RynthAi] Meta '{name}' parsed 0 rules" - + (loaded.Warnings.Count > 0 ? $" — {loaded.Warnings[0]}" : " (profile/empty?)"), 1); - } - } - catch { } - } - else - { - _host.WriteToChat($"[RynthAi] Meta not found: {name}", 1); - } + _raCommandHandler?.Invoke($"/ra meta load {name}"); return true; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/PropertyNames.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/PropertyNames.cs index 9563aef..4042c0f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/PropertyNames.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/PropertyNames.cs @@ -4,7 +4,7 @@ namespace RynthCore.Plugin.RynthAi.Meta; /// /// AC property-id → name, generated from ACE's PropertyInt/PropertyBool/ -/// PropertyString enums. SPARSE on purpose: the real AC enums have gaps, so the +/// PropertyString/PropertyInt64/PropertyFloat/PropertyDataId/PropertyInstanceId enums. SPARSE on purpose: the real AC enums have gaps, so the /// old dense position-indexed string[] mislabelled every property after the /// first gap (the bug the SalvageManager STypes constants worked around). /// Used by the dumpprops diagnostic. Returns null for unknown ids. @@ -637,7 +637,359 @@ internal static class PropertyNames { 9007, "TinkerLog" }, }; + private static readonly Dictionary Int64Names = new() + { + { 0, "Undef" }, + { 1, "TotalExperience" }, + { 2, "AvailableExperience" }, + { 3, "AugmentationCost" }, + { 4, "ItemTotalXp" }, + { 5, "ItemBaseXp" }, + { 6, "AvailableLuminance" }, + { 7, "MaximumLuminance" }, + { 8, "InteractionReqs" }, + { 9000, "AllegianceXPCached" }, + { 9001, "AllegianceXPGenerated" }, + { 9002, "AllegianceXPReceived" }, + { 9003, "VerifyXp" }, + }; + + private static readonly Dictionary FloatNames = new() + { + { 0, "Undef" }, + { 1, "HeartbeatInterval" }, + { 2, "HeartbeatTimestamp" }, + { 3, "HealthRate" }, + { 4, "StaminaRate" }, + { 5, "ManaRate" }, + { 6, "HealthUponResurrection" }, + { 7, "StaminaUponResurrection" }, + { 8, "ManaUponResurrection" }, + { 9, "StartTime" }, + { 10, "StopTime" }, + { 11, "ResetInterval" }, + { 12, "Shade" }, + { 13, "ArmorModVsSlash" }, + { 14, "ArmorModVsPierce" }, + { 15, "ArmorModVsBludgeon" }, + { 16, "ArmorModVsCold" }, + { 17, "ArmorModVsFire" }, + { 18, "ArmorModVsAcid" }, + { 19, "ArmorModVsElectric" }, + { 20, "CombatSpeed" }, + { 21, "WeaponLength" }, + { 22, "DamageVariance" }, + { 23, "CurrentPowerMod" }, + { 24, "AccuracyMod" }, + { 25, "StrengthMod" }, + { 26, "MaximumVelocity" }, + { 27, "RotationSpeed" }, + { 28, "MotionTimestamp" }, + { 29, "WeaponDefense" }, + { 30, "WimpyLevel" }, + { 31, "VisualAwarenessRange" }, + { 32, "AuralAwarenessRange" }, + { 33, "PerceptionLevel" }, + { 34, "PowerupTime" }, + { 35, "MaxChargeDistance" }, + { 36, "ChargeSpeed" }, + { 37, "BuyPrice" }, + { 38, "SellPrice" }, + { 39, "DefaultScale" }, + { 40, "LockpickMod" }, + { 41, "RegenerationInterval" }, + { 42, "RegenerationTimestamp" }, + { 43, "GeneratorRadius" }, + { 44, "TimeToRot" }, + { 45, "DeathTimestamp" }, + { 46, "PkTimestamp" }, + { 47, "VictimTimestamp" }, + { 48, "LoginTimestamp" }, + { 49, "CreationTimestamp" }, + { 50, "MinimumTimeSincePk" }, + { 51, "DeprecatedHousekeepingPriority" }, + { 52, "AbuseLoggingTimestamp" }, + { 53, "LastPortalTeleportTimestamp" }, + { 54, "UseRadius" }, + { 55, "HomeRadius" }, + { 56, "ReleasedTimestamp" }, + { 57, "MinHomeRadius" }, + { 58, "Facing" }, + { 59, "ResetTimestamp" }, + { 60, "LogoffTimestamp" }, + { 61, "EconRecoveryInterval" }, + { 62, "WeaponOffense" }, + { 63, "DamageMod" }, + { 64, "ResistSlash" }, + { 65, "ResistPierce" }, + { 66, "ResistBludgeon" }, + { 67, "ResistFire" }, + { 68, "ResistCold" }, + { 69, "ResistAcid" }, + { 70, "ResistElectric" }, + { 71, "ResistHealthBoost" }, + { 72, "ResistStaminaDrain" }, + { 73, "ResistStaminaBoost" }, + { 74, "ResistManaDrain" }, + { 75, "ResistManaBoost" }, + { 76, "Translucency" }, + { 77, "PhysicsScriptIntensity" }, + { 78, "Friction" }, + { 79, "Elasticity" }, + { 80, "AiUseMagicDelay" }, + { 81, "ItemMinSpellcraftMod" }, + { 82, "ItemMaxSpellcraftMod" }, + { 83, "ItemRankProbability" }, + { 84, "Shade2" }, + { 85, "Shade3" }, + { 86, "Shade4" }, + { 87, "ItemEfficiency" }, + { 88, "ItemManaUpdateTimestamp" }, + { 89, "SpellGestureSpeedMod" }, + { 90, "SpellStanceSpeedMod" }, + { 91, "AllegianceAppraisalTimestamp" }, + { 92, "PowerLevel" }, + { 93, "AccuracyLevel" }, + { 94, "AttackAngle" }, + { 95, "AttackTimestamp" }, + { 96, "CheckpointTimestamp" }, + { 97, "SoldTimestamp" }, + { 98, "UseTimestamp" }, + { 99, "UseLockTimestamp" }, + { 100, "HealkitMod" }, + { 101, "FrozenTimestamp" }, + { 102, "HealthRateMod" }, + { 103, "AllegianceSwearTimestamp" }, + { 104, "ObviousRadarRange" }, + { 105, "HotspotCycleTime" }, + { 106, "HotspotCycleTimeVariance" }, + { 107, "SpamTimestamp" }, + { 108, "SpamRate" }, + { 109, "BondWieldedTreasure" }, + { 110, "BulkMod" }, + { 111, "SizeMod" }, + { 112, "GagTimestamp" }, + { 113, "GeneratorUpdateTimestamp" }, + { 114, "DeathSpamTimestamp" }, + { 115, "DeathSpamRate" }, + { 116, "WildAttackProbability" }, + { 117, "FocusedProbability" }, + { 118, "CrashAndTurnProbability" }, + { 119, "CrashAndTurnRadius" }, + { 120, "CrashAndTurnBias" }, + { 121, "GeneratorInitialDelay" }, + { 122, "AiAcquireHealth" }, + { 123, "AiAcquireStamina" }, + { 124, "AiAcquireMana" }, + { 125, "ResistHealthDrain" }, + { 126, "LifestoneProtectionTimestamp" }, + { 127, "AiCounteractEnchantment" }, + { 128, "AiDispelEnchantment" }, + { 129, "TradeTimestamp" }, + { 130, "AiTargetedDetectionRadius" }, + { 131, "EmotePriority" }, + { 132, "LastTeleportStartTimestamp" }, + { 133, "EventSpamTimestamp" }, + { 134, "EventSpamRate" }, + { 135, "InventoryOffset" }, + { 136, "CriticalMultiplier" }, + { 137, "ManaStoneDestroyChance" }, + { 138, "SlayerDamageBonus" }, + { 139, "AllegianceInfoSpamTimestamp" }, + { 140, "AllegianceInfoSpamRate" }, + { 141, "NextSpellcastTimestamp" }, + { 142, "AppraisalRequestedTimestamp" }, + { 143, "AppraisalHeartbeatDueTimestamp" }, + { 144, "ManaConversionMod" }, + { 145, "LastPkAttackTimestamp" }, + { 146, "FellowshipUpdateTimestamp" }, + { 147, "CriticalFrequency" }, + { 148, "LimboStartTimestamp" }, + { 149, "WeaponMissileDefense" }, + { 150, "WeaponMagicDefense" }, + { 151, "IgnoreShield" }, + { 152, "ElementalDamageMod" }, + { 153, "StartMissileAttackTimestamp" }, + { 154, "LastRareUsedTimestamp" }, + { 155, "IgnoreArmor" }, + { 156, "ProcSpellRate" }, + { 157, "ResistanceModifier" }, + { 158, "AllegianceGagTimestamp" }, + { 159, "AbsorbMagicDamage" }, + { 160, "CachedMaxAbsorbMagicDamage" }, + { 161, "GagDuration" }, + { 162, "AllegianceGagDuration" }, + { 163, "GlobalXpMod" }, + { 164, "HealingModifier" }, + { 165, "ArmorModVsNether" }, + { 166, "ResistNether" }, + { 167, "CooldownDuration" }, + { 168, "WeaponAuraOffense" }, + { 169, "WeaponAuraDefense" }, + { 170, "WeaponAuraElemental" }, + { 171, "WeaponAuraManaConv" }, + { 8004, "PCAPRecordedWorkmanship" }, + { 8010, "PCAPRecordedVelocityX" }, + { 8011, "PCAPRecordedVelocityY" }, + { 8012, "PCAPRecordedVelocityZ" }, + { 8013, "PCAPRecordedAccelerationX" }, + { 8014, "PCAPRecordedAccelerationY" }, + { 8015, "PCAPRecordedAccelerationZ" }, + { 8016, "PCAPRecordeOmegaX" }, + { 8017, "PCAPRecordeOmegaY" }, + { 8018, "PCAPRecordeOmegaZ" }, + }; + + private static readonly Dictionary DataIdNames = new() + { + { 0, "Undef" }, + { 1, "Setup" }, + { 2, "MotionTable" }, + { 3, "SoundTable" }, + { 4, "CombatTable" }, + { 5, "QualityFilter" }, + { 6, "PaletteBase" }, + { 7, "ClothingBase" }, + { 8, "Icon" }, + { 9, "EyesTexture" }, + { 10, "NoseTexture" }, + { 11, "MouthTexture" }, + { 12, "DefaultEyesTexture" }, + { 13, "DefaultNoseTexture" }, + { 14, "DefaultMouthTexture" }, + { 15, "HairPalette" }, + { 16, "EyesPalette" }, + { 17, "SkinPalette" }, + { 18, "HeadObject" }, + { 19, "ActivationAnimation" }, + { 20, "InitMotion" }, + { 21, "ActivationSound" }, + { 22, "PhysicsEffectTable" }, + { 23, "UseSound" }, + { 24, "UseTargetAnimation" }, + { 25, "UseTargetSuccessAnimation" }, + { 26, "UseTargetFailureAnimation" }, + { 27, "UseUserAnimation" }, + { 28, "Spell" }, + { 29, "SpellComponent" }, + { 30, "PhysicsScript" }, + { 31, "LinkedPortalOne" }, + { 32, "WieldedTreasureType" }, + { 33, "InventoryTreasureType" }, + { 34, "ShopTreasureType" }, + { 35, "DeathTreasureType" }, + { 36, "MutateFilter" }, + { 37, "ItemSkillLimit" }, + { 38, "UseCreateItem" }, + { 39, "DeathSpell" }, + { 40, "VendorsClassId" }, + { 41, "ItemSpecializedOnly" }, + { 42, "HouseId" }, + { 43, "AccountHouseId" }, + { 44, "RestrictionEffect" }, + { 45, "CreationMutationFilter" }, + { 46, "TsysMutationFilter" }, + { 47, "LastPortal" }, + { 48, "LinkedPortalTwo" }, + { 49, "OriginalPortal" }, + { 50, "IconOverlay" }, + { 51, "IconOverlaySecondary" }, + { 52, "IconUnderlay" }, + { 53, "AugmentationMutationFilter" }, + { 54, "AugmentationEffect" }, + { 55, "ProcSpell" }, + { 56, "AugmentationCreateItem" }, + { 57, "AlternateCurrency" }, + { 58, "BlueSurgeSpell" }, + { 59, "YellowSurgeSpell" }, + { 60, "RedSurgeSpell" }, + { 61, "OlthoiDeathTreasureType" }, + { 8001, "PCAPRecordedWeenieHeader" }, + { 8002, "PCAPRecordedWeenieHeader2" }, + { 8003, "PCAPRecordedObjectDesc" }, + { 8005, "PCAPRecordedPhysicsDesc" }, + { 8009, "PCAPRecordedParentLocation" }, + { 8019, "PCAPRecordedDefaultScript" }, + { 8020, "PCAPRecordedTimestamp0" }, + { 8021, "PCAPRecordedTimestamp1" }, + { 8022, "PCAPRecordedTimestamp2" }, + { 8023, "PCAPRecordedTimestamp3" }, + { 8024, "PCAPRecordedTimestamp4" }, + { 8025, "PCAPRecordedTimestamp5" }, + { 8026, "PCAPRecordedTimestamp6" }, + { 8027, "PCAPRecordedTimestamp7" }, + { 8028, "PCAPRecordedTimestamp8" }, + { 8029, "PCAPRecordedTimestamp9" }, + { 8030, "PCAPRecordedMaxVelocityEstimated" }, + { 8044, "PCAPPhysicsDIDDataTemplatedFrom" }, + }; + + private static readonly Dictionary InstanceIdNames = new() + { + { 0, "Undef" }, + { 1, "Owner" }, + { 2, "Container" }, + { 3, "Wielder" }, + { 4, "Freezer" }, + { 5, "Viewer" }, + { 6, "Generator" }, + { 7, "Scribe" }, + { 8, "CurrentCombatTarget" }, + { 9, "CurrentEnemy" }, + { 10, "ProjectileLauncher" }, + { 11, "CurrentAttacker" }, + { 12, "CurrentDamager" }, + { 13, "CurrentFollowTarget" }, + { 14, "CurrentAppraisalTarget" }, + { 15, "CurrentFellowshipAppraisalTarget" }, + { 16, "ActivationTarget" }, + { 17, "Creator" }, + { 18, "Victim" }, + { 19, "Killer" }, + { 20, "Vendor" }, + { 21, "Customer" }, + { 22, "Bonded" }, + { 23, "Wounder" }, + { 24, "Allegiance" }, + { 25, "Patron" }, + { 26, "Monarch" }, + { 27, "CombatTarget" }, + { 28, "HealthQueryTarget" }, + { 29, "LastUnlocker" }, + { 30, "CrashAndTurnTarget" }, + { 31, "AllowedActivator" }, + { 32, "HouseOwner" }, + { 33, "House" }, + { 34, "Slumlord" }, + { 35, "ManaQueryTarget" }, + { 36, "CurrentGame" }, + { 37, "RequestedAppraisalTarget" }, + { 38, "AllowedWielder" }, + { 39, "AssignedTarget" }, + { 40, "LimboSource" }, + { 41, "Snooper" }, + { 42, "TeleportedCharacter" }, + { 43, "Pet" }, + { 44, "PetOwner" }, + { 45, "PetDevice" }, + { 8000, "PCAPRecordedObjectIID" }, + { 8008, "PCAPRecordedParentIID" }, + }; + public static string? GetIntName(uint id) => IntNames.TryGetValue(id, out var n) ? n : null; public static string? GetBoolName(uint id) => BoolNames.TryGetValue(id, out var n) ? n : null; public static string? GetStringName(uint id) => StringNames.TryGetValue(id, out var n) ? n : null; + public static string? GetInt64Name(uint id) => Int64Names.TryGetValue(id, out var n) ? n : null; + public static string? GetFloatName(uint id) => FloatNames.TryGetValue(id, out var n) ? n : null; + public static string? GetDataIdName(uint id) => DataIdNames.TryGetValue(id, out var n) ? n : null; + public static string? GetInstanceIdName(uint id) => InstanceIdNames.TryGetValue(id, out var n) ? n : null; + + // Every named key per type (propertydump's per-key probe on an engine before plugin API 84). + public static IEnumerable IntKeys => IntNames.Keys; + public static IEnumerable Int64Keys => Int64Names.Keys; + public static IEnumerable BoolKeys => BoolNames.Keys; + public static IEnumerable FloatKeys => FloatNames.Keys; + public static IEnumerable StringKeys => StringNames.Keys; + public static IEnumerable DataIdKeys => DataIdNames.Keys; + public static IEnumerable InstanceIdKeys => InstanceIdNames.Keys; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index 7c40aa0..31308d5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -206,6 +206,22 @@ public static unsafe class PluginExports [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentRemoved", CallConvs = new[] { typeof(CallConvCdecl) })] public static void OnEnchantmentRemoved(uint enchantmentId) => Runtime.OnEnchantmentRemoved(enchantmentId); + // API v78 server messages: only what RynthAiPlugin asked for (SetServerMessageInterest in + // Initialize: the transient-text game event, for "The door is locked!"). `data` lives only + // during the call; the text is copied out by the parser. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnServerMessage", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnServerMessage(uint opcode, byte* data, int length) + { + try + { + var msg = RynthCore.PluginSdk.Net.ServerMessage.FromCallback(opcode, data, length); + if (msg.IsGameEvent && msg.EventType == RynthCore.PluginSdk.Net.GameEventType.TransientString + && RynthCore.PluginSdk.Net.SystemText.TryParse(msg.EventBody, true, out var text)) + Runtime.Plugin?.NoteDoorServerText(text.Text); + } + catch { } + } + // ── Snapshot bridge for the engine-side Avalonia RynthAi panel ────────── // The panel polls these exports every ~250ms to mirror the live dashboard. // The returned ANSI buffer is freed on the next call; the caller MUST copy diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 66b5cb0..f8897dd 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -64,8 +64,11 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra navdebug — show nav coordinate/debug info"); ChatLine("[RynthAi] /ra addnavpt — append a waypoint at current location to loaded nav"); ChatLine("[RynthAi] /ra nav save [name] — save the route; a name saves it as .nav"); - ChatLine("[RynthAi] /ra nav load — load a nav from NavProfiles"); + ChatLine("[RynthAi] /ra nav load — load a nav from NavProfiles (none by that name: a new empty one)"); ChatLine("[RynthAi] /ra nav list — list the navs in NavProfiles"); + ChatLine("[RynthAi] /ra meta load — load a meta from MetaFiles (none by that name: a new blank one)"); + ChatLine("[RynthAi] /ra meta new — create a blank meta and load it"); + ChatLine("[RynthAi] /ra meta list — list the metas in MetaFiles"); ChatLine("[RynthAi] /ra lua run — run a RynthLua script (same as /lua run; also stop, list, exec )"); ChatLine("[RynthAi] /ra items fill — add weapons, healing kits, lockpicks and pet essences from your pack"); ChatLine("[RynthAi] /ra offhand [auto|shield|weapon|none] [rule] — the off hand (shield / dual wield), global or for a Monsters rule; dual on|off"); @@ -765,126 +768,6 @@ public sealed partial class RynthAiPlugin ChatLine($"[RynthAi] {kv.Key} = {kv.Value}"); } - /// - /// /ra dumpprops [0xId] (and /ub propertydump): every property of the given object, else - /// the selected one, else the character - as UB's propertydump does. It was always the - /// character, whatever was selected. - /// - private void HandleDumpPropsCommand(string[] parts) - { - uint me = Host.GetPlayerId(); - if (me == 0) - { - ChatLine("[RynthAi] Not logged in."); - return; - } - uint playerId = me; // the object dumped (the name below predates the target choice) - if (parts.Length >= 3 && uint.TryParse(parts[2].StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? parts[2][2..] : parts[2], - System.Globalization.NumberStyles.HexNumber, null, out uint given) && given != 0) - playerId = given; - else if (_currentTargetId != 0) - playerId = _currentTargetId; - string label = Host.TryGetObjectName(playerId, out string nm) && nm.Length > 0 ? nm : "?"; - ChatLine($"[RynthAi] === Properties of {label} (0x{playerId:X8}){(playerId == me ? " - nothing selected, your character" : "")} ==="); - - // Int properties 0-400 - int intCount = 0; - if (Host.HasGetObjectIntProperty) - { - ChatLine("[RynthAi] === Int Properties (0-400) ==="); - for (uint i = 0; i <= 400; i++) - { - if (Host.TryGetObjectIntProperty(playerId, i, out int v)) - { - string? name = PropertyNames.GetIntName(i); - ChatLine(name != null - ? $"[RynthAi] IntProp[{i}] = {v} ({name})" - : $"[RynthAi] IntProp[{i}] = {v}"); - intCount++; - } - } - ChatLine($"[RynthAi] Found {intCount} int properties."); - } - else ChatLine("[RynthAi] Int property API not available."); - - // Bool properties 0-300 - int boolCount = 0; - if (Host.HasGetObjectBoolProperty) - { - ChatLine("[RynthAi] === Bool Properties (0-300) ==="); - for (uint i = 0; i <= 300; i++) - { - if (Host.TryGetObjectBoolProperty(playerId, i, out bool v)) - { - string? name = PropertyNames.GetBoolName(i); - ChatLine(name != null - ? $"[RynthAi] BoolProp[{i}] = {(v ? "1" : "0")} ({name})" - : $"[RynthAi] BoolProp[{i}] = {(v ? "1" : "0")}"); - boolCount++; - } - } - ChatLine($"[RynthAi] Found {boolCount} bool properties."); - } - else ChatLine("[RynthAi] Bool property API not available."); - - // String properties 0-60 - int strCount = 0; - if (Host.HasGetObjectStringProperty) - { - ChatLine("[RynthAi] === String Properties (0-60) ==="); - for (uint i = 0; i <= 60; i++) - { - if (Host.TryGetObjectStringProperty(playerId, i, out string v)) - { - string? name = PropertyNames.GetStringName(i); - ChatLine(name != null - ? $"[RynthAi] StringProp[{i}] = {v} ({name})" - : $"[RynthAi] StringProp[{i}] = {v}"); - strCount++; - } - } - ChatLine($"[RynthAi] Found {strCount} string properties."); - } - else ChatLine("[RynthAi] String property API not available."); - - // Int64 (0-12: experience, luminance, item XP), float (0-400), data id (0-80) and - // instance id (0-50) properties, unnamed. Data ids and instance ids print in hex. - int quadCount = 0, floatCount = 0, didCount = 0, iidCount = 0; - if (Host.HasGetObjectQuadProperty) - for (uint i = 0; i <= 12; i++) - if (Host.TryGetObjectQuadProperty(playerId, i, out long q)) - { - ChatLine($"[RynthAi] Int64Prop[{i}] = {q}"); - quadCount++; - } - for (uint i = 0; i <= 400; i++) - if (Host.TryGetObjectDoubleProperty(playerId, i, out double d)) - { - ChatLine($"[RynthAi] FloatProp[{i}] = {d.ToString("0.#####", System.Globalization.CultureInfo.InvariantCulture)}"); - floatCount++; - } - if (Host.HasGetObjectDataIdProperty) - for (uint i = 0; i <= 80; i++) - if (Host.TryGetObjectDataIdProperty(playerId, i, out uint did)) - { - ChatLine($"[RynthAi] DataIdProp[{i}] = 0x{did:X8}"); - didCount++; - } - if (Host.HasGetObjectInstanceIdProperty) - for (uint i = 0; i <= 50; i++) - if (Host.TryGetObjectInstanceIdProperty(playerId, i, out uint iid)) - { - string who = Host.TryGetObjectName(iid, out string wn) && wn.Length > 0 ? $" ({wn})" : ""; - ChatLine($"[RynthAi] InstanceIdProp[{i}] = 0x{iid:X8}{who}"); - iidCount++; - } - - ChatLine($"[RynthAi] Total: {intCount} int, {boolCount} bool, {strCount} string, {quadCount} int64, {floatCount} float, " + - $"{didCount} data id, {iidCount} instance id."); - if (playerId != me && intCount + boolCount + strCount + quadCount + floatCount < 5) - ChatLine("[RynthAi] Few properties: the item may not be identified yet - run it again in a moment."); - } - private void HandleWieldedCommand() { if (_objectCache == null) { ChatLine("[RynthAi] Cache not ready."); return; } @@ -1271,6 +1154,28 @@ public sealed partial class RynthAiPlugin } } + private void HandleMetaCommand(string[] parts) + { + if (_dashboard == null) { ChatLine("[RynthAi] Settings not ready."); return; } + string sub = parts.Length > 2 ? parts[2].ToLowerInvariant() : ""; + string rest = parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3) : ""; + switch (sub) + { + case "load": + case "new": + if (rest.Length == 0) { ChatLine($"[RynthAi] Usage: /ra meta {sub} "); break; } + ChatLine(_dashboard.LoadMetaByName(rest, createOnly: sub == "new")); + break; + case "list": + var names = _dashboard.MetaFileNames(); + ChatLine(names.Count == 0 ? "[RynthAi] No metas in MetaFiles." : $"[RynthAi] Metas ({names.Count}): {string.Join(", ", names)}"); + break; + default: + ChatLine("[RynthAi] /ra meta load | /ra meta new | /ra meta list"); + break; + } + } + private void HandleScanCommand() { if (_objectCache == null) { ChatLine("[RynthAi] Cache not ready."); return; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PropertyDump.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PropertyDump.cs new file mode 100644 index 0000000..2f7e954 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PropertyDump.cs @@ -0,0 +1,264 @@ +using System; +using System.Collections.Generic; +using System.IO; +using RynthCore.Plugin.RynthAi.Diagnostics; +using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// /ra dumpprops [0xId], /ub propertydump, /vt propertydump and the PropertyDump hotkey: every +/// property of the given object, else the selected one, else the character, as UtilityBelt's +/// propertydump lists them. +/// +/// The dump used to ask the engine for fixed key ranges one key at a time (int 0-400, bool 0-300, +/// string 0-60, int64 0-12, float 0-400, data id 0-80, instance id 0-50), so keys outside them were +/// never shown, there was no spell book, and int64 / float / data id / instance id keys had no +/// names. With engine API v84 the engine hands over every key it holds (GetObjectProperties); on an +/// older engine every named key is probed plus the old ranges. An object that isn't identified yet +/// is identified first (RequestId) and dumped when the answer arrives. Chat gets the dump a few +/// lines per tick; the whole dump is also written to RynthAi\Logs\propertydump-<name>-<time>.txt. +/// +public sealed partial class RynthAiPlugin +{ + private sealed class PendingPropertyDump + { + public uint Id; + public string Label = ""; + public bool WaitingForId; + public long IdDeadline; // stop waiting for the identify answer + public long QualitiesDeadline; // stop waiting for the engine's main-thread qualities read + public long NextCheck; + } + + private const long PropertyDumpIdWaitMs = 4000, PropertyDumpQualitiesWaitMs = 1500, PropertyDumpPollMs = 100; + + private readonly object _propertyDumpLock = new(); + private PendingPropertyDump? _pendingPropertyDump; + private readonly Queue _propertyDumpChat = new(); + + /// Clock for the dump's waits; tests replace it. + internal Func PropertyDumpClock = () => Environment.TickCount64; + + private void HandleDumpPropsCommand(string[] parts) + { + uint me = Host.GetPlayerId(); + if (me == 0) + { + ChatLine("[RynthAi] Not logged in."); + return; + } + uint target = me; + if (parts.Length >= 3 && uint.TryParse(parts[2].StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? parts[2][2..] : parts[2], + System.Globalization.NumberStyles.HexNumber, null, out uint given) && given != 0) + target = given; + else if (_currentTargetId != 0) + target = _currentTargetId; + StartPropertyDump(target, me); + } + + internal void StartPropertyDump(uint target, uint me) + { + string label = (Host.TryGetObjectName(target, out string nm) && nm.Length > 0 ? nm : "?") + $" (0x{target:X8})"; + long now = PropertyDumpClock(); + var pending = new PendingPropertyDump + { + Id = target, + Label = label, + QualitiesDeadline = now + PropertyDumpQualitiesWaitMs, + }; + + // Not identified yet: ask, and dump when the answer is in (UtilityBelt shows the object as + // Decal has it, which after an ID is the full appraisal). + if (target != me && Host.HasHasAppraisalData && !Host.HasAppraisalData(target) && Host.HasRequestId) + { + Host.RequestId(target); + pending.WaitingForId = true; + pending.IdDeadline = now + PropertyDumpIdWaitMs; + pending.QualitiesDeadline = pending.IdDeadline + PropertyDumpQualitiesWaitMs; + ChatLine($"[RynthAi] {label} isn't identified yet - asked the server; the property dump follows when the answer arrives."); + } + else if (target == me) + ChatLine($"[RynthAi] Nothing selected - dumping your character, {label}."); + + lock (_propertyDumpLock) + _pendingPropertyDump = pending; + TickPropertyDump(force: !pending.WaitingForId); + } + + /// Every tick: the waiting dump, then a few lines of the dump's chat. + private void TickPropertyDump(bool force = false) + { + PendingPropertyDump? p; + lock (_propertyDumpLock) p = _pendingPropertyDump; + long now = PropertyDumpClock(); + if (p != null && (force || now >= p.NextCheck)) + { + p.NextCheck = now + PropertyDumpPollMs; + string? note = null; + bool ready = true; + if (p.WaitingForId) + { + if (Host.HasAppraisalData(p.Id)) + p.WaitingForId = false; + else if (now >= p.IdDeadline) + { + p.WaitingForId = false; + note = $"No identify answer for {p.Label} within {PropertyDumpIdWaitMs / 1000} s - showing what the client has."; + } + else + ready = false; + } + PropertyDumpData? data = null; + if (ready) + { + data = CollectPropertyDump(p.Id, out bool qualitiesPending); + if (qualitiesPending && now < p.QualitiesDeadline) + ready = false; // the engine reads the client's tables at AC's next tick: ask again + } + if (ready) + { + lock (_propertyDumpLock) + if (ReferenceEquals(_pendingPropertyDump, p)) _pendingPropertyDump = null; + EmitPropertyDump(p, data, note); + } + } + + DrainPropertyDumpChat(); + } + + private void DrainPropertyDumpChat() + { + for (int i = 0; i < PropertyDump.ChatLinesPerTick; i++) + { + string line; + lock (_propertyDumpLock) + { + if (_propertyDumpChat.Count == 0) return; + line = _propertyDumpChat.Dequeue(); + } + ChatLine(line); + } + } + + /// Logout: nothing waits for an object of the session that ended. + private void ClearPropertyDump() + { + lock (_propertyDumpLock) + { + _pendingPropertyDump = null; + _propertyDumpChat.Clear(); + } + } + + private void EmitPropertyDump(PendingPropertyDump p, PropertyDumpData? data, string? note) + { + if (data == null) + { + ChatLine($"[RynthAi] Nothing is known about {p.Label} (not in the client)."); + return; + } + List lines = PropertyDump.Format(data, + id => SpellDatabase.GetSpellName(unchecked((int)id)), + id => Host.TryGetObjectName(id, out string n) && n.Length > 0 ? n : null); + if (note != null) lines.Insert(1, note); + + string fileNote = ""; + try + { + string folder = PropertyDump.Folder; + string path = Path.Combine(folder, PropertyDump.FileName(data.Name.Length > 0 ? data.Name : $"0x{data.Id:X8}", DateTime.Now)); + if (DataWriteGuard.TrySave("Property dump", path, () => + { + Directory.CreateDirectory(folder); + File.WriteAllLines(path, lines); + }, out string reason, callerShows: true)) + fileNote = $"[RynthAi] Full property dump ({lines.Count} lines) written to {path}"; + else + fileNote = $"[RynthAi] The property dump couldn't be written to a file: {reason}"; + } + catch (Exception ex) + { + fileNote = $"[RynthAi] The property dump couldn't be written to a file: {ex.Message}"; + } + + lock (_propertyDumpLock) + { + foreach (string l in lines) _propertyDumpChat.Enqueue("[RynthAi] " + l); + _propertyDumpChat.Enqueue(fileNote); + } + } + + /// + /// Every property of : the engine's whole set (API v84), else per-key reads + /// of every named key and the old fixed ranges. Null when the client knows nothing about it. + /// + internal PropertyDumpData? CollectPropertyDump(uint id, out bool qualitiesPending) + { + qualitiesPending = false; + var d = new PropertyDumpData { Id = id }; + uint me = Host.GetPlayerId(); + d.IsPlayer = id != 0 && id == me; + if (Host.TryGetObjectName(id, out string name)) d.Name = name ?? ""; + if (Host.HasGetObjectWcid) Host.TryGetObjectWcid(id, out d.Wcid); + var wo = _objectCache?[unchecked((int)id)]; + if (wo != null) + { + d.ObjectClass = wo.ObjectClass.ToString(); + d.ObjectClassValue = (int)wo.ObjectClass; + } + d.HasIdData = Host.HasHasAppraisalData && Host.HasAppraisalData(id); + if (Host.HasGetLastIdTime) d.LastIdTime = Host.GetLastIdTime(id); + + if (Host.HasGetObjectProperties) + { + if (!Host.TryGetObjectProperties(id, out ObjectProperties? props) || props == null) + return d.Name.Length > 0 ? d : null; + qualitiesPending = props.QualitiesPending; + d.Complete = true; + d.HasIdData |= props.HasIdData; + if (props.LastIdTime > 0) d.LastIdTime = props.LastIdTime; + foreach (var kv in props.Ints) d.Ints[kv.Key] = kv.Value; + foreach (var kv in props.Int64s) d.Int64s[kv.Key] = kv.Value; + foreach (var kv in props.Bools) d.Bools[kv.Key] = kv.Value; + foreach (var kv in props.Floats) d.Floats[kv.Key] = kv.Value; + foreach (var kv in props.Strings) d.Strings[kv.Key] = kv.Value; + foreach (var kv in props.DataIds) d.DataIds[kv.Key] = kv.Value; + foreach (var kv in props.InstanceIds) d.InstanceIds[kv.Key] = kv.Value; + d.Spells.AddRange(props.Spells); + return d; + } + + // An engine before v84: one key at a time. + if (Host.HasGetObjectIntProperty) + foreach (uint k in PropertyDump.ProbeKeys(PropertyNames.IntKeys, 400)) + if (Host.TryGetObjectIntProperty(id, k, out int v)) d.Ints[k] = v; + if (Host.HasGetObjectQuadProperty) + foreach (uint k in PropertyDump.ProbeKeys(PropertyNames.Int64Keys, 12)) + if (Host.TryGetObjectQuadProperty(id, k, out long v)) d.Int64s[k] = v; + if (Host.HasGetObjectBoolProperty) + foreach (uint k in PropertyDump.ProbeKeys(PropertyNames.BoolKeys, 300)) + if (Host.TryGetObjectBoolProperty(id, k, out bool v)) d.Bools[k] = v; + foreach (uint k in PropertyDump.ProbeKeys(PropertyNames.FloatKeys, 400)) + if (Host.TryGetObjectDoubleProperty(id, k, out double v)) d.Floats[k] = v; + if (Host.HasGetObjectStringProperty) + foreach (uint k in PropertyDump.ProbeKeys(PropertyNames.StringKeys, 60)) + if (Host.TryGetObjectStringProperty(id, k, out string v)) d.Strings[k] = v; + if (Host.HasGetObjectDataIdProperty) + foreach (uint k in PropertyDump.ProbeKeys(PropertyNames.DataIdKeys, 80)) + if (Host.TryGetObjectDataIdProperty(id, k, out uint v)) d.DataIds[k] = v; + if (Host.HasGetObjectInstanceIdProperty) + foreach (uint k in PropertyDump.ProbeKeys(PropertyNames.InstanceIdKeys, 50)) + if (Host.TryGetObjectInstanceIdProperty(id, k, out uint v)) d.InstanceIds[k] = v; + if (Host.HasGetObjectSpellIds) + { + var buf = new uint[256]; + int n = Host.GetObjectSpellIds(id, buf, buf.Length); + for (int i = 0; i < Math.Min(n, buf.Length); i++) + if (buf[i] != 0 && !d.Spells.Contains(buf[i])) d.Spells.Add(buf[i]); + } + return d.PropertyCount == 0 && d.Spells.Count == 0 && d.Name.Length == 0 ? null : d; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 18c12ce..dc87279 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -197,6 +197,18 @@ public sealed partial class RynthAiPlugin : RynthPluginBase CombatHook.LastUseDone = () => hookHost.HasUseDoneSeq && hookHost.TryGetLastUseDone(out int s, out uint e) ? (s, e) : null; RynthCore.Plugin.Shared.UseAudit.AfterSend = RecordUseForPacing; RynthCore.Plugin.Shared.UseAudit.WorldUseHold = SalvagePanelHold; + // "The door is locked!" comes as a transient string (ACE Door.ActOnUse): the door logic picks a + // lock only when the server says so (DoorInteractionController). The chat line is the fallback. + try + { + if (Host.HasServerMessages) + { + int sm = Host.SetServerMessageInterest(ReadOnlySpan.Empty, + new uint[] { RynthCore.PluginSdk.Net.GameEventType.TransientString }); + if (sm != 1) Host.Log($"[RynthAi] Server messages: not streaming ({sm}); locked doors are read from chat only."); + } + } + catch (Exception ex) { Host.Log($"[RynthAi] Server messages: {ex.Message}"); } _objectCache = new WorldObjectCache(Host); // must exist before CreateObject events fire during login // Items we use (or use something on) get re-identified before a meta reads them. // ObjectUsed is a static event and Shutdown never unsubscribes: when the engine @@ -438,6 +450,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _pendingGives.Clear(); // A /ub delay armed before logout must not fire into the next character's session. _delayedCommands.Clear(); + ClearPropertyDump(); // The engine drops its appraisal cache at logout; ask for worn gear again next login. _equipIdRequested.Clear(); // Callers save first (Shutdown, OnLogout); after this nothing writes to this @@ -1365,6 +1378,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (_loginComplete) PostDataWriteProblems(); // a save that failed / folder not writable: say so in chat CombatHook.ObserveUseDone(); // ctx.last.err: the answer to the hook's last cast TickDelayedCommands(); // /ub delay + TickPropertyDump(); // /ub propertydump: waits for the ID, chat in chunks if (_loginComplete) _dashboard?.TickPackSetup(_objectCache, _playerId); // new/copied profile items // /ra pause : restart the macro once the window elapses. Cleared by @@ -2244,6 +2258,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase public override void OnChatWindowText(string? text, int chatType, ref int eat) { if (string.IsNullOrEmpty(text)) return; + try { NoteDoorServerText(text); } catch { } // "The door is locked!" (the door logic) try { _sessionStats?.OnChatWindowText(text); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats chat"); } // The Meta Manager eats the reply to its own /myquests poll (only that). bool mmEat = false; @@ -3501,6 +3516,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "groundloot": HandleGroundLootCommand(parts); break; case "addnavpt": HandleAddNavPointCommand(); break; case "nav": HandleNavCommand(parts); break; + case "meta": HandleMetaCommand(parts); break; case "lua": ForwardLuaCommand(parts); break; case "items": if (parts.Length >= 3 && parts[2].Equals("fill", StringComparison.OrdinalIgnoreCase)) diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index fa979b6..3dc7d1a 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -226,6 +226,21 @@ internal static unsafe class FakeHost public static int ForceResets; public static int BusyStateValue; + /// Opt-in (set before Create): GetObjectProperties (API v84), answering the record + /// returns for an id (null = the engine knows nothing: 0). + public static bool ObjectPropertiesCalls; + public static Func? PropertyRecord; + /// GetObjectProperties calls, in order (the buffer-size retries included). + public static readonly List PropertyQueries = new(); + + /// Object id -> CPhysicsObj m_state (GetObjectState; 0x4 ETHEREAL = a door that is open). + /// When it has entries at Create() time the host also gets GetObjectState (opt-in, as Bitfields). + public static readonly Dictionary ObjectStates = new(); + /// Runs inside UseObject, after the use is recorded (the test plays the server here). + public static Action? OnUseObject; + /// Runs inside UseObjectOn, after it is recorded. + public static Action? OnUseObjectOn; + // ANSI strings handed back to tested code stay alive for the whole run. private static readonly Dictionary _ansi = new(); @@ -268,6 +283,8 @@ internal static unsafe class FakeHost PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear(); CombatModeCalls = false; CombatModeRequests.Clear(); CombatModeRefuse = false; CombatModeRefusals = 0; BusyCalls = false; ForceResets = 0; BusyStateValue = 0; + ObjectPropertiesCalls = false; PropertyRecord = null; PropertyQueries.Clear(); + ObjectStates.Clear(); OnUseObject = null; OnUseObjectOn = null; } /// @@ -306,6 +323,8 @@ internal static unsafe class FakeHost api.GetContainerContentsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetContainerContents; if (Bitfields.Count > 0) api.GetObjectBitfieldFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectBitfield; + if (ObjectStates.Count > 0) + api.GetObjectStateFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectState; if (InstanceIds.Count > 0) api.GetObjectInstanceIdPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectInstanceIdProperty; api.SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl])&SetAutoRun; @@ -424,6 +443,11 @@ internal static unsafe class FakeHost api.Version = Math.Max(api.Version, 64u); api.SendPluginCommandFn = (IntPtr)(delegate* unmanaged[Cdecl])&SendPluginCommand; } + if (ObjectPropertiesCalls) + { + api.Version = Math.Max(api.Version, 84u); + api.GetObjectPropertiesFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectProperties; + } LastApi = api; return new RynthCoreHost(api); } @@ -646,6 +670,16 @@ internal static unsafe class FakeHost return ids.Length; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetObjectProperties(uint id, byte* buf, int size) + { + PropertyQueries.Add(id); + byte[]? rec = PropertyRecord?.Invoke(id); + if (rec == null) return 0; + if (rec.Length <= size) rec.AsSpan().CopyTo(new Span(buf, size)); + return rec.Length; + } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectPalettes(uint id, uint* subIds, uint* offsets, int max) { @@ -750,10 +784,17 @@ internal static unsafe class FakeHost private static int ChangeCombatMode(int mode) { if (CombatModeRefuse) { CombatModeRefusals++; return 0; } CombatModeRequests.Add(mode); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int UseObject(uint id) { Uses.Add(id); return 1; } + private static int UseObject(uint id) { Uses.Add(id); OnUseObject?.Invoke(id); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetObjectState(uint id, uint* state) + { + if (!ObjectStates.TryGetValue(id, out uint s)) return 0; + *state = s; + return 1; + } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int UseObjectOn(uint source, uint target) { UsesOn.Add((source, target)); return 1; } + private static int UseObjectOn(uint source, uint target) { UsesOn.Add((source, target)); OnUseObjectOn?.Invoke(source, target); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int WieldItem(uint id, uint mask) { Wields.Add((id, mask)); return 1; } diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 79818f0..13648c3 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -51,6 +51,7 @@ internal static class Program var runner = new Runner(); NativeLootTests.Register(runner); VTankLootTests.Register(runner); + PropertyDumpTests.Register(runner); T11LootTests.Register(runner); MagItemDescriberTests.Register(runner); ExpressionTests.Register(runner); @@ -125,6 +126,8 @@ internal static class Program CorpseCloseTests.Register(runner); VTankHotkeyTests.Register(runner); SaveFailureTests.Register(runner); + DoorTests.Register(runner); + BlankLoadTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj b/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj index 34563ca..692d7e1 100644 --- a/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj +++ b/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj @@ -55,6 +55,10 @@ + + + diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/BlankLoadTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/BlankLoadTests.cs new file mode 100644 index 0000000..c4857f8 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/BlankLoadTests.cs @@ -0,0 +1,319 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.Plugin.Shared; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-10-13: "load makes a new one", as in VTank. /ra nav load and /vt nav load create an +// empty Circular route when NavProfiles has no .nav, and load it (so a route can be recorded +// into it); /ra meta load and /vt meta load create a blank .af (one state "Default", no +// rules) when MetaFiles has neither .af nor .met, and load it: the old rules are +// cleared and the meta is in Default. Existing files are loaded as before, never rewritten. Names +// that aren't plain file names are refused. Only scratch folders are used (the dashboard's +// NavProfiles / MetaFiles fields are pointed at them). +internal static class BlankLoadTests +{ + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("blank load: /ra nav load creates an empty Circular nav and loads it", NavCreates); + r.Add("blank load: /ra nav load of an existing nav loads it, file unchanged", NavExisting); + r.Add("blank load: a blank nav round-trips through the nav parser (VTank header, 0 points)", NavRoundTrip); + r.Add("blank load: /ra meta load creates a blank .af and loads it (rules cleared, state Default)", MetaCreates); + r.Add("blank load: /ra meta load of an existing .af / .met loads it, files unchanged", MetaExisting); + r.Add("blank load: /ra meta new creates only; an existing meta is left alone", MetaNew); + r.Add("blank load: a blank .af round-trips through AfFileParser; a file with no state is still refused", MetaRoundTrip); + r.Add("blank load: unsafe names are refused and nothing is written", UnsafeNames); + r.Add("blank load: names are tidied (quotes, .nav/.af/.met)", Tidy); + r.Add("blank load: /ra meta load|new|list reach the dashboard", MetaCommand); + } + + private sealed class Rig + { + public readonly LegacyUiSettings S = new(); + public readonly LegacyDashboardRenderer Dash; + public readonly string Root, Navs, Metas; + + public Rig(string name) + { + Root = Path.Combine(Program.TempRoot, "blank-load", name); + if (Directory.Exists(Root)) Directory.Delete(Root, recursive: true); + Navs = Path.Combine(Root, "NavProfiles"); + Metas = Path.Combine(Root, "MetaFiles"); + Directory.CreateDirectory(Navs); + Directory.CreateDirectory(Metas); + + Dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + var navFiles = new List(); + Set("_settings", S); + Set("_host", FakeHost.Create()); + Set("_navFolder", Navs); + Set("_metaFolder", Metas); + Set("_navFiles", navFiles); + Set("_metaFiles", new List()); + Set("_profileListsLock", new object()); + Set("_metaUi", new LegacyMetaUi(S, navFiles)); + // _settingsFilePath stays null: SaveSettings writes nothing. + } + + private void Set(string f, object v) => typeof(LegacyDashboardRenderer).GetField(f, Any)!.SetValue(Dash, v); + + public string[] Files() => Directory.GetFiles(Root, "*", SearchOption.AllDirectories); + } + + private static List HuntRules() => new() + { + new MetaRule { State = "Hunt", Condition = MetaConditionType.Always, Action = MetaActionType.ChatCommand, ActionData = "/ra start" }, + new MetaRule { State = "Hunt", Condition = MetaConditionType.Always, Action = MetaActionType.SetMetaState, ActionData = "Default" }, + }; + + private static void NavCreates() + { + DataWriteGuard.Reset(); + var rig = new Rig("nav-create"); + rig.S.CurrentRoute.Points.Add(new NavPoint { NS = 1, EW = 2 }); // a route was loaded before + rig.S.CurrentRoute.RouteType = NavRouteType.Linear; + + string msg = rig.Dash.LoadNavByName("Fresh Route"); + string path = Path.Combine(rig.Navs, "Fresh Route.nav"); + Check.Eq(msg, "[RynthAi] Created new nav 'Fresh Route' (empty, Circular) and loaded it.", "message"); + Check.True(File.Exists(path), "Fresh Route.nav written"); + Check.Eq(string.Join("|", File.ReadAllLines(path)), "uTank2 NAV 1.2|1|0", "VTank nav: header, Circular, 0 points"); + Check.Eq(rig.S.CurrentNavPath, path, "it is the loaded nav"); + Check.Eq(rig.S.CurrentRoute.Points.Count, 0, "the old route's points are gone"); + Check.Eq(rig.S.CurrentRoute.RouteType, NavRouteType.Circular, "Circular"); + Check.Eq(rig.S.ActiveNavIndex, 0, "at the start"); + Check.True(rig.Dash.NavFileNames().Contains("Fresh Route"), "listed by /ra nav list"); + + // Loading it again finds it (no second create). + msg = rig.Dash.LoadNavByName("fresh route"); + Check.Eq(msg, "[RynthAi] Loaded fresh route (0 waypoints).", "second load is a plain load: " + msg); + Check.Eq(DataWriteGuard.PendingCount, 0, "nothing reported"); + } + + private static void NavExisting() + { + var rig = new Rig("nav-existing"); + string path = Path.Combine(rig.Navs, "Hive Loop.nav"); + var route = new NavRouteParser { RouteType = NavRouteType.Linear }; + route.Points.Add(new NavPoint { NS = 10.5, EW = -3.25 }); + route.Points.Add(new NavPoint { NS = 11.5, EW = -4.25 }); + route.Save(path); + byte[] before = File.ReadAllBytes(path); + DateTime stamp = File.GetLastWriteTimeUtc(path); + + string msg = rig.Dash.LoadNavByName("\"Hive Loop.nav\""); + Check.Eq(msg, "[RynthAi] Loaded Hive Loop (2 waypoints).", "loaded: " + msg); + Check.Eq(rig.S.CurrentNavPath, path, "the existing file"); + Check.Eq(rig.S.CurrentRoute.RouteType, NavRouteType.Linear, "its own route type"); + Check.True(((ReadOnlySpan)File.ReadAllBytes(path)).SequenceEqual(before), "file bytes unchanged"); + Check.Eq(File.GetLastWriteTimeUtc(path), stamp, "file not rewritten"); + Check.Eq(Directory.GetFiles(rig.Navs).Length, 1, "no other file"); + } + + private static void NavRoundTrip() + { + NavRouteParser blank = NewProfileFiles.BlankNav(); + List lines = blank.ToLines(); + Check.Eq(string.Join("|", lines), "uTank2 NAV 1.2|1|0", "lines"); + NavRouteParser back = NavRouteParser.LoadFromLines(lines); + Check.Eq(back.RouteType, NavRouteType.Circular, "route type"); + Check.Eq(back.Points.Count, 0, "no points"); + Check.Null(back.LoadWarning, "no warning"); + + string path = Path.Combine(Program.TempRoot, "blank-load", "roundtrip.nav"); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + blank.Save(path); + NavRouteParser fromFile = NavRouteParser.Load(path); + Check.Eq(fromFile.RouteType, NavRouteType.Circular, "file: route type"); + Check.Eq(fromFile.Points.Count, 0, "file: no points"); + Check.Null(fromFile.LoadWarning, "file: no warning"); + Check.Eq(string.Join("|", fromFile.ToLines()), "uTank2 NAV 1.2|1|0", "saves back the same"); + } + + private static void MetaCreates() + { + DataWriteGuard.Reset(); + var rig = new Rig("meta-create"); + rig.S.MetaRules = HuntRules(); + rig.S.EmbeddedNavs["old nav"] = new List { "uTank2 NAV 1.2", "1", "0" }; + rig.S.CurrentState = "Hunt"; + rig.S.CurrentMetaPath = Path.Combine(rig.Metas, "old.af"); + + string msg = rig.Dash.LoadMetaByName("'Blank Farm.af'"); + string path = Path.Combine(rig.Metas, "Blank Farm.af"); + Check.Eq(msg, "[RynthAi] Created new meta 'Blank Farm' (one state 'Default', no rules) and loaded it.", "message"); + Check.True(File.Exists(path), "Blank Farm.af written"); + Check.Eq(File.ReadAllText(path), AfFileWriter.BlankMetaText(), "the blank meta text"); + Check.Eq(rig.S.MetaRules.Count, 0, "old rules cleared"); + Check.Eq(rig.S.EmbeddedNavs.Count, 0, "old embedded navs cleared"); + Check.Eq(rig.S.CurrentState, "Default", "state Default"); + Check.True(rig.S.ForceStateReset, "state reset forced"); + Check.True(rig.S.MetaCallStackReset, "call stack reset"); + Check.Eq(rig.S.CurrentMetaPath, path, "it is the loaded meta"); + Check.True(rig.Dash.MetaFileNames().Contains("Blank Farm.af"), "listed by /ra meta list"); + Check.Eq(DataWriteGuard.PendingCount, 0, "nothing reported"); + + // Without an extension, the same name is now found. + msg = rig.Dash.LoadMetaByName("blank farm"); + Check.True(msg.StartsWith("[RynthAi] Loaded meta 'blank farm': 0 rules"), "second load is a plain load: " + msg); + Check.Eq(Directory.GetFiles(rig.Metas).Length, 1, "one file"); + } + + private static void MetaExisting() + { + var rig = new Rig("meta-existing"); + string af = Path.Combine(rig.Metas, "Farm.af"); + AfFileWriter.Save(af, HuntRules(), new Dictionary>()); + byte[] afBefore = File.ReadAllBytes(af); + DateTime afStamp = File.GetLastWriteTimeUtc(af); + + string msg = rig.Dash.LoadMetaByName("Farm"); + Check.Eq(msg, "[RynthAi] Loaded meta 'Farm': 2 rules, 0 navs", "loaded: " + msg); + Check.Eq(rig.S.MetaRules.Count, 2, "its rules"); + Check.Eq(rig.S.CurrentState, "Hunt", "its start state"); + Check.Eq(rig.S.CurrentMetaPath, af, "the .af"); + Check.True(((ReadOnlySpan)File.ReadAllBytes(af)).SequenceEqual(afBefore), ".af bytes unchanged"); + Check.Eq(File.GetLastWriteTimeUtc(af), afStamp, ".af not rewritten"); + + // Only a .met by that name: loaded, no .af created beside it. (A .met that parses to no + // rules is refused as before: "not loaded", and still no .af.) + string met = Path.Combine(rig.Metas, "Old.met"); + File.WriteAllText(met, "garbage"); + byte[] metBefore = File.ReadAllBytes(met); + msg = rig.Dash.LoadMetaByName("Old.met"); + Check.True(msg.StartsWith("[RynthAi] Meta 'Old' not loaded:"), "a .met with no rules is refused: " + msg); + Check.False(File.Exists(Path.Combine(rig.Metas, "Old.af")), "no blank .af made for an existing .met"); + Check.True(((ReadOnlySpan)File.ReadAllBytes(met)).SequenceEqual(metBefore), ".met unchanged"); + Check.Eq(rig.S.MetaRules.Count, 2, "the loaded meta stays when a load is refused"); + } + + private static void MetaNew() + { + var rig = new Rig("meta-new"); + string af = Path.Combine(rig.Metas, "Farm.af"); + AfFileWriter.Save(af, HuntRules(), new Dictionary>()); + byte[] before = File.ReadAllBytes(af); + + string msg = rig.Dash.LoadMetaByName("Farm", createOnly: true); + Check.Eq(msg, "[RynthAi] Meta 'Farm.af' already exists. /ra meta load Farm loads it.", "refused: " + msg); + Check.True(((ReadOnlySpan)File.ReadAllBytes(af)).SequenceEqual(before), "unchanged"); + Check.Eq(rig.S.MetaRules.Count, 0, "nothing loaded"); + + msg = rig.Dash.LoadMetaByName("Next", createOnly: true); + Check.Eq(msg, "[RynthAi] Created new meta 'Next' (one state 'Default', no rules) and loaded it.", "created: " + msg); + Check.True(File.Exists(Path.Combine(rig.Metas, "Next.af")), "Next.af written"); + } + + private static void MetaRoundTrip() + { + string text = AfFileWriter.BlankMetaText(); + LoadedMeta m = AfFileParser.LoadFromText(text); + Check.Eq(m.Rules.Count, 0, "no rules"); + Check.Eq(string.Join(",", m.DeclaredStates), "Default", "one state, Default"); + Check.Eq(m.Warnings.Count, 0, "no warnings"); + Check.True(m.IsBlank, "a blank meta"); + Check.Eq(m.StartState, "Default", "starts in Default"); + Check.Eq(AfFileWriter.SaveToString(m.Rules, m.EmbeddedNavs), text, "writes back the same (a meta whose last rule was deleted)"); + + // A file with no state at all (a profile, an empty file) is still not a meta. + LoadedMeta empty = AfFileParser.LoadFromText(""); + Check.False(empty.IsBlank, "an empty file isn't a blank meta"); + string dir = Path.Combine(Program.TempRoot, "blank-load", "roundtrip"); + Directory.CreateDirectory(dir); + string path = Path.Combine(dir, "empty.af"); + File.WriteAllText(path, ""); + var settings = new LegacyUiSettings { MetaRules = HuntRules() }; + var ui = new LegacyMetaUi(settings, new List()); + Check.False(ui.LoadMacroFile(path), "an empty .af is refused"); + Check.Eq(settings.MetaRules.Count, 2, "rules kept"); + File.WriteAllText(path, text); + Check.True(ui.LoadMacroFile(path), "the blank .af loads: " + ui.LastLoadStatus); + Check.Eq(settings.MetaRules.Count, 0, "rules cleared"); + Check.Eq(settings.CurrentState, "Default", "Default"); + } + + private static void UnsafeNames() + { + var rig = new Rig("unsafe"); + string parent = Path.GetDirectoryName(rig.Root)!; + int parentFiles = Directory.GetFiles(parent).Length; + string[] bad = + { + "", " ", "\"\"", @"..\evil", "../evil", "..", "sub/route", @"sub\route", "a:b", "what?", "star*", + "pipe|x", "", "CON", "nul", "com1.txt", "LPT9", "trailing.", "dots..inside", new string('x', 121), + }; + foreach (string name in bad) + { + string nav = rig.Dash.LoadNavByName(name); + Check.True(nav.StartsWith("[RynthAi] Can't use '") && nav.Contains("as a nav name"), $"nav '{name}' refused: {nav}"); + string meta = rig.Dash.LoadMetaByName(name); + Check.True(meta.StartsWith("[RynthAi] Can't use '") && meta.Contains("as a meta name"), $"meta '{name}' refused: {meta}"); + string mnew = rig.Dash.LoadMetaByName(name, createOnly: true); + Check.True(mnew.StartsWith("[RynthAi] Can't use '"), $"meta new '{name}' refused: {mnew}"); + } + Check.Eq(rig.Files().Length, 0, "nothing written in the data folders"); + Check.Eq(Directory.GetFiles(parent).Length, parentFiles, "nothing written beside them"); + Check.False(File.Exists(Path.Combine(parent, "evil.nav")) || File.Exists(Path.Combine(parent, "evil.af")), "no escape from the folder"); + + // Ordinary names with dots, spaces and dashes are fine. + Check.Null(NewProfileFiles.Validate("Farm v2.1 - Hive"), "a normal name"); + Check.Null(NewProfileFiles.Validate("console"), "CON is reserved, console isn't"); + } + + private static void Tidy() + { + Check.Eq(NewProfileFiles.Tidy(" \"Hive Loop.nav\" ", NewProfileFiles.NavExtensions, out string e1), "Hive Loop", "quotes + .nav"); + Check.Eq(e1, ".nav", "extension seen"); + Check.Eq(NewProfileFiles.Tidy("'farm.MET'", NewProfileFiles.MetaExtensions, out string e2), "farm", "single quotes + .MET"); + Check.Eq(e2, ".met", "lower-cased"); + Check.Eq(NewProfileFiles.Tidy("farm.af", NewProfileFiles.MetaExtensions, out _), "farm", ".af"); + Check.Eq(NewProfileFiles.Tidy("route.nav", NewProfileFiles.MetaExtensions, out string e3), "route.nav", ".nav isn't a meta extension"); + Check.Eq(e3, "", "none"); + Check.Eq(NewProfileFiles.Tidy(".nav", NewProfileFiles.NavExtensions, out _), ".nav", "an extension alone isn't stripped to nothing"); + } + + private static void MetaCommand() + { + FakeHost.Reset(); + var rig = new Rig("meta-command"); + var plugin = new RynthAiPlugin(); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi }); + typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(plugin, rig.Dash); + MethodInfo dispatch = typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!; + void Ra(string line) + { + string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + dispatch.Invoke(plugin, new object[] { parts[1].ToLowerInvariant(), parts, 0 }); + } + + Ra("/ra meta load Night Farm"); + Check.True(FakeHost.Chat.Exists(l => l.Contains("Created new meta 'Night Farm' (one state 'Default', no rules) and loaded it.")), + "/ra meta load creates: " + string.Join(" / ", FakeHost.Chat)); + Check.True(File.Exists(Path.Combine(rig.Metas, "Night Farm.af")), "file written"); + FakeHost.Chat.Clear(); + Ra("/ra meta new Night Farm"); + Check.True(FakeHost.Chat.Exists(l => l.Contains("already exists")), "/ra meta new refuses an existing one"); + FakeHost.Chat.Clear(); + Ra("/ra meta list"); + Check.True(FakeHost.Chat.Exists(l => l.Contains("Metas (1): Night Farm.af")), "/ra meta list: " + string.Join(" / ", FakeHost.Chat)); + FakeHost.Chat.Clear(); + Ra("/ra meta load"); + Check.True(FakeHost.Chat.Exists(l => l.Contains("Usage: /ra meta load ")), "usage"); + FakeHost.Chat.Clear(); + Ra("/ra nav load New Route"); + Check.True(FakeHost.Chat.Exists(l => l.Contains("Created new nav 'New Route' (empty, Circular) and loaded it.")), + "/ra nav load creates: " + string.Join(" / ", FakeHost.Chat)); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/DoorTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/DoorTests.cs new file mode 100644 index 0000000..1fd0e97 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/DoorTests.cs @@ -0,0 +1,320 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Doors (2026-10-13, a mage on DreamWeave, "doors aren't opening"): the use went out while the +// client was busy (portal space), a second use followed 3 s later with the first unanswered (the +// server's walk to the door took up to 3.7 s), and a door still closed after a use was called +// locked and sent to the lockpick cooldown although the server never said so. See the header of +// DoorInteractionController.cs for the rules these check. +internal static class DoorTests +{ + private const uint Player = 0x50000D01; + private const uint Door = 0x701C9139; + private const uint Pick = 0x80000D11; + private const uint Kit = 0x80000D12; + private const uint Closed = 0x00010018, Ethereal = 0x4; + private const uint BfDoor = 0x1000; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public; + private static (uint Cell, float X, float Y, float Z) Me0 => (0x01C90231u, 60f, 10f, 0f); + + public static void Register(Runner r) + { + r.Add("door: no use while the client is busy or another use is unanswered; it goes when they clear", WaitsForBusyAndAnswer); + r.Add("door: a slow server walk (3.7 s to the answer) is waited out - one use, no retry, opened", SlowWalkOneUse); + r.Add("door: no second use while the first is unanswered; a lost use is re-sent only after the answer limit", NoDoubleUse); + r.Add("door: still closed after an answered use, no 'locked' from the server: used again, never picked", NotLockedWithoutServer); + r.Add("door: the server says locked: a lockpick goes on it, then the door is opened again", LockedUsesLockpick); + r.Add("door: locked and no lockpick: cooldown, and the door is skipped a while", LockedNoPick); + r.Add("door: nothing in portal space, nor just after it", NothingInPortalSpace); + r.Add("door: a door that opens is released at once (no fixed waits)", OpensFast); + r.Add("door: 'locked' from chat counts only as the server's line, not a player's", LockedChatLine); + } + + // ── Rig ───────────────────────────────────────────────────────────────── + + private sealed class Bot + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new() { IsMacroRunning = true, OpenDoors = true, OpenDoorRange = 5f, AutoUnlockDoors = true }; + public readonly WorldObjectCache Cache; + public long Now = 50_000_000; + public readonly RynthCoreHost Host; + + public Bot(bool lockpick = true) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; // UseObject + FakeHost.UseOnCalls = true; // UseObjectOn (the lockpick) + FakeHost.ServerGates = true; // GetUseDoneSeq, GetCastBusyState + FakeHost.LastUseDoneCalls = true; + FakeHost.StopCalls = true; + FakeHost.Names[Player] = "Mage"; + FakeHost.Positions[Player] = Me0; + FakeHost.PlayerPose = Me0; + FakeHost.Names[Door] = "Door"; + FakeHost.Positions[Door] = (Me0.Cell, Me0.X + 2f, Me0.Y, Me0.Z); + FakeHost.Bitfields[Door] = BfDoor; + FakeHost.ObjectStates[Door] = Closed; + FakeHost.Names[Pick] = "Plain Lockpick"; + FakeHost.Names[Kit] = "Treated Healing Kit"; + Host = FakeHost.Create(Player); + + ActionPacer.Reset(); + ActionPacer.Enabled = true; + ActionPacer.NowMs = () => Now; + UseAudit.Reset("RynthAi", () => true); + UseAudit.NowMs = () => Now; + UseAudit.TrackWorldUses = true; + MoveAudit.Reset(); + MoveAudit.NowMs = () => Now; + var rec = typeof(RynthAiPlugin).GetMethod("RecordUseForPacing", Any)!; + UseAudit.AfterSend = (h, u) => rec.Invoke(null, new object[] { h, u }); + RynthAiPlugin.DoorClock = () => Now; + + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + Set("_dashboard", dash); + Cache = new WorldObjectCache(Host); + Cache.SetPlayerId(Player); + Set("_objectCache", Cache); + Set("_playerId", Player); + Cache.OnCreateObject(Player); + Cache.OnCreateObject(Door); + _ = Cache[unchecked((int)Pick)]; + _ = Cache[unchecked((int)Kit)]; + Cache.Tick(); + if (lockpick) + S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Pick), Name = "Plain Lockpick", Type = "Lockpick" }); + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public T Get(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!; + public int Busy { set => Set("_busyCount", value); } + public string State => Get("_doorState").ToString()!; + + /// One door tick at the current time; true while the door holds nav. + public bool Tick() => (bool)typeof(RynthAiPlugin).GetMethod("TickDoorInteraction", Any)!.Invoke(P, null)!; + + /// Ticks every for . + public void Run(long ms, long stepMs = 50) + { + for (long t = 0; t < ms; t += stepMs) { Now += stepMs; Tick(); } + } + + public void Answer(bool open) + { + if (open) FakeHost.ObjectStates[Door] = Closed | Ethereal; + FakeHost.UseDone(0); + } + + public void Say(string line) => P.NoteDoorServerText(line); + } + + private static int DoorUses() => FakeHost.Uses.Count(u => u == Door); + private static int Picks() => FakeHost.UsesOn.Count(u => u.Source == Pick && u.Target == Door); + + private static void Cleanup() + { + ActionPacer.Enabled = false; + ActionPacer.Reset(); + ActionPacer.NowMs = () => Environment.TickCount64; + UseAudit.Reset("?", null); + UseAudit.NowMs = () => Environment.TickCount64; + UseAudit.TrackWorldUses = false; + MoveAudit.Reset(); + MoveAudit.NowMs = () => Environment.TickCount64; + RynthAiPlugin.DoorClock = static () => Environment.TickCount64; + } + + private static void With(Action body) + { + try { body(); } + finally { Cleanup(); } + } + + // ── Tests ─────────────────────────────────────────────────────────────── + + private static void WaitsForBusyAndAnswer() => With(() => + { + var b = new Bot(); + // A kit the server hasn't answered yet, and the client's busy count up. + ActionPacer.Begin(b.Host, PacedKind.ItemUse, Kit, "'Treated Healing Kit'", "RynthAi/Buff", FakeHost.UseDoneSeq); + b.Busy = 1; + Check.True(b.Tick(), "targeting the door holds nav"); + b.Run(1000); + Check.Eq(DoorUses(), 0, "no door use while the kit is unanswered (and the client busy)"); + Check.True(FakeHost.Logs.Any(l => l.Contains("Door: 0x701C9139 waits:")), "the wait is logged"); + + FakeHost.UseDone(0); // the kit's answer + b.Run(500); + Check.Eq(DoorUses(), 0, "the kit answered, but the client still reads busy"); + b.Busy = 0; + b.Run(100); + Check.Eq(DoorUses(), 1, "busy 0 and nothing unanswered: the use goes"); + Check.Eq(b.State, "Opening", "...and waits for the server"); + }); + + private static void SlowWalkOneUse() => With(() => + { + var b = new Bot(); + b.Tick(); + Check.Eq(FakeHost.Stops, 1, "the character is stopped first"); + Check.Eq(DoorUses(), 0, "...and the use waits for the stop to settle"); + b.Run(300); // the stop settles + Check.Eq(DoorUses(), 1, "the use went out once the stop settled"); + b.Run(3700, 100); // the server walks the character to the door: 3.7 s in the 10-13 log + Check.Eq(DoorUses(), 1, "no second use during the walk (the old 3 s timeout re-sent it)"); + Check.False(FakeHost.Logs.Any(l => l.Contains("is locked")), "nothing called locked"); + b.Answer(open: true); + b.Now += 50; + Check.False(b.Tick(), "opened: nav released"); + Check.True(FakeHost.Logs.Any(l => l.Contains("opened OK")), "opened OK logged"); + Check.Eq(b.State, "None", "back to idle"); + b.Run(2000); + Check.Eq(DoorUses(), 1, "an opened door is not used again"); + }); + + private static void NoDoubleUse() => With(() => + { + var b = new Bot(); + b.Tick(); + b.Run(300); + Check.Eq(DoorUses(), 1, "first use"); + b.Run(5500, 100); // no answer at all + Check.Eq(DoorUses(), 1, "no second use while the first is unanswered (5.8 s)"); + b.Run(1000, 100); // past the 6 s answer limit + Check.Eq(DoorUses(), 2, "a use never answered is sent again after the limit"); + Check.True(FakeHost.Logs.Any(l => l.Contains("no answer from the server")), "the lost use is logged"); + Check.False(FakeHost.Logs.Any(l => l.Contains("went out while")), "the pacer never saw a use go out over an unanswered one"); + }); + + private static void NotLockedWithoutServer() => With(() => + { + var b = new Bot(lockpick: true); + b.Tick(); + b.Run(300); + Check.Eq(DoorUses(), 1, "first use"); + b.Run(2000, 100); + b.Answer(open: false); // answered (UseDone 0), the door stays shut, no locked text + b.Run(1000, 100); + Check.Eq(DoorUses(), 1, "the door gets a moment to swing after the answer"); + b.Run(500, 100); + Check.Eq(DoorUses(), 2, "still closed: used again"); + Check.Eq(Picks(), 0, "no lockpick: the server never said locked"); + b.Answer(open: false); + b.Run(1500, 100); + b.Answer(open: false); + b.Run(1500, 100); + Check.Eq(DoorUses(), 3, "three uses in all"); + Check.Eq(b.State, "Cooldown", "then a cooldown"); + Check.Eq(Picks(), 0, "still no lockpick"); + Check.False(FakeHost.Logs.Any(l => l.Contains("is locked")), "never logged as locked"); + }); + + private static void LockedUsesLockpick() => With(() => + { + var b = new Bot(lockpick: true); + b.Tick(); + b.Run(300); + Check.Eq(DoorUses(), 1, "first use"); + b.Run(1500, 100); + b.Say("The door is locked!"); // ACE Door.ActOnUse's transient string + b.Answer(open: false); + b.Run(300); + Check.Eq(Picks(), 1, "the lockpick goes on the door"); + Check.Eq(DoorUses(), 1, "...and no open over it"); + b.Run(1000); + Check.Eq(DoorUses(), 1, "nothing while the lockpick is unanswered"); + FakeHost.UseDone(0); // "You have successfully picked the lock!" + b.Run(300); + Check.Eq(DoorUses(), 2, "opened again after the lockpick's answer"); + b.Run(800); + b.Answer(open: true); + b.Now += 50; + Check.False(b.Tick(), "opened: nav released"); + Check.Eq(b.State, "None", "done"); + }); + + private static void LockedNoPick() => With(() => + { + var b = new Bot(lockpick: false); + b.Tick(); + b.Run(300); + b.Run(1000, 100); + b.Say("The door is locked!"); + b.Answer(open: false); + b.Run(100); + Check.Eq(b.State, "Cooldown", "locked, no lockpick: cooldown"); + Check.True(FakeHost.Logs.Any(l => l.Contains("is locked but there's no lockpick")), "says why"); + b.Run(6000, 100); + Check.Eq(b.State, "None", "cooldown over"); + b.Run(2000, 100); + Check.Eq(DoorUses(), 1, "the locked door is skipped a while (not targeted again)"); + }); + + private static void NothingInPortalSpace() => With(() => + { + var b = new Bot(); + FakeHost.Portaling = true; + b.Run(2000); + Check.Eq(b.State, "None", "no door targeted in portal space"); + Check.Eq(DoorUses(), 0, "no use"); + FakeHost.Portaling = false; + b.Run(1000); + Check.Eq(b.State, "None", "nor in the first moment after it"); + b.Run(1000); + Check.Eq(DoorUses(), 1, "then the door is opened as usual"); + + // Portal space in the middle of a use: forgotten, not judged. + FakeHost.Portaling = true; + b.Run(200); + Check.Eq(b.State, "None", "a use under way is dropped in portal space"); + Check.False(FakeHost.Logs.Any(l => l.Contains("is locked") || l.Contains(", cooldown")), "never called locked"); + }); + + private static void OpensFast() => With(() => + { + var b = new Bot(); + b.Tick(); + b.Run(200); + Check.Eq(DoorUses(), 1, "use out within 0.2 s of targeting"); + b.Run(300); + FakeHost.ObjectStates[Door] = Closed | Ethereal; // swings open before the UseDone arrives + b.Now += 50; + Check.False(b.Tick(), "released the tick it reads open"); + Check.Eq(b.State, "None", "done without waiting for anything else"); + }); + + private static void LockedChatLine() => With(() => + { + var b = new Bot(lockpick: true); + b.Tick(); + b.Run(300); + b.Run(1000, 100); + var chat = typeof(RynthAiPlugin).GetMethod("OnChatWindowText", Any)!; + object?[] args = { "Bob says, \"The door is locked!\"", 2, 0 }; + try { chat.Invoke(b.P, args); } catch { } // the rest of the chat pipeline isn't set up here + b.Answer(open: false); + b.Run(200); + Check.Eq(Picks(), 0, "a player's line isn't the server's"); + b.Run(1500, 100); + args = new object?[] { "The door is locked!", 0, 0 }; + try { chat.Invoke(b.P, args); } catch { } + b.Run(100); + b.Answer(open: false); + b.Run(300); + Check.Eq(Picks(), 1, "the server's line from chat sends the lockpick"); + }); +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs index 21566d5..49b5265 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs @@ -48,6 +48,10 @@ internal static class MetaTests 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); + r.Add("meta .af: EmbedNav and NAV names lose stray brackets ('None]' was loaded as a route named 'None]')", EmbedNavStrayBrackets); + r.Add("meta action: EmbedNav [None] with no route behind it is an empty route (no 'None.nav', no 'Route missing')", EmbedNavNoneKeepsRoute); + r.Add("meta action: a [None] route with points loads, as in VTank (an old 'None]' key too)", EmbedNavNoneWithPointsLoads); + r.Add("meta .met: VTank's [None] embedded nav - with points it is a route, empty it is no nav", MetEmbedNavNone); r.Add("meta action: watchdog", Watchdog); r.Add("meta action: RA options, chat expression, expression, views", MiscActions); r.Add("meta: an exception in a tick is caught and forces a reset", ExceptionInTick); @@ -883,6 +887,8 @@ internal static class MetaTests Check.True(rig.Ra.Contains("/ra stop"), "/vt stop"); RunAction(rig, A.ChatCommand, "/vt nav load Hive Loop"); Check.True(rig.Ra.Contains("/ra nav load Hive Loop"), "/vt nav load keeps spaces"); + RunAction(rig, A.ChatCommand, "/vt meta load Night Farm"); + Check.True(rig.Ra.Contains("/ra meta load Night Farm"), "/vt meta load is /ra meta load (one implementation; a new name makes a blank meta)"); RunAction(rig, A.ChatCommand, "/vt setattackbar 0.75"); Check.True(rig.Ra.Contains("/ra power 75"), "/vt setattackbar 0.75 -> 75%"); RunAction(rig, A.ChatCommand, "/vt setattackbar 3"); @@ -1020,6 +1026,135 @@ internal static class MetaTests Check.Eq(rig.S.CurrentNavPath, "", "...and loaded"); } + // The CQ meta family on DreamWeave (C:\Games\metaf\CQHunt~0.af, decompiled by metaf): VTank's + // "[None]" routes become tags like nav9___None_ - a one-point hunt spot, and an empty one. + // "None]" is the broken spelling from the 10-13 player log ("EmbedNav: loaded 'None]' (1 pts)"). + private const string CqNoneSnippet = + "STATE: {Hunt} ~~ {\n" + + "\tIF:\tAlways\n" + + "\t\tDO:\tDoAll\n" + + "\t\t\t\tChat {/vt opt set enablenav true}\n" + + "\t\t\t\tEmbedNav nav9___None_ {[none]}\n" + + "\t\t\t\tEmbedNav None] {[None]}\n" + + "\t\t\t\tEmbedNav [None] {[None]}\n" + + "\t\t\t\tEmbedNav nav42___None_ {[none]}\n" + + "~~ }\n" + + "NAV: nav9___None_ circular ~~ {\n" + + "\tpnt 12.7402540842692 64.8717851956685 1.15794169108073\n" + + "~~ }\n" + + "NAV: None] circular ~~ {\n" + + "\tpnt 12.7402540842692 64.8717851956685 1.15794169108073\n" + + "~~ }\n" + + "NAV: nav42___None_ circular ~~ {\n" + + "~~ }\n"; + + private static void EmbedNavStrayBrackets() + { + var m = AfFileParser.LoadFromText(CqNoneSnippet); + var all = m.Rules.Single(); + var data = all.ActionChildren.Select(c => c.ActionData).ToList(); + Check.Eq(string.Join("|", data), "/vt opt set enablenav true|nav9___None_|None|None|", "action names: the tag, 'None]' and '[None]' cleaned to None, the empty route's ref cleared"); + Check.True(m.EmbeddedNavs.ContainsKey("None"), "the NAV block 'None]' is filed as 'None'"); + Check.False(m.EmbeddedNavs.Keys.Any(k => k.Contains('[') || k.Contains(']')), "no key keeps a stray bracket"); + Check.True(m.EmbeddedNavs.ContainsKey("nav9___None_"), "metaf's tag is kept as it is"); + Check.False(m.EmbeddedNavs.ContainsKey("nav42___None_"), "the empty [None] route is dropped"); + + // Saved and read back: the same names (the Meta panel saves through AfFileWriter). + var back = AfFileParser.LoadFromText(AfFileWriter.SaveToString(m.Rules, m.EmbeddedNavs)); + Check.Eq(string.Join("|", back.Rules.Single().ActionChildren.Select(c => c.ActionData)), + "/vt opt set enablenav true|nav9___None_|None|None|", "round trip keeps the names"); + Check.True(back.EmbeddedNavs.ContainsKey("None") && back.EmbeddedNavs.ContainsKey("nav9___None_"), "round trip keeps the routes"); + + // The clean-up itself. + Check.Eq(EmbedNavName.Clean(" [None] "), "None", "wrapping brackets"); + Check.Eq(EmbedNavName.Clean("None]"), "None", "a stray closing bracket"); + Check.Eq(EmbedNavName.Clean("[None"), "None", "a stray opening bracket"); + Check.Eq(EmbedNavName.Clean("Hive [East]"), "Hive [East]", "brackets inside a name are kept"); + Check.Eq(EmbedNavName.Clean("[a] [b]"), "[a] [b]", "two bracketed parts are not unwrapped"); + Check.True(EmbedNavName.IsNone("[none]") && EmbedNavName.IsNone("None]") && !EmbedNavName.IsNone("nav9___None_"), "IsNone"); + } + + private static void EmbedNavNoneKeepsRoute() + { + FakeHost.Reset(); + FakeHost.PlayerPose = (0xA9B4001Cu, 96f, 96f, 0f); + var host = FakeHost.Create(); + var rig = new Rig(host, Player); + rig.S.EmbeddedNavs["Hive Route"] = NavLines(1, (0, 30, 40, NoTrailer), (0, 33.65, 42.45, NoTrailer), (0, 36, 44, NoTrailer)); + RunAction(rig, A.EmbeddedNavRoute, "Hive Route"); + Check.Eq(rig.S.CurrentRoute.Points.Count, 3, "a route is running"); + foreach (string none in new[] { "[None]", "None]", "None", "[none]" }) + { + FakeHost.Chat.Clear(); + RunAction(rig, A.EmbeddedNavRoute, "Hive Route"); + RunAction(rig, A.EmbeddedNavRoute, none); + Check.Eq(rig.S.CurrentRoute.Points.Count, 0, $"'{none}': an empty route"); + Check.Eq(rig.S.CurrentNavPath, "", $"'{none}': no nav file"); + Check.False(FakeHost.Chat.Exists(c => c.Contains("Route missing")), $"'{none}': no 'Route missing'"); + } + // An empty [None] route is no route either. + rig.S.EmbeddedNavs["None"] = NavLines(1); + RunAction(rig, A.EmbeddedNavRoute, "Hive Route"); + RunAction(rig, A.EmbeddedNavRoute, "[None]"); + Check.Eq(rig.S.CurrentRoute.Points.Count, 0, "an empty [None] route: an empty route"); + } + + private static void EmbedNavNoneWithPointsLoads() + { + FakeHost.Reset(); + FakeHost.PlayerPose = (0xA9B4001Cu, 96f, 96f, 0f); + var host = FakeHost.Create(); + var rig = new Rig(host, Player); + // A key from a settings file or meta saved before names were cleaned. + rig.S.EmbeddedNavs["None]"] = NavLines(1, (0, 33.65, 42.45, NoTrailer)); + RunAction(rig, A.EmbeddedNavRoute, "[None]"); + Check.Eq(rig.S.CurrentRoute.Points.Count, 1, "the one-point [None] route (a hunt spot) loads"); + Check.True(rig.S.EnableNavigation, "...and navigation runs"); + RunAction(rig, A.EmbeddedNavRoute, "None]"); + Check.Eq(rig.S.CurrentNavPath, "", "the old key is found from any spelling"); + } + + /// A VTank .met with two rules (Always / Never) whose action is an embedded nav named + /// "[None]": one with a one-point route, one with an empty route. The layout is VTank's (the + /// CQ metas, S_Tusks.met): name line, point count, then the .nav lines, byte-counted. + private static string MetWithNoneNavs() + { + static string Block(params string[] lines) => string.Join("\r\n", lines) + "\r\n"; + string onePoint = Block("[None]", "1", "uTank2 NAV 1.2", "1", "1", "0", "33.65", "42.45", "0", "0"); + string empty = Block("[None]", "0", "uTank2 NAV 1.2", "1", "0"); + var met = new List { "1", "CondAct", "5", "CType", "AType", "CData", "AData", "State", "n", "n", "n", "n", "n", "2" }; + met.AddRange(new[] { "i", "1", "i", "4", "i", "0", "ba", System.Text.Encoding.UTF8.GetByteCount(onePoint).ToString() }); + string head = string.Join("\r\n", met) + "\r\n" + onePoint; + var mid = new List { "s", "Default", "i", "0", "i", "4", "i", "0", "ba", System.Text.Encoding.UTF8.GetByteCount(empty).ToString() }; + return head + string.Join("\r\n", mid) + "\r\n" + empty + "s\r\nDefault\r\n"; + } + + private static void MetEmbedNavNone() + { + string path = System.IO.Path.Combine(Program.TempRoot, "embednav-none-test.met"); + System.IO.File.WriteAllText(path, MetWithNoneNavs()); + var m = MetFileParser.Load(path); + Check.Eq(m.Warnings.Count, 0, "parses cleanly"); + Check.Eq(m.Rules.Count, 2, "two rules"); + string first = m.Rules[0].ActionData; + Check.True(first.Length > 0 && m.EmbeddedNavs.ContainsKey(first), $"the one-point [None] route is a route ('{first}')"); + Check.False(first.Contains('[') || first.Contains(']'), "its name has no bracket"); + Check.Eq(NavRouteParser.LoadFromLines(m.EmbeddedNavs[first]).Points.Count, 1, "...with its point"); + Check.Eq(m.Rules[1].ActionData, "", "the empty [None] route: no nav"); + + // Through the meta: the empty one keeps the running route, the one-point one replaces it. + FakeHost.Reset(); + FakeHost.PlayerPose = (0xA9B4001Cu, 96f, 96f, 0f); + var rig = new Rig(FakeHost.Create(), Player); + foreach (var kv in m.EmbeddedNavs) rig.S.EmbeddedNavs[kv.Key] = kv.Value; + rig.S.EmbeddedNavs["Hive Route"] = NavLines(1, (0, 30, 40, NoTrailer), (0, 36, 44, NoTrailer)); + RunAction(rig, A.EmbeddedNavRoute, "Hive Route"); + RunAction(rig, A.EmbeddedNavRoute, m.Rules[1].ActionData); + Check.Eq(rig.S.CurrentRoute.Points.Count, 2, "empty [None]: the running route is kept"); + RunAction(rig, A.EmbeddedNavRoute, first); + Check.Eq(rig.S.CurrentRoute.Points.Count, 1, "one-point [None]: loaded"); + } + private static void Watchdog() { FakeHost.Reset(); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PropertyDumpTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PropertyDumpTests.cs new file mode 100644 index 0000000..6236c8a --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PropertyDumpTests.cs @@ -0,0 +1,312 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using RynthCore.Engine.Compatibility; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.Diagnostics; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; +using EngineFlags = RynthCore.Engine.Compatibility.ObjectPropertyFlags; + +namespace RynthCore.RynthAiHostTests.Tests; + +// /ub propertydump (2026-10-13): a tester found it "isn't exposing all item properties" next to +// UtilityBelt's. It probed fixed key ranges one key at a time; now it lists every key the engine +// holds (plugin API v84 GetObjectProperties), identifies the object first, chats in chunks and +// writes the whole dump to RynthAi\Logs. On an older engine it probes every named key. +internal static class PropertyDumpTests +{ + private const uint Player = 0x50000A01, Coat = 0x80001234, Pack = 0x80001200; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("propertydump: every key the engine holds, by type, named, ids in hex, spells by name", ListsEverything); + r.Add("propertydump: layout like UtilityBelt's (header, sections sorted by name, unknown keys as numbers)", Layout); + r.Add("propertydump: an unidentified item is identified first and dumped when the answer arrives", WaitsForId); + r.Add("propertydump: no identify answer in time - dumps what the client has, and says so", IdTimeout); + r.Add("propertydump: waits a moment for the engine's main-thread qualities read", QualitiesPending); + r.Add("propertydump: long dumps reach chat in chunks; the full dump goes to RynthAi\\Logs", ChunksAndFile); + r.Add("propertydump: an engine before v84 probes every named key, past the old ranges", OlderEngineFallback); + r.Add("propertydump: /ub, /vt and /ra all route to it; nothing selected = the character", Routes); + } + + private sealed class Bot + { + public readonly RynthAiPlugin P = new(); + public long Now = 1_000_000; + + public Bot() + { + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + Set("_playerId", Player); + Set("_loginComplete", true); + Set("_initialized", true); // OnChatBarEnter routes /ub, /vt and /ra only once initialized + P.PropertyDumpClock = () => Now; + // /vt propertydump goes through MetaManager.TryHandleVtCommand back to /ra. + var meta = new RynthCore.Plugin.RynthAi.Meta.MetaManager(new RynthCore.Plugin.RynthAi.LegacyUi.LegacyUiSettings(), + new RynthCoreHost(FakeHost.LastApi), new PlayerVitalsCache()); + var ra = typeof(RynthAiPlugin).GetMethod("HandleRaCommand", Any)!; + meta.SetRaCommandHandler(cmd => ra.Invoke(P, new object[] { cmd })); + Set("_metaManager", meta); + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public void Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a); + public void Tick() => Call("TickPropertyDump", false); + public void Ra(string line) + { + string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(P, new object[] { parts[1].ToLowerInvariant(), parts, 0 }); + } + public void DrainAll() { for (int i = 0; i < 200; i++) Tick(); } + public string AllChat => string.Join("\n", FakeHost.Chat); + } + + private static string DumpFolder() + { + string dir = Path.Combine(Program.TempRoot, "propdump-" + Guid.NewGuid().ToString("N")[..8]); + PropertyDump.FolderOverride = dir; + return dir; + } + + private static PropertyBag CoatBag() + { + var b = new PropertyBag(); + b.Ints[1] = 2; // ItemType Armor + b.Ints[19] = 15000; // Value + b.Ints[28] = 210; // ArmorLevel + b.Ints[9015] = 3; // InventoryOrder: no fixed range reached it + b.Ints[4242] = 7; // a key with no name + b.Int64s[4] = 123456789012L; // ItemTotalXp: int64s had no names + b.Bools[22] = true; // Inscribable + b.Floats[13] = 1.3; // ArmorModVsSlash: floats had no names + b.Floats[167] = 2.5; // CooldownDuration + b.Strings[1] = "Olthoi Amuli Coat"; + b.Strings[16] = "A heavy coat."; + b.DataIds[8] = 0x06001F88; // Icon + b.DataIds[8044] = 0x1234; // PCAPPhysicsDIDDataTemplatedFrom: past the old 0-80 range + b.InstanceIds[2] = Pack; // Container + b.InstanceIds[38] = Player; // AllowedWielder + return b; + } + + private static void Setup(Func records, bool appraised = true) + { + FakeHost.Reset(); + FakeHost.Names[Player] = "Tester"; + FakeHost.Names[Coat] = "Olthoi Amuli Coat"; + FakeHost.Names[Pack] = "Pack"; + FakeHost.Wcids[Coat] = 37191; + FakeHost.WeaponCalls = true; // RequestId + HasAppraisalData + FakeHost.ObjectPropertiesCalls = true; + FakeHost.PropertyRecord = records; + if (appraised) FakeHost.Appraised.Add(Coat); + FakeHost.Create(Player); + } + + private static byte[] CoatRecord(EngineFlags flags = EngineFlags.HasIdData | EngineFlags.QualitiesRead) => + ObjectPropertyRecord.Encode(CoatBag(), new uint[] { 2783, 4400, 99999 }, flags, 1_760_000_000L); + + private static void ListsEverything() + { + DumpFolder(); + Setup(id => id == Coat ? CoatRecord() : null); + var bot = new Bot(); + bot.Set("_currentTargetId", Coat); + bot.Ra("/ra dumpprops"); + bot.DrainAll(); + string chat = bot.AllChat; + Check.True(chat.Contains("Property Dump for Olthoi Amuli Coat"), "header"); + Check.True(chat.Contains(" InventoryOrder (9015) = 3"), "an int past the old 0-400 range"); + Check.True(chat.Contains(" 4242 = 7"), "an unknown key as its number"); + Check.True(chat.Contains(" ItemTotalXp (4) = 123456789012"), "int64 named"); + Check.True(chat.Contains(" ArmorModVsSlash (13) = 1.3"), "float named"); + Check.True(chat.Contains(" Inscribable (22) = True"), "bool as True/False"); + Check.True(chat.Contains(" Icon (8) = 0x06001F88"), "data id in hex"); + Check.True(chat.Contains(" PCAPPhysicsDIDDataTemplatedFrom (8044) = 0x00001234"), "data id past the old 0-80 range"); + Check.True(chat.Contains(" Container (2) = 0x80001200 (Pack)"), "instance id in hex with the object's name"); + Check.True(chat.Contains(" AllowedWielder (38) = 0x50000A01 (Tester)"), "instance id 38"); + Check.True(chat.Contains("Spells (3):"), "spell book"); + Check.True(chat.Contains("(2783)") && chat.Contains("(4400)") && chat.Contains("(99999)"), "every spell by id"); + Check.True(chat.Contains("Total: 15 properties"), "total (" + chat.Split('\n').LastOrDefault(l => l.Contains("Total")) + ")"); + Check.False(chat.Contains("Older RynthCore engine"), "no older-engine note on v84"); + Check.Eq(FakeHost.IdRequests.Count, 0, "already identified: no new ID request"); + } + + private static void Layout() + { + var d = new PropertyDumpData { Id = Coat, Name = "Coat", Wcid = 37191, ObjectClass = "Armor", ObjectClassValue = 2, HasIdData = true, Complete = true }; + d.Ints[19] = 5; d.Ints[1] = 2; d.Ints[5000] = 1; d.Ints[4999] = 1; + d.Strings[1] = "Coat"; + d.InstanceIds[2] = Pack; + d.Spells.Add(2783); + List lines = PropertyDump.Format(d, s => "Spell" + s, id => id == Pack ? "Pack" : null); + Check.Eq(lines[0], "Property Dump for Coat", "first line"); + Check.Eq(lines[1], $"Id = {Coat} (0x{Coat:X8})", "id line"); + Check.True(lines.Contains("Type (wcid) = 37191") && lines.Contains("ObjectClass = Armor (2)"), "wcid, object class"); + Check.True(lines.Contains("Container = 0x80001200 (Pack)") && lines.Contains("HasIdData = True"), "container, id data"); + int strings = lines.IndexOf("String Values:"), ints = lines.IndexOf("Int Values:"), iids = lines.IndexOf("InstanceId Values:"), spells = lines.IndexOf("Spells (1):"); + Check.True(strings > 0 && strings < ints && ints < iids && iids < spells, "sections in UB's order, spells last"); + Check.False(lines.Contains("Bool Values:"), "an empty section is left out"); + Check.Eq(lines[ints + 1], " ItemType (1) = 2", "ints sorted by name: ItemType"); + Check.Eq(lines[ints + 2], " Value (19) = 5", "then Value"); + Check.Eq(lines[ints + 3], " 4999 = 1", "unknown keys after the named ones, by number"); + Check.Eq(lines[spells + 1], " Spell2783 (2783)", "spell line"); + Check.Eq(PropertyDump.FileName("Olthoi Amuli Coat", new DateTime(2026, 10, 13, 9, 5, 7)), "propertydump-Olthoi_Amuli_Coat-20261013-090507.txt", "file name"); + Check.Eq(PropertyDump.FileName("<>:|?*", DateTime.MinValue), "propertydump-object-00010101-000000.txt", "unsafe name"); + } + + private static void WaitsForId() + { + DumpFolder(); + bool idArrived = false; + Setup(id => id != Coat ? null + : idArrived ? CoatRecord() + : ObjectPropertyRecord.Encode(new PropertyBag(), null, EngineFlags.HasCreateData, 0), appraised: false); + var bot = new Bot(); + bot.Set("_currentTargetId", Coat); + bot.Call("HandleRynthChatSubmit", "/ub propertydump"); + Check.True(FakeHost.IdRequests.Contains(Coat), "asked the server for an ID"); + Check.True(bot.AllChat.Contains("isn't identified yet"), "said so"); + Check.False(bot.AllChat.Contains("Property Dump for"), "no dump before the answer"); + bot.Now += 300; bot.Tick(); + Check.False(bot.AllChat.Contains("Property Dump for"), "still waiting"); + FakeHost.Appraised.Add(Coat); idArrived = true; + bot.Now += 150; bot.DrainAll(); + Check.True(bot.AllChat.Contains("Property Dump for Olthoi Amuli Coat") && bot.AllChat.Contains("InventoryOrder (9015) = 3"), "the dump after the answer, in full"); + Check.Eq(FakeHost.IdRequests.Count(i => i == Coat), 1, "one ID request"); + } + + private static void IdTimeout() + { + DumpFolder(); + var bag = new PropertyBag(); bag.Ints[19] = 100; bag.Strings[1] = "Olthoi Amuli Coat"; + Setup(id => id == Coat ? ObjectPropertyRecord.Encode(bag, null, EngineFlags.HasCreateData, 0) : null, appraised: false); + var bot = new Bot(); + bot.Ra($"/ra dumpprops 0x{Coat:X8}"); + bot.Now += 1000; bot.Tick(); + Check.False(bot.AllChat.Contains("Property Dump for"), "waiting inside the 4 s"); + bot.Now += 3500; bot.DrainAll(); + Check.True(bot.AllChat.Contains("No identify answer"), "the timeout is said"); + Check.True(bot.AllChat.Contains(" Value (19) = 100"), "what the client has is dumped"); + Check.True(bot.AllChat.Contains("Not identified"), "the not-identified note"); + } + + private static void QualitiesPending() + { + DumpFolder(); + int calls = 0; + Setup(id => + { + if (id != Coat) return null; + calls++; + return calls <= 2 ? CoatRecord(EngineFlags.HasIdData | EngineFlags.QualitiesPending) : CoatRecord(); + }); + var bot = new Bot(); + bot.Set("_currentTargetId", Coat); + bot.Ra("/ra dumpprops"); + Check.False(bot.AllChat.Contains("Property Dump for"), "pending: not yet"); + bot.Now += 50; bot.Tick(); + Check.False(bot.AllChat.Contains("Property Dump for"), "inside the poll interval nothing is asked"); + bot.Now += 100; bot.Tick(); // second query: still pending + bot.Now += 100; bot.DrainAll(); + Check.True(bot.AllChat.Contains("Property Dump for"), "dumped once the read is in"); + + // An engine that never finishes the read: dumped anyway after the wait. + Setup(id => id == Coat ? CoatRecord(EngineFlags.HasIdData | EngineFlags.QualitiesPending) : null); + bot = new Bot(); + bot.Set("_currentTargetId", Coat); + bot.Ra("/ra dumpprops"); + bot.Now += 2000; bot.DrainAll(); + Check.True(bot.AllChat.Contains("Property Dump for"), "never finished: dumped after the wait"); + } + + private static void ChunksAndFile() + { + string dir = DumpFolder(); + var big = CoatBag(); + for (uint k = 5000; k < 5200; k++) big.Ints[k] = (int)k; + Setup(id => id == Coat ? ObjectPropertyRecord.Encode(big, null, EngineFlags.HasIdData, 0) : null); + var bot = new Bot(); + bot.Set("_currentTargetId", Coat); + int before = FakeHost.Chat.Count; + bot.Ra("/ra dumpprops"); + int first = FakeHost.Chat.Count - before; + Check.True(first <= PropertyDump.ChatLinesPerTick, $"first chunk {first} lines"); + bot.Tick(); + Check.True(FakeHost.Chat.Count - before <= 2 * PropertyDump.ChatLinesPerTick, "one more chunk per tick"); + bot.DrainAll(); + Check.True(bot.AllChat.Contains(" 5199 = 5199"), "the last line reaches chat"); + string[] files = Directory.Exists(dir) ? Directory.GetFiles(dir, "propertydump-Olthoi_Amuli_Coat-*.txt") : Array.Empty(); + Check.Eq(files.Length, 1, "one file in RynthAi\\Logs"); + if (files.Length == 1) + { + string[] text = File.ReadAllLines(files[0]); + Check.True(text[0] == "Property Dump for Olthoi Amuli Coat" && text.Contains(" 5199 = 5199"), "the full dump, without chat prefixes"); + Check.True(bot.AllChat.Contains("written to " + files[0]), "chat says where"); + } + } + + private static void OlderEngineFallback() + { + DumpFolder(); + FakeHost.Reset(); + FakeHost.Names[Player] = "Tester"; + FakeHost.Names[Coat] = "Olthoi Amuli Coat"; + FakeHost.Ints[(Coat, 19)] = 15000; + FakeHost.Ints[(Coat, 9015)] = 3; // named, past the old range: now probed + FakeHost.Ints[(Coat, 4242)] = 7; // unnamed, past the range: an older engine can't know it + FakeHost.Doubles[(Coat, 167)] = 2.5; // CooldownDuration + FakeHost.Strings[(Coat, 1)] = "Olthoi Amuli Coat"; + FakeHost.DataIds[(Coat, 8)] = 0x06001F88; + FakeHost.SpellIds[Coat] = new uint[] { 2783 }; + FakeHost.Create(Player); // no ObjectPropertiesCalls: GetObjectProperties absent + var bot = new Bot(); + PropertyDumpData? d = bot.P.CollectPropertyDump(Coat, out bool pending); + Check.True(d != null && !pending && !d.Complete, "collected without v84"); + Check.True(d!.Ints.TryGetValue(9015, out int io) && io == 3 && d.Ints[19] == 15000, "named keys past the old ranges"); + Check.False(d.Ints.ContainsKey(4242), "an unnamed key beyond the ranges stays unknown (older engine)"); + Check.True(d.Floats.TryGetValue(167, out double cd) && cd == 2.5 && d.DataIds[8] == 0x06001F88, "float and data id probed"); + Check.True(d.Spells.SequenceEqual(new uint[] { 2783 }), "spells from GetObjectSpellIds"); + bot.Set("_currentTargetId", Coat); + bot.Ra("/ra dumpprops"); + bot.DrainAll(); + Check.True(bot.AllChat.Contains("Older RynthCore engine"), "the older-engine note"); + Check.True(bot.AllChat.Contains(" CooldownDuration (167) = 2.5"), "names on the fallback too"); + } + + private static void Routes() + { + DumpFolder(); + var selfBag = new PropertyBag(); selfBag.Ints[25] = 275; selfBag.Strings[1] = "Tester"; + Setup(id => id == Player ? ObjectPropertyRecord.Encode(selfBag, null, EngineFlags.IsPlayer, 0) + : id == Coat ? CoatRecord() : null); + var bot = new Bot(); + bot.Ra("/ra dumpprops"); + bot.DrainAll(); + Check.True(bot.AllChat.Contains("Nothing selected") && bot.AllChat.Contains(" Level (25) = 275"), "nothing selected: the character"); + Check.Eq(FakeHost.IdRequests.Count, 0, "the character isn't identified first"); + + FakeHost.Chat.Clear(); + bot.Set("_currentTargetId", Coat); + bot.Ra("/ra propertydump"); + bot.DrainAll(); + Check.True(bot.AllChat.Contains("Property Dump for Olthoi Amuli Coat"), "/ra propertydump (the hotkey's command)"); + + FakeHost.Chat.Clear(); + bot.Call("HandleRynthChatSubmit", "/vt propertydump"); + bot.DrainAll(); + bool vt = bot.AllChat.Contains("Property Dump for Olthoi Amuli Coat"); + FakeHost.Chat.Clear(); + bot.Call("HandleRynthChatSubmit", "/ub propertydump"); + bot.DrainAll(); + bool ub = bot.AllChat.Contains("Property Dump for Olthoi Amuli Coat"); + Check.True(ub, "/ub propertydump"); + Check.True(vt, "/vt propertydump"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/UseAtLoginTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/UseAtLoginTests.cs index 26713cd..5dddbe5 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/UseAtLoginTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/UseAtLoginTests.cs @@ -282,20 +282,31 @@ internal static class UseAtLoginTests bot.S.IsMacroRunning = true; bot.S.OpenDoors = false; // only the requested door bot.Set("_doorRequestedId", unchecked((int)Door)); + long now = 70_000_000; + RynthAiPlugin.DoorClock = () => now; + // The targeting tick stops the character; the use goes on the next one (2026-10-13: + // it waits for its turn - ActionPacer, the client's busy count). + bot.Call("TickDoorInteraction"); bot.Call("TickDoorInteraction"); Check.Eq(FakeHost.Uses.Count(u => u == Door), 1, "the requested door is used once"); Check.True(FakeHost.Logs.Any(l => l.Contains("[Use] RynthAi/Door") && l.Contains("nav detour")), "logged with the reason"); // The fake never reports the door open. Right after the use: still waiting. for (int i = 0; i < 5; i++) bot.Call("TickDoorInteraction"); - Check.False(FakeHost.Logs.Any(l => l.Contains("not open after use")), "not judged 'not open' within ms of the use"); + Check.False(FakeHost.Logs.Any(l => l.Contains("not open")), "not judged 'not open' within ms of the use"); Check.Eq(FakeHost.Uses.Count(u => u == Door), 1, "and not used again (a second use would close it)"); - Thread.Sleep(1300); + // No UseDone count on this fake engine: the use counts as answered after 600 ms, then + // the door gets its time to swing. + now += 700; bot.Call("TickDoorInteraction"); - Check.True(FakeHost.Logs.Any(l => l.Contains("not open after use")), "judged once the door had time to swing"); + Check.False(FakeHost.Logs.Any(l => l.Contains("not open")), "not judged right at the answer"); + now += 1300; + bot.Call("TickDoorInteraction"); + Check.True(FakeHost.Logs.Any(l => l.Contains("not open")), "judged once the door had time to swing"); + Check.False(FakeHost.Logs.Any(l => l.Contains("is locked")), "and not called locked (the server never said so)"); } - finally { Done(); } + finally { RynthAiPlugin.DoorClock = static () => Environment.TickCount64; Done(); } } }