diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs new file mode 100644 index 0000000..7124cd9 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs @@ -0,0 +1,266 @@ +// ============================================================================ +// RynthSuite - Combat/BuffManager.HpFailsafe.cs +// The HP failsafe: at or under Emergency Heal At, a character whose heals keep +// failing (refused, fizzled, never sent, or out-healed) must not sit and die. +// +// Measured by health, not by counting heal attempts: a round of FailsafeRoundMs +// with no rise of FailsafeRiseMinPct counts as a failed round (whatever the +// reason: a stuck cast, 'too busy', no mana, no kits). +// 1. FailsafeRoundsToBreak failed rounds: ActionPacer.ForceBreak (a jump; on +// ACE's fast tick it fails the cast in progress, Player.HandleActionJump). +// Starts are held until landed, then the vitals step heals again. +// 2. FailsafeRoundsToRecall more failed rounds after the break: recall to the +// lifestone ("/lifestone", ACE GameAction TeleToLifestone) when +// HpFailsafeRecall is on. The macro is switched off first, because ACE +// cancels the recall when the character moves during its animation and +// refuses it while busy (Player_Location.HandleActionTeleToLifestone). +// 3. No " is recalling to the lifestone." after RecallMaxSends tries +// (ACE refuses the recall while busy, under a PK timer or with recalls +// disabled, which is just the stuck state this is for): the macro is +// switched back on, so the heals and kits run again, and the failsafe +// re-arms; the next recall waits RecallCooldownMs. A failed recall must not +// leave the character standing at low health with nothing running. Only a +// macro the failsafe itself stopped is switched back on, never past a VTank +// yield (MayRestartMacro), and a death drops the pending recall (the player's +// Stop Macro On Death stands). +// Health back over the line (or 100%) ends the episode. Nothing counts in portal space. +// ============================================================================ + +using System; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +public partial class BuffManager +{ + internal const double FailsafeRoundMs = 2500; + internal const int FailsafeRoundsToBreak = 3; + internal const int FailsafeRoundsToRecall = 3; + // A rise this large (health %) means a heal landed; natural regeneration is smaller. + private const int FailsafeRiseMinPct = 3; + // The recall goes this long after the macro stop (the stop edge runs on the next tick), + // and is sent again this often, a few times, until our "is recalling to the lifestone" is seen. + private const double RecallFirstDelayMs = 600; + private const double RecallResendMs = 1500; + private const int RecallMaxSends = 3; + /// After a recall that never started, the next one waits this long (the heals run meanwhile). + internal const double RecallCooldownMs = 30_000; + internal const string RecallCommand = "/lifestone"; + + private bool _fsActive; + private DateTime _fsRoundStart; + private int _fsLowHp; + private int _fsFailedRounds; + private bool _fsBroken; + private bool _fsRecallLogged; + private DateTime _fsRecallNotBefore = DateTime.MinValue; + + private bool _recallPending; + private bool _recallSeen; + private int _recallSends; + private DateTime _recallNextAt; + + /// Set by the plugin: the rest of a /ra stop (nav stop, pause cancel) for the recall. + internal Action? MacroStopForRecall { get; set; } + /// Set by the plugin: false when the macro must not be started now (VTank yield). Null = may. + internal Func? MayRestartMacro { get; set; } + + // The macro is off because the failsafe stopped it for a recall (only then does it switch it back on). + private bool _macroStoppedByFailsafe; + private bool _recallNameLogged; + + internal int HpFailsafeBreaks { get; private set; } + internal int HpFailsafeRecalls { get; private set; } + internal int HpFailsafeRecallsFailed { get; private set; } + + private bool Portaling() + { + try { return _host.HasIsPortaling && _host.IsPortaling(); } catch { return false; } + } + + /// Once per heartbeat while the macro runs, before the pacing gate. + private void TickHpFailsafe() + { + int at = _settings.EmergencyHealAt; + if (at <= 0 || _vitals.MaxHealth <= 0 || _recallPending || Portaling()) { ResetHpFailsafe(); return; } + int hp = _vitals.HealthPct; + DateTime now = Now; + if (hp > at || hp >= 100) + { + if (_fsActive && (_fsFailedRounds > 0 || _fsBroken)) + _host.Log($"[Vitals] HP failsafe: health back to {hp}% (over Emergency Heal At {at}%)."); + ResetHpFailsafe(); + return; + } + if (!_fsActive) + { + _fsActive = true; + _fsRoundStart = now; + _fsLowHp = hp; + _fsFailedRounds = 0; + _fsBroken = false; + return; + } + if (hp >= _fsLowHp + FailsafeRiseMinPct) + { + // A heal landed: the heals work, start counting again from here. + _fsLowHp = hp; + _fsRoundStart = now; + _fsFailedRounds = 0; + return; + } + if (hp < _fsLowHp) _fsLowHp = hp; + if ((now - _fsRoundStart).TotalMilliseconds < FailsafeRoundMs) return; + + _fsFailedRounds++; + _fsRoundStart = now; + double failedSec = _fsFailedRounds * FailsafeRoundMs / 1000.0; + if (!_fsBroken) + { + if (_fsFailedRounds < FailsafeRoundsToBreak) return; + string why = $"HP failsafe: health {hp}% at or under Emergency Heal At {at}%, no heal landed in {failedSec:0.#} s"; + bool jumped = ActionPacer.ForceBreak(_host, why); + if (jumped) HpFailsafeBreaks++; + _host.Log($"[Vitals] {why}: {(jumped ? "breaking the cast with a jump, then healing again" : "no jump available (or one under way), healing again")}."); + _fsBroken = true; + _fsFailedRounds = 0; + return; + } + if (_fsFailedRounds < FailsafeRoundsToRecall) return; + if (!_settings.HpFailsafeRecall) + { + if (!_fsRecallLogged) + { + _fsRecallLogged = true; + _host.Log($"[Vitals] HP failsafe: health {hp}%, heals still failing {failedSec:0.#} s after the break; HP Failsafe Recall is off, no recall."); + } + return; + } + if (now < _fsRecallNotBefore) + { + // The last recall never started: heal on and break again, the next recall after the cooldown. + _fsBroken = false; + _fsFailedRounds = 0; + return; + } + StartFailsafeRecall(now, hp, failedSec); + } + + private void ResetHpFailsafe() + { + _fsActive = false; + _fsFailedRounds = 0; + _fsBroken = false; + _fsRecallLogged = false; + } + + private void StartFailsafeRecall(DateTime now, int hp, double failedSec) + { + HpFailsafeRecalls++; + _settings.IsMacroRunning = false; + _macroStoppedByFailsafe = true; + _recallNameLogged = false; + MacroStopForRecall?.Invoke(); + _recallPending = true; + _recallSeen = false; + _recallSends = 0; + _recallNextAt = now.AddMilliseconds(RecallFirstDelayMs); + string line = $"HP failsafe: health {hp}%, heals still failing {failedSec:0.#} s after the break: macro stopped, recalling to the lifestone."; + _host.Log("[Vitals] " + line); + _host.WriteToChat("[RynthAi] " + line, 2); + ResetHpFailsafe(); + } + + /// Every heartbeat, macro running or not: sends a pending recall, or gives up on it. + private void TickFailsafeRecall() + { + if (!_recallPending) return; + DateTime now = Now; + if (_recallSeen) + { + _recallPending = false; + _macroStoppedByFailsafe = false; + _host.Log("[Vitals] HP failsafe: the recall started."); + return; + } + if (_vitals.MaxHealth > 0 && _vitals.CurrentHealth == 0) + { + CancelPendingRecall("dead"); + return; + } + if (_settings.IsMacroRunning) + { + // Someone switched the macro back on: their call, the recall is dropped. + _recallPending = false; + _macroStoppedByFailsafe = false; + _host.Log("[Vitals] HP failsafe: the macro was started again; the recall is dropped."); + return; + } + if (now < _recallNextAt) return; + if (_recallSends >= RecallMaxSends || !_host.HasInvokeChatParser) + { + _recallPending = false; + HpFailsafeRecallsFailed++; + _fsRecallNotBefore = now.AddMilliseconds(RecallCooldownMs); + string why = _host.HasInvokeChatParser + ? $"no recall seen after {_recallSends} tries of {RecallCommand} (refused: busy, a PK timer or recalls disabled)" + : "this engine has no chat parser, so no recall"; + string what; + if (!_macroStoppedByFailsafe) what = "the macro stays as it is"; + else if (MayRestartMacro != null && !MayRestartMacro()) what = "the macro stays off (VTank yield)"; + else + { + _settings.IsMacroRunning = true; // the heals and kits run again; the failsafe re-arms + what = "macro back on to keep healing"; + } + _macroStoppedByFailsafe = false; + string line = $"HP failsafe: {why}: {what}; next recall in {RecallCooldownMs / 1000:0} s at the earliest."; + _host.Log("[Vitals] " + line); + _host.WriteToChat("[RynthAi] " + line, 2); + return; + } + _host.InvokeChatParser(RecallCommand); + _recallSends++; + _recallNextAt = now.AddMilliseconds(RecallResendMs); + } + + /// + /// The plugin's death hold (and a 0-health read): a pending recall is dropped and the macro is + /// left off, so nothing re-sends /lifestone or restarts the macro after the respawn. + /// + internal void CancelPendingRecall(string why) + { + if (!_recallPending) return; + _recallPending = false; + _macroStoppedByFailsafe = false; + _host.Log($"[Vitals] HP failsafe: the pending recall is dropped ({why}); the macro stays off."); + } + + /// OnChatWindowText: " is recalling to the lifestone." while a recall is pending. + private void ObserveRecallLine(string lower) + { + if (!_recallPending || !lower.Contains("is recalling to the lifestone")) return; + string me = ""; + try + { + uint id = unchecked((uint)_host.GetPlayerId()); + if (id != 0 && _host.HasGetObjectName && _host.TryGetObjectName(id, out string n)) me = n ?? ""; + } + catch { me = ""; } + // Someone else's recall ("Bob is recalling to the lifestone.") is not ours. The chat layer + // can drop a line's first letter ("ou cast ..."), so the name may arrive without it. + if (me.Length > 0) + { + string who = lower.Substring(0, lower.IndexOf(" is recalling to the lifestone", StringComparison.Ordinal)).Trim(); + string mine = me.ToLowerInvariant(); + bool ours = who == mine || (who.Length == mine.Length - 1 && who.Length > 0 && mine.EndsWith(who, StringComparison.Ordinal)); + if (!ours) return; + } + else if (!_recallNameLogged) + { + _recallNameLogged = true; + _host.Log("[Vitals] HP failsafe: our name could not be read; any 'is recalling to the lifestone' line is taken as ours."); + } + _recallSeen = true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.RecoveryRetry.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.RecoveryRetry.cs new file mode 100644 index 0000000..a2d048a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.RecoveryRetry.cs @@ -0,0 +1,184 @@ +// ============================================================================ +// RynthSuite - Combat/BuffManager.RecoveryRetry.cs +// Fast retry of the recovery vitals (Heal Self, Stamina to Health, Revitalize, +// Stamina to Mana) after the server's "not enough mana" answer. +// +// ACE (origin/master, Creature_Magic.GetManaCost) rolls Mana Conversion on every +// cast attempt: a trained caster pays between the full cost and 1 mana. The roll +// and the check run before the windup (Player_Magic.CalculateManaUsage), so a +// refusal costs nothing: no mana, no busy period, no recoil, only UseDone 0x401. +// At low mana the cast goes through on a good roll, so trying again soon is the +// way to get it off. Before this, the refusal rested the spell's family (LowManaHealRestSec). +// +// Bounds (the refusal-spam crash class, see the "too busy" handler): the retry +// gap is never under RecoveryRetryMinMs, at most RecoveryRetryMaxPerSecond +// recovery casts go out in any second while an episode is open, and an episode +// stops after RecoveryRetryMaxRefusals mana refusals in a row (any recovery +// spell); the refused family then rests as before (a vital LowManaHealRestSec, 2 s). +// ============================================================================ + +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +public partial class BuffManager +{ + internal const int RecoveryRetryMinMs = 200; + internal const int RecoveryRetryMaxMs = 5000; + internal const int RecoveryRetryMaxPerSecond = 5; + internal const int RecoveryRetryMaxRefusals = 20; + // A refusal this long after the last one starts a new episode; an open episode with no refusal + // for this long ends. Above the slowest retry gap (the setting's 5000 ms maximum) with room for + // the pacing in between, so a slow setting never ends its own episode between two retries. + internal const double RecoveryEpisodeStaleMs = RecoveryRetryMaxMs + 2000; + // Stamina to Mana is attempted only above this stamina % (the CheckVitals and mana floor gates). + private const int RecoveryMinStaminaToConvert = 15; + + private bool _recoveryOpen; + private DateTime _recoveryStartedAt; + private DateTime _recoveryLastRefusalAt; + private int _recoveryRefusals; + private readonly Dictionary _recoveryNextAt = new(); + private readonly List _recoveryNames = new(); + // Recovery casts sent (any time), for the per-second ceiling. + private readonly Queue _recoveryAttempts = new(); + // The base name of the pending vital ("Stamina to Mana Self"...), set by CastVital. + private string _pendingVitalBase = ""; + + /// Recovery casts held by the per-second ceiling (tests, status). + internal int RecoveryRateHolds { get; private set; } + /// The last episode summary line (tests, status). + internal string LastRecoverySummary { get; private set; } = ""; + /// True while a fast-retry episode is open (tests). + internal bool RecoveryRetryOpen => _recoveryOpen; + + internal static bool IsRecoveryVital(string baseName) => + baseName is "Heal Self" or "Stamina to Health Self" or "Revitalize Self" or "Stamina to Mana Self"; + + private int RecoveryRetryMs => Math.Clamp(_settings.RecoveryRetryMs, RecoveryRetryMinMs, RecoveryRetryMaxMs); + + /// + /// Why a fast retry can't help now, or "" when it can. Untrained Mana Conversion pays the full + /// cost every time (GetManaCost returns the base cost), so a retry would only be refused again; + /// trained, the least a cast can cost is 1 mana. + /// + private string RecoveryRetryBlocked(string baseName) + { + if (!IsSkillUsable(AcSkillType.ManaConversion)) return "Mana Conversion not trained (no cost roll)"; + if (_vitals.MaxMana > 0 && _vitals.CurrentMana < 1) return "no mana at all"; + if (baseName == "Stamina to Mana Self" && _vitals.StaminaPct <= RecoveryMinStaminaToConvert) + return $"stamina {_vitals.StaminaPct}% too low to convert"; + if (baseName == "Stamina to Health Self" && _vitals.StaminaPct <= _settings.StaminaToHealthMinStamina) + return $"stamina {_vitals.StaminaPct}% too low to convert"; + return ""; + } + + /// + /// "Not enough mana" for the pending cast. Returns true when it was a recovery vital that will be + /// retried soon (the caller then skips the family rest); false leaves the old handling. + /// + private bool OnRecoveryManaRefusal(SpellInfo? pending) + { + if (pending == null || _pendingSpellId != _pendingVitalSpellId || !IsRecoveryVital(_pendingVitalBase)) + return false; + DateTime now = Now; + if (_recoveryOpen && (now - _recoveryLastRefusalAt).TotalMilliseconds > RecoveryEpisodeStaleMs) + EndRecoveryEpisode(now, "no refusal for a while", success: false, ""); + if (!_recoveryOpen) + { + _recoveryOpen = true; + _recoveryStartedAt = now; + _recoveryRefusals = 0; + _recoveryNames.Clear(); + } + _recoveryRefusals++; + _recoveryLastRefusalAt = now; + if (!_recoveryNames.Contains(pending.Name)) _recoveryNames.Add(pending.Name); + string blocked = RecoveryRetryBlocked(_pendingVitalBase); + if (blocked.Length > 0) + { + EndRecoveryEpisode(now, blocked, success: false, ""); + return false; + } + if (_recoveryRefusals >= RecoveryRetryMaxRefusals) + { + EndRecoveryEpisode(now, $"{_recoveryRefusals} refusals in a row", success: false, ""); + return false; + } + _recoveryNextAt[pending.Family] = now.AddMilliseconds(RecoveryRetryMs); + if (_recoveryRefusals == 1) + _host.Log($"[Vitals] {pending.Name}: not enough mana (mana {_vitals.CurrentMana}); retrying every {RecoveryRetryMs} ms for a Mana Conversion roll (at most {RecoveryRetryMaxPerSecond}/s, {RecoveryRetryMaxRefusals} refusals)."); + return true; + } + + /// A result line for : a retried cast went through. + private void OnRecoveryCastResult(int family, string name) + { + if (_recoveryOpen && _recoveryNextAt.ContainsKey(family)) + EndRecoveryEpisode(Now, "", success: true, name); + } + + private void EndRecoveryEpisode(DateTime now, string why, bool success, string name) + { + if (!_recoveryOpen) return; + _recoveryOpen = false; + _recoveryNextAt.Clear(); + double ms = (now - _recoveryStartedAt).TotalMilliseconds; + string names = string.Join(", ", _recoveryNames); + LastRecoverySummary = success + ? $"[Vitals] {name} went through after {_recoveryRefusals + 1} attempts ({_recoveryRefusals} refused for mana: {names}) in {ms:0} ms." + : $"[Vitals] stopped retrying {names} after {_recoveryRefusals} mana refusals in {ms:0} ms ({why})."; + _host.Log(LastRecoverySummary); + } + + /// + /// Ends an episode with no refusal for RecoveryEpisodeStaleMs (the cast went through unseen, the + /// vital is no longer needed, or something else took over), so a stale one never keeps letting + /// casts past Spell Interval. Once per heartbeat. + /// + private void ExpireRecoveryEpisode() + { + if (_recoveryOpen && (Now - _recoveryLastRefusalAt).TotalMilliseconds > RecoveryEpisodeStaleMs) + EndRecoveryEpisode(Now, $"no refusal for {RecoveryEpisodeStaleMs / 1000:0} s", success: false, ""); + } + + /// + /// The cast interval gate lets a due recovery retry through: the retry gap (RecoveryRetryMs) + /// replaces Spell Interval for it, and the per-second ceiling still applies in CastVital. + /// + private bool RecoveryRetryDue() + { + if (!_recoveryOpen) return false; + DateTime now = Now; + foreach (var at in _recoveryNextAt.Values) + if (now >= at) return true; + return false; + } + + /// CastVital's gate for a recovery vital while an episode is open: "" to cast, else why it waits. + private string RecoveryRetryHolds(int family) + { + if (!_recoveryOpen) return ""; + DateTime now = Now; + if (_recoveryNextAt.TryGetValue(family, out DateTime next) && now < next) + return $"retrying after a mana refusal in {(next - now).TotalMilliseconds:0} ms"; + while (_recoveryAttempts.Count > 0 && (now - _recoveryAttempts.Peek()).TotalMilliseconds >= 1000) + _recoveryAttempts.Dequeue(); + if (_recoveryAttempts.Count >= RecoveryRetryMaxPerSecond) + { + RecoveryRateHolds++; + return $"{RecoveryRetryMaxPerSecond} recovery casts in the last second"; + } + return ""; + } + + private void NoteRecoveryAttempt() + { + DateTime now = Now; + while (_recoveryAttempts.Count > 0 && (now - _recoveryAttempts.Peek()).TotalMilliseconds >= 1000) + _recoveryAttempts.Dequeue(); + _recoveryAttempts.Enqueue(now); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.ScriptHook.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.ScriptHook.cs index 015b297..28cab05 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.ScriptHook.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.ScriptHook.cs @@ -61,8 +61,9 @@ public partial class BuffManager // than RynthAi's own heals' (Vitality Siphon: 2.42-2.75 s after the incantation, 2026-10-10 // log), or never (a resisted or dead target), and an early nudge steps the character. if (sent && _cast.Current is { } sentCast && sentCast.SpellId == (int)spell) sentCast.Script = true; + if (sent) ActionPacer.MarkScriptCast((int)spell); // the stuck-cast breaker gives it the same room // Handled: cast, or a swap step to Magic mode is in flight (the next check asks again). - CombatHook.Cast(slot, sent ? spell : 0, sent ? target : 0); + CombatHook.Cast(slot, sent ? spell : 0, sent ? target : 0, sent ? ActionPacer.LastCastSeqAtSend : -1); if (sent) _host.Log($"[RynthAi] Vitals: script heal id={spell} '{name}' at 0x{target:X8} (owner '{CombatHook.Owner}')."); return true; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 0bcf5e5..f8d05be 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -1124,11 +1124,18 @@ public partial class BuffManager : IDisposable LogPostCastDiff(diag); } + // A recall the HP failsafe asked for goes out after the macro stop (BuffManager.HpFailsafe.cs). + TickFailsafeRecall(); + if (!_settings.IsMacroRunning) return; // Close casts the server reports finished, and say once when one is being held open. PollCastTracker(); + // Heals failing at Emergency Heal At: break the cast, then recall (BuffManager.HpFailsafe.cs). + TickHpFailsafe(); + if (!_settings.IsMacroRunning) return; + // A Magic stance we asked for: watch the client's mode every tick (see ObserveStance). ObserveStance(); @@ -1381,7 +1388,11 @@ public partial class BuffManager : IDisposable } } - if ((DateTime.Now - _lastCastAttempt).TotalMilliseconds < _settings.SpellCastIntervalMs) + // A due recovery retry (BuffManager.RecoveryRetry.cs) gets past Spell Interval, for the vitals + // step only: the buffs after it still wait (intervalHeld below). A stale episode ends first. + ExpireRecoveryEpisode(); + bool intervalHeld = (DateTime.Now - _lastCastAttempt).TotalMilliseconds < _settings.SpellCastIntervalMs; + if (intervalHeld && !RecoveryRetryDue()) { Hold("cast interval"); return; @@ -1433,6 +1444,13 @@ public partial class BuffManager : IDisposable return; } + // Only a recovery retry got past Spell Interval; nothing else goes inside it. + if (intervalHeld) + { + Hold("cast interval"); + return; + } + // The login refresh above held buffs only: the heal had its turn, the buffs wait. if (buffsHeldForRefresh) { @@ -1972,6 +1990,9 @@ public partial class BuffManager : IDisposable && _buffFailCooldownUntil.TryGetValue(family, out DateTime coolUntil) && DateTime.Now < coolUntil) return VitalNo($"parked for {(coolUntil - DateTime.Now).TotalSeconds:0} s more after a refusal or no-show"); + // A recovery vital retried after a mana refusal: its retry gap and the per-second ceiling. + if (IsRecoveryVital(what) && RecoveryRetryHolds(family) is { Length: > 0 } recoveryWhy) + return VitalNo(recoveryWhy); if (CurrentCombatMode != CombatMode.Magic && DateTime.Now < _vitalSwapBlockedUntil) return VitalNo("wand swap blocked, retrying shortly"); bool urgentHeal = label == LabelHealing && HealIsUrgent(_vitals.HealthPct, _vitals.StaminaPct); @@ -1989,6 +2010,7 @@ public partial class BuffManager : IDisposable _pendingSpellId = spellId; _pendingVitalSpellId = spellId; // instant: confirmed by chat, never by the registry _pendingVitalLabel = label; + _pendingVitalBase = what; bool castOk = _host.CastSpellFor(targetId, spellId, "Buff", SpellTableStub.GetById(spellId)?.Name ?? what); _lastCastAttempt = DateTime.Now; @@ -1998,6 +2020,7 @@ public partial class BuffManager : IDisposable return VitalNo($"the client refused the cast (spell {spellId})"); } sent = true; + if (IsRecoveryVital(what)) NoteRecoveryAttempt(); NoteCastIssued(spellId); if (_pendingVitalLabel == LabelMana) _manaStarvedLogged = false; // the next starved spell logs again if (_pendingVitalLabel == LabelHealing) @@ -3554,6 +3577,7 @@ public partial class BuffManager : IDisposable public void OnChatWindowText(string text, int chatType) { string lower = text.ToLowerInvariant(); + ObserveRecallLine(lower); // Diagnostic: log every chat seen while waiting on a cast confirmation, @@ -3723,6 +3747,15 @@ public partial class BuffManager : IDisposable _lastManaRefusalAt = DateTime.Now; // a combat cast's refusal too: ManaStarved with costs unknown if (_pendingSpellId == 0) return; var pendingSpell = SpellTableStub.GetById(_pendingSpellId); + // A recovery vital tries again soon for a better Mana Conversion roll (RecoveryRetry). + if (OnRecoveryManaRefusal(pendingSpell)) + { + _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} - not enough mana; retrying in {RecoveryRetryMs} ms, buffs {LowManaBuffPauseMs / 1000:0}s."); + _pendingSpellId = 0; + _lowManaPauseUntil = DateTime.Now.AddMilliseconds(LowManaBuffPauseMs); + _onCastResolved?.Invoke("not enough mana"); + return; + } double restSec = LowManaFamilyRestSec; if (pendingSpell != null) { @@ -3867,6 +3900,7 @@ public partial class BuffManager : IDisposable // which never fires for instant vitals (Heal/Revitalize/Stamina to Mana), so // two slow confirmations hours apart parked Heal Self for 30 minutes. _silentNoShowCounts.Remove(spellInfo.Family); + OnRecoveryCastResult(spellInfo.Family, spellInfo.Name); NoteCastAccepted(); // AC accepted a cast — end any too-busy backoff // Chat-authoritative record: only NOW (AC confirmed "you cast X"). // Item/armor enchants live in _itemSpellTimers (what IsBuffActive diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.ScriptHook.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.ScriptHook.cs index d178a14..6a6ef98 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.ScriptHook.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.ScriptHook.cs @@ -74,7 +74,7 @@ public partial class CombatManager CombatHook.Reject(slot, "the client refused the cast", s => _host.Log(s)); return false; } - CombatHook.Cast(slot, spell, castTarget); + CombatHook.Cast(slot, spell, castTarget, ActionPacer.LastCastSeqAtSend); return true; } @@ -134,6 +134,7 @@ public partial class CombatManager try { ok = _host.CastSpellFor(castTarget, spellId, "Combat", name + " (script)"); } catch { ok = false; } if (!ok) return false; + ActionPacer.MarkScriptCast(spellId); MarkCombatCastIssued(); StartCastChatTrace(spellId, unchecked((int)castTarget)); // the server's answers, logged as for RynthAi's own casts @@ -154,6 +155,7 @@ public partial class CombatManager _pendingOffensiveSpellId = spellId; _pendingOffensiveCastAt = DateTime.Now; _pendingOffensiveTargetId = activeTargetId; + NoteOffensiveSeq(); } // As the native block: a throw here must not fail the cast that already went out (the // slot would stay Decided and the same answer be cast again). diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index 5875041..972ec2f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -1120,6 +1120,29 @@ public partial class CombatManager : IDisposable // chat-confirmation handler can record the cast against the right target // for blacklist judgement — even if activeTargetId has since changed. private int _pendingOffensiveTargetId = 0; + // The UseDone count at the pending offensive cast's send, and its answer (-1 = not seen yet). + private int _pendingOffensiveSeqAtSend; + private long _pendingOffensiveErr = -1; + /// Casts the server refused 'too busy' that were kept out of the no-damage count (tests, status). + internal int RefusedCastsNotJudged { get; private set; } + + private void NoteOffensiveSeq() + { + _pendingOffensiveSeqAtSend = _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0; + _pendingOffensiveErr = -1; + } + + /// The first UseDone after the pending offensive cast's send is its answer. + private void ObserveOffensiveAnswer() + { + if (_pendingOffensiveErr >= 0 || !_host.HasUseDoneSeq) return; + try + { + if (_host.TryGetLastUseDone(out int seq, out uint err) && seq == _pendingOffensiveSeqAtSend + 1) + _pendingOffensiveErr = err; + } + catch { } + } private const double OFFENSIVE_NOCHAT_TIMEOUT_MS = 5000.0; // ACE doesn't emit "You cast X" chat for offensive war magic, so we infer // a successful server cast by NEGATION: if no "You're too busy!" arrives @@ -2007,9 +2030,24 @@ public partial class CombatManager : IDisposable if (_pendingOffensiveSpellId == 0) return; if (_pendingOffensiveTargetId == 0) return; if (_pendingOffensiveCastAt == DateTime.MinValue) return; + ObserveOffensiveAnswer(); if ((DateTime.Now - _pendingOffensiveCastAt).TotalMilliseconds < OffensiveRefusalWindowMs) return; + // A refusal is not a cast (in a client log, three healthy targets were blacklisted 'after 3 + // no-damage casts' whose casts had all come back UseDone 0x1D): + // the answer 0x1D, or no answer yet while the server is taken as busy, is not judged. + bool refused = _pendingOffensiveErr == ActionPacer.TooBusyErr || (_pendingOffensiveErr < 0 && ActionPacer.ServerBusy); + if (refused) + { + RefusedCastsNotJudged++; + _host.Log($"[Blacklist] cast at 0x{(uint)_pendingOffensiveTargetId:X8} {(_pendingOffensiveErr >= 0 ? "refused 'too busy' (UseDone 0x1D)" : "unanswered while the server is busy")}: not counted as a no-damage cast"); + _pendingOffensiveSpellId = 0; + _pendingOffensiveTargetId = 0; + _pendingOffensiveCastAt = DateTime.MinValue; + return; + } + // Refusal window passed without a "too busy" — the server accepted // the gesture. Queue this cast for blacklist judgement. int targetId = _pendingOffensiveTargetId; @@ -2948,12 +2986,13 @@ public partial class CombatManager : IDisposable // wield, attack or cast while the server is still answering the last action (a kit, a corpse // use, a buff, the last stance change). On ACE a mode change cancels a pending use's walk // and fails a cast in progress; that interleaving began every stuck-use stall on record. - // Melee/missile attack repeats skip the animation gate (gestureGate false): the server swings + // Melee/missile attack repeats skip the animation and settle gates and the 'too busy' latch (ACE + // sends no UseDone for a swing, so a latch set by a refused pickup would starve them): the server swings // on its own timers, a swing can't land inside a use's server turn because the use above holds // every attack until it is answered, and waiting for each swing animation would cost DPS. A // stance change still waits (ChangeCombatModeFor), and so does everything in peace/magic. bool attackRepeat = CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile; - if (!ActionPacer.MayStart(_host, "Combat", HealNeed.None, out _, gestureGate: !attackRepeat)) + if (!ActionPacer.MayStart(_host, "Combat", HealNeed.None, out _, animationGate: !attackRepeat, settleGate: !attackRepeat, attackRepeat: attackRepeat)) { LastCombatSkipReason = "server-answering"; // D4 record-only _tickWait = CombatLatencyTracker.Wait.Busy; @@ -5532,6 +5571,7 @@ public partial class CombatManager : IDisposable _pendingOffensiveSpellId = offensiveSpellId; _pendingOffensiveCastAt = DateTime.Now; _pendingOffensiveTargetId = activeTargetId; + NoteOffensiveSeq(); // Tag this cast's weapon + element + tier so the pushed damage event // can be attributed to it, count it for casts-to-kill learning, then diff --git a/Plugins/RynthCore.Plugin.RynthAi/CombatHookInterface.cs b/Plugins/RynthCore.Plugin.RynthAi/CombatHookInterface.cs index 6547f52..82cfe96 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CombatHookInterface.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CombatHookInterface.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using RynthCore.Plugin.Shared; @@ -35,6 +36,27 @@ internal static class CombatHook // The last decision consumed (handed back in the next request). public uint LastSeq, LastSpell, LastTarget; public long LastAtMs; + // The cast in flight (PendingSpell 0 = none), with the UseDone count at its send, and the + // most recent resolved cast with its final answer (ResolvedErr -1 = none could be read). + public uint PendingSeq, PendingSpell, PendingTarget; + public long PendingAtMs; + public int PendingSeqAtSend = -1; + // The UseDone count that answers it: one more than its send count, or than the answer of the + // cast still in flight before it (both kinds, in send order); -1 = unknown (time limit only). + public int PendingExpectSeq = -1; + public uint ResolvedSeq, ResolvedSpell, ResolvedTarget; + public long ResolvedAtMs; + public int ResolvedErr = -1; + + /// The cast in flight is done: its answer (-1 = none read). + public void Resolve(int err) + { + if (PendingSpell == 0) return; + ResolvedSeq = PendingSeq; ResolvedSpell = PendingSpell; ResolvedTarget = PendingTarget; + ResolvedAtMs = PendingAtMs; ResolvedErr = err; + PendingSeq = PendingSpell = PendingTarget = 0; PendingAtMs = 0; PendingSeqAtSend = -1; PendingExpectSeq = -1; + InFlight.Remove(this); + } // Counters for /ra combat and the tests. public int Opened, Casts, Declines, Timeouts, Rejects; @@ -46,6 +68,9 @@ internal static class CombatHook Open = false; Decided = false; Request = default; DecidedSpell = DecidedTarget = DecidedFlags = 0; LastSeq = LastSpell = LastTarget = 0; LastAtMs = 0; + PendingSeq = PendingSpell = PendingTarget = 0; PendingAtMs = 0; PendingSeqAtSend = -1; PendingExpectSeq = -1; + InFlight.Remove(this); + ResolvedSeq = ResolvedSpell = ResolvedTarget = 0; ResolvedAtMs = 0; ResolvedErr = -1; Opened = Casts = Declines = Timeouts = Rejects = 0; LastTimeoutLogMs = LastRejectLogMs = long.MinValue; } @@ -55,6 +80,39 @@ internal static class CombatHook internal static Func Clock = static () => Environment.TickCount64; internal static long Now => Clock(); + /// + /// The last UseDone (count, error), or null when the engine can't say: RynthAi sets it at Init. A + /// cast's answer is the first UseDone after its send (ctx.last.err). + /// + internal static Func<(int Seq, uint Err)?>? LastUseDone; + + // The casts in flight of both kinds, in send order: the UseDones answer them in that order. + private static readonly List InFlight = new(2); + + /// + /// Resolves the casts in flight (each tick, at Poll, and before the next cast goes out), in send + /// order: each one's answer is the UseDone after its send, or after the answer of the cast sent + /// before it (an attack and a heal both in flight). A later count with that one unseen, or no + /// UseDone within RynthAiCombat.ResolveTimeoutMs, resolves it with no answer (-1). + /// + public static void ObserveUseDone() + { + if (InFlight.Count == 0) return; + (int Seq, uint Err)? last; + try { last = LastUseDone?.Invoke(); } catch { last = null; } + long now = Now; + for (int i = 0; i < InFlight.Count;) + { + Slot s = InFlight[i]; + if (last is { } u && s.PendingExpectSeq >= 0 && u.Seq >= s.PendingExpectSeq) + { + s.Resolve(u.Seq == s.PendingExpectSeq ? unchecked((int)u.Err) : -1); // removes it + continue; + } + if (now - s.PendingAtMs >= RynthAiCombat.ResolveTimeoutMs) { s.Resolve(-1); continue; } + i++; + } + } /// A timeout is logged at most this often per kind. internal const long TimeoutLogIntervalMs = 60_000; private const long RejectLogIntervalMs = 5_000; @@ -143,6 +201,16 @@ internal static class CombatHook request.LastSpell = s.LastSpell; request.LastTarget = s.LastTarget; request.LastAtMs = s.LastAtMs; + ObserveUseDone(); + request.ResolvedSeq = s.ResolvedSeq; + request.ResolvedSpell = s.ResolvedSpell; + request.ResolvedTarget = s.ResolvedTarget; + request.ResolvedAtMs = s.ResolvedAtMs; + request.ResolvedErr = s.ResolvedSpell != 0 ? s.ResolvedErr : -1; + request.PendingSeq = s.PendingSeq; + request.PendingSpell = s.PendingSpell; + request.PendingTarget = s.PendingTarget; + request.PendingAtMs = s.PendingAtMs; return true; } @@ -232,10 +300,14 @@ internal static class CombatHook return Outcome.Wait; } - /// The decided spell went out (or was waited on): the request is done. - public static void Cast(Slot slot, uint spellId, uint targetId) + /// + /// The decided spell went out (or was waited on): the request is done. + /// is the UseDone count read just before the send (ActionPacer.LastCastSeqAtSend); -1 reads the + /// last UseDone now instead. + /// + public static void Cast(Slot slot, uint spellId, uint targetId, int seqAtSend = -1) { - Consume(slot, spellId, targetId); + Consume(slot, spellId, targetId, seqAtSend); if (spellId != 0) slot.Casts++; // 0: handled without a cast (a wand swap step in flight) } @@ -253,12 +325,31 @@ internal static class CombatHook } } - private static void Consume(Slot slot, uint spellId, uint targetId) + private static void Consume(Slot slot, uint spellId, uint targetId, int seqAtSend = -1) { slot.LastSeq = slot.Request.Seq; slot.LastSpell = spellId; slot.LastTarget = targetId; slot.LastAtMs = Now; + if (spellId != 0) + { + // The cast before it resolves first (its answer if one came, else none). + ObserveUseDone(); + slot.Resolve(-1); + slot.PendingSeq = slot.Request.Seq; + slot.PendingSpell = spellId; + slot.PendingTarget = targetId; + slot.PendingAtMs = slot.LastAtMs; + // The count read before the send: a UseDone that lands between the send and this call is + // then still this cast's answer, not taken as the baseline. + if (seqAtSend >= 0) slot.PendingSeqAtSend = seqAtSend; + else try { slot.PendingSeqAtSend = LastUseDone?.Invoke()?.Seq ?? -1; } catch { slot.PendingSeqAtSend = -1; } + Slot? before = InFlight.Count > 0 ? InFlight[InFlight.Count - 1] : null; + if (slot.PendingSeqAtSend < 0) slot.PendingExpectSeq = -1; + else if (before != null && before.PendingExpectSeq < 0) slot.PendingExpectSeq = -1; // can't tell which answer is whose + else slot.PendingExpectSeq = Math.Max(slot.PendingSeqAtSend, before?.PendingExpectSeq ?? int.MinValue) + 1; + InFlight.Add(slot); + } slot.Open = false; slot.Decided = false; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index 0ffb9f2..66e8efe 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -507,6 +507,32 @@ internal sealed class LegacyAdvancedSettingsUi "Lower = faster buff chains. 400ms is a good balance.\n" + "Below 200ms may cause fizzles or dropped casts on laggy servers."); + ImGui.SetNextItemWidth(180); + ImGui.SliderInt("Stuck Cast Break (ms)", ref _settings.StuckCastBreakMs, 0, 20000); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip( + "The longest a cast may stay unanswered before it is broken\n" + + "with a jump (the server then fails the cast). It fires sooner,\n" + + "about 2 s past the spell's normal cycle, when that is shorter.\n" + + "After a 'too busy' answer nothing is cast until the server answers.\n" + + "0 = never break."); + + ImGui.SetNextItemWidth(180); + ImGui.SliderInt("Recovery Retry (ms)", ref _settings.RecoveryRetryMs, 200, 5000); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip( + "Heal Self, Stamina to Health, Revitalize and Stamina to Mana refused\n" + + "for 'not enough mana' are tried again after this long: each try\n" + + "rolls Mana Conversion again, and a refusal costs nothing.\n" + + "At most 5 tries a second, 20 in a row."); + + ImGui.Checkbox("HP Failsafe Recall", ref _settings.HpFailsafeRecall); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip( + "At or under Emergency Heal At with heals failing: break the\n" + + "stuck cast with a jump and heal again; if that fails too,\n" + + "recall to the lifestone."); + ImGui.SetNextItemWidth(180); ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 0, 5000); if (ImGui.IsItemHovered()) diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 5b2ef62..b701abe 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -1816,6 +1816,9 @@ internal sealed class LegacyDashboardRenderer dst.GiveQueueIntervalMs = tmp.GiveQueueIntervalMs; dst.T11ItemAugsOverride = tmp.T11ItemAugsOverride; dst.SpellCastIntervalMs = tmp.SpellCastIntervalMs; + dst.StuckCastBreakMs = tmp.StuckCastBreakMs; + dst.RecoveryRetryMs = tmp.RecoveryRetryMs; + dst.HpFailsafeRecall = tmp.HpFailsafeRecall; dst.AttackSpellIntervalMs = tmp.AttackSpellIntervalMs; dst.EmbeddedNavs = tmp.EmbeddedNavs; dst.SuppressRetailRadar = tmp.SuppressRetailRadar; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index e97cac2..7f16574 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -332,6 +332,30 @@ public sealed class LegacyUiSettings public int SpellCastIntervalMs = 400; + /// + /// Stuck-cast breaker (Plugins/Shared/ActionPacer.cs): the longest a cast may stay unanswered + /// (ms from the send; no result, no UseDone) before it is broken with a jump (a Peace mode + /// request when the engine can't jump). It fires sooner, about 2 s past the spell's normal + /// cycle, when that is shorter. Nothing is cast meanwhile once the server says 'too busy'. + /// 0 = no breaker. + /// + public int StuckCastBreakMs = 8000; + + /// + /// Recovery vitals (Heal Self, Stamina to Health, Revitalize, Stamina to Mana) refused for + /// "not enough mana" are tried again after this many ms, for a better Mana Conversion roll + /// (ACE rolls the cost on every attempt and a refusal costs nothing). Clamped to 200..5000; + /// at most 5 tries a second and 20 refusals in a row, then the old 15 s family rest. + /// + public int RecoveryRetryMs = 200; + + /// + /// HP failsafe: at or under Emergency Heal At with heals failing for a while, the stuck-cast + /// breaker runs and the heal is tried again; when that fails too, recall to the lifestone. + /// Off: the breaker still runs, no recall. + /// + public bool HpFailsafeRecall = true; + /// /// Minimum delay between offensive (war/void) COMBAT spell casts, in ms. /// Combat magic uses this instead of so diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs index 80ed74d..472335d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs @@ -55,6 +55,16 @@ public sealed partial class RynthAiPlugin /// reloaded the world) came with the bot still casting and dequipping through /// the death. Reads the vitals every tick (the regular poll is every 30). /// + private bool _wasPortalingForPacer; + + /// Portal space starts: the server dropped what was open (no breaker on a teleport's gap). + private void NotePortalForPacer() + { + bool portaling = Host.HasIsPortaling && Host.IsPortaling(); + if (portaling && !_wasPortalingForPacer) RynthCore.Plugin.Shared.ActionPacer.Forget("portal space"); + _wasPortalingForPacer = portaling; + } + private bool HoldForDeath() { long now = Environment.TickCount64; @@ -82,6 +92,8 @@ public sealed partial class RynthAiPlugin Log("[RynthAi] Died — holding all actions until respawned and out of portal space."); _combatManager?.ReleaseHeldTurn(); _navigationEngine?.Stop(); + RynthCore.Plugin.Shared.ActionPacer.Forget("death"); // the server dropped whatever was open + _buffManager?.CancelPendingRecall("death"); // no /lifestone or macro restart after the respawn } else { diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index c2f731c..cd3eadb 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -185,6 +185,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // use-on, cast and combat-mode change waits for the server's answer to the last one. RynthCore.Plugin.Shared.ActionPacer.Reset(); RynthCore.Plugin.Shared.ActionPacer.Enabled = true; + var hookHost = Host; + CombatHook.LastUseDone = () => hookHost.HasUseDoneSeq && hookHost.TryGetLastUseDone(out int s, out uint e) ? (s, e) : null; RynthCore.Plugin.Shared.UseAudit.AfterSend = RecordUseForPacing; _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. @@ -597,6 +599,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _weaponSwapGate.IsWielded = id => RynthCore.Plugin.Shared.ActionPacer.IsWieldedByPlayer(Host, unchecked((uint)id)); _buffManager = new BuffManager(Host, _dashboard.Settings, _spellManager, _vitals); + // The HP failsafe's recall stops the macro as /ra stop does (the macro-stop edge in OnTick + // then cancels the attack and stops movement): a move during the recall cancels it. + _buffManager.MacroStopForRecall = () => + { + _macroResumeAt = 0; + _navigationEngine?.Stop(); + }; + // The failsafe switching the macro back on after a failed recall is a start like any other. + _buffManager.MayRestartMacro = () => !RefuseMacroStartForVTank(); _inGameMarkerSet = false; if (IsCarriedOverSession(_playerId)) { @@ -887,7 +898,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase ["MeleeAttackPower"] = (-1, 100), ["MissileAttackPower"] = (-1, 100), ["MeleeAttackHeight"] = (0, 2), ["MissileAttackHeight"] = (0, 2), ["PetMinMonsters"] = (1, 20), - ["SpellCastIntervalMs"] = (100, 1500), ["AttackSpellIntervalMs"] = (0, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100), ["MinWallTargets"] = (1, 20), ["WallRange"] = (0, 100), + ["SpellCastIntervalMs"] = (100, 1500), ["StuckCastBreakMs"] = (0, 60000), ["RecoveryRetryMs"] = (200, 5000), ["AttackSpellIntervalMs"] = (0, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100), ["MinWallTargets"] = (1, 20), ["WallRange"] = (0, 100), ["MinSkillLevelTier1"] = (1, 500), ["MinSkillLevelTier2"] = (1, 500), ["MinSkillLevelTier3"] = (1, 500), ["MinSkillLevelTier4"] = (1, 500), ["MinSkillLevelTier5"] = (1, 500), ["MinSkillLevelTier6"] = (1, 500), ["MinSkillLevelTier7"] = (1, 500), ["MinSkillLevelTier8"] = (1, 500), ["MonsterRange"] = (1, 200), ["MonsterDisengageRange"] = (0, 200), ["TargetSelection"] = (0, 3), ["RingRange"] = (1, 50), ["ApproachRange"] = (1, 50), @@ -1248,6 +1259,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase try { _dashboard?.DrainMetaCommands(); // apply queued meta edits on this (plugin-tick) thread + CombatHook.ObserveUseDone(); // ctx.last.err: the answer to the hook's last cast TickDelayedCommands(); // /ub delay if (_loginComplete) _dashboard?.TickPackSetup(_objectCache, _playerId); // new/copied profile items @@ -1488,6 +1500,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (_dashboard?.Settings is { } safetySettings) CheckPlayerDeath(safetySettings); // Dead or on the way back from a death: do nothing (HoldForDeath). The // finally below still submits the nav markers. + RynthCore.Plugin.Shared.ActionPacer.NoteFrame(); + // Stuck Cast Break, once per tick: the breaker runs for every subsystem's casts. + if (_dashboard?.Settings is { } paceSettings) + RynthCore.Plugin.Shared.ActionPacer.StuckCastMs = Math.Max(0, paceSettings.StuckCastBreakMs); + NotePortalForPacer(); if (HoldForDeath()) return; // Standing in acid or lava: nothing but getting out (RynthAiPlugin.HazardEscape.cs). diff --git a/Plugins/RynthCore.Plugin.RynthLua/CombatHookPump.cs b/Plugins/RynthCore.Plugin.RynthLua/CombatHookPump.cs index 391d63a..1641766 100644 --- a/Plugins/RynthCore.Plugin.RynthLua/CombatHookPump.cs +++ b/Plugins/RynthCore.Plugin.RynthLua/CombatHookPump.cs @@ -348,11 +348,35 @@ public sealed partial class RynthLuaPlugin } t["monsters"] = monsters; + // ctx.last: the most recent RESOLVED cast, its err final (nil only when no answer could be + // read); ctx.pending: the cast still in flight, or nil. From a RynthAi that writes the + // appended fields; an older one: ctx.last is its last decision, no err, no pending. var last = new Table(s); - last["seq"] = (double)r.LastSeq; - last["spell"] = (double)r.LastSpell; - last["target"] = (double)r.LastTarget; - last["at"] = (double)r.LastAtMs; + uint newEnd = (uint)System.Runtime.InteropServices.Marshal.OffsetOf(nameof(CombatRequestV1.PendingAtMs)) + sizeof(long); + if (r.StructSize >= newEnd) + { + last["seq"] = (double)r.ResolvedSeq; + last["spell"] = (double)r.ResolvedSpell; + last["target"] = (double)r.ResolvedTarget; + last["at"] = (double)r.ResolvedAtMs; + if (r.ResolvedSpell != 0 && r.ResolvedErr >= 0) last["err"] = (double)r.ResolvedErr; + if (r.PendingSpell != 0) + { + var pending = new Table(s); + pending["seq"] = (double)r.PendingSeq; + pending["spell"] = (double)r.PendingSpell; + pending["target"] = (double)r.PendingTarget; + pending["at"] = (double)r.PendingAtMs; + t["pending"] = pending; + } + } + else + { + last["seq"] = (double)r.LastSeq; + last["spell"] = (double)r.LastSpell; + last["target"] = (double)r.LastTarget; + last["at"] = (double)r.LastAtMs; + } t["last"] = last; return DynValue.NewTable(t); } diff --git a/Plugins/RynthCore.Plugin.RynthLua/Types/rynthlua.d.lua b/Plugins/RynthCore.Plugin.RynthLua/Types/rynthlua.d.lua index f25432a..2af3720 100644 --- a/Plugins/RynthCore.Plugin.RynthLua/Types/rynthlua.d.lua +++ b/Plugins/RynthCore.Plugin.RynthLua/Types/rynthlua.d.lua @@ -1470,7 +1470,7 @@ function RynthAiModule.SubmitCommand(text) end ---another target while the projectile flies, and the next request names the new target. An ---unknown spell, a target that isn't the fight target, a scanned monster or the player, or a spell ---the server refused outright right after the script cast it (no components) is rejected and ----RynthAi casts its own; a rejected request reads as last.spell = 0. A refused spell stays parked +---RynthAi casts its own; a rejected request is not a cast and appears in neither ctx.last nor ctx.pending. A refused spell stays parked ---for 600 s (as RynthAi parks a vital level); restocking components does not unpark it sooner. ---One script per kind: the first to register owns it; the same script registering again replaces ---its handler; nil clears it. An error declines that request; a handler still running 1 s past @@ -1515,17 +1515,34 @@ function RynthAiModule.ClearCombatHandlers() end ---@field issuedAt number clock() when RynthAi asked. ---@field deadline number clock() after which RynthAi casts its own choice. ---@field monsters RynthLua.CombatMonster[] RynthAi's targets in range (attackable, in sight), nearest first. ----@field last RynthLua.CombatLast The last answer of this kind RynthAi used. +---@field last RynthLua.CombatLast The most recent RESOLVED cast of this kind (its answer is in). +---@field pending RynthLua.CombatPending? The cast of this kind still in flight (sent, no answer yet); nil = none. ---@class RynthLua.CombatMonster ---@field id integer ---@field distance number Metres. +---A cast of this kind is in flight from its send until its answer: the UseDones answer the casts in flight of both kinds in send order (an attack sent first takes the first one, a heal sent after it the next), +---then resolved. ctx.last never changes after the fact: a cast moves from ctx.pending to ctx.last once, +---with its final err. Declines and rejects are not casts and appear in neither. +---With an older RynthAi (one that does not write these fields): ctx.last is the last decision RynthAi used (spell 0 = +---declined or rejected), with no err, and ctx.pending is always nil. ---@class RynthLua.CombatLast ----@field seq integer 0 before the first. ----@field spell integer The spell cast; 0 = declined or rejected. +---@field seq integer The request seq of that cast; 0 before the first resolved cast. +---@field spell integer The spell cast; 0 before the first resolved cast. ---@field target integer ----@field at number clock() when it was used. +---@field at number clock() when it was sent. +---@field err integer? Its answer, final: the UseDone error. 0 = done (it went off), 29 (0x1D) = +--- refused 'too busy' (it never went off: not a miss), 1025 (0x401) = not enough +--- mana, 1026 (0x402) = fizzled. nil only when no answer could be read: no UseDone +--- within 7 s of the send, or another answer came first; also nil before the +--- first resolved cast. + +---@class RynthLua.CombatPending +---@field seq integer The request seq of the cast in flight. +---@field spell integer +---@field target integer +---@field at number clock() when it was sent. ---ai.CombatHook ---@class RynthLua.CombatHookInfo diff --git a/Plugins/Shared/ActionPacer.cs b/Plugins/Shared/ActionPacer.cs index 20075f1..4bd07ca 100644 --- a/Plugins/Shared/ActionPacer.cs +++ b/Plugins/Shared/ActionPacer.cs @@ -34,7 +34,7 @@ // queue (CMotionInterp pending motions, the engine's cast gate: GetCastBusyState) must // be empty, for uses, kits, potions, casts, stance changes, wields and the item // managers' moves (GestureHolds). Melee/missile attack repeats are exempt (MayStart -// with gestureGate false). Time limit GestureHoldMaxMs (GestureEmergencyMaxMs for an +// with animationGate false). Time limit GestureHoldMaxMs (GestureEmergencyMaxMs for an // emergency heal), logged, like Combat/CastGateWatchdog for casts. // // Why the animation gate (2026-10-06 afternoon, ops/overnight/2026-10-06-turnto-stall.md, @@ -92,6 +92,8 @@ internal sealed class PacedAction public long SentMs; public int SeqAtSend; public int ModeTarget; + public uint Target; // a cast's target (the held-cast turn faces it) + public bool Script; // a cast a script chose (the combat hook): the breaker waits ScriptCastMinBreakMs public bool WieldedAtSend; public bool ResultSeen; // a cast's result is in (enchantment / chat); the server is in its recoil public bool HealQueued; // the one heal allowed behind that recoil went out @@ -175,13 +177,43 @@ internal static class ActionPacer _maxWaitWhat = ""; _holdsByWho.Clear(); _lastTimeout = ""; + ClearBusyLocked(); + _stuckBreaks = 0; + _refusalHolds = 0; + _heldTurns = 0; + _forcedBreaks = 0; + _jumpAt = 0; + _cycleBySpell.Clear(); + _lastSeenSeq = int.MinValue; + _lastFrameMs = 0; + _gapEnd = 0; + _gapLen = 0; + _errorAnswers.Clear(); + _staleDrops = _latchExpiries = _burstHolds = 0; + } + } + + /// + /// The plugin's heartbeat, every frame whatever the macro does. A gap of PollGapMs or more between + /// two calls (the client froze or loaded) makes a cast sent before the gap ENDED stale at the next + /// check (a cast sent in the tick just before a freeze is sent after that tick's NoteFrame), so + /// a teleport's or a freeze's gap is never mistaken for a stuck cast and broken by a jump. Never + /// called (a plugin without it, the tests that don't): no gap detection, only StaleCastMs. + /// + public static void NoteFrame() + { + long now = NowMs(); + lock (Gate) + { + if (_lastFrameMs != 0 && now - _lastFrameMs >= PollGapMs) { _gapEnd = now; _gapLen = now - _lastFrameMs; } + _lastFrameMs = now; } } /// Forget the outstanding action (logout, death, portal): the server dropped it. public static void Forget(string why) { - lock (Gate) { _cur = null; } + lock (Gate) { _cur = null; ClearBusyLocked(); } } // ── Recording what went out ────────────────────────────────────────────── @@ -209,6 +241,8 @@ internal static class ActionPacer { _sentOverOutstanding++; over = $"[Pace] {who}: {Describe(kind, label)} went out while {Describe(prev.Kind, prev.Label)} ({prev.Who}) was unanswered for {now - prev.SentMs} ms"; + // Our cast is still the server's: a 0x1D to this send says it is open (the stuck-cast rules). + if (prev.Kind == PacedKind.Cast && _shadow == null && _hung == null) _shadow = prev; } _cur = a; } @@ -254,6 +288,12 @@ internal static class ActionPacer if (hasSeq && seq != a.SeqAtSend) { answeredHow = "UseDone"; + if (a.Kind == PacedKind.Cast) + { + uint err = TooBusyErr; + try { if (host.TryGetLastUseDone(out int ls, out uint le) && ls == a.SeqAtSend + 1) err = le; } catch { } + if (err != TooBusyErr) NoteCycle(a.Id, age); + } } else if (a.Kind == PacedKind.ItemUse && IsWieldedByPlayer(host, a.Id) != a.WieldedAtSend) { @@ -293,6 +333,7 @@ internal static class ActionPacer { _timedOut++; _lastTimeout = $"{Describe(a.Kind, a.Label)} ({a.Who}) after {age} ms"; + if (a.Kind == PacedKind.Cast && _hung == null) _hung = a; // still the server's: see the stuck-cast hold line = $"[Pace] no answer from the server to {Describe(a.Kind, a.Label)} ({a.Who}) in {age} ms - going on (nothing cleared)"; } else @@ -317,14 +358,31 @@ internal static class ActionPacer /// May send a use, a cast or a mode change now? False (with why) while /// another action waits for the server, except the heal rules in the file header, and while /// the character is still animating (; skipped with - /// false: melee/missile attack repeats). One log line per + /// false: melee/missile attack repeats). One log line per /// outstanding action (or animation) and subsystem. /// - public static bool MayStart(RynthCoreHost host, string who, HealNeed heal, out string why, bool gestureGate = true) + /// False: skip (melee/missile attack repeats). + /// False: skip the movement settle (; attack repeats only). + /// + /// A melee/missile attack repeat: never held by the 'too busy' latch. ACE sends no UseDone for a + /// swing, so a latch set by anything else (a refused pickup) would otherwise leave combat only the + /// probe slots. + /// + public static bool MayStart(RynthCoreHost host, string who, HealNeed heal, out string why, + bool animationGate = true, bool settleGate = true, bool attackRepeat = false) { if (!Enabled) { why = ""; return true; } + if (ServerBusyHolds(host, who, attackRepeat, out why, healStart: heal != HealNeed.None)) return false; + if (settleGate && MoveAudit.SettleHolds(host, out why)) + { + bool log; + lock (Gate) { _settleHolds++; log = _settleLogged.Add(who); } + if (log) Log(host, $"[Pace] {who} waits: {why}"); + return false; + } + lock (Gate) _settleLogged.Clear(); if (!OutstandingAllows(host, who, heal, out why)) return false; - if (gestureGate && GestureHolds(host, who, heal, out why)) return false; + if (animationGate && GestureHolds(host, who, heal, out why)) return false; return true; } @@ -495,8 +553,471 @@ internal static class ActionPacer return true; } + // -- A cast the server holds open, and a server that answers "too busy" ---------------- + // Two hangs in a client log, both ACE's fast-tick turn-to-cast wait (Player_Magic + // TurnTo_Magic / PendingTurnRelease: the cast waits until the character faces its target within + // spellcast_max_angle, with no time limit): a Bolt VII sent in the same tick as nav's autorun stop + // (answered 40.8 s later) and a Drain at a moving target (its + // incantation 2865 ms after the send, fizzled 37 s later on a client mode change). The server + // kept IsBusy, so every cast after it came back UseDone 0x1D, and the vitals path re-sent a heal + // every 2.5 s. So: + // * a cast that times out unanswered (CastMaxMs) is kept as the server's (hung); + // * a UseDone with 0x1D latches "server busy": nothing starts (MayStart) until a UseDone with + // another error arrives. With no cast of ours open, one probe goes after BusyProbeMs, then + // after twice that each time, up to BusyProbeMaxMs (the busy thing may have no UseDone of its + // own, e.g. a pickup). No timer re-sends into a server busy with our own cast; + // * a cast of ours still unanswered TurnAfterMs past its normal cycle: turn to face its target + // (the server's angle check then lets it finish), once, when RynthAi is not moving us; + // * still unanswered JumpAfterMs past its normal cycle (capped by StuckCastMs), or a 0x1D to + // another send while it is open past RefusalBreakMinMs: the breaker, a jump (0xF61B, TapJump): + // on fast tick ACE's HandleActionJump clears the pending motions and calls FailCast (origin/ + // master Player.cs ~1195-1214), a 0x402 fizzle. Nothing starts until the character has landed + // (a cast in the air is refused). No UseDone BreakerWaitMaxMs after landing: a Peace mode + // request (HandleActionChangeCombatMode_Inner also calls FailCast, fast tick or not); then + // BreakerWaitMaxMs more and it goes on (logged). + + /// ACE's YoureTooBusy, as a UseDone error. + public const uint TooBusyErr = 0x1D; + /// With no cast of ours open, one start is let through this long after a 0x1D (doubling per probe). + public const long BusyProbeMs = 1500; + public const long BusyProbeMaxMs = 6000; + /// A cast's normal send-to-UseDone time when none was seen for its spell, and the floor of a learned one. + public const long DefaultCycleMs = 3000; + /// Past its normal cycle: turn to face the target after this, jump after this. + public const long TurnAfterMs = 1000; + public const long JumpAfterMs = 2000; + /// A 0x1D to another send breaks our open cast only once it is this old (a recoil refusal is normal). + public const long RefusalBreakMinMs = 3000; + /// After the jump: landed once the height is back (and this long passed), or at the max. + public const long JumpLandMinMs = 400; + public const long JumpLandMaxMs = 1500; + /// After landing (or after the Peace request), the longest wait for a UseDone before the next step. + public const long BreakerWaitMaxMs = 3000; + /// The stuck-cast limit (ms from the send; 0 = no turn, no breaker). RynthAi sets it from its settings. + public static long StuckCastMs = 8000; + /// + /// A script-chosen cast is not broken by a jump before this (ms from the send), whatever its + /// cycle, Stuck Cast Break or a 'too busy' answer say: a script's slower spells (a siphon + /// answered about 5.5 s after the send) get 6 s from the send before the first jump; the + /// held-cast nudge, which counts from the incantation, comes later. + /// + public const long ScriptCastMinBreakMs = 6000; + /// + /// A cast of ours this old (or one sent before a gap of PollGapMs between NoteFrame calls: a + /// client freeze, a long load) is stale: dropped with the latch, never broken. Bounds every hold, + /// the breaker off (StuckCastMs 0) included. + /// + public const long StaleCastMs = 3 * (CastMaxMs > BusyProbeMaxMs ? CastMaxMs : BusyProbeMaxMs); + public const long PollGapMs = 5000; + /// A 'too busy' latch with no cast of ours open is cleared after this long (logged). + public const long LatchMaxMs = 15000; + /// 'Too busy' UseDones in the last second at which every start but a heal waits (bounds refusal chat lines). + public const int RefusalBurstMax = 5; + public const int PeaceMode = 1, MagicMode = 8; + + private enum BreakStage { None, Turned, Jumped, Landed, ModeSent } + + private static PacedAction? _hung; // a cast past CastMaxMs with no UseDone + private static PacedAction? _shadow; // our cast still unanswered when another action went out over it + private static long _busySince; // first 0x1D of the latch (0 = no latch) + private static int _busyRefusals; // 0x1D answers in this latch + private static int _probes; + private static long _lastProbeAt; + private static BreakStage _stage; + private static long _stageAt; + private static PacedAction? _stageFor; + private static long _jumpAt; // 0 = not in the air after a breaker jump + private static float _jumpZ; + private static int _lastSeenSeq = int.MinValue; + private static long _lastFrameMs; // the last NoteFrame (gap detection; 0 = never) + private static long _gapEnd, _gapLen; // the frame that ended the last gap, and its length (0 = none) + private static readonly Queue _errorAnswers = new(); // times of error UseDones (burst limiter) + private static long _staleDrops, _latchExpiries, _burstHolds; + public static long StaleDrops => _staleDrops; + public static long LatchExpiries => _latchExpiries; + public static long BurstHolds => _burstHolds; + private static long _stuckBreaks, _refusalHolds, _heldTurns, _forcedBreaks, _settleHolds; + private static readonly HashSet _settleLogged = new(); + public static long SettleHoldCount => _settleHolds; + private static readonly HashSet _busyLogged = new(); + private static readonly Dictionary _cycleBySpell = new(); + public static long StuckBreaks => _stuckBreaks; + public static long RefusalHolds => _refusalHolds; + public static long HeldCastTurns => _heldTurns; + /// True while the server is taken as busy (a 0x1D latch or a hung cast). + public static bool ServerBusy { get { lock (Gate) return _busySince != 0 || _hung != null; } } + /// True while the character is in the air after a breaker jump. + public static bool BreakerAirborne { get { lock (Gate) return _jumpAt != 0; } } + + private static void ClearBusyLocked() + { + _hung = null; + _shadow = null; + _busySince = 0; + _busyRefusals = 0; + _probes = 0; + _lastProbeAt = 0; + _stage = BreakStage.None; + _stageAt = 0; + _stageFor = null; + _busyLogged.Clear(); + } + + /// The normal send-to-UseDone time of : the longest of its last answers, at least DefaultCycleMs. + internal static long NormalCycleMs(uint spellId) + { + lock (Gate) return _cycleBySpell.TryGetValue(spellId, out long c) ? Math.Max(DefaultCycleMs, c) : DefaultCycleMs; + } + + /// A cast of was answered (not 0x1D) after its send. + private static void NoteCycle(uint spellId, long ms) + { + if (ms <= 0 || ms > CastMaxMs) return; + lock (Gate) + { + // The longest recent answer, easing down: a slow one counts at once, old slow ones fade. + _cycleBySpell[spellId] = _cycleBySpell.TryGetValue(spellId, out long c) ? Math.Max(ms, (c * 7 + ms) / 8) : ms; + } + } + + /// Reads the last UseDone: a 0x1D starts or feeds the latch, any other answer clears it. + private static void ObserveUseDone(RynthCoreHost host, long now, out string? line) + { + line = null; + int seq; uint err; + try + { + if (!host.HasUseDoneSeq || !host.TryGetLastUseDone(out seq, out err)) return; + } + catch { return; } + lock (Gate) + { + if (_lastSeenSeq == int.MinValue) { _lastSeenSeq = seq; return; } + if (seq == _lastSeenSeq) return; + _lastSeenSeq = seq; + if (err == TooBusyErr) _errorAnswers.Enqueue(now); // the burst counts 'too busy' only (0x401 retries are paced on their own) + if (err == TooBusyErr) + { + if (_busySince == 0) { _busySince = now; if (_hung == null) _busyLogged.Clear(); } + _busyRefusals++; + return; + } + if (_busySince != 0 || _hung != null || _stage != BreakStage.None) + line = $"[Pace] the server answered again (UseDone 0x{err:X}): casting resumes" + + (_hung != null ? $" ({Describe(_hung.Kind, _hung.Label)} ended {now - _hung.SentMs} ms after its send)" : ""); + ClearBusyLocked(); + } + } + + /// + /// True (with why) while the server is taken as busy (a 0x1D answer with no other answer since, + /// a hung cast) or the character is in the air after a breaker jump. Runs the held-cast turn and + /// the stuck-cast breaker. Called by MayStart. + /// + private static bool ServerBusyHolds(RynthCoreHost host, string who, bool attackRepeat, out string why, bool healStart = false) + { + why = ""; + long now = NowMs(); + long gapEnd, gapLen; + lock (Gate) { gapEnd = _gapEnd; gapLen = _gapLen; } + ObserveUseDone(host, now, out string? line); + if (line != null) Log(host, line); + + if (AirborneHolds(host, now, out why)) return true; + + PacedAction? open = Current(host); + PacedAction? stuck; + bool probe = false; + long age = 0; + string? staleLine = null; + lock (Gate) + { + if (_shadow != null && _hung == null && now - _shadow.SentMs >= CastMaxMs) { _hung = _shadow; _shadow = null; } + stuck = _hung ?? _shadow ?? (open is { Kind: PacedKind.Cast } ? open : null); + if (stuck != null) age = now - stuck.SentMs; + // Stale: too old to still be the server's, or sent before a gap with no checks (a freeze, + // portal space, the macro off). Dropped with the latch, never broken. + bool beforeGap = stuck != null && gapEnd != 0 && stuck.SentMs < gapEnd; + if (stuck != null && (age >= StaleCastMs || beforeGap)) + { + staleLine = $"[Pace] {Describe(stuck.Kind, stuck.Label)} ({stuck.Who}) is stale ({age} ms" + + (beforeGap ? $", sent before a {gapLen} ms gap with no check" : "") + "): dropped, the server is taken as free"; + if (ReferenceEquals(_cur, stuck)) _cur = null; + ClearBusyLocked(); + _staleDrops++; + stuck = null; + } + // A 'too busy' latch with no cast of ours open: bounded, not probed for ever. + else if (stuck == null && _busySince != 0 && now - _busySince >= LatchMaxMs && _stage == BreakStage.None) + { + staleLine = $"[Pace] no answer cleared the 'too busy' latch in {now - _busySince} ms and no cast of ours is open: going on"; + ClearBusyLocked(); + _latchExpiries++; + } + if (_stageFor != null && !ReferenceEquals(_stageFor, stuck)) { _stage = BreakStage.None; _stageAt = 0; _stageFor = null; } + // A forced break with no cast of ours open (stage for nothing): once on the ground, it is + // over. Left set it would block the latch expiry and the probe for good. + else if (_stageFor == null && _stage != BreakStage.None && _jumpAt == 0) { _stage = BreakStage.None; _stageAt = 0; } + if (!attackRepeat && stuck == null && _busySince != 0 && _stage == BreakStage.None + && now - Math.Max(_busySince, _lastProbeAt) >= Math.Min(BusyProbeMs << Math.Min(_probes, 8), BusyProbeMaxMs)) + { + probe = true; + _probes++; + _lastProbeAt = now; + } + } + + if (staleLine != null) Log(host, staleLine); + if (stuck != null && !IsPortaling(host)) StepBreaker(host, stuck, age, now); + if (AirborneHolds(host, now, out why)) return true; + + // Any source: RefusalBurstMax 'too busy' answers in the last second hold every start but a heal for the rest + // of that second (each refusal is a chat line; a burst of them is the 0x00460D1D crash class). + int burst; + lock (Gate) + { + while (_errorAnswers.Count > 0 && now - _errorAnswers.Peek() >= 1000) _errorAnswers.Dequeue(); + burst = _errorAnswers.Count; + if (burst >= RefusalBurstMax && !healStart) _burstHolds++; + } + // A heal is never held by the burst (an emergency must not wait on refusals of other starts). + if (burst >= RefusalBurstMax && !healStart) + { + why = $"{burst} refusals from the server in the last second"; + return true; + } + + // Attack repeats are never held by the latch (no UseDone ever comes for a swing). + if (attackRepeat) return false; + + bool latched; + lock (Gate) latched = _busySince != 0 || _hung != null; + // Our cast still inside CastMaxMs with no 0x1D: OutstandingAllows holds it (heal rules included). + if (!latched) return false; + if (probe) + { + Log(host, $"[Pace] {who}: one try (#{_probes}) after the server's 'too busy' answer; no cast of ours is open"); + return false; + } + + int refusals; + BreakStage stage; + lock (Gate) + { + _refusalHolds++; + _holdsByWho[who] = _holdsByWho.TryGetValue(who, out int n) ? n + 1 : 1; + refusals = _busyRefusals; + stage = _stage; + } + string what = stuck != null ? $"{Describe(stuck.Kind, stuck.Label)} ({stuck.Who}) has had no answer for {age} ms" : "the server answered 'too busy'"; + why = stage >= BreakStage.Jumped + ? $"{what}; stuck-cast break sent, waiting for its UseDone" + : $"{what}{(refusals > 0 ? $" ({refusals} 'too busy' answer(s))" : "")}: nothing goes until the server answers"; + bool log; + lock (Gate) log = _busyLogged.Add(who); + if (log) Log(host, $"[Pace] {who} waits: {why}"); + return true; + } + + /// The held-cast turn and the breaker steps for (one step per call at most). + private static void StepBreaker(RynthCoreHost host, PacedAction stuck, long age, long now) + { + if (StuckCastMs <= 0) return; + long cycle = NormalCycleMs(stuck.Id); + long jumpAt = Math.Min(cycle + JumpAfterMs, StuckCastMs); + long turnAt = Math.Min(cycle + TurnAfterMs, jumpAt); + long refusalBreakAt = RefusalBreakMinMs; + if (stuck.Script) { jumpAt = Math.Max(jumpAt, ScriptCastMinBreakMs); refusalBreakAt = Math.Max(refusalBreakAt, ScriptCastMinBreakMs); } + BreakStage stage; long stageAt; int refusals; + lock (Gate) { stage = _stage; stageAt = _stageAt; refusals = _busyRefusals; } + + if (stage == BreakStage.None && age >= turnAt && age < jumpAt) + { + SetStage(BreakStage.Turned, now, stuck); + TurnToFace(host, stuck, age); + return; + } + if (stage <= BreakStage.Turned && (age >= jumpAt || (refusals > 0 && age >= refusalBreakAt))) + { + string why = age >= jumpAt ? $"{age} ms with no answer ({cycle} ms is normal for it)" : $"a send was refused 'too busy' while it was open {age} ms"; + Jump(host, stuck, age, why, forced: false); + return; + } + if (stage == BreakStage.Landed && now - stageAt >= BreakerWaitMaxMs) + { + SetStage(BreakStage.ModeSent, now, stuck); + PeaceBreak(host, stuck, age); + return; + } + if (stage == BreakStage.ModeSent && now - stageAt >= BreakerWaitMaxMs) + { + lock (Gate) ClearBusyLocked(); + Log(host, $"[Pace] no UseDone after the stuck-cast break ({Describe(stuck.Kind, stuck.Label)}, {age} ms) - going on"); + } + } + + private static void SetStage(BreakStage stage, long now, PacedAction? forAction) + { + lock (Gate) { _stage = stage; _stageAt = now; _stageFor = forAction; } + } + + /// In the air after a breaker jump: hold until landed (height back, or JumpLandMaxMs). + private static bool AirborneHolds(RynthCoreHost host, long now, out string why) + { + why = ""; + long jumpAt; float z0; + lock (Gate) { jumpAt = _jumpAt; z0 = _jumpZ; } + if (jumpAt == 0) return false; + long air = now - jumpAt; + bool landed = air >= JumpLandMaxMs; + if (!landed && air >= JumpLandMinMs) + { + try { landed = !host.HasGetPlayerPose || (host.TryGetPlayerPose(out _, out _, out _, out float z, out _, out _, out _, out _) && Math.Abs(z - z0) < 0.1f); } + catch { landed = true; } + } + if (!landed) + { + why = $"in the air after the stuck-cast jump ({air} ms)"; + return true; + } + lock (Gate) + { + _jumpAt = 0; + if (_stage == BreakStage.Jumped) + { + if (_stageFor == null) { _stage = BreakStage.None; _stageAt = 0; } // a forced break with no cast of ours open + else { _stage = BreakStage.Landed; _stageAt = now; } + } + } + return false; + } + + /// The breaker jump (TapJump: the keyboard jump, 0xF61B). No TapJump: the Peace request instead. + private static void Jump(RynthCoreHost host, PacedAction? stuck, long age, string why, bool forced) + { + long now = NowMs(); + string what = stuck != null ? Describe(stuck.Kind, stuck.Label) : "the server's busy action"; + if (!host.HasTapJump) + { + SetStage(BreakStage.ModeSent, now, stuck); + Log(host, $"[Pace] stuck cast: no TapJump on this engine; {what}: {why}"); + PeaceBreak(host, stuck, age); + return; + } + float z = 0; + try { if (host.HasGetPlayerPose) host.TryGetPlayerPose(out _, out _, out _, out z, out _, out _, out _, out _); } catch { } + bool ok; + try { ok = host.TapJump(); } catch { ok = false; } + lock (Gate) + { + _stuckBreaks++; + if (forced) _forcedBreaks++; + _stage = BreakStage.Jumped; + _stageAt = now; + _stageFor = stuck; + if (ok) { _jumpAt = now; _jumpZ = z; } + } + Log(host, $"[Pace] stuck cast broken by jump after {age} ms: {what} - {why}{(ok ? "" : " (the jump was refused by the client)")}; nothing starts until landed and answered"); + // Refused by the client: nothing in the air. For no cast of ours, nothing to wait for either. + if (!ok) { SetStage(stuck == null ? BreakStage.None : BreakStage.Landed, now, stuck); } + } + + /// The Peace mode request (ACE fails a cast in progress on a mode change). Only from Magic. + private static void PeaceBreak(RynthCoreHost host, PacedAction? stuck, long age) + { + int mode = -1; + try { if (host.HasGetCurrentCombatMode) mode = host.GetCurrentCombatMode(); } catch { mode = -1; } + string what = stuck != null ? Describe(stuck.Kind, stuck.Label) : "the server's busy action"; + if (mode == MagicMode && host.HasChangeCombatMode) + { + int seq = UseDoneSeqNow(host); + bool ok; + try { ok = host.ChangeCombatMode(PeaceMode); } catch { ok = false; } + lock (Gate) _stuckBreaks++; + if (ok) + { + PacedAction? keep; + lock (Gate) keep = _hung; + Begin(host, PacedKind.CombatMode, 0, ModeName(PeaceMode), "StuckCast", seq, PeaceMode); + lock (Gate) _hung = keep; + } + Log(host, $"[Pace] stuck cast broken by Peace mode after {age} ms: {what} - no answer after the jump; Peace {(ok ? "requested" : "refused by the client")}"); + } + else + { + Log(host, $"[Pace] stuck cast: {what} still unanswered after the jump, not in Magic mode ({ModeName(mode)}): nothing more to cancel"); + } + } + + /// + /// Turn to face a held cast's target (once per cast), when RynthAi is not moving the character: + /// ACE's fast-tick cast waits for the facing to come within spellcast_max_angle. + /// + private static void TurnToFace(RynthCoreHost host, PacedAction stuck, long age) + { + uint target = stuck.Target; + uint player = 0; + try { if (host.HasGetPlayerId) player = host.GetPlayerId(); } catch { } + if (target == 0 || target == player || !host.HasTurnToHeading || MoveAudit.OwnMovementActive) return; + if (!TryHeadingTo(host, target, out double want, out double off)) return; + if (off < 10.0) return; // already facing it: the turn is not what holds it + try { host.TurnToHeading((float)want); } catch { return; } + lock (Gate) _heldTurns++; + Log(host, $"[Pace] held cast: {Describe(stuck.Kind, stuck.Label)} unanswered {age} ms; turning {off:0} deg to face 0x{target:X8} (heading {want:0})"); + } + + /// The heading to (AC degrees: 0 north, 90 east) and how far off the player faces. + internal static bool TryHeadingTo(RynthCoreHost host, uint target, out double heading, out double offDeg) + { + heading = 0; offDeg = 180; + try + { + if (!host.HasGetPlayerPose || !host.HasGetObjectPosition) return false; + if (!host.TryGetPlayerPose(out uint pcell, out float px, out float py, out _, out float qw, out _, out _, out float qz)) return false; + if (!host.TryGetObjectPosition(target, out uint tcell, out float tx, out float ty, out _)) return false; + double dx = (((tcell >> 24) & 0xFF) - (double)((pcell >> 24) & 0xFF)) * 192.0 + (tx - px); + double dy = (((tcell >> 16) & 0xFF) - (double)((pcell >> 16) & 0xFF)) * 192.0 + (ty - py); + if (Math.Abs(dx) < 0.01 && Math.Abs(dy) < 0.01) return false; + heading = Math.Atan2(dx, dy) * (180.0 / Math.PI); + if (heading < 0) heading += 360.0; + double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI); + double cur = ((-yaw) % 360.0 + 720.0) % 360.0; + double e = heading - cur; + while (e > 180) e -= 360; + while (e < -180) e += 360; + offDeg = Math.Abs(e); + return true; + } + catch { return false; } + } + + /// + /// The HP failsafe's break (BuffManager): a jump now, whatever is open (on fast tick it fails a + /// cast in progress and clears the pending motions). False when one is already under way or + /// this engine has no TapJump. + /// + public static bool ForceBreak(RynthCoreHost host, string why) + { + if (!Enabled || !host.HasTapJump || IsPortaling(host)) return false; + PacedAction? stuck; + lock (Gate) + { + if (_jumpAt != 0 || _stage == BreakStage.Jumped) return false; + stuck = _hung ?? _shadow ?? (_cur is { Kind: PacedKind.Cast } ? _cur : null); + } + long age = stuck != null ? NowMs() - stuck.SentMs : 0; + Jump(host, stuck, age, why, forced: true); + return true; + } + // ── Helpers ───────────────────────────────────────────────────────────── + /// In portal space: no breaker step, no forced break (the server is moving us). + internal static bool IsPortaling(RynthCoreHost host) + { + try { return host.HasIsPortaling && host.IsPortaling(); } catch { return false; } + } + internal static string Describe(PacedKind kind, string label) => kind switch { PacedKind.WorldUse => $"the use of {label}", @@ -560,6 +1081,7 @@ internal static class ActionPacer lines.Add($" Starts held {_heldStarts}, moves held {_heldMoves}, heals let ahead {_healsAhead}, sent over an unanswered one {_sentOverOutstanding}"); lines.Add($" Mode changes refused while waiting {_modeRefused}, skipped (already in that mode) {_modeSkipped}"); lines.Add($" Held while the character was animating {_gestureHolds}, animation time limits {_gestureLimits}"); + lines.Add($" Held after a 'too busy' answer {_refusalHolds}, held casts turned to {_heldTurns}, stuck casts broken {_stuckBreaks} ({_forcedBreaks} by the HP failsafe; limit {StuckCastMs} ms)"); if (_maxWaitMs > 0) lines.Add($" Longest wait seen: {_maxWaitMs} ms ({_maxWaitWhat})"); if (_holdsByWho.Count > 0) { @@ -588,11 +1110,25 @@ internal static class ActionPacer if (ok) { CastsSent++; + LastCastSeqAtSend = host.HasUseDoneSeq ? seq : -1; Begin(host, PacedKind.Cast, unchecked((uint)spellId), label, who, seq); + lock (Gate) { if (_cur is { Kind: PacedKind.Cast } c && c.Id == unchecked((uint)spellId)) c.Target = targetId; } } return ok; } + /// The open cast of was chosen by a script (see ). + public static void MarkScriptCast(int spellId) + { + lock (Gate) { if (_cur is { Kind: PacedKind.Cast } c && c.Id == unchecked((uint)spellId)) c.Script = true; } + } + + /// + /// The UseDone count read just before the last cast sent (its answer is + /// the next UseDone after it); -1 when the engine has no UseDone count. + /// + public static int LastCastSeqAtSend { get; private set; } = -1; + /// /// Casts sent through in this plugin (every caller: combat, buffs, /// nav, commands, meta): a caller that remembers the count at its own cast can tell whether diff --git a/Plugins/Shared/MoveAudit.cs b/Plugins/Shared/MoveAudit.cs index 15ecdce..3151e77 100644 --- a/Plugins/Shared/MoveAudit.cs +++ b/Plugins/Shared/MoveAudit.cs @@ -55,6 +55,7 @@ internal static class MoveAudit if (on) FlushPendingStops(host, "before a start"); Note(host, who, "SetAutoRun", on ? "True" : "False", collapseByKindOnly: false); lock (Gate) { _autoRunOn = on; if (on) _lastStartMs = NowMs(); else _pendingAutoRunOff = null; } + Changed(on ? "SetAutoRun(True)" : "SetAutoRun(False)"); return host.SetAutoRun(on); } @@ -63,6 +64,7 @@ internal static class MoveAudit if (HeldForAction(host, who, "StopCompletely()", isStop: true, deferAs: PendingStop.Complete())) return false; Note(host, who, "StopCompletely", "", collapseByKindOnly: false); lock (Gate) { _autoRunOn = false; _motionsOn.Clear(); ClearPendingLocked(); } // clears everything AC has on + Changed("StopCompletely()"); return host.StopCompletely(); } @@ -73,6 +75,7 @@ internal static class MoveAudit if (on) FlushPendingStops(host, "before a start"); Note(host, who, "SetMotion", $"0x{motion:X8}, {(on ? "True" : "False")}", collapseByKindOnly: false); lock (Gate) { if (on) { _motionsOn.Add(motion); _lastStartMs = NowMs(); } else { _motionsOn.Remove(motion); _pendingMotionOff.Remove(motion); } } + Changed($"SetMotion(0x{motion:X8}, {(on ? "True" : "False")})"); return host.SetMotion(motion, on); } @@ -83,6 +86,7 @@ internal static class MoveAudit FlushPendingStops(host, "before a start"); Note(host, who, "DoMovement", $"0x{motion:X8}, {speed:0.##}, {holdKey}", collapseByKindOnly: false); lock (Gate) { _motionsOn.Add(motion); _lastStartMs = NowMs(); } + Changed($"DoMovement(0x{motion:X8})"); return host.DoMovement(motion, speed, holdKey); } @@ -290,6 +294,9 @@ internal static class MoveAudit } catch { } + // A held stop sent now is a movement change like any other: the settle wait applies to it. + if (sent.Count > 0) Changed(sent[sent.Count - 1]); + if (sent.Count > 0 && Enabled) { try { host.Log($"[Move] {PluginName} held stop(s) sent {why} after {waited} ms: {string.Join(", ", sent)}"); } @@ -332,6 +339,7 @@ internal static class MoveAudit if (HeldForAction(host, who, $"StopMovement(0x{motion:X8})", isStop: true, motion, PendingStop.StopMovement(motion, holdKey))) return false; Note(host, who, "StopMovement", $"0x{motion:X8}, {holdKey}", collapseByKindOnly: false); lock (Gate) { _motionsOn.Remove(motion); _pendingStopMovement.Remove(motion); } + Changed($"StopMovement(0x{motion:X8})"); return host.StopMovement(motion, holdKey); } @@ -341,6 +349,7 @@ internal static class MoveAudit if (HeldForUse(host, who, "TurnToHeading")) return false; if (HeldForAction(host, who, "TurnToHeading", isStop: false)) return false; Note(host, who, "TurnToHeading", headingDegrees.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture), collapseByKindOnly: true); + Changed("TurnToHeading"); return host.TurnToHeading(headingDegrees); } @@ -400,6 +409,38 @@ internal static class MoveAudit ClearPendingLocked(); _pendingSinceMs = 0; _deferredStopsSent = 0; + _lastChangeMs = long.MinValue / 2; + _lastChangeWhat = ""; } } + + // -- Settle after a movement change ------------------------------------------------- + // A Bolt VII went out in the same tick as nav's SetAutoRun(False), after nav's turns; on ACE's + // fast tick the movement packet cancelled the cast's turn and the server held the cast 40.8 s + // (ActionPacer's stuck-cast notes). After any movement call RynthAi sends (a start, a stop, a + // turn), nothing starts until MoveSettleMinMs has passed and the client's motion queue reads + // clear (GetCastBusyState), or MoveSettleMaxMs. ActionPacer.MayStart asks (not for attack repeats). + internal const long MoveSettleMinMs = 150; + internal const long MoveSettleMaxMs = 600; + private static long _lastChangeMs = long.MinValue / 2; + private static string _lastChangeWhat = ""; + + private static void Changed(string what) + { + lock (Gate) { _lastChangeMs = NowMs(); _lastChangeWhat = what; } + } + + /// True (with why) while the last movement change has not settled. + internal static bool SettleHolds(RynthCoreHost host, out string why) + { + why = ""; + long age; string what; + lock (Gate) { age = NowMs() - _lastChangeMs; what = _lastChangeWhat; } + if (age >= MoveSettleMaxMs) return false; + bool queueBusy; + try { queueBusy = host.HasGetCastBusyState && host.GetCastBusyState() != 0; } catch { queueBusy = false; } + if (age >= MoveSettleMinMs && !queueBusy) return false; + why = $"the movement change {what} sent {age} ms ago has not settled"; + return true; + } } diff --git a/Plugins/Shared/RynthAiCombatApi.cs b/Plugins/Shared/RynthAiCombatApi.cs index 8a3fb3d..4b9b344 100644 --- a/Plugins/Shared/RynthAiCombatApi.cs +++ b/Plugins/Shared/RynthAiCombatApi.cs @@ -17,9 +17,11 @@ // Rules (as RynthAi.Script, Shared/RynthAiScriptApi.cs): // - Its own interface, so RynthAi.Script v1 (exact-version checked) and // RynthAi.Status stay as they are. -// - Append-only: new functions and request fields go at the end, and Version -// goes up. CombatRequestV1.StructSize is set by the caller before Poll; -// RynthAi never writes past it. +// - Append-only: new functions go at the end, and Version goes up. New +// request fields also go at the end but do not bump Version: they are gated +// by StructSize. The caller sets CombatRequestV1.StructSize before Poll; +// RynthAi never writes past it and writes back how much it filled, so a +// reader uses an appended field only when that StructSize covers it. // - Strings are UTF-8, NUL-terminated. // - Call only from the plugin pump thread (OnTick), never from AC's thread or Render. // - Every function returns safely (no exception crosses the boundary). @@ -61,6 +63,12 @@ public static class RynthAiCombat public const uint MinTimeoutMs = 100; public const uint MaxTimeoutMs = 3000; + /// + /// A cast with no answer (UseDone) this long after its send is resolved with no answer (error -1). + /// The pacing's own cast limit (ActionPacer.CastMaxMs). + /// + public const long ResolveTimeoutMs = 7000; + /// Longest owner name RynthAi keeps (characters). public const int MaxOwnerLength = 64; @@ -118,6 +126,27 @@ public struct CombatRequestV1 public uint LastSpell; public uint LastTarget; public long LastAtMs; + + // Appended fields (present only when the StructSize RynthAi wrote back covers them; an older + // RynthAi does not). A cast of this kind is IN FLIGHT from its send until its answer, the first + // UseDone after the send, and RESOLVED after it. Declines and rejects are not casts. + + /// The most recent resolved cast: Seq of its request, spell, target, send time (0s before the first). + public uint ResolvedSeq; + public uint ResolvedSpell; + public uint ResolvedTarget; + public long ResolvedAtMs; + /// + /// Its answer, final: the UseDone error (0 = done, 0x1D = refused 'too busy', 0x401 = not enough + /// mana, 0x402 = fizzled, ...); -1 = no answer could be read: no UseDone within + /// RynthAiCombat.ResolveTimeoutMs of the send, or another answer came first. + /// + public int ResolvedErr; + /// The cast still in flight (sent, no answer yet): Seq, spell, target, send time; Spell 0 = none. + public uint PendingSeq; + public uint PendingSpell; + public uint PendingTarget; + public long PendingAtMs; } [StructLayout(LayoutKind.Sequential)] diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index 804f35b..7d4b16b 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -85,9 +85,13 @@ internal static unsafe class FakeHost public static readonly List AutoRunCalls = new(); public static bool AutoRun; public static int Jumps; + /// Runs inside CastSpell, after the cast is recorded (a UseDone that lands during the send). + public static Action? AfterCastSpell; /// Opt-in: wires TapJump (the keyboard jump, 0xF61B); calls land in . public static bool TapJumpCalls; public static int TapJumps; + /// TapJump returns 0 (the client refused the jump); the call still counts in TapJumps. + public static bool TapJumpRefuse; 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 . @@ -208,8 +212,8 @@ internal static unsafe class FakeHost ServerTime = 0; Vitae = 1.0f; Portaling = false; PlayerPose = default; HasPose = true; 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; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; + Logs.Clear(); Chat.Clear(); ChatCommands.Clear(); AfterCastSpell = null; + AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1; VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0; ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false; @@ -651,10 +655,10 @@ internal static unsafe class FakeHost private static int JumpNonAutonomous(float extent) { Jumps++; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int TapJump() { TapJumps++; return 1; } + private static int TapJump() { TapJumps++; return TapJumpRefuse ? 0 : 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); Sent.Add($"cast {spellId}"); return 1; } + private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); Sent.Add($"cast {spellId}"); AfterCastSpell?.Invoke(); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int StopCompletely() { Stops++; Sent.Add("stop"); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 2135229..465c4c4 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -101,6 +101,10 @@ internal static class Program CastNoDamageTests.Register(runner); ManaReserveTests.Register(runner); DamageRowsTests.Register(runner); + StuckCastTests.Register(runner); + PacerEdgeTests.Register(runner); + RecoveryRetryTests.Register(runner); + HpFailsafeTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs index 1356aa0..cb643b1 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs @@ -703,7 +703,7 @@ internal static class ActionPacingTests _t += 110; Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out string why), "the wand waits: the swing hasn't animated yet"); Check.True(why.Contains("swing"), "why: " + why); - Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "the next attack isn't held"); + Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true), "the next attack isn't held"); _t += 200; FakeHost.CastBusy = 1; Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "swinging: still waits"); @@ -830,10 +830,10 @@ internal static class ActionPacingTests { var host = World(combatMode: 2); FakeHost.CastBusy = 1; // the last swing still plays - Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "a melee attack repeat is not held by the animation"); + Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true), "a melee attack repeat is not held by the animation"); Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "anything gated is"); host.UseFor(Corpse, "Loot", "open"); - Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "but an attack still waits for an unanswered corpse use (the server's turn)"); + Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true), "but an attack still waits for an unanswered corpse use (the server's turn)"); FakeHost.UseDone(0); Check.True(ActionPacer.Current(host) == null, "the use is answered"); ActionPacer.Enabled = false; diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs index 7139e83..9cda84a 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs @@ -49,6 +49,15 @@ internal static class CombatHookTests r.Add("combat hook: ctx.monsters leaves out a Priority 0 (ignored) monster, even one hitting us", HookScanSkipsIgnored); r.Add("combat hook: a script answer at an ignored monster is rejected, even one hitting us (RynthAi casts its own)", HookRejectsIgnoredTarget); r.Add("combat hook: a script heal (a drain) at a fight target whose rule turned to Priority 0 is rejected", HookHealRejectsIgnoredTarget); + r.Add("blacklist: casts answered 'too busy' (UseDone 0x1D) are not no-damage casts (answered 0: the target is dropped)", RefusedCastsNotJudged); + r.Add("combat hook: ctx.pending is the cast in flight; ctx.last the last resolved one, err its first UseDone (final; -1 when missed or after 7 s)", LastErrIsTheCastsAnswer); + r.Add("combat hook: an attack and a heal in flight take their UseDones in send order (attack 0x401, heal 0)", AnswersInSendOrder); + r.Add("combat hook: a script heal refused for mana keeps its 2 s rest (no recovery fast retry)", ScriptHealNoFastRetry); + r.Add("combat hook: a script attack with no answer is not jumped in 5.5 s; RynthAi's own cast is", ScriptAttackNotJumpedEarly); + r.Add("combat hook: a script heal (a drain) with no answer is not jumped in 5.5 s", ScriptHealNotJumpedEarly); + r.Add("combat hook: a 'too busy' answer at 3.5 s does not jump a script attack before 6 s; RynthAi's own cast is jumped", ScriptAttackRefusalNoEarlyJump); + r.Add("combat hook: a 'too busy' answer at 3.5 s does not jump a script heal before 6 s", ScriptHealRefusalNoEarlyJump); + r.Add("combat hook: a UseDone that lands during the send is the cast's answer (ctx.last.err)", AnswerDuringSendIsTheCasts); r.Add("combat hook: a script cast at the fight target is tagged for the Damage tab (element and tier from its spell)", ScriptCastAttribution); r.Add("combat hook: a heal request names the fight target and its health; a nil answer target still heals the player", HealRequestNamesFightTarget); r.Add("combat hook: a refusal after another cast (a heal) or after the script spell landed does not park the script spell", RefusalNotMisattributed); @@ -584,8 +593,9 @@ internal static class CombatHookTests public readonly PlayerVitalsCache V; public readonly CombatManager C; public readonly WorldObjectCache Cache; + public readonly RynthCoreHost Host; - public HealRig(int healthPct = 40, int mode = CombatMode.Magic, int emergencyAt = 0) + public HealRig(int healthPct = 40, int mode = CombatMode.Magic, int emergencyAt = 0, Action? setup = null) { FakeHost.Reset(); FakeHost.WeaponCalls = true; @@ -599,7 +609,8 @@ internal static class CombatHookTests FakeHost.Names[(uint)Target] = "Drudge Skulker"; FakeHost.Positions[(uint)Target] = (0x0101001Bu, 0f, 10f, 0f); FakeHost.ItemTypes[(uint)Target] = 0x10; - var host = FakeHost.Create(Player); + setup?.Invoke(); + var host = Host = FakeHost.Create(Player); S = new LegacyUiSettings { IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = emergencyAt, StaminaToHealthAt = 0, @@ -916,6 +927,24 @@ internal static class CombatHookTests Check.False(FakeHost.Casts.Any(c => c.SpellId == drain), "the drain is not cast"); }); + // Recovery retry: only RynthAi's own recovery vitals retry fast after "not enough mana"; a script's heal + // (even the same Heal Self) keeps the rest it had, with Mana Conversion trained. + private static void ScriptHealNoFastRetry() => Guard(() => + { + int heal = Id("Heal Self V"); + var rig = new HealRig(); + FakeHost.Skills[(Player, 16)] = (300, 2); // Mana Conversion trained + Claim(HealKind); + rig.B.CheckVitals(); + CombatHook.Decide(OpenSeq(HealKind), HealKind, (uint)heal, 0, 0); + rig.B.CheckVitals(); + Check.Eq(FakeHost.Casts.Single(), (Player, heal), "the script's Heal Self V is cast"); + rig.B.OnChatWindowText("You don't have enough Mana to cast this spell.", 0); + Check.False(rig.B.RecoveryRetryOpen, "a script heal: no fast-retry episode"); + Check.True(FakeHost.Logs.Any(l => l.Contains("not enough mana; resting the family 2s")), "the 2 s heal rest, as before"); + Check.False(FakeHost.Logs.Any(l => l.Contains("retrying in 200 ms")), "no retry line"); + }); + private static void NoJudgeSkipsBlacklist() => Guard(() => { int drain = Id("Drain Health Other V"); @@ -951,6 +980,310 @@ internal static class CombatHookTests } }); + // In a client log, three healthy targets were blacklisted "after 3 no-damage casts" whose casts + // the server had refused with UseDone 0x1D. + private static void RefusedCastsNotJudged() => Guard(() => + { + int drain = Id("Drain Health Other V"); + foreach (uint answer in new uint[] { 0, ActionPacer.TooBusyErr }) + { + string what = answer == 0 ? "answered 0" : "answered 0x1D"; + var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; }); + rig.S.BlacklistAttempts = 2; + rig.S.EnableRaycasting = false; + Claim(Atk); + for (int i = 0; i < 2; i++) + { + ScriptCast(rig, drain); + Check.Eq(FakeHost.Casts.Count, i + 1, $"{what}: cast {i + 1} went out"); + FakeHost.UseDone(answer); + SetField(rig.C, "_pendingOffensiveCastAt", DateTime.Now.AddSeconds(-5)); + CallPrivate(rig.C, "JudgePendingOffensiveCast"); + if (Field(rig.C, "_pendingJudgeCastAt") != DateTime.MinValue) + SetField(rig.C, "_pendingJudgeCastAt", DateTime.Now.AddSeconds(-30)); + CallPrivate(rig.C, "JudgePendingCast"); + } + if (answer == 0) + Check.Eq(rig.C.activeTargetId, 0, "answered 0: two no-damage casts blacklist and drop the target"); + else + { + Check.Eq(rig.C.activeTargetId, Target, "answered 0x1D: refusals are not casts, the target is kept"); + Check.Eq(rig.C.RefusedCastsNotJudged, 2, "both kept out of the count"); + Check.True(FakeHost.Logs.Any(l => l.Contains("refused 'too busy' (UseDone 0x1D): not counted")), "logged"); + } + } + }); + + private static void LastErrIsTheCastsAnswer() => Guard(() => + { + int drain = Id("Drain Health Other V"); + var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; }); + FakeHost.UseDone(0); // an earlier answer + CombatHook.LastUseDone = () => (FakeHost.UseDoneSeq, FakeHost.LastUseDoneError); + try + { + Claim(Atk); + ScriptCast(rig, drain); + uint firstSeq = CombatHook.Attack.PendingSeq; + rig.Attack(); // the next request opens + Check.True(CombatHook.Poll(Atk, out var r1), "a request is open"); + Check.Eq(r1.PendingSpell, (uint)drain, "ctx.pending: the drain, in flight"); + Check.Eq(r1.PendingSeq, firstSeq, "ctx.pending.seq"); + Check.Eq(r1.ResolvedSpell, 0u, "ctx.last: no resolved cast yet"); + Check.Eq(r1.ResolvedErr, -1, "no answer: -1 (nil in Lua)"); + FakeHost.UseDone(ActionPacer.TooBusyErr); + CombatHook.ObserveUseDone(); + FakeHost.UseDone(0); // a later answer (another action) must not overwrite it + CombatHook.ObserveUseDone(); + Check.True(CombatHook.Poll(Atk, out var r2), "still open"); + Check.Eq((r2.ResolvedSeq, r2.ResolvedSpell), (firstSeq, (uint)drain), "ctx.last: the drain, resolved"); + Check.Eq(r2.ResolvedErr, (int)ActionPacer.TooBusyErr, "its own answer: 0x1D, final"); + Check.Eq(r2.PendingSpell, 0u, "ctx.pending: none"); + + // Its first answer missed (two UseDones before RynthAi looked): resolved with none (-1), + // not with the second one's error. + ScriptCast(rig, drain); + uint secondSeq = CombatHook.Attack.PendingSeq; + Check.True(secondSeq != 0 && secondSeq != firstSeq, "the second cast is in flight"); + FakeHost.UseDone(ActionPacer.TooBusyErr); + FakeHost.UseDone(0); + CombatHook.ObserveUseDone(); + rig.Attack(); + Check.True(CombatHook.Poll(Atk, out var r3), "a request is open"); + Check.Eq(r3.ResolvedSeq, secondSeq, "ctx.last: the second cast"); + Check.Eq(r3.ResolvedErr, -1, "its answer was not read: -1, not the later 0"); + + // No UseDone at all: resolved with none after ResolveTimeoutMs. + ScriptCast(rig, drain); + uint thirdSeq = CombatHook.Attack.PendingSeq; + _now += RynthAiCombat.ResolveTimeoutMs - 1; + CombatHook.ObserveUseDone(); + Check.Eq(CombatHook.Attack.PendingSeq, thirdSeq, "just under the timeout: still in flight"); + _now += 1; + CombatHook.ObserveUseDone(); + Check.Eq((CombatHook.Attack.ResolvedSeq, CombatHook.Attack.ResolvedErr), (thirdSeq, -1), "at the timeout: resolved, no answer"); + +// The next cast goes out before any answer to this one: this one resolves first, with none. + uint SendOne() + { + Claim(Atk); // the lease ran out with the clock + var slot = CombatHook.Attack; + CombatHook.Step(slot, 0x80000777u, () => new CombatRequestV1(), null, out _, out _, out _); + Check.True(CombatHook.Decide(slot.Request.Seq, Atk, (uint)drain, 0, 0), "decided"); + Check.Eq(CombatHook.Step(slot, 0x80000777u, () => new CombatRequestV1(), null, out _, out _, out _), CombatHook.Outcome.Decided, "taken"); + uint seq = slot.Request.Seq; + CombatHook.Cast(slot, (uint)drain, 0x80000777u); + return seq; + } + uint fourthSeq = SendOne(); + Check.Eq(CombatHook.Attack.PendingSeq, fourthSeq, "the fourth cast is in flight"); + uint fifthSeq = SendOne(); + Check.Eq(CombatHook.Attack.PendingSeq, fifthSeq, "the fifth cast is in flight"); + Check.Eq((CombatHook.Attack.ResolvedSeq, CombatHook.Attack.ResolvedErr), (fourthSeq, -1), "the fourth: resolved by the fifth's send, no answer"); + } + finally { CombatHook.LastUseDone = null; } + }); + + // An attack unanswered, then a heal sent: the UseDones answer them in send order. + private static void AnswersInSendOrder() => Guard(() => + { + int drain = Id("Drain Health Other V"); + int heal = Id("Heal Other V"); + var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; }); + FakeHost.UseDone(0); + CombatHook.LastUseDone = () => (FakeHost.UseDoneSeq, FakeHost.LastUseDoneError); + try + { + Claim(Atk | HealKind); + uint Send(CombatHook.Slot slot, uint kind, int spell) + { + CombatHook.Step(slot, 0x80000777u, () => new CombatRequestV1(), null, out _, out _, out _); + Check.True(CombatHook.Decide(slot.Request.Seq, kind, (uint)spell, 0, 0), "decided"); + Check.Eq(CombatHook.Step(slot, 0x80000777u, () => new CombatRequestV1(), null, out _, out _, out _), CombatHook.Outcome.Decided, "taken"); + uint seq = slot.Request.Seq; + CombatHook.Cast(slot, (uint)spell, 0x80000777u); + return seq; + } + uint atkSeq = Send(CombatHook.Attack, Atk, drain); + uint healSeq = Send(CombatHook.Heal, HealKind, heal); + Check.Eq(CombatHook.Attack.PendingSeq, atkSeq, "the attack is in flight"); + Check.Eq(CombatHook.Heal.PendingSeq, healSeq, "the heal is in flight"); + FakeHost.UseDone(0x401); + CombatHook.ObserveUseDone(); + Check.Eq((CombatHook.Attack.ResolvedSeq, CombatHook.Attack.ResolvedErr), (atkSeq, 0x401), "the first answer is the attack's"); + Check.Eq(CombatHook.Heal.PendingSeq, healSeq, "the heal waits for its own"); + FakeHost.UseDone(0); + CombatHook.ObserveUseDone(); + Check.Eq((CombatHook.Heal.ResolvedSeq, CombatHook.Heal.ResolvedErr), (healSeq, 0), "the second is the heal's"); + } + finally { CombatHook.LastUseDone = null; } + }); + + // -- The stuck-cast breaker and the hook: both hook paths mark their cast as a script's + // (ActionPacer.MarkScriptCast), and the breaker gives it ScriptCastMinBreakMs from the send. + + private static long _paceT; + + private static void PacerGates() + { + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.TapJumpCalls = true; + } + + private static void PaceOn() + { + _paceT = 70_000_000; + ActionPacer.Reset(); + ActionPacer.Enabled = true; + ActionPacer.NowMs = () => _paceT; + MoveAudit.Reset(); + MoveAudit.NowMs = () => _paceT; + ActionPacer.StuckCastMs = 8000; + FakeHost.UseDone(0); // an earlier action's answer: the observer's baseline + } + + private static void PaceOff() + { + ActionPacer.Enabled = false; + ActionPacer.Reset(); + ActionPacer.NowMs = () => Environment.TickCount64; + MoveAudit.Reset(); + MoveAudit.NowMs = () => Environment.TickCount64; + ActionPacer.StuckCastMs = 8000; + } + + /// The pacer's checks every 100 ms for (no UseDone comes). + private static void RunPacer(RynthCoreHost host, long ms) + { + for (long s = 0; s < ms; s += 100) { _paceT += 100; ActionPacer.MayStart(host, "Test", HealNeed.Heal, out _); } + } + + /// A heal let ahead of the open cast, answered 'too busy' (the refusal trigger). + private static void RefuseAnother(RynthCoreHost host) + { + int heal = Id("Heal Self V"); + Check.True(host.CastSpellFor(Player, heal, "Buff", "Heal Self V"), "another send"); + FakeHost.UseDone(ActionPacer.TooBusyErr); + } + + private static void ScriptHealCast(HealRig rig, int drain) + { + Claim(HealKind); + rig.B.CheckVitals(); + CombatHook.Decide(OpenSeq(HealKind), HealKind, (uint)drain, (uint)Target, 0); + rig.B.CheckVitals(); + Check.Eq(FakeHost.Casts.Single(), ((uint)Target, drain), "the script's drain went out"); + } + + private static void ScriptAttackNotJumpedEarly() => Guard(() => + { + int drain = Id("Drain Health Other V"); + var own = new AttackRig(setup: PacerGates); + PaceOn(); + try + { + Check.True(own.Host.CastSpellFor((uint)Target, drain, "Combat", "Drain Health Other V"), "control: RynthAi's own cast"); + RunPacer(own.Host, 5500); + Check.Eq(FakeHost.TapJumps, 1, "control: RynthAi's own cast is jumped at 5 s (cycle 3 s + 2 s)"); + } + finally { PaceOff(); } + + var rig = new AttackRig(setup: PacerGates); + PaceOn(); + try + { + Claim(Atk); + ScriptCast(rig, drain); + Check.Eq(FakeHost.Casts.Last(), ((uint)Target, drain), "the script's drain went out"); + RunPacer(rig.Host, 5500); + Check.Eq(FakeHost.TapJumps, 0, "a script attack: no jump in 5.5 s"); + } + finally { PaceOff(); } + }); + + private static void ScriptHealNotJumpedEarly() => Guard(() => + { + int drain = Id("Drain Health Other V"); + var rig = new HealRig(setup: PacerGates); + PaceOn(); + try + { + ScriptHealCast(rig, drain); + RunPacer(rig.Host, 5500); + Check.Eq(FakeHost.TapJumps, 0, "a script heal: no jump in 5.5 s"); + } + finally { PaceOff(); } + }); + + private static void ScriptAttackRefusalNoEarlyJump() => Guard(() => + { + int drain = Id("Drain Health Other V"); + var own = new AttackRig(setup: PacerGates); + PaceOn(); + try + { + Check.True(own.Host.CastSpellFor((uint)Target, drain, "Combat", "Drain Health Other V"), "control: RynthAi's own cast"); + RunPacer(own.Host, 3500); + Check.Eq(FakeHost.TapJumps, 0, "control: no jump before the refusal"); + RefuseAnother(own.Host); + RunPacer(own.Host, 200); + Check.Eq(FakeHost.TapJumps, 1, "control: a 0x1D past 3 s jumps RynthAi's own cast at once"); + } + finally { PaceOff(); } + + var rig = new AttackRig(setup: PacerGates); + PaceOn(); + try + { + Claim(Atk); + ScriptCast(rig, drain); + RunPacer(rig.Host, 3500); + RefuseAnother(rig.Host); + RunPacer(rig.Host, 2000); + Check.Eq(FakeHost.TapJumps, 0, "a script attack: a 0x1D at 3.5 s does not jump it by 5.5 s"); + } + finally { PaceOff(); } + }); + + private static void ScriptHealRefusalNoEarlyJump() => Guard(() => + { + int drain = Id("Drain Health Other V"); + var rig = new HealRig(setup: PacerGates); + PaceOn(); + try + { + ScriptHealCast(rig, drain); + RunPacer(rig.Host, 3500); + RefuseAnother(rig.Host); + RunPacer(rig.Host, 2000); + Check.Eq(FakeHost.TapJumps, 0, "a script heal: a 0x1D at 3.5 s does not jump it by 5.5 s"); + } + finally { PaceOff(); } + }); + + private static void AnswerDuringSendIsTheCasts() => Guard(() => + { + int drain = Id("Drain Health Other V"); + var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; }); + FakeHost.UseDone(0); // an earlier answer + CombatHook.LastUseDone = () => (FakeHost.UseDoneSeq, FakeHost.LastUseDoneError); + try + { + Claim(Atk); + FakeHost.AfterCastSpell = () => FakeHost.UseDone(0x402); // the answer lands before CombatHook.Cast runs + ScriptCast(rig, drain); + FakeHost.AfterCastSpell = null; + uint seq = CombatHook.Attack.PendingSeq; + Check.True(seq != 0, "the drain is in flight"); + rig.Attack(); // the next request opens (ctx as the script sees it) + Check.True(CombatHook.Poll(Atk, out var r), "a request is open"); + Check.Eq((r.ResolvedSeq, r.ResolvedSpell), (seq, (uint)drain), "ctx.last: the drain"); + Check.Eq(r.ResolvedErr, 0x402, "ctx.last.err: the answer that came during the send"); + } + finally { CombatHook.LastUseDone = null; FakeHost.AfterCastSpell = null; } + }); + private static void ScriptCastAttribution() => Guard(() => { int shock = Id("Shock Wave IV"); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HealLatencyTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HealLatencyTests.cs index 665621e..c1f25c4 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/HealLatencyTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/HealLatencyTests.cs @@ -184,6 +184,9 @@ internal static class HealLatencyTests { var r = new Rig(healthPct: 40, manaPct: 2); r.S.GetManaAt = 50; r.S.TopOffMana = 50; + // Mana Conversion untrained: the rests below. Trained, a recovery vital retries in 200 ms + // instead (RecoveryRetryTests). + FakeHost.Skills[(Player, 16)] = (10, 1); 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); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HpFailsafeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HpFailsafeTests.cs new file mode 100644 index 0000000..8c4568f --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/HpFailsafeTests.cs @@ -0,0 +1,363 @@ +using System; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// HP failsafe: under Emergency Heal At with heals failing (here: every heal sent and never answered, +// as in a client log's hung casts), the character must not sit and die. 3 rounds of 2.5 s with no +// rise: a forced jump (ActionPacer.ForceBreak), then healing again; 3 more: the macro stops and +// "/lifestone" goes out (HpFailsafeRecall, default on). +internal static class HpFailsafeTests +{ + private const uint Player = 0x50000B31; + private const uint STypeLife = 33; + + public static void Register(Runner r) + { + r.Add("hp failsafe: 7.5 s at Emergency Heal At with no heal landing -> one jump; 7.5 s more -> macro stop and /lifestone", BreakThenRecall); + r.Add("hp failsafe: a heal landing (+3%) restarts the count; health over the line ends it", HealLandingResets); + r.Add("hp failsafe: HP Failsafe Recall off -> the jump still, no recall; no recall line -> 3 sends, then it gives up", RecallOffAndResends); + r.Add("hp failsafe: a recall that never starts turns the macro back on and re-arms; the next recall after 30 s", FailedRecallResumes); + r.Add("hp failsafe: another player's recall line is not ours; ours with its first letter dropped is", RecallLineIsOurs); + r.Add("hp failsafe: Emergency Heal At 100 at full health is not an emergency", FullHealthAtHundred); + r.Add("hp failsafe: nothing counts in portal space", NothingInPortalSpace); + r.Add("hp failsafe: a death drops the pending recall (0 health, and the plugin's death hold): no /lifestone, the macro stays off", DeathDropsRecall); + r.Add("hp failsafe: a failed recall does not switch the macro back on past a VTank yield", VTankYieldRespected); + r.Add("hp failsafe: our name unreadable: the recall line is taken as ours, and that is logged once", RecallNameUnreadable); + r.Add("vitals (L8):a heal the server leaves unanswered is not re-sent at the 2.5 s give-up after a 'too busy' answer", VitalResendObeysLatch); + } + + // No re-send into a busy server: a client log re-sent a heal every 2.5 s (the vitals give-up) into a server + // answering 0x1D. Through the whole vitals step (BuffManager heartbeats, pacer on, the pacer's + // breaker off to isolate the latch): a heal goes out, the server never answers it, and another + // send is refused 0x1D. No heal is re-sent while that heal is unanswered. + private static void VitalResendObeysLatch() + { + try + { + var r = new Rig(healthPct: 40); + r.S.EmergencyHealAt = 0; // the failsafe out of it + r.S.SpellCastIntervalMs = 100; + r.Run(0, 0); + Check.Eq(FakeHost.Casts.Count, 1, "the heal goes out (and is never answered)"); + r.Run(0.1, 0.5); + int heal = FakeHost.Casts[0].SpellId; + // Another send goes out over the open heal (as when a cast hangs) and is refused 'too busy'. + Check.True(r.Host.CastSpellFor(0x80000AAAu, 1237, "Combat", "Drain Health Other I"), "the other send"); + FakeHost.UseDone(ActionPacer.TooBusyErr); + // Real time too: BuffManager's own retry limits run on the real clock. + for (int ms = 600; ms <= 6000; ms += 200) { System.Threading.Thread.Sleep(200); r.At(ms / 1000.0); r.B.OnHeartbeat(); } + Check.Eq(FakeHost.Casts.Count(c => c.SpellId == heal), 1, "no heal re-sent in 6 s (the 2.5 s give-up re-sent one before): " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("[Pace]") || l.Contains("[Buff")).Take(20))); + Check.True(r.Logged("Buff waits:") && r.Logged("nothing goes until the server answers"), "the hold is logged: " + string.Join(" | ", FakeHost.Logs.Take(30))); + } + finally { Done(); } + } + + private sealed class Rig + { + public DateTime T0 = new(2026, 10, 10, 19, 0, 0); + public DateTime NowAt; + public readonly BuffManager B; + public readonly LegacyUiSettings S; + public readonly PlayerVitalsCache V; + public readonly RynthCore.PluginSdk.RynthCoreHost Host; + public int MacroStops; + + public Rig(int healthPct = 20) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.TapJumpCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + FakeHost.Names[Player] = "Mira"; + FakeHost.PlayerPose = (0x6347028Au, 100f, 100f, 0f); + FakeHost.Positions[Player] = FakeHost.PlayerPose; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + var host = Host = FakeHost.Create(Player); + 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, SpellCastIntervalMs = 100, + }; + 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 = 100, + }; + B = new BuffManager(host, S, sm, V); + B.SetCharacterSkills(skills); + B.MacroStopForRecall = () => MacroStops++; + NowAt = T0; + B.Clock = () => NowAt; + B.MarkLiveBuffsReadyForTests(); + + ActionPacer.Reset(); + ActionPacer.Enabled = true; + ActionPacer.StuckCastMs = 0; // the pacer's own breaker off: only the failsafe jumps here + ActionPacer.NowMs = () => 50_000_000 + (long)(NowAt - T0).TotalMilliseconds; + MoveAudit.Reset(); + MoveAudit.NowMs = ActionPacer.NowMs; + FakeHost.UseDone(0); + } + + public void At(double seconds) => NowAt = T0.AddMilliseconds(Math.Round(seconds * 1000)); + public bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal)); + + /// Heartbeats every 100 ms from up to and including . + public void Run(double from, double to) + { + for (int ms = (int)Math.Round(from * 1000); ms <= (int)Math.Round(to * 1000); ms += 100) + { + At(ms / 1000.0); + B.OnHeartbeat(); + } + } + } + + private static void Done() + { + ActionPacer.Enabled = false; + ActionPacer.Reset(); + ActionPacer.NowMs = () => Environment.TickCount64; + ActionPacer.StuckCastMs = 8000; + MoveAudit.Reset(); + MoveAudit.NowMs = () => Environment.TickCount64; + } + + private static void BreakThenRecall() + { + try + { + var r = new Rig(healthPct: 20); + r.Run(0, 7.4); + Check.True(FakeHost.Casts.Count > 0, "a heal went out (and is never answered)"); + Check.Eq(FakeHost.TapJumps, 0, "7.4 s: no jump yet"); + r.Run(7.5, 7.5); + Check.Eq(FakeHost.TapJumps, 1, "7.5 s (3 rounds, no rise): one jump"); + Check.Eq(r.B.HpFailsafeBreaks, 1, "counted"); + Check.True(r.Logged("HP failsafe: health 20% at or under Emergency Heal At 30%, no heal landed in 7.5 s: breaking the cast with a jump"), + "the break is logged"); + r.Run(7.6, 14.9); + Check.Eq(FakeHost.TapJumps, 1, "only one jump"); + Check.True(r.S.IsMacroRunning, "14.9 s: still running"); + r.Run(15.0, 15.0); + Check.False(r.S.IsMacroRunning, "15 s (3 more rounds): the macro is stopped"); + Check.Eq(r.MacroStops, 1, "with the rest of a /ra stop"); + Check.Eq(r.B.HpFailsafeRecalls, 1, "counted"); + Check.True(FakeHost.Chat.Any(c => c.Contains("recalling to the lifestone")), "and said in chat"); + Check.Eq(FakeHost.ChatCommands.Count, 0, "the recall waits for the stop to take effect"); + r.Run(15.1, 15.5); + Check.Eq(FakeHost.ChatCommands.Count, 0, "500 ms later: still waiting for the stop to take effect"); + r.Run(15.6, 15.6); + Check.Eq(FakeHost.ChatCommands.Count, 1, "600 ms later: one recall"); + Check.Eq(FakeHost.ChatCommands[0], BuffManager.RecallCommand, "/lifestone"); + r.B.OnChatWindowText("Mira is recalling to the lifestone.", 0); + r.Run(15.7, 20); + Check.Eq(FakeHost.ChatCommands.Count, 1, "the recall line: no resend"); + Check.True(r.Logged("HP failsafe: the recall started"), "logged"); + } + finally { Done(); } + } + + private static void HealLandingResets() + { + try + { + var r = new Rig(healthPct: 20); + r.Run(0, 5.0); + r.V.CurrentHealth = 22; // +2: regeneration, not a heal + r.Run(5.1, 7.5); + Check.Eq(FakeHost.TapJumps, 1, "+2% is not a heal landing: the jump at 7.5 s"); + + var h = new Rig(healthPct: 20); + h.Run(0, 5.0); + h.V.CurrentHealth = 23; // +3: a heal landed + h.Run(5.1, 12.4); + Check.Eq(FakeHost.TapJumps, 0, "a heal landed at 5 s: no jump at 7.5 s, none by 12.4 s"); + h.Run(12.5, 12.6); + Check.Eq(FakeHost.TapJumps, 1, "7.5 s after the heal with no other: the jump"); + + var o = new Rig(healthPct: 20); + o.Run(0, 5.0); + o.V.CurrentHealth = 31; // over Emergency Heal At 30 + o.Run(5.1, 5.1); + o.V.CurrentHealth = 20; + o.Run(5.2, 12.6); + Check.Eq(FakeHost.TapJumps, 0, "over the line at 5.1 s: the count started again at 5.2 s"); + Check.True(o.Logged("HP failsafe: health back to 31%"), "the end is logged"); + } + finally { Done(); } + } + + private static void RecallOffAndResends() + { + try + { + var r = new Rig(healthPct: 20); + r.S.HpFailsafeRecall = false; + r.Run(0, 20); + Check.Eq(FakeHost.TapJumps, 1, "recall off: the jump still"); + Check.True(r.S.IsMacroRunning, "recall off: the macro keeps running"); + Check.Eq(FakeHost.ChatCommands.Count, 0, "no recall"); + Check.True(r.Logged("HP Failsafe Recall is off"), "said once in the log"); + + var n = new Rig(healthPct: 20); + n.Run(0, 15.0); + Check.False(n.S.IsMacroRunning, "recall: macro stopped"); + n.Run(15.1, 25); + Check.Eq(FakeHost.ChatCommands.Count, 3, "no recall line: sent 3 times, 1.5 s apart, then stopped"); + Check.True(n.Logged("no recall seen after 3 tries"), "and logged"); + } + finally { Done(); } + } + + // A recall that never starts must not leave the macro stopped at low health. + private static void FailedRecallResumes() + { + try + { + var n = new Rig(healthPct: 20); + n.Run(0, 15.0); + Check.False(n.S.IsMacroRunning, "recall: macro stopped"); + n.Run(15.1, 21.0); + Check.Eq(FakeHost.ChatCommands.Count, 3, "3 tries, no recall line"); + Check.True(n.S.IsMacroRunning, "the macro is back on (the heals and kits run again)"); + Check.Eq(n.B.HpFailsafeRecallsFailed, 1, "a failed recall counted"); + Check.True(FakeHost.Chat.Any(c => c.Contains("macro back on to keep healing")), "said in chat"); + n.Run(21.1, 49.0); + Check.Eq(FakeHost.ChatCommands.Count, 3, "inside the 30 s cooldown: no recall"); + Check.True(n.S.IsMacroRunning, "and the macro keeps running"); + int breaks = FakeHost.Logs.Count(l => l.Contains("HP failsafe: health 20% at or under Emergency Heal At 30%, no heal landed in")); + Check.True(breaks >= 2, $"the failsafe re-armed: it reached the break stage again ({breaks})"); + n.Run(49.1, 75.0); + Check.Eq(n.B.HpFailsafeRecalls, 2, "after the cooldown: the next recall"); + Check.True(FakeHost.ChatCommands.Count > 3, "sent"); + } + finally { Done(); } + } + + // Only our own recall line ends the wait. + private static void RecallLineIsOurs() + { + try + { + var r = new Rig(healthPct: 20); + r.Run(0, 15.6); + Check.Eq(FakeHost.ChatCommands.Count, 1, "the first recall"); + r.B.OnChatWindowText("Bob is recalling to the lifestone.", 0); + r.Run(15.7, 17.1); + Check.Eq(FakeHost.ChatCommands.Count, 2, "another player's recall line: sent again"); + Check.False(r.Logged("HP failsafe: the recall started"), "not taken as ours"); + r.B.OnChatWindowText("ira is recalling to the lifestone.", 0); // the first letter dropped by the chat layer + r.Run(17.2, 22); + Check.Eq(FakeHost.ChatCommands.Count, 2, "ours (first letter dropped): no more sends"); + Check.True(r.Logged("HP failsafe: the recall started"), "logged"); + } + finally { Done(); } + } + + // Emergency Heal At 100 at full health is not an emergency. + private static void FullHealthAtHundred() + { + try + { + var r = new Rig(healthPct: 100); + r.S.EmergencyHealAt = 100; + r.Run(0, 20); + Check.Eq(FakeHost.TapJumps, 0, "100% at Emergency Heal At 100: no break"); + Check.True(r.S.IsMacroRunning, "no recall"); + } + finally { Done(); } + } + + // A pending recall is dropped on death: after the respawn it must not send /lifestone or switch + // the macro on, against Stop Macro On Death. + private static void DeathDropsRecall() + { + try + { + var r = new Rig(healthPct: 20); + r.Run(0, 15.0); + Check.False(r.S.IsMacroRunning, "recall pending: macro stopped"); + r.V.CurrentHealth = 0; // dead before the first send + r.Run(15.1, 30); + Check.Eq(FakeHost.ChatCommands.Count, 0, "0 health: no /lifestone"); + Check.False(r.S.IsMacroRunning, "the macro stays off"); + Check.True(r.Logged("the pending recall is dropped (dead)"), "logged"); + + // The plugin's death hold drops it too (the vitals cache still reads the old health). + var p = new Rig(healthPct: 20); + p.Run(0, 15.0); + var plugin = new RynthAiPlugin(); + PacerEdgeTests.SetHost(plugin, p.Host); + typeof(RynthAiPlugin).GetField("_buffManager", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.SetValue(plugin, p.B); + FakeHost.Vitals = (0, 100, 0, 100, 0, 100); + typeof(RynthAiPlugin).GetMethod("HoldForDeath", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.Invoke(plugin, null); + p.Run(15.1, 30); + Check.Eq(FakeHost.ChatCommands.Count, 0, "death hold: no /lifestone after the respawn"); + Check.False(p.S.IsMacroRunning, "death hold: the macro stays off"); + Check.True(p.Logged("the pending recall is dropped (death)"), "logged"); + } + finally { Done(); } + } + + // The failsafe's restart is a macro start like any other. + private static void VTankYieldRespected() + { + try + { + var r = new Rig(healthPct: 20); + r.B.MayRestartMacro = () => false; // VTank runs and yield is on + r.Run(0, 21.0); + Check.Eq(FakeHost.ChatCommands.Count, 3, "3 tries, no recall line"); + Check.False(r.S.IsMacroRunning, "VTank yield: the macro stays off"); + Check.True(FakeHost.Chat.Any(c => c.Contains("the macro stays off (VTank yield)")), "said in chat"); + } + finally { Done(); } + } + + private static void RecallNameUnreadable() + { + try + { + var r = new Rig(healthPct: 20); + FakeHost.Names.Remove(Player); + r.Run(0, 15.6); + Check.Eq(FakeHost.ChatCommands.Count, 1, "the first recall"); + r.B.OnChatWindowText("Bob is recalling to the lifestone.", 0); + r.Run(15.7, 20); + Check.Eq(FakeHost.ChatCommands.Count, 1, "no name to compare: taken as ours, no resend"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("our name could not be read")), 1, "logged once"); + } + finally { Done(); } + } + + // Nothing counts in portal space. + private static void NothingInPortalSpace() + { + try + { + var r = new Rig(healthPct: 20); + FakeHost.Portaling = true; + r.Run(0, 20); + Check.Eq(FakeHost.TapJumps, 0, "portal space: no failsafe jump"); + Check.True(r.S.IsMacroRunning, "no recall"); + Check.Eq(r.B.HpFailsafeBreaks, 0, "nothing counted"); + } + finally { FakeHost.Portaling = false; Done(); } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ManaReserveTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ManaReserveTests.cs index cd88bee..9717823 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ManaReserveTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ManaReserveTests.cs @@ -154,6 +154,9 @@ internal static class ManaReserveTests // and mana regenerates meanwhile with attacks still held. var u = new Rig(mana: 50); BuffManager.ManaCostOverride = _ => 0; + // Mana Conversion untrained: the rest below. Trained, a recovery vital retries in 200 ms + // instead (RecoveryRetryTests). + FakeHost.Skills[(Player, 16)] = (10, 1); Check.True(u.B.CheckVitals(), "50/383 under Get Mana At: Stamina to Mana goes"); Check.Eq(FakeHost.Casts.Count, 1, "one cast"); u.B.OnChatWindowText(NotEnoughMana, 0); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PacerEdgeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PacerEdgeTests.cs new file mode 100644 index 0000000..58ff5df --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PacerEdgeTests.cs @@ -0,0 +1,335 @@ +using System; +using System.Linq; +using System.Reflection; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Bounds on the pacer's holds: the 0x1D latch must not throttle melee and missile (ACE sends no +// UseDone for a swing), StuckCastMs = 0 must not hold for ever, a teleport's gap must not break a +// cast by jump, the settle gate stands apart from the animation gate, and only 'too busy' answers +// count toward the refusal burst. +internal static class PacerEdgeTests +{ + private const uint Player = 0x50000F21; + private const uint Monster = 0x80116791; + private const int DrainHealthOtherI = 1237; + private static (uint Cell, float X, float Y, float Z) Me0 => (0x6347028Au, 100f, 100f, 0f); + + public static void Register(Runner r) + { + r.Add("pacer edge: after a lone 'too busy' answer, attack repeats go (over 50 swings in 60 s); a cast with ours open is still held", AttackRepeatsPastLatch); + r.Add("pacer edge: a 'too busy' latch with no cast of ours open ends after LatchMaxMs (logged once)", LatchExpires); + r.Add("pacer edge: StuckCastMs 0 never deadlocks: a hung cast is dropped as stale by StaleCastMs (inside 120 s)", StuckCastZeroBounded); + r.Add("pacer edge: in portal space nothing is broken (no jump, ForceBreak refused); a cast sent before a 20 s gap is dropped, not jumped", PortalAndGap); + r.Add("pacer edge: 5 'too busy' answers in one second hold every start but a heal, attack repeats too, for the rest of that second", RefusalBurst); + r.Add("pacer edge: the settle gate holds a start with the animation gate off", SettleGateSplit); + r.Add("pacer edge: portal-enter and the death hold forget the open cast and the latch", PortalAndDeathForget); + r.Add("pacer edge: a client-refused forced jump with no cast open does not hold starts for good (latch expiry, probe)", RefusedForcedJumpNoDeadlock); + r.Add("pacer edge: the refusal burst counts 'too busy' only and never holds a heal", BurstCountsTooBusyAndSparesHeals); + } + + private static long _t; + + private static RynthCoreHost Setup() + { + FakeHost.Reset(); + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.WeaponCalls = true; + FakeHost.CombatModeCalls = true; + FakeHost.TapJumpCalls = true; + FakeHost.CombatModeValue = ActionPacer.MagicMode; + FakeHost.Names[Player] = "Mira"; + FakeHost.PlayerPose = Me0; + FakeHost.Positions[Player] = Me0; + FakeHost.Positions[Monster] = (Me0.Cell, Me0.X + 10f, Me0.Y, Me0.Z); + var host = FakeHost.Create(Player); + _t = 70_000_000; + ActionPacer.Reset(); + ActionPacer.Enabled = true; + ActionPacer.NowMs = () => _t; + MoveAudit.Reset(); + MoveAudit.NowMs = () => _t; + ActionPacer.StuckCastMs = 8000; + FakeHost.UseDone(0); + ActionPacer.MayStart(host, "Setup", HealNeed.None, out _); // the UseDone observer's baseline + return host; + } + + private static void Done() + { + ActionPacer.Enabled = false; + ActionPacer.Reset(); + ActionPacer.NowMs = () => Environment.TickCount64; + MoveAudit.Reset(); + MoveAudit.NowMs = () => Environment.TickCount64; + ActionPacer.StuckCastMs = 8000; + FakeHost.Portaling = false; + } + + private static bool May(RynthCoreHost host) => ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _); + private static bool Swing(RynthCoreHost host, out string why) => + ActionPacer.MayStart(host, "Combat", HealNeed.None, out why, animationGate: false, settleGate: false, attackRepeat: true); + private static void Cast(RynthCoreHost host) => + Check.True(host.CastSpellFor(Monster, DrainHealthOtherI, "Buff", "Drain Health Other I"), "cast sent"); + private static int Jumps() => FakeHost.TapJumps + FakeHost.Jumps; + + private static void AttackRepeatsPastLatch() + { + var host = Setup(); + try + { + FakeHost.CombatModeValue = 2; // melee + FakeHost.UseDone(ActionPacer.TooBusyErr); // a lone 0x1D (a pickup, a player command) + Check.False(May(host), "a gated start is held by the latch"); + Check.True(ActionPacer.ServerBusy, "latched"); + int swings = 0; + for (int i = 0; i < 60; i++) + { + _t += 1000; + if (Swing(host, out _)) { swings++; ActionPacer.NoteAttackSent(); } + } + Check.True(swings > 55, $"a swing a second for 60 s after the 0x1D (no UseDone ever comes for a swing): {swings}"); + + // Our cast open (hung past CastMaxMs) and another send refused 'too busy': a cast is still held. + var h2 = Setup(); + ActionPacer.StuckCastMs = 0; + Cast(h2); + _t += ActionPacer.CastMaxMs + 100; + Check.False(May(h2), "our cast hung"); + FakeHost.UseDone(ActionPacer.TooBusyErr); + bool any = false; + for (int i = 0; i < 50; i++) { _t += 100; any |= May(h2); } + Check.False(any, "a cast with ours open and refused: held"); + } + finally { Done(); } + } + + private static void LatchExpires() + { + var host = Setup(); + ActionPacer.StuckCastMs = 0; + try + { + FakeHost.UseDone(ActionPacer.TooBusyErr); + May(host); // observed here: the latch starts + long t0 = _t; + while (_t + 100 < t0 + ActionPacer.LatchMaxMs) { _t += 100; May(host); } + Check.True(ActionPacer.ServerBusy, "still latched just under LatchMaxMs"); + Check.Eq(ActionPacer.LatchExpiries, 0L, "no expiry yet"); + _t = t0 + ActionPacer.LatchMaxMs; + Check.True(May(host), "at LatchMaxMs: free"); + Check.False(ActionPacer.ServerBusy, "the latch is gone"); + Check.Eq(ActionPacer.LatchExpiries, 1L, "one expiry"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("no answer cleared the 'too busy' latch in")), 1, "logged once"); + } + finally { Done(); } + } + + private static void StuckCastZeroBounded() + { + var host = Setup(); + ActionPacer.StuckCastMs = 0; + try + { + Cast(host); + long t0 = _t; + _t += ActionPacer.CastMaxMs + 100; + Check.False(May(host), "our cast hung"); + FakeHost.UseDone(ActionPacer.TooBusyErr); // another send refused while it is open + long freeAt = -1; + while (_t < t0 + 120_000) { _t += 100; if (May(host)) { freeAt = _t - t0; break; } } + Check.True(freeAt > 0, "free within 120 s"); + Check.True(freeAt >= ActionPacer.StaleCastMs - 100 && freeAt <= ActionPacer.StaleCastMs + 100, $"free at StaleCastMs ({ActionPacer.StaleCastMs}): {freeAt}"); + Check.Eq(Jumps(), 0, "StuckCastMs 0: no jump"); + Check.True(FakeHost.Logs.Any(l => l.Contains("is stale (") && l.Contains("dropped, the server is taken as free")), "logged"); + } + finally { Done(); } + } + + private static void PortalAndGap() + { + var host = Setup(); + try + { + Cast(host); + FakeHost.Portaling = true; + for (int i = 0; i < 150; i++) { _t += 100; May(host); } // 15 s in portal space + Check.Eq(Jumps(), 0, "portal space: no breaker jump"); + Check.False(ActionPacer.ForceBreak(host, "test"), "portal space: ForceBreak refused"); + Check.Eq(Jumps(), 0, "still no jump"); + FakeHost.Portaling = false; + + // A 20 s gap with no check (a freeze, a long portal with the macro off): stale, dropped. + // The tick's frame, then the cast 5 ms later in the same tick, then the freeze. + var g = Setup(); + ActionPacer.NoteFrame(); + _t += 5; + Cast(g); + _t += 20_000; + ActionPacer.NoteFrame(); // the first frame after the freeze + Check.True(May(g), "after the gap: the cast is dropped and starts go"); + Check.Eq(Jumps(), 0, "no jump for a cast sent before the gap"); + Check.Eq(ActionPacer.StaleDrops, 1L, "one stale drop"); + Check.True(FakeHost.Logs.Any(l => l.Contains("is stale (") && l.Contains("ms gap with no check")), "the gap is in the line"); + + // Control: the same 20 s with frames every 100 ms is a stuck cast, broken by the jump. + var c = Setup(); + Cast(c); + for (int i = 0; i < 200; i++) { _t += 100; ActionPacer.NoteFrame(); May(c); } + Check.True(Jumps() >= 1, "no gap: the stuck cast is broken (control)"); + Check.Eq(ActionPacer.StaleDrops, 0L, "and not dropped"); + } + finally { Done(); } + } + + private static void RefusalBurst() + { + var host = Setup(); + try + { + FakeHost.CombatModeValue = 2; + string why = ""; + bool[] free = new bool[ActionPacer.RefusalBurstMax]; + for (int i = 0; i < ActionPacer.RefusalBurstMax; i++) + { + FakeHost.UseDone(ActionPacer.TooBusyErr); + _t += 50; + free[i] = Swing(host, out why); + } + Check.True(free.Take(ActionPacer.RefusalBurstMax - 1).All(b => b), "4 refusals: still free"); + Check.False(free[^1], "the 5th refusal inside a second: held"); + Check.True(why.Contains("refusals from the server in the last second"), "why: " + why); + Check.False(May(host), "a gated start too"); + Check.True(ActionPacer.BurstHolds >= 1, "counted (the heal start above is held by the latch, not the burst)"); + _t += 1000; + Check.True(Swing(host, out _), "a second later: free"); + } + finally { Done(); } + } + + private static void SettleGateSplit() + { + var host = Setup(); + try + { + FakeHost.AutoRun = true; + host.SetAutoRunBy("Nav", true); + _t += 1000; + host.SetAutoRunBy("Nav", false); // the stop goes out this tick + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out string why, animationGate: false), + "animation gate off, settle gate on: held in the tick of the stop"); + Check.True(why.Length > 0, "why: " + why); + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _, animationGate: false, settleGate: false), + "both off: free (only attack repeats do this)"); + _t += MoveAudit.MoveSettleMinMs; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _, animationGate: false), "settled: free"); + } + finally { Done(); } + } + + // ForceBreak with no cast open and the client refusing the jump must not leave the breaker stage + // at Landed for nothing, which would hold every start for good. + private static void RefusedForcedJumpNoDeadlock() + { + var host = Setup(); + try + { + FakeHost.UseDone(ActionPacer.TooBusyErr); + May(host); // the latch starts here + long t0 = _t; + FakeHost.TapJumpRefuse = true; + Check.True(ActionPacer.ForceBreak(host, "test"), "the forced break is tried"); + Check.Eq(FakeHost.TapJumps, 1, "the jump was sent (and refused)"); + long firstFree = -1; + while (_t < t0 + ActionPacer.LatchMaxMs + 500) { _t += 100; if (May(host) && firstFree < 0) firstFree = _t - t0; } + Check.True(firstFree > 0 && firstFree <= ActionPacer.LatchMaxMs + 100, $"a start goes by LatchMaxMs (first at {firstFree} ms)"); + Check.False(ActionPacer.ServerBusy, "the latch is gone by then"); + Check.Eq(ActionPacer.LatchExpiries, 1L, "it expired"); + } + finally { Done(); } + } + + // 0x401 retries (5 a second by design) do not trip the burst, and the burst never holds a heal. + private static void BurstCountsTooBusyAndSparesHeals() + { + var host = Setup(); + try + { + for (int i = 0; i < ActionPacer.RefusalBurstMax + 1; i++) { FakeHost.UseDone(0x401); _t += 50; May(host); } + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out string w1), "6 'not enough mana' answers in a second: no burst hold (" + w1 + ")"); + Check.Eq(ActionPacer.BurstHolds, 0L, "none counted"); + + var h = Setup(); + for (int i = 0; i < ActionPacer.RefusalBurstMax; i++) + { + FakeHost.UseDone(ActionPacer.TooBusyErr); + _t += 50; + ActionPacer.MayStart(h, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true); + } + FakeHost.UseDone(0); // the server answers: the latch is gone, the burst is not + _t += 50; + Check.False(ActionPacer.MayStart(h, "Buff", HealNeed.None, out string why), "inside the second: a buff is held by the burst"); + Check.True(why.Contains("refusals from the server in the last second"), "why: " + why); + Check.True(ActionPacer.MayStart(h, "Buff", HealNeed.Emergency, out string hw), "an emergency heal is not (" + hw + ")"); + Check.True(ActionPacer.MayStart(h, "Buff", HealNeed.Heal, out _), "nor a heal"); + } + finally { Done(); } + } + + internal static void SetHost(RynthAiPlugin p, RynthCoreHost host) + { + for (Type? t = p.GetType(); t != null; t = t.BaseType) + { + var prop = t.GetProperty("Host", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); + if (prop?.SetMethod != null) { prop.SetValue(p, host); return; } + var f = t.GetField("k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly) + ?? t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly).FirstOrDefault(x => x.FieldType == typeof(RynthCoreHost)); + if (f != null) { f.SetValue(p, host); return; } + } + throw new InvalidOperationException("no Host to set on RynthAiPlugin"); + } + + private static void Call(object o, string name) => + o.GetType().GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(o, null); + + private static void PortalAndDeathForget() + { + var host = Setup(); + try + { + ActionPacer.StuckCastMs = 0; + var p = new RynthAiPlugin(); + SetHost(p, host); + Cast(host); + _t += ActionPacer.CastMaxMs + 100; + FakeHost.UseDone(ActionPacer.TooBusyErr); + May(host); + Check.True(ActionPacer.ServerBusy, "our cast hung, latched"); + Call(p, "NotePortalForPacer"); + Check.True(ActionPacer.ServerBusy, "not portaling: nothing forgotten"); + FakeHost.Portaling = true; + Call(p, "NotePortalForPacer"); + Check.False(ActionPacer.ServerBusy, "portal-enter: the latch is forgotten"); + Check.True(May(host), "and starts go"); + FakeHost.Portaling = false; + Call(p, "NotePortalForPacer"); + + Cast(host); + _t += ActionPacer.CastMaxMs + 100; + FakeHost.UseDone(ActionPacer.TooBusyErr); + May(host); + Check.True(ActionPacer.ServerBusy, "latched again"); + FakeHost.Vitals = (0, 100, 0, 100, 0, 100); + Call(p, "HoldForDeath"); + Check.False(ActionPacer.ServerBusy, "the death hold forgets the latch"); + Check.True(May(host), "and starts go"); + } + finally { Done(); } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/RecoveryRetryTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/RecoveryRetryTests.cs new file mode 100644 index 0000000..5253f7b --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/RecoveryRetryTests.cs @@ -0,0 +1,287 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Recovery retry: Stamina to Mana at about 10 mana took a long time to get off. ACE rolls Mana +// Conversion on every attempt (Creature_Magic.GetManaCost, at least 1 mana when trained) before the +// windup, and a refusal (UseDone 0x401) costs nothing. RynthAi parked the family 15 s after each +// refusal. Recovery vitals now retry every RecoveryRetryMs (200), at most 5 a second and 20 refusals +// in a row; everything else keeps the old rest. +internal static class RecoveryRetryTests +{ + private const uint Player = 0x50000B21; + private const uint STypeLife = 33; + private const uint STypeManaConversion = 16; + private const uint NotEnoughMana = 0x401; + private const string RefusalLine = "You don't have enough Mana to cast this spell."; + + public static void Register(Runner r) + { + r.Add("recovery retry: with spell costs unknown, Stamina to Mana goes out at 1 mana and a refusal is retried", PrecheckAllowsBelowBaseCost); + r.Add("recovery retry: with spell costs known, the mana reserve holds Stamina to Mana under its cost (no cast, no episode); Heal Self still retries", CostKnownHoldsStaminaToMana); + r.Add("recovery retry: a mana refusal is retried after 200 ms, past Spell Interval; the episode line counts the tries", RetryCadence); + r.Add("recovery retry: 20 refusals in a row end it (the vital's 2 s rest); stamina too low ends it; untrained Mana Conversion never starts it", RetryCap); + r.Add("recovery retry: at most 5 recovery casts in any second (Heal Self and Stamina to Mana alternating)", RateCeiling); + r.Add("recovery retry: an episode with no refusal for RecoveryEpisodeStaleMs (7 s) ends; it no longer lets casts past Spell Interval", StaleEpisodeEnds); + r.Add("recovery retry: RecoveryRetryMs at its 5000 ms maximum keeps its episode between retries", SlowRetryKeepsEpisode); + } + + // With RecoveryRetryMs at the slider's 5000 ms maximum the retry (plus a little pacing) must not + // come after the stale limit, or the episode would end itself between retries. + private static void SlowRetryKeepsEpisode() + { + var r = new Rig(manaPct: 10); + r.S.RecoveryRetryMs = 5000; + r.S.SpellCastIntervalMs = 0; + r.At(0); r.B.OnHeartbeat(); + Check.Eq(CastsOf("Stamina to Mana Self"), 1, "Stamina to Mana goes out"); + r.Refuse(); + r.At(5.05); r.B.OnHeartbeat(); // the retry, 50 ms late + Check.Eq(CastsOf("Stamina to Mana Self"), 2, "the retry at 5.05 s"); + Check.True(r.B.RecoveryRetryOpen, "the episode is still open"); + Check.False(r.Logged("stopped retrying"), "not ended between retries: " + r.B.LastRecoverySummary); + } + + // The vital stops being needed (mana regenerated) and no refusal comes again: the open episode + // must end, or it would let every cast past Spell Interval for good. + private static void StaleEpisodeEnds() + { + var r = new Rig(manaPct: 10); + r.S.SpellCastIntervalMs = 60_000; // real clock: nothing else gets past it in this test + r.At(0); r.B.OnHeartbeat(); + Check.Eq(CastsOf("Stamina to Mana Self"), 1, "Stamina to Mana goes out"); + r.Refuse(); + Check.True(r.B.RecoveryRetryOpen, "an episode opens"); + r.V.CurrentMana = 100; // no longer needed + r.At(BuffManager.RecoveryEpisodeStaleMs / 1000.0 + 0.1); r.B.OnHeartbeat(); + Check.False(r.B.RecoveryRetryOpen, "no refusal for RecoveryEpisodeStaleMs: the episode ends"); + Check.True(r.B.LastRecoverySummary.Contains("no refusal for 7 s"), "summary: " + r.B.LastRecoverySummary); + r.V.CurrentHealth = 40; // a heal is needed now + int before = FakeHost.Casts.Count; + r.At(BuffManager.RecoveryEpisodeStaleMs / 1000.0 + 1); r.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, before, "the heal waits for Spell Interval (the ended episode lets nothing past)"); + } + + private sealed class Rig + { + public DateTime T0 = new(2026, 10, 10, 18, 0, 0); + public DateTime NowAt; + public readonly BuffManager B; + public readonly LegacyUiSettings S; + public readonly PlayerVitalsCache V; + + public Rig(int healthPct = 100, int manaPct = 10, bool manaConversion = true) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + FakeHost.Skills[(Player, STypeManaConversion)] = manaConversion ? (300, 2) : (10, 1); + var host = FakeHost.Create(); + S = new LegacyUiSettings + { + IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 50, TopOffMana = 50, 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); + NowAt = T0; + B.Clock = () => NowAt; + B.MarkLiveBuffsReadyForTests(); + } + + public void At(double seconds) => NowAt = T0.AddMilliseconds(Math.Round(seconds * 1000)); + public bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal)); + public int LogCount(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal)); + public string LastCastName => SpellTable.ById(FakeHost.Casts.Last().SpellId)?.Name ?? ""; + + /// The server's answer to an unaffordable cast: UseDone 0x401, the client's chat line. + public void Refuse() + { + FakeHost.UseDone(NotEnoughMana); + B.OnChatWindowText(RefusalLine, 0); + } + } + + private static int CastsOf(string baseName) + { + int cat = SpellTable.Named(baseName + " I").First().Category; + return FakeHost.Casts.Count(c => SpellTable.ById(c.SpellId)?.Category == cat); + } + + private static void PrecheckAllowsBelowBaseCost() + { + // This rig leaves spell costs unknown (FakeHost.Reset: ManaCostOverride 0, as with no + // portal.dat), so the mana reserve's cost check in AttemptVitalCast has nothing to hold on. + var r = new Rig(manaPct: 1); + Check.True(r.B.CheckVitals(), "1 mana: the vitals step acts"); + Check.Eq(CastsOf("Stamina to Mana Self"), 1, "costs unknown: Stamina to Mana is sent at 1 mana (the server rolls the cost)"); + + // Refused at 1 mana: the retry is allowed (the least a trained cast can cost is 1 mana). + r.Refuse(); + Check.True(r.B.RecoveryRetryOpen, "a retry episode is open at 1 mana"); + Check.True(r.Logged("retrying in 200 ms"), "and the refusal line says so"); + + // At 0 mana no cast can be afforded: the old rest. + var z = new Rig(manaPct: 0); + z.B.CheckVitals(); + Check.Eq(CastsOf("Stamina to Mana Self"), 1, "0 mana: the first try still goes (as before)"); + z.Refuse(); + Check.False(z.B.RecoveryRetryOpen, "0 mana: no retry episode"); + Check.True(z.Logged("resting the family 2s") && z.Logged("(no mana at all)"), "the vital's 2 s rest, and why"); + } + + private static void CostKnownHoldsStaminaToMana() + { + // Costs known (level x 10 here, as ManaReserveTests): at 5 mana even Stamina to Mana I (10) + // is unaffordable, so AttemptVitalCast's reserve check sends nothing and no episode opens. + try + { + var r = new Rig(manaPct: 5); + BuffManager.ManaCostOverride = id => (SpellTableStub.GetById(id)?.Level ?? 0) * 10; + r.At(0); r.B.CheckVitals(); + r.At(0.2); r.B.CheckVitals(); + Check.Eq(CastsOf("Stamina to Mana Self"), 0, "under its cost: Stamina to Mana is not cast"); + Check.False(r.B.RecoveryRetryOpen, "and no retry episode opens"); + + // Heal Self is tried below its cost (60 here) and a refusal is still retried. + var h = new Rig(healthPct: 40, manaPct: 5); + BuffManager.ManaCostOverride = id => (SpellTableStub.GetById(id)?.Level ?? 0) * 10; + h.At(0); h.B.CheckVitals(); + Check.Eq(CastsOf("Heal Self"), 1, "Heal Self goes out under its cost"); + h.Refuse(); + Check.True(h.B.RecoveryRetryOpen, "refused for mana: a retry episode"); + h.At(0.2); h.B.CheckVitals(); + Check.Eq(CastsOf("Heal Self"), 2, "retried after 200 ms"); + Check.Eq(CastsOf("Stamina to Mana Self"), 0, "Stamina to Mana still held under its cost"); + } + finally { BuffManager.ManaCostOverride = _ => 0; } + } + + private static void RetryCadence() + { + var r = new Rig(manaPct: 10); + r.At(0); r.B.OnHeartbeat(); + Check.Eq(CastsOf("Stamina to Mana Self"), 1, "Stamina to Mana goes out"); + r.Refuse(); + Check.False(r.Logged("resting the family"), "no family rest"); + + r.At(0.1); r.B.OnHeartbeat(); + Check.Eq(CastsOf("Stamina to Mana Self"), 1, "100 ms after the refusal: still waiting"); + r.At(0.2); r.B.OnHeartbeat(); + Check.Eq(CastsOf("Stamina to Mana Self"), 2, "200 ms: tried again (Spell Interval 400 on the real clock does not hold it)"); + r.Refuse(); + r.At(0.3); r.B.OnHeartbeat(); + Check.Eq(CastsOf("Stamina to Mana Self"), 2, "300 ms: waiting"); + r.At(0.4); r.B.OnHeartbeat(); + Check.Eq(CastsOf("Stamina to Mana Self"), 3, "400 ms: the third try"); + + // A good roll: the result line ends the episode with its summary. + r.At(0.55); + r.B.OnChatWindowText($"You cast {r.LastCastName} on yourself and lose 35 points of stamina and also gain 47 points of mana", 0); + Check.False(r.B.RecoveryRetryOpen, "the result closes the episode"); + Check.True(r.B.LastRecoverySummary.Contains("went through after 3 attempts (2 refused for mana") && r.B.LastRecoverySummary.Contains("in 550 ms"), + $"summary: {r.B.LastRecoverySummary}"); + + // The retry gap is a setting. + var s = new Rig(manaPct: 10); + s.S.RecoveryRetryMs = 1000; + s.At(0); s.B.CheckVitals(); s.Refuse(); + s.At(0.9); s.B.CheckVitals(); + Check.Eq(CastsOf("Stamina to Mana Self"), 1, "RecoveryRetryMs 1000: nothing at 900 ms"); + s.At(1.0); s.B.CheckVitals(); + Check.Eq(CastsOf("Stamina to Mana Self"), 2, "RecoveryRetryMs 1000: the retry at 1 s"); + // ...clamped to 200 at the bottom. + var c = new Rig(manaPct: 10); + c.S.RecoveryRetryMs = 50; + c.At(0); c.B.CheckVitals(); c.Refuse(); + c.At(0.1); c.B.CheckVitals(); + Check.Eq(CastsOf("Stamina to Mana Self"), 1, "RecoveryRetryMs 50 is clamped: nothing at 100 ms"); + c.At(0.2); c.B.CheckVitals(); + Check.Eq(CastsOf("Stamina to Mana Self"), 2, "...the retry at 200 ms"); + } + + private static void RetryCap() + { + var r = new Rig(manaPct: 10); + for (int i = 0; i < 25; i++) + { + r.At(i * 0.2); + int before = FakeHost.Casts.Count; + r.B.CheckVitals(); + if (FakeHost.Casts.Count == before) break; + r.Refuse(); + } + Check.Eq(CastsOf("Stamina to Mana Self"), 20, "20 tries, then it stops"); + Check.True(r.B.LastRecoverySummary.Contains("after 20 mana refusals") && r.B.LastRecoverySummary.Contains("(20 refusals in a row)"), + $"summary: {r.B.LastRecoverySummary}"); + Check.Eq(r.LogCount("resting the family 2s"), 1, "the 20th refusal rests the family 2 s, as before"); + r.At(4.2); r.B.CheckVitals(); + Check.Eq(CastsOf("Stamina to Mana Self"), 20, "no try inside the rest"); + + // Stamina too low to convert when the refusal comes: the old rest. + var st = new Rig(manaPct: 10); + st.V.CurrentStamina = 20; + st.B.CheckVitals(); + st.V.CurrentStamina = 10; + st.Refuse(); + Check.False(st.B.RecoveryRetryOpen, "stamina 10%: no retry"); + Check.True(st.B.LastRecoverySummary.Contains("stamina 10% too low to convert") && st.Logged("resting the family 2s"), + $"summary: {st.B.LastRecoverySummary}"); + + // Mana Conversion untrained: the cost is never rolled, so no retry (the vital's 2 s rest). + var u = new Rig(manaPct: 10, manaConversion: false); + u.B.CheckVitals(); + u.Refuse(); + Check.False(u.B.RecoveryRetryOpen, "untrained: no retry"); + Check.True(u.Logged("resting the family 2s") && u.B.LastRecoverySummary.Contains("Mana Conversion not trained"), "the old rest, and why"); + } + + private static void RateCeiling() + { + // 40% health and 2% mana: Heal Self and Stamina to Mana each retry every 200 ms, which would + // be 10 casts a second. Two vitals checks per 100 ms, every cast refused. + var r = new Rig(healthPct: 40, manaPct: 2); + var sentAt = new List(); + for (int step = 0; step < 30; step++) + { + double t = step * 0.1; + r.At(t); + for (int k = 0; k < 2; k++) + { + int before = FakeHost.Casts.Count; + r.B.CheckVitals(); + if (FakeHost.Casts.Count == before) continue; + sentAt.Add(t); + r.Refuse(); + } + } + Check.True(CastsOf("Heal Self") > 0 && CastsOf("Stamina to Mana Self") > 0, "both spells were tried"); + int worst = 0; + foreach (double a in sentAt) + worst = Math.Max(worst, sentAt.Count(b => b >= a && b < a + 1.0 - 1e-9)); + Check.True(worst <= BuffManager.RecoveryRetryMaxPerSecond, $"at most 5 in any second (worst {worst}, sent at {string.Join(",", sentAt.Select(x => x.ToString("0.0")))})"); + Check.True(worst == BuffManager.RecoveryRetryMaxPerSecond, $"and the ceiling is reached, so it is what held them (worst {worst})"); + Check.True(r.B.RecoveryRateHolds > 0, "the ceiling held some"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs new file mode 100644 index 0000000..7783e8c --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs @@ -0,0 +1,364 @@ +using System; +using System.Linq; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// In a client log, two casts were held open by ACE's fast-tick turn-to-cast wait (40.8 s and 37 s); +// every cast after them came back UseDone 0x1D and the vitals path re-sent a heal every 2.5 s. A +// client mode change ended the second. ActionPacer now holds every start after a 0x1D until the +// server answers, turns to face a held cast's target, breaks a stuck cast with a jump (then Peace +// mode), waits until landed, and holds starts until a movement change has settled. +internal static class StuckCastTests +{ + private const uint Player = 0x50000F01; + private const uint Monster = 0x80116781; + private const int DrainHealthOtherI = 1237; + private static (uint Cell, float X, float Y, float Z) Me0 => (0x6347028Au, 100f, 100f, 0f); + + public static void Register(Runner r) + { + r.Add("stuck cast: after a 'too busy' UseDone nothing starts until the server answers; no timer re-send while our cast is open", NoResendAfterTooBusy); + r.Add("stuck cast: with no cast of ours open, one probe after 1.5 s, then doubling; a UseDone(0) clears", ProbeWhenNothingOpen); + r.Add("stuck cast: a held cast is turned to its target at cycle + 1 s, broken by a jump at cycle + 2 s; a normal 4 s cast trips neither", TurnThenJump); + r.Add("stuck cast: no starts in the air; after landing, no UseDone in 3 s -> Peace mode, 3 s more -> going on", AfterTheJump); + r.Add("stuck cast: a 'too busy' answer while our cast is open past 3 s breaks it at once; before 3 s it does not", RefusalWhileOpen); + r.Add("stuck cast: StuckCastMs 0 turns nothing and breaks nothing; no TapJump -> Peace mode", BreakerOffAndNoJump); + r.Add("move settle: no start in the tick of a movement change; 150 ms and a clear motion queue (or 600 ms) let it go", MoveSettle); + r.Add("stuck cast: the HP failsafe's forced break jumps once and holds starts until landed", ForcedBreak); + r.Add("stuck cast: a script's cast is not jumped before ScriptCastMinBreakMs (6 s): answered at 5.5 s, no jump; RynthAi's own is jumped at 5 s", ScriptCastGetsNudgeWindow); + } + + private static long _t; + + private static RynthCoreHost Setup(int mode = ActionPacer.MagicMode, bool tapJump = true) + { + FakeHost.Reset(); + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.WeaponCalls = true; // GetCurrentCombatMode + FakeHost.CombatModeCalls = true; // ChangeCombatMode + FakeHost.TapJumpCalls = tapJump; + FakeHost.CombatModeValue = mode; + FakeHost.Names[Player] = "Mira"; + FakeHost.PlayerPose = Me0; + FakeHost.Positions[Player] = Me0; + FakeHost.HeadingDeg = 0; // facing north + FakeHost.Positions[Monster] = (Me0.Cell, Me0.X + 10f, Me0.Y, Me0.Z); // due east: 90 deg off + var host = FakeHost.Create(Player); + _t = 90_000_000; + ActionPacer.Reset(); + ActionPacer.Enabled = true; + ActionPacer.NowMs = () => _t; + MoveAudit.Reset(); + MoveAudit.NowMs = () => _t; + ActionPacer.StuckCastMs = 8000; + FakeHost.UseDone(0); // an earlier action's answer: the observer's baseline + return host; + } + + private static void Done() + { + ActionPacer.Enabled = false; + ActionPacer.Reset(); + ActionPacer.NowMs = () => Environment.TickCount64; + MoveAudit.Reset(); + MoveAudit.NowMs = () => Environment.TickCount64; + ActionPacer.StuckCastMs = 8000; + } + + private static bool May(RynthCoreHost host, HealNeed heal = HealNeed.Heal) => + ActionPacer.MayStart(host, "Buff", heal, out _); + + private static void Cast(RynthCoreHost host, string label = "Drain Health Other I") => + Check.True(host.CastSpellFor(Monster, DrainHealthOtherI, "Buff", label), "cast sent"); + + private static int JumpLines() => FakeHost.Logs.Count(l => l.Contains("stuck cast broken by jump after")); + + private static void Run(RynthCoreHost host, long ms) { for (long s = 0; s < ms; s += 100) { _t += 100; May(host); } } + + private static void ScriptCastGetsNudgeWindow() + { + // Control: RynthAi's own cast of a spell with no learned cycle (3 s) is jumped at cycle + 2 s. + var own = Setup(); + try + { + Cast(own); + Run(own, 5500); + Check.Eq(JumpLines(), 1, "RynthAi's own cast: jumped by 5.5 s (at 5 s)"); + } + finally { Done(); } + + // The same cast chosen by a script, answered at 5.5 s: no jump. + var host = Setup(); + try + { + Cast(host); + ActionPacer.MarkScriptCast(DrainHealthOtherI); + Run(host, 5500); + Check.Eq(JumpLines(), 0, "a script's cast: no jump in the first 5.5 s"); + FakeHost.UseDone(0); // its answer + Run(host, 3000); + Check.Eq(JumpLines(), 0, "answered: never jumped"); + } + finally { Done(); } + + // A script's cast with no answer is still broken, once ScriptCastMinBreakMs has passed. + var held = Setup(); + try + { + Cast(held); + ActionPacer.MarkScriptCast(DrainHealthOtherI); + Run(held, ActionPacer.ScriptCastMinBreakMs + 200); + Check.Eq(JumpLines(), 1, "unanswered: jumped after ScriptCastMinBreakMs"); + } + finally { Done(); } + } + + private static void NoResendAfterTooBusy() + { + var host = Setup(); + ActionPacer.StuckCastMs = 0; // the hold alone (the breaker has its own tests) + try + { + Check.True(May(host), "free at first"); + Cast(host); // the cast the server will hold open: no UseDone + _t += 500; + Check.False(May(host), "our cast is unanswered"); + + // Past CastMaxMs (7 s) the pacer used to "go on" and the heal went out into a busy server. + _t += ActionPacer.CastMaxMs - 500; + Check.False(May(host), "unanswered past CastMaxMs: still held (the cast is hung, the server is busy with it)"); + Check.True(ActionPacer.ServerBusy, "the server is taken as busy"); + + // A cast the player sent by hand is refused: 0x1D. Still nothing goes for 13 s (no timer re-send). + FakeHost.UseDone(ActionPacer.TooBusyErr); + bool any = false; + for (int i = 0; i < 130; i++) { _t += 100; any |= May(host); } + Check.False(any, "nothing goes for 13 s after the 0x1D while our cast is hung"); + Check.True(FakeHost.Logs.Any(l => l.Contains("Buff waits:") && l.Contains("has had no answer")), "the hold is logged"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("Buff waits:") && l.Contains("has had no answer")), 1, "once"); + + // The server finally answers (the cast's own UseDone): everything goes again. + FakeHost.UseDone(0x402); + Check.True(May(host), "a UseDone with another error clears the hold"); + Check.False(ActionPacer.ServerBusy, "not busy any more"); + Check.True(FakeHost.Logs.Any(l => l.Contains("the server answered again (UseDone 0x402)")), "logged"); + } + finally { Done(); } + } + + private static void ProbeWhenNothingOpen() + { + var host = Setup(); + try + { + Check.True(May(host), "free"); + Cast(host, "Heart Rend"); + _t += 100; + FakeHost.UseDone(ActionPacer.TooBusyErr); // refused: the server is busy with something of no UseDone (a pickup) + Check.False(May(host), "held right after the 0x1D"); + _t += ActionPacer.BusyProbeMs - 1; + Check.False(May(host), "held until BusyProbeMs"); + _t += 1; + Check.True(May(host), "one probe at BusyProbeMs"); + Check.False(May(host), "only one"); + Cast(host, "Heart Rend"); + _t += 100; + FakeHost.UseDone(ActionPacer.TooBusyErr); // refused again + _t += ActionPacer.BusyProbeMs * 2 - 101; + Check.False(May(host), "the next probe waits twice as long"); + _t += 1; + Check.True(May(host), "second probe at 2 x BusyProbeMs"); + Check.Eq(FakeHost.TapJumps + FakeHost.CombatModeRequests.Count, 0, "no breaker: no cast of ours was left open"); + Cast(host, "Heart Rend"); + _t += 900; + FakeHost.UseDone(0); + Check.True(May(host), "a UseDone(0) clears it"); + } + finally { Done(); } + } + + private static void TurnThenJump() + { + var host = Setup(); + try + { + // A normal 4 s cast: answered; it sets the spell's cycle (4 s) and trips nothing. + Check.True(May(host), "free"); + Cast(host); + _t += 4000; + FakeHost.UseDone(0); + May(host); // the answer seen at 4000 ms + Run(host, 10_000); + Check.Eq(FakeHost.Turns + FakeHost.TapJumps + FakeHost.CombatModeRequests.Count, 0, "a normal 4 s cast: no turn, no jump, no mode change"); + Check.Eq(ActionPacer.NormalCycleMs(DrainHealthOtherI), 4000L, "the cycle learned from it"); + + // The next one is held open: turn at 4 + 1 s, jump at 4 + 2 s. + Cast(host); + long sent = _t; + while (_t - sent < 4900) { _t += 100; May(host); } + Check.Eq(FakeHost.Turns, 0, "no turn before cycle + 1 s"); + _t += 100; May(host); + Check.Eq(FakeHost.Turns, 1, "turned at cycle + 1 s"); + Check.Near(FakeHost.HeadingDeg, 90.0, 0.5, "to face the target (east)"); + Check.True(FakeHost.Logs.Any(l => l.Contains("held cast:") && l.Contains("turning 90 deg to face 0x80116781")), "logged"); + while (_t - sent < 5900) { _t += 100; Check.False(May(host), "held"); } + Check.Eq(FakeHost.TapJumps, 0, "no jump before cycle + 2 s"); + _t += 100; May(host); + Check.Eq(FakeHost.TapJumps, 1, "the breaker jump at cycle + 2 s"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[Pace] stuck cast broken by jump after 6000 ms")), "logged with the time"); + Run(host, 2000); + Check.Eq(FakeHost.TapJumps, 1, "one jump"); + Check.Eq(FakeHost.Turns, 1, "one turn"); + + // The fizzle (0x402): free again once landed. + FakeHost.UseDone(0x402); + Check.True(May(host), "free after the cast's UseDone"); + } + finally { Done(); } + } + + private static void AfterTheJump() + { + var host = Setup(); + try + { + Check.True(May(host), "free"); + Cast(host); + long sent = _t; + while (FakeHost.TapJumps == 0 && _t - sent < 10_000) { _t += 100; May(host); } + Check.Eq(_t - sent, ActionPacer.DefaultCycleMs + ActionPacer.JumpAfterMs, "unknown spell cycle: the jump at 3 + 2 s"); + long jumped = _t; + // In the air: even with the cast's UseDone in, nothing starts. + FakeHost.PlayerPose = (Me0.Cell, Me0.X, Me0.Y, Me0.Z + 0.6f); + FakeHost.UseDone(0x402); + _t += 200; + Check.False(May(host), "in the air: held even with the UseDone in"); + Check.True(ActionPacer.BreakerAirborne, "airborne"); + _t += 300; + Check.False(May(host), "still above the take-off height at 500 ms"); + FakeHost.PlayerPose = Me0; + Check.True(May(host), "landed: free (the cast was answered)"); + + // A second hung cast: jump, land, no answer: Peace mode 3 s after landing, then going on 3 s later. + Cast(host); + sent = _t; + while (FakeHost.TapJumps < 2 && _t - sent < 10_000) { _t += 100; May(host); } + Check.Eq(FakeHost.TapJumps, 2, "jumped"); + _t += ActionPacer.JumpLandMinMs; May(host); // landed (height unchanged) + long landed = _t; + while (_t - landed < ActionPacer.BreakerWaitMaxMs - 100) { _t += 100; Check.False(May(host), "held after landing, no answer"); } + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no Peace yet"); + _t += 100; May(host); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), ActionPacer.PeaceMode.ToString(), "Peace requested once, 3 s after landing"); + Check.True(FakeHost.Logs.Any(l => l.Contains("stuck cast broken by Peace mode after")), "logged"); + FakeHost.CombatModeValue = ActionPacer.PeaceMode; + Run(host, ActionPacer.BreakerWaitMaxMs); + Check.True(FakeHost.Logs.Any(l => l.Contains("no UseDone after the stuck-cast break")), "going on, logged"); + _t += ActionPacer.ModeSettleMs; + Check.True(May(host), "free after it"); + Check.Eq(FakeHost.CombatModeRequests.Count, 1, "one Peace request"); + } + finally { Done(); } + } + + private static void RefusalWhileOpen() + { + var host = Setup(); + try + { + Check.True(May(host), "free"); + Cast(host); + _t += 2000; + Cast(host, "Rushed Recovery"); // a heal let ahead of it: refused, 2 s in (a recoil refusal is normal) + FakeHost.UseDone(ActionPacer.TooBusyErr); + _t += 100; May(host); + Check.Eq(FakeHost.TapJumps, 0, "a 0x1D at 2 s: no jump"); + _t += 900; May(host); + Check.Eq(FakeHost.TapJumps, 1, "past RefusalBreakMinMs with a 0x1D in: jump at once (before cycle + 2 s)"); + Check.True(FakeHost.Logs.Any(l => l.Contains("was refused 'too busy' while it was open")), "the reason is logged"); + } + finally { Done(); } + } + + private static void BreakerOffAndNoJump() + { + var host = Setup(); + try + { + ActionPacer.StuckCastMs = 0; + Check.True(May(host), "free"); + Cast(host); + Run(host, 30_000); + Check.Eq(FakeHost.Turns + FakeHost.TapJumps + FakeHost.CombatModeRequests.Count, 0, "StuckCastMs 0: nothing"); + } + finally { Done(); } + + host = Setup(tapJump: false); + try + { + Check.True(May(host), "free"); + Cast(host); + Run(host, 6000); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), ActionPacer.PeaceMode.ToString(), "no TapJump: Peace mode at the jump time"); + Check.True(FakeHost.Logs.Any(l => l.Contains("no TapJump on this engine")), "logged"); + } + finally { Done(); } + } + + private static void MoveSettle() + { + var host = Setup(); + try + { + FakeHost.AutoRun = true; + Check.True(May(host), "free"); + host.SetAutoRunBy("Nav", true); + _t += 1000; + host.SetAutoRunBy("Nav", false); // nav's stop goes out this tick + Check.False(May(host), "no cast in the tick of the stop"); + Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true), "an attack repeat is not held"); + _t += MoveAudit.MoveSettleMinMs - 1; + Check.False(May(host), "held under MoveSettleMinMs"); + _t += 1; + FakeHost.CastBusy = 1; // the client still animates the stop + Check.False(May(host), "the motion queue still busy: held"); + FakeHost.CastBusy = 0; + Check.True(May(host), "settled: free"); + Check.True(FakeHost.Logs.Any(l => l.Contains("SetAutoRun(False) sent") && l.Contains("has not settled")), "logged"); + + host.TurnToHeadingBy("Nav", 45f); + FakeHost.CastBusy = 1; + _t += MoveAudit.MoveSettleMaxMs - 1; + Check.False(May(host), "busy queue: held under MoveSettleMaxMs"); + _t += 1; + // The gesture gate itself would still hold a busy queue; the settle gate lets go at its max. + Check.True(!MoveAudit.SettleHolds(host, out _), "the settle gate lets go at MoveSettleMaxMs"); + FakeHost.CastBusy = 0; + } + finally { Done(); } + } + + private static void ForcedBreak() + { + var host = Setup(); + try + { + Check.True(ActionPacer.ForceBreak(host, "HP failsafe"), "the forced break goes"); + Check.Eq(FakeHost.TapJumps, 1, "one jump"); + Check.False(ActionPacer.ForceBreak(host, "HP failsafe"), "not twice while in the air"); + FakeHost.PlayerPose = (Me0.Cell, Me0.X, Me0.Y, Me0.Z + 0.5f); + _t += 300; + Check.False(May(host), "in the air: held"); + FakeHost.PlayerPose = Me0; + _t += 200; + Check.True(May(host), "landed: free (nothing of ours was open)"); + Check.True(FakeHost.Logs.Any(l => l.Contains("stuck cast broken by jump after 0 ms") && l.Contains("HP failsafe")), "logged"); + } + finally { Done(); } + } +} diff --git a/Tools/RynthLua.CompatTests/FakeCombat.cs b/Tools/RynthLua.CompatTests/FakeCombat.cs index f2983cd..7cc3bfa 100644 --- a/Tools/RynthLua.CompatTests/FakeCombat.cs +++ b/Tools/RynthLua.CompatTests/FakeCombat.cs @@ -33,8 +33,24 @@ internal static unsafe class FakeCombat private static long Now => Environment.TickCount64; + /// Per kind, as RynthAi's CombatHook: the taken cast in flight, and the most recent resolved one (Err -1 = no answer read). + private sealed class Cast { public uint Seq, Spell, Target; public long At; public int Err = -1; } + private static readonly Dictionary InFlight = new(), Resolved = new(); + /// OlderRynthAi: a RynthAi from before the resolved/pending fields (writes none of them). + public static bool OlderRynthAi; + + /// The server answers the cast in flight of (err -1: no answer read). + public static void ResolveInFlight(uint kind, int err) + { + if (!InFlight.Remove(kind, out var c)) return; + c.Err = err; + Resolved[kind] = c; + } + public static void Reset() { + InFlight.Clear(); Resolved.Clear(); + OlderRynthAi = false; Enabled = false; Owner = ""; Kinds = 0; @@ -83,7 +99,7 @@ internal static unsafe class FakeCombat StructSize = (uint)sizeof(CombatRequestV1), Seq = seq, Kind = kind, TargetId = targetId, TargetHealth = kind == RynthAiCombat.KindAttack ? 0.5f : -1f, HealthPct = 80, StaminaPct = 70, ManaPct = 60, HealLine = kind == RynthAiCombat.KindHeal ? 60 : 0, InCombat = 1, CombatMode = 8, - IssuedAtMs = Now, DeadlineMs = Now + timeoutMs, + IssuedAtMs = Now, DeadlineMs = Now + timeoutMs, ResolvedErr = -1, }; if (Slots.TryGetValue(kind, out var old) && old.Decided) { @@ -92,7 +108,14 @@ internal static unsafe class FakeCombat r.LastSpell = d?.Spell ?? 0; r.LastTarget = d?.Target ?? 0; r.LastAtMs = Now; + if (r.LastSpell != 0) + { + ResolveInFlight(kind, -1); // the cast before it, still unanswered: no answer read + InFlight[kind] = new Cast { Seq = old.R.Seq, Spell = r.LastSpell, Target = r.LastTarget, At = Now }; + } } + if (Resolved.TryGetValue(kind, out var rc)) { r.ResolvedSeq = rc.Seq; r.ResolvedSpell = rc.Spell; r.ResolvedTarget = rc.Target; r.ResolvedAtMs = rc.At; r.ResolvedErr = rc.Err; } + if (InFlight.TryGetValue(kind, out var pc)) { r.PendingSeq = pc.Seq; r.PendingSpell = pc.Spell; r.PendingTarget = pc.Target; r.PendingAtMs = pc.At; } Slots[kind] = new Req { R = r, Open = true }; return seq; } @@ -126,6 +149,7 @@ internal static unsafe class FakeCombat { if (req == null || !Active(kind) || !Slots.TryGetValue(kind, out var s) || !s.Open || s.Decided || Now > s.R.DeadlineMs) return 0; uint room = req->StructSize == 0 || req->StructSize > (uint)sizeof(CombatRequestV1) ? (uint)sizeof(CombatRequestV1) : req->StructSize; + if (OlderRynthAi) room = Math.Min(room, (uint)Marshal.OffsetOf(nameof(CombatRequestV1.ResolvedSeq))); // writes none of the appended fields CombatRequestV1 r = s.R; r.StructSize = room; Buffer.MemoryCopy(&r, req, room, room); diff --git a/Tools/RynthLua.CompatTests/Harness.cs b/Tools/RynthLua.CompatTests/Harness.cs index 8b54598..fd7ca24 100644 --- a/Tools/RynthLua.CompatTests/Harness.cs +++ b/Tools/RynthLua.CompatTests/Harness.cs @@ -229,6 +229,8 @@ internal static class Harness // would, and read back what RynthLua claimed, decided and released. Fn("combatTable", a => { FakeCombat.Enabled = a.Count > 0 && a[0].CastToBool(); return DynValue.Nil; }); Fn("combatOpen", a => DynValue.NewNumber(FakeCombat.Open((uint)Num(a, 0, 1), Id(a, 1), (long)Num(a, 2, 2000)))); + Fn("combatResolve", a => { FakeCombat.ResolveInFlight(RynthCore.Plugin.Shared.RynthAiCombat.KindAttack, (int)Num(a, 0, -1)); return DynValue.Nil; }); + Fn("combatOlderRynthAi", a => { FakeCombat.OlderRynthAi = a.Count > 0 && a[0].CastToBool(); return DynValue.Nil; }); Fn("combatScanned", a => { FakeCombat.Scanned.Clear(); diff --git a/Tools/RynthLua.CompatTests/Scripts/combathook.lua b/Tools/RynthLua.CompatTests/Scripts/combathook.lua index 2c4d442..601d0f8 100644 --- a/Tools/RynthLua.CompatTests/Scripts/combathook.lua +++ b/Tools/RynthLua.CompatTests/Scripts/combathook.lua @@ -55,14 +55,48 @@ check(seen.deadline > seen.issuedAt, "ctx.deadline after ctx.issuedAt") check(seen.deadline > clock(), "ctx.deadline is on clock()'s scale and still ahead") eq(#seen.monsters, 2, "ctx.monsters") eq(seen.monsters[1].distance, 3.5, "ctx.monsters[1].distance") -eq(seen.last.seq, 0, "no last decision yet") +eq(seen.last.seq, 0, "no resolved cast yet") +eq(seen.pending, nil, "nothing in flight yet") --- The next request carries the last decision. +-- ctx.pending: the cast in flight; ctx.last: the most recent RESOLVED cast, err final. local seq2 = harness.combatOpen(ATTACK, 0x80000101) check(waitDecisions(2), "second request answered") -eq(seen.last.seq, seq1, "ctx.last.seq") +eq(seen.pending.seq, seq1, "ctx.pending.seq: the first cast, no answer yet") +eq(seen.pending.spell, 1234, "ctx.pending.spell") +eq(seen.pending.target, 0x80000102, "ctx.pending.target") +eq(seen.last.seq, 0, "ctx.last: still no resolved cast") +eq(seen.last.err, nil, "ctx.last.err: nil before the first resolved cast") + +harness.combatResolve(0x1D) -- the first cast's UseDone: 0x1D +local seqE = harness.combatOpen(ATTACK, 0x80000101) +check(waitDecisions(3), "third request answered") +eq(seen.last.seq, seq1, "ctx.last: the first cast, now resolved") eq(seen.last.spell, 1234, "ctx.last.spell") eq(seen.last.target, 0x80000102, "ctx.last.target") +eq(seen.last.err, 29, "ctx.last.err = 0x1D (refused 'too busy')") +eq(seen.pending.seq, seq2, "ctx.pending: the second cast") + +-- No answer for the second before the third went out: resolved with no answer (nil). +harness.combatOpen(ATTACK, 0x80000101) +check(waitDecisions(4), "fourth request answered") +eq(seen.last.seq, seq2, "ctx.last: the second cast") +eq(seen.last.err, nil, "no answer read for it: nil") +eq(seen.pending.seq, seqE, "ctx.pending: the third cast") + +harness.combatResolve(0) +harness.combatOpen(ATTACK, 0x80000101) +check(waitDecisions(5), "fifth request answered") +eq(seen.last.seq, seqE, "ctx.last: the third cast") +eq(seen.last.err, 0, "ctx.last.err = 0 (done)") + +harness.combatResolve(0x1D) +harness.combatOlderRynthAi(true) +harness.combatOpen(ATTACK, 0x80000101) +check(waitDecisions(6), "older RynthAi request answered") +eq(seen.last.err, nil, "an older RynthAi: no err") +eq(seen.pending, nil, "an older RynthAi: no pending") +check(seen.last.seq > seqE, "an older RynthAi: ctx.last is its last decision") +harness.combatOlderRynthAi(false) -- 2. A yielding handler (the same script registering again replaces its handler), area flag. ok = ai.SetAttackHandler(function(ctx) @@ -71,8 +105,8 @@ ok = ai.SetAttackHandler(function(ctx) end) eq(ok, true, "the same script replaces its handler") local seq3 = harness.combatOpen(ATTACK, 0x80000101) -check(waitDecisions(3), "the yielding handler still answers") -d = decisions()[3] +check(waitDecisions(7), "the yielding handler still answers") +d = decisions()[7] eq(d.seq, seq3, "for its seq") eq(d.spell, 55, "its spell") eq(d.target, 0, "nil target = the request's target") @@ -82,16 +116,16 @@ eq(d.taken, true, "taken") -- 3. nil declines. ai.SetAttackHandler(function(ctx) return nil end) harness.combatOpen(ATTACK, 0x80000101) -check(waitDecisions(4), "a nil answer is still an answer") -eq(decisions()[4].spell, 0, "nil = decline (spell 0)") +check(waitDecisions(8), "a nil answer is still an answer") +eq(decisions()[8].spell, 0, "nil = decline (spell 0)") -- 4. An error declines at once; three in a row unregister. ai.SetAttackHandler(function(ctx) error("boom (expected)") end) for i = 1, 3 do harness.combatOpen(ATTACK, 0x80000101) - check(waitDecisions(4 + i), "error " .. i .. ": declined at once") - eq(decisions()[4 + i].spell, 0, "error " .. i .. ": spell 0") - eq(decisions()[4 + i].taken, true, "error " .. i .. ": taken (no wait for the deadline)") + check(waitDecisions(8 + i), "error " .. i .. ": declined at once") + eq(decisions()[8 + i].spell, 0, "error " .. i .. ": spell 0") + eq(decisions()[8 + i].taken, true, "error " .. i .. ": taken (no wait for the deadline)") end eq(ai.CombatHook.AttackOwner, nil, "three errors: the handler is removed") check(waitfor(function() return harness.combatState().kinds == 0 end, 2000), "and the kind released in RynthAi") @@ -105,8 +139,8 @@ check(harness.scriptConsole("combathook"):find("combat attack handler:", 1, true -- A bad answer counts as an error too (and declines). ai.SetAttackHandler(function(ctx) return "fireball" end) harness.combatOpen(ATTACK, 0x80000101) -check(waitDecisions(8), "a bad answer declines") -eq(decisions()[8].spell, 0, "spell 0") +check(waitDecisions(12), "a bad answer declines") +eq(decisions()[12].spell, 0, "spell 0") check(harness.scriptConsole("combathook"):find("expected a spell id", 1, true) ~= nil, "and says what was wrong") ai.ClearCombatHandlers() eq(ai.CombatHook.AttackOwner, nil, "ClearCombatHandlers drops it") @@ -130,10 +164,10 @@ eq(harness.combatState().owner, "RynthLua/combathook+rival", "under both scripts check(harness.scriptLoaded("rival"), "the rival's main chunk ended but its handler keeps it running") local healSeq = harness.combatOpen(HEAL, 0) -check(waitDecisions(9), "heal answered") -eq(decisions()[9].seq, healSeq, "heal seq") -eq(decisions()[9].kind, HEAL, "heal kind") -eq(decisions()[9].spell, 2001, "heal spell") +check(waitDecisions(13), "heal answered") +eq(decisions()[13].seq, healSeq, "heal seq") +eq(decisions()[13].kind, HEAL, "heal kind") +eq(decisions()[13].spell, 2001, "heal spell") local releasesBefore = harness.combatState().releases check(harness.stopScript("rival"), "stop the rival")