RynthAi: stuck-cast breaker, no re-send into a busy server, recovery retry, HP failsafe
Two casts were held open 40.8 s and 37 s by ACE's fast-tick turn-to-cast wait; every later send was answered UseDone 0x1D and a heal was re-sent every 2.5 s. - ActionPacer: after a 0x1D UseDone nothing starts until the server answers; with no cast of ours open, one probe after 1.5 s, then doubling (max 6 s). Attack repeats are not held (ACE sends no UseDone for a swing), and a latch with no cast of ours open ends after LatchMaxMs (15 s). A cast still unanswered 1 s past its normal cycle (learned per spell, at least 3 s) is turned to face its target; 2 s past it (capped by Stuck Cast Break, default 8000 ms) or on a 0x1D while it has been open 3 s, it is broken with a jump (TapJump; ACE fails a cast on a fast-tick jump). Starts wait until landed; no UseDone 3 s after landing -> Peace mode; 3 s more -> going on. Every hold is bounded: a cast StaleCastMs old, or sent before a frame gap of 5 s (keyed on the gap's end), is dropped with the latch, never broken. No breaker step in portal space; Forget on portal-enter and the death hold. A burst of 5 'too busy' answers in a second holds every start except a heal. A refused forced jump with no cast open leaves no breaker stage. A cast a script chose (the combat hook) is not jumped before 6 s from its send (ScriptCastMinBreakMs, the held-cast nudge's HeldAfterIncantMs). Stuck Cast Break is read from the settings once per tick. - MoveAudit: no start in the tick of a movement change; 150 ms and a clear motion queue (or 600 ms) let it go. A held stop sent later by FlushPendingStops counts as a movement change too; the forced flush in CastSpellFor still goes out in the same tick as the cast that follows it. - Blacklist: casts answered 0x1D (or unanswered while the server is busy) are not no-damage casts. - Combat hook: ctx.pending is the cast in flight; ctx.last is the most recent RESOLVED cast, its err final (the first UseDone after its send; nil only when none could be read: 7 s timeout, or another answer came first). The casts in flight of both kinds resolve in send order through one queue. The send-time UseDone count comes from the pacer (LastCastSeqAtSend). CombatRequestV1 appends Resolved*/Pending* fields (StructSize-gated, no Version bump); an older RynthAi keeps the old ctx.last. - HP failsafe (BuffManager.HpFailsafe.cs): at or under Emergency Heal At with no heal landing for 3 rounds of 2.5 s, a forced jump; 3 more rounds, the macro stops and /lifestone goes out (HP Failsafe Recall, default on). Nothing counts in portal space; a pending recall is dropped on death; a recall that never starts turns the macro back on (only one the failsafe stopped, never past the VTank yield) and re-arms after a 30 s cooldown. Recovery retry: recovery vitals (Heal Self, Stamina to Health, Revitalize, Stamina to Mana) refused for "not enough mana" retry after Recovery Retry (200 ms, a setting) instead of resting the family: ACE rolls Mana Conversion on every attempt before the windup and a refusal costs nothing. At most 5 recovery casts a second, 20 refusals in a row, stamina and Mana Conversion checks, an episode with no refusal for 7 s ends; an episode summary line. Stamina to Mana and Revitalize are still held under their cost by the mana reserve (AttemptVitalCast), so for them the retry applies when the mana reading is stale or costs are unknown; Heal Self and Stamina to Health, which are tried below cost, gain the most. When the retry stops, the vital rests as the existing mana reserve has it (LowManaHealRestSec, 2 s). Script heals and other casts are unchanged. Tests: StuckCastTests (incl. the script cast's break floor), PacerEdgeTests, RecoveryRetryTests (incl. costs known: Stamina to Mana held), HpFailsafeTests, CombatHookTests (ctx.last/ctx.pending, send order, an answer during the send, 0x1D blacklist, script heal keeps its rest, script attack and heal not jumped before 6 s with or without a 'too busy' answer); HealLatencyTests' and ManaReserveTests' low-mana rest cases pin untrained Mana Conversion; RynthLua compat combathook.lua. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
7cbc6fdca9
commit
2d8bebb0f4
30 changed files with 3156 additions and 53 deletions
|
|
@ -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 "<our name> 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;
|
||||
/// <summary>After a recall that never started, the next one waits this long (the heals run meanwhile).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Set by the plugin: the rest of a /ra stop (nav stop, pause cancel) for the recall.</summary>
|
||||
internal Action? MacroStopForRecall { get; set; }
|
||||
/// <summary>Set by the plugin: false when the macro must not be started now (VTank yield). Null = may.</summary>
|
||||
internal Func<bool>? 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; }
|
||||
}
|
||||
|
||||
/// <summary>Once per heartbeat while the macro runs, before the pacing gate.</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Every heartbeat, macro running or not: sends a pending recall, or gives up on it.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>OnChatWindowText: "<our name> is recalling to the lifestone." while a recall is pending.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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<int, DateTime> _recoveryNextAt = new();
|
||||
private readonly List<string> _recoveryNames = new();
|
||||
// Recovery casts sent (any time), for the per-second ceiling.
|
||||
private readonly Queue<DateTime> _recoveryAttempts = new();
|
||||
// The base name of the pending vital ("Stamina to Mana Self"...), set by CastVital.
|
||||
private string _pendingVitalBase = "";
|
||||
|
||||
/// <summary>Recovery casts held by the per-second ceiling (tests, status).</summary>
|
||||
internal int RecoveryRateHolds { get; private set; }
|
||||
/// <summary>The last episode summary line (tests, status).</summary>
|
||||
internal string LastRecoverySummary { get; private set; } = "";
|
||||
/// <summary>True while a fast-retry episode is open (tests).</summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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 "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A result line for <paramref name="family"/>: a retried cast went through.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private void ExpireRecoveryEpisode()
|
||||
{
|
||||
if (_recoveryOpen && (Now - _recoveryLastRefusalAt).TotalMilliseconds > RecoveryEpisodeStaleMs)
|
||||
EndRecoveryEpisode(Now, $"no refusal for {RecoveryEpisodeStaleMs / 1000:0} s", success: false, "");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private bool RecoveryRetryDue()
|
||||
{
|
||||
if (!_recoveryOpen) return false;
|
||||
DateTime now = Now;
|
||||
foreach (var at in _recoveryNextAt.Values)
|
||||
if (now >= at) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>CastVital's gate for a recovery vital while an episode is open: "" to cast, else why it waits.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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).
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
/// <summary>Casts the server refused 'too busy' that were kept out of the no-damage count (tests, status).</summary>
|
||||
internal int RefusedCastsNotJudged { get; private set; }
|
||||
|
||||
private void NoteOffensiveSeq()
|
||||
{
|
||||
_pendingOffensiveSeqAtSend = _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
|
||||
_pendingOffensiveErr = -1;
|
||||
}
|
||||
|
||||
/// <summary>The first UseDone after the pending offensive cast's send is its answer.</summary>
|
||||
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
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
/// <summary>The cast in flight is done: <paramref name="err"/> its answer (-1 = none read).</summary>
|
||||
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<long> Clock = static () => Environment.TickCount64;
|
||||
internal static long Now => Clock();
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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<Slot> InFlight = new(2);
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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++;
|
||||
}
|
||||
}
|
||||
/// <summary>A timeout is logged at most this often per kind.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The decided spell went out (or was waited on): the request is done.</summary>
|
||||
public static void Cast(Slot slot, uint spellId, uint targetId)
|
||||
/// <summary>
|
||||
/// The decided spell went out (or was waited on): the request is done. <paramref name="seqAtSend"/>
|
||||
/// is the UseDone count read just before the send (ActionPacer.LastCastSeqAtSend); -1 reads the
|
||||
/// last UseDone now instead.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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())
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -332,6 +332,30 @@ public sealed class LegacyUiSettings
|
|||
|
||||
public int SpellCastIntervalMs = 400;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public int StuckCastBreakMs = 8000;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public int RecoveryRetryMs = 200;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public bool HpFailsafeRecall = true;
|
||||
|
||||
/// <summary>
|
||||
/// Minimum delay between offensive (war/void) COMBAT spell casts, in ms.
|
||||
/// Combat magic uses this instead of <see cref="SpellCastIntervalMs"/> so
|
||||
|
|
|
|||
|
|
@ -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).
|
||||
/// </summary>
|
||||
private bool _wasPortalingForPacer;
|
||||
|
||||
/// <summary>Portal space starts: the server dropped what was open (no breaker on a teleport's gap).</summary>
|
||||
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
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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).
|
||||
|
|
|
|||
|
|
@ -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<CombatRequestV1>(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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static void NoteFrame()
|
||||
{
|
||||
long now = NowMs();
|
||||
lock (Gate)
|
||||
{
|
||||
if (_lastFrameMs != 0 && now - _lastFrameMs >= PollGapMs) { _gapEnd = now; _gapLen = now - _lastFrameMs; }
|
||||
_lastFrameMs = now;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forget the outstanding action (logout, death, portal): the server dropped it.</summary>
|
||||
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 <paramref name="who"/> 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 (<see cref="GestureHolds"/>; skipped with
|
||||
/// <paramref name="gestureGate"/> false: melee/missile attack repeats). One log line per
|
||||
/// <paramref name="animationGate"/> false: melee/missile attack repeats). One log line per
|
||||
/// outstanding action (or animation) and subsystem.
|
||||
/// </summary>
|
||||
public static bool MayStart(RynthCoreHost host, string who, HealNeed heal, out string why, bool gestureGate = true)
|
||||
/// <param name="animationGate">False: skip <see cref="GestureHolds"/> (melee/missile attack repeats).</param>
|
||||
/// <param name="settleGate">False: skip the movement settle (<see cref="MoveAudit.SettleHolds"/>; attack repeats only).</param>
|
||||
/// <param name="attackRepeat">
|
||||
/// 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.
|
||||
/// </param>
|
||||
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).
|
||||
|
||||
/// <summary>ACE's YoureTooBusy, as a UseDone error.</summary>
|
||||
public const uint TooBusyErr = 0x1D;
|
||||
/// <summary>With no cast of ours open, one start is let through this long after a 0x1D (doubling per probe).</summary>
|
||||
public const long BusyProbeMs = 1500;
|
||||
public const long BusyProbeMaxMs = 6000;
|
||||
/// <summary>A cast's normal send-to-UseDone time when none was seen for its spell, and the floor of a learned one.</summary>
|
||||
public const long DefaultCycleMs = 3000;
|
||||
/// <summary>Past its normal cycle: turn to face the target after this, jump after this.</summary>
|
||||
public const long TurnAfterMs = 1000;
|
||||
public const long JumpAfterMs = 2000;
|
||||
/// <summary>A 0x1D to another send breaks our open cast only once it is this old (a recoil refusal is normal).</summary>
|
||||
public const long RefusalBreakMinMs = 3000;
|
||||
/// <summary>After the jump: landed once the height is back (and this long passed), or at the max.</summary>
|
||||
public const long JumpLandMinMs = 400;
|
||||
public const long JumpLandMaxMs = 1500;
|
||||
/// <summary>After landing (or after the Peace request), the longest wait for a UseDone before the next step.</summary>
|
||||
public const long BreakerWaitMaxMs = 3000;
|
||||
/// <summary>The stuck-cast limit (ms from the send; 0 = no turn, no breaker). RynthAi sets it from its settings.</summary>
|
||||
public static long StuckCastMs = 8000;
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public const long ScriptCastMinBreakMs = 6000;
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public const long StaleCastMs = 3 * (CastMaxMs > BusyProbeMaxMs ? CastMaxMs : BusyProbeMaxMs);
|
||||
public const long PollGapMs = 5000;
|
||||
/// <summary>A 'too busy' latch with no cast of ours open is cleared after this long (logged).</summary>
|
||||
public const long LatchMaxMs = 15000;
|
||||
/// <summary>'Too busy' UseDones in the last second at which every start but a heal waits (bounds refusal chat lines).</summary>
|
||||
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<long> _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<string> _settleLogged = new();
|
||||
public static long SettleHoldCount => _settleHolds;
|
||||
private static readonly HashSet<string> _busyLogged = new();
|
||||
private static readonly Dictionary<uint, long> _cycleBySpell = new();
|
||||
public static long StuckBreaks => _stuckBreaks;
|
||||
public static long RefusalHolds => _refusalHolds;
|
||||
public static long HeldCastTurns => _heldTurns;
|
||||
/// <summary>True while the server is taken as busy (a 0x1D latch or a hung cast).</summary>
|
||||
public static bool ServerBusy { get { lock (Gate) return _busySince != 0 || _hung != null; } }
|
||||
/// <summary>True while the character is in the air after a breaker jump.</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>The normal send-to-UseDone time of <paramref name="spellId"/>: the longest of its last answers, at least DefaultCycleMs.</summary>
|
||||
internal static long NormalCycleMs(uint spellId)
|
||||
{
|
||||
lock (Gate) return _cycleBySpell.TryGetValue(spellId, out long c) ? Math.Max(DefaultCycleMs, c) : DefaultCycleMs;
|
||||
}
|
||||
|
||||
/// <summary>A cast of <paramref name="spellId"/> was answered (not 0x1D) <paramref name="ms"/> after its send.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the last UseDone: a 0x1D starts or feeds the latch, any other answer clears it.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The held-cast turn and the breaker steps for <paramref name="stuck"/> (one step per call at most).</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>In the air after a breaker jump: hold until landed (height back, or JumpLandMaxMs).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The breaker jump (TapJump: the keyboard jump, 0xF61B). No TapJump: the Peace request instead.</summary>
|
||||
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); }
|
||||
}
|
||||
|
||||
/// <summary>The Peace mode request (ACE fails a cast in progress on a mode change). Only from Magic.</summary>
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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})");
|
||||
}
|
||||
|
||||
/// <summary>The heading to <paramref name="target"/> (AC degrees: 0 north, 90 east) and how far off the player faces.</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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 ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>In portal space: no breaker step, no forced break (the server is moving us).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The open cast of <paramref name="spellId"/> was chosen by a script (see <see cref="ScriptCastMinBreakMs"/>).</summary>
|
||||
public static void MarkScriptCast(int spellId)
|
||||
{
|
||||
lock (Gate) { if (_cur is { Kind: PacedKind.Cast } c && c.Id == unchecked((uint)spellId)) c.Script = true; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The UseDone count read just before the last cast <see cref="CastSpellFor"/> sent (its answer is
|
||||
/// the next UseDone after it); -1 when the engine has no UseDone count.
|
||||
/// </summary>
|
||||
public static int LastCastSeqAtSend { get; private set; } = -1;
|
||||
|
||||
/// <summary>
|
||||
/// Casts sent through <see cref="CastSpellFor"/> in this plugin (every caller: combat, buffs,
|
||||
/// nav, commands, meta): a caller that remembers the count at its own cast can tell whether
|
||||
|
|
|
|||
|
|
@ -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; }
|
||||
}
|
||||
|
||||
/// <summary>True (with why) while the last movement change has not settled.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public const long ResolveTimeoutMs = 7000;
|
||||
|
||||
/// <summary>Longest owner name RynthAi keeps (characters).</summary>
|
||||
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.
|
||||
|
||||
/// <summary>The most recent resolved cast: Seq of its request, spell, target, send time (0s before the first).</summary>
|
||||
public uint ResolvedSeq;
|
||||
public uint ResolvedSpell;
|
||||
public uint ResolvedTarget;
|
||||
public long ResolvedAtMs;
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public int ResolvedErr;
|
||||
/// <summary>The cast still in flight (sent, no answer yet): Seq, spell, target, send time; Spell 0 = none.</summary>
|
||||
public uint PendingSeq;
|
||||
public uint PendingSpell;
|
||||
public uint PendingTarget;
|
||||
public long PendingAtMs;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
|
|
|
|||
Loading…
Reference in a new issue