From 6847868401eb3b9e6347614a9ccd4e9c86ee7696 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Mon, 5 Oct 2026 14:59:43 -0400 Subject: [PATCH] RynthSuite as of 2026-10-05 evening (internal a078b8e): release 2026.10.5.20 - healing delay fixes, stuck-cast safeguards, buffs over items, slayers recognised and chosen first, recover my corpse, /ub give and /mt give, Mana Tap skips wands, dungeon floor-plan bake, heal latency log --- Plugins/Directory.Build.props | 10 + Plugins/Directory.Build.targets | 12 + .../ActivityArbiter.cs | 16 + .../Combat/BuffManager.cs | 862 ++++++++++++++++-- .../Combat/CastTracker.cs | 255 ++++++ .../Combat/CombatManager.cs | 53 +- .../Combat/HealLatencyTracker.cs | 205 +++++ .../Combat/ReloadSafety.cs | 32 + .../Combat/WeaponPlanner.cs | 74 +- .../CorpseOpenController.cs | 237 ++++- .../CreatureData/CreatureWeakness.cs | 16 + .../DoorInteractionController.cs | 2 +- Plugins/RynthCore.Plugin.RynthAi/Jumper.cs | 3 +- .../LegacyUi/DungeonMapUi.cs | 274 +++--- .../LegacyUi/LegacyAdvancedSettingsUi.cs | 13 + .../LegacyUi/LegacyDashboardRenderer.cs | 24 +- .../LegacyUi/LegacyNavigationUi.cs | 5 +- .../LegacyUi/LegacyUiSettings.cs | 32 + .../Loot/LootEditorBridge.cs | 35 + .../Loot/ScrollLearner.cs | 20 +- .../MagToolsCommands.cs | 9 +- .../ManaStoneManager.cs | 5 +- .../Maps/DungeonMapBake.cs | 279 ++++++ .../Meta/ExpressionEngine.cs | 9 +- .../NavigationEngine.cs | 76 +- .../RynthCore.Plugin.RynthAi/PluginExports.cs | 28 + .../RynthAiCommands.cs | 98 +- .../RynthAiPlugin.OwnCorpse.cs | 687 ++++++++++++++ .../RynthAiPlugin.Safety.cs | 6 + .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 160 +++- .../RynthCore.Plugin.RynthAi.csproj | 13 + .../StatusInterface.cs | 2 +- .../UtilityBeltCommands.cs | 16 + .../Vendor/AutoVendorManager.cs | 6 +- .../RynthCore.Plugin.RynthChat.csproj | 3 + .../RynthCore.Plugin.RynthInventory.csproj | 4 + .../RynthCore.Plugin.RynthLua.csproj | 9 + .../RynthCore.Plugin.RynthNav.csproj | 4 + .../RynthCore.Plugin.RynthNet.csproj | 9 + .../RynthCore.Plugin.RynthOracle.csproj | 4 + .../RynthCore.Plugin.RynthTracker.csproj | 4 + .../RynthCore.Plugin.RynthVision.csproj | 4 + Plugins/Shared/MoveAudit.cs | 136 +++ .../RynthCore.LootSdk/Editing/LootEditWire.cs | 6 + Shared/RynthCore.TerrainData/DatDatabase.cs | 781 ++++++++-------- THIRD-PARTY-NOTICES.md | 31 + Tools/RynthCore.DatReaderCheck/Program.cs | 373 ++++++++ .../RynthCore.DatReaderCheck.csproj | 43 + .../LootAddItemTests.cs | 15 + .../Fakes/FakeHost.cs | 55 +- Tools/RynthCore.RynthAiHostTests/Program.cs | 7 + .../Tests/BuffTests.cs | 123 +++ .../Tests/CastSafetyTests.cs | 457 ++++++++++ .../Tests/DungeonMapBakeTests.cs | 217 +++++ .../Tests/GiveTests.cs | 121 +++ .../Tests/HealLatencyTests.cs | 331 +++++++ .../Tests/LootAddItemTests.cs | 121 ++- .../Tests/OwnCorpseTests.cs | 461 ++++++++++ .../Tests/VitalsTests.cs | 114 +++ .../Tests/WeaponTests.cs | 129 ++- 60 files changed, 6364 insertions(+), 772 deletions(-) create mode 100644 Plugins/Directory.Build.targets create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/CastTracker.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/HealLatencyTracker.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/ReloadSafety.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Maps/DungeonMapBake.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OwnCorpse.cs create mode 100644 Plugins/Shared/MoveAudit.cs create mode 100644 Tools/RynthCore.DatReaderCheck/Program.cs create mode 100644 Tools/RynthCore.DatReaderCheck/RynthCore.DatReaderCheck.csproj create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/CastSafetyTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/DungeonMapBakeTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/HealLatencyTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/OwnCorpseTests.cs diff --git a/Plugins/Directory.Build.props b/Plugins/Directory.Build.props index c5e824d..3b60288 100644 --- a/Plugins/Directory.Build.props +++ b/Plugins/Directory.Build.props @@ -11,4 +11,14 @@ + + + + RynthSuite + https://aelrynth.com/rynth.html + MIT + diff --git a/Plugins/Directory.Build.targets b/Plugins/Directory.Build.targets new file mode 100644 index 0000000..04a6051 --- /dev/null +++ b/Plugins/Directory.Build.targets @@ -0,0 +1,12 @@ + + + + <_RynthCoreSdkTargets>$(MSBuildThisFileDirectory)..\..\RynthCore\src\RynthCore.PluginSdk\build\RynthCore.PluginSdk.targets + + + diff --git a/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs b/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs index 7ebc41a..b04ec15 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs @@ -149,6 +149,22 @@ internal sealed class ActivityArbiter _ => "Default", }; + /// + /// What a display shows for the bot's activity (the RynthAi dashboard and the phone, through + /// the snapshot's "botAction"; RynthNet's status "action"). The same as the BotAction control + /// string except for "Buffing", which is one slot for every vitals and buff job: there it is + /// (Healing, Restoring mana, Restoring stamina or Buffing). + /// Healing showed as "Buffing" on both (2026-10-05). The control string itself never changes: + /// CombatManager's canRun and CorpseOpenController compare against "Buffing". + /// + public static string DisplayLabel(string? botAction, string? buffingLabel) + { + string action = string.IsNullOrEmpty(botAction) ? "Default" : botAction; + if (string.Equals(action, "Buffing", OIC) && !string.IsNullOrEmpty(buffingLabel)) + return buffingLabel; + return action; + } + /// /// STEP 1 shadow mode. Compute the would-be decision and log it whenever /// it (or the legacy BotAction it's being compared against) changes. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 76cb525..2d2d7bd 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -120,6 +120,12 @@ public class BuffManager : IDisposable // recorded (live refresh or post-cast). Max-of-observed so it converges to // the character's true ceiling after the first cast. private readonly Dictionary _familyAchievedTier = new(); + // Every live player enchantment per family from the last RefreshFromLiveMemory + // (_ramBuffTimers keeps only the strongest). Lets a family read "on" when the + // strongest entry is running out but another one at the tier we'd cast is under it: + // a buff bot's level 8 expiring over our own fresh VI (2026-10-05). Permanent marks an + // item-granted entry (no expiry), which CastBuffsOverItemBuffs leaves out. + private readonly Dictionary> _familyLiveEntries = new(); // Highest tier this session has CAST per family (nominal level). The achieved-tier cap // applies only once the target tier has been tried, so a family deliberately cast low // first (the tier-7 creature bootstrap before 8s) still upgrades. @@ -234,20 +240,40 @@ public class BuffManager : IDisposable // a slower tier-8 cast simply produces a later UseDone. Bounded by a timeout // so a dropped event can't wedge buffing, and inert (never waits) on an // engine build without UseDone observation. - private int _useDoneSeqAtCast; - private bool _awaitingCastResolution; - private DateTime _castResolutionDeadline = DateTime.MinValue; - private const double CastResolutionTimeoutMs = 2500; // covers a tier-7/8 windup+recoil + // + // 2026-10-05 (Drakkon, DreamWeave): "finished" used to be ANY new UseDone, and the refusal + // of the next cast is a UseDone too (err 0x1D), so under a refusal storm the wait cleared at + // once. The wait now belongs to the cast: see CastTracker.AwaitingServer. + private const double CastResolutionTimeoutMs = 2500; // from the send; later when the incantation is late + // Sends, incantations, results and the server's UseDones for the casts this class sends. + private readonly CastTracker _cast; + + /// Clock for the cast-safety timing (give-up, server wait, held-cast nudge, stance + /// settle). The host tests replace it; everything else here reads DateTime.Now. + internal Func Clock { get => _cast.Clock; set => _cast.Clock = value; } + private DateTime Now => _cast.Now; + + // Held-cast nudge (2026-10-05): a cast the server holds open (incantation, no result) is + // only let go by a movement packet; StopCompletely from a standing character may send none. + // Once per held cast: autorun on and straight off again, then no cast for this long. + private const double NudgeHoldMs = 2000; + /// Movement nudges sent for held casts this session (/ra status, tests). + internal int CastNudges { get; private set; } private int _busyRefusalStreak; private DateTime _busyBackoffUntil = DateTime.MinValue; private const double BusyBackoffBaseMs = 500; private const double BusyBackoffMaxMs = 8000; + // During a too-busy backoff a heal may still retry, but no faster than this. + private const double BusyHealRetryMs = 1500; + // Refusals in a row (with backoff, about 3.5 s or more) before StopCompletely: longer than any real gesture. + private const int BusyStopAtStreak = 4; // "Not enough mana" refusal (see OnChatWindowText): the refused family rests // briefly and buffing pauses; neither is a silent-no-show strike. private DateTime _lowManaPauseUntil = DateTime.MinValue; private const double LowManaBuffPauseMs = 5000; + private const double LowManaHealRestSec = 2; private const double LowManaFamilyRestSec = 15; private readonly Dictionary _castIssuedAtByFamily = new(); @@ -335,8 +361,52 @@ public class BuffManager : IDisposable public int CurrentCombatMode => _host.HasGetCurrentCombatMode ? _host.GetCurrentCombatMode() : CombatMode.NonCombat; - /// Client busy count — when > 0, don't send any game actions. - public int BusyCount { get; set; } + /// Client busy count — when > 0, don't send any game actions (but see + /// : a heal goes ahead of a leftover count). + public int BusyCount + { + get => _busyCount; + set + { + _busyCount = value; + _busyGate.NoteCount(value, UseDoneSeqNow()); + } + } + private int _busyCount; + + // A heal and a leftover busy count (2026-10-05, a mage's heals "sometimes several seconds + // late"): a war or void cast raises the plugin's busy count, and AC lowers its own count + // inline when the server's UseDone arrives, where the busy hook can't see it, so the plugin's + // count sits at 1 until CheckBusyTimeout force-clears it 5 s after it rose (CombatBusyGate). + // Combat checks for that leftover before each attack. A heal never did: once health crossed a + // line the arbiter gave the tick to vitals, combat stopped running, nobody cleared the count, + // and the heal waited out the rest of the 5 s. How late depended on how long before the drop + // the last war spell went out. Heals now use the same rule combat does. + private readonly CombatBusyGate _busyGate = new(); + private Action? _onStaleBusy; + /// Resets the plugin's shared busy mirror when a heal finds the count is a leftover + /// (the same callback combat uses). Set by RynthAiPlugin. + public void SetStaleBusyCallback(Action cb) => _onStaleBusy = cb; + + /// + /// True while the busy count should hold a heal: it is positive and not a leftover. A leftover + /// (a UseDone arrived after the count last rose and no cast gesture is animating: the server + /// finished every action behind it) is cleared here, as combat does, and lets the heal go. + /// + internal bool BusyHoldsHeal() + { + if (BusyCount <= 0) return false; + bool gesture = _host.HasGetCastBusyState && !_host.CanCastNow; + if (!_busyGate.IsStale(BusyCount, _host.HasUseDoneSeq, UseDoneSeqNow(), gesture)) return true; + int was = BusyCount; + StaleBusyClears++; + _onStaleBusy?.Invoke($"vitals: health is under a heal line and the server finished the action (UseDone) — was {was}"); + if (BusyCount > 0) BusyCount = 0; // no callback, or the shared mirror was already 0 + _busyGate.Reset(); + return false; + } + /// Times a heal found the busy count was a leftover and went ahead (tests, status). + internal int StaleBusyClears { get; private set; } /// /// Record-only diagnostic (D4): the reason the most recent buff-decision cycle @@ -402,6 +472,8 @@ public class BuffManager : IDisposable _settings = settings; _spellManager = spellManager; _vitals = vitals; + _cast = new CastTracker(s => _host.Log(s)); + _healLatency = new HealLatencyTracker(s => _host.Log(s)); } public void SetCharacterSkills(CharacterSkills skills) => _charSkills = skills; @@ -576,14 +648,86 @@ public class BuffManager : IDisposable return HealthUnderAnyLine(_vitals.HealthPct, _vitals.StaminaPct); } - private bool HealthUnderAnyLine(int hp, int stamPct) + private bool HealthUnderAnyLine(int hp, int stamPct) => ActiveHealLine(hp, stamPct, out _, out _).Length > 0; + + /// For the engine's reload deferral (ReloadSafety): the heal line health is under now + /// ("" = none, or vitals not read yet), with the health and the line's value. + internal string HealLineNow(out int healthPct, out int lineValue) { - if (_settings.EmergencyHealAt > 0 && hp <= _settings.EmergencyHealAt) return true; - if (StaminaToHealthAllowed(_settings, hp, stamPct)) return true; - bool inCombat = _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true; - return hp < (inCombat ? _settings.HealAt : _settings.TopOffHP); + healthPct = _vitals.HealthPct; + lineValue = 0; + if (_vitals.MaxHealth == 0) return ""; + return ActiveHealLine(healthPct, _vitals.StaminaPct, out lineValue, out _); } + /// For the engine's reload deferral: the cast awaiting its result (pending, or held + /// open by the server), or "". + internal string CastInFlightName + { + get + { + if (_pendingSpellId != 0) return SpellTableStub.GetById(_pendingSpellId)?.Name ?? $"spell {_pendingSpellId}"; + return _cast.Held?.Name ?? ""; + } + } + + /// + /// The heal line health is under, by name ("" = none): Emergency Heal At, Stamina To Health At, + /// Heal At (a monster within MonsterRange) or Top Off HP (idle). The same test HealthUnderAnyLine + /// always made; the name and value are for [HealLatency]. + /// + private string ActiveHealLine(int hp, int stamPct, out int value, out bool inCombat) + { + inCombat = _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true; + value = 0; + if (_settings.EmergencyHealAt > 0 && hp <= _settings.EmergencyHealAt) { value = _settings.EmergencyHealAt; return "Emergency Heal At"; } + if (StaminaToHealthAllowed(_settings, hp, stamPct)) { value = _settings.StaminaToHealthAt; return "Stamina To Health At"; } + value = inCombat ? _settings.HealAt : _settings.TopOffHP; + if (hp < value) return inCombat ? "Heal At" : "Top Off HP"; + return ""; + } + + // ── What the activity display says while the arbiter's slot is "Buffing" ── + // BotAction stays "Buffing" for every vitals job: it is a control string (CombatManager's + // canRun and CorpseOpenController read it). The dashboard and the phone showed it as is, so a + // heal read "Buffing" (2026-10-05). The display label says which job it is. + public const string LabelHealing = "Healing"; + public const string LabelMana = "Restoring mana"; + public const string LabelStamina = "Restoring stamina"; + public const string LabelBuffing = "Buffing"; + + /// + /// Why the vitals/buff slot is held, for display: Healing, Restoring mana, Restoring stamina or + /// Buffing. The cast or kit in flight says it first; then health under a heal line; then what + /// the last vitals check started. Side-effect free (KitPending is not called). + /// + public string BuffingLabel + { + get + { + if (_pendingSpellId != 0 && _pendingSpellId == _pendingVitalSpellId && _pendingVitalLabel.Length > 0) + return _pendingVitalLabel; + if (_kitUsedAt != DateTime.MinValue && (DateTime.Now - _kitUsedAt).TotalMilliseconds < KitResultTimeoutMs) + return _kitIsStamina ? LabelStamina : LabelHealing; + if (_isHealingSelf || WantsHealNow()) return LabelHealing; + if (_pendingSpellId != 0) return LabelBuffing; + if (_isRechargingMana) return LabelMana; + if (_isRechargingStamina) return LabelStamina; + return LabelBuffing; + } + } + + /// The display label for a vital spell's base name (AttemptVitalCast's argument). + internal static string VitalLabel(string baseName) => baseName switch + { + "Heal Self" or "Stamina to Health Self" => LabelHealing, + "Stamina to Mana Self" => LabelMana, + "Revitalize Self" => LabelStamina, + _ => LabelBuffing, + }; + private string _pendingVitalLabel = ""; + private bool _kitIsStamina; + public BuffStateSnapshot GetStateSnapshot() => new() { EnableBuffing = _settings.EnableBuffing, @@ -621,6 +765,17 @@ public class BuffManager : IDisposable } private bool _liveBuffsRefreshed; + /// Host tests: skip the login refresh wait so OnHeartbeat runs at once. + internal void MarkLiveBuffsReadyForTests() => _liveBuffsRefreshed = true; + /// The login refresh has a trusted snapshot of the live buffs (buff casting may start). + public bool LiveBuffsReady => _liveBuffsRefreshed; + /// + /// Set by RynthAiPlugin when this login is a hot reload (engine or plugin) of a character + /// that was already in game in this client: the enchantment registry is complete, so the + /// login refresh trusts its first read instead of waiting for two equal reads (5.8 s after + /// the 2026-10-05 reload). + /// + public bool CarriedOverSession { get; set; } private DateTime _lastLiveRefreshAttempt = DateTime.MinValue; private DateTime _lastPeriodicRefreshAt = DateTime.MinValue; private const int PeriodicRefreshIntervalMs = 30_000; @@ -634,7 +789,53 @@ public class BuffManager : IDisposable private int _lastLoginRefreshCount = -1; private const int LoginRefreshMaxWaitMs = 20_000; + // ── [HealLatency] (see HealLatencyTracker) ───────────────────────────────── + private readonly HealLatencyTracker _healLatency; + internal HealLatencyTracker HealLatency => _healLatency; + // Why this heartbeat sent no heal (the tracker files the tick's time under it), plus a detail. + private string _healHold = ""; + private string _healHoldDetail = ""; + // What a vitals step that "handled" the tick without sending anything was waiting on. + private string _healWaitKind = ""; + /// The arbiter's last decision (set by RynthAiPlugin after it decides), for [HealLatency]. + internal string ArbiterActivity { get; set; } = ""; + + private void Hold(string why, string detail = "") + { + _healHold = why; + _healHoldDetail = detail; + } + + /// A heal (kit or spell) sent earlier hasn't resolved yet. + private bool HealInFlight() => + (_pendingSpellId != 0 && _pendingSpellId == _pendingVitalSpellId && _pendingVitalLabel == LabelHealing) + || (_kitUsedAt != DateTime.MinValue && !_kitIsStamina && (DateTime.Now - _kitUsedAt).TotalMilliseconds < KitResultTimeoutMs); + public void OnHeartbeat() + { + bool track = _settings.IsMacroRunning && _vitals.MaxHealth > 0; + _healHold = ""; + _healHoldDetail = ""; + _healWaitKind = ""; + if (track) + { + string line = ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out int lineValue, out bool inCombat); + _healLatency.Observe(Now, _vitals.HealthPct, line, lineValue, inCombat, HealInFlight()); + } + try { HeartbeatCore(); } + finally + { + NoteStanceLateHolder(); + if (track) + { + string hold = _healHold; + if (hold.Length == 0 && DateTime.Now < _healUnavailableUntil) hold = "heal backoff (nothing could heal)"; + _healLatency.EndTick(Now, hold, _healHoldDetail, ArbiterActivity); + } + } + } + + private void HeartbeatCore() { // Requests queued from other threads (see RequestForceFullRebuff), in click order // as far as it matters: a cancel after a rebuff request wins. @@ -655,11 +856,24 @@ public class BuffManager : IDisposable if (!_settings.IsMacroRunning) return; + // Close casts the server reports finished, and say once when one is being held open. + PollCastTracker(); + + // A Magic stance we asked for: watch the client's mode every tick (see ObserveStance). + ObserveStance(); + // RefreshFromLiveMemory at OnLoginComplete fails when the server-time // packet hasn't landed yet (GetServerTime returns 0). On those // logins we have NO timers and would recast every buff that has // hours left server-side. Retry every second until we get the - // live snapshot, and BLOCK any cast attempts in the meantime. + // live snapshot, and hold BUFF casts in the meantime. + // + // Heals are not held (2026-10-05, Drakkon died after an engine hot reload mid-fight: + // "health 12% under Emergency Heal At 30% ... held by: login buff refresh 5737 ms"). + // The refresh only protects buff timers; a heal, a kit or a potion never reads them, + // so the vitals step below runs during the refresh and only the buff casting after it + // waits (buffsHeldForRefresh). + bool buffsHeldForRefresh = false; if (!_liveBuffsRefreshed) { if ((DateTime.Now - _lastLiveRefreshAttempt).TotalMilliseconds > 1000) @@ -672,20 +886,32 @@ public class BuffManager : IDisposable // Only trust the snapshot once the registry stops growing // (two equal 1s reads), so we don't open the gate on a // half-streamed set and rebuff buffs that are still landing. + // After a hot reload (engine or plugin) the client never left the world and + // its registry is complete: the first read is trusted (CarriedOverSession), unless + // it is empty (a read that found nothing yet must not wipe every timer). bool stable = (n == _lastLoginRefreshCount); bool timedOut = (DateTime.Now - _loginRefreshStartAt).TotalMilliseconds > LoginRefreshMaxWaitMs; + bool carried = CarriedOverSession && n > 0; _lastLoginRefreshCount = n; - if (stable || timedOut) + if (stable || timedOut || carried) { _liveBuffsRefreshed = true; - _host.Log($"[BuffDiag] login refresh ready: {n} enchantment(s) (stable={stable} timedOut={timedOut})"); + string why = carried && !stable && !timedOut + ? "hot reload: still in game, the first read is complete" + : $"stable={stable} timedOut={timedOut}"; + _host.Log($"[BuffDiag] login refresh ready: {n} enchantment(s) ({why})"); _host.WriteToChat($"[RynthAi] Live buff timers ready ({n} loaded).", 1); } } } - // Don't cast anything until we have a real snapshot — otherwise + // Don't cast a buff until we have a real snapshot — otherwise // we'd recast over a 1-hour-old buff at the start of every login. - return; + buffsHeldForRefresh = !_liveBuffsRefreshed; + if (buffsHeldForRefresh && !HealthUnderAnyLine(_vitals.HealthPct, _vitals.StaminaPct)) + { + Hold("login buff refresh"); + return; + } } // Periodic re-sync: if the character died and lost all enchantments, the @@ -713,7 +939,7 @@ public class BuffManager : IDisposable // at worst a buff is recast later (2026-10-04). if (_pendingSpellId != 0 && _pendingSpellId != _pendingVitalSpellId && WantsHealNow() && (DateTime.Now - _lastCastAttempt).TotalMilliseconds >= HealInterruptMinMs - && BusyCount == 0 && CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s))) + && CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s)) && !BusyHoldsHeal()) { _host.Log($"[BuffDiag] health {_vitals.HealthPct}% under a heal line: released pending buff id={_pendingSpellId} to heal first."); _pendingSpellId = 0; @@ -733,9 +959,12 @@ public class BuffManager : IDisposable // releases the pending cast, with no strike. if (pendingSpell != null && _pendingSpellId == _pendingVitalSpellId) { - if ((DateTime.Now - _lastCastAttempt).TotalMilliseconds > SelfBuffGiveUpMs) + // Timed from the incantation when one arrived (2026-10-05): a healthy DreamWeave + // vital takes 2.2-2.5 s after its incantation, and 2.5 s from the send gave up on + // casts the server was still finishing. + if (PendingGiveUpReached(SelfBuffGiveUpMs)) { - _host.Log($"[BuffDiag] vital cast '{pendingSpell.Name}' (id={_pendingSpellId}) not confirmed by chat in {SelfBuffGiveUpMs:0}ms — released, no strike."); + _host.Log($"[BuffDiag] vital cast '{pendingSpell.Name}' (id={_pendingSpellId}) not confirmed by chat ({GiveUpWhy(SelfBuffGiveUpMs)}) — released, no strike."); _pendingSpellId = 0; _pendingVitalSpellId = 0; _onCastResolved?.Invoke("vital cast unconfirmed"); @@ -743,6 +972,7 @@ public class BuffManager : IDisposable else { TryEmergencyHealWhilePending(); + Hold(_pendingVitalLabel == LabelHealing ? "heal cast in flight" : "vital cast in flight", pendingSpell.Name); return; } } @@ -765,7 +995,9 @@ public class BuffManager : IDisposable // refreshed, and the late fizzle line then cleared the NEXT cast. // While the old entry hasn't moved, wait for the chat line or the // enchantment event; at the give-up it is judged exactly as before. - if (active && sinceCastMs <= SelfBuffGiveUpMs + // Give-up timed from the incantation when one arrived (see the vital path). + bool pastGiveUp = PendingGiveUpReached(SelfBuffGiveUpMs); + if (active && !pastGiveUp && _castIssuedAtByFamily.TryGetValue(pendingSpell.Family, out DateTime issuedAt) && _expiryAtCastByFamily.TryGetValue(pendingSpell.Family, out DateTime expiryThen) && expiryThen > issuedAt // it was on when we cast @@ -777,11 +1009,12 @@ public class BuffManager : IDisposable // _forceRebuffCastFamilies (not timers), so the family MUST be // marked cast here or the batch respins this buff forever. if (_isForceRebuffing) _forceRebuffCastFamilies.Add(pendingSpell.Family); + _cast.Confirmed(_pendingSpellId, "confirmed in the enchantment registry"); _pendingSpellId = 0; // landed — registry confirms it; advance NoteCastAccepted(); // it went through — end any too-busy backoff _onCastResolved?.Invoke("self-buff confirmed (registry)"); } - else if (sinceCastMs > SelfBuffGiveUpMs) + else if (pastGiveUp) { // Not in the registry after settling → this tier didn't take. // A WARM snapshot already excludes unknown tiers, so a no-show @@ -815,14 +1048,15 @@ public class BuffManager : IDisposable // Yield while the self-buff cast is in flight. PendingSpellId keeps // the arbiter on Buffing, so CombatManager can't sneak a peace-mode // switch in mid-cast. - if (_pendingSpellId != 0) { TryEmergencyHealWhilePending(); return; } + if (_pendingSpellId != 0) { TryEmergencyHealWhilePending(); Hold("buff cast in flight", pendingSpell.Name); return; } } else if (pendingIsArmor) { // ARMOR/ITEM: chat is authoritative. No-chat valve abandons a cast // AC never answers so the cycle can't wedge; the chat handlers do // the cooldown. Blacklist (unless snapshot confirms known) drops tier. - if ((DateTime.Now - _lastCastAttempt).TotalMilliseconds > NoChatResolveTimeoutMs) + // From the send, or later when the incantation came late (never earlier than before). + if (PendingGiveUpReached(NoChatResolveTimeoutMs)) { int stuckId = _pendingSpellId; var stuck = SpellTableStub.GetById(stuckId); @@ -873,12 +1107,15 @@ public class BuffManager : IDisposable _onCastResolved?.Invoke("no-chat timeout (armor)"); } // Hold the cycle until chat resolves the item cast. - if (_pendingSpellId != 0) { TryEmergencyHealWhilePending(); return; } + if (_pendingSpellId != 0) { TryEmergencyHealWhilePending(); Hold("item spell in flight", pendingSpell?.Name ?? ""); return; } } } if ((DateTime.Now - _lastCastAttempt).TotalMilliseconds < _settings.SpellCastIntervalMs) + { + Hold("cast interval"); return; + } // Don't issue a cast while the previous cast GESTURE is still animating. // CanCastNow is the engine's CMotionInterp gesture gate (the REAL cast @@ -894,14 +1131,31 @@ public class BuffManager : IDisposable // CombatManager can't sneak in a peace-mode switch mid-cast") is the // arbiter's call now — it reads PendingSpellId / WantsVitalRecharge / // NeedsAnyBuff and is the sole writer of the "Buffing" string. - if (!CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s)) || BusyCount > 0) + // A heal goes ahead of a busy count the server has already finished (BusyHoldsHeal); + // everything else still waits for the count to drop. + bool gateOpen = CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s)); + bool busyHolds = BusyCount > 0 + && (ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out _, out _).Length == 0 || BusyHoldsHeal()); + if (!gateOpen || busyHolds) { - LastBuffSkipReason = BusyCount > 0 ? "busy (BusyCount>0)" : "cast gate closed (CanCastNow=false / gesture animating)"; + LastBuffSkipReason = busyHolds ? "busy (BusyCount>0)" : "cast gate closed (CanCastNow=false / gesture animating)"; + if (!gateOpen) Hold("cast gate (a gesture is animating)"); + else Hold("busy count", $"busy {BusyCount}"); return; } if (CheckVitals()) + { + if (_healHold.Length == 0) Hold(_healWaitKind.Length > 0 ? _healWaitKind : "vitals step busy", _vitalWhy); return; + } + + // The login refresh above held buffs only: the heal had its turn, the buffs wait. + if (buffsHeldForRefresh) + { + Hold("login buff refresh"); + return; + } // Mana floor: no buff while mana is under Get Mana At. CheckVitals above already tried // Stamina to Mana and a mana potion; when neither could run (stamina too low, none @@ -1021,7 +1275,10 @@ public class BuffManager : IDisposable /// DateTime.MinValue when the family has no timer at all. private DateTime CurrentExpiryFor(int family) { - if (_ramBuffTimers.TryGetValue(family, out RamTimerInfo? t)) return t.Expiration; + // An item-granted permanent isn't ours when CastBuffsOverItemBuffs is on (only possible + // between the setting being switched on and the next live read). + if (_ramBuffTimers.TryGetValue(family, out RamTimerInfo? t) && !(t.IsPermanent && _settings.CastBuffsOverItemBuffs)) + return t.Expiration; if (_itemSpellTimers.TryGetValue(family, out ItemSpellRecord? i)) return i.ExpiresAt; return DateTime.MinValue; } @@ -1102,6 +1359,7 @@ public class BuffManager : IDisposable if (KitPending()) { _isHealingSelf = true; + Hold(_kitIsStamina ? "stamina kit in flight" : "healing kit in flight"); return true; } @@ -1157,6 +1415,7 @@ public class BuffManager : IDisposable return true; } _healUnavailableUntil = DateTime.Now.AddMilliseconds(HealUnavailableMs); + Hold("nothing could heal", $"kit: {Why(kitWhy)}; Heal Self: {Why(spellWhy)}; potion: {Why(_vitalWhy)}"); LogNoHeal($"health {curHealthPct}% < {(inCombat ? "Heal At" : "Top Off HP")} {hpThreshold}% but nothing healed: " + $"kit: {Why(kitWhy)}; Heal Self: {Why(spellWhy)}; potion: {Why(_vitalWhy)}"); } @@ -1224,7 +1483,7 @@ public class BuffManager : IDisposable int emergencyAt = _settings.EmergencyHealAt; if (emergencyAt <= 0 || _vitals.HealthPct > emergencyAt) return; if ((DateTime.Now - _lastPendingEmergencyHealAt).TotalMilliseconds < 2500) return; - if (IsAwaitingCastResolution() || BusyCount > 0 || KitPending()) return; + if (IsAwaitingCastResolution() || BusyHoldsHeal() || KitPending()) return; if (!CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s))) return; if (AttemptHealthKitUse() || AttemptPotion("HealthPotion")) { @@ -1259,6 +1518,28 @@ public class BuffManager : IDisposable private bool AttemptVitalCast(string baseName) { if (!IsSkillUsable(AcSkillType.LifeMagic)) return VitalNo("Life Magic not usable"); + // AC just said "You're too busy!": a cast now draws another refusal and can keep the + // gesture from finishing (Drakkon, 2026-10-05: Stamina to Mana every 0.4 s until he was + // moved). Mana and stamina wait out the backoff; a heal still retries, but no faster + // than BusyHealRetryMs. Waiting counts as handled, so no potion is drunk meanwhile. + if (DateTime.Now < _busyBackoffUntil) + { + bool healthSpell = baseName is "Heal Self" or "Stamina to Health Self"; + if (!healthSpell || (DateTime.Now - _lastCastAttempt).TotalMilliseconds < BusyHealRetryMs) + { + _vitalWhy = $"AC too busy, waiting {(_busyBackoffUntil - DateTime.Now).TotalMilliseconds:0} ms"; + _healWaitKind = "too-busy backoff"; + return true; + } + } + // Mana and stamina also wait until the server has finished the last cast (its result, or + // its UseDone after the incantation; bounded by its give-up time). A heal never waits. + if (baseName is not ("Heal Self" or "Stamina to Health Self") && IsAwaitingCastResolution()) + { + _vitalWhy = "the server hasn't finished the last cast"; + _healWaitKind = "server finishing the last cast"; + return true; + } int spellId = FindBestSpellId(baseName, AcSkillType.LifeMagic); if (spellId == 0) return VitalNo($"no known '{baseName}' spell at the allowed tiers"); // Parked after a hard server refusal (see OnChatWindowText) — the same @@ -1270,9 +1551,10 @@ public class BuffManager : IDisposable return VitalNo($"parked for {(coolUntil - DateTime.Now).TotalSeconds:0} s more after a refusal or no-show"); if (CurrentCombatMode != CombatMode.Magic && DateTime.Now < _vitalSwapBlockedUntil) return VitalNo("wand swap blocked, retrying shortly"); - if (!EnsureMagicMode()) + bool urgentHeal = baseName is "Heal Self" or "Stamina to Health Self" && HealIsUrgent(_vitals.HealthPct, _vitals.StaminaPct); + if (!EnsureMagicMode(urgentHeal: urgentHeal)) { - if (!_magicModeBlocked) return true; // a swap step is in flight: yield the tick + if (!_magicModeBlocked) { _healWaitKind = "wand swap / Magic stance"; return true; } // a swap step is in flight: yield the tick // The switch can't complete now (no room to put the bow away, the wand won't // wield): not handled, so the kit/potion after this gets its turn. _vitalSwapBlockedUntil = DateTime.Now.AddSeconds(VitalSwapBlockedRetrySec); @@ -1283,6 +1565,7 @@ public class BuffManager : IDisposable // strike. Mirror the buff path: not handled, so the potion gets its turn. _pendingSpellId = spellId; _pendingVitalSpellId = spellId; // instant: confirmed by chat, never by the registry + _pendingVitalLabel = VitalLabel(baseName); bool castOk = _host.CastSpell((uint)_host.GetPlayerId(), spellId); _lastCastAttempt = DateTime.Now; if (!castOk) @@ -1290,10 +1573,18 @@ public class BuffManager : IDisposable _pendingSpellId = 0; return VitalNo($"the client refused the cast (spell {spellId})"); } - NoteCastIssued(); + NoteCastIssued(spellId); + if (_pendingVitalLabel == LabelHealing) + { + _healSpellIds.Add(spellId); + _healLatency.HealSent(Now, baseName); + } return true; } + private static bool IsHealthPotionType(string[] types) => + Array.FindIndex(types, t => t.Equals("HealthPotion", StringComparison.OrdinalIgnoreCase)) >= 0; + /// /// Drinks the first potion of from the Items panel. /// "Stamina" is the older name for stamina potions. Off with UsePotions. @@ -1306,10 +1597,12 @@ public class BuffManager : IDisposable { if (Array.FindIndex(types, t => t.Equals(rule.Type, StringComparison.OrdinalIgnoreCase)) < 0) continue; if (_worldObjectCache[rule.Id] == null) continue; + if (HeldCastBlocksItemUse(out string heldWhy)) return VitalNo(heldWhy); _host.Log($"[RynthAi] Vitals: drinking {rule.Name} ({rule.Type})."); _host.UseFor(unchecked((uint)rule.Id), "Buff", $"vitals: drink {rule.Name} ({rule.Type}) from the Items list"); _lastPotionAt = DateTime.Now; _lastCastAttempt = DateTime.Now; + if (IsHealthPotionType(types)) _healLatency.HealSent(Now, rule.Name); return true; } // Nothing on the Items panel: anything in the pack of that kind (Field Rations @@ -1318,10 +1611,12 @@ public class BuffManager : IDisposable { string? kind = RynthCore.Plugin.RynthAi.LegacyUi.LegacyWeaponsUi.PotionType(wo); if (kind == null || Array.FindIndex(types, t => t.Equals(kind, StringComparison.OrdinalIgnoreCase)) < 0) continue; + if (HeldCastBlocksItemUse(out string heldWhy)) return VitalNo(heldWhy); _host.Log($"[RynthAi] Vitals: using {wo.Name} from the pack ({kind})."); _host.UseFor(unchecked((uint)wo.Id), "Buff", $"vitals: {kind} potion from the pack"); _lastPotionAt = DateTime.Now; _lastCastAttempt = DateTime.Now; + if (IsHealthPotionType(types)) _healLatency.HealSent(Now, wo.Name ?? "health potion"); return true; } return VitalNo("none in the Items list or the pack"); @@ -1447,6 +1742,7 @@ public class BuffManager : IDisposable if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase) && _worldObjectCache[r.Id] is WorldObject wo) { kit = wo; break; } if (kit == null) { kit = BestPackHealingKit(); fromPack = true; } if (kit == null) return VitalNo("no healing kit"); + if (KitRetryWait(out string kitWait)) return VitalNo(kitWait); // Too likely to fail on what's missing (KitMinSuccessPct): let the spell have it. uint missing = _vitals.MaxHealth > _vitals.CurrentHealth ? _vitals.MaxHealth - _vitals.CurrentHealth : 0; if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return VitalNo($"{kit.Name} under Kit Min Success %"); @@ -1454,15 +1750,18 @@ public class BuffManager : IDisposable { _host.ChangeCombatMode(CombatMode.NonCombat); _lastCastAttempt = DateTime.Now; + _healWaitKind = "peace mode for the kit"; return true; // use the kit next tick, once in peace mode } uint playerId = _host.GetPlayerId(); if (playerId == 0) return false; + if (HeldCastBlocksItemUse(out string heldWhy)) return VitalNo(heldWhy); if (fromPack) _host.Log($"[RynthAi] Vitals: using {kit.Name} from the pack."); _host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: healing kit on yourself"); _lastCastAttempt = DateTime.Now; MarkKitUsed(); + _healLatency.HealSent(Now, kit.Name ?? "healing kit"); return true; } @@ -1477,6 +1776,7 @@ public class BuffManager : IDisposable if (mode == CombatMode.Magic && !_settings.UseKitsInMagicMode) return false; WorldObject? kit = BestPackStaminaKit(); if (kit == null) return false; + if (KitRetryWait(out _)) return false; uint missing = _vitals.MaxStamina > _vitals.CurrentStamina ? _vitals.MaxStamina - _vitals.CurrentStamina : 0; if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return false; if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode) @@ -1487,10 +1787,11 @@ public class BuffManager : IDisposable } uint playerId = _host.GetPlayerId(); if (playerId == 0) return false; + if (HeldCastBlocksItemUse(out _)) return false; _host.Log($"[RynthAi] Vitals: using {kit.Name} from the pack."); - _host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: healing kit on yourself"); + _host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: stamina kit on yourself"); _lastCastAttempt = DateTime.Now; - MarkKitUsed(); + MarkKitUsed(stamina: true); return true; } @@ -1505,15 +1806,39 @@ public class BuffManager : IDisposable private const double KitResultTimeoutMs = 8000; private const double KitLandGraceMs = 700; - internal void MarkKitUsed() // internal for the host tests (VitalsTests) + // A refused kit (2026-10-05): ACE answers a kit used while the character is busy (a swing, a + // cast still resolving), in the air, or on something it can't heal with a UseDone error and + // no chat result (Healer.cs: YoureTooBusy, YouCantDoThatWhileInTheAir, YouCantHealThat). No + // result line ever came, so every vital waited the full KitResultTimeoutMs, 8 s with no heal + // at all (CheckVitals returns at KitPending, Heal Self included). Now the kit's refusal ends + // the wait: a UseDone with an error after the kit went out, or "You're too busy!" within + // KitRefusalWindowMs of it. The next kit waits KitRetryAfterRefusalMs, so Heal Self or a + // potion gets the turn first and a refusal can't become a kit every tick. + private int _kitSeqAtUse; + private DateTime _kitRefusedAt = DateTime.MinValue; + private const double KitRefusalWindowMs = 3000; + private const double KitRetryAfterRefusalMs = 1000; + /// Kit uses the server refused (tests, status). + internal int KitRefusals { get; private set; } + + internal void MarkKitUsed(bool stamina = false) // internal for the host tests (VitalsTests) { _kitUsedAt = DateTime.Now; _kitLandedAt = DateTime.MinValue; + _kitIsStamina = stamina; + _kitSeqAtUse = UseDoneSeqNow(); } internal bool KitPending() { if (_kitUsedAt == DateTime.MinValue) return false; + // Refused by the server: a UseDone carrying an error since the kit went out. + if (_kitLandedAt == DateTime.MinValue && _host.TryGetLastUseDone(out int seq, out uint err) + && seq != _kitSeqAtUse && err != 0) + { + KitRefused($"UseDone error 0x{err:X}"); + return false; + } DateTime now = DateTime.Now; bool done = _kitLandedAt != DateTime.MinValue ? (now - _kitLandedAt).TotalMilliseconds >= KitLandGraceMs @@ -1522,6 +1847,31 @@ public class BuffManager : IDisposable return !done; } + /// The kit in flight was refused: no result line will come, so stop waiting for one. + private void KitRefused(string why) + { + if (_kitUsedAt == DateTime.MinValue || _kitLandedAt != DateTime.MinValue) return; + double ms = (DateTime.Now - _kitUsedAt).TotalMilliseconds; + _kitUsedAt = DateTime.MinValue; + _kitRefusedAt = DateTime.Now; + KitRefusals++; + _host.Log($"[RynthAi] Vitals: the {(_kitIsStamina ? "stamina" : "healing")} kit was refused {ms:0} ms after use ({why}): " + + $"no result will come, vitals carry on (next kit in {KitRetryAfterRefusalMs:0} ms)."); + } + + /// True (with why) while a kit must wait after its last refusal. + private bool KitRetryWait(out string why) + { + double since = (DateTime.Now - _kitRefusedAt).TotalMilliseconds; + if (since < KitRetryAfterRefusalMs) + { + why = $"kit refused {since:0} ms ago, retrying shortly"; + return true; + } + why = ""; + return false; + } + /// True for the chat lines that end a kit use on yourself (ACE Healer.cs). internal static bool IsKitResultLine(string lower) => lower.Contains("heal yourself") // "You heal yourself for ...", "You critically heal ...", "You fail to heal yourself." @@ -1754,7 +2104,7 @@ public class BuffManager : IDisposable if (diagnose) _host.Log($"[FR] CAST '{buffBaseName}' resolvedSpellId={spellId} (pending now set)"); bool castOk = _host.CastSpell((uint)_host.GetPlayerId(), spellId); _lastCastAttempt = DateTime.Now; - if (castOk) NoteCastIssued(); + if (castOk) NoteCastIssued(spellId); if (castOk && buffFamily != 0 && spellInfo != null) { // Highest tier cast per family this session: IsBuffActive's landed-tier cap only @@ -2040,8 +2390,12 @@ public class BuffManager : IDisposable return false; } - // Player buffs — use RAM timers - if (_ramBuffTimers.TryGetValue(targetSpell.Family, out RamTimerInfo? timer)) + // Player buffs — use RAM timers. With CastBuffsOverItemBuffs on, a permanent + // (item-granted) entry is not ours and never satisfies the family. The live refresh + // already keeps permanents out of the timers then; this covers the setting being + // switched on between refreshes. + if (_ramBuffTimers.TryGetValue(targetSpell.Family, out RamTimerInfo? timer) + && !(timer.IsPermanent && _settings.CastBuffsOverItemBuffs)) { // Tier-upgrade flap guard: many high-tier buffs are Incantations // (nominal tier 8) that LAND at a lower, skill-capped tier — e.g. @@ -2072,9 +2426,22 @@ public class BuffManager : IDisposable _lastArmorRecastReason.Remove(targetSpell.Family); return true; } + // The strongest entry is running out, but another one in the family at the + // tier we'd cast (or better) still has time: AC moves to it when the strong one + // ends, so casting again changes nothing. Without this a buff bot's expiring 8 + // made our own fresh VI under it recast every pass until the audit parked it. + if (CoveredByAnotherEntry(targetSpell.Family, effectiveTarget, rebufferSec)) + { + _lastArmorRecastReason.Remove(targetSpell.Family); + return true; + } double remainSec = (timer.Expiration - DateTime.Now).TotalSeconds; LogPlayerRecast(targetSpell, $"expiry-window remainSec={remainSec:F0} threshold={rebufferSec} storedLvl={timer.SpellLevel} exp={timer.Expiration:HH:mm:ss} (stored='{timer.SpellName}')"); } + else if (timer != null) + { + LogPlayerRecast(targetSpell, $"only an item-granted '{timer.SpellName}' (permanent, lvl={timer.SpellLevel}) and CastBuffsOverItemBuffs is on: cast our own"); + } else { LogPlayerRecast(targetSpell, $"NO ram-timer entry for family={targetSpell.Family} (targetLvl={targetLevel}, _ramBuffTimers.Count={_ramBuffTimers.Count})"); @@ -2085,6 +2452,21 @@ public class BuffManager : IDisposable return false; } + /// True when the last live read holds an entry in at + /// or above with more than left + /// (a permanent one counts unless CastBuffsOverItemBuffs is on: then only our timed + /// entries do). + private bool CoveredByAnotherEntry(int family, int minLevel, int rebufferSec) + { + if (!_familyLiveEntries.TryGetValue(family, out var entries)) return false; + bool ignorePermanent = _settings.CastBuffsOverItemBuffs; + DateTime due = DateTime.Now.AddSeconds(rebufferSec); + foreach (var (level, expiration, permanent) in entries) + if (level >= minLevel && expiration > due && !(permanent && ignorePermanent)) + return true; + return false; + } + // Player-buff counterpart to LogArmorRecast — explains why a character // self-buff (Impregnability/Aura of Deflection, masteries, etc.) is judged // inactive. Throttled per-family (IsBuffActive is polled every tick). @@ -2243,6 +2625,7 @@ public class BuffManager : IDisposable } _ramBuffTimers.Clear(); + _familyLiveEntries.Clear(); for (int i = 0; i < count; i++) { var spellInfo = SpellTableStub.GetById((int)spellIds[i]); @@ -2298,14 +2681,28 @@ public class BuffManager : IDisposable // Keep the higher tier; on a tie keep whichever lasts longer // (PermanentSentinel naturally sorts last, so a permanent entry wins // a tie against a timed one of the same tier). + // + // CastBuffsOverItemBuffs (default on, 2026-10-05): a permanent entry is item-granted, + // not ours, and on a server with buff augments our own cast is stronger or longer. + // It never takes the family timer then, so the timer tracks the highest TIMED entry + // (ours) and the buff is cast, then recast when it runs low. Once our cast lands + // the family reads on until it runs low, so no recast loop: the 09-27 loop came + // from a permanent entry OWNING the timer at a tier below the target, which can't + // happen when permanents are left out. + bool ignoredAsItemBuff = isPermanent && _settings.CastBuffsOverItemBuffs; bool keepExisting = - _ramBuffTimers.TryGetValue(spellInfo.Family, out RamTimerInfo? seen) - && (seen.SpellLevel > level - || (seen.SpellLevel == level && seen.Expiration >= candidate.Expiration)); + ignoredAsItemBuff + || (_ramBuffTimers.TryGetValue(spellInfo.Family, out RamTimerInfo? seen) + && (seen.SpellLevel > level + || (seen.SpellLevel == level && seen.Expiration >= candidate.Expiration))); if (!keepExisting) _ramBuffTimers[spellInfo.Family] = candidate; + if (!_familyLiveEntries.TryGetValue(spellInfo.Family, out var familyEntries)) + _familyLiveEntries[spellInfo.Family] = familyEntries = new List<(int, DateTime, bool)>(); + familyEntries.Add((level, candidate.Expiration, isPermanent)); + // Learn the real ceiling this family lands at (Incantations cap below // their nominal tier) so IsBuffActive stops chasing an unreachable tier. // Recorded for every timed entry read, including one the merge above @@ -2321,9 +2718,11 @@ public class BuffManager : IDisposable if (isPermanent && _loggedPermanentFamilies.Add(spellInfo.Family)) _host.Log($"[BuffDiag] permanent player enchant tracked: id={spellInfo.Id} '{spellInfo.Name}' (fam={spellInfo.Family}, lvl={level}) — presence-only, not persisted" + - (keepExisting - ? $" — outranked in this family by '{seen!.SpellName}' (lvl={seen.SpellLevel}), which owns the timer" - : "")); + (ignoredAsItemBuff + ? " — item-granted, CastBuffsOverItemBuffs is on: our own cast owns the timer" + : keepExisting && _ramBuffTimers.TryGetValue(spellInfo.Family, out RamTimerInfo? owner) + ? $" — outranked in this family by '{owner.SpellName}' (lvl={owner.SpellLevel}), which owns the timer" + : "")); } // Restore item enchantment timers that weren't covered by player enchantments @@ -2628,6 +3027,7 @@ public class BuffManager : IDisposable // while _pendingSpellId is still set. Clearing pending here without marking // it would make an auto-batch respin this buff forever. if (_isForceRebuffing) _forceRebuffCastFamilies.Add(pendingSpell.Family); + _cast.Confirmed(_pendingSpellId, "enchantment landed"); _pendingSpellId = 0; NoteCastAccepted(); _onCastResolved?.Invoke("self-buff confirmed (enchantment event)"); @@ -2690,6 +3090,15 @@ public class BuffManager : IDisposable if (_pendingSpellId != 0) _host.Log($"[BuffChat] pending={_pendingSpellId} type={chatType} text='{text}'"); + // Our own incantation ('You say, "Puish Zharil"') is the server STARTING the last cast we + // sent: its give-up and the server wait are timed from here (CastTracker). It is speech, + // so it never reaches the result matchers below. + if (IsOwnIncantation(text)) + { + _cast.Incantation(UseDoneSeqNow()); + return; + } + // Speech and our own lines are never cast results. Every chat line reaches // this handler, so "Bob tells you, "did you cast banes?"" matched "ou cast ", // fell back to the pending spell and wrote a phantom 1-hour armor timer; a @@ -2722,7 +3131,25 @@ public class BuffManager : IDisposable // construction → 0x00460D1D killed regardless of gate precision. if (lower.Contains("you're too busy") || lower.Contains("you are too busy")) { - if (_pendingSpellId != 0) + // A kit in flight with no result yet: this is its refusal (see KitRefused). Our bot + // sends nothing else while a kit is pending (CheckVitals returns at KitPending). + if (_kitUsedAt != DateTime.MinValue && _kitLandedAt == DateTime.MinValue + && (DateTime.Now - _kitUsedAt).TotalMilliseconds <= KitRefusalWindowMs) + KitRefused("You're too busy!"); + // A refusal, never "done" (2026-10-05). When the pending cast's incantation has come, + // the server is running it and this refused something else (a loot use, a kit): the + // pending cast is kept and still resolves on its own result or give-up time. + ObserveLastUseDone(); + var cur = _cast.Current; + bool pendingRunning = _pendingSpellId != 0 && cur != null && cur.SpellId == _pendingSpellId + && cur.HasIncantation && !cur.Done; + bool urgentNudge = HeldNudgeUrgent(); + bool nudge = _cast.Refusal(UseDoneSeqNow(), urgentNudge ? CastTracker.UrgentHeldAfterIncantMs : CastTracker.HeldAfterIncantMs); + if (pendingRunning) + { + _host.Log($"[BuffChat] too busy while pending={_pendingSpellId} is running on the server (incantation seen) — something else was refused; pending kept."); + } + else if (_pendingSpellId != 0) { var pendingSpell = SpellTableStub.GetById(_pendingSpellId); if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name)) @@ -2732,7 +3159,7 @@ public class BuffManager : IDisposable } _host.Log($"[BuffChat] PARKED pending={_pendingSpellId} — AC too busy (cast gesture in progress); throttle kept, backing off before re-issue."); } - _pendingSpellId = 0; + if (!pendingRunning) _pendingSpellId = 0; // AC is authoritatively busy — wait, escalating, rather than retrying // on the 400ms tick. Cleared by NoteCastAccepted on the next success. @@ -2742,7 +3169,22 @@ public class BuffManager : IDisposable if (_busyRefusalStreak == 1 || _busyRefusalStreak % 5 == 0) _host.Log($"[BuffChat] too-busy streak={_busyRefusalStreak} — backing off {backoffMs:0}ms before the next cast attempt."); - _onCastResolved?.Invoke("too busy"); + // A run of refusals with nothing landing is a gesture that won't finish on its own; + // moving the character cleared it (Drakkon, 2026-10-05). Do that once per streak. + // Not while one of our casts is open on the server (incantation, no result): a stop + // mid-windup can cancel a healthy cast, and a held one gets the nudge below instead. + if (_busyRefusalStreak == BusyStopAtStreak && _host.HasStopCompletely && _cast.HeldSeconds == 0) + { + _host.StopCompletelyBy("Buff/TooBusy"); + _host.Log($"[BuffChat] too-busy streak={_busyRefusalStreak} — the cast gesture looks stuck: StopCompletely to clear it."); + } + + // A cast the server has held open past CastTracker.HeldAfterIncantMs while it refuses + // the next ones: one movement nudge, once per held cast (what moving him by hand did). + if (nudge && _settings.IsMacroRunning) + SendCastNudge(urgentNudge); + + if (!pendingRunning) _onCastResolved?.Invoke("too busy"); return; } @@ -2760,6 +3202,7 @@ public class BuffManager : IDisposable lower.Contains("you must specify") || lower.Contains("have all the components for this spell")) { + _cast.Result(null, "refused by the server", atStart: true); if (_pendingSpellId != 0) { var pendingSpell = SpellTableStub.GetById(_pendingSpellId); @@ -2797,8 +3240,10 @@ public class BuffManager : IDisposable // A zeroed _lastCastAttempt (the soft-fail path) would re-cast at tick rate. if (lower.Contains("enough mana")) { + _cast.Result(null, "not enough mana", atStart: true); if (_pendingSpellId == 0) return; var pendingSpell = SpellTableStub.GetById(_pendingSpellId); + double restSec = LowManaFamilyRestSec; if (pendingSpell != null) { if (IsItemEnchantment(pendingSpell.Name)) @@ -2806,9 +3251,14 @@ public class BuffManager : IDisposable _itemSpellTimers.Remove(pendingSpell.Family); SaveBuffTimers(); } - _buffFailCooldownUntil[pendingSpell.Family] = DateTime.Now.AddSeconds(LowManaFamilyRestSec); + // A heal rests only LowManaHealRestSec (2026-10-05): long enough for the mana step + // after it to cast Stamina to Mana or drink, not 15 s with no Heal Self after the + // mana was back (a mage low on mana mid-fight). + bool healSpell = _pendingSpellId == _pendingVitalSpellId && _pendingVitalLabel == LabelHealing; + restSec = healSpell ? LowManaHealRestSec : LowManaFamilyRestSec; + _buffFailCooldownUntil[pendingSpell.Family] = DateTime.Now.AddSeconds(restSec); } - _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} - not enough mana; resting the family {LowManaFamilyRestSec:0}s, buffs {LowManaBuffPauseMs / 1000:0}s."); + _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} - not enough mana; resting the family {restSec:0}s, buffs {LowManaBuffPauseMs / 1000:0}s."); _pendingSpellId = 0; _lowManaPauseUntil = DateTime.Now.AddMilliseconds(LowManaBuffPauseMs); _onCastResolved?.Invoke("not enough mana"); @@ -2821,6 +3271,7 @@ public class BuffManager : IDisposable lower.Contains("your spell failed") || lower.Contains("lack the mana")) { + _cast.Result(null, "fizzled"); if (_pendingSpellId != 0) { var pendingSpell = SpellTableStub.GetById(_pendingSpellId); @@ -2853,14 +3304,36 @@ public class BuffManager : IDisposable if (commaIdx > 0 && commaIdx < endIdx) endIdx = commaIdx; string spellName = afterCast.Substring(0, endIdx).Trim(); + // Which of our casts this result belongs to, by the spell name it starts with (a vital's + // line, "You cast Revitalize Self V and restore 70 points...", has no " on " or comma). + var tracked = _cast.Result(afterCast, "result"); + // Try to find the spell by name first (authoritative — this is what was actually cast) int spellId = SpellDatabase.GetIdByName(spellName); SpellInfo? spellInfo = spellId > 0 ? SpellTableStub.GetById(spellId) : null; - // Fall back to pending spell if name lookup fails + // Then the cast the line names (a late result of an earlier cast is credited to that cast, + // not to whatever is pending now: Stamina to Mana was credited to Creature Enchantment + // Mastery, 2026-10-05), then the pending spell. + if (spellInfo == null && tracked != null) + spellInfo = SpellTableStub.GetById(tracked.SpellId); if (spellInfo == null && _pendingSpellId != 0) spellInfo = SpellTableStub.GetById(_pendingSpellId); + // A result that names another spell than the pending one is not the pending cast's + // result: the pending cast keeps waiting for its own (or its give-up time). + var pendingInfo = _pendingSpellId != 0 ? SpellTableStub.GetById(_pendingSpellId) : null; + if (pendingInfo != null && spellInfo != null && spellInfo.Family != pendingInfo.Family) + { + _buffFailCooldownUntil.Remove(spellInfo.Family); + _silentNoShowCounts.Remove(spellInfo.Family); + NoteCastAccepted(); + if (IsItemEnchantment(spellInfo.Name)) RecordItemSpellCast(spellInfo); + else RecordSpellTimer(spellInfo); + _host.Log($"[BuffChat] result for '{spellInfo.Name}' is not pending={_pendingSpellId} ('{pendingInfo.Name}') — recorded, pending kept."); + return; + } + if (spellInfo != null) { _buffFailCooldownUntil.Remove(spellInfo.Family); // it cast — clear any stale hard-fail cooldown @@ -2893,33 +3366,152 @@ public class BuffManager : IDisposable /// Record that a cast just went out, so the next one waits for the /// server to report the action finished rather than a blind interval. - private void NoteCastIssued() + private void NoteCastIssued(int spellId) { - if (!_host.HasUseDoneSeq) { _awaitingCastResolution = false; return; } - _useDoneSeqAtCast = _host.GetUseDoneSeq(); - _awaitingCastResolution = true; - _castResolutionDeadline = DateTime.Now.AddMilliseconds(CastResolutionTimeoutMs); + string name = SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}"; + _cast.Sent(spellId, name, UseDoneSeqNow()); } - /// True while the server has not yet reported finishing the last - /// cast. Self-clears on the UseDone-seq advance (completed OR refused) or on - /// the timeout, so this can never wedge the buff loop. - private bool IsAwaitingCastResolution() + /// + /// True while the server has not finished the last cast sent: until its own result line, a + /// UseDone with no error after its incantation, or (after a refusal) a UseDone(0) showing + /// the server free, bounded by its give-up time (CastResolutionTimeoutMs from the send, + /// later with a late incantation). A refusal (0x1D) is never "finished" (2026-10-05). + /// Inert on an engine without UseDone observation, as before. Internal for the host tests. + /// + internal bool IsAwaitingCastResolution() { - if (!_awaitingCastResolution) return false; - if (_host.HasUseDoneSeq && _host.GetUseDoneSeq() != _useDoneSeqAtCast) - { - _awaitingCastResolution = false; - return false; - } - if (DateTime.Now >= _castResolutionDeadline) - { - _awaitingCastResolution = false; - return false; - } - return true; + if (!_host.HasUseDoneSeq) return false; + bool hasLast = _host.TryGetLastUseDone(out int lastSeq, out uint lastErr); + return _cast.AwaitingServer(CastResolutionTimeoutMs, _host.GetUseDoneSeq(), hasLast, lastSeq, lastErr); } + private int UseDoneSeqNow() => _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0; + + private void ObserveLastUseDone() + { + if (_host.TryGetLastUseDone(out int seq, out uint err)) + _cast.ObserveUseDone(seq, err); + } + + /// Each tick: casts the server finished (UseDone(0) after the incantation) close, + /// and a cast held open past CastTracker.HeldAfterIncantMs is logged once. + private void PollCastTracker() + { + if ((_cast.Current == null || _cast.Current.Done) && (_cast.Open == null || _cast.Open.Done)) return; + ObserveLastUseDone(); + _cast.Poll(); + // A held heal, or any held cast while health is under a heal line: nudge at + // UrgentHeldAfterIncantMs on its own, without waiting for AC to refuse something + // (2026-10-05: the held Heal Self was nudged 11.2 s after its incantation). + if (_settings.IsMacroRunning && HeldNudgeUrgent() && _cast.TakeNudge(CastTracker.UrgentHeldAfterIncantMs)) + SendCastNudge(urgent: true); + } + + /// The held cast is a heal, or health is under a heal line: nudge it early. + private bool HeldNudgeUrgent() + { + var held = _cast.Held; + if (held == null) return false; + return IsHealCast(held.SpellId) + || (_vitals.MaxHealth > 0 && HealthUnderAnyLine(_vitals.HealthPct, _vitals.StaminaPct)); + } + + // Spell ids this session sent as health spells (Heal Self, Stamina to Health Self at any tier: + // the high tiers have their own names, e.g. Adja's Intervention). Set by AttemptVitalCast. + private readonly HashSet _healSpellIds = new(); + private bool IsHealCast(int spellId) => _healSpellIds.Contains(spellId); + + // Kits and potions while a cast is held open (2026-10-05): ACE (Healer.cs, Food.cs) answers a + // use while the player is busy with "You're too busy!", and every kit Drakkon used while a Heal + // Self was held open came back 0x1D (13:42:26, 13:42:34, 13:42:47). So while a cast is held: + // none before its nudge has gone out (the nudge is what may free it), then one try every + // HeldItemRetryMs (the nudge does not always free it at once: 9 s at 13:42:34). + private const double HeldItemRetryMs = 3000; + private DateTime _lastHeldItemTryAt = DateTime.MinValue; + /// Kit / potion attempts skipped because a cast was held open (tests, status). + internal int HeldItemSkips { get; private set; } + + /// True (with why) when a kit or potion would only be refused: a cast is held open. + /// Otherwise false, and an attempt now is counted against HeldItemRetryMs. + internal bool HeldCastBlocksItemUse(out string why) // internal for the host tests (CastSafetyTests) + { + why = ""; + var held = _cast.Held; + // Only a cast past its normal result window: before that the vital is still pending + // and the server is simply finishing it. + if (held == null || (Now - held.IncantAt).TotalMilliseconds <= CastTracker.IncantToResultMs) return false; + if (!held.Nudged) + { + HeldItemSkips++; + why = $"'{held.Name}' is held open by the server: ACE refuses kits and potions until it ends (nudge first)"; + return true; + } + double since = (Now - _lastHeldItemTryAt).TotalMilliseconds; + if (since < HeldItemRetryMs) + { + HeldItemSkips++; + why = $"'{held.Name}' still held open after the nudge: next kit/potion try in {HeldItemRetryMs - since:0} ms"; + return true; + } + _lastHeldItemTryAt = Now; + return false; + } + + /// The pending cast is past its give-up time: from its incantation when one came + /// (CastTracker.GiveUpAt), else from the send. + private bool PendingGiveUpReached(double fallbackMs) => + _cast.GiveUpReached(_pendingSpellId, fallbackMs) + ?? (DateTime.Now - _lastCastAttempt).TotalMilliseconds > fallbackMs; + + private string GiveUpWhy(double fallbackMs) + { + var c = _cast.Current; + if (c == null || c.SpellId != _pendingSpellId) return $"in {fallbackMs:0} ms"; + return c.HasIncantation + ? $"{(Now - c.IncantAt).TotalMilliseconds:0} ms after its incantation, {(Now - c.SentAt).TotalMilliseconds:0} ms after the send" + : $"no incantation in {(Now - c.SentAt).TotalMilliseconds:0} ms"; + } + + /// Our own speech line: 'You say, "..."' (the leading Y may be stripped). + internal static bool IsOwnIncantation(string text) => + text.StartsWith("You say, \"", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("ou say, \"", StringComparison.OrdinalIgnoreCase); + + /// + /// One movement nudge for a cast the server holds open (CastTracker.Refusal said so, once per + /// held cast). ACE ends a cast when the cast gesture's motion completes on the server, and a + /// movement packet from the client is what let Drakkon's held casts finish (2026-10-05). + /// StopCompletely from a standing character may send no movement at all, so this sends + /// autorun on and straight off: two movement-state changes, no real step. Then casts wait + /// NudgeHoldMs for the held cast's result. + /// + private void SendCastNudge(bool urgent = false) + { + var held = _cast.Open; + string name = held?.Name ?? "?"; + double secs = _cast.HeldSeconds; + if (!_host.HasSetAutoRun) + { + _host.Log($"[CastSafe] '{name}' held open {secs:0.0} s after its incantation, but this engine has no SetAutoRun: no nudge."); + return; + } + _host.SetAutoRunBy("Buff/Nudge", true); + _host.SetAutoRunBy("Buff/Nudge", false); + CastNudges++; + if (urgent) UrgentNudges++; + DateTime hold = DateTime.Now.AddMilliseconds(NudgeHoldMs); + if (_busyBackoffUntil < hold) _busyBackoffUntil = hold; + string why = urgent + ? (held != null && IsHealCast(held.SpellId) ? "it is a heal" : $"health {_vitals.HealthPct}% is under a heal line") + + $": nudged at {CastTracker.UrgentHeldAfterIncantMs / 1000:0.0} s, not {CastTracker.HeldAfterIncantMs / 1000:0} s" + : "AC answers 'too busy'"; + _host.Log($"[CastSafe] '{name}' held open {secs:0.0} s after its incantation and {why}: " + + $"one movement nudge (autorun on, off; #{CastNudges} this session). Casts wait {NudgeHoldMs:0} ms for its result."); + } + /// Nudges sent early because the held cast was a heal or health was under a heal line. + internal int UrgentNudges { get; private set; } + /// A cast was accepted by AC, so whatever it was busy with has /// cleared — drop the too-busy backoff immediately rather than serving out a /// stale delay. @@ -2991,7 +3583,126 @@ public class BuffManager : IDisposable // No-wand branch: bare-handed flips sent without reaching Magic before it stops holding the bot. private const int NoWandFlipMaxFails = 4; - private bool EnsureMagicMode(bool forBuff = false) + // Stance settle (2026-10-05): the first hung cast went out 0.55 s after ChangeCombatMode(Magic) + // and the wand use. EnsureMagicMode trusted the client's combat-mode field, which flips before + // the server's stance animation has run. After a stance request or wand use from here, the + // first cast waits until the client reports Magic for StanceSettleMs AND StanceMinAfterRequestMs + // have passed since the request (the stance animation, about 1 s). A request older than + // StanceWaitStaleMs is not waited on. + private const double StanceSettleMs = 300; + private const double StanceMinAfterRequestMs = 1000; + private const double StanceWaitStaleMs = 10_000; + private DateTime _stanceRequestedAt = DateTime.MinValue; + private DateTime _magicSeenAt = DateTime.MinValue; + private bool _stanceWaitLogged; + // Emergency heals (2026-10-05): a heal under Emergency Heal At or Stamina To Health At, or under + // Heal At with a monster in range, waits only for the client to read Magic plus StanceSettleMs: + // no StanceMinAfterRequestMs floor. Drakkon's last Heal Self waited 4.1 s after the request. + private bool _stanceUrgent; + // What held the first cast after the stance was ready (logged with the settle; see StanceSettled). + private string _stanceLateHolder = ""; + /// Times the first cast after a stance change used the emergency-heal settle (tests, status). + internal int UrgentStanceSettles { get; private set; } + + private void NoteStanceRequest() + { + _stanceRequestedAt = Now; + _magicSeenAt = DateTime.MinValue; + _stanceWaitLogged = false; + _stanceLateHolder = ""; + } + + /// + /// Each heartbeat while a stance request is open: when the client first reads Magic, and a + /// drop out of Magic restarts it. StanceSettled used to start the 300 ms clock only when it + /// was first CALLED in Magic, which every other gate in front of it (cast interval, a busy + /// count, a kit in flight) could put off; it also measured the "settled" time at that call. + /// Root cause of the 4.1 s logged on 2026-10-05: the stance was ready 1 s after the request, + /// but a healing kit went out 0.9 s after the request and the vitals step held the spell for + /// the kit's result and grace (KitPending) until 3.1 s later; the log blamed the stance. + /// + private void ObserveStance() + { + if (_stanceRequestedAt == DateTime.MinValue) return; + if (CurrentCombatMode == CombatMode.Magic) + { + if (_magicSeenAt == DateTime.MinValue) _magicSeenAt = Now; + } + else + _magicSeenAt = DateTime.MinValue; // not Magic (yet, or again): the streak restarts + } + + /// When the stance we asked for counts as settled (MinValue: not reading Magic yet). + private DateTime StanceReadyAt(bool urgent) + { + if (_magicSeenAt == DateTime.MinValue) return DateTime.MinValue; + DateTime ready = _magicSeenAt.AddMilliseconds(StanceSettleMs); + if (urgent) return ready; + DateTime minAfterRequest = _stanceRequestedAt.AddMilliseconds(StanceMinAfterRequestMs); + return minAfterRequest > ready ? minAfterRequest : ready; + } + + /// OnHeartbeat's end: while the stance is ready but no cast has used it, remember + /// what held the tick, for the settle line. + private void NoteStanceLateHolder() + { + if (_stanceRequestedAt == DateTime.MinValue) return; + DateTime ready = StanceReadyAt(_stanceUrgent); + if (ready == DateTime.MinValue || Now < ready) return; + string h = _healHold.Length > 0 ? _healHold : LastBuffSkipReason; + if (h.Length > 0 && !h.StartsWith("Magic stance settling", StringComparison.Ordinal)) _stanceLateHolder = h; + } + + /// False while the Magic stance we asked for is still settling (see the fields). + /// : an emergency heal, which skips the 1 s floor. + private bool StanceSettled(bool urgentHeal = false) + { + if (_stanceRequestedAt == DateTime.MinValue) return true; + DateTime now = Now; + if ((now - _stanceRequestedAt).TotalMilliseconds > StanceWaitStaleMs) + { + _stanceRequestedAt = DateTime.MinValue; + return true; + } + _stanceUrgent = urgentHeal; + if (_magicSeenAt == DateTime.MinValue) _magicSeenAt = now; // the client reads Magic (the caller checked) + DateTime ready = StanceReadyAt(urgentHeal); + if (now < ready) + { + LastBuffSkipReason = $"Magic stance settling ({(ready - now).TotalMilliseconds:0} ms left)"; + if (!_stanceWaitLogged) + { + _stanceWaitLogged = true; + _host.Log($"[BuffStance] client reads Magic {(now - _stanceRequestedAt).TotalMilliseconds:0} ms after the stance request; first cast waits {(ready - now).TotalMilliseconds:0} ms more for the stance to settle" + + (urgentHeal ? " (emergency heal: no 1 s floor)." : ".")); + } + return false; + } + double late = (now - ready).TotalMilliseconds; + string lateText = late > 250 + ? $"; the stance was ready {(ready - _stanceRequestedAt).TotalMilliseconds:0} ms after the request and the cast then waited {late:0} ms" + + (_stanceLateHolder.Length > 0 ? $" for: {_stanceLateHolder}" : "") + : ""; + _host.Log($"[BuffStance] Magic stance settled: first cast {(now - _stanceRequestedAt).TotalMilliseconds:0} ms after the stance request ({(now - _magicSeenAt).TotalMilliseconds:0} ms after the client read Magic)" + + (urgentHeal ? ", emergency heal" : "") + lateText + "."); + if (urgentHeal) UrgentStanceSettles++; + _stanceRequestedAt = DateTime.MinValue; + _magicSeenAt = DateTime.MinValue; + _stanceLateHolder = ""; + return true; + } + + /// + /// A health spell that must not wait for the full stance settle: health under Emergency Heal + /// At or Stamina To Health At, or under Heal At with a monster within MonsterRange. + /// + private bool HealIsUrgent(int hp, int stamPct) + { + string line = ActiveHealLine(hp, stamPct, out _, out bool inCombat); + return line is "Emergency Heal At" or "Stamina To Health At" || (line == "Heal At" && inCombat); + } + + private bool EnsureMagicMode(bool forBuff = false, bool urgentHeal = false) { // Per-call signal; only the buff path may set it (vitals/self-heals NEVER degrade). _wandSwapExhausted = false; @@ -3015,7 +3726,8 @@ public class BuffManager : IDisposable _bowDequipPendingId = 0; _bowDequipAttempts = 0; _wieldGateFailCount = 0; - return true; + // In Magic, but the stance we asked for may still be settling: yield the tick. + return StanceSettled(urgentHeal); } int wandId = FindWandInItems(); @@ -3031,6 +3743,7 @@ public class BuffManager : IDisposable if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs) { _host.ChangeCombatMode(CombatMode.Magic); + NoteStanceRequest(); _lastBuffStanceAttempt = DateTime.Now; _lastCastAttempt = DateTime.Now; if (_buffStanceConsecutiveFails < 6) _buffStanceConsecutiveFails++; @@ -3115,7 +3828,7 @@ public class BuffManager : IDisposable (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile)) { if (_host.HasCancelAttack) _host.CancelAttack(); - if (_host.HasStopCompletely) _host.StopCompletely(); + if (_host.HasStopCompletely) _host.StopCompletelyBy("Buff/WandSwap"); _combatTeardownDoneForCurrentBuffCycle = true; _host.Log($"[BuffPre] CancelAttack+StopCompletely before wand equip (mode was {CurrentCombatMode})"); } @@ -3158,6 +3871,7 @@ public class BuffManager : IDisposable } _host.UseFor((uint)wandId, "Buff", "buffing: wield the wand"); + NoteStanceRequest(); _pendingWieldId = wandId; _pendingWieldAt = now; _lastCastAttempt = now; @@ -3189,6 +3903,7 @@ public class BuffManager : IDisposable _buffStanceReEquips++; _host.Log($"[BuffStance] STUCK {stuckMs:0}ms (wielded, mode={CurrentCombatMode}≠Magic) — re-equip attempt {_buffStanceReEquips}/{BuffStanceReEquipMax} 0x{(uint)wandId:X8}"); _host.UseFor((uint)wandId, "Buff", "buffing: stance stuck, wield the wand again"); + NoteStanceRequest(); _lastCastAttempt = DateTime.Now; return false; } @@ -3212,6 +3927,7 @@ public class BuffManager : IDisposable if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs) { _host.ChangeCombatMode(CombatMode.Magic); + NoteStanceRequest(); _lastBuffStanceAttempt = DateTime.Now; _lastCastAttempt = DateTime.Now; if (_buffStanceConsecutiveFails < 6) _buffStanceConsecutiveFails++; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CastTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CastTracker.cs new file mode 100644 index 0000000..bfc882e --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CastTracker.cs @@ -0,0 +1,255 @@ +using System; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Bookkeeping for the casts BuffManager sends (buffs and vitals): when each one went out, +/// when its incantation ("You say, ...") arrived, and whether the server has finished it. +/// +/// Why (Drakkon on DreamWeave, 2026-10-05, ops\overnight\2026-10-05-stuck-cast.md): +/// * The give-up timers ran from the SEND. A healthy DreamWeave vital takes 2.2-2.5 s from +/// its incantation to its result, and the incantation lags the send by up to 1.2 s, so a +/// cast the server was still finishing was given up at 2.5 s and the next one drew +/// "You're too busy!". Now the give-up runs from the incantation when one arrives +/// (), capped, and from the send when none does. +/// * "Has the server finished?" cleared on ANY UseDone, including the 0x1D refusal of the +/// next cast. Now only a completion that belongs to the outstanding cast counts: its own +/// result line, or a UseDone with no error after its incantation (). +/// A refusal is a refusal, not "done". +/// * A cast the server held open (incantation, no result) was only released when someone +/// moved the character. says when to send one movement nudge. +/// * Each cast's time from incantation to result is logged ([CastTime]), so a slow or held +/// cast shows in the log. +/// +/// Pure bookkeeping: it never calls the game. The clock is injectable for the tests. +/// +internal sealed class CastTracker +{ + internal sealed class Cast + { + public int SpellId; + public string Name = ""; + public DateTime SentAt; + public DateTime IncantAt = DateTime.MinValue; + public int SeqAtSend; + public int SeqAtIncant; + public int SeqAtRefusal; + public bool Refused; // AC answered this cast with "You're too busy!" + public bool Done; // its result line, or UseDone(0) after its incantation + public bool Nudged; // the one movement nudge for this held cast has gone out + public bool StuckLogged; + public bool HasIncantation => IncantAt != DateTime.MinValue; + } + + /// Incantation to result, at most. Healthy DreamWeave vitals: 2.21-2.52 s. + public const double IncantToResultMs = 3000; + /// Never wait longer than this after the send, whatever the incantation said. + public const double GiveUpCapMs = 6000; + /// An incantation with no result for this long is a held cast. + public const double HeldAfterIncantMs = 6000; + /// + /// The same, when the held cast is a heal or health is under a heal line (2026-10-05: Drakkon + /// died 4 s after a Heal Self the server held open). Past the healthy 2.2-2.5 s from + /// incantation to result, so a cast still finishing normally is not nudged. + /// + public const double UrgentHeldAfterIncantMs = 2800; + /// An incantation this long after the send isn't credited to it. + private const double IncantWindowMs = 15000; + + private readonly Action _log; + + public CastTracker(Action log) => _log = log; + + public Func Clock = () => DateTime.Now; + public DateTime Now => Clock(); + + /// The last cast sent. + public Cast? Current { get; private set; } + + /// The cast whose incantation arrived and whose result hasn't (may be older than Current). + public Cast? Open { get; private set; } + + /// When to stop waiting for : after + /// the send, or later when its incantation came late (incantation + IncantToResultMs), but + /// never past max(fallbackMs, GiveUpCapMs) after the send. + public static DateTime GiveUpAt(Cast c, double fallbackMs) + { + DateTime basis = c.SentAt.AddMilliseconds(fallbackMs); + if (!c.HasIncantation) return basis; + DateTime byIncant = c.IncantAt.AddMilliseconds(IncantToResultMs); + DateTime cap = c.SentAt.AddMilliseconds(Math.Max(fallbackMs, GiveUpCapMs)); + DateTime d = byIncant > basis ? byIncant : basis; + return d < cap ? d : cap; + } + + /// True when the pending cast is past its give-up time. + /// Null when the tracker doesn't hold that cast (the caller uses its old timer). + public bool? GiveUpReached(int spellId, double fallbackMs) + { + Cast? c = Current; + if (c == null || c.SpellId != spellId) return null; + return Now >= GiveUpAt(c, fallbackMs); + } + + public void Sent(int spellId, string name, int useDoneSeq) + { + DateTime now = Now; + // An earlier cast that is still held open stays Open; one with no incantation is simply replaced. + Current = new Cast { SpellId = spellId, Name = name, SentAt = now, SeqAtSend = useDoneSeq }; + } + + /// "You say, ..." arrived. Credited to the last cast sent when it has none yet. + /// A new incantation also means the server let go of any older open cast. + public Cast? Incantation(int useDoneSeq) + { + DateTime now = Now; + Cast? c = Current; + if (c == null || c.HasIncantation || c.Refused || c.Done || (now - c.SentAt).TotalMilliseconds > IncantWindowMs) + return null; + + if (Open != null && Open != c && !Open.Done) + { + _log($"[CastTime] '{Open.Name}': no result {Secs(now - Open.IncantAt)} after its incantation; the server started the next cast ('{c.Name}'), so it is over."); + Open.Done = true; + } + c.IncantAt = now; + c.SeqAtIncant = useDoneSeq; + Open = c; + _log($"[CastTime] '{c.Name}': incantation {Ms(now - c.SentAt)} after the send."); + return c; + } + + /// A result line ("You cast X ...", a fizzle, a hard refusal). + /// is what followed "You cast " (null for lines that don't name the spell). : + /// an unnamed refusal the server gives before the cast starts (no components, not enough mana), + /// which belongs to the last cast sent. Returns the cast it belongs to, or null. + public Cast? Result(string? castText, string kind, bool atStart = false) + { + Cast? c = null; + bool currentLive = Current != null && !Current.Done && !Current.Refused; + bool openLive = Open != null && !Open.Done; + if (!string.IsNullOrEmpty(castText)) + { + if (Current != null && !Current.Done && Matches(castText, Current.Name)) c = Current; + else if (openLive && Matches(castText, Open!.Name)) c = Open; + } + else if (atStart) + c = currentLive && !Current!.HasIncantation ? Current : (openLive ? Open : null); + else + // Unnamed, after the windup (a fizzle): the cast the server is running, else the last one sent. + c = openLive ? Open : (currentLive ? Current : null); + if (c == null) return null; + Close(c, kind); + return c; + } + + private static bool Matches(string castText, string name) => + name.Length > 0 && castText.StartsWith(name, StringComparison.OrdinalIgnoreCase); + + /// The cast's own enchantment landed (self-buff confirmed by event or registry). + public void Confirmed(int spellId, string kind) + { + if (Current != null && !Current.Done && Current.SpellId == spellId) Close(Current, kind); + else if (Open != null && !Open.Done && Open.SpellId == spellId) Close(Open, kind); + } + + private void Close(Cast c, string kind) + { + c.Done = true; + DateTime now = Now; + string nudged = c.Nudged ? " (after the movement nudge)" : ""; + if (c.HasIncantation) + _log($"[CastTime] '{c.Name}': {kind} {Secs(now - c.IncantAt)} after its incantation (send to incantation {Ms(c.IncantAt - c.SentAt)}){nudged}."); + else + _log($"[CastTime] '{c.Name}': {kind} {Secs(now - c.SentAt)} after the send (no incantation seen){nudged}."); + if (Open == c) Open = null; + } + + /// The last UseDone the engine saw. A UseDone with no error after a cast's incantation + /// is that cast finishing; anything else (0x1D too busy, a UseDone before the incantation) is not. + public void ObserveUseDone(int lastSeq, uint lastError) + { + if (lastError != 0) return; + foreach (Cast? c in new[] { Open, Current }) + { + if (c == null || c.Done || !c.HasIncantation || lastSeq <= c.SeqAtIncant) continue; + Close(c, $"UseDone #{lastSeq} (no error)"); + } + } + + /// + /// True while the server hasn't finished the last cast sent. Clears on that cast's result + /// line, on a UseDone(0) after its incantation, after a refusal once a UseDone(0) shows the + /// server free again, or at its give-up time ( from the send, + /// later with a late incantation). false (an engine before v70) + /// keeps the old rule: any new UseDone clears it. + /// + public bool AwaitingServer(double fallbackMs, int useDoneSeq, bool hasLast, int lastSeq, uint lastError) + { + Cast? c = Current; + if (c == null || c.Done) return false; + if (Now >= GiveUpAt(c, fallbackMs)) return false; + if (!hasLast) return useDoneSeq == c.SeqAtSend; + ObserveUseDone(lastSeq, lastError); + if (c.Done) return false; + if (c.Refused && lastError == 0 && lastSeq > c.SeqAtRefusal) return false; + return true; + } + + /// + /// "You're too busy!" arrived. The last cast sent, if it had no incantation yet, was refused. + /// Returns true exactly once per held cast: an incantation more than HeldAfterIncantMs ago, + /// no result, and AC still refusing casts. The caller sends one movement nudge. + /// + public bool Refusal(int useDoneSeq, double heldAfterMs = HeldAfterIncantMs) + { + Cast? c = Current; + if (c != null && !c.HasIncantation && !c.Done && !c.Refused) + { + c.Refused = true; + c.SeqAtRefusal = useDoneSeq; + } + return TakeNudge(heldAfterMs); + } + + /// + /// True exactly once per held cast: open (incantation, no result) for more than + /// and not nudged yet. Marks it nudged. The refusal path uses + /// it with HeldAfterIncantMs; a heal (or health under a heal line) polls it each tick with + /// UrgentHeldAfterIncantMs, without waiting for a refusal. + /// + public bool TakeNudge(double heldAfterMs) + { + Cast? held = Open; + if (held == null || held.Done || held.Nudged || !held.HasIncantation) return false; + if ((Now - held.IncantAt).TotalMilliseconds <= heldAfterMs) return false; + held.Nudged = true; + return true; + } + + /// The cast the server holds open (incantation, no result), or null. + public Cast? Held => Open is { Done: false } o && o.HasIncantation ? o : null; + + /// One log line the first time a cast has been open past HeldAfterIncantMs (polled each tick). + public void Poll() + { + Cast? held = Open; + if (held == null || held.Done || held.StuckLogged) return; + if ((Now - held.IncantAt).TotalMilliseconds <= HeldAfterIncantMs) return; + held.StuckLogged = true; + _log($"[CastTime] '{held.Name}': HELD - incantation {Secs(Now - held.IncantAt)} ago and no result yet (the server is holding the cast open)."); + } + + /// Seconds a cast has been held open (incantation, no result), or 0. + public double HeldSeconds + { + get + { + Cast? held = Open; + return held == null || held.Done ? 0 : (Now - held.IncantAt).TotalSeconds; + } + } + + private static string Secs(TimeSpan t) => $"{t.TotalSeconds:0.00} s"; + private static string Ms(TimeSpan t) => $"{t.TotalMilliseconds:0} ms"; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index e53b499..b9d250b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -3348,8 +3348,9 @@ public partial class CombatManager : IDisposable /// /// The weapon to fight with (0 = none), and the element in - /// . See WeaponPlanner for the order: the Damage tab's weapon - /// (listed only), the Monsters rule's damage type, the weakness (weakest element a listed + /// . See WeaponPlanner for the order: this monster's Damage tab + /// weapon (listed only), a slayer of the monster, the Damage tab DEFAULT row's weapon, the + /// Monsters rule's damage type, the weakness (weakest element a listed /// weapon of the main kind has), else the weapon in hand, the learned best, the first. /// Casters are skipped when the character has no War/Void Magic (IsUsableCombatWeapon). /// @@ -3414,7 +3415,13 @@ public partial class CombatManager : IDisposable var weak = WeaknessFor(target); listed = ApplyAmmo(listed, ruleElement, weak); // Slayers (PropertyInt 166 = the monster's PropertyInt 2) only when a listed weapon has one. - int ctype = listed.Any(c => c.SlayerType > 0) ? CreatureTypeOf(wcid, target.Name, target.Id) : 0; + int ctype = 0; + if (listed.Any(c => c.SlayerType > 0)) + { + ctype = CreatureTypeOf(wcid, target.Name, target.Id); + if (ctype == 0 && _slayerTypeUnknownNoted.TryAdd(wcid != 0 ? wcid.ToString() : target.Name ?? "", 0)) + _host.Log($"[EquipDiag] '{target.Name}' (wcid {wcid}): creature type not known yet (not appraised, not in the creature data) - no slayer check until it is"); + } return WeaponPlanner.Choose(listed, ruleElement, weak, e => CanCastElement(e, rule), fixedId, fixedSource, learnedId, ctype, fixedIsDefault); } @@ -3424,18 +3431,26 @@ public partial class CombatManager : IDisposable /// /// A weapon's slayer (creature type, damage multiplier); (0, 0) when it has none or isn't - /// identified yet (the weapon tracker identifies listed weapons). ACE needs both properties. + /// identified yet (the weapon tracker identifies listed weapons). The multiplier is 0 when + /// not known: ACE sends SlayerCreatureType (int 166, an assessment property) on appraisal + /// but never SlayerDamageBonus (float 138), so requiring both (as before 2026-10-05) meant no + /// slayer was ever seen on an ACE server. A server that does send float 138 gets it used. /// internal (int Type, double Bonus) SlayerOf(int weaponId) { uint uid = unchecked((uint)weaponId); if (!_host.HasGetObjectIntProperty || !_host.TryGetObjectIntProperty(uid, PropSlayerCreatureType, out int t) || t <= 0) return (0, 0); - if (!_host.HasGetObjectDoubleProperty || !_host.TryGetObjectDoubleProperty(uid, PropSlayerDamageBonus, out double b) || b <= 0) - return (0, 0); - return (t, b); + double bonus = _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(uid, PropSlayerDamageBonus, out double b) && b > 0 ? b : 0; + if (_slayerNoted.TryAdd((weaponId, t), 0)) + _host.Log($"[EquipDiag] weapon 0x{uid:X8} '{WeaponName(weaponId)}' slays {CreatureTypeNames.Name(t)} ({(bonus > 0 ? "x" + bonus.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture) : "bonus not sent")})"); + return (t, bonus); } + // Logged once each: a listed weapon's slayer; a monster whose type isn't known while a slayer is listed. + private readonly System.Collections.Concurrent.ConcurrentDictionary<(int, int), byte> _slayerNoted = new(); + private readonly System.Collections.Concurrent.ConcurrentDictionary _slayerTypeUnknownNoted = new(); + // Creature type by wcid, once seen: a wcid's type never changes, so the next spawn is instant. // Concurrent: the Damage tab's JSON export asks for weaknesses off the combat tick. private readonly System.Collections.Concurrent.ConcurrentDictionary _creatureTypeByWcid = new(); @@ -3443,7 +3458,8 @@ public partial class CombatManager : IDisposable /// /// The monster's CreatureType (PropertyInt 2; 0 = unknown): this session's per-wcid cache, /// else the creature store (appraisals saved by name and wcid), else the live appraisal - /// (the engine identifies every new object). Never guessed from the name. + /// (the engine identifies every new object), else the shipped world-database table + /// (CreatureWeakness: wcid and exact name). Never guessed from name keywords. /// internal int CreatureTypeOf(uint wcid, string? name, int objectId = 0) { @@ -3464,6 +3480,11 @@ public partial class CombatManager : IDisposable if (_creatureTypeByWcid.Count > 4096) _creatureTypeByWcid.Clear(); _creatureTypeByWcid[wcid] = ctype; } + // Not seen yet on this server: the shipped world-database table (wcid and name must both + // match, as for its resists). Not cached, so this monster's own appraisal still wins once + // it lands. 4,506 of the ~4,900 creature profiles are seeded without a type (2026-10-05), + // so before this the first fight with a monster had no slayer step. + if (ctype <= 0) ctype = CreatureWeakness.TableCreatureType(wcid, name); return ctype > 0 ? ctype : 0; } @@ -3996,7 +4017,7 @@ public partial class CombatManager : IDisposable && (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile)) { if (_host.HasCancelAttack) _host.CancelAttack(); - if (_host.HasStopCompletely) _host.StopCompletely(); + if (_host.HasStopCompletely) _host.StopCompletelyBy("Combat"); _combatSwapTeardownDone = true; _host.Log($"[EquipDiag] CancelAttack+StopCompletely before wand equip (mode was {CurrentCombatMode})"); } @@ -4244,7 +4265,7 @@ public partial class CombatManager : IDisposable && (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile)) { if (_host.HasCancelAttack) _host.CancelAttack(); - if (_host.HasStopCompletely) _host.StopCompletely(); + if (_host.HasStopCompletely) _host.StopCompletelyBy("Combat"); _combatSwapTeardownDone = true; } if (!EnsureHandClearForWand(wandId, diagNow: true)) @@ -4393,13 +4414,13 @@ public partial class CombatManager : IDisposable } else if (error > 0) { - _host.SetMotion(MotionTurnRight, true); - _host.SetMotion(MotionTurnLeft, false); + _host.SetMotionBy("Combat", MotionTurnRight, true); + _host.SetMotionBy("Combat", MotionTurnLeft, false); } else { - _host.SetMotion(MotionTurnLeft, true); - _host.SetMotion(MotionTurnRight, false); + _host.SetMotionBy("Combat", MotionTurnLeft, true); + _host.SetMotionBy("Combat", MotionTurnRight, false); } } catch { } @@ -4407,8 +4428,8 @@ public partial class CombatManager : IDisposable private void ClearCombatTurnMotions() { - _host.SetMotion(MotionTurnRight, false); - _host.SetMotion(MotionTurnLeft, false); + _host.SetMotionBy("Combat", MotionTurnRight, false); + _host.SetMotionBy("Combat", MotionTurnLeft, false); } /// Let go of a turn the facing servo is holding. Called when combat stops diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/HealLatencyTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/HealLatencyTracker.cs new file mode 100644 index 0000000..5900e44 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/HealLatencyTracker.cs @@ -0,0 +1,205 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// [HealLatency]: how long health sat under a heal line before the first heal went out, and what +/// held it meanwhile. One line per episode, and a summary every episodes. +/// +/// Why (2026-10-05): a tester playing a mage reported heals that are "sometimes fine, sometimes +/// several seconds late", and nothing in the log said when health crossed a line or what the bot +/// was waiting on. With this a tester's log answers it: +/// +/// [HealLatency] 3120 ms: health 41% under Heal At 60% (in combat) -> Heal Self; held by: busy count 2980 ms (leftover), cast gate 140 ms; arbiter Combat 120 ms +/// +/// An episode opens on the first tick health is under the active line (Emergency Heal At, Stamina +/// To Health At, Heal At in combat, Top Off HP idle) and ends at the first heal sent for it (kit, +/// Heal Self, Stamina to Health or a health potion). While health stays under a line, the next +/// episode opens once that heal has resolved (no kit or vital cast left in flight), so a slow +/// second heal is measured from when it became possible, not from the first one. An episode that +/// ends with no heal (health rose, or the fight ended and the idle line is lower) is logged only +/// when it lasted or more. +/// +/// Pure bookkeeping: BuffManager feeds it once per heartbeat and when a heal goes out; it never +/// calls the game. The clock comes from the caller (tests move it by hand). +/// +internal sealed class HealLatencyTracker +{ + /// A summary line after this many healed episodes. + public const int SummaryEvery = 10; + /// An episode that ends without a heal is logged only from this long. + public const double NoHealLogMs = 1000; + + private readonly Action _log; + public HealLatencyTracker(Action log) => _log = log; + + // ── The open episode ──────────────────────────────────────────────────── + private bool _open; + private bool _healed; // a heal went out for the open episode; waiting for it to resolve + private bool _followUp; // opened while health stayed under the line after a heal + private DateTime _start; + private int _startHp; + private string _line = ""; + private int _lineValue; + private bool _inCombat; + private DateTime _lastTickAt = DateTime.MinValue; + // Time held per reason, and time the arbiter gave the tick to something other than Buffing. + private readonly Dictionary _held = new(StringComparer.Ordinal); + private readonly Dictionary _arbiter = new(StringComparer.Ordinal); + private string _lastDetail = ""; + + // ── Summary since the last summary line ───────────────────────────────── + private int _n; + private double _sumMs, _maxMs; + private string _maxWhat = ""; + private int _over1s, _over3s, _noHeal; + + /// Totals for the tests and /ra status. + public int Episodes { get; private set; } + public double LastDelayMs { get; private set; } = -1; + public string LastLine { get; private set; } = ""; + public bool IsOpen => _open && !_healed; + + /// + /// Once per heartbeat, before the tick's work: health and the line it is under (line "" = none). + /// : a kit or a heal cast from the last episode hasn't resolved yet. + /// + public void Observe(DateTime now, int hp, string line, int lineValue, bool inCombat, bool healInFlight) + { + bool under = line.Length > 0; + if (!under) + { + if (_open && !_healed) + { + double ms = (now - _start).TotalMilliseconds; + if (ms >= NoHealLogMs) + { + _noHeal++; + _log($"[HealLatency] no heal in {ms:0} ms: health {_startHp}% under {_line} {_lineValue}%{Where(_inCombat)}{(_followUp ? " (follow-up)" : "")}, " + + $"then {hp}% (over the line now); held by: {Held()}{Arb()}"); + } + } + _open = false; + _healed = false; + _followUp = false; + return; + } + + if (_open && _healed) + { + // Still under a line after a heal: the next one is measured from when it became possible. + if (healInFlight) { _lastTickAt = now; return; } + Begin(now, hp, line, lineValue, inCombat, followUp: true); + return; + } + if (!_open) + { + Begin(now, hp, line, lineValue, inCombat, followUp: false); + return; + } + // Open and waiting: a lower line (Heal At -> Emergency) is worth saying in the line. + if (line != _line && (line.StartsWith("Emergency", StringComparison.Ordinal) || line.StartsWith("Stamina", StringComparison.Ordinal))) + { + _line = line; + _lineValue = lineValue; + } + } + + /// Once per heartbeat, after the tick's work: why no heal went out this tick. + public void EndTick(DateTime now, string heldBy, string detail, string arbiterActivity) + { + if (!_open || _healed) { _lastTickAt = now; return; } + double dt = _lastTickAt == DateTime.MinValue ? 0 : (now - _lastTickAt).TotalMilliseconds; + if (dt < 0 || dt > 2000) dt = 0; // a hitch or a paused clock is not "held" + _lastTickAt = now; + if (dt <= 0) return; + string key = heldBy.Length > 0 ? heldBy : "nothing reported"; + _held[key] = (_held.TryGetValue(key, out double h) ? h : 0) + dt; + if (detail.Length > 0) _lastDetail = detail; + if (arbiterActivity.Length > 0 && arbiterActivity != "Buffing") + _arbiter[arbiterActivity] = (_arbiter.TryGetValue(arbiterActivity, out double a) ? a : 0) + dt; + } + + /// A heal went out (kit, Heal Self, Stamina to Health, health potion). + public void HealSent(DateTime now, string action) + { + if (!_open || _healed) return; + _healed = true; + double ms = Math.Max(0, (now - _start).TotalMilliseconds); + Episodes++; + LastDelayMs = ms; + string line = $"[HealLatency] {ms:0} ms: health {_startHp}% under {_line} {_lineValue}%{Where(_inCombat)}{(_followUp ? " (follow-up)" : "")} -> {action}; held by: {Held()}{Arb()}"; + LastLine = line; + _log(line); + + _n++; + _sumMs += ms; + if (ms >= 1000) _over1s++; + if (ms >= 3000) _over3s++; + if (ms > _maxMs) { _maxMs = ms; _maxWhat = $"{action}, {TopHeld()}"; } + if (_n >= SummaryEvery) + { + _log($"[HealLatency] summary of {_n} heals: avg {_sumMs / _n:0} ms, max {_maxMs:0} ms ({_maxWhat}); " + + $"{_over1s} over 1 s, {_over3s} over 3 s; {_noHeal} episode(s) with no heal"); + _n = 0; _sumMs = 0; _maxMs = 0; _maxWhat = ""; _over1s = 0; _over3s = 0; _noHeal = 0; + } + } + + private void Begin(DateTime now, int hp, string line, int lineValue, bool inCombat, bool followUp) + { + _open = true; + _healed = false; + _followUp = followUp; + _start = now; + _startHp = hp; + _line = line; + _lineValue = lineValue; + _inCombat = inCombat; + _lastTickAt = now; + _held.Clear(); + _arbiter.Clear(); + _lastDetail = ""; + } + + private static string Where(bool inCombat) => inCombat ? " (in combat)" : " (idle)"; + + private string Held() + { + if (_held.Count == 0) return "nothing (healed on the first tick)"; + var parts = new List>(_held); + parts.Sort((a, b) => b.Value.CompareTo(a.Value)); + var sb = new StringBuilder(); + for (int i = 0; i < parts.Count && i < 4; i++) + { + if (i > 0) sb.Append(", "); + sb.Append(parts[i].Key).Append(' ').Append(parts[i].Value.ToString("0")).Append(" ms"); + } + if (_lastDetail.Length > 0) sb.Append(" [last: ").Append(_lastDetail).Append(']'); + return sb.ToString(); + } + + private string TopHeld() + { + string top = "nothing"; + double best = -1; + foreach (var kv in _held) + if (kv.Value > best) { best = kv.Value; top = kv.Key; } + return top; + } + + private string Arb() + { + if (_arbiter.Count == 0) return ""; + var sb = new StringBuilder("; arbiter gave the tick to "); + bool first = true; + foreach (var kv in _arbiter) + { + if (!first) sb.Append(", "); + first = false; + sb.Append(kv.Key).Append(' ').Append(kv.Value.ToString("0")).Append(" ms"); + } + return sb.ToString(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/ReloadSafety.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/ReloadSafety.cs new file mode 100644 index 0000000..8bf7904 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/ReloadSafety.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// What RynthAi tells the engine before a hot reload (the RynthPluginReloadBlocker export). +/// +/// Drakkon died on 2026-10-05 13:43:20 after an engine hot reload at 13:42:55 took every plugin +/// down for about 8 s in the middle of a fight. The engine now asks each plugin before it reloads +/// and waits (up to 2 minutes) while one says a reload would hurt. RynthAi says so while the macro +/// runs and a monster is engaged, health is under a heal line, or a cast is awaiting its result. +/// +/// Pure: the plugin computes the text on its own thread each tick; the export only hands the last +/// text to the engine. +/// +internal static class ReloadSafety +{ + /// Why a reload now would hurt, or "" when it is safe. The engine logs + /// "engine reload waiting: RynthAi " followed by this text. + public static string Reason(bool macroRunning, bool monsterEngaged, string healLine, int healthPct, + int lineValue, string castInFlight) + { + if (!macroRunning) return ""; + var parts = new List(3); + if (monsterEngaged) parts.Add("a monster engaged"); + if (healLine.Length > 0) parts.Add($"health {healthPct}% under {healLine} {lineValue}%"); + if (castInFlight.Length > 0) parts.Add($"'{castInFlight}' awaiting its result"); + if (parts.Count == 0) return ""; + bool fight = monsterEngaged || healLine.Length > 0; + return (fight ? "in combat" : "casting") + " (" + string.Join(", ", parts) + ")"; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponPlanner.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponPlanner.cs index 87b299a..ef5363e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponPlanner.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponPlanner.cs @@ -9,7 +9,9 @@ namespace RynthCore.Plugin.RynthAi; /// Normalized element ("" = unknown). /// Element of a rending imbue ("" = none). /// The creature type it slays (PropertyInt 166 SlayerCreatureType, 0 = none). -/// Its damage multiplier against that type (PropertyFloat 138 SlayerDamageBonus, 0 = none). +/// Its damage multiplier against that type (PropertyFloat 138 SlayerDamageBonus); 0 = not +/// known. ACE never sends float 138 on appraisal (it isn't an assessment property), so with a SlayerType it is +/// usually 0, and the weapon still slays (every slayer in the ACE world database has a bonus of 1.15 or more). internal sealed record WeaponCandidate(int Id, string Name, int Kind, string Element, string Rending, bool InHand, int SlayerType = 0, double SlayerBonus = 0); @@ -19,17 +21,22 @@ internal readonly record struct WeaponPlan(int WeaponId, string Element, string /// /// The element-and-weapon rule, pure (no host). The weakness decides the weapon, never the -/// other way round, except for a slayer: -/// 1. A Damage tab weapon (this monster's, else the DEFAULT row's) is used as set; it must be in the Items list. -/// Its element is the rule's, else its own, else the weakest the character can cast. +/// other way round, except for a slayer (owner's rule, 2026-10-05: a monster is always +/// attacked with a slayer of it before an element choice, even when another weapon's element +/// meets a lower resistance; only a weapon the player set for that monster trumps it): +/// 1. The weapon set on THIS monster's own Damage tab row is used as set, slayer or not; it +/// must be in the Items list. Its element is the rule's, else its own, else the weakest +/// the character can cast. /// 2. A slayer: a listed weapon of the character's main kind whose SlayerCreatureType is -/// the monster's CreatureType and whose SlayerDamageBonus is above 1 (ACE multiplies the -/// whole hit by it, so it beats any element choice). Several: the biggest bonus, then -/// the element order (the rule's element, else the weakest group), then a matching -/// rending, then the one in hand, then list order. Its element is the wand's own, else a -/// melee/missile weapon's own, else the rule's, else the weakest the character can cast. -/// Creature type unknown (not appraised yet): no slayer step. -/// 3. (The Damage tab DEFAULT row's weapon is a player pick too: it is step 1.) +/// the monster's CreatureType and whose SlayerDamageBonus is above 1 or not known (ACE +/// multiplies the whole hit by it, so it beats any element choice, and never sends the +/// bonus on appraisal). Several: the biggest bonus (an unknown one counts as +/// UnknownSlayerBonus), then the element order (the rule's element, else the weakest +/// group), then a matching rending, then the one in hand, then list order. Its element +/// is the wand's own, else a melee/missile weapon's own, else the rule's, else the +/// weakest the character can cast. Creature type unknown: no slayer step. +/// A slayer of another kind (a melee slayer for a mage) is not a candidate. +/// 3. The Damage tab DEFAULT row's weapon (listed only): above the element steps, below a slayer. /// 4. A Monsters rule damage type (not Auto) is the element; wield the listed weapon of that /// element (a matching rending first, then the one in hand, then list order). /// Whatever is chosen, a wand casts its own element when it has one (owner's rule, @@ -51,6 +58,12 @@ internal static class WeaponPlanner /// Two multipliers this close are a tie. public const double TieEpsilon = 0.005; + /// + /// The bonus a slayer whose SlayerDamageBonus isn't known is ranked at: the smallest in the + /// ACE world database (1.15), so a slayer with a known bigger bonus wins over it. + /// + public const double UnknownSlayerBonus = 1.15; + /// Fallback element order when nothing is known ("Slash" first). public static readonly string[] FallbackOrder = { "Slash", "Fire", "Cold", "Lightning", "Acid", "Pierce", "Bludgeon", "Nether" }; @@ -69,12 +82,13 @@ internal static class WeaponPlanner bool ruleSet = rule.Length > 0; WeaponCandidate? fixedPick = fixedWeaponId != 0 ? Find(listed, fixedWeaponId) : null; - // 1. A weapon the player picked on the Damage tab: for this monster, or the DEFAULT row's - // (listed only). A player's pick is honoured, slayer or not (owner, 2026-10-04: "if - // it's set to auto slayer wins, if the player picks a weapon we honour that"). - // fixedIsDefault only changes the source label. - if (fixedPick != null) - return FixedPlan(fixedPick, fixedSource, rule, weak, canCast); + // 1. The weapon the player set on this monster's own Damage tab row (listed only): honoured, + // slayer or not (owner, 2026-10-05: "the only time a slayer property gets trumped is if + // the player manually inputs a weapon without it"). The DEFAULT row's weapon is not a + // pick for this monster: a slayer of it beats that one (step 3). + if (fixedPick != null && !fixedIsDefault) + return FixedPlan(fixedPick, Slays(fixedPick, creatureType) + ? fixedSource + ", " + SlayerSource(creatureType, fixedPick.SlayerBonus) : fixedSource, rule, weak, canCast); if (listed.Count == 0) { @@ -101,7 +115,7 @@ internal static class WeaponPlanner } } - // 3. The Damage tab default weapon (listed only). + // 3. The Damage tab DEFAULT row's weapon (listed only): no slayer of this monster is listed. if (fixedPick != null) return FixedPlan(fixedPick, fixedSource, rule, weak, canCast); @@ -200,16 +214,24 @@ internal static class WeaponPlanner return null; } - /// True when slays (ACE: SlayerCreatureType == CreatureType, with a bonus). + /// + /// True when slays (ACE: SlayerCreatureType == + /// CreatureType). A bonus that is known must be above 1; an unknown one (0: ACE doesn't send + /// float 138 on appraisal) counts. + /// public static bool Slays(WeaponCandidate c, int creatureType) => - creatureType > 0 && c.SlayerType == creatureType && c.SlayerBonus > 1.0 + TieEpsilon; + creatureType > 0 && c.SlayerType == creatureType && (c.SlayerBonus <= 0 || c.SlayerBonus > 1.0 + TieEpsilon); - /// The plan's source for a slayer: "slayer (Olthoi x2)". - public static string SlayerSource(int creatureType, double bonus) => - $"slayer ({CreatureTypeNames.Name(creatureType)} x{bonus.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)})"; + /// The bonus a slayer is ranked at: its own when known, else . + public static double RankBonus(WeaponCandidate c) => c.SlayerBonus > 0 ? c.SlayerBonus : UnknownSlayerBonus; + + /// The plan's source for a slayer: "slayer (Olthoi x2)", or "slayer (Olthoi)" when the bonus isn't known. + public static string SlayerSource(int creatureType, double bonus) => bonus > 0 + ? $"slayer ({CreatureTypeNames.Name(creatureType)} x{bonus.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)})" + : $"slayer ({CreatureTypeNames.Name(creatureType)})"; /// - /// The matching slayer to wield: the biggest bonus (ties within ), + /// The matching slayer to wield: the biggest bonus (; ties within ), /// then the element order (the rule's element, else the weakest group), then a matching /// rending, then the one in hand, then list order. Null when none matches. /// @@ -217,7 +239,7 @@ internal static class WeaponPlanner CreatureWeakness.Ranking? weak, Func canCast) { double top = 0; - foreach (var c in pool) if (Slays(c, creatureType) && c.SlayerBonus > top) top = c.SlayerBonus; + foreach (var c in pool) if (Slays(c, creatureType) && RankBonus(c) > top) top = RankBonus(c); if (top <= 0) return null; List>? groups = rule.Length == 0 && weak != null && weak.Order.Count > 0 ? TieGroups(weak) : null; @@ -226,7 +248,7 @@ internal static class WeaponPlanner for (int i = 0; i < pool.Count; i++) { var c = pool[i]; - if (!Slays(c, creatureType) || c.SlayerBonus < top - TieEpsilon) continue; + if (!Slays(c, creatureType) || RankBonus(c) < top - TieEpsilon) continue; int elemRank = 0; if (rule.Length > 0) elemRank = c.Element == rule ? 0 : 1; else if (groups != null) diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index 32a6d9a..0e7da6c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using RynthCore.Plugin.RynthAi.LegacyUi; @@ -21,6 +22,8 @@ public sealed partial class RynthAiPlugin public string LongDesc { get; init; } public bool InFellowship { get; init; } public bool KillerIsFellow { get; init; } + /// Your own death corpse, to be recovered whole (LootOwnCorpse; see MatchOwnDeathCorpse). + public bool IsOwnDeathCorpse { get; init; } } // id → completed-at ms. Authoritative "looted, do not reopen" set. Aged out @@ -238,7 +241,7 @@ public sealed partial class RynthAiPlugin { string count = _lastCombatBusyStaleLogAt == 0 ? "first" : $"{_combatBusyStaleSinceLog} in the last {(now - _lastCombatBusyStaleLogAt) / 1000.0:0}s"; - Log($"[RynthAi] shadow busy-reset by combat (was {was}, {reason}; {count}) — real field left to the engine reconciler"); + Log($"[RynthAi] shadow busy-reset for a leftover count (was {was}, {reason}; {count}) — real field left to the engine reconciler"); _lastCombatBusyStaleLogAt = now; _combatBusyStaleSinceLog = 0; } @@ -522,8 +525,9 @@ public sealed partial class RynthAiPlugin if (_targetCorpseId == 0) { // Same gate as HasLootWork: this claim runs every tick whatever the arbiter - // decided, so without it a full pack still claimed the next corpse. - if (IsLootingBlockedByPack(settings)) + // decided, so without it a full pack still claimed the next corpse. Your own + // corpse is let through unless no pack has a slot at all. + if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, maxMeters)) return; if (!TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out _)) @@ -546,6 +550,22 @@ public sealed partial class RynthAiPlugin LootDiag($"[RynthAi] Corpse loot: claimed corpse target 0x{(uint)corpse.Id:X8}."); PauseNavigationForCorpse(); } + else if (_openedContainerId == 0 && settings.LootOwnCorpse) + { + // Your own corpse came into range while another (unopened) corpse was claimed: + // it beats normal looting, so switch to it. + WorldObject? claimed = _objectCache[_targetCorpseId]; + if ((claimed == null || !EvaluateCorpseLootDecision(claimed).IsOwnDeathCorpse) + && TryFindOwnCorpseInRange(maxMeters, out WorldObject? ownNow) && ownNow != null && ownNow.Id != _targetCorpseId) + { + LootDiag($"[RynthAi] Own corpse: 0x{(uint)ownNow.Id:X8} is in range; switching to it from 0x{(uint)_targetCorpseId:X8}."); + ResetCorpseTarget(); + _targetCorpseId = ownNow.Id; + _corpseTargetSince = now; + _lastCorpseOpenAttemptAt = 0; + _lastOpenAttemptCorpseId = 0; + } + } // A claim can be tentative: the killer is unknown until the corpse's ID lands. // Once it says the corpse isn't ours to loot, drop the claim instead of walking @@ -685,6 +705,8 @@ public sealed partial class RynthAiPlugin long now = CorpseNowMs; int playerId = unchecked((int)_playerId); + WorldObject? ownCorpse = null; + double ownDistance = double.MaxValue; foreach (WorldObject candidate in _objectCache.GetLandscapeObjects()) { if (candidate.ObjectClass != AcObjectClass.Corpse) @@ -712,13 +734,28 @@ public sealed partial class RynthAiPlugin } double dist = _objectCache.Distance(playerId, candidate.Id); - if (dist > maxMeters || dist >= distanceMeters) + if (dist > maxMeters) + continue; + + // Your own corpse beats any other corpse in range, whatever the distances. + if (decision.IsOwnDeathCorpse) + { + if (ownCorpse == null || dist < ownDistance) { ownCorpse = candidate; ownDistance = dist; } + continue; + } + + if (dist >= distanceMeters) continue; corpse = candidate; distanceMeters = dist; } + if (ownCorpse != null) + { + corpse = ownCorpse; + distanceMeters = ownDistance; + } return corpse != null; } @@ -769,6 +806,44 @@ public sealed partial class RynthAiPlugin }; } + // Your own death corpse (LootOwnCorpse): recovered whole, whatever Loot From says. A + // corpse with your name whose ID hasn't landed yet waits for it (no profile looting of + // it meanwhile); anything else falls through to the ownership rules below unchanged. + if (settings.LootOwnCorpse) + { + OwnCorpseMatch own = MatchOwnDeathCorpse(corpse.Name, myName, longDesc); + if (own == OwnCorpseMatch.Yes) + { + return new CorpseLootDecision + { + ShouldLoot = true, + ModeName = "Own corpse", + Reason = "Your own corpse: every item on it is recovered (Recover My Corpse).", + KillerName = killerName, + PlayerName = myName, + LongDesc = longDesc, + InFellowship = inFellowship, + KillerIsFellow = killerIsFellow, + IsOwnDeathCorpse = true + }; + } + if (own == OwnCorpseMatch.Pending) + { + RequestOwnCorpseId(corpse.Id); + return new CorpseLootDecision + { + ShouldLoot = false, + ModeName = "Own corpse", + Reason = "Named like your corpse; waiting for its ID (the 'Killed by' line) before recovering it.", + KillerName = killerName, + PlayerName = myName, + LongDesc = longDesc, + InFellowship = inFellowship, + KillerIsFellow = killerIsFellow + }; + } + } + if (lootOwnership >= 2) { return new CorpseLootDecision @@ -1017,6 +1092,15 @@ public sealed partial class RynthAiPlugin TickPendingCorpsePickup(settings); if (_currentLootItemMovePending) return; // Still waiting for this pickup to clear + if (_openedContainerId != corpseId) + return; // the retry finished or paused the corpse (no pack had room) + } + + // Your own corpse: every item, no profile (RynthAiPlugin.OwnCorpse.cs). + if (IsOwnDeathCorpseId(settings, corpseId)) + { + TickOwnCorpseRecovery(settings, corpseId, containedItems, openAge, now); + return; } // Pre-classify items and batch-request IDs only for items that need them. @@ -1384,7 +1468,16 @@ public sealed partial class RynthAiPlugin /// private LootPickupResult SendLootPickup(int itemId, string itemName, int corpseId) { - LootPickupResult r = LootPickup.Send(Host, _objectCache, unchecked((uint)itemId), _playerId, out uint dest); + bool ownCorpse = corpseId != 0 && corpseId == _ownRecoveryCorpseId; + uint dest; + LootPickupResult r = ownCorpse + ? SendOwnCorpsePickup(itemId, out dest) + : LootPickup.Send(Host, _objectCache, unchecked((uint)itemId), _playerId, out dest); + if (ownCorpse && r == LootPickupResult.NoRoom) + { + PauseOwnCorpseNoRoom(corpseId, itemName); + return r; + } switch (r) { case LootPickupResult.Moved: @@ -1412,6 +1505,8 @@ public sealed partial class RynthAiPlugin _processedCorpseItems.Add(_currentLootItemId); LootDiag($"[RynthAi] Corpse loot: pickup confirmed for 0x{(uint)_currentLootItemId:X8}; {reason}."); + if (_openedContainerId != 0 && _openedContainerId == _ownRecoveryCorpseId) + NoteOwnCorpseItemRecovered(now); if (!string.IsNullOrWhiteSpace(_currentLootItemName)) ChatLine($"[RynthAi] Looted [{_currentLootItemActionLabel}] {_currentLootItemName}"); @@ -1462,7 +1557,8 @@ public sealed partial class RynthAiPlugin } // No room anywhere: don't start on another corpse (IsPackFull says so once in chat). - if (IsLootingBlockedByPack(settings)) + // Your own corpse is let through unless no pack has a slot at all. + if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, GetCorpseApproachRangeMaxMeters(settings))) return false; // Loot grace: combat just ended and the corpse CreateObject has not @@ -1542,6 +1638,10 @@ public sealed partial class RynthAiPlugin if (now - _corpseWaitingSince[candidate.Id] >= LootStarveMs) _lootStarved = true; } + else if (dist != double.MaxValue && decision.IsOwnDeathCorpse && _corpseSkipLogged.Add(candidate.Id)) + { + LootDiag($"[RynthAi] Own corpse: 0x{(uint)candidate.Id:X8} '{candidate.Name}' is out of loot range (d={dist:0.0}m > {maxMeters:0.0}m); it is recovered once it is within range."); + } else if (dist != double.MaxValue && IsOwnKill(decision) && _corpseSkipLogged.Add(candidate.Id)) { LootDiag($"[RynthAi] Corpse loot: own corpse 0x{(uint)candidate.Id:X8} '{candidate.Name}' is out of loot range (d={dist:0.0}m > {maxMeters:0.0}m); not walking back for it."); @@ -1603,22 +1703,37 @@ public sealed partial class RynthAiPlugin } /// - /// Pure classification — evaluates an item against the active loot profile - /// without performing any pickup or side effects. Returns true if the item - /// matched a loot/salvage rule. + /// Classification: evaluates an item against the active loot profile and RynthAi's + /// built-in keeps without performing any pickup. Returns true if the item is to be + /// taken; actionLabel/ruleLabel are what [LootEval] logs. The looter's calls record + /// what they approve (pending sets, counters, chat); ClassifyLootItem has the preview. /// - private bool ClassifyItemAgainstProfile(WorldObject item, LegacyUiSettings settings, out string actionLabel, out bool isSalvage, out string ruleLabel) + private bool ClassifyItemAgainstProfile(WorldObject item, LegacyUiSettings settings, out string actionLabel, out bool isSalvage, out string ruleLabel) => + ClassifyLootItem(item, settings, preview: false, out actionLabel, out isSalvage, out ruleLabel, out _); + + /// + /// The one place the looter decides, with : the same verdict + /// with nothing recorded, counted, logged or said in chat (the "Add to loot profile" + /// popup asking why an item is taken). is set when one of + /// RynthAi's built-in keeps took the item rather than a loot profile rule: Learn unknown + /// spells and mana stones (checked before the profile), Mana Tap (when no rule matches). + /// It says what and where to change it, in plain ASCII (the popup's font). + /// + private bool ClassifyLootItem(WorldObject item, LegacyUiSettings settings, bool preview, + out string actionLabel, out bool isSalvage, out string ruleLabel, out string builtIn) { actionLabel = string.Empty; isSalvage = false; ruleLabel = string.Empty; + builtIn = string.Empty; // Learn unknown spells (VTank ReadUnknownScrolls): a built-in rule ahead of the loot // profile, as in VTank. A scroll of a spell we don't know and can learn is looted to read. - if (_scrollLearner != null && _scrollLearner.ShouldLootFromCorpse(item, out string learnRule)) + if (_scrollLearner != null && _scrollLearner.ShouldLootFromCorpse(item, out string learnRule, out string learnWhy, preview)) { actionLabel = ScrollLearner.ReadAction; ruleLabel = learnRule; + builtIn = $"Learn unknown spells ({learnWhy}) - change in Settings > Looting, Learn Unknown Spells"; return true; } @@ -1663,15 +1778,17 @@ public sealed partial class RynthAiPlugin int haveCount = liveCount + pendingNotYetCounted; // One-time-per-corpse log so we can see what the count was based on. - if (_pendingManaStoneIds.Count == 0) + if (!preview && _pendingManaStoneIds.Count == 0) Host.Log($"[RynthAi] ManaStone count for cap check: live={liveCount} pending={pendingNotYetCounted} cap={settings.ManaStoneKeepCount} (cache_known={_objectCache?.AllKnownObjects().Count() ?? 0})"); // If this specific stone is already approved, return the same answer // we returned last time (no further log spam, no count change). + string stoneWhy = $"a mana stone, {haveCount} of {settings.ManaStoneKeepCount} kept - change in the Items panel, Mana Stone Tapping (Keep count)"; if (_pendingManaStoneIds.Contains(item.Id)) { actionLabel = "Keep"; ruleLabel = $"ManaStone (Consumable, {haveCount + 1}/{settings.ManaStoneKeepCount})"; + builtIn = stoneWhy; return true; } @@ -1679,39 +1796,42 @@ public sealed partial class RynthAiPlugin { actionLabel = "Keep"; ruleLabel = $"ManaStone (Consumable, {haveCount + 1}/{settings.ManaStoneKeepCount})"; + builtIn = stoneWhy; + if (preview) return true; ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}, +1) — looting."); _pendingManaStoneIds.Add(item.Id); return true; } - ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}) — at cap, leaving."); + if (!preview) + ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}) — at cap, leaving."); return false; } if (TryLoadNativeLootProfile(out LootProfile nativeProfile, out _)) { - _corpseItemsEvaluated++; + if (!preview) _corpseItemsEvaluated++; var (nativeAction, nativeRule) = LootEvaluator.Classify(nativeProfile, item, _charSkills); if (nativeRule == null) { - if (TryClassifyAsManaTap(item, settings, out actionLabel, out ruleLabel)) + if (TryClassifyAsManaTap(item, settings, preview, out actionLabel, out ruleLabel, out builtIn)) { - _corpseItemsMatched++; + if (!preview) _corpseItemsMatched++; return true; } return false; } ruleLabel = string.IsNullOrWhiteSpace(nativeRule.Name) ? "rule" : nativeRule.Name.Trim(); - if (nativeAction == LootAction.Read && IsReadOfNonScroll(item, ruleLabel)) + if (nativeAction == LootAction.Read && IsReadOfNonScroll(item, ruleLabel, preview)) return false; if (nativeAction == LootAction.KeepUpTo) { var rule = nativeRule; if (!UnderKeepCap("n:" + ruleLabel, ruleLabel, item, rule.KeepCount, - inv => LootEvaluator.Matches(rule, inv, _charSkills))) + inv => LootEvaluator.Matches(rule, inv, _charSkills), preview)) return false; } - _corpseItemsMatched++; + if (!preview) _corpseItemsMatched++; actionLabel = nativeAction.ToString(); isSalvage = nativeAction == LootAction.Salvage; return true; @@ -1721,15 +1841,15 @@ public sealed partial class RynthAiPlugin if (!TryLoadLootProfile(string.Empty, out VTankLootProfile vtankProfile, out _)) return false; - _corpseItemsEvaluated++; + if (!preview) _corpseItemsEvaluated++; VTankLootContext lootCtx = new(Host, _playerId) { Cache = _objectCache }; VTankLootRule? matchedRule = VTankLootEvaluator.FirstMatch(vtankProfile, item, lootCtx, out int matchedRuleIndex); if (matchedRule == null) { - if (TryClassifyAsManaTap(item, settings, out actionLabel, out ruleLabel)) + if (TryClassifyAsManaTap(item, settings, preview, out actionLabel, out ruleLabel, out builtIn)) { - _corpseItemsMatched++; + if (!preview) _corpseItemsMatched++; return true; } return false; @@ -1738,16 +1858,16 @@ public sealed partial class RynthAiPlugin ruleLabel = string.IsNullOrWhiteSpace(matchedRule.Name) ? $"#{matchedRuleIndex}" : matchedRule.Name.Trim(); - if (matchedRule.Action == VTankLootAction.Read && IsReadOfNonScroll(item, ruleLabel)) + if (matchedRule.Action == VTankLootAction.Read && IsReadOfNonScroll(item, ruleLabel, preview)) return false; if (matchedRule.Action == VTankLootAction.KeepUpTo) { var rule = matchedRule; if (!UnderKeepCap("v:" + matchedRuleIndex + ":" + ruleLabel, ruleLabel, item, rule.KeepCount ?? 0, - inv => VTankLootEvaluator.Match(rule, inv, lootCtx))) + inv => VTankLootEvaluator.Match(rule, inv, lootCtx), preview)) return false; } - _corpseItemsMatched++; + if (!preview) _corpseItemsMatched++; actionLabel = matchedRule.Action.ToString(); isSalvage = matchedRule.Action == VTankLootAction.Salvage; return true; @@ -1760,9 +1880,10 @@ public sealed partial class RynthAiPlugin /// attempted to classify item ... for reading, but that item does not appear to be a /// scroll. Ignoring it." The item is left, with one log line. /// - private bool IsReadOfNonScroll(WorldObject item, string ruleLabel) + private bool IsReadOfNonScroll(WorldObject item, string ruleLabel, bool preview = false) { if (ScrollLearner.LooksLikeScroll(item)) return false; + if (preview) return true; if (_readNonScrollLogged.Count > 1000) _readNonScrollLogged.Clear(); if (_readNonScrollLogged.Add(item.Id)) Host.Log($"[Learn] loot rule '{ruleLabel}' says Read, but '{item.Name}' isn't a scroll - leaving it"); @@ -1775,10 +1896,13 @@ public sealed partial class RynthAiPlugin /// items already approved on this corpse that haven't reached the pack yet. /// A matching Keep # rule used to loot everything, like a plain Keep. /// - private bool UnderKeepCap(string key, string ruleLabel, WorldObject item, int cap, Func matches) + private bool UnderKeepCap(string key, string ruleLabel, WorldObject item, int cap, Func matches, bool preview = false) { if (!_pendingKeepUpTo.TryGetValue(key, out var pending)) - _pendingKeepUpTo[key] = pending = new Dictionary(); + { + pending = new Dictionary(); + if (!preview) _pendingKeepUpTo[key] = pending; + } if (pending.ContainsKey(item.Id)) return true; // approved on an earlier pass // Whole stacks in the pack that the rule matches, plus approved-but-not-in-the-pack-yet @@ -1791,6 +1915,7 @@ public sealed partial class RynthAiPlugin id => _objectCache?[id] != null); int stack = LootKeepCap.StackOf(item); + if (preview) return LootKeepCap.UnderCap(have, cap); if (!LootKeepCap.UnderCap(have, cap)) { ChatLine($"[RynthAi] Keep # '{ruleLabel}': have {have}/{cap} — leaving {item.Name}."); @@ -1859,14 +1984,19 @@ public sealed partial class RynthAiPlugin /// only way an item becomes a tap target: the pickup (label ManaTap) is /// recorded via ManaStoneManager.MarkLootedForTap. /// - private bool TryClassifyAsManaTap(WorldObject item, LegacyUiSettings settings, - out string actionLabel, out string ruleLabel) + private bool TryClassifyAsManaTap(WorldObject item, LegacyUiSettings settings, bool preview, + out string actionLabel, out string ruleLabel, out string builtIn) { actionLabel = string.Empty; ruleLabel = string.Empty; + builtIn = string.Empty; if (_manaStoneManager == null) return false; if (!Host.HasGetObjectIntProperty) return false; + // ACE won't drain a wand, staff or orb into a stone, so ManaStoneManager never taps + // one (and its pending-drain count skips them, so the quota never filled): every + // high-mana wand was looted and kept for good. Drakkon's "Piercing Sceptre", 2026-10-05. + if (ManaStoneManager.IsWandLike(item)) return false; int threshold = settings.ManaTapMinMana; if (threshold <= 0) return false; @@ -1876,12 +2006,17 @@ public sealed partial class RynthAiPlugin return false; if (curMana < threshold) return false; + string tapWhy = "Mana Tap (" + curMana.ToString("N0", CultureInfo.InvariantCulture) + " mana >= " + + threshold.ToString("N0", CultureInfo.InvariantCulture) + + "), looted to drain into an empty mana stone - change in the Items panel, Mana Stone Tapping"; + // Already approved this session — return same answer without re-logging // or re-counting against the quota. if (_pendingManaTapIds.Contains(item.Id)) { actionLabel = ManaTapActionLabel; ruleLabel = $"ManaTap (mana={curMana} ≥ {threshold})"; + builtIn = tapWhy; return true; } @@ -1893,6 +2028,8 @@ public sealed partial class RynthAiPlugin actionLabel = ManaTapActionLabel; ruleLabel = $"ManaTap (mana={curMana} ≥ {threshold})"; + builtIn = tapWhy; + if (preview) return true; ChatLine($"[RynthAi] Mana tap candidate: '{item.Name}' (mana {curMana}, slot {_pendingManaTapIds.Count + 1}) — looting to drain."); _pendingManaTapIds.Add(item.Id); return true; @@ -2090,13 +2227,13 @@ public sealed partial class RynthAiPlugin ClearCorpseTurnMotions(); if (!_navigationEngine.ServoToward(desiredDeg)) { - if (_corpseAutorunActive) { Host.SetAutoRun(false); _corpseAutorunActive = false; } + if (_corpseAutorunActive) { Host.SetAutoRunBy("Loot", false); _corpseAutorunActive = false; } return; } long nowMs = CorpseNowMs; if (!_corpseAutorunActive || nowMs - _lastCorpseApproachHeartbeatAt >= 500) { - Host.SetAutoRun(true); + Host.SetAutoRunBy("Loot", true); _corpseAutorunActive = true; _lastCorpseApproachHeartbeatAt = nowMs; } @@ -2110,13 +2247,13 @@ public sealed partial class RynthAiPlugin // Use smooth motion turns, same as NavigationEngine/CombatManager if (signedError > 0) { - Host.SetMotion(MotionTurnRight, true); - Host.SetMotion(MotionTurnLeft, false); + Host.SetMotionBy("Loot", MotionTurnRight, true); + Host.SetMotionBy("Loot", MotionTurnLeft, false); } else { - Host.SetMotion(MotionTurnLeft, true); - Host.SetMotion(MotionTurnRight, false); + Host.SetMotionBy("Loot", MotionTurnLeft, true); + Host.SetMotionBy("Loot", MotionTurnRight, false); } _corpseApproachTurnsActive = true; return; @@ -2127,7 +2264,7 @@ public sealed partial class RynthAiPlugin long now = CorpseNowMs; if (!_corpseAutorunActive || now - _lastCorpseApproachHeartbeatAt >= 500) { - Host.SetAutoRun(true); + Host.SetAutoRunBy("Loot", true); _corpseAutorunActive = true; _lastCorpseApproachHeartbeatAt = now; } @@ -2138,8 +2275,8 @@ public sealed partial class RynthAiPlugin if (!_corpseApproachTurnsActive) return; _corpseApproachTurnsActive = false; - Host.SetMotion(MotionTurnRight, false); - Host.SetMotion(MotionTurnLeft, false); + Host.SetMotionBy("Loot", MotionTurnRight, false); + Host.SetMotionBy("Loot", MotionTurnLeft, false); } private void StopCorpseMovement() @@ -2149,9 +2286,9 @@ public sealed partial class RynthAiPlugin if (!_corpseAutorunActive) return; - Host.SetAutoRun(false); + Host.SetAutoRunBy("Loot", false); if (Host.HasStopCompletely) - Host.StopCompletely(); + Host.StopCompletelyBy("Loot"); _corpseAutorunActive = false; } @@ -2457,7 +2594,21 @@ public sealed partial class RynthAiPlugin bool openWasSent = wasOpened || _lastOpenAttemptCorpseId == corpseId; int abandons =_corpseAbandonCounts.TryGetValue(corpseId, out int n) ? n + 1 : 1; _corpseAbandonCounts[corpseId] = abandons; - if (wasOpened || abandons >= 3) + // Your own corpse is never written off after one timeout: it gets OwnCorpseMaxAbandons tries. + bool ownCorpse = IsOwnDeathCorpseId(_dashboard?.Settings, corpseId); + if (ownCorpse && abandons < OwnCorpseMaxAbandons) + { + _corpseCooldownUntil[corpseId] = now + NeverOpenedAbandonRetryMs; + LootDiag($"[RynthAi] Own corpse: 0x{(uint)corpseId:X8} timed out (try {abandons} of {OwnCorpseMaxAbandons}); trying again in {NeverOpenedAbandonRetryMs / 1000}s."); + } + else if (ownCorpse) + { + _completedCorpses[corpseId] = now; + _corpseCooldownUntil.Remove(corpseId); + _corpseAbandonCounts.Remove(corpseId); + ChatLine($"[RynthAi] Own corpse: giving up after {abandons} tries; recover what is left on it by hand."); + } + else if (wasOpened || abandons >= 3) { _completedCorpses[corpseId] = now; _corpseCooldownUntil.Remove(corpseId); @@ -2509,7 +2660,7 @@ public sealed partial class RynthAiPlugin if (Host.HasCancelAttack) Host.CancelAttack(); if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat); - if (Host.HasStopCompletely) Host.StopCompletely(); + if (Host.HasStopCompletely) Host.StopCompletelyBy("Loot/Wedge"); if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount(); // The lock is client-side: AC's pending-item-request slot or attacking // flag (see the engine's ClientActionGates). Open both now. diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureWeakness.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureWeakness.cs index c2e97df..bf64950 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureWeakness.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureWeakness.cs @@ -91,6 +91,22 @@ internal static class CreatureWeakness return null; } + /// + /// The creature type the world-database table gives this monster (0 = not in it). Same match + /// as : the wcid's row when its name agrees (or no name is given); no wcid, + /// the first row of that name. Never guessed from name keywords. + /// + public static int TableCreatureType(uint wcid, string? name) + { + EnsureLoaded(); + name ??= ""; + if (wcid == 0 && name.Length > 0 && ByName.TryGetValue(name, out uint byName)) wcid = byName; + if (wcid != 0 && ByWcid.TryGetValue(wcid, out var row) + && (name.Length == 0 || row.Name.Equals(name, StringComparison.OrdinalIgnoreCase))) + return row.Type > 0 ? row.Type : 0; + return 0; + } + /// Damage multiplier for one element from the server table or the type average; false when unknown. public static bool TryGetMultiplier(uint wcid, string? name, int creatureType, string element, out double mult) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs b/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs index 88640a9..92facb2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs @@ -104,7 +104,7 @@ public sealed partial class RynthAiPlugin _doorActionAt = now; _navigationEngine?.Stop(); - if (Host.HasStopCompletely) Host.StopCompletely(); + if (Host.HasStopCompletely) Host.StopCompletelyBy("Door"); _doorPausedNav = true; Host.UseFor(unchecked((uint)doorId), "Door", diff --git a/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs b/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs index 6b89011..22ece09 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs @@ -1,6 +1,7 @@ using System; using RynthCore.Plugin.RynthAi.LegacyUi; using RynthCore.PluginSdk; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi; @@ -87,7 +88,7 @@ internal sealed class Jumper { _turningStartedAt = DateTime.UtcNow; if (_host.HasTurnToHeading) - _host.TurnToHeading(_targetHeading); + _host.TurnToHeadingBy("Jump", _targetHeading); _host.Log($"[Jumper] Start turn->{_targetHeading:F0} letters='{directionLetters}' hold={_msToHoldDown}ms"); } else diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/DungeonMapUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/DungeonMapUi.cs index 850c1ff..088ce82 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/DungeonMapUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/DungeonMapUi.cs @@ -17,6 +17,7 @@ namespace RynthCore.Plugin.RynthAi.LegacyUi; /// CellType: Flat, SlopeUp (avg vertex Z above the layer), SlopeDown (below). /// This was also RynthAi's plugin-drawn Dungeon Map window (with baked D3D9 floor /// textures); that window is the engine's DungeonMapFace now, so nothing here draws. +/// The floor grids are also baked to disk (Maps/DungeonMapBake) for DrakRemote's /map. /// internal sealed class DungeonMapUi { @@ -45,6 +46,31 @@ internal sealed class DungeonMapUi internal int BestLayerIdxFor(float playerZ) => BestLayerIdx(playerZ); + // Last indoor landblock TickBake handed to the bake (0 = none yet). + private uint _bakeCheckLandblock; + + /// + /// Game-thread tick (throttled by the caller): when the player is indoors in a landblock not + /// seen yet, bake its floor plans to disk for the StatusAgent's /map, whether or not a Radar + /// or Dungeon Map panel is open (only those build this cache). One pose read here; the dat + /// read, rasterise and disk work run on a pool thread, once per landblock per session. + /// Also logs what the background bakes reported. + /// + internal void TickBake(RynthCoreHost host) + { + Maps.DungeonMapBake.DrainLog(host.Log); + if (!host.HasGetPlayerPose + || !host.TryGetPlayerPose(out uint cellId, out _, out _, out _, out _, out _, out _, out _)) + return; + uint landblock = cellId >> 16; + bool isIndoor = (cellId & 0xFFFF) >= 0x100 && landblock != 0; + if (!isIndoor || landblock == _bakeCheckLandblock) return; + var los = _raycast?.GeometryLoader?.DungeonLOS; + if (los is null) return; // dats still loading; try again next tick + _bakeCheckLandblock = landblock; + Maps.DungeonMapBake.RequestFromDat(los, landblock); + } + private const float GridCell = 0.5f; private const float FloorNormalThreshold = 0.4f; // |Nz|/|N| — must exceed to be floor-like private const float FlatNormalThreshold = 0.95f; // |Nz|/|N| — must exceed to be flat (not a ramp) @@ -77,115 +103,14 @@ internal sealed class DungeonMapUi var portalPolys = los.GetDungeonMapPolygons(landblock); if (floorPolys.Count == 0 && portalPolys.Count == 0) return; - var zSet = new SortedSet(); - foreach (var p in floorPolys) zSet.Add((float)Math.Round(p.CellZ, 1)); - foreach (var p in portalPolys) zSet.Add((float)Math.Round(p.CellZ, 1)); - _zLayers = new List(zSet); + _zLayers = LayerZs(floorPolys, portalPolys); _outerEdges = new Dictionary>(_zLayers.Count); _fillStrips = new Dictionary>(_zLayers.Count); - const float LayerTol = 1.0f; - foreach (float layerZ in _zLayers) { - var filled = new Dictionary<(int, int), CellType>(); - - foreach (var poly in floorPolys) - { - if (MathF.Abs(poly.CellZ - layerZ) > LayerTol) continue; - var verts = poly.Vertices; - if (verts == null || verts.Length < 3) continue; - - CellType type = ClassifyPoly(verts, layerZ); - if ((byte)type == NotFloor) continue; // physics floor polys are upward-facing; skip any edge cases - - RasterizeXY(verts, filled, type); - } - - // ── Portal gap-closing (width-matched bridges) ─────────────── - // For each pair of portals within 5 units, fill a rectangle - // bridge between them. Width = actual doorway opening derived - // from the portal polygon's larger XY bounding-box dimension. - { - var portals = new List<(float cx, float cy, float halfW)>(); - var pDedup = new HashSet<(int, int)>(); - foreach (var poly in portalPolys) - { - if (!poly.IsPortal) continue; - if (MathF.Abs(poly.CellZ - layerZ) > LayerTol) continue; - var verts = poly.Vertices; - if (verts == null || verts.Length < 3) continue; - float cx = 0, cy = 0; - float xMin = verts[0].X, xMax = verts[0].X; - float yMin = verts[0].Y, yMax = verts[0].Y; - for (int k = 0; k < verts.Length; k++) - { - cx += verts[k].X; cy += verts[k].Y; - if (verts[k].X < xMin) xMin = verts[k].X; - if (verts[k].X > xMax) xMax = verts[k].X; - if (verts[k].Y < yMin) yMin = verts[k].Y; - if (verts[k].Y > yMax) yMax = verts[k].Y; - } - cx /= verts.Length; cy /= verts.Length; - float halfW = MathF.Max(xMax - xMin, yMax - yMin) * 0.5f; - halfW = MathF.Max(halfW, 1.0f); // minimum 1 unit wide - if (pDedup.Add(((int)MathF.Round(cx), (int)MathF.Round(cy)))) - portals.Add((cx, cy, halfW)); - } - - const float ConnectDist = 5f; - - for (int a = 0; a < portals.Count; a++) - for (int b = a + 1; b < portals.Count; b++) - { - float ddx = portals[b].cx - portals[a].cx; - float ddy = portals[b].cy - portals[a].cy; - float distSq = ddx * ddx + ddy * ddy; - if (distSq > ConnectDist * ConnectDist) continue; - - float dist = MathF.Sqrt(distSq); - float hw = MathF.Max(portals[a].halfW, portals[b].halfW); - - // Normalised A→B direction, then perpendicular scaled by half-width - float normDx = dist > 0.001f ? ddx / dist : 1f; - float normDy = dist > 0.001f ? ddy / dist : 0f; - float perpX = -normDy * hw; - float perpY = normDx * hw; - - float pax = portals[a].cx, pay = portals[a].cy; - float pbx = portals[b].cx, pby = portals[b].cy; - - // 4 corners of the bridge quad - float c0x = pax - perpX, c0y = pay - perpY; - float c1x = pax + perpX, c1y = pay + perpY; - float c2x = pbx + perpX, c2y = pby + perpY; - float c3x = pbx - perpX, c3y = pby - perpY; - - float bbMinX = MathF.Min(MathF.Min(c0x, c1x), MathF.Min(c2x, c3x)); - float bbMaxX = MathF.Max(MathF.Max(c0x, c1x), MathF.Max(c2x, c3x)); - float bbMinY = MathF.Min(MathF.Min(c0y, c1y), MathF.Min(c2y, c3y)); - float bbMaxY = MathF.Max(MathF.Max(c0y, c1y), MathF.Max(c2y, c3y)); - - int gcxMin2 = (int)MathF.Floor(bbMinX / GridCell); - int gcxMax2 = (int)MathF.Ceiling(bbMaxX / GridCell); - int gcyMin2 = (int)MathF.Floor(bbMinY / GridCell); - int gcyMax2 = (int)MathF.Ceiling(bbMaxY / GridCell); - - for (int gcy2 = gcyMin2; gcy2 <= gcyMax2; gcy2++) - for (int gcx2 = gcxMin2; gcx2 <= gcxMax2; gcx2++) - { - float testX = (gcx2 + 0.5f) * GridCell; - float testY = (gcy2 + 0.5f) * GridCell; - if (PointInConvexQuad(testX, testY, - c0x, c0y, c1x, c1y, c2x, c2y, c3x, c3y)) - { - var key = (gcx2, gcy2); - if (!filled.ContainsKey(key)) filled[key] = CellType.Flat; - } - } - } - } + var filled = RasterizeLayer(floorPolys, portalPolys, layerZ); if (filled.Count == 0) continue; @@ -266,6 +191,149 @@ internal sealed class DungeonMapUi if (strips.Count > 0) _fillStrips[layerZ] = strips; } + // Disk floor plans for DrakRemote (StatusAgent /map). Once per landblock, off this + // thread; a plan that is already on disk with the same bytes is left alone. + Maps.DungeonMapBake.Request(landblock, _zLayers, _floorCells); + } + + /// The floor heights (cell Z rounded to 0.1) of a landblock's polygons, ascending. + /// A layer's index in this list is the layer number in the baked map file names. + internal static List LayerZs(List floorPolys, List portalPolys) + { + var zSet = new SortedSet(); + foreach (var p in floorPolys) zSet.Add((float)Math.Round(p.CellZ, 1)); + foreach (var p in portalPolys) zSet.Add((float)Math.Round(p.CellZ, 1)); + return new List(zSet); + } + + /// + /// The typed floor-cell grid of one layer (GridCell squares): physics floor polygons + /// rasterised, plus width-matched bridges between nearby portals. Pure; no state. + /// + internal static Dictionary<(int, int), CellType> RasterizeLayer( + List floorPolys, List portalPolys, float layerZ) + { + const float LayerTol = 1.0f; + var filled = new Dictionary<(int, int), CellType>(); + + foreach (var poly in floorPolys) + { + if (MathF.Abs(poly.CellZ - layerZ) > LayerTol) continue; + var verts = poly.Vertices; + if (verts == null || verts.Length < 3) continue; + + CellType type = ClassifyPoly(verts, layerZ); + if ((byte)type == NotFloor) continue; // physics floor polys are upward-facing; skip any edge cases + + RasterizeXY(verts, filled, type); + } + + // ── Portal gap-closing (width-matched bridges) ─────────────── + // For each pair of portals within 5 units, fill a rectangle + // bridge between them. Width = actual doorway opening derived + // from the portal polygon's larger XY bounding-box dimension. + { + var portals = new List<(float cx, float cy, float halfW)>(); + var pDedup = new HashSet<(int, int)>(); + foreach (var poly in portalPolys) + { + if (!poly.IsPortal) continue; + if (MathF.Abs(poly.CellZ - layerZ) > LayerTol) continue; + var verts = poly.Vertices; + if (verts == null || verts.Length < 3) continue; + float cx = 0, cy = 0; + float xMin = verts[0].X, xMax = verts[0].X; + float yMin = verts[0].Y, yMax = verts[0].Y; + for (int k = 0; k < verts.Length; k++) + { + cx += verts[k].X; cy += verts[k].Y; + if (verts[k].X < xMin) xMin = verts[k].X; + if (verts[k].X > xMax) xMax = verts[k].X; + if (verts[k].Y < yMin) yMin = verts[k].Y; + if (verts[k].Y > yMax) yMax = verts[k].Y; + } + cx /= verts.Length; cy /= verts.Length; + float halfW = MathF.Max(xMax - xMin, yMax - yMin) * 0.5f; + halfW = MathF.Max(halfW, 1.0f); // minimum 1 unit wide + if (pDedup.Add(((int)MathF.Round(cx), (int)MathF.Round(cy)))) + portals.Add((cx, cy, halfW)); + } + + const float ConnectDist = 5f; + + for (int a = 0; a < portals.Count; a++) + for (int b = a + 1; b < portals.Count; b++) + { + float ddx = portals[b].cx - portals[a].cx; + float ddy = portals[b].cy - portals[a].cy; + float distSq = ddx * ddx + ddy * ddy; + if (distSq > ConnectDist * ConnectDist) continue; + + float dist = MathF.Sqrt(distSq); + float hw = MathF.Max(portals[a].halfW, portals[b].halfW); + + // Normalised A→B direction, then perpendicular scaled by half-width + float normDx = dist > 0.001f ? ddx / dist : 1f; + float normDy = dist > 0.001f ? ddy / dist : 0f; + float perpX = -normDy * hw; + float perpY = normDx * hw; + + float pax = portals[a].cx, pay = portals[a].cy; + float pbx = portals[b].cx, pby = portals[b].cy; + + // 4 corners of the bridge quad + float c0x = pax - perpX, c0y = pay - perpY; + float c1x = pax + perpX, c1y = pay + perpY; + float c2x = pbx + perpX, c2y = pby + perpY; + float c3x = pbx - perpX, c3y = pby - perpY; + + float bbMinX = MathF.Min(MathF.Min(c0x, c1x), MathF.Min(c2x, c3x)); + float bbMaxX = MathF.Max(MathF.Max(c0x, c1x), MathF.Max(c2x, c3x)); + float bbMinY = MathF.Min(MathF.Min(c0y, c1y), MathF.Min(c2y, c3y)); + float bbMaxY = MathF.Max(MathF.Max(c0y, c1y), MathF.Max(c2y, c3y)); + + int gcxMin2 = (int)MathF.Floor(bbMinX / GridCell); + int gcxMax2 = (int)MathF.Ceiling(bbMaxX / GridCell); + int gcyMin2 = (int)MathF.Floor(bbMinY / GridCell); + int gcyMax2 = (int)MathF.Ceiling(bbMaxY / GridCell); + + for (int gcy2 = gcyMin2; gcy2 <= gcyMax2; gcy2++) + for (int gcx2 = gcxMin2; gcx2 <= gcxMax2; gcx2++) + { + float testX = (gcx2 + 0.5f) * GridCell; + float testY = (gcy2 + 0.5f) * GridCell; + if (PointInConvexQuad(testX, testY, + c0x, c0y, c1x, c1y, c2x, c2y, c3x, c3y)) + { + var key = (gcx2, gcy2); + if (!filled.ContainsKey(key)) filled[key] = CellType.Flat; + } + } + } + } + + return filled; + } + + /// + /// The layer heights and per-layer floor grids of a landblock, the same ones RefreshMap + /// builds, without touching this instance's cache. Used by the background map bake. Layers + /// with no cells are left out of the dictionary (but keep their index in the list). + /// + internal static (List ZLayers, Dictionary> Cells) BuildFloorCells( + DungeonLOS los, uint landblock) + { + var floorPolys = los.GetDungeonMapFloorPolygons(landblock); + var portalPolys = los.GetDungeonMapPolygons(landblock); + var cells = new Dictionary>(); + if (floorPolys.Count == 0 && portalPolys.Count == 0) return (new List(), cells); + var zLayers = LayerZs(floorPolys, portalPolys); + foreach (float layerZ in zLayers) + { + var filled = RasterizeLayer(floorPolys, portalPolys, layerZ); + if (filled.Count > 0) cells[layerZ] = filled; + } + return (zLayers, cells); } // Merge collinear/adjacent axis-aligned edge segments into the fewest possible lines. diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index 547fe5f..6b363d0 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -711,6 +711,13 @@ internal sealed class LegacyAdvancedSettingsUi "alone. Default 1200 (20 minutes). At or below 'Rebuff With', only the\n" + "expiring buff is recast."); + ImGui.Checkbox("Cast buffs even when an item gives them", ref _settings.CastBuffsOverItemBuffs); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip( + "Cast your own buff even when worn gear already gives that buff.\n" + + "For servers with buff augments, where your own cast is stronger or\n" + + "lasts longer. On by default: on retail it costs a few extra casts."); + ImGui.Spacing(); ImGui.Separator(); ImGui.Text("Buff Difficulty (Min Buffed Skill)"); @@ -757,6 +764,12 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Text("Corpse Ownership"); ImGui.SetNextItemWidth(180); ImGui.Combo("Loot From", ref _settings.LootOwnership, LootOwnershipModes, LootOwnershipModes.Length); + ImGui.Checkbox("Recover My Corpse", ref _settings.LootOwnCorpse); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("When your own corpse (\"Corpse of \") is within loot range, open it and take\nevery item on it, whatever the loot profile and Loot From say."); + ImGui.Checkbox("Travel Back To My Corpse", ref _settings.TravelToOwnCorpse); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("After a death, travel back to where you died with RynthNav (outdoors only),\nfighting on the way, recover the corpse, then carry on. Needs the macro running."); ImGui.Spacing(); ImGui.Text("Inventory Management"); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index a0fd10c..38dddac 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -8,6 +8,7 @@ using System.Text.Json; using RynthCore.PluginSdk; using RynthCore.Plugin.RynthAi; using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi.LegacyUi; @@ -294,6 +295,10 @@ internal sealed class LegacyDashboardRenderer _dungeonMapUi.SetRaycast(raycast); } + /// Bake the floor plans of a dungeon just entered, with no map panel open + /// (DrakRemote's /map). Cheap: one pose read; the work runs on a pool thread. + public void TickDungeonMapBake() => _dungeonMapUi?.TickBake(_host); // null in tests' bare dashboards + public void PushChatLine(string? text, int chatType) => _rynthChatUi.Push(text, chatType); /// Set the handler invoked when the user submits a line from the @@ -1028,6 +1033,7 @@ internal sealed class LegacyDashboardRenderer RebuffWhenIdle = s.RebuffWhenIdle, RebuffSecondsRemaining = s.RebuffSecondsRemaining, RebuffTopOffSecondsRemaining = s.RebuffTopOffSecondsRemaining, + CastBuffsOverItemBuffs = s.CastBuffsOverItemBuffs, BuffMinSkillLevelTier1 = s.BuffMinSkillLevelTier1, BuffMinSkillLevelTier2 = s.BuffMinSkillLevelTier2, BuffMinSkillLevelTier3 = s.BuffMinSkillLevelTier3, @@ -1048,6 +1054,8 @@ internal sealed class LegacyDashboardRenderer LootJumpEnabled = s.LootJumpEnabled, LootJumpHeight = s.LootJumpHeight, LootOwnership = s.LootOwnership, + LootOwnCorpse = s.LootOwnCorpse, + TravelToOwnCorpse = s.TravelToOwnCorpse, EnableAutostack = s.EnableAutostack, ReadUnknownScrolls = s.ReadUnknownScrolls, EnableCombineSalvage = s.EnableCombineSalvage, @@ -1228,6 +1236,7 @@ internal sealed class LegacyDashboardRenderer s.RebuffWhenIdle = p.RebuffWhenIdle; s.RebuffSecondsRemaining = p.RebuffSecondsRemaining; if (p.RebuffTopOffSecondsRemaining > 0) s.RebuffTopOffSecondsRemaining = p.RebuffTopOffSecondsRemaining; + if (p.CastBuffsOverItemBuffs is bool castOverItems) s.CastBuffsOverItemBuffs = castOverItems; // absent = unchanged s.BuffMinSkillLevelTier1 = p.BuffMinSkillLevelTier1; s.BuffMinSkillLevelTier2 = p.BuffMinSkillLevelTier2; s.BuffMinSkillLevelTier3 = p.BuffMinSkillLevelTier3; @@ -1245,6 +1254,8 @@ internal sealed class LegacyDashboardRenderer s.LootJumpEnabled = p.LootJumpEnabled; s.LootJumpHeight = p.LootJumpHeight; s.LootOwnership = p.LootOwnership; + if (p.LootOwnCorpse is bool lootOwn) s.LootOwnCorpse = lootOwn; // absent = unchanged + if (p.TravelToOwnCorpse is bool travelOwn) s.TravelToOwnCorpse = travelOwn; // absent = unchanged s.EnableAutostack = p.EnableAutostack; s.ReadUnknownScrolls = p.ReadUnknownScrolls; s.EnableCombineSalvage = p.EnableCombineSalvage; @@ -1644,11 +1655,14 @@ internal sealed class LegacyDashboardRenderer dst.OpenDoorRange = tmp.OpenDoorRange; dst.AutoUnlockDoors = tmp.AutoUnlockDoors; dst.LootOwnership = tmp.LootOwnership; + dst.LootOwnCorpse = tmp.LootOwnCorpse; + dst.TravelToOwnCorpse = tmp.TravelToOwnCorpse; dst.LootOnlyRareCorpses = tmp.LootOnlyRareCorpses; dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle; dst.RebuffWhenIdle = tmp.RebuffWhenIdle; dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining; dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining; + dst.CastBuffsOverItemBuffs = tmp.CastBuffsOverItemBuffs; dst.BlacklistAttempts = tmp.BlacklistAttempts; dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec; // 0 is never meant (every UI floors it at 250+) and is what the Settings-panel bug @@ -2316,8 +2330,8 @@ internal sealed class LegacyDashboardRenderer break; case "addWaypoint": - _host.SetMotion(0x6500000D, false); // stop TurnRight - _host.SetMotion(0x6500000E, false); // stop TurnLeft + _host.SetMotionBy("UI", 0x6500000D, false); // stop TurnRight + _host.SetMotionBy("UI", 0x6500000E, false); // stop TurnLeft if (_host.HasGetPlayerPose && _host.TryGetPlayerPose(out _, out float wx, out float wy, out float wz, out _, out _, out _, out _) && NavCoordinateHelper.TryGetNavCoords(_host, out double wNS, out double wEW)) @@ -2441,7 +2455,11 @@ internal sealed class LegacyDashboardRenderer sb.Append('{'); AppendBool(sb, "macroRunning", _settings.IsMacroRunning); sb.Append(','); AppendString(sb, "currentState", _settings.CurrentState ?? string.Empty); sb.Append(','); - AppendString(sb, "botAction", _settings.BotAction ?? "Default"); sb.Append(','); + // "botAction" is what the displays show (the dashboard's activity line, and the phone through + // RynthRemote's status file): the control string, except that the Buffing slot says what it + // is doing (Healing, Restoring mana, ...). The control string itself is "botActionControl". + AppendString(sb, "botAction", ActivityArbiter.DisplayLabel(_settings.BotAction, _settings.BuffingLabel)); sb.Append(','); + AppendString(sb, "botActionControl", _settings.BotAction ?? "Default"); sb.Append(','); AppendString(sb, "selectedProfile", _settings.SelectedProfile ?? "Default"); sb.Append(','); // Copy the four profile lists under the lock so we never enumerate one // while a Refresh*Files mutator Clear()s it on the pump thread — that diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs index f78a732..579659a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs @@ -3,6 +3,7 @@ using System.IO; using System.Numerics; using ImGuiNET; using RynthCore.PluginSdk; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi.LegacyUi; @@ -97,8 +98,8 @@ internal sealed class LegacyNavigationUi if (ImGui.Button("Add Waypoint", new Vector2(100, 25))) { // Stop any active turn motion so the character doesn't keep spinning - _host.SetMotion(0x6500000D, false); // TurnRight - _host.SetMotion(0x6500000E, false); // TurnLeft + _host.SetMotionBy("UI", 0x6500000D, false); // TurnRight + _host.SetMotionBy("UI", 0x6500000E, false); // TurnLeft if (_host.HasGetPlayerPose && _host.TryGetPlayerPose(out _, out float x, out float y, out float z, out _, out _, out _, out _)) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index 218aebf..46da731 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -24,6 +24,10 @@ public sealed class LegacyUiSettings /// Bot action state — what the bot is doing right now (Default, Combat, Looting, Navigating, Buffing). /// Separate from meta state so operational cycling doesn't corrupt meta rule matching. [JsonIgnore] public string BotAction = "Default"; + /// Display only: what the "Buffing" slot is doing (Healing, Restoring mana, Restoring + /// stamina, Buffing). Written by RynthAiPlugin every tick; never read by control flow. + /// Displays use ActivityArbiter.DisplayLabel, never this field alone. + [JsonIgnore] public string BuffingLabel = "Buffing"; [JsonIgnore] public bool IsRecordingNav; public bool EnableBuffing = true; @@ -180,6 +184,18 @@ public sealed class LegacyUiSettings public float OpenDoorRange = 5.0f; public bool AutoUnlockDoors; public int LootOwnership; + /// + /// Recover your own death corpse ("Corpse of <you>", identified by its "Killed by" line): + /// when it is within loot range the bot opens it and takes every item on it, whatever the + /// loot profile, Loot From, value or salvage rules say. On by default (owner, 2026-10-05); + /// a profile saved before this setting loads it as on. + /// + public bool LootOwnCorpse = true; + /// + /// After a death and respawn, travel back to where you died (RynthNav, outdoors only), fight + /// on the way as usual, recover the corpse, then carry on. Off by default. + /// + public bool TravelToOwnCorpse; public bool LootOnlyRareCorpses; public bool PeaceModeWhenIdle = true; public bool RebuffWhenIdle; @@ -197,6 +213,15 @@ public sealed class LegacyUiSettings /// below RebuffSecondsRemaining only the expiring buff is recast. /// public int RebuffTopOffSecondsRemaining = 1200; + /// + /// Cast our own buff even when an item already gives that buff (a permanent, item-granted + /// enchantment at the same tier or higher). For servers with buff augments, where a player's + /// own cast is stronger or lasts longer than the item's. On by default: on retail the cost + /// is a few extra casts, while missing the buff is worse. A profile saved before this + /// setting existed loads it as on. Off = an item-granted buff at the tier we'd cast counts + /// as on for good (the behaviour before 2026-10-05). + /// + public bool CastBuffsOverItemBuffs = true; public bool StartMacroOnLogin; public bool PatrolOnLogin; /// @@ -828,6 +853,9 @@ public sealed class SettingsBridgePayload public bool RebuffWhenIdle { get; set; } public int RebuffSecondsRemaining { get; set; } public int RebuffTopOffSecondsRemaining { get; set; } = 1200; // absent in older files + // Nullable: an engine that predates the setting doesn't send it, and a save from its + // Settings face must leave the setting alone rather than force it either way. + public bool? CastBuffsOverItemBuffs { get; set; } public int BuffMinSkillLevelTier1 { get; set; } public int BuffMinSkillLevelTier2 { get; set; } public int BuffMinSkillLevelTier3 { get; set; } @@ -850,6 +878,10 @@ public sealed class SettingsBridgePayload public bool LootJumpEnabled { get; set; } public int LootJumpHeight { get; set; } public int LootOwnership { get; set; } + // Nullable, as CastBuffsOverItemBuffs: an engine that predates them doesn't send them, + // and its save must leave them alone. + public bool? LootOwnCorpse { get; set; } + public bool? TravelToOwnCorpse { get; set; } public bool EnableAutostack { get; set; } public bool ReadUnknownScrolls { get; set; } = true; // absent from an older engine: keep the default public bool EnableCombineSalvage { get; set; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs index bc8ee54..8a17650 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs @@ -187,6 +187,7 @@ internal sealed class LootEditorBridge d.ItemName = facts.Name; d.ClassName = LootItemRules.ClassName(facts.ObjectClass); d.Stackable = facts.Stackable; + d.BuiltInReason = BuiltInSentence(Items.BuiltInKeep(id)); string inUse = InUse; string target = req.ToOpenProfile && _session.IsOpen ? _session.Path : inUse; @@ -246,6 +247,7 @@ internal sealed class LootEditorBridge } else d.OrderNote = $"Goes in at the end ({at + 1} of {count + 1}): no rule takes this item now, so at the end it only gets items no other rule wants."; + AppendBuiltIn(d); if (s.IsDirty) return Refuse(d, $"The Loot Editor has unsaved changes in {d.TargetFile}. Save or discard them first."); d.Ok = true; @@ -261,9 +263,30 @@ internal sealed class LootEditorBridge { d.Ok = false; d.Error = error; + AppendBuiltIn(d); return d; } + /// + /// The popup's sentence for one of RynthAi's built-in keeps. "No rule matches" alone + /// misled: a wand Mana Tap had looted read as looted for no reason (2026-10-05). + /// + internal static string BuiltInSentence(LootBuiltInKeep? keep) + { + if (keep == null || keep.Reason.Length == 0) return string.Empty; + return keep.BeforeProfile + ? $"RynthAi takes it before any loot profile rule: {keep.Reason}." + : $"No rule in the loot profile in use takes it, but RynthAi keeps it anyway: {keep.Reason}."; + } + + // OrderNote is what every engine's popup (and /ra loot add) shows, so the reason rides on it; + // BuiltInReason carries it on its own for a face that wants it separately. + private static void AppendBuiltIn(LootEditItemDraft d) + { + if (d.BuiltInReason.Length == 0 || d.OrderNote.EndsWith(d.BuiltInReason, StringComparison.Ordinal)) return; + d.OrderNote = d.OrderNote.Length == 0 ? d.BuiltInReason : d.OrderNote + " " + d.BuiltInReason; + } + /// The editor's session when it has open, else a second one (fresh from disk). private LootEditSession SessionFor(string target) { @@ -321,4 +344,16 @@ internal sealed class LootItemHooks public Func FirstMatchNative { get; set; } = (_, _) => -1; /// A rule was added and saved: say so and reload the profile. Outside the bridge's lock. public Action Added { get; set; } = _ => { }; + /// + /// One of RynthAi's built-in keeps that takes the item now with the loot profile in use + /// (the looter's own classification, run as a preview), or null. + /// + public Func BuiltInKeep { get; set; } = _ => null; } + +/// +/// A built-in keep: says what and where to change it (ASCII); +/// when it is checked ahead of the loot profile's rules +/// (Learn unknown spells, mana stones) rather than only when no rule matches (Mana Tap). +/// +internal sealed record LootBuiltInKeep(string Reason, bool BeforeProfile); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/ScrollLearner.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/ScrollLearner.cs index 4515c77..d2a4ad8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/ScrollLearner.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/ScrollLearner.cs @@ -279,28 +279,38 @@ internal sealed class ScrollLearner /// setting on, a scroll on a corpse whose spell the character doesn't know and can learn. /// One copy per spell. /// - public bool ShouldLootFromCorpse(WorldObject item, out string ruleLabel) + public bool ShouldLootFromCorpse(WorldObject item, out string ruleLabel) => + ShouldLootFromCorpse(item, out ruleLabel, out _, preview: false); + + // preview: the same answer with nothing recorded or logged (the loot popup asking why). + // why: the spell and why it is taken, in a few words. + public bool ShouldLootFromCorpse(WorldObject item, out string ruleLabel, out string why, bool preview) { ruleLabel = string.Empty; + why = string.Empty; if (!_settings.ReadUnknownScrolls || !LooksLikeScroll(item)) return false; ScrollJudgement j = Judge(item); if (j.Verdict == ScrollVerdict.NoSpell) return false; // a book, a note: not ours to judge if (!j.Learnable) { - LogItem(item.Id, $"[Learn] leaving '{item.Name}' ({j.SpellName}: {j.Why})"); + if (!preview) LogItem(item.Id, $"[Learn] leaving '{item.Name}' ({j.SpellName}: {j.Why})"); return false; } long now = NowMs(); if (OtherCopyTaken(j.SpellId, item.Id, now)) { - LogItem(item.Id, $"[Learn] leaving '{item.Name}' ({j.SpellName}: another copy is already on its way)"); + if (!preview) LogItem(item.Id, $"[Learn] leaving '{item.Name}' ({j.SpellName}: another copy is already on its way)"); return false; } - _approved[j.SpellId] = (item.Id, now); - LogItem(item.Id, $"[Learn] looting '{item.Name}' ({j.SpellName}: {j.Why})"); + if (!preview) + { + _approved[j.SpellId] = (item.Id, now); + LogItem(item.Id, $"[Learn] looting '{item.Name}' ({j.SpellName}: {j.Why})"); + } ruleLabel = RuleLabel; + why = $"{j.SpellName}: {j.Why}"; return true; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs index a4bfed4..aad7156 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs @@ -303,7 +303,7 @@ public sealed partial class RynthAiPlugin if (parts.Length < 3 || !float.TryParse(parts[2], out float degrees)) return false; if (!Host.HasTurnToHeading) { ChatLine("[RynthAi] TurnToHeading not available."); return true; } - Host.TurnToHeading(degrees); + Host.TurnToHeadingBy("Command", degrees); return true; } @@ -470,7 +470,12 @@ public sealed partial class RynthAiPlugin string itemName = argStr[..toIdx].Trim(); string targetName = argStr[(toIdx + 4)..].Trim(); - var item = FindObject(itemName, inv: true, land: false, partial: partial); + // /mt give hands over the FIRST carried match (/ub give hands over all of them). + // Never worn or wielded gear: FindObject's inventory walk includes it. + var candidates = GiveCandidates(n => partial + ? n.IndexOf(itemName, StringComparison.OrdinalIgnoreCase) >= 0 + : string.Equals(n, itemName, StringComparison.OrdinalIgnoreCase)); + var item = candidates.Count > 0 ? candidates[0] : null; if (item == null) { ChatLine($"[RynthAi] Item not found: '{itemName}'"); return true; } var target = FindObject(targetName, inv: false, land: true, partial: true); diff --git a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs index d32a253..578070d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs @@ -249,6 +249,9 @@ internal sealed class ManaStoneManager if (itemId != 0) _lootedForTap[itemId] = NowMs; } + /// The looter picked this item up as "ManaTap" this session (it is waiting to be drained). + public bool WasLootedForTap(int itemId) => _lootedForTap.ContainsKey(itemId); + /// /// Drops entries whose item has left the pack: drained (destroyed), sold, given /// away, salvaged, dropped, or never arrived. Also drops items the player has @@ -685,7 +688,7 @@ internal sealed class ManaStoneManager /// is unreliable for unappraised items, so we fall back to the name, matching /// CombatManager/BuffManager.IsWandObject. /// - private static bool IsWandLike(WorldObject item) + internal static bool IsWandLike(WorldObject item) => item.ObjectClass == AcObjectClass.WandStaffOrb || IsWandName(item.Name); private static bool IsWandName(string name) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Maps/DungeonMapBake.cs b/Plugins/RynthCore.Plugin.RynthAi/Maps/DungeonMapBake.cs new file mode 100644 index 0000000..627e03f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Maps/DungeonMapBake.cs @@ -0,0 +1,279 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Raycasting; + +namespace RynthCore.Plugin.RynthAi.Maps; + +/// +/// Writes each dungeon floor as a finished top-down raster to +/// C:\Games\RynthSuite\RynthAi\Maps\{landblock:X8}_{layer}.bin, which the RynthCore StatusAgent +/// serves at /map (re-encoded to PNG) for DrakRemote's dungeon map. +/// +/// File format (must match the StatusAgent's MapService and the 81 plans baked before +/// 2026-09-28 by the old DungeonMapTexture): 20-byte header [uint32 Magic "XTMR" 0x524D5458, +/// int32 xMin, int32 yMin, int32 w, int32 h], then w*h little-endian ARGB uint32 pixels +/// (A<<24|R<<16|G<<8|B), 0.5 world units a pixel, row 0 = northernmost, 0 = empty. +/// xMin/yMin are grid-cell coordinates (world units * 2). The landblock in the file name is the +/// short form (cellId >> 16, e.g. 00006346_1.bin) and the layer is the index into the +/// landblock's ascending floor heights (DungeonMapUi.LayerZs), empty layers included. +/// +/// This is the disk half of the old DungeonMapTexture only: no D3D9 textures. Each landblock +/// is baked at most once per session, on a pool thread, and a file that already holds the +/// same bytes is left alone (no mtime churn on the plans already there). Writes go to a temp +/// file that is then renamed over the target, so the agent never reads a half-written plan. +/// +internal static class DungeonMapBake +{ + internal const uint Magic = 0x524D5458u; // "XTMR" - same constant as the StatusAgent's MapService + private const int MaxDim = 8192; // the agent refuses bigger rasters + + /// Where plans go. A test points this at its own folder. + internal static string CacheDir { get; set; } = @"C:\Games\RynthSuite\RynthAi\Maps"; + + // Pixel colours, as the old DungeonMapTexture (and DungeonMapUi's former ImGui colours). + private static uint Argb(float r, float g, float b, float a) => + ((uint)(a * 255f) << 24) | ((uint)(r * 255f) << 16) | ((uint)(g * 255f) << 8) | (uint)(b * 255f); + + private static readonly uint FillFlat = Argb(0.18f, 0.55f, 0.22f, 0.40f); + private static readonly uint FillSlopeUp = Argb(0.55f, 0.12f, 0.08f, 0.40f); + private static readonly uint FillSlopeDown = Argb(0.10f, 0.50f, 0.15f, 0.40f); + private static readonly uint EdgeFlat = Argb(0.55f, 0.80f, 1.00f, 1.00f); + private static readonly uint EdgeSlopeUp = Argb(1.00f, 0.35f, 0.25f, 1.00f); + private static readonly uint EdgeSlopeDown = Argb(0.25f, 1.00f, 0.35f, 1.00f); + + internal enum SaveResult { Written, Unchanged, Failed } + + // Landblocks already baked (or being baked) this session. + private static readonly ConcurrentDictionary _requested = new(); + // Messages from the pool thread, logged by the game-thread tick (DrainLog). + private static readonly ConcurrentQueue _log = new(); + + /// Normalise to the short landblock id the file names use (0x63460000 -> 0x6346). + internal static uint ShortLandblock(uint landblock) => + landblock > 0xFFFFu ? landblock >> 16 : landblock; + + internal static bool WasRequested(uint landblock) => _requested.ContainsKey(ShortLandblock(landblock)); + + /// Messages queued by background bakes since the last call (game thread logs them). + internal static void DrainLog(Action log) + { + while (_log.TryDequeue(out string? m)) log(m); + } + + /// + /// Bake already-built floor grids (DungeonMapUi.RefreshMap) once per landblock. Returns at + /// once; the rasterise and disk work run on a pool thread. The dictionaries must not be + /// changed afterwards (RefreshMap builds new ones each time). + /// + internal static void Request(uint landblock, List? zLayers, + Dictionary>? floorCells) + { + if (zLayers is null || floorCells is null || floorCells.Count == 0) return; + uint lb = ShortLandblock(landblock); + if (lb == 0 || !_requested.TryAdd(lb, 0)) return; + Task.Run(() => BakeLogged(lb, zLayers, floorCells)); + } + + /// + /// Build the floor grids from the dat and bake them, once per landblock, on a pool thread. + /// For a landblock change indoors with no Radar or Dungeon Map panel open. + /// + internal static void RequestFromDat(DungeonLOS los, uint landblock) + { + uint lb = ShortLandblock(landblock); + if (lb == 0 || !_requested.TryAdd(lb, 0)) return; + Task.Run(() => + { + try + { + var (zLayers, cells) = DungeonMapUi.BuildFloorCells(los, lb); + if (cells.Count == 0) return; // no floor geometry (not a dungeon, or no dat data) + BakeLogged(lb, zLayers, cells); + } + catch (Exception ex) + { + _requested.TryRemove(lb, out _); + _log.Enqueue($"[RynthAi] map bake 0x{lb:X4}: {ex.GetType().Name}: {ex.Message}"); + } + }); + } + + private static void BakeLogged(uint lb, List zLayers, + Dictionary> floorCells) + { + try + { + var (written, unchanged, failed) = BakeLayers(CacheDir, lb, zLayers, floorCells); + // A layer that could not be written (file held open, disk full): let the next + // RefreshMap or re-entry try again instead of skipping it for the session. + if (failed > 0) _requested.TryRemove(lb, out _); + if (written > 0 || failed > 0) + _log.Enqueue($"[RynthAi] map bake 0x{lb:X4}: {written} written, {unchanged} unchanged, {failed} failed ({CacheDir})"); + } + catch (Exception ex) + { + _requested.TryRemove(lb, out _); + _log.Enqueue($"[RynthAi] map bake 0x{lb:X4}: {ex.GetType().Name}: {ex.Message}"); + } + } + + /// Bake every non-empty layer of a landblock into . Synchronous. + internal static (int Written, int Unchanged, int Failed) BakeLayers(string dir, uint landblock, List zLayers, + Dictionary> floorCells) + { + uint lb = ShortLandblock(landblock); + int written = 0, unchanged = 0, failed = 0; + foreach (var (layerZ, cells) in floorCells) + { + int idx = zLayers.IndexOf(layerZ); + if (idx < 0) continue; + byte[]? bytes = BuildFile(cells); + if (bytes is null) continue; + switch (SaveToDisk(dir, lb, idx, bytes)) + { + case SaveResult.Written: written++; break; + case SaveResult.Unchanged: unchanged++; break; + default: failed++; break; + } + } + return (written, unchanged, failed); + } + + internal static string FileName(uint landblock, int layerIdx) => $"{ShortLandblock(landblock):X8}_{layerIdx}.bin"; + + /// The whole .bin (header + pixels) for one layer's cells, or null if empty / too big. + internal static byte[]? BuildFile(Dictionary<(int gx, int gy), DungeonMapUi.CellType> cells) + { + if (cells.Count == 0) return null; + int xMin = int.MaxValue, xMax = int.MinValue; + int yMin = int.MaxValue, yMax = int.MinValue; + foreach (var (gx, gy) in cells.Keys) + { + if (gx < xMin) xMin = gx; if (gx > xMax) xMax = gx; + if (gy < yMin) yMin = gy; if (gy > yMax) yMax = gy; + } + int w = xMax - xMin + 1, h = yMax - yMin + 1; + if (w <= 0 || h <= 0 || w > MaxDim || h > MaxDim) return null; + + uint[] pixels = Rasterise(cells, xMin, yMax, w, h); + var bytes = new byte[20 + pixels.Length * 4]; + var span = bytes.AsSpan(); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(span, Magic); + System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(span.Slice(4), xMin); + System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(span.Slice(8), yMin); + System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(span.Slice(12), w); + System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(span.Slice(16), h); + for (int i = 0; i < pixels.Length; i++) + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(20 + i * 4), pixels[i]); + return bytes; + } + + /// + /// One layer's cells as ARGB pixels: cells bordering empty space get the bright edge colour, + /// the rest the translucent fill, by cell type; empty = 0. Row 0 = northernmost (highest gy). + /// Unchanged from the old DungeonMapTexture.Rasterise. + /// + internal static uint[] Rasterise(Dictionary<(int gx, int gy), DungeonMapUi.CellType> cells, + int xMin, int yMax, int w, int h) + { + var pixels = new uint[w * h]; + foreach (var ((gx, gy), ctype) in cells) + { + bool isEdge = !cells.ContainsKey((gx + 1, gy)) + || !cells.ContainsKey((gx - 1, gy)) + || !cells.ContainsKey((gx, gy + 1)) + || !cells.ContainsKey((gx, gy - 1)); + uint col = isEdge + ? ctype switch + { + DungeonMapUi.CellType.SlopeUp => EdgeSlopeUp, + DungeonMapUi.CellType.SlopeDown => EdgeSlopeDown, + _ => EdgeFlat, + } + : ctype switch + { + DungeonMapUi.CellType.SlopeUp => FillSlopeUp, + DungeonMapUi.CellType.SlopeDown => FillSlopeDown, + _ => FillFlat, + }; + pixels[(yMax - gy) * w + (gx - xMin)] = col; + } + return pixels; + } + + /// + /// Write one plan unless the file already holds exactly these bytes. Temp file + rename, so a + /// reader sees the old plan or the new one, never a partial one. Never throws. + /// + internal static SaveResult SaveToDisk(string dir, uint landblock, int layerIdx, byte[] bytes) + { + string path = Path.Combine(dir, FileName(landblock, layerIdx)); + string? tmp = null; + try + { + if (SameContent(path, bytes)) return SaveResult.Unchanged; + + Directory.CreateDirectory(dir); + // Unique per process and call: two clients in the same dungeon can bake at once. + string tmpPath = path + "." + Environment.ProcessId.ToString("X") + "." + Guid.NewGuid().ToString("N").Substring(0, 8) + ".tmp"; + tmp = tmpPath; + using (var fs = new FileStream(tmpPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + fs.Write(bytes, 0, bytes.Length); + + // The agent may hold the target open for a moment (FileShare.ReadWrite, not Delete), + // which makes the replace fail; try a few times. + for (int attempt = 0; ; attempt++) + { + try + { + File.Move(tmpPath, path, overwrite: true); + tmp = null; + return SaveResult.Written; + } + catch (IOException) when (attempt < 4) + { + if (SameContent(path, bytes)) return SaveResult.Unchanged; // another client won + Thread.Sleep(100); + } + catch (UnauthorizedAccessException) when (attempt < 4) + { + Thread.Sleep(100); + } + } + } + catch + { + return SaveResult.Failed; + } + finally + { + if (tmp != null) { try { File.Delete(tmp); } catch { } } + } + } + + private static bool SameContent(string path, byte[] bytes) + { + try + { + var fi = new FileInfo(path); + if (!fi.Exists || fi.Length != bytes.Length) return false; + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + var buf = new byte[64 * 1024]; + int off = 0; + while (off < bytes.Length) + { + int got = fs.Read(buf, 0, Math.Min(buf.Length, bytes.Length - off)); + if (got <= 0) return false; + if (!buf.AsSpan(0, got).SequenceEqual(bytes.AsSpan(off, got))) return false; + off += got; + } + return true; + } + catch { return false; } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index 658b660..2d70da8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -2543,7 +2543,7 @@ internal sealed class ExpressionEngine if (!_castCombatTornDown && (mode == CombatMode.Melee || mode == CombatMode.Missile)) { if (_host.HasCancelAttack) _host.CancelAttack(); - if (_host.HasStopCompletely) _host.StopCompletely(); + if (_host.HasStopCompletely) _host.StopCompletelyBy("Meta"); _castCombatTornDown = true; _host.Log($"[MetaCast] CancelAttack+StopCompletely before wand equip (mode was {mode})"); } @@ -2882,7 +2882,7 @@ internal sealed class ExpressionEngine if (!MotionValues.TryGetValue(motionArg, out uint motionVal)) return "0"; bool on = ToDouble(stateArg) != 0; _wantedMotion[motionArg] = on; - return _host.SetMotion(motionVal, on) ? "1" : "0"; + return _host.SetMotionBy("Meta", motionVal, on) ? "1" : "0"; } private string EvalGetMotion(string motionArg) @@ -2899,7 +2899,7 @@ internal sealed class ExpressionEngine if (_host.HasSetMotion) { foreach (var kvp in MotionValues) - _host.SetMotion(kvp.Value, false); + _host.SetMotionBy("Meta", kvp.Value, false); } _wantedMotion.Clear(); return "1"; @@ -3305,6 +3305,8 @@ internal sealed class ExpressionEngine ["StopMacroOnDeath"] = (() => B(s.StopMacroOnDeath), v => s.StopMacroOnDeath = ToDouble(v) != 0), ["StopMacroOnNoComponents"] = (() => B(s.StopMacroOnNoComponents), v => s.StopMacroOnNoComponents = ToDouble(v) != 0), ["StopLootingWhenPackFull"] = (() => B(s.StopLootingWhenPackFull), v => s.StopLootingWhenPackFull = ToDouble(v) != 0), + ["LootOwnCorpse"] = (() => B(s.LootOwnCorpse), v => s.LootOwnCorpse = ToDouble(v) != 0), + ["TravelToOwnCorpse"] = (() => B(s.TravelToOwnCorpse), v => s.TravelToOwnCorpse = ToDouble(v) != 0), ["StopMacroWhenPackFull"] = (() => B(s.StopMacroWhenPackFull), v => s.StopMacroWhenPackFull = ToDouble(v) != 0), ["SummonPets"] = (() => B(s.SummonPets), v => s.SummonPets = ToDouble(v) != 0), ["MineOnly"] = (() => B(s.MineOnly), v => s.MineOnly = ToDouble(v) != 0), @@ -3340,6 +3342,7 @@ internal sealed class ExpressionEngine ["ManaStoneKeepCount"] = (() => I(s.ManaStoneKeepCount), v => { if (int.TryParse(v, out int i)) s.ManaStoneKeepCount = i; }), ["RebuffSecondsRemaining"] = (() => I(s.RebuffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffSecondsRemaining = i; }), ["RebuffTopOffSecondsRemaining"] = (() => I(s.RebuffTopOffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffTopOffSecondsRemaining = i; }), + ["CastBuffsOverItemBuffs"] = (() => B(s.CastBuffsOverItemBuffs), v => s.CastBuffsOverItemBuffs = ToDouble(v) != 0), // AutoVendor (UB names map here through /ub opt: AutoVendor.Enabled -> AutoVendorEnabled, ...) ["AutoVendorEnabled"] = (() => B(s.AutoVendorEnabled), v => s.AutoVendorEnabled = ToDouble(v) != 0), ["AutoVendorEnableBuying"] = (() => B(s.AutoVendorEnableBuying), v => s.AutoVendorEnableBuying = ToDouble(v) != 0), diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs index 532b5f0..38f1c02 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs @@ -367,7 +367,7 @@ internal sealed class NavigationEngine if (Now - _stopRequestedAt >= (long)StopDebounceMs) { - _host.SetAutoRun(false); + _host.SetAutoRunBy("Nav", false); _isMovingForward = false; _isTurning = false; _hasStopped = true; @@ -444,16 +444,16 @@ internal sealed class NavigationEngine // Handle active settle period if (_globalSettling) { - _host.SetAutoRun(false); + _host.SetAutoRunBy("Nav", false); ClearTurnMotions(); - if (_host.HasStopCompletely) _host.StopCompletely(); + if (_host.HasStopCompletely) _host.StopCompletelyBy("Nav"); _isMovingForward = false; _isTurning = false; if (Now - _globalSettleStart > (long)PostTeleportMs) { _host.Log($"Nav: global post-teleport settle done ({PostTeleportMs:F0}ms)"); - if (_host.HasStopCompletely) _host.StopCompletely(); + if (_host.HasStopCompletely) _host.StopCompletelyBy("Nav"); if (_host.HasForceResetBusyCount) _host.ForceResetBusyCount(); if (_combatManager != null) _combatManager.BusyCount = 0; _hasGoodHeading = false; @@ -632,7 +632,7 @@ internal sealed class NavigationEngine _offTrackSince = 0; RememberFiredPortalAction(); ResetPortalState(); - _host.SetAutoRun(false); + _host.SetAutoRunBy("Nav", false); ClearTurnMotions(); _isMovingForward = false; _isTurning = false; @@ -999,11 +999,11 @@ internal sealed class NavigationEngine int want = absError <= DeadZone ? 0 : (error > 0 ? 1 : -1); if (want != _tier1TurnDir) { - if (_tier1TurnDir > 0) _host.StopMovement(MotionTurnRight, 0); - else if (_tier1TurnDir < 0) _host.StopMovement(MotionTurnLeft, 0); + if (_tier1TurnDir > 0) _host.StopMovementBy("Nav", MotionTurnRight, 0); + else if (_tier1TurnDir < 0) _host.StopMovementBy("Nav", MotionTurnLeft, 0); - if (want > 0) _host.DoMovement(MotionTurnRight, (float)Tier1TurnSpeed, 0); - else if (want < 0) _host.DoMovement(MotionTurnLeft, (float)Tier1TurnSpeed, 0); + if (want > 0) _host.DoMovementBy("Nav", MotionTurnRight, (float)Tier1TurnSpeed, 0); + else if (want < 0) _host.DoMovementBy("Nav", MotionTurnLeft, (float)Tier1TurnSpeed, 0); _tier1TurnDir = want; } @@ -1019,14 +1019,14 @@ internal sealed class NavigationEngine double newHeading = currentDeg + step; if (newHeading >= 360.0) newHeading -= 360.0; else if (newHeading < 0.0) newHeading += 360.0; - _host.TurnToHeading((float)newHeading); + _host.TurnToHeadingBy("Nav", (float)newHeading); } } // ── Heartbeat: periodically re-assert autorun ─────────────────────── if (_isMovingForward && Now - _lastHeartbeat > (long)HeartbeatMs) { - _host.SetAutoRun(true); + _host.SetAutoRunBy("Nav", true); _lastHeartbeat = Now; } } @@ -1050,13 +1050,13 @@ internal sealed class NavigationEngine if (error > 0) { - _host.SetMotion(MotionTurnRight, true); - _host.SetMotion(MotionTurnLeft, false); + _host.SetMotionBy("Nav", MotionTurnRight, true); + _host.SetMotionBy("Nav", MotionTurnLeft, false); } else { - _host.SetMotion(MotionTurnLeft, true); - _host.SetMotion(MotionTurnRight, false); + _host.SetMotionBy("Nav", MotionTurnLeft, true); + _host.SetMotionBy("Nav", MotionTurnRight, false); } return; } @@ -1067,13 +1067,13 @@ internal sealed class NavigationEngine StopForward(); if (error > 0) { - _host.SetMotion(MotionTurnRight, true); - _host.SetMotion(MotionTurnLeft, false); + _host.SetMotionBy("Nav", MotionTurnRight, true); + _host.SetMotionBy("Nav", MotionTurnLeft, false); } else { - _host.SetMotion(MotionTurnLeft, true); - _host.SetMotion(MotionTurnRight, false); + _host.SetMotionBy("Nav", MotionTurnLeft, true); + _host.SetMotionBy("Nav", MotionTurnRight, false); } _isTurning = true; return; @@ -1098,13 +1098,13 @@ internal sealed class NavigationEngine if (_lastTurnDir > 0) { - _host.SetMotion(MotionTurnRight, true); - _host.SetMotion(MotionTurnLeft, false); + _host.SetMotionBy("Nav", MotionTurnRight, true); + _host.SetMotionBy("Nav", MotionTurnLeft, false); } else { - _host.SetMotion(MotionTurnLeft, true); - _host.SetMotion(MotionTurnRight, false); + _host.SetMotionBy("Nav", MotionTurnLeft, true); + _host.SetMotionBy("Nav", MotionTurnRight, false); } } else @@ -1115,7 +1115,7 @@ internal sealed class NavigationEngine if (_isMovingForward && Now - _lastHeartbeat > (long)HeartbeatMs) { - _host.SetAutoRun(true); + _host.SetAutoRunBy("Nav", true); _lastHeartbeat = Now; } } @@ -1742,7 +1742,7 @@ internal sealed class NavigationEngine case PortalState.Settling: // Keep clearing motions until settled ClearTurnMotions(); - _host.SetAutoRun(false); + _host.SetAutoRunBy("Nav", false); _isMovingForward = false; if (Now - _portalStateStart > (long)SettleDelayMs) @@ -1861,9 +1861,9 @@ internal sealed class NavigationEngine // Hammer-stop to cancel any lingering UseItem walk and clear // the client's internal action queue (prevents stuck hourglass // cursor when UseObject is interrupted by portal teleport). - _host.SetAutoRun(false); + _host.SetAutoRunBy("Nav", false); ClearTurnMotions(); - if (_host.HasStopCompletely) _host.StopCompletely(); + if (_host.HasStopCompletely) _host.StopCompletelyBy("Nav"); _isMovingForward = false; _isTurning = false; @@ -1874,7 +1874,7 @@ internal sealed class NavigationEngine // Force-clear the client's internal busy count (hourglass cursor) // and our tracked busy count. Portal teleport interrupts actions // without firing the matching DecrementBusyCount callback. - if (_host.HasStopCompletely) _host.StopCompletely(); + if (_host.HasStopCompletely) _host.StopCompletelyBy("Nav"); if (_host.HasForceResetBusyCount) _host.ForceResetBusyCount(); if (_combatManager != null) _combatManager.BusyCount = 0; @@ -2096,13 +2096,13 @@ internal sealed class NavigationEngine double step = Math.Clamp(err, -MaxStepDeg, MaxStepDeg); double newHeading = curDeg + step; if (newHeading >= 360.0) newHeading -= 360.0; else if (newHeading < 0.0) newHeading += 360.0; - _host.TurnToHeading((float)newHeading); + _host.TurnToHeadingBy("Nav", (float)newHeading); // Run only once roughly aligned, so we don't arc wide on a big turn. if (Math.Abs(err) <= BigTurnEnter) StartForward(); else StopForward(); } else { - _host.TurnToHeading((float)desiredDeg); + _host.TurnToHeadingBy("Nav", (float)desiredDeg); StartForward(); } } @@ -2220,7 +2220,7 @@ internal sealed class NavigationEngine if (escapeHeading >= 360.0) escapeHeading -= 360.0; else if (escapeHeading < 0.0) escapeHeading += 360.0; _host.Log($"Nav: stuck x{_stuckCount} — escape burst {offset:+0;-0}° for {RecoveryBurstMs:F0}ms."); - _host.TurnToHeading((float)escapeHeading); + _host.TurnToHeadingBy("Nav", (float)escapeHeading); StartForward(); _recoveryKind = RecoveryKind.Escape; _recoveryUntil = Now + (long)RecoveryBurstMs; @@ -2767,7 +2767,7 @@ internal sealed class NavigationEngine long now = Environment.TickCount64; if (!_isMovingForward || now - _lastForwardAssertMs >= ForwardReassertMs) { - _host.SetAutoRun(true); + _host.SetAutoRunBy("Nav", true); _isMovingForward = true; _lastForwardAssertMs = now; } @@ -2775,15 +2775,15 @@ internal sealed class NavigationEngine private void StopForward() { - _host.SetAutoRun(false); + _host.SetAutoRunBy("Nav", false); _isMovingForward = false; } private void ClearTurnMotions() { // Mode-0/legacy motion keys are local cmdinterp toggles — cheap, always clear. - _host.SetMotion(MotionTurnRight, false); - _host.SetMotion(MotionTurnLeft, false); + _host.SetMotionBy("Nav", MotionTurnRight, false); + _host.SetMotionBy("Nav", MotionTurnLeft, false); // Tier 1 turns are CM_Movement *server events* (0xF661). Only send a // StopMovement when a turn is actually in flight — this method is called @@ -2791,7 +2791,7 @@ internal sealed class NavigationEngine // send floods the server. _tier1TurnDir tracks the one active direction. if (_tier1TurnDir != 0 && _host.HasStopMovement) { - _host.StopMovement(_tier1TurnDir > 0 ? MotionTurnRight : MotionTurnLeft, 0); + _host.StopMovementBy("Nav", _tier1TurnDir > 0 ? MotionTurnRight : MotionTurnLeft, 0); _tier1TurnDir = 0; } } @@ -2850,7 +2850,7 @@ internal sealed class NavigationEngine if (!_host.HasTurnToHeading) return true; if (!TryGetQuaternionHeading(out float curDeg)) { - _host.TurnToHeading((float)desiredDeg); + _host.TurnToHeadingBy("Nav", (float)desiredDeg); return true; } long nowTicks = System.Diagnostics.Stopwatch.GetTimestamp(); @@ -2862,7 +2862,7 @@ internal sealed class NavigationEngine double maxStep = Math.Max(10.0, _settings.NavTurnRateDegPerSec) * Math.Max(dt, 0.01); double newHeading = curDeg + Math.Clamp(err, -maxStep, maxStep); if (newHeading >= 360.0) newHeading -= 360.0; else if (newHeading < 0.0) newHeading += 360.0; - _host.TurnToHeading((float)newHeading); + _host.TurnToHeadingBy("Nav", (float)newHeading); double abs = Math.Abs(err); if (_servoTurning) { if (abs <= BigTurnExit) _servoTurning = false; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index 542a8b8..2487766 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -159,6 +159,34 @@ public static unsafe class PluginExports } } + // ── Hot-reload deferral (2026-10-05) ───────────────────────────────────────── + // The engine calls this on its reload thread before it tears itself down for a hot reload: + // a non-empty text ("in combat (a monster engaged, ...)") makes it wait and ask again, up to + // its cap. Fixed signature, const char* (void); null or "" = safe. Optional: an engine that + // doesn't know it simply reloads, and a plugin without it never holds a reload. Per-thread + // buffer (same reasoning as _snapshotPtr). + [ThreadStatic] private static IntPtr _reloadBlockerPtr; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginReloadBlocker", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr ReloadBlocker() + { + try + { + string reason = Runtime.Plugin?.ReloadBlocker ?? ""; + if (reason.Length == 0) return IntPtr.Zero; + IntPtr newPtr = Marshal.StringToHGlobalAnsi(reason); + IntPtr oldPtr = _reloadBlockerPtr; + _reloadBlockerPtr = newPtr; + if (oldPtr != IntPtr.Zero) + Marshal.FreeHGlobal(oldPtr); + return newPtr; + } + catch + { + return IntPtr.Zero; + } + } + // ── Full-inventory bridge (read-only remote inventory viewer, P1) ─────────── // Dedicated export (NOT folded into the 150ms status snapshot) so 100s of items never ride the // hot path. The RynthRemote plugin polls this on its own slower cadence (P2). Per-thread buffer diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 578c24c..5e25525 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -68,6 +68,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra hazard add|del|list|near — mark current cell as lava/acid so patrol avoids it"); ChatLine("[RynthAi] /ra jump[swzxc] [heading] [holdtime] — jump with optional face/direction (s=run w=fwd x=back z=strafeL c=strafeR)"); ChatLine("[RynthAi] /ra corpseinfo — show corpse range/open diagnostics"); + ChatLine("[RynthAi] /ra owncorpse [go|stop] — where your corpse is; travel back to it, or stop"); ChatLine("[RynthAi] /ra corpsecheck — explain whether a corpse would be looted"); ChatLine("[RynthAi] /ra corpseopen — force the nearest corpse open flow"); ChatLine("[RynthAi] /ra fellowinfo — show fellowship tracker state"); @@ -1209,8 +1210,8 @@ public sealed partial class RynthAiPlugin } // Stop any active turn motion so the character doesn't keep spinning - Host.SetMotion(0x6500000D, false); // TurnRight - Host.SetMotion(0x6500000E, false); // TurnLeft + Host.SetMotionBy("Command", 0x6500000D, false); // TurnRight + Host.SetMotionBy("Command", 0x6500000E, false); // TurnLeft if (!Host.HasGetPlayerPose || !Host.TryGetPlayerPose(out _, out _, out _, out float z, out _, out _, out _, out _)) { @@ -1517,9 +1518,38 @@ public sealed partial class RynthAiPlugin FirstMatchUtl = FirstLootRuleFor, FirstMatchNative = FirstLootRuleFor, Added = OnLootRuleAdded, + BuiltInKeep = LootBuiltInKeepFor, }, }; + /// + /// Why RynthAi's looting takes the item without a loot profile rule, for the "Add to + /// loot profile" popup: the looter's own ClassifyItemAgainstProfile as a preview (nothing + /// recorded), so the answer is exactly what [LootEval] would tag. An item already in the + /// pack that Mana Tap looted earlier says so even when the tap quota is full now. + /// + private Loot.LootBuiltInKeep? LootBuiltInKeepFor(uint itemId) + { + WorldObject? wo = _objectCache?[unchecked((int)itemId)]; + LegacyUiSettings? settings = _dashboard?.Settings; + if (wo == null || settings == null) return null; + try + { + if (ClassifyLootItem(wo, settings, preview: true, out string action, out _, out _, out string builtIn) + && builtIn.Length > 0) + return new Loot.LootBuiltInKeep(builtIn, BeforeProfile: action != ManaTapActionLabel); + if (_manaStoneManager?.WasLootedForTap(wo.Id) == true) + return new Loot.LootBuiltInKeep( + "it was looted for Mana Tap, to drain into an empty mana stone - change in the Items panel, Mana Stone Tapping", + BeforeProfile: false); + } + catch (Exception ex) + { + Host.Log($"[LootAdd] built-in keep check failed for 0x{itemId:X8}: {ex.GetType().Name}: {ex.Message}"); + } + return null; + } + /// /// The Loot Editor saved : drop the cached copies and, /// when it is the loot profile in use, load it again now (its chat line says so). @@ -2121,7 +2151,7 @@ public sealed partial class RynthAiPlugin if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount(); if (Host.HasStopCompletely) - Host.StopCompletely(); + Host.StopCompletelyBy("Command"); // Reset all tracked counts — engine, plugin, combat, buff _busyCount = 0; _busyCountLastIncrementAt = 0; @@ -2144,7 +2174,7 @@ public sealed partial class RynthAiPlugin if (Host.HasCancelAttack) Host.CancelAttack(); if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat); - if (Host.HasStopCompletely) Host.StopCompletely(); + if (Host.HasStopCompletely) Host.StopCompletelyBy("Command"); if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount(); // The item-action lock itself is not the busy count: AC refuses every use, // equip and move while its pending-item-request slot or attacking flag is @@ -2409,6 +2439,38 @@ public sealed partial class RynthAiPlugin private enum GiveItemMatch { Exact, Partial, Regex } + /// + /// Hands of an item to a player or NPC with AC's give action + /// (Event_GiveObjectRequest) when the engine has it; MoveItemExternal is move-to-container + /// and silently does nothing for an NPC. amount 0 or the whole stack = the whole object. + /// + internal bool GiveItem(uint itemId, uint targetId, int amount, int stackSize) + { + if (Host.HasGiveObjectTo) + return Host.GiveObjectTo(itemId, targetId, amount <= 0 || amount >= stackSize ? 0 : amount); + return Host.MoveItemExternal(itemId, targetId, Math.Max(1, amount)); + } + + /// + /// Carried items a give may hand over, in pack order: never worn or wielded gear. Walks the + /// live inventory, then every known object the client says the player carries (the live walk + /// can miss items off AC's main thread, as FindObject notes). + /// + private List GiveCandidates(Func nameMatches) + { + var found = new List(); + var seen = new HashSet(); + if (_objectCache == null) return found; + foreach (var wo in _objectCache.GetDirectInventory(forceRefresh: true)) + if (nameMatches(wo.Name) && !WorldObjectCache.IsWieldedByPlayer(Host, wo) && seen.Add(wo.Id)) + found.Add(wo); + foreach (var wo in _objectCache.AllKnownObjects()) + if (!seen.Contains(wo.Id) && nameMatches(wo.Name) && IsCarriedByPlayer(wo.Id) + && !WorldObjectCache.IsWieldedByPlayer(Host, wo) && seen.Add(wo.Id)) + found.Add(wo); + return found; + } + private void HandleGiveCommand(string[] parts, GiveItemMatch itemMatch, bool partialPlayer, bool allItems = false) { if (_objectCache == null) { ChatLine("[RynthAi] Object cache not ready."); return; } @@ -2463,22 +2525,15 @@ public sealed partial class RynthAiPlugin catch { ChatLine($"[RynthAi] Invalid regex: {itemPart}"); return; } } - // Collect matching inventory stacks - var matches = new List(); - foreach (var wo in _objectCache.GetDirectInventory(forceRefresh: true)) + // Collect matching carried stacks (never worn or wielded gear) + var matches = GiveCandidates(name => itemMatch switch { - // GetDirectInventory includes worn and wielded gear; never give that away. - if (WorldObjectCache.IsWieldedByPlayer(Host, wo)) continue; - bool hit = itemMatch switch - { - GiveItemMatch.Exact => string.Equals(wo.Name, itemPart, StringComparison.OrdinalIgnoreCase), - GiveItemMatch.Partial => wo.Name.IndexOf(itemPart, StringComparison.OrdinalIgnoreCase) >= 0, - GiveItemMatch.Regex => rx!.IsMatch(wo.Name), - _ => false, - }; - if (hit) matches.Add(wo); - if (matches.Count >= maxCount) break; - } + GiveItemMatch.Exact => string.Equals(name, itemPart, StringComparison.OrdinalIgnoreCase), + GiveItemMatch.Partial => name.IndexOf(itemPart, StringComparison.OrdinalIgnoreCase) >= 0, + GiveItemMatch.Regex => rx!.IsMatch(name), + _ => false, + }); + if (!allItems && matches.Count > maxCount) matches.RemoveRange(maxCount, matches.Count - maxCount); if (matches.Count == 0) { ChatLine($"[RynthAi] No items found matching '{itemPart}'"); return; } @@ -2509,7 +2564,8 @@ public sealed partial class RynthAiPlugin } if (gives.Count == 1) { - Host.MoveItemExternal((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount); + GiveItem((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount, + Math.Max(1, gives[0].Item.Values(LongValueKey.StackCount, 1))); ChatLine($"[RynthAi] Giving {gives[0].Amount} x '{gives[0].Item.Name}' to {target.Name}"); } else @@ -2523,7 +2579,7 @@ public sealed partial class RynthAiPlugin { var item = matches[0]; int stackSize = Math.Max(1, item.Values(LongValueKey.StackCount, 1)); - Host.MoveItemExternal((uint)item.Id, (uint)target.Id, stackSize); + GiveItem((uint)item.Id, (uint)target.Id, stackSize, stackSize); ChatLine($"[RynthAi] Giving '{item.Name}' to {target.Name}"); } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OwnCorpse.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OwnCorpse.cs new file mode 100644 index 0000000..04aa4c4 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OwnCorpse.cs @@ -0,0 +1,687 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text.RegularExpressions; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Loot; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +/// What made of a corpse. +internal enum OwnCorpseMatch +{ + /// Not your death corpse. + No, + /// Named "Corpse of <you>", but its ID (the "Killed by" line) hasn't landed yet. + Pending, + /// Your death corpse. + Yes, +} + +/// +/// Own-corpse recovery (owner, 2026-10-05: "It needs to loot your corpse and every item on it. +/// If it's a setting default to true please"). +/// +/// Recover My Corpse (LootOwnCorpse, default on): when your own death corpse is within loot range +/// the looter opens it and takes every item on it, one at a time with the normal looter's +/// pick-up confirmation, ignoring the loot profile, Loot From, value and salvage rules and the +/// weapon-swap free-slot reserve (only "no pack has a slot at all" stops it). It beats any other +/// corpse in range but not combat (the arbiter's Looting slot, loot starvation as usual). +/// +/// It is identified as: name exactly "Corpse of <your name>" (ACE names a player's corpse +/// "Corpse of " + the player's full name, GM sigil included; character names are unique per +/// server, so no other player's corpse can carry it and a pet's corpse carries the pet's name), +/// AND an identified LongDesc that is the server's "Killed by X." line with X not you (a death +/// corpse is never killed by its own victim, so a namesake monster you killed is not it). The +/// corpse's owner (the Victim instance id) is not sent to clients by ACE, so it can't be checked. +/// Until the ID lands a corpse with your name is held, never looted by the profile meanwhile. +/// +/// The death spot (position at the death) is remembered and logged, and with Travel Back To My +/// Corpse (TravelToOwnCorpse, default off) the bot walks back there with RynthNav after the +/// respawn: /rnav go <coords> through the engine's plugin-command broker, the way RynthRemote's +/// Travel tab does. RynthNav routes on the map only, so this works for outdoor deaths only. +/// RynthNav walks on its own and does not fight, so whenever RynthAi wants the tick (combat, +/// buffing, looting, salvage) the walk is stopped and RynthAi does that; it resumes once RynthAi +/// is idle again. Gives up on no progress or a timeout, and says why. +/// +public sealed partial class RynthAiPlugin +{ + internal const string OwnCorpsePrefix = "Corpse of "; + + // ── Identifying it ─────────────────────────────────────────────────────── + + /// + /// Is this your death corpse? Pure (tests call it directly). is the + /// player object's name as the client has it (with a GM sigil if any, as the corpse name has). + /// + internal static OwnCorpseMatch MatchOwnDeathCorpse(string? corpseName, string? myName, string? longDesc) + { + if (string.IsNullOrWhiteSpace(myName) || string.IsNullOrEmpty(corpseName)) + return OwnCorpseMatch.No; + if (!string.Equals(corpseName, OwnCorpsePrefix + myName, StringComparison.Ordinal)) + return OwnCorpseMatch.No; + if (string.IsNullOrWhiteSpace(longDesc)) + return OwnCorpseMatch.Pending; + // The server writes exactly "Killed by X." on every corpse it makes for a death. + if (!longDesc.TrimStart().StartsWith("Killed by ", StringComparison.OrdinalIgnoreCase)) + return OwnCorpseMatch.No; + string? killer = ExtractCorpseKillerName(longDesc); + if (string.IsNullOrWhiteSpace(killer)) + return OwnCorpseMatch.No; + if (NormalizeCharName(killer).Equals(NormalizeCharName(myName), StringComparison.OrdinalIgnoreCase)) + return OwnCorpseMatch.No; // your own kill of a namesake, not your death corpse + return OwnCorpseMatch.Yes; + } + + /// Recover My Corpse is on and this corpse id is your identified death corpse. + private bool IsOwnDeathCorpseId(LegacyUiSettings? settings, int corpseId) + { + if (settings == null || !settings.LootOwnCorpse || corpseId == 0 || _objectCache == null) + return false; + WorldObject? corpse = _objectCache[corpseId]; + if (corpse == null) + return false; + return MatchOwnDeathCorpse(corpse.Name, GetPlayerNameForLootOwnership(), + corpse.Values(StringValueKey.LongDesc, string.Empty)) == OwnCorpseMatch.Yes; + } + + // A corpse with your name waiting for its ID: asked again every OwnCorpseIdRetryMs (the + // general corpse ID request goes out once per corpse; a lost answer must not strand it). + private readonly Dictionary _ownCorpseIdRequestedAt = new(); + private const long OwnCorpseIdRetryMs = 5_000; + + private void RequestOwnCorpseId(int corpseId) + { + long now = CorpseNowMs; + if (!_ownCorpseIdRequestedAt.TryGetValue(corpseId, out long last)) + { + _ownCorpseIdRequestedAt[corpseId] = now; // the general request just went out + LootDiag($"[RynthAi] Own corpse: 0x{(uint)corpseId:X8} is named like yours; waiting for its ID to confirm it."); + return; + } + if (now - last < OwnCorpseIdRetryMs || !Host.HasRequestId) + return; + _ownCorpseIdRequestedAt[corpseId] = now; + Host.RequestId(unchecked((uint)corpseId)); + } + + /// Your identified death corpse within (not completed, not cooling down). + private bool TryFindOwnCorpseInRange(double maxMeters, out WorldObject? corpse) + { + corpse = null; + var settings = _dashboard?.Settings; + if (settings == null || !settings.LootOwnCorpse || _objectCache == null || _playerId == 0) + return false; + string myName = GetPlayerNameForLootOwnership(); + if (myName.Length == 0) + return false; + string wanted = OwnCorpsePrefix + myName; + long now = CorpseNowMs; + int playerId = unchecked((int)_playerId); + double best = double.MaxValue; + foreach (WorldObject candidate in _objectCache.GetLandscapeObjects()) + { + if (candidate.ObjectClass != AcObjectClass.Corpse || !string.Equals(candidate.Name, wanted, StringComparison.Ordinal)) + continue; + if (_completedCorpses.ContainsKey(candidate.Id)) + continue; + if (_corpseCooldownUntil.TryGetValue(candidate.Id, out long until) && until > now) + continue; + if (!EvaluateCorpseLootDecision(candidate).IsOwnDeathCorpse) + continue; + double d = _objectCache.Distance(playerId, candidate.Id); + if (d > maxMeters || d >= best) + continue; + best = d; + corpse = candidate; + } + return corpse != null; + } + + /// + /// The pack gates (Stop Looting When Pack Full, the weapon-swap reserve) don't hold your own + /// corpse back: only "no pack has a free slot at all" does, since then nothing can move. + /// + private bool OwnCorpseBypassesPackGate(LegacyUiSettings settings, double maxMeters) + => settings.LootOwnCorpse && !IsPackFull() && TryFindOwnCorpseInRange(maxMeters, out _); + + // ── Recovering it ──────────────────────────────────────────────────────── + + private int _ownRecoveryCorpseId; // the own corpse this recovery is about (kept across pauses) + private int _ownRecoveryTotal; // items on it when first opened + private int _ownRecoveryTaken; // confirmed moved into a pack + private int _ownRecoveryRounds; // opens that ended with items that would not move + private readonly HashSet _ownCorpseNoRoomSaid = new(); + + internal const int OwnCorpseMaxAbandons = 5; // timeouts before it is written off + private const int OwnCorpseMaxRounds = 3; // reopen rounds for items that would not move + private const long OwnCorpseNoRoomPauseMs = 60_000; // no pack has a slot: look again after this + private const long OwnCorpseRetryPauseMs = 30_000; // items would not move: reopen after this + private const long OwnCorpseBusyWaitMs = 1_000; // hold a pickup this long behind a busy count + private const long OwnCorpseSettleMs = 1_000; // after the last pickup, before judging what is left + + /// + /// One tick of recovering your own corpse (it is open and its contents are listed): the next + /// item still on it is moved into a pack; the normal pick-up confirmation in + /// TickPendingCorpsePickup confirms it. Then the corpse is closed and completed. + /// + private void TickOwnCorpseRecovery(LegacyUiSettings settings, int corpseId, List items, long openAge, long now) + { + if (items.Count == 0) + { + if (openAge < Math.Max(200, settings.LootEmptyCorpseMs)) + return; + if (_ownRecoveryCorpseId != corpseId) + BeginOwnCorpseRecovery(corpseId, 0); + FinishOwnCorpseRecovery(corpseId, items); + return; + } + + if (_ownRecoveryCorpseId != corpseId) + BeginOwnCorpseRecovery(corpseId, items.Count); + + WorldObject? next = null; + int remaining = 0; + foreach (WorldObject item in items) + { + if (item.Id == 0 || _processedCorpseItems.Contains(item.Id)) + continue; + remaining++; + next ??= item; + } + + if (next == null) + { + // Every item was tried. Let the last confirmed move leave the corpse's list first. + if (_lastLootActionAt != 0 && now - _lastLootActionAt < OwnCorpseSettleMs) + return; + FinishOwnCorpseRecovery(corpseId, items); + return; + } + + // One item at a time, as the looter does: wait out a busy count from our last action, + // but only briefly (CheckBusyTimeout clears a leaked one). + if (_busyCount > 0 && _lastLootActionAt != 0 && now - _lastLootActionAt < OwnCorpseBusyWaitMs) + return; + + string name = string.IsNullOrWhiteSpace(next.Name) ? $"0x{(uint)next.Id:X8}" : next.Name; + _currentLootItemId = next.Id; + Host.SelectItem(unchecked((uint)next.Id)); + LootDiag($"[RynthAi] Own corpse: taking 0x{(uint)next.Id:X8} '{name}' ({remaining} left on 0x{(uint)corpseId:X8})."); + + LootPickupResult pickup = SendLootPickup(next.Id, name, corpseId); + if (pickup == LootPickupResult.NoRoom || pickup == LootPickupResult.Refused) + return; // SendLootPickup paused the corpse / left the item + if (pickup != LootPickupResult.Moved && pickup != LootPickupResult.Used) + { + if (_busyCount > 0) + return; + LootDiag($"[RynthAi] Own corpse: the move of 0x{(uint)next.Id:X8} was not sent."); + if (IncrementCorpseItemAttempt(next.Id) >= 3) + _processedCorpseItems.Add(next.Id); + ResetCurrentLootItem(); + _lastLootActionAt = now; + return; + } + + _currentLootItemMovePending = true; + _currentLootItemMoveRequestedAt = now; + _currentLootItemMoveAttempts = 1; + _currentLootItemActionLabel = "Recover"; + _currentLootItemName = name; + _currentLootItemIsSalvage = false; // never salvage your own things + _lastLootActionAt = now; + _corpseTargetSince = now; // progress: a long recovery must not hit the corpse timeout + } + + private void BeginOwnCorpseRecovery(int corpseId, int itemCount) + { + _ownRecoveryCorpseId = corpseId; + _ownRecoveryTotal = itemCount; + _ownRecoveryTaken = 0; + _ownRecoveryRounds = 0; + _ownCorpseNoRoomSaid.Remove(corpseId); + // Anything the profile looter passed over before the corpse was known to be yours + // (opened by hand before its ID landed) is taken now; items already moved have left it. + _processedCorpseItems.Clear(); + _corpseItemAttempts.Clear(); + if (itemCount > 0) + OwnCorpseSay($"[RynthAi] Own corpse: recovering {itemCount} item{(itemCount == 1 ? "" : "s")}."); + } + + /// A pick-up from your corpse was confirmed (ConfirmCurrentLootItemMoved). + private void NoteOwnCorpseItemRecovered(long now) + { + _ownRecoveryTaken++; + _corpseTargetSince = now; + } + + private void FinishOwnCorpseRecovery(int corpseId, List items) + { + var left = items.Where(i => i.Id != 0).ToList(); + if (left.Count == 0) + { + OwnCorpseSay(_ownRecoveryTaken > 0 + ? $"[RynthAi] Own corpse: recovered everything ({_ownRecoveryTaken} item{(_ownRecoveryTaken == 1 ? "" : "s")})." + : "[RynthAi] Own corpse: there was nothing on it to recover."); + MarkDeathSpotRecovered(); + _ownRecoveryCorpseId = 0; + MarkCorpseCompleted(corpseId); + return; + } + + _ownRecoveryRounds++; + string names = string.Join(", ", left.Take(5).Select(i => string.IsNullOrWhiteSpace(i.Name) ? $"0x{(uint)i.Id:X8}" : i.Name)) + + (left.Count > 5 ? ", ..." : ""); + if (_ownRecoveryRounds >= OwnCorpseMaxRounds) + { + OwnCorpseSay($"[RynthAi] Own corpse: recovered {_ownRecoveryTaken}; {left.Count} item(s) would not move after {_ownRecoveryRounds} tries ({names}). Take them by hand."); + _ownRecoveryCorpseId = 0; + MarkCorpseCompleted(corpseId); + return; + } + OwnCorpseSay($"[RynthAi] Own corpse: {left.Count} item(s) would not move ({names}); trying again in {OwnCorpseRetryPauseMs / 1000}s."); + PauseOwnCorpse(corpseId, OwnCorpseRetryPauseMs, "own corpse: retry later"); + } + + /// No pack has a slot for the next item: close the corpse and look again later (never write it off). + private void PauseOwnCorpseNoRoom(int corpseId, string itemName) + { + LootDiag($"[RynthAi] Own corpse: no pack has room for '{itemName}'; pausing {OwnCorpseNoRoomPauseMs / 1000}s."); + if (_ownCorpseNoRoomSaid.Add(corpseId)) + { + ChatLine("[RynthAi] Own corpse: your packs are full. Make room and it carries on (it looks again every minute)."); + WorldObjectCache.WarnPackFull(Host, "own corpse recovery paused, no pack has a free slot"); + } + PauseOwnCorpse(corpseId, OwnCorpseNoRoomPauseMs, "own corpse: no room"); + } + + /// Closes the corpse and holds it for , without the completed mark. + private void PauseOwnCorpse(int corpseId, long ms, string why) + { + ResetCurrentLootItem(); + CloseCorpseContainer(corpseId, why); + if (_openedContainerId == corpseId) + { + _openedContainerId = 0; + _openedContainerAt = 0; + _openedContainerInventoryObservedAt = 0; + } + MarkCorpseCooldown(corpseId, (int)ms); + ResetCorpseTarget(); + } + + /// + /// The move for an item on your corpse. A pack (or a foci) only fits the main pack, and its + /// contents come with it (ACE never drops packs on death, but a slippery one can); everything + /// else goes where the looter puts things (LootPickup). + /// + private LootPickupResult SendOwnCorpsePickup(int itemId, out uint destination) + { + destination = 0; + WorldObject? item = _objectCache?[itemId]; + if (item != null && item.ObjectClass is AcObjectClass.Container or AcObjectClass.Foci + && Host.HasMoveItemExternal && _playerId != 0) + { + destination = _playerId; + return Host.MoveItemExternal(unchecked((uint)itemId), _playerId, 0) ? LootPickupResult.Moved : LootPickupResult.Failed; + } + return LootPickup.Send(Host, _objectCache, unchecked((uint)itemId), _playerId, out destination); + } + + private void OwnCorpseSay(string text) + { + Log(text); + ChatLine(text); + } + + // ── Where you died ─────────────────────────────────────────────────────── + + internal sealed class OwnDeathSpot + { + public uint Cell; // 0 when only the server's chat line gave the place + public float X, Y, Z; + public double Ns, Ew; + public bool HasCoords; + public bool Outdoors; // outdoor landblock cell: map coordinates mean something + public DateTime AtUtc; + public bool NothingDropped; // "You have retained all your items..." + public bool Recovered; + public string Where + { + get + { + if (Cell == 0) + return FormatMapCoords(Ns, Ew); + string cell = $"landblock 0x{Cell >> 16:X4}, cell 0x{Cell & 0xFFFF:X4}"; + return HasCoords && Outdoors + ? $"{FormatMapCoords(Ns, Ew)} ({cell})" + : $"{cell} at ({X:0.0}, {Y:0.0}, {Z:0.0}), indoors"; + } + } + } + + private OwnDeathSpot? _deathSpot; + internal OwnDeathSpot? DeathSpot => _deathSpot; + + /// The death edge (CheckPlayerDeath): where the player stands is where the corpse will be. + private void RecordDeathSpot() + { + if (_ownCorpseTravel != OwnCorpseTravelState.None) + EndOwnCorpseTravel("you died again", sayInChat: false); + + if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _) || cell == 0) + { + _deathSpot = null; + Log("[RynthAi] Death spot: no player position to remember."); + return; + } + bool outdoors = (cell & 0xFFFF) < 0x100; + bool hasCoords = NavCoordinateHelper.TryConvertPoseToCoords(cell, x, y, out double ns, out double ew); + _deathSpot = new OwnDeathSpot + { + Cell = cell, X = x, Y = y, Z = z, Ns = ns, Ew = ew, + HasCoords = hasCoords, Outdoors = outdoors, AtUtc = DateTime.UtcNow, + }; + OwnCorpseSay($"[RynthAi] Your corpse is at {_deathSpot.Where}."); + } + + private static readonly Regex CorpseLocatedRx = new( + @"Your corpse is located at \(\s*(\d+(?:\.\d+)?)\s*([NS])\s*,\s*(\d+(?:\.\d+)?)\s*([EW])\s*\)", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + /// The server's death lines: where the corpse is (outdoor deaths), or that nothing dropped. + private void OnOwnCorpseChat(string text) + { + if (text.IndexOf("You do not need to recover your corpse", StringComparison.OrdinalIgnoreCase) >= 0) + { + if (_deathSpot != null && (DateTime.UtcNow - _deathSpot.AtUtc).TotalMinutes < 2) + { + _deathSpot.NothingDropped = true; + Log("[RynthAi] Own corpse: the server says nothing dropped; no need to go back for it."); + } + return; + } + Match m = CorpseLocatedRx.Match(text); + if (!m.Success) + return; + double ns = double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture) * (m.Groups[2].Value.Equals("S", StringComparison.OrdinalIgnoreCase) ? -1 : 1); + double ew = double.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture) * (m.Groups[4].Value.Equals("W", StringComparison.OrdinalIgnoreCase) ? -1 : 1); + if (_deathSpot != null && (DateTime.UtcNow - _deathSpot.AtUtc).TotalMinutes < 2) + { + Log($"[RynthAi] Own corpse: the server confirms {FormatMapCoords(ns, ew)} (remembered {_deathSpot.Where})."); + return; + } + // No position at the death edge (or it was missed): the server's line is the death spot. + _deathSpot = new OwnDeathSpot { Ns = ns, Ew = ew, HasCoords = true, Outdoors = true, AtUtc = DateTime.UtcNow }; + OwnCorpseSay($"[RynthAi] Your corpse is at {FormatMapCoords(ns, ew)} (from the server)."); + } + + private void MarkDeathSpotRecovered() + { + if (_deathSpot != null) + _deathSpot.Recovered = true; + } + + internal static string FormatMapCoords(double ns, double ew) + => Math.Abs(ns).ToString("0.00", CultureInfo.InvariantCulture) + (ns >= 0 ? "N" : "S") + ", " + + Math.Abs(ew).ToString("0.00", CultureInfo.InvariantCulture) + (ew >= 0 ? "E" : "W"); + + /// /ra owncorpse [go|stop]: where your corpse is, the two settings, the travel state. + private void HandleOwnCorpseCommand(string[] parts) + { + var s = _dashboard?.Settings; + string sub = parts.Length >= 3 ? parts[2].Trim().ToLowerInvariant() : string.Empty; + if (sub == "stop") + { + if (_ownCorpseTravel == OwnCorpseTravelState.None) ChatLine("[RynthAi] Own corpse: not travelling."); + else EndOwnCorpseTravel("stopped by /ra owncorpse stop"); + return; + } + if (sub == "go") + { + StartOwnCorpseTravel(manual: true); + return; + } + + var spot = _deathSpot; + if (spot == null) + ChatLine("[RynthAi] Own corpse: no death remembered this session."); + else + { + int mins = (int)(DateTime.UtcNow - spot.AtUtc).TotalMinutes; + string state = spot.Recovered ? ", recovered" : spot.NothingDropped ? ", nothing dropped" : string.Empty; + ChatLine($"[RynthAi] Your corpse is at {spot.Where}, died {mins} min ago{state}."); + } + if (s != null) + ChatLine($"[RynthAi] Recover My Corpse: {(s.LootOwnCorpse ? "on" : "off")}, Travel Back To My Corpse: {(s.TravelToOwnCorpse ? "on" : "off")}; travel: {OwnCorpseTravelText()}. /ra owncorpse go|stop"); + } + + // ── Travelling back (TravelToOwnCorpse) ───────────────────────────────── + + internal enum OwnCorpseTravelState { None, Waiting, Travelling, Paused, Arrived } + + private OwnCorpseTravelState _ownCorpseTravel; + private long _travelStartedAt; + private long _travelIdleSince; + private long _travelBestAt; + private long _travelArrivedAt; + private double _travelBestDistance; + private bool _ownCorpseTravelManual; + + internal const long OwnCorpseTravelTimeoutMs = 15 * 60_000; // whole trip, fights included + internal const long OwnCorpseTravelNoProgressMs = 120_000; // walking without getting 10 m closer + internal const double OwnCorpseTravelProgressMeters = 10.0; + internal const double OwnCorpseArriveMeters = 6.0; // at the spot: stop walking, look for it + internal const long OwnCorpseArriveSearchMs = 20_000; // at the spot with no corpse in range + internal const long OwnCorpseTravelResumeMs = 1_500; // idle this long before walking (again) + internal const string RynthNavPlugin = "RynthNav"; + + /// While travelling back, RynthAi's own nav route stays parked (the arbiter's wantNav). + private bool OwnCorpseTravelHoldsNav => _ownCorpseTravel != OwnCorpseTravelState.None; + + private string OwnCorpseTravelText() => _ownCorpseTravel switch + { + OwnCorpseTravelState.None => "off", + OwnCorpseTravelState.Waiting => "waiting for a quiet moment", + OwnCorpseTravelState.Travelling => "walking (RynthNav)", + OwnCorpseTravelState.Paused => "paused while RynthAi works", + OwnCorpseTravelState.Arrived => "at the spot, looking for the corpse", + _ => _ownCorpseTravel.ToString(), + }; + + /// The respawn edge (HoldForDeath): start the trip back when Travel Back To My Corpse is on. + private void OnRespawnedForOwnCorpse() + { + var s = _dashboard?.Settings; + if (s == null || !s.TravelToOwnCorpse) + return; + StartOwnCorpseTravel(manual: false); + } + + private void StartOwnCorpseTravel(bool manual) + { + var s = _dashboard?.Settings; + var spot = _deathSpot; + if (s == null) + return; + if (spot == null) + { + if (manual) ChatLine("[RynthAi] Own corpse: no death remembered this session, so nowhere to go."); + return; + } + if (spot.Recovered) + { + if (manual) ChatLine("[RynthAi] Own corpse: already recovered."); + return; + } + if (spot.NothingDropped && !manual) + { + Log("[RynthAi] Own corpse: nothing dropped on it; not travelling back."); + return; + } + if (!s.IsMacroRunning) + { + OwnCorpseSay("[RynthAi] Own corpse: the macro is off; not travelling back (start it and use /ra owncorpse go)."); + return; + } + if (!spot.Outdoors || !spot.HasCoords) + { + OwnCorpseSay($"[RynthAi] Own corpse: you died indoors ({spot.Where}); travelling back only works outdoors, where RynthNav can route on the map."); + return; + } + if (!Host.HasSendPluginCommand) + { + OwnCorpseSay("[RynthAi] Own corpse: this engine can't send RynthNav commands; not travelling back."); + return; + } + + long now = Environment.TickCount64; + _ownCorpseTravel = OwnCorpseTravelState.Waiting; + _ownCorpseTravelManual = manual; + _travelStartedAt = now; + _travelIdleSince = 0; + _travelArrivedAt = 0; + _travelBestAt = now; + _travelBestDistance = double.MaxValue; + OwnCorpseSay($"[RynthAi] Own corpse: travelling back to {FormatMapCoords(spot.Ns, spot.Ew)} with RynthNav once nothing else needs doing."); + } + + /// + /// Every tick after the arbiter's decision. Walks (RynthNav) only while RynthAi is idle; stops + /// the walk the moment RynthAi wants the tick (combat, buffing, looting, salvage, a vendor or + /// trade session, crafting) and resumes after. Ends when your corpse is in loot range. + /// + private void TickOwnCorpseTravel(LegacyUiSettings s) + { + if (_ownCorpseTravel == OwnCorpseTravelState.None) + return; + + long now = Environment.TickCount64; + var spot = _deathSpot; + if (spot == null) { EndOwnCorpseTravel("no death spot"); return; } + if (!s.TravelToOwnCorpse && !_ownCorpseTravelManual) { EndOwnCorpseTravel("Travel Back To My Corpse was turned off"); return; } + if (!s.IsMacroRunning) { EndOwnCorpseTravel("the macro stopped"); return; } + if (spot.Recovered) { EndOwnCorpseTravel("your corpse is recovered", sayInChat: false); return; } + + double lootRange = GetCorpseApproachRangeMaxMeters(s); + if (s.EnableLooting && TryFindOwnCorpseInRange(lootRange, out WorldObject? corpse) && corpse != null) + { + EndOwnCorpseTravel($"your corpse (0x{(uint)corpse.Id:X8}) is in loot range; recovering it"); + return; + } + if (now - _travelStartedAt > OwnCorpseTravelTimeoutMs) + { + EndOwnCorpseTravel($"gave up: not there after {OwnCorpseTravelTimeoutMs / 60_000} min"); + return; + } + + double d = DistanceToDeathSpotMeters(spot); + if (!double.IsNaN(d) && d <= OwnCorpseArriveMeters) + { + if (_ownCorpseTravel != OwnCorpseTravelState.Arrived) + { + if (_ownCorpseTravel == OwnCorpseTravelState.Travelling) SendRynthNav("stop"); + _ownCorpseTravel = OwnCorpseTravelState.Arrived; + _travelArrivedAt = now; + Log($"[RynthAi] Own corpse: at the death spot ({d:0.0} m); looking for the corpse."); + } + if (now - _travelArrivedAt > OwnCorpseArriveSearchMs) + EndOwnCorpseTravel(s.EnableLooting + ? "gave up: at the spot, but no corpse of yours in loot range (it may have decayed, or lie further than loot range)" + : "at the spot; Enable Looting is off, so it is not recovered"); + return; + } + + if (OwnCorpseTravelBlockedBy(out string by)) + { + if (_ownCorpseTravel == OwnCorpseTravelState.Travelling) + { + SendRynthNav("stop"); + Log($"[RynthAi] Own corpse: travel paused for {by}."); + } + if (_ownCorpseTravel != OwnCorpseTravelState.Waiting) + _ownCorpseTravel = OwnCorpseTravelState.Paused; + _travelIdleSince = 0; + _travelBestAt = now; // a fight is not "no progress" + return; + } + + if (_ownCorpseTravel != OwnCorpseTravelState.Travelling) + { + if (_travelIdleSince == 0) _travelIdleSince = now; + if (now - _travelIdleSince < OwnCorpseTravelResumeMs) + return; + bool resume = _ownCorpseTravel == OwnCorpseTravelState.Paused || _ownCorpseTravel == OwnCorpseTravelState.Arrived; + if (!SendRynthNav("go " + FormatMapCoords(spot.Ns, spot.Ew))) + { + EndOwnCorpseTravel("gave up: RynthNav isn't loaded in this client", sendStop: false); + return; + } + Log($"[RynthAi] Own corpse: {(resume ? "resuming the walk" : "walking")} to {FormatMapCoords(spot.Ns, spot.Ew)}{(double.IsNaN(d) ? "" : $" ({d:0} m away)")}."); + _ownCorpseTravel = OwnCorpseTravelState.Travelling; + _travelArrivedAt = 0; + _travelBestAt = now; + _travelBestDistance = double.IsNaN(d) ? double.MaxValue : d; + return; + } + + if (!double.IsNaN(d) && (_travelBestDistance == double.MaxValue || d < _travelBestDistance - OwnCorpseTravelProgressMeters)) + { + _travelBestDistance = d; + _travelBestAt = now; + } + else if (now - _travelBestAt > OwnCorpseTravelNoProgressMs) + { + EndOwnCorpseTravel($"gave up: no closer in {OwnCorpseTravelNoProgressMs / 1000}s (RynthNav may have no route or navmesh here; /rnav here says)"); + } + } + + /// RynthAi wants the tick for something, so RynthNav must not be walking. + private bool OwnCorpseTravelBlockedBy(out string by) + { + by = string.Empty; + if (_activity != BotActivity.Idle) by = ActivityArbiter.ToBotAction(_activity); + else if (_autoVendor?.HoldsBot == true) by = "AutoVendor"; + else if (_autoTrade?.HoldsBot == true) by = "AutoTrade"; + else if (_missileCraftingManager?.IsCrafting == true) by = "ammo crafting"; + else if (Host.HasIsPortaling && Host.IsPortaling()) by = "portal space"; + return by.Length > 0; + } + + private void EndOwnCorpseTravel(string why, bool sayInChat = true, bool sendStop = true) + { + if (sendStop && _ownCorpseTravel == OwnCorpseTravelState.Travelling) + SendRynthNav("stop"); + _ownCorpseTravel = OwnCorpseTravelState.None; + _ownCorpseTravelManual = false; + _travelIdleSince = 0; + _travelArrivedAt = 0; + string line = $"[RynthAi] Own corpse: travel back ended: {why}."; + if (sayInChat) OwnCorpseSay(line); else Log(line); + // RynthAi's own nav carries on from the nearest waypoint, not one from before the death. + _navigationEngine?.ResumeFromNearestWaypoint(); + } + + private bool SendRynthNav(string command) + { + bool sent = Host.HasSendPluginCommand && Host.SendPluginCommand(RynthNavPlugin, "rnav", command); + Log($"[RynthAi] Own corpse: /rnav {command} -> RynthNav {(sent ? "ok" : "NOT delivered")}."); + return sent; + } + + /// Metres from the player to the death spot by map coordinates (NaN without a position). + private double DistanceToDeathSpotMeters(OwnDeathSpot spot) + { + if (!spot.HasCoords) + return double.NaN; + if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out _, out _, out _, out _, out _) || cell == 0) + return double.NaN; + if (!NavCoordinateHelper.TryConvertPoseToCoords(cell, x, y, out double ns, out double ew)) + return double.NaN; + // 0.1 of a map coordinate is 24 m. + return Math.Sqrt(Math.Pow(ns - spot.Ns, 2) + Math.Pow(ew - spot.Ew, 2)) * 240.0; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs index a4cc314..80ed74d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs @@ -29,6 +29,8 @@ public sealed partial class RynthAiPlugin { _deathSeen = true; Log("[RynthAi] Death detected (health 0)."); + try { RecordDeathSpot(); } // where the corpse will be (RynthAiPlugin.OwnCorpse.cs) + catch (Exception ex) { Log($"[RynthAi] Death spot not recorded: {ex.Message}"); } if (s.StopMacroOnDeath && s.IsMacroRunning) { HandleMacroRunCommand("stop", Array.Empty()); @@ -82,7 +84,11 @@ public sealed partial class RynthAiPlugin _navigationEngine?.Stop(); } else + { Log("[RynthAi] Respawned — resuming."); + try { OnRespawnedForOwnCorpse(); } // Travel Back To My Corpse + catch (Exception ex) { Log($"[RynthAi] Own corpse travel not started: {ex.Message}"); } + } } return hold; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 44f5026..6a37fb7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -14,6 +14,7 @@ using RynthCore.Plugin.RynthAi.Vendor; using RynthCore.PluginCore; using RynthCore.Loot; using RynthCore.Loot.VTank; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi; @@ -64,14 +65,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthAi"); internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi(PluginModule.HandWrittenVersion); - /// - /// Oldest engine RynthAi runs on. Players get plugin updates automatically but engine - /// updates only when they click, so this stays at 66 while newer calls are feature- - /// detected (Host.HasVendorTrade for API v67 vendor trading: AutoVendor reports "needs a - /// RynthCore update" without it). The SDK default is CurrentApiVersion, which would make - /// every SDK bump refuse older engines. Raise it only for a call RynthAi can't run without. - /// - public override uint MinimumApiVersion => 66; + // Oldest engine RynthAi runs on: RynthPluginMinEngineApi in the csproj (66), which is both its + // manifest's minEngineApi and, through RynthPluginBase.MinimumApiVersion's default, its own + // runtime check. Players get plugin updates automatically but engine updates only when they + // click, so it stays at 66 while newer calls are feature-detected (Host.HasVendorTrade for API + // v67 vendor trading: AutoVendor reports "needs a RynthCore update" without it). Raise it only + // for a call RynthAi can't run without. private LegacyDashboardRenderer? _dashboard; @@ -105,7 +104,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase private ActivityArbiter? _arbiter; // STEP 1: shadow-mode only (ACTIVITY_ARBITER_PLAN.md) private PlayerVitalsCache _vitals = new(); private uint _playerId; - private int _vitalsTickCounter; + private long _lastVitalsPollAt; + private const long VitalsPollMs = 100; // see the poll in OnTick private bool _initialized; private bool _loginComplete; private bool _patrolOnLoginPending; @@ -153,6 +153,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase private readonly HashSet _seenMonstersThisSession = new(); private int _creatureSaveTickCounter; private int _settingsSaveTickCounter; + private int _mapBakeTickCounter; private int _settingsLoadRetryCounter; public override int Initialize() @@ -167,6 +168,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // Every use goes through Host.UseFor (Plugins/Shared/UseAudit.cs): one log line // each, and no automatic door/corpse use while the macro is off. RynthCore.Plugin.Shared.UseAudit.Reset("RynthAi", () => _dashboard?.Settings.IsMacroRunning == true); + // Every movement call is logged with its subsystem (Plugins/Shared/MoveAudit.cs). + RynthCore.Plugin.Shared.MoveAudit.Reset(); _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 @@ -242,9 +245,82 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { Log("RynthAi: logout — tearing down session."); try { _dashboard?.SaveSettings(); } catch { } + // A real logout: the next OnLoginComplete is a fresh login, not a hot reload. + ClearInGameMarker(); TeardownSession(); } + // ── Hot reload vs real login (2026-10-05) ────────────────────────────────────────────── + // The engine calls OnLoginComplete on a real login AND on a freshly (re)loaded plugin while + // the character is already in game. After the engine reload at 13:42:55 RynthAi treated it as + // a login: the buff refresh waited 5.8 s for two equal reads of an enchantment registry that + // was already complete. A process-wide environment variable (it outlives the plugin's load + // context and a NativeAOT plugin's runtime alike, and dies with the client) names the player + // whose live buffs were read in this client; a real logout clears it. + private const string InGameMarkerVar = "RYNTHAI_INGAME_PLAYER"; + private bool _inGameMarkerSet; + + private static string InGameMarkerValue(uint playerId) => $"{Environment.ProcessId}:{playerId:X8}"; + + /// At login: true when this player's live buffs were already read in this client + /// and no logout came since (an engine or plugin hot reload). + private static bool IsCarriedOverSession(uint playerId) + { + if (playerId == 0) return false; + try { return Environment.GetEnvironmentVariable(InGameMarkerVar) == InGameMarkerValue(playerId); } + catch { return false; } + } + + /// Each tick until done: once the login refresh has a trusted snapshot, mark this + /// player as in game for a later hot reload. + private void NoteCarriedOverSessionReady() + { + if (_inGameMarkerSet || _buffManager == null || !_buffManager.LiveBuffsReady || _playerId == 0) return; + _inGameMarkerSet = true; + try { Environment.SetEnvironmentVariable(InGameMarkerVar, InGameMarkerValue(_playerId)); } catch { } + } + + private void ClearInGameMarker() + { + _inGameMarkerSet = false; + try { Environment.SetEnvironmentVariable(InGameMarkerVar, null); } catch { } + } + + // ── Reload deferral (2026-10-05) ─────────────────────────────────────────────────────── + // The engine asks every plugin before a hot reload (RynthPluginReloadBlocker) and waits while + // one answers with a reason. Computed here on the pump thread each tick; the export reads the + // last text from the engine's reload thread. A text older than ReloadBlockerStaleMs (the tick + // stopped, a logout) counts as safe, so a stalled plugin can't hold a reload. + private volatile string _reloadBlocker = ""; + private long _reloadBlockerAt; + private const long ReloadBlockerStaleMs = 5000; + + private void UpdateReloadBlocker() + { + var s = _dashboard?.Settings; + string reason = ""; + if (s != null && _buffManager != null) + { + string line = _buffManager.HealLineNow(out int hp, out int lineValue); + reason = ReloadSafety.Reason(s.IsMacroRunning, _combatManager?.HasEngageableTarget == true, + line, hp, lineValue, _buffManager.CastInFlightName); + } + _reloadBlocker = reason; + Interlocked.Exchange(ref _reloadBlockerAt, Environment.TickCount64); + } + + /// For the RynthPluginReloadBlocker export (any thread): why a hot reload now would + /// hurt, or "" when it is safe. + internal string ReloadBlocker + { + get + { + if (!_loginComplete) return ""; + if (Environment.TickCount64 - Interlocked.Read(ref _reloadBlockerAt) > ReloadBlockerStaleMs) return ""; + return _reloadBlocker; + } + } + /// /// Releases every component that depends on being in-world. Idempotent. /// Used by both Shutdown (full plugin unload) and OnLogout (session-only). @@ -493,6 +569,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _weaponSwapGate ??= new WeaponSwapGate(); _buffManager = new BuffManager(Host, _dashboard.Settings, _spellManager, _vitals); + _inGameMarkerSet = false; + if (IsCarriedOverSession(_playerId)) + { + // A hot reload: the registry is complete, and heals must not wait on a login refresh. + _buffManager.CarriedOverSession = true; + Log("RynthAi: hot reload - this character was already in game in this client; the buff refresh trusts its first read."); + } _buffManager.SetWeaponSwapGate(_weaponSwapGate); _buffManager.SetCastResolvedCallback(OnBuffCastResolved); _buffManager.SetCharacterSkills(_charSkills); @@ -525,6 +608,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _combatManager = new CombatManager(Host, _dashboard.Settings, _objectCache!, _spellManager); _combatManager.SetWeaponSwapGate(_weaponSwapGate); _combatManager.SetStaleBusyCallback(OnCombatBusyStale); + _buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count if (_buffManager != null) _buffManager.OffhandStowed = id => _combatManager?.NoteOffhandStowed(id); _combatManager.SetCharacterSkills(_charSkills); @@ -651,7 +735,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _navigationEngine?.Stop(); if (Host.HasStopCompletely) - Host.StopCompletely(); + Host.StopCompletelyBy("Arbiter"); // Combat taking the tick invalidates any in-progress door interaction. // The legacy cascade did this on the combat edge only; keep it there. @@ -1262,6 +1346,14 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _settingsSaveTickCounter = 0; _dashboard?.TickAutoSave(); } + // Dungeon floor plans on disk for DrakRemote (StatusAgent /map), whether or not a + // map panel is open: one pose read about twice a second; the bake itself runs once + // per landblock on a pool thread. + if (_loginComplete && ++_mapBakeTickCounter >= 30) + { + _mapBakeTickCounter = 0; + _dashboard?.TickDungeonMapBake(); + } // Pick up an external Monster Editor save (monsters.json watcher). This used // to run only inside the legacy dashboard's Render(), which the engine no // longer calls, so edits waited for the next login. A flag check when idle. @@ -1317,9 +1409,16 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // One bot per client (Decal bridge): VTank's macro started -> ours stops, before // anything below can move, attack, cast or buff this tick. if (_dashboard?.Settings is { } yieldSettings) TickVTankYield(yieldSettings); - if (++_vitalsTickCounter >= 30) + // Player vitals: AC sends none of its own health through OnUpdateHealth (that is the + // 0x01C0 health-of-a-target message), so this read is how the bot learns health + // dropped. It ran every 30th tick: ~1 s at a background client's 30 fps, 1.5-3 s on a + // slower or busier PC, added to every heal at random (2026-10-05, "heals sometimes + // late"). The engine's snapshot is a locked struct copy kept current by its vitals + // hook, so read it every VitalsPollMs instead. + long vitalsNow = Environment.TickCount64; + if (vitalsNow - _lastVitalsPollAt >= VitalsPollMs) { - _vitalsTickCounter = 0; + _lastVitalsPollAt = vitalsNow; if (Host.HasGetPlayerVitals && Host.TryGetPlayerVitals(out uint hp, out uint maxHp, out uint st, out uint maxSt, out uint mp, out uint maxMp)) { @@ -1342,6 +1441,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (diag) Host.Log("[RynthAi] OnTick: before buffManager"); _buffManager?.OnHeartbeat(); if (diag) Host.Log("[RynthAi] OnTick: after buffManager"); + NoteCarriedOverSessionReady(); + UpdateReloadBlocker(); var settings = _dashboard?.Settings; if (settings == null) @@ -1370,7 +1471,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { int busyBefore = Host.HasGetBusyState ? Host.GetBusyState() : -1; if (Host.HasCancelAttack) Host.CancelAttack(); - if (Host.HasStopCompletely) Host.StopCompletely(); + if (Host.HasStopCompletely) Host.StopCompletelyBy("MacroStop"); if (busyBefore > 0 && Host.HasForceResetBusyCount) Host.ForceResetBusyCount(); _busyCount = 0; _busyCountLastIncrementAt = 0; @@ -1499,8 +1600,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase bool followActive = (settings.FollowMode && settings.FollowTargetId != 0) || (settings.CurrentRoute != null && settings.CurrentRoute.RouteType == NavRouteType.Follow && settings.CurrentRoute.FollowTargetName.Length > 0); + // Travelling back to your corpse (RynthNav walks): RynthAi's own route waits. bool wantNav = settings.IsMacroRunning && settings.EnableNavigation - && (routeLoaded || followActive); + && (routeLoaded || followActive) + && !OwnCorpseTravelHoldsNav; // Loot starvation: a lootable corpse in range has waited LootStarveMs behind // combat and no monster is within LootStarveCloseYards. A busy spawn always // has a monster inside MonsterRange, so without this corpses waited until @@ -1515,6 +1618,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase lootStarved: lootStarved); _activity = _arbiter.Apply(in inputs, settings); _lootStarveTurn = lootStarved && _activity == BotActivity.Looting; + // Display only: what the Buffing slot is doing (ActivityArbiter.DisplayLabel), + // and the decision for [HealLatency]'s "arbiter gave the tick to" part. + if (_buffManager != null) + { + settings.BuffingLabel = _activity == BotActivity.Buffing ? _buffManager.BuffingLabel : BuffManager.LabelBuffing; + _buffManager.ArbiterActivity = ActivityArbiter.ToBotAction(_activity); + } } catch (Exception ex) { @@ -1531,6 +1641,19 @@ public sealed partial class RynthAiPlugin : RynthPluginBase } } + // ── Travel back to your corpse (TravelToOwnCorpse) ───────────────── + // After the decision, ahead of every early return below: RynthNav walks only + // while the arbiter says Idle, and is stopped the moment RynthAi wants the tick. + try { TickOwnCorpseTravel(settings); } + catch (Exception ex) + { + if (Environment.TickCount64 - _lastOwnCorpseTravelErrorLogAt > 10_000) + { + _lastOwnCorpseTravelErrorLogAt = Environment.TickCount64; + Host.Log($"[RynthAi] Own corpse travel tick threw: {ex.GetType().Name}: {ex.Message}"); + } + } + // ── Meta Manager ───────────────────────────────────────────────── // Here, ahead of every early return below (buffing, vendor, crafting), // so its timers and polls keep running; it reads _activity to wait for @@ -1819,6 +1942,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase } private long _lastArbiterErrorLogAt = -100_000; private long _lastMetaScheduleErrorLogAt = -100_000; + private long _lastOwnCorpseTravelErrorLogAt = -100_000; private long _lastTickErrorLogAt = -100_000; private bool _lootInspectMode = true; // always on; /ra lootcheck off to disable @@ -1877,6 +2001,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _metaManager?.HandleChat(text, chatType); _questTracker?.OnChatLine(text); CheckChatForSafetyStops(text); + try { OnOwnCorpseChat(text); } catch { } } // ACE sends GameEventKillerNotification (0x01AD) to the killer at the @@ -2845,7 +2970,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if ((DateTime.UtcNow - _lastGiveAt).TotalMilliseconds < intervalMs) return; var (itemId, targetId, stackSize) = _pendingGives.Dequeue(); - Host.MoveItemExternal(itemId, targetId, stackSize); + // The queued amount is what to hand over; GiveItem gives the whole object when it is + // the whole stack (amount 0) and uses AC's real give action, which an NPC accepts. + int whole = _objectCache?[unchecked((int)itemId)] is WorldObject wo ? Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) : stackSize; + GiveItem(itemId, targetId, stackSize, whole); _lastGiveAt = DateTime.UtcNow; if (_pendingGives.Count == 0) @@ -2926,6 +3054,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "corpseinfo": HandleCorpseInfoCommand(); break; case "corpsecheck": HandleCorpseCheckCommand(parts); break; case "corpseopen": HandleCorpseOpenCommand(); break; + case "owncorpse": + case "mycorpse": HandleOwnCorpseCommand(parts); break; case "fellow": case "fellowship": HandleFellowshipCommand(parts); break; case "fellowinfo": HandleFellowshipInfoCommand(); break; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj index 3e7c051..e45f8d7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj @@ -15,8 +15,19 @@ RynthCore.Plugin.RynthAi RynthCore.Plugin.RynthAi x86 + + 66 + The bot: combat, buffs, looting, navigation routes and metas. + + + + + + + @@ -26,6 +37,8 @@ + + diff --git a/Plugins/RynthCore.Plugin.RynthAi/StatusInterface.cs b/Plugins/RynthCore.Plugin.RynthAi/StatusInterface.cs index 8b97280..04b940d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/StatusInterface.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/StatusInterface.cs @@ -76,7 +76,7 @@ public sealed partial class RynthAiPlugin { w.WriteStartObject(); w.WriteBoolean("macro", st.IsMacroRunning); - w.WriteString("action", st.BotAction ?? ""); + w.WriteString("action", ActivityArbiter.DisplayLabel(st.BotAction, st.BuffingLabel)); // display (RynthNet) w.WriteString("state", st.CurrentState ?? ""); w.WriteBoolean("combat", st.EnableCombat); w.WriteBoolean("buff", st.EnableBuffing); diff --git a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCommands.cs index d27c48a..46b9a57 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCommands.cs @@ -117,6 +117,22 @@ public sealed partial class RynthAiPlugin // through to HandleMtCommand returning false → "Unrecognized /ub". int sp = fullCommand.IndexOf(' '); + // /ub give[p] [count] to : UtilityBelt gives EVERY matching carried item + // (Tom, 2026-10-05: "/ub give ... should give every item that matches the name"), unless + // a count is given. It used to fall through to /mt give, which hands over only the first. + // Targets match partially, as /mt give always did. give = exact item, givep = partial item. + if (sp > 0 && cmd is "give" or "givep") + { + string rest = fullCommand.Substring(sp + cmd.Length + 1).TrimStart(); + string first = rest.Split(' ', 2)[0]; + bool counted = int.TryParse(first, out int n) && n > 0; + string verb = cmd == "givep" + ? (counted ? "givepp" : "giveapp") + : (counted ? "givexp" : "giveaxp"); + HandleRaCommand("/ra " + verb + " " + rest); + return true; + } + // Verbs /mt doesn't implement but /ra does — route to the /ra dispatcher // (VTank-meta migration). "/ub follow X" → "/ra follow X"; myquests → /ra // quest-flag refresh. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs index 9de7499..6404863 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs @@ -337,7 +337,7 @@ internal sealed class AutoVendorManager _openAttempts = 1; _openNextAt = Now() + 250; // UB fudges the first attempt to ~250 ms after the command _opening = true; - if (_host.HasSetAutoRun) _host.SetAutoRun(false); + if (_host.HasSetAutoRun) _host.SetAutoRunBy("Vendor", false); _host.Log($"[RynthAi] AutoVendor: attempting to open vendor {vendor.Name}"); } @@ -959,9 +959,9 @@ internal sealed class AutoVendorManager private void CancelUse() { if (_host.HasTurnToHeading && _host.TryGetPlayerHeading(out float h)) - _host.TurnToHeading((h + 359f) % 360f); + _host.TurnToHeadingBy("Vendor", (h + 359f) % 360f); else if (_host.HasStopCompletely) - _host.StopCompletely(); + _host.StopCompletelyBy("Vendor"); } private WorldObject? FindVendor(string target, bool partial) diff --git a/Plugins/RynthCore.Plugin.RynthChat/RynthCore.Plugin.RynthChat.csproj b/Plugins/RynthCore.Plugin.RynthChat/RynthCore.Plugin.RynthChat.csproj index 538b923..e97a81a 100644 --- a/Plugins/RynthCore.Plugin.RynthChat/RynthCore.Plugin.RynthChat.csproj +++ b/Plugins/RynthCore.Plugin.RynthChat/RynthCore.Plugin.RynthChat.csproj @@ -15,6 +15,9 @@ RynthCore.Plugin.RynthChat RynthCore.Plugin.RynthChat x86 + + 66 + A chat window that sorts messages into tabs. diff --git a/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj b/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj index 7c02f88..0ca55c4 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj +++ b/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj @@ -22,6 +22,10 @@ RynthCore.Plugin.RynthInventory RynthCore.Plugin.RynthInventory x86 + + 66 + Search every character's items. diff --git a/Plugins/RynthCore.Plugin.RynthLua/RynthCore.Plugin.RynthLua.csproj b/Plugins/RynthCore.Plugin.RynthLua/RynthCore.Plugin.RynthLua.csproj index ef781e3..673c466 100644 --- a/Plugins/RynthCore.Plugin.RynthLua/RynthCore.Plugin.RynthLua.csproj +++ b/Plugins/RynthCore.Plugin.RynthLua/RynthCore.Plugin.RynthLua.csproj @@ -15,8 +15,17 @@ RynthCore.Plugin.RynthLua RynthCore.Plugin.RynthLua x86 + + 66 + Lua scripting for metas and your own scripts. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthCore.Plugin.RynthNav.csproj b/Plugins/RynthCore.Plugin.RynthNav/RynthCore.Plugin.RynthNav.csproj index ffd24a5..e152420 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthCore.Plugin.RynthNav.csproj +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthCore.Plugin.RynthNav.csproj @@ -15,6 +15,10 @@ RynthCore.Plugin.RynthNav RynthCore.Plugin.RynthNav x86 + + 66 + Walks you to coordinates and towns, with route planning and the Atlas. Downloads its map (about 540 MB). C:\Games\RynthSuite\RynthNav\ diff --git a/Plugins/RynthCore.Plugin.RynthNet/RynthCore.Plugin.RynthNet.csproj b/Plugins/RynthCore.Plugin.RynthNet/RynthCore.Plugin.RynthNet.csproj index dc38ae0..b8d525e 100644 --- a/Plugins/RynthCore.Plugin.RynthNet/RynthCore.Plugin.RynthNet.csproj +++ b/Plugins/RynthCore.Plugin.RynthNet/RynthCore.Plugin.RynthNet.csproj @@ -15,8 +15,17 @@ RynthCore.Plugin.RynthNet RynthCore.Plugin.RynthNet x86 + + 66 + Lets the RynthCore clients on this PC talk to each other: shared commands, vitals, positions and bot state. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj b/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj index c1ce39c..de4ae2a 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj +++ b/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj @@ -20,6 +20,10 @@ RynthCore.Plugin.RynthOracle RynthCore.Plugin.RynthOracle x86 + + 66 + Quests, character, titles and leaderboards. diff --git a/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj b/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj index e3965e4..87e9c13 100644 --- a/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj +++ b/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj @@ -15,6 +15,10 @@ RynthCore.Plugin.RynthTracker RynthCore.Plugin.RynthTracker x86 + + 66 + Kills, experience and luminance per hour for each session. diff --git a/Plugins/RynthCore.Plugin.RynthVision/RynthCore.Plugin.RynthVision.csproj b/Plugins/RynthCore.Plugin.RynthVision/RynthCore.Plugin.RynthVision.csproj index 21ef158..cd236a2 100644 --- a/Plugins/RynthCore.Plugin.RynthVision/RynthCore.Plugin.RynthVision.csproj +++ b/Plugins/RynthCore.Plugin.RynthVision/RynthCore.Plugin.RynthVision.csproj @@ -15,6 +15,10 @@ RynthCore.Plugin.RynthVision RynthCore.Plugin.RynthVision x86 + + 66 + Shows unclimbable slopes, impassable water and your radar range in the world. + + Exe + net10.0-windows + disable + true + RynthCore.DatReaderCheck + $(NoWarn);CS8632 + false + + + + + + + + + + + + + + + + diff --git a/Tools/RynthCore.LootSdkTests/LootAddItemTests.cs b/Tools/RynthCore.LootSdkTests/LootAddItemTests.cs index beebd30..e0f9f70 100644 --- a/Tools/RynthCore.LootSdkTests/LootAddItemTests.cs +++ b/Tools/RynthCore.LootSdkTests/LootAddItemTests.cs @@ -38,6 +38,7 @@ internal static partial class Program TestAddJsonInsert(crlf: false); TestAddJsonInsert(crlf: true); TestAddJsonEdgeCases(); + TestAddBuiltInReasonWire(); TestAddDeployedCopies(args); } finally @@ -46,6 +47,20 @@ internal static partial class Program } } + // The popup's "why RynthAi takes it anyway" (2026-10-05): on the wire next to OrderNote, + // and a payload from a RynthAi without it reads as empty. + private static void TestAddBuiltInReasonWire() + { + Console.WriteLine("\n-- LootAdd: built-in keep reason on the wire --"); + var st = new LootEditState { ItemDraft = new LootEditItemDraft { Seq = 3, OrderNote = "Goes in at the end. Why.", BuiltInReason = "Why." } }; + string json = System.Text.Json.JsonSerializer.Serialize(st, LootEditJsonContext.Default.LootEditState); + LootEditState? back = System.Text.Json.JsonSerializer.Deserialize(json, LootEditJsonContext.Default.LootEditState); + Eq(back?.ItemDraft?.BuiltInReason, "Why.", "BuiltInReason round-trips"); + Eq(back?.ItemDraft?.OrderNote, "Goes in at the end. Why.", "OrderNote too"); + LootEditState? old = System.Text.Json.JsonSerializer.Deserialize("{\"ItemDraft\":{\"Seq\":1,\"OrderNote\":\"x\"}}", LootEditJsonContext.Default.LootEditState); + Eq(old?.ItemDraft?.BuiltInReason, "", "an older RynthAi's draft: empty"); + } + private static string AddFile(string name, byte[] bytes) { string path = Path.Combine(_addDir, name); diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index 834686c..87cddaf 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -81,6 +81,14 @@ internal static unsafe class FakeHost public static int Jumps; public static int Turns; public static readonly List<(uint Target, int SpellId)> Casts = new(); + /// Opt-in: wires GiveObjectTo (AC's give action); every call lands in . + public static bool GiveCalls; + /// Every GiveObjectTo (item, target, amount; 0 = the whole object), in order. + public static readonly List<(uint Item, uint Target, int Amount)> Gives = new(); + /// Opt-in: wires StopCompletely (off by default so no other test sees it). + public static bool StopCalls; + /// StopCompletely calls (opt-in with ). + public static int Stops; /// Every UseObject (a wield, a use) and RequestId (an identify), in order. public static readonly List Uses = new(); public static readonly List IdRequests = new(); @@ -100,6 +108,12 @@ internal static unsafe class FakeHost public static bool ServerGates; /// The count of server UseDone (0x01C7) events the fake reports. public static int UseDoneSeq; + /// The error code of the last UseDone (GetLastUseDone, v70; 0 = completed, 0x1D = too busy). + /// Opt-in with (set before Create, together with ServerGates). + public static uint LastUseDoneError; + public static bool LastUseDoneCalls; + /// One more UseDone with (0 = the action completed). + public static void UseDone(uint error) { UseDoneSeq++; LastUseDoneError = error; } /// 1 while a cast gesture animates (GetCastBusyState), else 0. public static int CastBusy; public static int VTankSeq; @@ -135,6 +149,12 @@ internal static unsafe class FakeHost public static uint GroundContainer; /// The item selected in the game (GetSelectedItemId); 0 = none. public static uint SelectedItem; + /// Opt-in: install SendPluginCommand (the engine's plugin-command broker, API v64). + public static bool PluginCommandCalls; + /// What SendPluginCommand answers: true = delivered (the target plugin is loaded). + public static bool PluginCommandDelivered = true; + /// Every SendPluginCommand (plugin, action, value), in order. + public static readonly List<(string Plugin, string Action, string Value)> PluginCommands = new(); // ANSI strings handed back to tested code stay alive for the whole run. private static readonly Dictionary _ansi = new(); @@ -150,15 +170,16 @@ internal static unsafe class FakeHost Vitals = default; BaseVitals = default; WorldName = ""; AccountName = ""; HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0; Logs.Clear(); Chat.Clear(); ChatCommands.Clear(); - AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; Turns = 0; Casts.Clear(); + AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear(); Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1; VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0; - ServerGates = false; UseDoneSeq = 0; CastBusy = 0; + ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false; WieldCalls = false; Wields.Clear(); SalvageCalls = false; ExternalMoves.Clear(); SalvageAdds.Clear(); SalvageExecutes.Clear(); RefuseSalvageAdd.Clear(); OnSalvageExecute = null; Wielded.Clear(); _panelItems.Clear(); CloseContainerCalls = false; Closes.Clear(); GroundContainer = 0; SelectedItem = 0; + PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear(); } /// @@ -199,6 +220,10 @@ internal static unsafe class FakeHost api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl])&TurnToHeading; api.JumpNonAutonomousFn = (IntPtr)(delegate* unmanaged[Cdecl])&JumpNonAutonomous; api.CastSpellFn = (IntPtr)(delegate* unmanaged[Cdecl])&CastSpell; + if (StopCalls) + api.StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl])&StopCompletely; + if (GiveCalls) + api.GiveObjectToFn = (IntPtr)(delegate* unmanaged[Cdecl])&GiveObjectTo; if (WeaponCalls) { api.UseObjectFn = (IntPtr)(delegate* unmanaged[Cdecl])&UseObject; @@ -256,6 +281,8 @@ internal static unsafe class FakeHost { api.GetUseDoneSeqFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetUseDoneSeq; api.GetCastBusyStateFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetCastBusyState; + if (LastUseDoneCalls) + api.GetLastUseDoneFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetLastUseDone; } if (VTankFlags >= 0) { @@ -268,6 +295,11 @@ internal static unsafe class FakeHost api.CloseContainerFn = (IntPtr)(delegate* unmanaged[Cdecl])&CloseContainer; api.GetGroundContainerIdFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetGroundContainerId; } + if (PluginCommandCalls) + { + api.Version = Math.Max(api.Version, 64u); + api.SendPluginCommandFn = (IntPtr)(delegate* unmanaged[Cdecl])&SendPluginCommand; + } LastApi = api; return new RynthCoreHost(api); } @@ -327,9 +359,24 @@ internal static unsafe class FakeHost [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetCastBusyState() => CastBusy; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetLastUseDone(int* seq, uint* error) + { + *seq = UseDoneSeq; + *error = UseDoneSeq == 0 ? 0 : LastUseDoneError; + return 1; + } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int WriteToChat(IntPtr text, int type) { Chat.Add(Marshal.PtrToStringUni(text) ?? ""); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int SendPluginCommand(IntPtr plugin, IntPtr action, IntPtr value) + { + PluginCommands.Add((Marshal.PtrToStringAnsi(plugin) ?? "", Marshal.PtrToStringAnsi(action) ?? "", Marshal.PtrToStringAnsi(value) ?? "")); + return PluginCommandDelivered ? 1 : 0; + } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int InvokeChatParser(IntPtr text) { ChatCommands.Add(Marshal.PtrToStringUni(text) ?? ""); return 1; } @@ -511,6 +558,10 @@ internal static unsafe class FakeHost [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int StopCompletely() { Stops++; return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GiveObjectTo(uint item, uint target, int amount) { Gives.Add((item, target, amount)); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetCurrentCombatMode() => CombatModeValue; diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 18a1334..a1cef53 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -28,6 +28,8 @@ internal static class Program ExpressionEngine.PvarsDir = Path.Combine(TempRoot, "pvars"); ExpressionEngine.GvarsPath = Path.Combine(TempRoot, "gvars.txt"); ExpressionEngine.ItemGiverDir = Path.Combine(TempRoot, "ItemGiver"); + // The dungeon map bake writes floor plans under C:\Games\RynthSuite\RynthAi\Maps. + RynthCore.Plugin.RynthAi.Maps.DungeonMapBake.CacheDir = Path.Combine(TempRoot, "Maps"); // Spell names (item spells, spell expiry by name) come from the plugin's embedded table. SpellDatabase.Load(); @@ -50,13 +52,18 @@ internal static class Program FloodPerfTests.Register(runner); LootSalvageTests.Register(runner); LootCorpseTests.Register(runner); + OwnCorpseTests.Register(runner); VitalsTests.Register(runner); + CastSafetyTests.Register(runner); + HealLatencyTests.Register(runner); BlastTests.Register(runner); ArcWhenClearTests.Register(runner); UseAtLoginTests.Register(runner); LearnSpellsTests.Register(runner); AttackLatencyTests.Register(runner); LootAddItemTests.Register(runner); + GiveTests.Register(runner); + DungeonMapBakeTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs index eda7c7c..7dd5cb5 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs @@ -1,6 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text.Json; using RynthCore.Loot; using RynthCore.Plugin.RynthAi; using RynthCore.Plugin.RynthAi.LegacyUi; @@ -48,6 +51,9 @@ internal static class BuffTests r.Add("rebuff: permanent, expired, and two enchantments in one family", RebuffPermanentAndDuplicates); r.Add("rebuff: a higher tier is only chased above the tier that has landed", RebuffTierUpgrade); r.Add("rebuff: a chat-confirmed item spell counts as on", ItemSpellFromChat); + r.Add("rebuff: our own lower tier under an expiring higher one counts as on", RebuffUnderExpiringHigherTier); + r.Add("rebuff: cast over item-granted buffs (CastBuffsOverItemBuffs on)", RebuffOverItemBuffs); + r.Add("rebuff: CastBuffsOverItemBuffs defaults on, loads, saves, bridges", OverItemBuffsSetting); r.Add("buff choice: spell names the tables miss (Bludgeon Bane, Nuhmudira's, T'ing, Celdiseth's)", NameGapsResolve); // was a known failure; fixed by 940cb21 r.Add("buff choice: a mastery whose name has several spell ids", MultiIdMastery); // was a known failure; fixed by 0aedcee @@ -438,21 +444,26 @@ internal static class BuffTests Check.True(rig.B.NeedsAnyBuff(), "Force Rebuff: everything is due"); } + // CastBuffsOverItemBuffs off: the behaviour before 2026-10-05 (an item-granted permanent + // entry at the tier we'd cast satisfies the family). The setting's own cases are below. private static void RebuffPermanentAndDuplicates() { var rig = StrengthRig(300, "Strength Self VI"); + rig.S.CastBuffsOverItemBuffs = false; rig.Live(("Strength Self VI", double.MaxValue)); Check.False(rig.B.NeedsAnyBuff(), "a permanent enchantment counts as on"); rig.Live(("Strength Self VI", -5)); Check.True(rig.B.NeedsAnyBuff(), "an expired entry is dropped: recast"); var t7 = StrengthRig(340, "Strength Self VI", "Might of the Lugians"); // 340 buffed: tier 7 + t7.S.CastBuffsOverItemBuffs = false; t7.Live(("Strength Self VI", double.MaxValue), ("Might of the Lugians", 3000)); Check.False(t7.B.NeedsAnyBuff(), "a permanent VI and a timed VII: the VII owns the family"); t7.Live(("Might of the Lugians", 3000), ("Strength Self VI", double.MaxValue)); Check.False(t7.B.NeedsAnyBuff(), "same in the other order"); var item = StrengthRig(340, "Strength Self VI", "Might of the Lugians"); + item.S.CastBuffsOverItemBuffs = false; item.Live(("Strength Self VI", double.MaxValue)); Check.True(item.B.NeedsAnyBuff(), "only a permanent (item-granted) VI while VII is castable: cast the VII"); } @@ -473,6 +484,118 @@ internal static class BuffTests Check.False(inc.B.NeedsAnyBuff(), "an Incantation that lands as VI isn't recast for ever"); } + // A buff bot's level 8 that runs out while our own lower tier is already under it + // (Drakkon, 2026-10-05): the 8 owns the family timer, so the family read "due" + // right after our VI landed and every pass recast it until the batch audit parked it. + private static void RebuffUnderExpiringHigherTier() + { + var rig = StrengthRig(300, "Strength Self VI"); // 300 buffed: tier 6 + rig.Live(("Incantation of Strength Self", 3000)); + Check.False(rig.B.NeedsAnyBuff(), "a bot's 8 with 3000 s left: fine"); + rig.Live(("Incantation of Strength Self", 200)); + Check.True(rig.B.NeedsAnyBuff(), "the 8 is running out and nothing is under it: cast our VI"); + rig.Live(("Incantation of Strength Self", 200), ("Strength Self VI", 1800)); + Check.False(rig.B.NeedsAnyBuff(), "our VI is under the expiring 8: covered, no recast"); + rig.Live(("Strength Self VI", 1800), ("Incantation of Strength Self", 200)); + Check.False(rig.B.NeedsAnyBuff(), "same in the other order"); + rig.Live(("Incantation of Strength Self", 200), ("Strength Self VI", 250)); + Check.True(rig.B.NeedsAnyBuff(), "both under the threshold: recast"); + + var low = StrengthRig(300, "Strength Self V", "Strength Self VI"); + low.Live(("Incantation of Strength Self", 200), ("Strength Self V", 1800)); + Check.True(low.B.NeedsAnyBuff(), "only a V under it while VI is castable: still cast the VI"); + low.S.CastBuffsOverItemBuffs = false; + low.Live(("Incantation of Strength Self", 200), ("Strength Self VI", double.MaxValue)); + Check.False(low.B.NeedsAnyBuff(), "setting off: a permanent VI under it covers it"); + low.S.CastBuffsOverItemBuffs = true; + low.Live(("Incantation of Strength Self", 200), ("Strength Self VI", double.MaxValue)); + Check.True(low.B.NeedsAnyBuff(), "setting on: a permanent (item) VI under it doesn't cover it: cast ours"); + } + + // "Cast buffs even when an item already gives that buff" (CastBuffsOverItemBuffs, default + // on, 2026-10-05). On servers with buff augments a player's own cast is stronger or longer + // than the item's, so a permanent item-granted entry must not satisfy the family; the timer + // follows our own timed entry, and once that lands it reads on until it runs low. + private static void RebuffOverItemBuffs() + { + var rig = StrengthRig(300, "Strength Self VI"); // tier 6 + Check.True(rig.S.CastBuffsOverItemBuffs, "on by default"); + rig.Live(("Strength Self VI", double.MaxValue)); + Check.True(rig.B.NeedsAnyBuff(), "only an item's permanent VI: cast our own"); + rig.Live(("Strength Self VI", double.MaxValue), ("Strength Self VI", 3000)); + Check.False(rig.B.NeedsAnyBuff(), "our VI landed (3000 s) over the item's VI: on, no recast loop"); + rig.Live(("Strength Self VI", 3000), ("Strength Self VI", double.MaxValue)); + Check.False(rig.B.NeedsAnyBuff(), "same in the other order"); + rig.Live(("Strength Self VI", double.MaxValue), ("Strength Self VI", 200)); + Check.True(rig.B.NeedsAnyBuff(), "ours running low (200 s) with the item's VI still on: recast"); + rig.Live(("Strength Self VI", 200), ("Strength Self VI", double.MaxValue)); + Check.True(rig.B.NeedsAnyBuff(), "same in the other order"); + rig.Live(("Strength Self VI", double.MaxValue), ("Strength Self VI", 2700)); + Check.False(rig.B.NeedsAnyBuff(), "recast landed: on again"); + + // A higher item tier than we can cast: ours is still cast and tracked. + var high = StrengthRig(300, "Strength Self VI"); + high.Live(("Might of the Lugians", double.MaxValue)); + Check.True(high.B.NeedsAnyBuff(), "an item's permanent VII, we cast VI: cast it"); + high.Live(("Might of the Lugians", double.MaxValue), ("Strength Self VI", 3000)); + Check.False(high.B.NeedsAnyBuff(), "our VI under the item's VII: on until it runs low"); + high.Live(("Might of the Lugians", double.MaxValue), ("Strength Self VI", 100)); + Check.True(high.B.NeedsAnyBuff(), "our VI running low: recast"); + + // The tier-upgrade rule still works on our timed entries. + var up = StrengthRig(340, "Strength Self VI", "Might of the Lugians"); // tier 7 + up.Live(("Might of the Lugians", 3000)); + up.Live(("Strength Self VI", double.MaxValue), ("Strength Self V", 3000)); + Check.True(up.B.NeedsAnyBuff(), "VII has landed before: our V is upgraded, the item's VI doesn't stop it"); + up.Live(("Strength Self VI", double.MaxValue), ("Might of the Lugians", 3000)); + Check.False(up.B.NeedsAnyBuff(), "our VII on: fine"); + + // Switched on between live reads: a permanent that owns the timer no longer counts. + var toggled = StrengthRig(300, "Strength Self VI"); + toggled.S.CastBuffsOverItemBuffs = false; + toggled.Live(("Strength Self VI", double.MaxValue)); + Check.False(toggled.B.NeedsAnyBuff(), "off: the item's VI counts"); + toggled.S.CastBuffsOverItemBuffs = true; + Check.True(toggled.B.NeedsAnyBuff(), "switched on before the next read: cast ours"); + toggled.S.CastBuffsOverItemBuffs = false; + toggled.Live(("Strength Self VI", double.MaxValue)); + Check.False(toggled.B.NeedsAnyBuff(), "switched back off: the item's VI counts again"); + } + + private static void OverItemBuffsSetting() + { + Check.True(new LegacyUiSettings().CastBuffsOverItemBuffs, "a new profile: on"); + var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true,\"RebuffSecondsRemaining\":300}", RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(old != null && old.CastBuffsOverItemBuffs, "a profile saved before the setting: on"); + var off = JsonSerializer.Deserialize( + JsonSerializer.Serialize(new LegacyUiSettings { CastBuffsOverItemBuffs = false }, RynthAiJsonContext.Default.LegacyUiSettings), + RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(off != null && !off.CastBuffsOverItemBuffs, "off is saved and loaded"); + + // Profile switch/load copies it (CopySettings is the hand-written field list). + var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!; + var dst = new LegacyUiSettings(); + copy.Invoke(null, new object[] { new LegacyUiSettings { CastBuffsOverItemBuffs = false }, dst }); + Check.False(dst.CastBuffsOverItemBuffs, "a profile with it off loads off"); + copy.Invoke(null, new object[] { old!, dst }); + Check.True(dst.CastBuffsOverItemBuffs, "an old profile loads on"); + + // Engine Settings face: the payload carries it; an engine without the field leaves it alone. + var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(payload != null && payload.CastBuffsOverItemBuffs == null, "an older engine's payload has no value"); + var s = new LegacyUiSettings { CastBuffsOverItemBuffs = false }; + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s); + typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)! + .SetValue(dash, new LegacyAdvancedSettingsUi(s)); // BuildSettingsJson reads its crafting state + var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(sent != null && sent.CastBuffsOverItemBuffs == false, "sent to the engine face"); + dash.ApplySettingsJson("{\"PatrolOnLogin\":false}"); + Check.False(s.CastBuffsOverItemBuffs, "a save without the field leaves it off"); + dash.ApplySettingsJson("{\"CastBuffsOverItemBuffs\":true}"); + Check.True(s.CastBuffsOverItemBuffs, "a save with it on turns it on"); + } + private static BuffRig ArmorRig() { FakeHost.Reset(); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CastSafetyTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CastSafetyTests.cs new file mode 100644 index 0000000..1aa4dbf --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/CastSafetyTests.cs @@ -0,0 +1,457 @@ +using System; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Cast safeguards after Drakkon's held casts on DreamWeave (2026-10-05, +// ops\overnight\2026-10-05-stuck-cast.md): give-up timed from the incantation, a refusal never +// counts as the server finishing, the first cast after a stance change waits for the stance, +// and a cast the server holds open gets exactly one movement nudge. +// +// BuffManager's cast-safety timing runs on an injectable clock (BuffManager.Clock), so these +// tests move time by hand. The rig is a mage at 10% mana: the only thing CheckVitals can do is +// cast Stamina to Mana Self. +internal static class CastSafetyTests +{ + private const uint Player = 0x50000B01; + private const uint STypeLife = 33; + private const uint TooBusy = 0x1D; + + public static void Register(Runner r) + { + r.Add("cast safety: a vital's give-up runs from its incantation; from the send without one", GiveUpFromIncantation); + r.Add("cast safety: give-up time is capped, and never earlier than the send-timed one", GiveUpCap); + r.Add("cast safety: 'You're too busy!' and a 0x1D UseDone don't count as the server finishing", TooBusyIsNotDone); + r.Add("cast safety: a result line for another spell doesn't clear the pending cast", ResultForAnotherSpell); + r.Add("cast safety: the first cast after a stance change waits for Magic plus the settle", StanceWait); + r.Add("cast safety: a cast held open gets exactly one movement nudge", NudgeOnce); + // Drakkon's death, 2026-10-05 13:43:20 (ops\overnight\2026-10-05-death-fixes.md). + r.Add("cast safety: an emergency heal waits for Magic plus 300 ms only; a top-off heal the full 1 s", EmergencyStanceWait); + r.Add("cast safety: the stance clock starts when the client reads Magic, not at the first cast attempt", StanceClockFromObservation); + r.Add("cast safety: the 4.1 s settle line: the stance was ready at 1 s, a kit in flight held the cast, and the line says so", StanceLateHolderNamed); + r.Add("cast safety: a held heal is nudged at 2.8 s without waiting for a refusal, once", UrgentNudgeForHeal); + r.Add("cast safety: any held cast is nudged early while health is under a heal line; not when health is fine", UrgentNudgeForLowHealth); + r.Add("cast safety: no kit or potion while a cast is held open until its nudge, then one try per 3 s", HeldCastItemGate); + r.Add("move audit: one line per call, repeats counted, subsystem in the line", MoveAuditLines); + } + + private sealed class Rig + { + public DateTime T0 = new(2026, 10, 5, 10, 30, 40); + public DateTime NowAt; + public readonly BuffManager B; + public readonly LegacyUiSettings S; + public readonly PlayerVitalsCache V; + + public Rig(int combatMode = CombatMode.Magic) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.CombatModeValue = combatMode; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + var host = FakeHost.Create(); + S = new LegacyUiSettings + { + IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false, + EnableBuffing = false, + // OnHeartbeat's interval check runs on the real clock: keep it shut so a heartbeat + // only resolves the pending cast and never casts again. + SpellCastIntervalMs = 600_000, + }; + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, S); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + V = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 10 }; + B = new BuffManager(host, S, sm, V); + B.SetCharacterSkills(skills); + NowAt = T0; + B.Clock = () => NowAt; + B.MarkLiveBuffsReadyForTests(); + } + + public void At(double seconds) => NowAt = T0.AddSeconds(seconds); + public void Chat(string text, int type = 0) => B.OnChatWindowText(text, type); + public void Incantation() => Chat("You say, \"Puish Zharil\"", 17); + public int CastId => FakeHost.Casts.Last().SpellId; + public string CastName => SpellTable.ById(CastId)?.Name ?? ""; + public bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal)); + } + + private static void GiveUpFromIncantation() + { + // The DreamWeave case: incantation 1.0 s after the send, result 2.3 s after that. + var r = new Rig(); + r.At(0); + Check.True(r.B.CheckVitals(), "10% mana: Stamina to Mana is cast"); + Check.Eq(FakeHost.Casts.Count, 1, "one cast"); + int pending = r.B.PendingSpellId; + Check.True(pending != 0, "the vital is pending"); + r.At(1.0); r.Incantation(); + r.At(2.6); r.B.OnHeartbeat(); + Check.Eq(r.B.PendingSpellId, pending, "2.6 s after the send, 1.6 s after the incantation: still waiting (the old timer gave up at 2.5 s)"); + r.At(3.9); r.B.OnHeartbeat(); + Check.Eq(r.B.PendingSpellId, pending, "2.9 s after the incantation: still waiting"); + r.At(4.1); r.B.OnHeartbeat(); + Check.Eq(r.B.PendingSpellId, 0, "3.1 s after the incantation: given up"); + Check.True(r.Logged("after its incantation") && r.Logged("released, no strike"), "the release line says it was timed from the incantation"); + + // No incantation at all: the send-timed 2.5 s as before. + var q = new Rig(); + q.At(0); + q.B.CheckVitals(); + int p2 = q.B.PendingSpellId; + q.At(2.4); q.B.OnHeartbeat(); + Check.Eq(q.B.PendingSpellId, p2, "no incantation, 2.4 s: still waiting"); + q.At(2.6); q.B.OnHeartbeat(); + Check.Eq(q.B.PendingSpellId, 0, "no incantation, 2.6 s: given up from the send"); + Check.True(q.Logged("no incantation in"), "the release line says no incantation came"); + + // A healthy result inside the window resolves it, and the time is logged. + var h = new Rig(); + h.At(0); h.B.CheckVitals(); + h.At(0.3); h.Incantation(); + h.At(2.6); h.Chat($"You cast {h.CastName} on yourself and lose 35 points of stamina and also gain 47 points of mana"); + Check.Eq(h.B.PendingSpellId, 0, "its result clears the pending cast"); + Check.True(h.Logged("[CastTime]") && h.Logged("2.30 s after its incantation (send to incantation 300 ms)"), + "[CastTime] logs incantation-to-result and send-to-incantation"); + } + + private static void GiveUpCap() + { + var t0 = new DateTime(2026, 10, 5); + var c = new CastTracker.Cast { SentAt = t0 }; + Check.Eq(CastTracker.GiveUpAt(c, 2500), t0.AddMilliseconds(2500), "no incantation: the fallback from the send"); + c.IncantAt = t0.AddMilliseconds(100); + Check.Eq(CastTracker.GiveUpAt(c, 2500), t0.AddMilliseconds(3100), "incantation at 0.1 s: 3 s after it"); + c.IncantAt = t0.AddMilliseconds(4500); + Check.Eq(CastTracker.GiveUpAt(c, 2500), t0.AddMilliseconds(6000), "a very late incantation: capped 6 s after the send"); + c.IncantAt = t0.AddMilliseconds(500); + Check.Eq(CastTracker.GiveUpAt(c, 5000), t0.AddMilliseconds(5000), "armor (5 s from the send): an early incantation never makes it earlier"); + } + + private static void TooBusyIsNotDone() + { + // The cast is running on the server (incantation seen). + var r = new Rig(); + r.At(0); r.B.CheckVitals(); + int pending = r.B.PendingSpellId; + r.At(0.1); + Check.True(r.B.IsAwaitingCastResolution(), "just sent: waiting for the server"); + FakeHost.UseDone(0); + Check.True(r.B.IsAwaitingCastResolution(), "a UseDone(0) before the incantation is some earlier action's, not this cast's (the old wait cleared on it)"); + r.At(0.5); r.Incantation(); + FakeHost.UseDone(TooBusy); + Check.True(r.B.IsAwaitingCastResolution(), "a 0x1D UseDone is a refusal, not 'done' (the old wait cleared on it)"); + r.At(1.0); r.Chat("You're too busy!"); + Check.True(r.B.IsAwaitingCastResolution(), "'You're too busy!' is not 'done'"); + Check.Eq(r.B.PendingSpellId, pending, "the running cast stays pending: the refusal was for something else"); + r.At(2.0); FakeHost.UseDone(0); + Check.False(r.B.IsAwaitingCastResolution(), "a UseDone(0) after the incantation: the server finished it"); + Check.True(r.Logged("UseDone #"), "[CastTime] logs the UseDone that finished it"); + + // A cast refused before it started: the refusal is not 'done' either; the next UseDone(0) + // (whatever the server was busy with, finishing) is. + var q = new Rig(); + q.At(0); q.B.CheckVitals(); + q.At(0.3); q.Chat("You're too busy!"); + Check.Eq(q.B.PendingSpellId, 0, "a cast refused before its incantation is parked, as before"); + FakeHost.UseDone(TooBusy); + Check.True(q.B.IsAwaitingCastResolution(), "refused: still waiting for the server to be free"); + q.At(1.0); FakeHost.UseDone(0); + Check.False(q.B.IsAwaitingCastResolution(), "a UseDone(0) after the refusal: the server is free"); + + // The cast's own result line ends the wait. + var s = new Rig(); + s.At(0); s.B.CheckVitals(); + s.At(0.4); s.Incantation(); + s.At(2.5); s.Chat($"You cast {s.CastName} on yourself and lose 18 points of stamina and also gain 24 points of mana"); + Check.False(s.B.IsAwaitingCastResolution(), "its result line: done"); + + // Mana and stamina casts wait for the server too (heals don't). + var w = new Rig(); + w.At(0); w.B.CheckVitals(); + w.At(0.4); w.Incantation(); + w.At(3.5); w.B.OnHeartbeat(); // pending released (incantation + 3 s) + Check.Eq(w.B.PendingSpellId, 0, "released"); + int before = FakeHost.Casts.Count; + w.At(3.6); + Check.True(w.B.CheckVitals(), "past the give-up the next Stamina to Mana may go"); + Check.Eq(FakeHost.Casts.Count, before + 1, "and it is cast"); + } + + private static void ResultForAnotherSpell() + { + var r = new Rig(); + r.At(0); r.B.CheckVitals(); + int pending = r.B.PendingSpellId; + r.At(0.2); r.Chat("You cast Strength Self V on yourself, refreshing Strength Self V"); + Check.Eq(r.B.PendingSpellId, pending, "a late result for Strength Self V doesn't clear the pending Stamina to Mana"); + Check.True(r.Logged("pending kept"), "and says so"); + r.At(1.0); r.Chat($"You cast {r.CastName} on yourself and lose 35 points of stamina and also gain 47 points of mana"); + Check.Eq(r.B.PendingSpellId, 0, "its own result does"); + } + + private static void StanceWait() + { + // Peace mode, no wand listed: the bare-handed switch to Magic. + var r = new Rig(CombatMode.NonCombat); + r.At(0); + Check.True(r.B.CheckVitals(), "out of Magic: the vital yields while the stance changes"); + Check.Eq(FakeHost.Casts.Count, 0, "no cast before the stance"); + FakeHost.CombatModeValue = CombatMode.Magic; // the client field flips 60 ms later + r.At(0.06); + Check.True(r.B.CheckVitals(), "client reads Magic: still yielding"); + Check.Eq(FakeHost.Casts.Count, 0, "no cast 60 ms after the stance request"); + r.At(0.55); + r.B.CheckVitals(); + Check.Eq(FakeHost.Casts.Count, 0, "no cast at 0.55 s (when the first hung cast went out)"); + r.At(1.01); + r.B.CheckVitals(); + Check.Eq(FakeHost.Casts.Count, 1, "cast once the stance has settled (1 s after the request, 300 ms after Magic)"); + Check.True(r.Logged("Magic stance settled"), "the settle is logged"); + + // Already in Magic, no stance change from us: no wait. + var q = new Rig(); + q.At(0); q.B.CheckVitals(); + Check.Eq(FakeHost.Casts.Count, 1, "already in Magic: cast at once"); + } + + private static void NudgeOnce() + { + var r = new Rig(); + MoveAudit.Reset(); + r.At(0); r.B.CheckVitals(); + string name = r.CastName; + r.At(0.3); r.Incantation(); + r.At(5.0); r.Chat("You're too busy!"); + Check.Eq(FakeHost.AutoRunCalls.Count, 0, "4.7 s after the incantation: no nudge yet"); + r.At(6.5); r.Chat("You're too busy!"); + Check.True(FakeHost.AutoRunCalls.SequenceEqual(new[] { true, false }), "held 6.2 s and still refused: one nudge, autorun on then off"); + Check.Eq(r.B.CastNudges, 1, "one nudge counted"); + Check.True(r.Logged("[CastSafe]") && r.Logged("Buff/Nudge SetAutoRun(True)"), "the nudge is logged, with its subsystem"); + r.At(8.0); r.Chat("You're too busy!"); + r.At(12.0); r.Chat("You're too busy!"); + r.B.OnHeartbeat(); + Check.Eq(FakeHost.AutoRunCalls.Count, 2, "more refusals: no second nudge for the same held cast"); + Check.True(r.Logged("HELD"), "the held cast is logged once it passes 6 s"); + r.At(13.0); r.Chat($"You cast {name} on yourself and lose 97 points of stamina and also gain 131 points of mana"); + Check.True(r.Logged("(after the movement nudge)"), "its late result is logged as coming after the nudge"); + + // Macro off: no nudge. + var q = new Rig(); + q.At(0); q.B.CheckVitals(); + q.At(0.3); q.Incantation(); + q.S.IsMacroRunning = false; + q.At(7.0); q.Chat("You're too busy!"); + Check.Eq(FakeHost.AutoRunCalls.Count, 0, "macro off: nothing moves the character"); + } + + // The same spell at any tier (skill 400 casts a high tier with its own name, e.g. Adja's Intervention). + private static bool CastIs(string baseName) + { + if (FakeHost.Casts.Count == 0) return false; + int cat = SpellTable.Named(baseName + " I").First().Category; + return SpellTable.ById(FakeHost.Casts.Last().SpellId)?.Category == cat; + } + + // Drakkon at 27% under Emergency Heal At 30%: Heal Self waited the full stance settle + // (at least 1 s after the request). An emergency heal now waits only for Magic plus 300 ms. + private static void EmergencyStanceWait() + { + var r = new Rig(CombatMode.NonCombat); + r.S.EmergencyHealAt = 30; r.S.HealAt = 60; r.S.TopOffHP = 60; + r.V.CurrentHealth = 20; + r.At(0); + Check.True(r.B.CheckVitals(), "20% health out of Magic: Heal Self yields while the stance changes"); + Check.Eq(FakeHost.Casts.Count, 0, "no cast before the stance"); + FakeHost.CombatModeValue = CombatMode.Magic; + r.At(0.06); r.B.CheckVitals(); + Check.Eq(FakeHost.Casts.Count, 0, "the client reads Magic: the 300 ms settle still runs"); + r.At(0.30); r.B.CheckVitals(); + Check.Eq(FakeHost.Casts.Count, 0, "240 ms after Magic: still settling"); + r.At(0.37); r.B.CheckVitals(); + Check.Eq(FakeHost.Casts.Count, 1, "310 ms after Magic (370 ms after the request): Heal Self goes, no 1 s floor"); + Check.True(CastIs("Heal Self"), "and it is Heal Self"); + Check.True(r.Logged("emergency heal"), "the stance lines say it was an emergency heal"); + Check.Eq(r.B.UrgentStanceSettles, 1, "counted"); + + // A top-off heal (idle, nothing in range): the full settle, as for a buff. + var q = new Rig(CombatMode.NonCombat); + q.S.EmergencyHealAt = 30; q.S.HealAt = 60; q.S.TopOffHP = 60; + q.V.CurrentHealth = 50; + q.At(0); q.B.CheckVitals(); + FakeHost.CombatModeValue = CombatMode.Magic; + q.At(0.06); q.B.CheckVitals(); + q.At(0.5); q.B.CheckVitals(); + Check.Eq(FakeHost.Casts.Count, 0, "50% under Top Off HP: no cast at 0.5 s"); + q.At(1.01); q.B.CheckVitals(); + Check.Eq(FakeHost.Casts.Count, 1, "cast once 1 s has passed since the request"); + Check.Eq(q.B.UrgentStanceSettles, 0, "not an emergency"); + } + + // The settle clock started at the first StanceSettled CALL in Magic, so any gate in front of + // it (a busy count here) pushed the 300 ms back. It now starts when a heartbeat sees Magic. + private static void StanceClockFromObservation() + { + var r = new Rig(CombatMode.NonCombat); + r.S.SpellCastIntervalMs = 0; + r.S.EmergencyHealAt = 30; r.S.HealAt = 60; r.S.TopOffHP = 60; + r.V.CurrentHealth = 20; + r.At(0); r.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 0, "stance requested"); + FakeHost.CombatModeValue = CombatMode.Magic; + FakeHost.UseDoneSeq = 5; + r.B.BusyCount = 1; // a live busy count: the vitals step doesn't run + r.At(0.1); r.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 0, "held by the busy count, but the heartbeat saw Magic"); + FakeHost.UseDone(0); // the server finished it: the count is a leftover now + r.At(0.45); r.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 1, "Magic seen at 0.1 s + 300 ms: Heal Self at 0.45 s (the old clock started at 0.45 s)"); + } + + // 13:43:12.67 stance request, 13:43:13.10 the client reads Magic (ready at 13.67), 13:43:13.56 a + // healing kit, 13:43:16.02 its UseDone, 13:43:16.77 Heal Self: "first cast 4097 ms after the + // stance request". The stance had settled; the kit in flight (KitPending: its result line plus + // a 700 ms grace) held the spell. The settle line now says when it was ready and what held it. + private static void StanceLateHolderNamed() + { + var r = new Rig(CombatMode.NonCombat); + r.S.SpellCastIntervalMs = 0; + r.S.HealAt = 60; r.S.TopOffHP = 60; + r.V.CurrentHealth = 50; + r.At(0); r.B.OnHeartbeat(); + FakeHost.CombatModeValue = CombatMode.Magic; + r.At(0.4); r.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 0, "settling"); + r.At(0.9); r.B.MarkKitUsed(); // a healing kit goes out during the wait + r.At(1.2); r.B.OnHeartbeat(); + r.At(2.0); r.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 0, "the kit in flight holds the spell past the stance's ready time"); + r.Chat("You heal yourself for 10 Health points."); + System.Threading.Thread.Sleep(750); // the kit's grace runs on the real clock + r.At(3.1); r.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 1, "the kit landed: Heal Self goes"); + string? line = FakeHost.Logs.LastOrDefault(l => l.Contains("Magic stance settled", StringComparison.Ordinal)); + Check.NotNull(line, "the settle is logged"); + Check.True(line != null && line.Contains("first cast 3100 ms after the stance request") + && line.Contains("the stance was ready 1000 ms after the request and the cast then waited 2100 ms for: healing kit in flight"), + $"and says the stance was ready at 1 s and the kit held the cast: {line}"); + } + + private static void UrgentNudgeForHeal() + { + var r = new Rig(); + MoveAudit.Reset(); + r.S.HealAt = 60; r.S.TopOffHP = 60; + r.V.CurrentHealth = 50; + r.At(0); r.B.CheckVitals(); + Check.True(CastIs("Heal Self"), "50% health: Heal Self is cast"); + r.At(0.2); r.Incantation(); + r.At(2.7); r.B.OnHeartbeat(); + Check.Eq(FakeHost.AutoRunCalls.Count, 0, "2.5 s after the incantation (a healthy cast takes 2.2-2.5 s): no nudge"); + r.At(3.1); r.B.OnHeartbeat(); + Check.True(FakeHost.AutoRunCalls.SequenceEqual(new[] { true, false }), "2.9 s with no result: one nudge, no refusal needed"); + Check.Eq(r.B.UrgentNudges, 1, "counted as an early nudge"); + Check.True(r.Logged("it is a heal: nudged at 2.8 s, not 6 s"), "the line says why it was early"); + r.At(4.0); r.Chat("You're too busy!"); + r.At(7.0); r.Chat("You're too busy!"); + r.B.OnHeartbeat(); + Check.Eq(FakeHost.AutoRunCalls.Count, 2, "still once per held cast"); + } + + private static void UrgentNudgeForLowHealth() + { + // 20% health under Emergency Heal At, nothing that can heal: Stamina to Mana is what's held. + var r = new Rig(); + r.S.EmergencyHealAt = 30; + r.V.CurrentHealth = 20; + r.At(0); r.B.CheckVitals(); + Check.True(CastIs("Stamina to Mana Self"), "Stamina to Mana is cast"); + r.At(0.3); r.Incantation(); + r.At(3.2); r.B.OnHeartbeat(); + Check.True(FakeHost.AutoRunCalls.SequenceEqual(new[] { true, false }), "held 2.9 s while health is critical: nudged"); + Check.True(r.Logged("health 20% is under a heal line"), "and says why"); + + // Health fine: the 6 s rule (on a refusal) as before. + var q = new Rig(); + q.At(0); q.B.CheckVitals(); + q.At(0.3); q.Incantation(); + q.At(3.2); q.B.OnHeartbeat(); + q.At(5.0); q.B.OnHeartbeat(); + Check.Eq(FakeHost.AutoRunCalls.Count, 0, "health fine: no early nudge"); + } + + // ACE refuses a kit or potion while the player is busy, and every kit Drakkon used while a + // Heal Self was held open came back 0x1D. + private static void HeldCastItemGate() + { + var r = new Rig(); + r.At(0); r.B.CheckVitals(); + string name = r.CastName; + r.At(0.3); r.Incantation(); + r.At(2.0); + Check.False(r.B.HeldCastBlocksItemUse(out _), "inside the normal result window: no gate (the vital is still pending)"); + r.At(3.5); + Check.True(r.B.HeldCastBlocksItemUse(out string why), "held 3.2 s, not nudged yet: no kit or potion"); + Check.True(why.Contains("nudge first"), $"why: {why}"); + r.At(6.5); r.Chat("You're too busy!"); + Check.Eq(FakeHost.AutoRunCalls.Count, 2, "the refusal at 6.2 s nudges it"); + r.At(6.6); + Check.False(r.B.HeldCastBlocksItemUse(out _), "after the nudge: one kit or potion try"); + r.At(7.0); + Check.True(r.B.HeldCastBlocksItemUse(out why), "the next try waits"); + Check.True(why.Contains("next kit/potion try in"), $"why: {why}"); + r.At(9.7); + Check.False(r.B.HeldCastBlocksItemUse(out _), "3 s later: another try"); + r.At(10.0); r.Chat($"You cast {name} on yourself and lose 35 points of stamina and also gain 47 points of mana"); + Check.False(r.B.HeldCastBlocksItemUse(out _), "the cast resolved: no gate"); + Check.Eq(r.B.HeldItemSkips, 2, "two attempts skipped"); + } + + private static void MoveAuditLines() + { + FakeHost.Reset(); + var host = FakeHost.Create(); + UseAudit.Reset("RynthAi", null); + MoveAudit.Reset(); + long now = 1000; + var oldClock = MoveAudit.NowMs; + MoveAudit.NowMs = () => now; + try + { + host.SetAutoRunBy("Nav", true); + host.SetAutoRunBy("Nav", true); // a repeat 0 ms later: counted + now += 100; + host.TurnToHeadingBy("Nav", 10f); + now += 30; host.TurnToHeadingBy("Nav", 12f); + now += 30; host.TurnToHeadingBy("Nav", 14f); + now += 30; host.SetAutoRunBy("Meta", false); + var lines = FakeHost.Logs.Where(l => l.StartsWith("[Move]", StringComparison.Ordinal)).ToList(); + Check.Eq(lines.Count, 3, "three lines: autorun, the first turn (carrying the autorun repeat), the meta stop (carrying the turns)"); + if (lines.Count == 3) + { + Check.Eq(lines[0], "[Move] RynthAi/Nav SetAutoRun(True)", "plugin/subsystem and the call"); + Check.True(lines[1].StartsWith("[Move] RynthAi/Nav TurnToHeading(10.0) (+1 more SetAutoRun(True)", StringComparison.Ordinal), $"the repeat is counted: {lines[1]}"); + Check.True(lines[2].StartsWith("[Move] RynthAi/Meta SetAutoRun(False) (+2 more TurnToHeading, last 14.0", StringComparison.Ordinal), $"turns collapse whatever the angle: {lines[2]}"); + } + Check.Eq(FakeHost.AutoRunCalls.Count, 3, "every call still reaches the engine"); + Check.Eq(FakeHost.Turns, 3, "every turn still reaches the engine"); + + now += 2000; host.SetAutoRunBy("Meta", false); + Check.Eq(FakeHost.Logs.Count(l => l.StartsWith("[Move]", StringComparison.Ordinal)), 4, "the same call after the 1 s window gets its own line"); + } + finally { MoveAudit.NowMs = oldClock; } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/DungeonMapBakeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/DungeonMapBakeTests.cs new file mode 100644 index 0000000..15fdc91 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/DungeonMapBakeTests.cs @@ -0,0 +1,217 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Maps; +using RynthCore.Plugin.RynthAi.Raycasting; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Dungeon floor-plan bake (2026-10-05): RynthAi writes _.bin floor plans for +// the StatusAgent's /map (DrakRemote's dungeon map). The bake was the disk half of the old +// DungeonMapTexture, deleted with the D3D9 textures on 2026-09-30 (f78392b); this is it back, +// disk only. The plans already in C:\Games\RynthSuite\RynthAi\Maps are READ here, never +// written: every bake in these tests goes to the scratch folder. +internal static class DungeonMapBakeTests +{ + private const string AcDir = @"C:\Turbine\Asheron's Call"; + private const string LiveMaps = @"C:\Games\RynthSuite\RynthAi\Maps"; + private const uint Matron = 0x6346; // Matron Hive South (PatrolProof / LosProof fixtures) + + public static void Register(Runner r) + { + r.Add("map bake: file format is the StatusAgent's (header, ARGB pixels, north row first)", Format); + r.Add("map bake: same bytes are not rewritten, changed bytes are, no temp files left", NoChurn); + r.Add("map bake: file names use the short landblock id", Names); + r.Add("map bake: 0x6346 from the real dats matches the plan already on disk (if dats and plan are here)", MatchesExisting6346); + r.Add("map bake: the plans already on disk keep their names, most byte for byte (if the dats are here)", MatchesAllExisting); + } + + private static string Dir(string name) + { + string d = Path.Combine(Program.TempRoot, "mapbake", name); + Directory.CreateDirectory(d); + return d; + } + + private static void Format() + { + // A 3x2 block of flat cells at gx 10..12, gy 4..5 plus one ramp cell north of it. + var cells = new Dictionary<(int, int), DungeonMapUi.CellType>(); + for (int gx = 10; gx <= 12; gx++) + for (int gy = 4; gy <= 5; gy++) + cells[(gx, gy)] = DungeonMapUi.CellType.Flat; + cells[(11, 6)] = DungeonMapUi.CellType.SlopeUp; + + byte[]? bytes = DungeonMapBake.BuildFile(cells); + Check.NotNull(bytes, "built"); + if (bytes is null) return; + int w = 3, h = 3; + Check.Eq(bytes.Length, 20 + w * h * 4, "length = header + w*h*4"); + Check.Eq(BitConverter.ToUInt32(bytes, 0), 0x524D5458u, "magic XTMR"); + Check.Eq(BitConverter.ToInt32(bytes, 4), 10, "xMin"); + Check.Eq(BitConverter.ToInt32(bytes, 8), 4, "yMin"); + Check.Eq(BitConverter.ToInt32(bytes, 12), w, "w"); + Check.Eq(BitConverter.ToInt32(bytes, 16), h, "h"); + + uint Px(int col, int row) => BitConverter.ToUInt32(bytes, 20 + (row * w + col) * 4); + // Row 0 is the northernmost row (gy 6): only the ramp cell at gx 11, an edge cell. + Check.Eq(Px(0, 0), 0u, "empty cell is transparent"); + Check.Eq(Px(1, 0) >> 24, 255u, "edge cell is opaque"); + Check.Eq((Px(1, 0) >> 16) & 0xFF, 255u, "ramp-up edge is red"); + // Row 1 (gy 5): (11,5) has neighbours on all four sides, so it is the translucent fill. + Check.Eq(Px(1, 1) >> 24, (uint)(0.40f * 255f), "interior cell is the translucent fill"); + Check.Eq(Px(0, 1) >> 24, 255u, "border cell is an edge"); + // Row 2 (gy 4): southern edge. + Check.Eq(Px(2, 2) >> 24, 255u, "south-east corner is an edge"); + } + + private static void NoChurn() + { + string dir = Dir("churn"); + var cells = new Dictionary<(int, int), DungeonMapUi.CellType> { [(0, 0)] = DungeonMapUi.CellType.Flat, [(1, 0)] = DungeonMapUi.CellType.Flat }; + byte[] a = DungeonMapBake.BuildFile(cells)!; + string path = Path.Combine(dir, "00001234_2.bin"); + + Check.Eq(DungeonMapBake.SaveToDisk(dir, 0x1234, 2, a), DungeonMapBake.SaveResult.Written, "first save writes"); + Check.True(File.ReadAllBytes(path).AsSpan().SequenceEqual(a), "file holds the bytes"); + var past = new DateTime(2026, 5, 1, 12, 0, 0, DateTimeKind.Utc); + File.SetLastWriteTimeUtc(path, past); + + Check.Eq(DungeonMapBake.SaveToDisk(dir, 0x1234, 2, a), DungeonMapBake.SaveResult.Unchanged, "same bytes: unchanged"); + Check.Eq(File.GetLastWriteTimeUtc(path), past, "same bytes: file not touched (mtime kept, so the agent's ETag holds)"); + + cells[(2, 0)] = DungeonMapUi.CellType.SlopeDown; + byte[] b = DungeonMapBake.BuildFile(cells)!; + Check.Eq(DungeonMapBake.SaveToDisk(dir, 0x1234, 2, b), DungeonMapBake.SaveResult.Written, "changed bytes: written"); + Check.True(File.ReadAllBytes(path).AsSpan().SequenceEqual(b), "file holds the new bytes"); + Check.Eq(Directory.GetFiles(dir).Length, 1, "no temp files left: " + string.Join(", ", Directory.GetFiles(dir).Select(Path.GetFileName))); + + // A reader holding the file open the way the agent does (ReadWrite share, no Delete) + // makes the replace fail; the save must not throw or leave a temp file. + cells[(3, 0)] = DungeonMapUi.CellType.Flat; + byte[] c = DungeonMapBake.BuildFile(cells)!; + DungeonMapBake.SaveResult held; + using (new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + held = DungeonMapBake.SaveToDisk(dir, 0x1234, 2, c); + Console.WriteLine($" save while the agent holds the file open: {held}"); + Check.Eq(Directory.GetFiles(dir).Length, 1, "no temp files left after a held file"); + Check.Eq(DungeonMapBake.SaveToDisk(dir, 0x1234, 2, c), DungeonMapBake.SaveResult.Written, "written once released"); + } + + private static void Names() + { + Check.Eq(DungeonMapBake.FileName(0x6346, 1), "00006346_1.bin", "short id"); + Check.Eq(DungeonMapBake.FileName(0x63460000, 1), "00006346_1.bin", "long id is shortened"); + Check.Eq(DungeonMapBake.FileName(0x002B, 10), "0000002B_10.bin", "two-digit layer"); + Check.Eq(DungeonMapBake.ShortLandblock(0x63460000), 0x6346u, "ShortLandblock"); + } + + private static GeometryLoader? _geo; + private static bool _geoTried; + + private static DungeonLOS? Los() + { + if (!_geoTried) + { + _geoTried = true; + if (Directory.Exists(AcDir)) + { + var g = new GeometryLoader(); + if (g.Initialize(AcDir)) _geo = g; + else Console.WriteLine(" geometry loader failed: " + g.StatusMessage); + } + } + return _geo?.DungeonLOS; + } + + /// Bake one landblock into a scratch folder and compare each layer with the live plan. + private static (int Same, int Differ, int OnlyNew, int OnlyLive, List Notes) Compare(DungeonLOS los, uint lb, string outDir) + { + var notes = new List(); + var (zLayers, cells) = DungeonMapUi.BuildFloorCells(los, lb); + DungeonMapBake.BakeLayers(outDir, lb, zLayers, cells); + string prefix = $"{lb:X8}_"; + var baked = Directory.GetFiles(outDir, prefix + "*.bin").Select(Path.GetFileName).ToHashSet(StringComparer.OrdinalIgnoreCase); + var live = Directory.Exists(LiveMaps) + ? Directory.GetFiles(LiveMaps, prefix + "*.bin").Select(Path.GetFileName).ToHashSet(StringComparer.OrdinalIgnoreCase) + : new HashSet(); + int same = 0, differ = 0, onlyNew = 0, onlyLive = 0; + foreach (string? name in baked.Union(live).OrderBy(n => n)) + { + if (name is null) continue; + bool inNew = baked.Contains(name), inLive = live.Contains(name); + if (inNew && !inLive) { onlyNew++; notes.Add($"{name}: new (no live plan)"); continue; } + if (!inNew) { onlyLive++; notes.Add($"{name}: live plan has no new counterpart"); continue; } + byte[] n = File.ReadAllBytes(Path.Combine(outDir, name)); + byte[] l = File.ReadAllBytes(Path.Combine(LiveMaps, name)); + if (n.AsSpan().SequenceEqual(l)) { same++; continue; } + differ++; + notes.Add($"{name}: differs - new {Header(n)} vs live {Header(l)}, {DiffPixels(n, l)}"); + } + return (same, differ, onlyNew, onlyLive, notes); + } + + private static string Header(byte[] b) => b.Length < 20 ? $"({b.Length} bytes)" + : $"x{BitConverter.ToInt32(b, 4)} y{BitConverter.ToInt32(b, 8)} {BitConverter.ToInt32(b, 12)}x{BitConverter.ToInt32(b, 16)}"; + + private static string DiffPixels(byte[] a, byte[] b) + { + if (a.Length != b.Length || a.Length < 20 || a.AsSpan(4, 16).SequenceEqual(b.AsSpan(4, 16)) == false) return "different bounds"; + int diff = 0, total = (a.Length - 20) / 4; + for (int i = 20; i < a.Length; i += 4) + if (BitConverter.ToUInt32(a, i) != BitConverter.ToUInt32(b, i)) diff++; + return $"{diff} of {total} pixels differ"; + } + + private static void MatchesExisting6346() + { + var los = Los(); + if (los is null) { Console.WriteLine(" skipped: no dats at " + AcDir); return; } + if (!File.Exists(Path.Combine(LiveMaps, DungeonMapBake.FileName(Matron, 0)))) + { Console.WriteLine(" skipped: no live plan for 0x6346"); return; } + var (same, differ, onlyNew, onlyLive, notes) = Compare(los, Matron, Dir("6346")); + Console.WriteLine($" 0x6346: {same} identical, {differ} differ, {onlyNew} new only, {onlyLive} live only"); + foreach (string n in notes) Console.WriteLine(" " + n); + Check.True(same > 0, "some layers baked"); + Check.Eq(differ + onlyNew + onlyLive, 0, "every 0x6346 layer is byte-identical to the live plan"); + } + + private static void MatchesAllExisting() + { + var los = Los(); + if (los is null) { Console.WriteLine(" skipped: no dats at " + AcDir); return; } + if (!Directory.Exists(LiveMaps)) { Console.WriteLine(" skipped: no live maps folder"); return; } + var rx = new Regex(@"^([0-9A-Fa-f]{8})_(\d+)\.bin$"); + var lbs = Directory.GetFiles(LiveMaps, "*.bin") + .Select(f => rx.Match(Path.GetFileName(f))) + .Where(m => m.Success) + .Select(m => Convert.ToUInt32(m.Groups[1].Value, 16)) + .Distinct().OrderBy(x => x).ToList(); + string outDir = Dir("all"); + int same = 0, differ = 0, onlyNew = 0, onlyLive = 0; + foreach (uint lb in lbs) + { + var c = Compare(los, lb, outDir); + same += c.Same; differ += c.Differ; onlyNew += c.OnlyNew; onlyLive += c.OnlyLive; + if (c.Notes.Count > 0) + { + Console.WriteLine($" 0x{lb:X4}: {c.Same} identical, {c.Differ} differ, {c.OnlyNew} new only, {c.OnlyLive} live only"); + foreach (string n in c.Notes) Console.WriteLine(" " + n); + } + } + Console.WriteLine($" {lbs.Count} landblocks: {same} plans identical, {differ} differ, {onlyNew} new only, {onlyLive} live only"); + // 2026-10-05: 59 of the 81 plans baked May-June are identical; 22 differ by a few + // pixels (or a few cells of bounds) because the floor rasteriser has changed since + // they were baked. Those 22 are refreshed once, on the next visit, to what the radar + // draws today; the identical ones are left alone. What must hold: the layer numbering + // is unchanged (every live plan has a counterpart under the same name), the header + // format is the same, and most plans come out identical. + Check.Eq(onlyLive, 0, "every live plan has a counterpart under the same file name (layer numbering unchanged)"); + Check.Eq(onlyNew, 0, "no extra layers compared with the live plans"); + Check.True(same > differ, $"most live plans are reproduced byte for byte ({same} identical, {differ} differ)"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs new file mode 100644 index 0000000..7493ce7 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs @@ -0,0 +1,121 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// /ub give and /mt give (Tom, 2026-10-05): "/ub give ... should give every item that matches the +// name in the inventory. /mt give should give the first one it finds." Both use AC's give action +// (an NPC ignores MoveItemExternal) and never hand over worn or wielded gear. +internal static class GiveTests +{ + private const uint Player = 0x50000F01; + private const uint Npc = 0x80281000; + private const uint Mote1 = 0x80281101, Mote2 = 0x80281102, Mote3 = 0x80281103, WornMote = 0x80281104, Other = 0x80281105; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("give: /ub give hands over every matching carried item, never worn gear", UbGivesAll); + r.Add("give: /ub give with a count hands over that many", UbGiveCount); + r.Add("give: /mt give hands over only the first match", MtGivesFirst); + r.Add("give: /ub givep matches part of the name", UbGivePartial); + } + + private sealed class World + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new() { GiveQueueIntervalMs = 0 }; + public readonly WorldObjectCache Cache; + + public World() + { + FakeHost.Reset(); + FakeHost.SalvageCalls = true; // MoveItemExternal + GetObjectWielderInfo (Wielded) + FakeHost.GiveCalls = true; + FakeHost.Names[Player] = "Giver"; + FakeHost.PlayerIdValue = Player; + FakeHost.Names[Npc] = "Town Crier"; + FakeHost.Positions[Npc] = (0x1048002Au, 101f, 100f, 0f); + FakeHost.ItemTypes[Npc] = 0x10; // a creature (an NPC) + FakeHost.NotAttackable.Add(Npc); + FakeHost.Positions[Player] = (0x1048002Au, 100f, 100f, 0f); + FakeHost.PlayerPose = (0x1048002Au, 100f, 100f, 0f); + foreach (var (id, name) in new[] { (Mote1, "Mana Mote"), (Mote2, "Mana Mote"), (Mote3, "Mana Mote"), (WornMote, "Mana Mote"), (Other, "Lesser Mana Mote") }) + { + FakeHost.Names[id] = name; + FakeHost.Containers[id] = Player; + FakeHost.ItemTypes[id] = 0x80; // misc + } + FakeHost.Wielded[WornMote] = 0x8000; // worn: never given + var host = FakeHost.Create(playerId: Player); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + Set("_dashboard", dash); + Cache = new WorldObjectCache(host); + Cache.SetPlayerId(Player); + Set("_objectCache", Cache); + Set("_playerId", Player); + Set("_initialized", true); + Set("_loginComplete", true); + foreach (uint id in new[] { Npc, Mote1, Mote2, Mote3, WornMote, Other }) Cache.OnCreateObject(id); + Cache.Tick(); + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public object? Call(string m, params object?[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a); + + /// Runs the chat command, then drains the give queue. + public void Run(string command) + { + if (command.StartsWith("/ub", StringComparison.Ordinal)) Call("HandleUbCommand", command); + else Call("HandleMtCommand", command); + for (int i = 0; i < 20; i++) Call("DrainGiveQueue"); + } + + public uint[] GivenItems => FakeHost.Gives.Select(g => g.Item).ToArray(); + } + + private static void UbGivesAll() + { + var w = new World(); + w.Run("/ub give Mana Mote to Town Crier"); + Check.Eq(FakeHost.Gives.Count, 3, "all three carried Mana Motes"); + Check.True(new[] { Mote1, Mote2, Mote3 }.All(id => w.GivenItems.Contains(id)), "each of them"); + Check.False(w.GivenItems.Contains(WornMote), "the worn one stays on"); + Check.False(w.GivenItems.Contains(Other), "an exact name doesn't take 'Lesser Mana Mote'"); + Check.True(FakeHost.Gives.All(g => g.Target == Npc), "all to the NPC, with AC's give action"); + Check.Eq(FakeHost.ExternalMoves.Count, 0, "never MoveItemExternal (an NPC ignores it)"); + } + + private static void UbGiveCount() + { + var w = new World(); + w.Run("/ub give 2 Mana Mote to Town Crier"); + Check.Eq(FakeHost.Gives.Count, 2, "a count gives that many"); + } + + private static void MtGivesFirst() + { + var w = new World(); + w.Run("/mt give Mana Mote to Town Crier"); + Check.Eq(FakeHost.Gives.Count, 1, "/mt give: one item"); + Check.False(w.GivenItems.Contains(WornMote), "and never the worn one"); + } + + private static void UbGivePartial() + { + var w = new World(); + w.Run("/ub givep Mana Mote to Town"); + Check.Eq(FakeHost.Gives.Count, 4, "partial: the three Mana Motes and the Lesser Mana Mote"); + Check.False(w.GivenItems.Contains(WornMote), "still not the worn one"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HealLatencyTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HealLatencyTests.cs new file mode 100644 index 0000000..56d25d2 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/HealLatencyTests.cs @@ -0,0 +1,331 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Heal latency (2026-10-05): a mage's heals "sometimes fine, sometimes several seconds late". +// - A war cast's busy count is a leftover once the server's UseDone arrives (AC lowers its own +// count inline, unseen), and only combat cleared it. With health under a line the arbiter +// hands the tick to vitals, combat stops running, and the heal waited for the 5 s force-clear. +// - A healing kit the server refused (too busy, in the air) never gets a result line, so every +// vital waited the kit's 8 s result timeout. +// - [HealLatency] logs each episode's delay and what held it. +// - The activity display says Healing / Restoring mana / Restoring stamina, not "Buffing". +internal static class HealLatencyTests +{ + private const uint Player = 0x50000B01; + private const uint STypeLife = 33; + private const uint TooBusy = 0x1D; + + public static void Register(Runner r) + { + r.Add("heal latency: a heal goes ahead of a leftover busy count (a war cast the server finished)", HealBeatsLeftoverBusy); + r.Add("heal latency: a live busy count still holds the heal; a leftover doesn't free buffs or mana", LiveBusyStillHolds); + r.Add("heal latency: a refused kit ends the kit wait (UseDone error or 'too busy'), Heal Self goes next", KitRefusalEndsWait); + r.Add("heal latency: Heal Self refused for mana rests 2 s, not the 15 s a buff rests", LowManaHealRest); + r.Add("heal latency: [HealLatency] logs delay, line and blockers per episode, and a summary", TrackerLines); + r.Add("heal latency: the heartbeat files a held heal under its blocker", HeartbeatLogsEpisode); + r.Add("activity label: the Buffing slot shows Healing / Restoring mana / Buffing; control string unchanged", ActivityLabels); + r.Add("heal latency: an emergency heal goes out during the login buff refresh; buffs still wait for it", EmergencyBeatsLoginRefresh); + } + + private sealed class Rig + { + public DateTime T0 = new(2026, 10, 5, 21, 0, 0); + public DateTime NowAt; + public readonly BuffManager B; + public readonly LegacyUiSettings S; + public readonly PlayerVitalsCache V; + public readonly List StaleResets = new(); + + public Rig(int healthPct = 40, int manaPct = 100, bool lastUseDone = true, bool liveBuffsReady = true) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = lastUseDone; + FakeHost.CombatModeValue = CombatMode.Magic; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + var host = FakeHost.Create(); + // No combat manager here, so the idle line applies: Heal At = Top Off HP = 60. + S = new LegacyUiSettings + { + IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, + EnableBuffing = false, + }; + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, S); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + V = new PlayerVitalsCache + { + MaxHealth = 100, CurrentHealth = (uint)healthPct, MaxStamina = 100, CurrentStamina = 100, + MaxMana = 100, CurrentMana = (uint)manaPct, + }; + B = new BuffManager(host, S, sm, V); + B.SetCharacterSkills(skills); + B.SetStaleBusyCallback(why => StaleResets.Add(why)); + NowAt = T0; + B.Clock = () => NowAt; + if (liveBuffsReady) B.MarkLiveBuffsReadyForTests(); + } + + public void At(double seconds) => NowAt = T0.AddSeconds(seconds); + public bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal)); + public string? Log(string part) => FakeHost.Logs.LastOrDefault(l => l.Contains(part, StringComparison.Ordinal)); + } + + // Heal Self at any tier (skill 400 casts a high tier with its own name): same category as Heal Self I. + private static int HealSelfCasts() + { + int cat = SpellTable.Named("Heal Self I").First().Category; + return FakeHost.Casts.Count(c => SpellTable.ById(c.SpellId)?.Category == cat); + } + + // The mage's case: a war cast went out (busy 0 -> 1 at UseDone #5), the server finished it + // (UseDone #6, AC lowered its own count unseen), and health dropped under Heal At. Before the + // fix the heal waited at BusyCount > 0 until CheckBusyTimeout's 5 s force-clear. + private static void HealBeatsLeftoverBusy() + { + var r = new Rig(healthPct: 40); + FakeHost.UseDoneSeq = 5; + r.B.BusyCount = 1; // the war cast's increment + FakeHost.UseDone(0); // the server finished it; nothing decrements the plugin's count + r.At(0.1); + r.B.OnHeartbeat(); + Check.Eq(HealSelfCasts(), 1, "Heal Self goes out on the first heartbeat, not after the 5 s force-clear"); + Check.Eq(r.B.StaleBusyClears, 1, "the leftover was cleared once"); + Check.Eq(r.B.BusyCount, 0, "and the shared mirror is 0"); + Check.Eq(r.StaleResets.Count, 1, "through the same callback combat uses"); + Check.True(r.StaleResets[0].StartsWith("vitals:", StringComparison.Ordinal), "the reason says it was the heal"); + } + + private static void LiveBusyStillHolds() + { + // A count with no UseDone since it rose is real (a swing, a cast still on the server). + var r = new Rig(healthPct: 40); + FakeHost.UseDoneSeq = 5; + r.B.BusyCount = 1; + r.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 0, "no UseDone since the count rose: the heal waits"); + Check.Eq(r.B.StaleBusyClears, 0, "nothing cleared"); + + // A gesture still animating: real too, even after a UseDone. + FakeHost.UseDone(0); + FakeHost.CastBusy = 1; + r.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 0, "a cast gesture animating: the heal waits"); + FakeHost.CastBusy = 0; + r.B.OnHeartbeat(); + Check.Eq(HealSelfCasts(), 1, "gesture done, UseDone seen: the heal goes"); + + // Health fine, mana low: the leftover rule is for heals only, so Stamina to Mana still waits. + var m = new Rig(healthPct: 100, manaPct: 10); + m.S.GetManaAt = 50; m.S.TopOffMana = 50; + FakeHost.UseDoneSeq = 5; + m.B.BusyCount = 1; + FakeHost.UseDone(0); + m.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 0, "no heal wanted: a leftover count still holds mana and buffs"); + Check.Eq(m.B.BusyCount, 1, "and is left for combat / the watchdog"); + } + + // ACE Healer.cs answers a kit used while busy with UseDone(YoureTooBusy) and no chat result. + private static void KitRefusalEndsWait() + { + // UseDone error. + var r = new Rig(healthPct: 40); + FakeHost.UseDoneSeq = 10; + r.B.MarkKitUsed(); + Check.True(r.B.KitPending(), "kit just used: waiting for its result"); + FakeHost.UseDone(TooBusy); + Check.False(r.B.KitPending(), "a UseDone error after the kit: refused, no 8 s wait"); + Check.Eq(r.B.KitRefusals, 1, "counted"); + Check.True(r.Logged("kit was refused") && r.Logged("UseDone error 0x1D"), "and logged with the error"); + Check.True(r.B.CheckVitals(), "vitals carry on at once"); + Check.Eq(HealSelfCasts(), 1, "Heal Self is cast (the kit waits a second after a refusal)"); + + // UseDone(0) after the kit is not a refusal: the kit is still healing. + var ok = new Rig(healthPct: 40); + FakeHost.UseDoneSeq = 10; + ok.B.MarkKitUsed(); + FakeHost.UseDone(0); + Check.True(ok.B.KitPending(), "UseDone(0): no refusal, still waiting for the result line"); + Check.Eq(ok.B.KitRefusals, 0, "not counted"); + + // No GetLastUseDone on this engine: the "too busy" line ends it. + var c = new Rig(healthPct: 40, lastUseDone: false); + c.B.MarkKitUsed(); + c.B.OnChatWindowText("You're too busy!", 26); + Check.False(c.B.KitPending(), "'You're too busy!' right after the kit: refused"); + Check.Eq(c.B.KitRefusals, 1, "counted"); + + // A result line first: a later "too busy" (something else refused) doesn't cut the grace. + var g = new Rig(healthPct: 40, lastUseDone: false); + g.B.MarkKitUsed(); + g.B.OnChatWindowText("You heal yourself for 52 Health points.", 0); + g.B.OnChatWindowText("You're too busy!", 26); + Check.True(g.B.KitPending(), "result seen: the grace for the vitals still runs"); + Check.Eq(g.B.KitRefusals, 0, "no refusal counted"); + } + + // A mage out of mana mid-fight: "You don't have enough Mana" parked Heal Self for 15 s, so after + // Stamina to Mana refilled it 2-3 s later the mage still couldn't heal for 12 s more. + private static void LowManaHealRest() + { + var r = new Rig(healthPct: 40, manaPct: 2); + r.S.GetManaAt = 50; r.S.TopOffMana = 50; + Check.True(r.B.CheckVitals(), "40% health: Heal Self is cast"); + Check.Eq(HealSelfCasts(), 1, "one Heal Self"); + r.B.OnChatWindowText("You don't have enough Mana to cast this spell.", 0); + Check.True(r.Logged("not enough mana; resting the family 2s"), "Heal Self rests 2 s"); + Check.Eq(r.B.PendingSpellId, 0, "pending cleared"); + Check.True(r.B.CheckVitals(), "next check: something is done"); + Check.Eq(HealSelfCasts(), 1, "not Heal Self inside the rest..."); + Check.Eq(FakeHost.Casts.Count, 2, "...but Stamina to Mana, so the mana comes back"); + Check.Eq(r.B.BuffingLabel, "Restoring mana", "and the slot reads Restoring mana"); + r.B.OnChatWindowText("You don't have enough Mana to cast this spell.", 0); + Check.True(r.Logged("not enough mana; resting the family 15s"), "a non-heal still rests 15 s"); + System.Threading.Thread.Sleep(2100); + r.V.CurrentMana = 60; + Check.True(r.B.CheckVitals(), "2 s later, mana back"); + Check.Eq(HealSelfCasts(), 2, "Heal Self is cast again"); + } + + private static void TrackerLines() + { + var logs = new List(); + var t = new HealLatencyTracker(logs.Add); + DateTime t0 = new(2026, 10, 5, 21, 0, 0); + DateTime At(double s) => t0.AddSeconds(s); + + t.Observe(At(0), 41, "Heal At", 60, inCombat: true, healInFlight: false); + for (int i = 1; i <= 30; i++) + t.EndTick(At(i * 0.1), i <= 28 ? "busy count" : "cast gate (a gesture is animating)", "busy 1", "Buffing"); + t.HealSent(At(3.1), "Heal Self"); + string line = logs.Last(); + Check.True(line.StartsWith("[HealLatency] 3100 ms: health 41% under Heal At 60% (in combat) -> Heal Self", StringComparison.Ordinal), $"episode line: {line}"); + Check.True(line.Contains("busy count 2800 ms") && line.Contains("cast gate (a gesture is animating) 200 ms"), "blockers with their time, biggest first"); + Check.Eq(t.Episodes, 1, "one episode"); + + // Still under the line: the next episode opens only once the heal has resolved. + t.Observe(At(3.2), 45, "Heal At", 60, true, healInFlight: true); + Check.False(t.IsOpen, "heal in flight: no new episode yet"); + t.Observe(At(5.5), 45, "Heal At", 60, true, healInFlight: false); + Check.True(t.IsOpen, "resolved and still under: a follow-up episode"); + t.EndTick(At(5.6), "cast interval", "", "Combat"); + t.HealSent(At(5.9), "Heal Self"); + Check.True(logs.Last().Contains("400 ms") && logs.Last().Contains("(follow-up)") && logs.Last().Contains("arbiter gave the tick to Combat 100 ms"), + $"follow-up measured from when it became possible: {logs.Last()}"); + + // Over the line with no heal: logged when it lasted a second or more. + t.Observe(At(6), 80, "", 0, true, false); + t.Observe(At(7), 55, "Top Off HP", 95, false, false); + t.Observe(At(7.5), 96, "", 0, false, false); + Check.False(logs.Last().Contains("no heal"), "a half-second dip isn't logged"); + t.Observe(At(8), 55, "Top Off HP", 95, false, false); + t.EndTick(At(8.5), "nothing could heal", "kit: no healing kit", "Navigating"); + t.Observe(At(9.5), 96, "", 0, false, false); + Check.True(logs.Last().StartsWith("[HealLatency] no heal in 1500 ms", StringComparison.Ordinal) && logs.Last().Contains("nothing could heal"), + $"a 1.5 s episode with no heal is: {logs.Last()}"); + + // Summary every 10 heals. + for (int i = 0; i < 8; i++) + { + double s0 = 20 + i * 10; + t.Observe(At(s0), 50, "Heal At", 60, true, false); + t.EndTick(At(s0 + 0.5), "busy count", "", "Buffing"); + t.HealSent(At(s0 + 0.5), "Heal Self"); + } + string sum = logs.Last(); + Check.True(sum.StartsWith("[HealLatency] summary of 10 heals:", StringComparison.Ordinal), $"summary line: {sum}"); + Check.True(sum.Contains("max 3100 ms (Heal Self, busy count)") && sum.Contains("2 over 1 s") == false && sum.Contains("1 over 1 s") && sum.Contains("1 over 3 s") && sum.Contains("1 episode(s) with no heal"), + $"summary numbers: {sum}"); + } + + private static void HeartbeatLogsEpisode() + { + var r = new Rig(healthPct: 40); + r.S.SpellCastIntervalMs = 0; + FakeHost.UseDoneSeq = 5; + r.B.BusyCount = 1; + r.At(0); + r.B.OnHeartbeat(); // opens the episode; a live count holds it + r.At(0.4); + r.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 0, "held by the live busy count"); + FakeHost.UseDone(0); + r.At(0.5); + r.B.OnHeartbeat(); + Check.Eq(HealSelfCasts(), 1, "the UseDone frees it"); + string? line = r.Log("[HealLatency] 500 ms: health 40% under Top Off HP 60% (idle) -> Heal Self"); + Check.NotNull(line, "the episode line is logged with the delay and the line"); + Check.True(line!.Contains("busy count 400 ms"), $"and what held it: {line}"); + Check.Eq(r.B.BuffingLabel, BuffManager.LabelHealing, "while Heal Self is in flight the slot reads Healing"); + } + + // Drakkon, 2026-10-05 13:43:09: "[HealLatency] 5831 ms: health 12% under Emergency Heal At 30% + // (idle) -> Peerless Healing Kit; held by: login buff refresh 5737 ms". An engine hot reload + // made RynthAi wait for its login buff refresh, and the refresh held heals too. It holds buffs + // only now. (The registry read never succeeds here: server time 0, as before a time sync.) + private static void EmergencyBeatsLoginRefresh() + { + var r = new Rig(healthPct: 12, liveBuffsReady: false); + r.S.EmergencyHealAt = 30; + r.S.EnableBuffing = true; + r.At(0); + r.B.OnHeartbeat(); + Check.False(r.B.LiveBuffsReady, "the login refresh hasn't got a snapshot"); + Check.Eq(HealSelfCasts(), 1, "Heal Self goes out on the first heartbeat anyway"); + string? line = r.Log("[HealLatency]"); + Check.True(line != null && !line.Contains("login buff refresh"), $"the heal was not held by the refresh: {line}"); + + // Health fine: the refresh still holds every buff. + var q = new Rig(healthPct: 100, liveBuffsReady: false); + q.S.EnableBuffing = true; + q.S.SpellCastIntervalMs = 0; + q.B.OnHeartbeat(); + q.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 0, "no buff cast before the refresh is ready"); + Check.Eq(FakeHost.Uses.Count, 0, "and no buff item used"); + } + + private static void ActivityLabels() + { + Check.Eq(ActivityArbiter.DisplayLabel("Buffing", "Healing"), "Healing", "Buffing slot: its label"); + Check.Eq(ActivityArbiter.DisplayLabel("Buffing", ""), "Buffing", "no label: Buffing"); + Check.Eq(ActivityArbiter.DisplayLabel("Combat", "Healing"), "Combat", "anything else: the control string"); + Check.Eq(ActivityArbiter.DisplayLabel(null, "Healing"), "Default", "empty: Default (the dashboard shows Idle)"); + Check.Eq(ActivityArbiter.ToBotAction(BotActivity.Buffing), "Buffing", "the control string stays Buffing"); + + Check.Eq(BuffManager.VitalLabel("Heal Self"), "Healing", "Heal Self"); + Check.Eq(BuffManager.VitalLabel("Stamina to Health Self"), "Healing", "Stamina to Health"); + Check.Eq(BuffManager.VitalLabel("Stamina to Mana Self"), "Restoring mana", "Stamina to Mana"); + Check.Eq(BuffManager.VitalLabel("Revitalize Self"), "Restoring stamina", "Revitalize"); + + var mana = new Rig(healthPct: 100, manaPct: 10); + mana.S.GetManaAt = 50; mana.S.TopOffMana = 50; + Check.True(mana.B.CheckVitals(), "10% mana: Stamina to Mana is cast"); + Check.Eq(mana.B.BuffingLabel, "Restoring mana", "and the slot reads Restoring mana"); + + var heal = new Rig(healthPct: 40); + Check.Eq(heal.B.BuffingLabel, "Healing", "health under the line before anything ran: Healing"); + heal.B.MarkKitUsed(); + Check.Eq(heal.B.BuffingLabel, "Healing", "a healing kit in flight: Healing"); + var stam = new Rig(healthPct: 100); + stam.B.MarkKitUsed(stamina: true); + Check.Eq(stam.B.BuffingLabel, "Restoring stamina", "a stamina kit in flight: Restoring stamina"); + + var idle = new Rig(healthPct: 100); + Check.Eq(idle.B.BuffingLabel, "Buffing", "nothing vital going on: Buffing"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootAddItemTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootAddItemTests.cs index 41c5360..a15fbc6 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootAddItemTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootAddItemTests.cs @@ -27,6 +27,8 @@ internal static class LootAddItemTests { private const uint Player = 0x50000E01; private const uint Opal = 0x80271101, Taper = 0x80271102, Coin = 0x80271103; + private const uint Ring = 0x80271104, Stone = 0x80271105, Sceptre = 0x80271106; + private const uint ItemTypeJewelry = 0x8, ItemTypeCaster = 0x8000, ItemTypeManaStone = 0x80000, CurrentMana = 107; private const uint ItemTypeGem = 0x800, ItemTypeComponent = 0x1000; private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; @@ -39,6 +41,8 @@ internal static class LootAddItemTests r.Add("loot add: refusals (nothing selected, the same rule twice, no profile)", Refusals); r.Add("loot add: the popup's item_preview / item_add / item_close through the editor bridge", BridgePopupFlow); r.Add("loot add: unsaved edits in the Loot Editor block the add (nothing saved behind them)", BridgeRefusesUnderEdits); + r.Add("loot add: the popup says when RynthAi's built-in looting takes the item (Mana Tap, mana stones)", BuiltInReasons); + r.Add("loot: Mana Tap never loots a wand (ACE won't drain one, so it was kept for good)", ManaTapSkipsWands); } // ── World and plugin ────────────────────────────────────────────────────── @@ -48,8 +52,10 @@ internal static class LootAddItemTests public readonly RynthAiPlugin P = new(); public readonly LegacyUiSettings S = new(); public readonly WorldObjectCache Cache; + public readonly RynthCoreHost Host; - public Bot() + /// adds objects (after the standard ones, before the host); list their ids in . + public Bot(Action? world = null, params uint[] extra) { FakeHost.Reset(); FakeHost.Names[Player] = "Tester"; @@ -62,12 +68,14 @@ internal static class LootAddItemTests FakeHost.Ints[(Taper, 11)] = 100; // MaxStackSize FakeHost.Ints[(Taper, 12)] = 37; // StackCount FakeHost.Names[Coin] = "Pyreal"; + world?.Invoke(); var host = FakeHost.Create(Player); + Host = host; typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); Set("_dashboard", dash); - Cache = FakeHost.MakeCache(host, Player, new[] { Player, Opal, Taper, Coin }); + Cache = FakeHost.MakeCache(host, Player, new[] { Player, Opal, Taper, Coin }.Concat(extra)); Set("_objectCache", Cache); Set("_playerId", Player); Set("_charSkills", new CharacterSkills(host)); @@ -340,4 +348,113 @@ internal static class LootAddItemTests Check.Eq(File.ReadAllText(path), SellGems, "nothing saved"); Check.Eq(State(b).Rules[1].Name, "half-done", "the edit is still there, unsaved"); } + + // ── Built-in keeps (2026-10-05) ─────────────────────────────────────────── + + // A ring with 3,001 mana, an empty mana stone in the pack, tapping on at 2,500. + private static Bot TapWorld() + { + var bot = new Bot(() => + { + FakeHost.Names[Ring] = "Gold Ring"; + FakeHost.ItemTypes[Ring] = ItemTypeJewelry; + FakeHost.Ints[(Ring, CurrentMana)] = 3001; + FakeHost.Names[Stone] = "Mana Stone"; + FakeHost.ItemTypes[Stone] = ItemTypeManaStone; + FakeHost.Ints[(Stone, CurrentMana)] = 0; + FakeHost.Names[Sceptre] = "Piercing Sceptre"; + FakeHost.ItemTypes[Sceptre] = ItemTypeCaster; + FakeHost.Ints[(Sceptre, CurrentMana)] = 3001; + }, Ring, Stone, Sceptre); + bot.S.EnableManaTapping = true; + bot.S.ManaTapMinMana = 2500; + bot.Set("_manaStoneManager", new ManaStoneManager(bot.Host, bot.S, bot.Cache)); + return bot; + } + + /// The looter's own call (what [LootEval] logs): taken?, action tag, rule label. + private static (bool Taken, string Action, string Rule) LootEval(Bot bot, uint id) + { + MethodInfo m = typeof(RynthAiPlugin).GetMethod("ClassifyItemAgainstProfile", Any)!; + object?[] args = { bot.Item(id), bot.S, null, null, null }; + bool taken = (bool)m.Invoke(bot.P, args)!; + return (taken, (string)args[2]!, (string)args[4]!); + } + + private static void BuiltInReasons() + { + // Tom, 2026-10-05: "when I click on the wand it says no rule matches" - Mana Tap had + // looted it. The popup now says which built-in keep takes an item and where to change it. + var bot = TapWorld(); + string path = Temp("tap.utl", SellGems); + bot.S.CurrentLootPath = path; + LootEditorBridge b = bot.P.LootEditor; + FakeHost.Chat.Clear(); + + Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Ring, Seq = 1 } }); + LootEditItemDraft? d = State(b).ItemDraft; + Check.True(d != null && d.Ok, "draft: " + d?.Error); + const string tap = "No rule in the loot profile in use takes it, but RynthAi keeps it anyway: " + + "Mana Tap (3,001 mana >= 2,500), looted to drain into an empty mana stone - change in the Items panel, Mana Stone Tapping."; + Check.Eq(d?.BuiltInReason, tap, "the reason, with the numbers and where to change it"); + Check.True(d != null && d.OrderNote.Contains("at the end") && d.OrderNote.EndsWith(tap, StringComparison.Ordinal), + "OrderNote (what every engine's popup shows) carries it: " + d?.OrderNote); + Check.True(d != null && d.OrderNote.All(c => c < 128), "ASCII only (the popup's font)"); + + // The same function the looter runs: [LootEval] tags it [ManaTap]. + Check.Eq(bot.Get>("_pendingManaTapIds")?.Count, 0, "the preview recorded nothing"); + Check.False(bot.ChatText.Contains("Mana tap candidate"), "and said nothing in chat\n" + bot.ChatText); + var eval = LootEval(bot, Ring); + Check.True(eval.Taken && eval.Action == "ManaTap", "the looter takes it as [ManaTap]: " + eval.Action); + Check.True(eval.Rule.StartsWith("ManaTap (mana=3001", StringComparison.Ordinal), "rule label as in the log: " + eval.Rule); + + // A profile rule decides: no built-in reason. + Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Opal, Seq = 2 } }); + d = State(b).ItemDraft; + Check.Eq(d?.BuiltInReason, "", "the gem: rule 1 sells it, nothing built in"); + Check.True(d != null && d.OrderNote.Contains("just before rule 1 'Sell all gems'"), "order note as before: " + d?.OrderNote); + + // Mana stones are checked ahead of the profile. + Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Stone, Seq = 3 } }); + d = State(b).ItemDraft; + Check.True(d != null && d.BuiltInReason.StartsWith("RynthAi takes it before any loot profile rule: a mana stone,", StringComparison.Ordinal), + "mana stone: " + d?.BuiltInReason); + Check.True(d != null && d.BuiltInReason.Contains("of 5 kept - change in the Items panel"), "with the keep count"); + + // Under the threshold: not taken, nothing to explain. + bot.S.ManaTapMinMana = 5000; + Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Ring, Seq = 4 } }); + Check.Eq(State(b).ItemDraft?.BuiltInReason, "", "3,001 mana under a 5,000 threshold: no reason"); + bot.S.ManaTapMinMana = 2500; + + // Already in the pack after a Mana Tap pickup, quota full now: still says why it was taken. + bot.Get>("_pendingManaTapIds")!.Clear(); // (the LootEval call above approved it) + bot.Get("_manaStoneManager")!.MarkLootedForTap(unchecked((int)Ring)); + FakeHost.Ints[(Stone, CurrentMana)] = 500; // the only stone is charged: no free slot + Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Ring, Seq = 5 } }); + Check.Eq(State(b).ItemDraft?.BuiltInReason, + "No rule in the loot profile in use takes it, but RynthAi keeps it anyway: it was looted for Mana Tap, to drain into an empty mana stone - change in the Items panel, Mana Stone Tapping.", + "looted for tapping earlier"); + + // /ra loot add preview shows it in chat too. + FakeHost.Ints[(Stone, CurrentMana)] = 0; + FakeHost.SelectedItem = Ring; + FakeHost.Chat.Clear(); + bot.Ra("/ra loot add preview"); + Check.True(bot.ChatText.Contains("RynthAi keeps it anyway: it was looted for Mana Tap"), "/ra loot add preview says it\n" + bot.ChatText); + Check.Eq(File.ReadAllText(path), SellGems, "preview saves nothing"); + } + + private static void ManaTapSkipsWands() + { + var bot = TapWorld(); + bot.S.CurrentLootPath = Temp("wand.utl", SellGems); + var wand = LootEval(bot, Sceptre); + Check.False(wand.Taken, $"a 3,001-mana sceptre is left: [{wand.Action}] {wand.Rule}"); + Check.Eq(bot.Get>("_pendingManaTapIds")?.Count, 0, "not counted against the tap quota"); + var ring = LootEval(bot, Ring); + Check.True(ring.Taken && ring.Action == "ManaTap", "a ring with the same mana is still tapped: " + ring.Action); + Send(bot.P.LootEditor, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Sceptre, Seq = 1 } }); + Check.Eq(State(bot.P.LootEditor).ItemDraft?.BuiltInReason, "", "the popup has no built-in reason for the wand"); + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/OwnCorpseTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/OwnCorpseTests.cs new file mode 100644 index 0000000..18e3f3e --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/OwnCorpseTests.cs @@ -0,0 +1,461 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text.Json; +using System.Threading; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-10-05, owner: "It needs to loot your corpse and every item on it. If it's a setting default +// to true please." Recover My Corpse (LootOwnCorpse, default on) takes every item on your own death +// corpse whatever the loot profile and Loot From say; the death spot is remembered; Travel Back To +// My Corpse (TravelToOwnCorpse, default off) walks back with RynthNav (/rnav go via the broker). +internal static class OwnCorpseTests +{ + private const uint Player = 0x50000D01; + private const uint Corpse = 0x80261100; + private const uint Gem = 0x80261101; + private const uint Cloak = 0x80261102; + private const uint Coins = 0x80261103; + private const uint ItemTypeClothing = 0x4, ItemTypeMoney = 0x40, ItemTypeContainer = 0x200, ItemTypeGem = 0x800; + private const uint LongDescKey = 16; + private const string Me = "Dargoth Hera"; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("own corpse: recognised by exact name + 'Killed by' line, never a namesake or another player's", Identification); + r.Add("own corpse: every item is taken, the loot profile and Loot From ignored, then closed", RecoveredWhole); + r.Add("own corpse: another player's corpse with a similar name is left alone", SimilarNameUntouched); + r.Add("own corpse: Recover My Corpse off = the behaviour before (profile only, My Kills skips it)", SettingOffIsOldBehaviour); + r.Add("own corpse: beats a nearer corpse of your kill; a timeout retries it instead of writing it off", PriorityAndTimeout); + r.Add("own corpse: settings default on/off, an old profile loads on, saved and bridged", SettingsDefaults); + r.Add("own corpse: the death spot is remembered and said, server lines read", DeathSpotRemembered); + r.Add("own corpse: travel back walks with RynthNav, stops for combat, ends in loot range", TravelBack); + r.Add("own corpse: travel back refuses an indoor death and a missing RynthNav", TravelRefusals); + } + + // ── World ───────────────────────────────────────────────────────────── + + private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f); + + private static void World(string corpseName, string? longDesc, bool closeCalls = false) + { + FakeHost.Reset(); + FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal + FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData + FakeHost.CloseContainerCalls = closeCalls; + FakeHost.Names[Player] = Me; + FakeHost.Positions[Player] = Me0; + FakeHost.PlayerPose = Me0; + FakeHost.Names[Corpse] = corpseName; + FakeHost.ItemTypes[Corpse] = ItemTypeContainer; + if (longDesc != null) + FakeHost.Strings[(Corpse, LongDescKey)] = longDesc; + FakeHost.NotAttackable.Add(Corpse); + FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z); + Item(Gem, "Black Opal", ItemTypeGem); // the test profile keeps gems + Item(Cloak, "Faran Cloak", ItemTypeClothing); // ...and nothing else + Item(Coins, "Pyreal", ItemTypeMoney); + } + + private static void Item(uint id, string name, uint type) + { + FakeHost.Names[id] = name; + FakeHost.ItemTypes[id] = type; + FakeHost.Containers[id] = Corpse; // also installs GetObjectOwnershipInfo + FakeHost.Appraised.Add(id); + } + + private sealed class Bot + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new() + { + IsMacroRunning = true, + EnableLooting = true, + EnableCombat = false, + LootOwnership = 0, // My Kills Only + LootContentSettleMs = 0, + LootEmptyCorpseMs = 0, + StopLootingWhenPackFull = false, + }; + public readonly WorldObjectCache Cache; + + public Bot(RynthCoreHost host) + { + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + Set("_dashboard", dash); + Cache = new WorldObjectCache(host); + Cache.SetPlayerId(Player); + Set("_objectCache", Cache); + Set("_playerId", Player); + + string profile = Path.Combine(Program.TempRoot, "own-corpse-test.json"); + var p = new LootProfile { Name = "gems" }; + var rule = new LootRule { Name = "Gems", Action = LootAction.Keep }; + rule.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem }); + p.Rules.Add(rule); + p.Save(profile); + S.CurrentLootPath = profile; + } + + 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 object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a); + public bool HasLootWork() => (bool)Call("HasLootWork", S, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())!; + public void Tick(BotActivity act) + { + Set("_activity", act); + Call("TickCorpseOpening"); + } + public bool Completed => Get>("_completedCorpses").ContainsKey(unchecked((int)Corpse)); + public bool ShouldLoot(uint id) => (bool)Call("ShouldLootCorpse", Cache[unchecked((int)id)]!)!; + } + + private static Bot NewBot() + { + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.Cache.OnCreateObject(Corpse); + bot.Cache.Tick(); + return bot; + } + + /// Claims and opens the corpse, then ticks; each item the bot moves lands in the pack. + private static void LootToTheEnd(Bot bot, int maxTicks = 400) + { + bot.Tick(BotActivity.Looting); + Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened"); + foreach (uint id in new[] { Gem, Cloak, Coins }) + bot.Cache.OnCreateObject(id); + bot.Cache.Tick(); + if (FakeHost.CloseContainerCalls) FakeHost.GroundContainer = Corpse; + bot.P.OnViewObjectContents(Corpse); + + for (int i = 0; i < maxTicks && !bot.Completed; i++) + { + bot.Tick(BotActivity.Looting); + foreach (var m in FakeHost.ExternalMoves) + FakeHost.Containers[m.Id] = Player; // the server moved it + Thread.Sleep(10); + } + } + + private static string Moves() => string.Join(",", FakeHost.ExternalMoves.Select(m => $"{m.Id:X8}->{m.Target:X8}")); + + // ── Identification ──────────────────────────────────────────────────── + + private static void Identification() + { + OwnCorpseMatch M(string name, string me, string? desc) => RynthAiPlugin.MatchOwnDeathCorpse(name, me, desc); + Check.Eq(M("Corpse of Dargoth Hera", Me, "Killed by Drudge Skulker."), OwnCorpseMatch.Yes, "your name, killed by a monster"); + Check.Eq(M("Corpse of Dargoth Hera", Me, "Killed by misadventure."), OwnCorpseMatch.Yes, "a fall (misadventure)"); + Check.Eq(M("Corpse of Dargoth Hera", Me, null), OwnCorpseMatch.Pending, "no ID yet: wait for it"); + Check.Eq(M("Corpse of Dargoth Hera", Me, "Killed by Dargoth Hera."), OwnCorpseMatch.No, "a namesake you killed is not your death corpse"); + Check.Eq(M("Corpse of Dargoth Hera", Me, "A corpse."), OwnCorpseMatch.No, "no 'Killed by' line: not a death corpse"); + Check.Eq(M("Corpse of Dargoth Heras", Me, "Killed by Drudge."), OwnCorpseMatch.No, "a longer name"); + Check.Eq(M("Corpse of Dargoth Her", Me, "Killed by Drudge."), OwnCorpseMatch.No, "a shorter name"); + Check.Eq(M("Corpse of dargoth hera", Me, "Killed by Drudge."), OwnCorpseMatch.No, "exact case only"); + Check.Eq(M("Corpse of Dargoth Hera's Wolf", Me, "Killed by Drudge."), OwnCorpseMatch.No, "a pet's corpse"); + Check.Eq(M("Dargoth Hera's corpse", Me, "Killed by Drudge."), OwnCorpseMatch.No, "another naming"); + Check.Eq(M("Corpse of +Dargoth Hera", "+Dargoth Hera", "Killed by Drudge."), OwnCorpseMatch.Yes, "a GM's corpse carries the sigil, as the name does"); + Check.Eq(M("Corpse of Dargoth Hera", "+Dargoth Hera", "Killed by Drudge."), OwnCorpseMatch.No, "a GM never matches the plain name"); + Check.Eq(M("Corpse of Dargoth Hera", "", "Killed by Drudge."), OwnCorpseMatch.No, "no player name yet: nothing matches"); + } + + // ── Recovery ────────────────────────────────────────────────────────── + + private static void RecoveredWhole() + { + World("Corpse of " + Me, "Killed by Ancient Water Elemental.", closeCalls: true); + var bot = NewBot(); + Check.True(bot.ShouldLoot(Corpse), "My Kills Only, killed by a monster: still yours to recover"); + Check.True(bot.HasLootWork(), "looting wants the tick"); + + LootToTheEnd(bot); + Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "the gem (the profile keeps it) is taken: " + Moves()); + Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Cloak), "the cloak (no profile rule) is taken too: " + Moves()); + Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Coins), "and the pyreals: " + Moves()); + Check.True(FakeHost.ExternalMoves.All(m => m.Target == Player), "into the pack"); + Check.False(FakeHost.Uses.Any(u => u is Gem or Cloak or Coins), "never a use (a use can wield)"); + var first = FakeHost.ExternalMoves.Select(m => m.Id).ToList(); + Check.Eq(first.Distinct().Count(), 3, "one move per item (each confirmed before the next)"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[RynthAi] Own corpse: recovering 3 items.")), "says how many it recovers"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[RynthAi] Own corpse: recovered everything (3 items).")), "and that it got everything"); + Check.True(FakeHost.Chat.Any(l => l.Contains("recovered everything")), "in chat too"); + Check.False(FakeHost.Logs.Any(l => l.Contains("[LootEval]")), "no loot profile evaluation at all"); + Check.True(bot.Completed, "the corpse is completed"); + Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{Corpse:X8}", "and closed, once"); + Check.False(bot.Get("_currentLootItemIsSalvage"), "nothing queued for salvage"); + } + + private static void SimilarNameUntouched() + { + World("Corpse of " + Me + "s", "Killed by Ancient Water Elemental."); + var bot = NewBot(); + Check.False(bot.ShouldLoot(Corpse), "My Kills Only: a similar name is someone else's corpse"); + Check.False(bot.HasLootWork(), "nothing to loot"); + bot.Tick(BotActivity.Looting); + Check.Eq(bot.Get("_targetCorpseId"), 0, "not claimed"); + Check.False(FakeHost.Uses.Contains(Corpse), "not opened"); + + // Loot From All Corpses: looted by the profile only (the gem), never recovered whole. + World("Corpse of " + Me + "s", "Killed by Ancient Water Elemental."); + var all = NewBot(); + all.S.LootOwnership = 2; + LootToTheEnd(all); + Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "All Corpses: the profile's gem: " + Moves()); + Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Cloak || m.Id == Coins), "nothing else: " + Moves()); + Check.False(FakeHost.Logs.Any(l => l.Contains("Own corpse")), "never treated as your corpse"); + + // Your exact name but no ID yet: held, not looted by the profile meanwhile. + World("Corpse of " + Me, null); + var pending = NewBot(); + pending.S.LootOwnership = 2; + Check.False(pending.ShouldLoot(Corpse), "named like yours, unidentified: waits for its ID"); + Check.True(FakeHost.IdRequests.Contains(Corpse), "its ID is asked for"); + } + + private static void SettingOffIsOldBehaviour() + { + World("Corpse of " + Me, "Killed by Ancient Water Elemental."); + var bot = NewBot(); + bot.S.LootOwnCorpse = false; + Check.False(bot.ShouldLoot(Corpse), "My Kills Only: a monster killed you, so it is skipped (as before)"); + Check.False(bot.HasLootWork(), "nothing to loot"); + + World("Corpse of " + Me, "Killed by Ancient Water Elemental."); + var all = NewBot(); + all.S.LootOwnCorpse = false; + all.S.LootOwnership = 2; + LootToTheEnd(all); + Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "All Corpses: the profile's gem: " + Moves()); + Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Cloak || m.Id == Coins), "only what the profile keeps: " + Moves()); + Check.False(FakeHost.Logs.Any(l => l.Contains("Own corpse")), "no own-corpse recovery"); + } + + private static void PriorityAndTimeout() + { + const uint Kill = 0x80261200; + World("Corpse of " + Me, "Killed by Ancient Water Elemental."); + FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 4.0f, Me0.Y, Me0.Z); // yours, 4 m + FakeHost.Names[Kill] = "Corpse of Drudge Skulker"; + FakeHost.ItemTypes[Kill] = ItemTypeContainer; + FakeHost.Strings[(Kill, LongDescKey)] = $"Killed by {Me}."; + FakeHost.NotAttackable.Add(Kill); + FakeHost.Positions[Kill] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z); // your kill, 1 m + var bot = NewBot(); + bot.Cache.OnCreateObject(Kill); + bot.Cache.Tick(); + Check.True(bot.ShouldLoot(Kill), "your kill is lootable"); + bot.Tick(BotActivity.Looting); + Check.Eq(bot.Get("_targetCorpseId"), unchecked((int)Corpse), "your own corpse is claimed first, though further"); + + // It timed out once it was opened: not completed (that would leave your things for good). + bot.P.OnViewObjectContents(Corpse); + bot.Call("AbandonCurrentCorpse", Environment.TickCount64, "timeout"); + Check.False(bot.Completed, "an own corpse that timed out is not written off"); + Check.True(bot.Get>("_corpseCooldownUntil").ContainsKey(unchecked((int)Corpse)), "it is retried after a short wait"); + for (int i = 1; i < RynthAiPlugin.OwnCorpseMaxAbandons; i++) + { + bot.P.OnViewObjectContents(Corpse); + bot.Call("AbandonCurrentCorpse", Environment.TickCount64, "timeout"); + } + Check.True(bot.Completed, $"after {RynthAiPlugin.OwnCorpseMaxAbandons} timeouts it is given up"); + Check.True(FakeHost.Chat.Any(l => l.Contains("Own corpse: giving up")), "and it says so"); + } + + // ── Settings ────────────────────────────────────────────────────────── + + private static void SettingsDefaults() + { + Check.True(new LegacyUiSettings().LootOwnCorpse, "Recover My Corpse: on for a new profile"); + Check.False(new LegacyUiSettings().TravelToOwnCorpse, "Travel Back To My Corpse: off for a new profile"); + var old = JsonSerializer.Deserialize("{\"EnableLooting\":true,\"LootOwnership\":0}", RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(old != null && old.LootOwnCorpse, "a profile saved before the setting: on"); + Check.True(old != null && !old.TravelToOwnCorpse, "and travel off"); + var saved = JsonSerializer.Deserialize( + JsonSerializer.Serialize(new LegacyUiSettings { LootOwnCorpse = false, TravelToOwnCorpse = true }, RynthAiJsonContext.Default.LegacyUiSettings), + RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(saved != null && !saved.LootOwnCorpse && saved.TravelToOwnCorpse, "both are saved and loaded"); + + var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!; + var dst = new LegacyUiSettings(); + copy.Invoke(null, new object[] { new LegacyUiSettings { LootOwnCorpse = false, TravelToOwnCorpse = true }, dst }); + Check.True(!dst.LootOwnCorpse && dst.TravelToOwnCorpse, "a profile switch copies both"); + copy.Invoke(null, new object[] { old!, dst }); + Check.True(dst.LootOwnCorpse && !dst.TravelToOwnCorpse, "an old profile loads the defaults"); + + // The engine's Settings face: sent, and an engine without the fields leaves them alone. + var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(payload != null && payload.LootOwnCorpse == null && payload.TravelToOwnCorpse == null, "an older engine's payload has no value"); + var s = new LegacyUiSettings { LootOwnCorpse = false, TravelToOwnCorpse = true }; + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s); + typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)! + .SetValue(dash, new LegacyAdvancedSettingsUi(s)); + var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(sent != null && sent.LootOwnCorpse == false && sent.TravelToOwnCorpse == true, "sent to the engine face"); + dash.ApplySettingsJson("{\"PatrolOnLogin\":false}"); + Check.True(!s.LootOwnCorpse && s.TravelToOwnCorpse, "a save without the fields leaves them"); + dash.ApplySettingsJson("{\"LootOwnCorpse\":true,\"TravelToOwnCorpse\":false}"); + Check.True(s.LootOwnCorpse && !s.TravelToOwnCorpse, "a save with them sets them"); + } + + // ── Death spot ──────────────────────────────────────────────────────── + + private static Bot DieAt(double ns, double ew, uint? cell = null, bool broker = false, bool navLoaded = true) + { + World("Corpse of " + Me, "Killed by Ancient Water Elemental."); + FakeHost.PluginCommandCalls = broker; + FakeHost.PluginCommandDelivered = navLoaded; + FakeHost.SetNavPosition(ns, ew); + if (cell is uint c) FakeHost.PlayerPose = (c, 50f, 60f, -12f); + FakeHost.Positions[Player] = FakeHost.PlayerPose; + var bot = NewBot(); + var vitals = bot.Get("_vitals"); + vitals.MaxHealth = 100; + vitals.CurrentHealth = 0; + bot.Call("CheckPlayerDeath", bot.S); + return bot; + } + + private static void DeathSpotRemembered() + { + var bot = DieAt(42.10, 33.60); + var spot = bot.P.DeathSpot; + Check.True(spot != null, "the death spot is remembered"); + Check.True(spot != null && Math.Abs(spot.Ns - 42.10) < 0.01 && Math.Abs(spot.Ew - 33.60) < 0.01, $"at the death position ({spot?.Ns:0.00}, {spot?.Ew:0.00})"); + Check.True(spot != null && spot.Outdoors && spot.Cell == FakeHost.PlayerPose.Cell, "with its landblock and cell"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[RynthAi] Your corpse is at 42.10N, 33.60E (landblock 0x")), "logged: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("corpse is at")))); + Check.True(FakeHost.Chat.Any(l => l.Contains("Your corpse is at 42.10N, 33.60E")), "and said in chat"); + + bot.Call("OnOwnCorpseChat", "You have retained all your items. You do not need to recover your corpse!"); // OnChatWindowText hands chat lines here + Check.True(bot.P.DeathSpot!.NothingDropped, "the server's 'nothing dropped' line is noted"); + + var indoor = DieAt(0, 0, cell: 0x01D90123u); + Check.True(indoor.P.DeathSpot != null && !indoor.P.DeathSpot.Outdoors, "a dungeon death is remembered as indoors"); + Check.True(FakeHost.Logs.Any(l => l.Contains("Your corpse is at landblock 0x01D9, cell 0x0123")), "with landblock and cell"); + + // No position at the death: the server's line gives the spot. + World("Corpse of " + Me, "Killed by Ancient Water Elemental."); + var noPose = NewBot(); + noPose.Call("OnOwnCorpseChat", "Your corpse is located at (12.3S, 45.6W)."); // OnChatWindowText hands chat lines here + var fromChat = noPose.P.DeathSpot; + Check.True(fromChat != null && Math.Abs(fromChat.Ns + 12.3) < 0.001 && Math.Abs(fromChat.Ew + 45.6) < 0.001, "taken from the server's line"); + } + + // ── Travel back ─────────────────────────────────────────────────────── + + private static void BackdateIdle(Bot bot) => bot.Set("_travelIdleSince", Environment.TickCount64 - 10_000); + + private static void TravelBack() + { + var bot = DieAt(42.10, 33.60, broker: true); + bot.S.TravelToOwnCorpse = true; + + // Respawned at a lifestone ~100 m away. + FakeHost.SetNavPosition(42.50, 33.60); + FakeHost.Positions[Player] = FakeHost.PlayerPose; + bot.Call("OnRespawnedForOwnCorpse"); + Check.True(bot.Get("_ownCorpseTravelManual") == false, "started by the respawn, not by hand"); + Check.True((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(bot.P)!, "RynthAi's own route is parked meanwhile"); + + bot.Set("_activity", BotActivity.Idle); + bot.Call("TickOwnCorpseTravel", bot.S); + Check.Eq(FakeHost.PluginCommands.Count, 0, "waits a moment of quiet before walking"); + BackdateIdle(bot); + bot.Call("TickOwnCorpseTravel", bot.S); + Check.True(FakeHost.PluginCommands.Contains(("RynthNav", "rnav", "go 42.10N, 33.60E")), + "walks with RynthNav: " + string.Join(" | ", FakeHost.PluginCommands)); + + // A monster: RynthAi fights, the walk stops. + bot.Set("_activity", BotActivity.Combat); + bot.Call("TickOwnCorpseTravel", bot.S); + Check.Eq(FakeHost.PluginCommands.Last(), ("RynthNav", "rnav", "stop"), "the walk stops for combat"); + int count = FakeHost.PluginCommands.Count; + bot.Call("TickOwnCorpseTravel", bot.S); + Check.Eq(FakeHost.PluginCommands.Count, count, "one stop, not one per tick"); + Check.True(FakeHost.Logs.Any(l => l.Contains("travel paused for Combat")), "logged"); + + // Fight over: walk on. + bot.Set("_activity", BotActivity.Idle); + bot.Call("TickOwnCorpseTravel", bot.S); + BackdateIdle(bot); + bot.Call("TickOwnCorpseTravel", bot.S); + Check.Eq(FakeHost.PluginCommands.Last(), ("RynthNav", "rnav", "go 42.10N, 33.60E"), "resumes after the fight"); + + // Near the spot, the corpse is in loot range: travel ends, looting takes over. + FakeHost.SetNavPosition(42.10, 33.61); // ~2.4 m east... 0.01 coord = 2.4 m + FakeHost.Positions[Player] = FakeHost.PlayerPose; + var p = FakeHost.PlayerPose; + FakeHost.Positions[Corpse] = (p.Cell, p.X + 1.0f, p.Y, p.Z); + bot.Cache.OnCreateObject(Corpse); + bot.Cache.Tick(); + bot.Call("TickOwnCorpseTravel", bot.S); + Check.Eq(FakeHost.PluginCommands.Last(), ("RynthNav", "rnav", "stop"), "the walk stops"); + Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(bot.P)!, "travel is over"); + Check.True(FakeHost.Logs.Any(l => l.Contains("travel back ended: your corpse") && l.Contains("is in loot range")), "says why"); + Check.True(bot.HasLootWork(), "and looting wants the tick for it"); + + // Timeout with no progress. + var stuck = DieAt(42.10, 33.60, broker: true); + stuck.S.TravelToOwnCorpse = true; + FakeHost.SetNavPosition(42.50, 33.60); + FakeHost.Positions[Player] = FakeHost.PlayerPose; + stuck.Call("OnRespawnedForOwnCorpse"); + stuck.Set("_activity", BotActivity.Idle); + BackdateIdle(stuck); + stuck.Call("TickOwnCorpseTravel", stuck.S); + stuck.Call("TickOwnCorpseTravel", stuck.S); // first distance sample + stuck.Set("_travelBestAt", Environment.TickCount64 - RynthAiPlugin.OwnCorpseTravelNoProgressMs - 1000); + stuck.Call("TickOwnCorpseTravel", stuck.S); + Check.True(FakeHost.Logs.Any(l => l.Contains("travel back ended: gave up: no closer")), "no progress: gives up and says so"); + Check.Eq(FakeHost.PluginCommands.Last(), ("RynthNav", "rnav", "stop"), "and stops RynthNav"); + + // Nothing dropped: no trip. + var none = DieAt(42.10, 33.60); + none.Call("OnOwnCorpseChat", "You have retained all your items. You do not need to recover your corpse!"); // OnChatWindowText hands chat lines here + none.S.TravelToOwnCorpse = true; + none.Call("OnRespawnedForOwnCorpse"); + Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(none.P)!, "nothing dropped: no trip back"); + + // Setting off (the default): no trip. + var off = DieAt(42.10, 33.60); + off.Call("OnRespawnedForOwnCorpse"); + Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(off.P)!, "Travel Back off: no trip back"); + } + + private static void TravelRefusals() + { + var indoor = DieAt(0, 0, cell: 0x01D90123u, broker: true); + indoor.S.TravelToOwnCorpse = true; + indoor.Call("OnRespawnedForOwnCorpse"); + Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(indoor.P)!, "an indoor death: no trip"); + Check.True(FakeHost.Chat.Any(l => l.Contains("you died indoors") && l.Contains("only works outdoors")), "and it says why"); + + var noNav = DieAt(42.10, 33.60, broker: true, navLoaded: false); // RynthNav not loaded + noNav.S.TravelToOwnCorpse = true; + FakeHost.SetNavPosition(42.50, 33.60); + FakeHost.Positions[Player] = FakeHost.PlayerPose; + noNav.Call("OnRespawnedForOwnCorpse"); + noNav.Set("_activity", BotActivity.Idle); + BackdateIdle(noNav); + noNav.Call("TickOwnCorpseTravel", noNav.S); + Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(noNav.P)!, "RynthNav missing: the trip ends"); + Check.True(FakeHost.Chat.Any(l => l.Contains("RynthNav isn't loaded")), "and it says why"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs index c8a9668..8a81edb 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs @@ -24,6 +24,46 @@ internal static class VitalsTests r.Add("vitals: profiles without the Stamina to Health keys load today's 30 / 20", StaminaToHealthDefaults); r.Add("vitals: after a kit, nothing else heals until the kit's result line lands", KitResultWait); r.Add("vitals: low health wins the arbiter even on a busy tick; backs off when nothing can heal", HealthWinsArbiter); + r.Add("vitals: 'You're too busy!' paces vital casts, and a long streak stops the character once", TooBusyVitals); + // Drakkon's death, 2026-10-05 13:43:20 (ops\overnight\2026-10-05-death-fixes.md). + r.Add("vitals: a hot reload's login refresh trusts its first read; a real login waits for two equal reads", HotReloadRefresh); + r.Add("vitals: RynthAi tells the engine a reload is unsafe while engaged, under a heal line or casting", ReloadBlockerReport); + } + + // Drakkon, 2026-10-05: stuck in the cast gesture, AC answering "You're too busy!" every + // 0.4 s. The buff path backed off; Stamina to Mana didn't, and re-cast on every + // SpellCastIntervalMs tick until the player moved. Mana/stamina casts now wait out the + // backoff, and a streak of refusals sends one StopCompletely (what moving did). + private static void TooBusyVitals() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.StopCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + var host = FakeHost.Create(); + var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false }; + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 10 }; + var b = new BuffManager(host, s, sm, vitals); + b.SetCharacterSkills(skills); + + Check.True(b.CheckVitals(), "10% mana: Stamina to Mana is cast"); + Check.Eq(FakeHost.Casts.Count, 1, "one cast"); + b.OnChatWindowText("You're too busy!", 26); + Check.True(b.CheckVitals(), "too busy: the vital tick still yields (no potion, no buff)"); + Check.Eq(FakeHost.Casts.Count, 1, "but nothing is re-cast inside the backoff"); + + for (int i = 0; i < 3; i++) b.OnChatWindowText("You're too busy!", 26); + Check.Eq(FakeHost.Stops, 1, "4 refusals in a row: one StopCompletely to clear the stuck gesture"); + for (int i = 0; i < 4; i++) b.OnChatWindowText("You're too busy!", 26); + Check.Eq(FakeHost.Stops, 1, "only once per streak"); } // 2026-10-04, "nav and looting have priority over healing, almost dying in packs": the @@ -172,6 +212,80 @@ internal static class VitalsTests Check.False(BuffManager.StaminaToHealthAllowed(d, 31, 99), "predicate: 31 on defaults"); } + private static BuffManager RefreshRig(out LegacyUiSettings s, out PlayerVitalsCache vitals, int healthPct = 100) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + var host = FakeHost.Create(); + s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 30, StaminaToHealthAt = 0, + GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false }; + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = (uint)healthPct, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, vitals); + b.SetCharacterSkills(skills); + return b; + } + + // The engine reload at 13:42:55 looked like a login to RynthAi: the buff refresh waited 5.8 s + // for two equal reads of a registry that was already complete (the client never left the world). + private static void HotReloadRefresh() + { + int strength = SpellTable.Named("Strength Self I").First().Id; + int endurance = SpellTable.Named("Endurance Self I").First().Id; + + var b = RefreshRig(out _, out _); + FakeHost.ServerTime = 1000; + FakeHost.Enchantments.Add(((uint)strength, 1000 + 3600)); + FakeHost.Enchantments.Add(((uint)endurance, 1000 + 3600)); + b.CarriedOverSession = true; + b.OnHeartbeat(); + Check.True(b.LiveBuffsReady, "hot reload: ready on the first successful read"); + Check.True(FakeHost.Logs.Any(l => l.Contains("login refresh ready") && l.Contains("hot reload")), "and the line says why"); + + var real = RefreshRig(out _, out _); + FakeHost.ServerTime = 1000; + FakeHost.Enchantments.Add(((uint)strength, 1000 + 3600)); + real.OnHeartbeat(); + Check.False(real.LiveBuffsReady, "a real login: one read isn't trusted (the registry may still be streaming)"); + System.Threading.Thread.Sleep(1100); + real.OnHeartbeat(); + Check.True(real.LiveBuffsReady, "two equal reads a second apart: ready"); + } + + private static void ReloadBlockerReport() + { + // The pure text. + Check.Eq(ReloadSafety.Reason(false, true, "Emergency Heal At", 12, 30, "Heal Self V"), "", "macro off: never blocks a reload"); + Check.Eq(ReloadSafety.Reason(true, false, "", 100, 0, ""), "", "nothing going on: safe"); + Check.Eq(ReloadSafety.Reason(true, true, "", 100, 0, ""), "in combat (a monster engaged)", "a monster engaged"); + Check.Eq(ReloadSafety.Reason(true, false, "Emergency Heal At", 12, 30, ""), "in combat (health 12% under Emergency Heal At 30%)", "under a heal line"); + Check.Eq(ReloadSafety.Reason(true, false, "", 100, 0, "Strength Self VI"), "casting ('Strength Self VI' awaiting its result)", "a buff in flight"); + Check.Eq(ReloadSafety.Reason(true, true, "Heal At", 45, 60, "Heal Self V"), + "in combat (a monster engaged, health 45% under Heal At 60%, 'Heal Self V' awaiting its result)", "all three"); + + // What BuffManager feeds it. + var b = RefreshRig(out _, out var v, healthPct: 50); + b.MarkLiveBuffsReadyForTests(); + Check.Eq(b.HealLineNow(out int hp, out int lineValue), "Top Off HP", "50% under Top Off HP (no monster: the idle line)"); + Check.Eq((hp, lineValue), (50, 60), "with the health and the line"); + Check.Eq(b.CastInFlightName, "", "nothing cast yet"); + Check.True(b.CheckVitals(), "Heal Self is cast"); + int healCat = SpellTable.Named("Heal Self I").First().Category; + Check.True(b.CastInFlightName.Length > 0 && SpellTable.Named(b.CastInFlightName).Any(row => row.Category == healCat), + $"the cast in flight is a Heal Self tier: {b.CastInFlightName}"); + v.CurrentHealth = 100; + Check.Eq(b.HealLineNow(out _, out _), "", "full health: no line"); + v.MaxHealth = 0; + Check.Eq(b.HealLineNow(out _, out _), "", "vitals not read yet: no line"); + } + private static void StaminaToHealthDefaults() { var old = JsonSerializer.Deserialize("{\"EmergencyHealAt\":25}", RynthAiJsonContext.Default.LegacyUiSettings); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs index 2441e6d..4c16db6 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs @@ -37,8 +37,13 @@ internal static class WeaponTests r.Add("element choice: a wand always casts its own element (rule, Damage tab, no match)", ChoiceWandCastsOwn); r.Add("element choice: elements the character can't cast are skipped", ChoiceCastable); r.Add("slayer: beats the weakness and the Monsters rule's damage type", SlayerBeatsWeaknessAndRule); - r.Add("slayer: a weapon the player picked (for the monster or on the DEFAULT row) beats it", SlayerVsDamageTab); - r.Add("slayer: other creature types, no bonus and other kinds are ignored", SlayerNonMatching); + r.Add("slayer: only this monster's own Damage tab weapon beats it, not the DEFAULT row's", SlayerVsDamageTab); + r.Add("slayer (owner's rule 2026-10-05): a Slash slayer beats a Pierce weapon the monster is weaker to", SlayerBeatsLowerResist); + r.Add("slayer: this monster's own pick that is a slayer is used, labelled", SlayerManualPickIsSlayer); + r.Add("slayer: the Damage tab's learned best never beats it", SlayerBeatsLearnedBest); + r.Add("slayer: bonus not sent (ACE never sends float 138) still slays, ranked below a known bonus", SlayerBonusUnknown); + r.Add("slayer: creature type from the world-database table before the monster's appraisal", SlayerTypeFromTable); + r.Add("slayer: other creature types, an x1 bonus and other kinds are ignored", SlayerNonMatching); r.Add("slayer: the bigger bonus wins, then the element order, then the hand", SlayerOrder); r.Add("slayer: creature type unknown, the old choice", SlayerUnknownType); r.Add("slayer: the element follows the chosen weapon", SlayerElement); @@ -376,12 +381,18 @@ internal static class WeaponTests var list = new List { Wand(1, "Fire"), Slayer(2, CombatMode.Magic, "Cold", Olthoi, 2.0) }; var pick = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 1, creatureType: Olthoi); - Check.Eq(pick.WeaponId, 1, "the Damage tab's weapon for this monster is the player's pick: it wins"); + Check.Eq(pick.WeaponId, 1, "a non-slayer set on this monster's own Damage tab row: the player's pick wins"); Check.Eq(pick.Source, "Damage tab", "source"); + Check.Eq(pick.Element, "Fire", "and casts its own element"); var def = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 1, fixedSource: "Damage tab default", creatureType: Olthoi, fixedIsDefault: true); - Check.Eq(def.WeaponId, 1, "the Damage tab DEFAULT row's weapon is a player pick too: it beats a matching slayer"); + Check.Eq(def.WeaponId, 2, "the DEFAULT row's non-slayer weapon: a slayer of this monster still wins"); + Check.Eq(def.Source, "slayer (Olthoi x2)", "source"); + + var defRule = WeaponPlanner.Choose(list, "Fire", weak, All, fixedWeaponId: 1, fixedSource: "Damage tab default", + creatureType: Olthoi, fixedIsDefault: true); + Check.Eq(defRule.WeaponId, 2, "the DEFAULT row's weapon and a Monsters rule of Fire: still the slayer"); var defNoSlayer = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 1, fixedSource: "Damage tab default", creatureType: Undead, fixedIsDefault: true); @@ -389,6 +400,109 @@ internal static class WeaponTests Check.Eq(defNoSlayer.Source, "Damage tab default", "source"); } + private static void SlayerBeatsLowerResist() + { + // Owner, 2026-10-05: an Olthoi slayer that does Slash is picked before a Pierce weapon + // even when the Olthoi resists Pierce less, because the slayer outperforms it. + var weak = Rank(("Pierce", 0.86), ("Slash", 0.67), ("Fire", 0.65)); + var spear = new WeaponCandidate(1, "Spear", CombatMode.Melee, "Pierce", "", true); + var list = new List { spear, Slayer(2, CombatMode.Melee, "Slash", Olthoi, 2.0) }; + + var p = WeaponPlanner.Choose(list, "", weak, All, creatureType: Olthoi); + Check.Eq(p.WeaponId, 2, "the Slash Olthoi slayer, not the Pierce spear in hand"); + Check.Eq(p.Element, "Slash", "it hits with Slash"); + Check.Eq(p.Source, "slayer (Olthoi x2)", "source"); + + var r = WeaponPlanner.Choose(list, "Pierce", weak, All, creatureType: Olthoi); + Check.Eq(r.WeaponId, 2, "a Monsters rule of Pierce: still the slayer"); + + Check.Eq(WeaponPlanner.Choose(list, "", weak, All, creatureType: Undead).WeaponId, 1, + "not an Olthoi: the Pierce spear (weakness)"); + } + + private static void SlayerManualPickIsSlayer() + { + var weak = Rank(("Fire", 1.4), ("Cold", 1.0)); + var list = new List + { + Wand(1, "Fire"), + Slayer(2, CombatMode.Magic, "Acid", Olthoi, 3.0), + Slayer(3, CombatMode.Magic, "Cold", Olthoi, 2.0), + }; + var p = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 3, creatureType: Olthoi); + Check.Eq(p.WeaponId, 3, "this monster's own pick is a slayer: that one, though another has a bigger bonus"); + Check.Eq(p.Element, "Cold", "its own element"); + Check.Eq(p.Source, "Damage tab, slayer (Olthoi x2)", "source names the pick and the slayer"); + + // The DEFAULT row's pick is a slayer: step 2 finds it like any listed slayer (biggest bonus first). + var d = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 3, fixedSource: "Damage tab default", + creatureType: Olthoi, fixedIsDefault: true); + Check.Eq(d.WeaponId, 2, "DEFAULT row's slayer pick: the best slayer of the monster (x3)"); + } + + private static void SlayerBeatsLearnedBest() + { + var weak = Rank(("Fire", 1.4), ("Cold", 1.0)); + var list = new List { Wand(1, "Fire"), Slayer(2, CombatMode.Magic, "Cold", Olthoi, 2.0) }; + Check.Eq(WeaponPlanner.Choose(list, "", weak, All, learnedBestId: 1, creatureType: Olthoi).WeaponId, 2, + "weakness known, the learned best is the Fire wand: the slayer"); + Check.Eq(WeaponPlanner.Choose(list, "", null, All, learnedBestId: 1, creatureType: Olthoi).WeaponId, 2, + "weakness unknown, learned best: the slayer"); + Check.Eq(WeaponPlanner.Choose(list, "", null, All, learnedBestId: 1, creatureType: 0).WeaponId, 1, + "creature type unknown: the learned best, as before"); + + // Through CombatManager: the store's learned best (GetBestWeapon) doesn't beat a listed slayer. + var rig = new Rig(990002, "Olthoi Learner"); + rig.S.ItemRules.Add(new() { Id = unchecked((int)FireWand), Name = "Fire Wand", Element = "Fire", ElementSource = "icon" }); + for (int i = 0; i < 4; i++) rig.Store.RecordHit(FireWand, 990002, "Olthoi Learner", "Fire", 7, 300, false); + Check.Eq(rig.Store.GetBestWeapon(990002), FireWand, "the Damage tab learned the fire wand as best"); + rig.C.InHandOverride = () => unchecked((int)FireWand); + FakeHost.Ints[(ListedWand, 166)] = Olthoi; + FakeHost.Ints[(Monster, 2)] = Olthoi; + Check.Eq(unchecked((uint)rig.C.PlanFor(rig.Target, null).WeaponId), ListedWand, "the slayer wand, not the learned best"); + } + + private static void SlayerBonusUnknown() + { + var weak = Rank(("Fire", 1.4), ("Cold", 1.0)); + var unknown = Slayer(2, CombatMode.Magic, "Cold", Olthoi, 0); + Check.True(WeaponPlanner.Slays(unknown, Olthoi), "SlayerCreatureType sent, bonus not: it slays"); + Check.False(WeaponPlanner.Slays(unknown, Undead), "not another type"); + var p = WeaponPlanner.Choose(new List { Wand(1, "Fire", inHand: true), unknown }, "", weak, All, creatureType: Olthoi); + Check.Eq(p.WeaponId, 2, "the slayer with no bonus sent beats the Fire wand the monster is weak to"); + Check.Eq(p.Source, "slayer (Olthoi)", "source has no multiplier"); + + var both = new List { unknown, Slayer(3, CombatMode.Magic, "Acid", Olthoi, 2.0) }; + Check.Eq(WeaponPlanner.Choose(both, "", weak, All, creatureType: Olthoi).WeaponId, 3, + "a known x2 bonus ranks above one not sent"); + var two = new List { Slayer(4, CombatMode.Magic, "Acid", Olthoi, 0), unknown }; + Check.Eq(WeaponPlanner.Choose(two, "", weak, All, creatureType: Olthoi).WeaponId, 2, + "two with no bonus sent: the element order (Cold before Acid)"); + } + + private static void SlayerTypeFromTable() + { + // wcid 3 "Olthoi Worker" is type 1 (Olthoi) in creature_resists.tsv. The monster isn't + // appraised (no int 2) and the creature store doesn't know it: the table answers. + var rig = new Rig(3, "Olthoi Worker"); + rig.S.ItemRules.Add(new() { Id = unchecked((int)FireWand), Name = "Fire Wand", Element = "Fire", ElementSource = "icon" }); + rig.C.InHandOverride = () => unchecked((int)FireWand); + FakeHost.Ints[(ListedWand, 166)] = Olthoi; // no float 138, as ACE sends it + Check.Eq(CreatureWeakness.TableCreatureType(3, "Olthoi Worker"), Olthoi, "table: wcid 3 is an Olthoi"); + Check.Eq(CreatureWeakness.TableCreatureType(3, "Not An Olthoi"), 0, "a custom monster reusing the wcid: no type"); + Check.Eq(rig.C.CreatureTypeOf(3, "Olthoi Worker"), Olthoi, "CreatureTypeOf falls back to the table"); + var p = rig.C.PlanFor(rig.Target, null); + Check.Eq(unchecked((uint)p.WeaponId), ListedWand, "first sight of an Olthoi Worker: the slayer wand"); + Check.Eq(p.Source, "slayer (Olthoi)", "source"); + Check.True(FakeHost.Logs.Any(l => l.Contains("slays Olthoi (bonus not sent)")), "the weapon's slayer is logged"); + + // A listed slayer and a monster of unknown type: logged once, no slayer step. + var odd = new WorldObject(unchecked((int)Monster) + 5, "Custom Thing", AcObjectClass.Monster); + FakeHost.Wcids[Monster + 5] = 990005; + Check.Eq(unchecked((uint)rig.C.PlanFor(odd, null).WeaponId), FireWand, "type unknown: the weakness choice"); + Check.True(FakeHost.Logs.Any(l => l.Contains("creature type not known yet")), "and it is logged"); + } + private static void SlayerNonMatching() { var weak = Rank(("Fire", 1.4), ("Cold", 1.0)); @@ -396,7 +510,6 @@ internal static class WeaponTests { Wand(1, "Fire"), Slayer(2, CombatMode.Magic, "Cold", Undead, 2.0), // another type - Slayer(3, CombatMode.Magic, "Cold", Olthoi, 0), // no bonus property (ACE needs both) Slayer(4, CombatMode.Magic, "Cold", Olthoi, 1.0), // x1: no gain Slayer(5, CombatMode.Melee, "Slash", Olthoi, 3.0), // not the main kind (magic) }; @@ -455,6 +568,9 @@ internal static class WeaponTests Check.Eq(p.Source, "weak to Fire (test)", "source"); var r = WeaponPlanner.Choose(list, "Cold", weak, All, creatureType: 0); Check.Eq(r.Source, "Monsters rule Cold", "and the rule as before"); + var d = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 1, fixedSource: "Damage tab default", creatureType: 0, fixedIsDefault: true); + Check.Eq(d.WeaponId, 1, "type unknown and a DEFAULT row weapon: the default, as before"); + Check.Eq(d.Source, "Damage tab default", "source"); } private static void SlayerElement() @@ -488,6 +604,9 @@ internal static class WeaponTests var before = rig.C.PlanFor(rig.Target, null); Check.Eq(unchecked((uint)before.WeaponId), FireWand, "no slayer properties yet: the Fire wand (weakness)"); + Check.Eq(rig.C.SlayerOf(unchecked((int)ListedWand)), (0, 0.0), "no int 166: no slayer"); + FakeHost.Ints[(ListedWand, 166)] = Olthoi; + Check.Eq(rig.C.SlayerOf(unchecked((int)ListedWand)), (Olthoi, 0.0), "int 166 alone (what ACE sends): a slayer, bonus not known"); FakeHost.Ints[(ListedWand, 166)] = Olthoi; FakeHost.Doubles[(ListedWand, 138)] = 2.0;