Snapshot for release 2026.10.28.2 (internal 48c46bd)

This commit is contained in:
Tom Bohar 2026-10-28 19:47:19 -04:00
commit 636adfcef2
41 changed files with 3402 additions and 120 deletions

View file

@ -0,0 +1,200 @@
// ============================================================================
// RynthDefective - Use/BusyGate.cs
// Whether the client's "busy" readings really hold a use back (2026-10-28).
//
// Why: the busy count the engine reports (GetBusyState) can stay above zero
// with nothing at all in flight: after a death (the engine's own resync waits
// out the death portal and 5 s more), after a logout and a login (the engine
// keeps its count across the session and can't clear it again), after an
// interrupted action. Holding every use on it made the bar "not work at all
// after logging in" until the client was restarted, and kits wait seconds
// after every death. RynthAi copes the same way (Combat/CombatBusyGate: a
// leftover count doesn't hold a heal), and RynthAi's "waiting on the server"
// bit includes its copy of the same count, so it sticks with it.
//
// The rule (pure: BusyRule.Decide; BusyGate keeps the clocks):
// * a gesture animating holds, for at most AnimationMaxMs without a break
// (RynthAi's ActionPacer.GestureHoldMaxMs: no real gesture lasts longer);
// * the busy count holds while it is above the count already judged a
// leftover AND it moved within CountTrustMs or our own last use went out
// within OwnTrustMs. A count that has read the same for longer, with
// nothing of ours in flight, is a leftover: it holds nothing, and only a
// count above it holds again (our own next use raises it and the server's
// answer brings it back down to the leftover);
// * RynthAi's "waiting on the server" bit holds while it is fresh:
// BotTrustMs since it came on (RynthAi's own actions are answered or let
// go well inside it), or only CountTrustMs when a leftover count explains it.
// After that the use is sent: if the server really is busy it answers
// "You're too busy" (UseDone 0x1D) and the use controller tries once more.
//
// RynthDefective never resets the client's count itself (ForceResetBusyCount):
// the count is the engine's (its reconciler and watchdogs own it), RynthAi
// stopped resetting it on 2026-10-06 because a reset zeroes actions the server
// hasn't answered yet (each later answer then drives it negative), and nothing
// here needs it at zero: ignoring a leftover is enough to send.
// ============================================================================
using System;
namespace RynthCore.Plugin.RynthDefective.Use;
/// <summary>What holds a use back now; None = send.</summary>
internal enum BusyHold { None, Busy, Animation, Bot }
/// <summary>The readings that were ignored as leftovers (each logged once).</summary>
[Flags]
internal enum BusyStale { None = 0, Count = 1, Animation = 2, Bot = 4 }
/// <summary>The readings at one moment, and how long each has read so. Pure data.</summary>
/// <param name="Count">The client's busy count (GetBusyState).</param>
/// <param name="CountSteadyMs">How long it has read this value.</param>
/// <param name="Leftover">The count already judged a leftover (0 = none): a reading at or under it holds nothing.</param>
/// <param name="SinceOwnSendMs">Since RynthDefective's own last use or cast went out.</param>
/// <param name="Animating">A cast or use gesture is animating.</param>
/// <param name="AnimatingMs">How long it has animated without a break.</param>
/// <param name="BotWaiting">RynthAi is waiting on the server (null = RynthAi isn't there).</param>
/// <param name="BotSteadyMs">How long that bit has read its current value.</param>
internal readonly record struct BusyFacts(
int Count, long CountSteadyMs, int Leftover, long SinceOwnSendMs,
bool Animating, long AnimatingMs, bool? BotWaiting, long BotSteadyMs);
internal static class BusyRule
{
/// <summary>A count that moved this recently is an action under way (a kit 2.5 s, a corpse use 3.7 s at the most seen).</summary>
public const long CountTrustMs = 4000;
/// <summary>After our own use went out the count is ours this long.</summary>
public const long OwnTrustMs = 4000;
/// <summary>A gesture that lasts longer is a stuck motion queue (RynthAi's ActionPacer.GestureHoldMaxMs).</summary>
public const long AnimationMaxMs = 4000;
/// <summary>RynthAi's bit this long: its corpse uses are let go at 5 s (ActionPacer.WorldUseMaxMs).</summary>
public const long BotTrustMs = 5500;
/// <summary>What holds a use back; <paramref name="stale"/> names the readings ignored as leftovers.</summary>
public static BusyHold Decide(in BusyFacts f, out BusyStale stale)
{
stale = BusyStale.None;
if (f.Animating)
{
if (f.AnimatingMs < AnimationMaxMs) return BusyHold.Animation;
stale |= BusyStale.Animation;
}
if (f.Count > 0)
{
bool fresh = f.CountSteadyMs < CountTrustMs || f.SinceOwnSendMs < OwnTrustMs;
if (f.Count > f.Leftover && fresh) return BusyHold.Busy;
stale |= BusyStale.Count;
}
if (f.BotWaiting == true)
{
// RynthAi's bit includes its copy of the same count: a leftover count explains it.
long trust = (stale & BusyStale.Count) != 0 ? CountTrustMs : BotTrustMs;
if (f.BotSteadyMs < trust) return BusyHold.Bot;
stale |= BusyStale.Bot;
}
return BusyHold.None;
}
}
/// <summary>
/// The clocks behind <see cref="BusyRule"/>: how long each reading has read the same, our own last
/// send, and the leftover count. <see cref="Observe"/> every tick (in or out of the world: a count
/// left by a death has read the same all through the death portal), <see cref="Judge"/> when a use
/// wants to go. Plugin pump thread only.
/// </summary>
internal sealed class BusyGate
{
private bool _started;
private int _count, _leftover;
private long _countSinceMs;
private bool _animating;
private long _animatingSinceMs;
private bool? _bot;
private long _botSinceMs;
private long _ownSendMs = long.MinValue / 4;
private BusyStale _logged;
/// <summary>The count judged a leftover (0 = none).</summary>
public int Leftover => _leftover;
public void Observe(int count, bool animating, bool? botWaiting, long now)
{
if (count < 0) count = 0;
if (!_started)
{
_started = true;
_count = count;
_countSinceMs = now;
_animating = animating;
_animatingSinceMs = now;
_bot = botWaiting;
_botSinceMs = now;
}
if (count != _count)
{
_count = count;
_countSinceMs = now;
}
if (_leftover > count) _leftover = count; // part of it was answered or cleared: what is left is the leftover
if (count == 0) _logged &= ~BusyStale.Count;
if (animating != _animating)
{
_animating = animating;
_animatingSinceMs = now;
if (!animating) _logged &= ~BusyStale.Animation;
}
if (botWaiting != _bot)
{
_bot = botWaiting;
_botSinceMs = now;
if (botWaiting != true) _logged &= ~BusyStale.Bot;
}
}
/// <summary>Our own use or cast went out now.</summary>
public void NoteOwnSend(long now) => _ownSendMs = now;
public BusyFacts Facts(long now) => new(
_count, now - _countSinceMs, _leftover, now - _ownSendMs,
_animating, _animating ? now - _animatingSinceMs : 0, _bot, now - _botSinceMs);
/// <summary>
/// What holds a use back now. A count found to be a leftover becomes the new leftover;
/// <paramref name="newlyIgnored"/> names the leftovers not reported before (log them once).
/// </summary>
public BusyHold Judge(long now, out BusyStale newlyIgnored)
{
BusyHold hold = BusyRule.Decide(Facts(now), out BusyStale stale);
if ((stale & BusyStale.Count) != 0 && _count > _leftover)
{
_leftover = _count;
_logged &= ~BusyStale.Count; // a new leftover is worth its own line
}
newlyIgnored = stale & ~_logged;
_logged |= stale;
return hold;
}
/// <summary>The words for the log line when a leftover is first ignored.</summary>
public string Describe(BusyStale what, long now)
{
BusyFacts f = Facts(now);
var parts = new System.Collections.Generic.List<string>(3);
if ((what & BusyStale.Count) != 0)
parts.Add($"the client's busy count has read {f.Count} for {f.CountSteadyMs / 1000.0:0.0} s with nothing of ours in flight");
if ((what & BusyStale.Animation) != 0)
parts.Add($"the character has read 'animating' for {f.AnimatingMs / 1000.0:0.0} s");
if ((what & BusyStale.Bot) != 0)
parts.Add($"RynthAi has read 'waiting on the server' for {f.BotSteadyMs / 1000.0:0.0} s"
+ ((what & BusyStale.Count) != 0 || (_logged & BusyStale.Count) != 0 ? " (its copy of the same count)" : ""));
return "[RynthDefective] " + string.Join("; ", parts)
+ ": a leftover (a death, a login or an interrupted action), not waited on. The count itself is left alone.";
}
public void Reset()
{
_started = false;
_leftover = 0;
_logged = BusyStale.None;
_ownSendMs = long.MinValue / 4;
}
}

View file

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.Json;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
@ -29,9 +30,12 @@ internal sealed unsafe class HostDefWorld : IDefWorld
public bool InWorld => _host.HasGetPlayerId && _host.GetPlayerId() != 0 && !(_host.HasIsPortaling && _host.IsPortaling());
public uint PlayerId => _host.HasGetPlayerId ? _host.GetPlayerId() : 0;
public uint SelectedId => _host.HasGetSelectedItemId ? _host.GetSelectedItemId() : 0;
public bool ClientBusy => _host.HasGetBusyState && _host.GetBusyState() != 0;
public int BusyCount => _host.HasGetBusyState ? Math.Max(0, _host.GetBusyState()) : 0;
public bool Animating => _host.HasGetCastBusyState && _host.GetCastBusyState() != 0;
public int UseDoneSeq => _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
public uint UseDoneError(int seqAtSend) =>
_host.TryGetLastUseDone(out int seq, out uint error) && seq == seqAtSend + 1 ? error : 0;
public int CombatMode => _host.GetCurrentCombatMode();
public bool? BotWaitingOnServer => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.ServerAction) != 0 : null;
@ -67,11 +71,81 @@ internal sealed unsafe class HostDefWorld : IDefWorld
public bool UseObjectOn(uint id, uint target) => _host.HasUseObjectOn && _host.UseObjectOn(id, target);
public bool SetCombatMode(int mode) => _host.HasChangeCombatMode && _host.ChangeCombatMode(mode);
// ── Spells (spell slots) ────────────────────────────────────────────────
/// <summary>The character's spells are re-read when older than this (a spell scribed since shows within it).</summary>
public const long KnownMaxAgeMs = 5000;
private uint[] _knownBuf = new uint[2048];
private HashSet<uint>? _known;
private SpellInfo[] _knownList = Array.Empty<SpellInfo>();
private long _knownAtMs = long.MinValue / 4;
public bool CanCast => _host.HasCastSpell;
public bool CastSpell(uint target, uint spellId) =>
_host.HasCastSpell && spellId != 0 && spellId <= int.MaxValue && _host.CastSpell(target, (int)spellId);
/// <summary>
/// From the spellbook the engine reads (ReadKnownSpells; RynthAi's note: the engine's IsSpellKnown
/// answers "known" for spells the character doesn't have, so it isn't asked). A "no" is checked
/// against a fresh read before it is believed. Null when the spellbook can't be read.
/// </summary>
public bool? KnowsSpell(uint spellId)
{
HashSet<uint>? known = KnownIds(KnownMaxAgeMs);
if (known == null) return null;
if (known.Contains(spellId)) return true;
known = KnownIds(0);
return known == null ? null : known.Contains(spellId);
}
/// <summary>The character's spells with names, A-Z (the bar's spell search); empty when they can't be read.</summary>
public SpellInfo[] KnownSpells(long maxAgeMs)
{
KnownIds(maxAgeMs);
return _knownList;
}
private HashSet<uint>? KnownIds(long maxAgeMs)
{
long now = NowMs;
if (now - _knownAtMs < maxAgeMs) return _known;
_knownAtMs = now;
if (!_host.HasReadKnownSpells)
{
_known = null;
_knownList = Array.Empty<SpellInfo>();
return null;
}
int n = _host.ReadKnownSpells(_knownBuf, _knownBuf.Length);
if (n > _knownBuf.Length && n <= 65536)
{
_knownBuf = new uint[n];
n = _host.ReadKnownSpells(_knownBuf, _knownBuf.Length);
}
if (n <= 0)
{
// Not readable yet (before the character's description arrives): can't tell.
_known = null;
_knownList = Array.Empty<SpellInfo>();
return null;
}
n = Math.Min(n, _knownBuf.Length);
var set = new HashSet<uint>(n);
for (int i = 0; i < n; i++) if (_knownBuf[i] != 0) set.Add(_knownBuf[i]);
if (_known == null || !set.SetEquals(_known)) _knownList = SpellTable.Known(_knownBuf.AsSpan(0, n));
_known = set;
return set;
}
public void Reset()
{
_reader.Reset();
_items = new List<CarriedItem>();
_itemsAtMs = long.MinValue / 4;
_known = null;
_knownList = Array.Empty<SpellInfo>();
_knownAtMs = long.MinValue / 4;
}
}

View file

@ -16,8 +16,11 @@ internal interface IDefWorld
bool InWorld { get; }
uint PlayerId { get; }
uint SelectedId { get; }
/// <summary>The client's busy count is above zero (an item action it sent has not been answered).</summary>
bool ClientBusy { get; }
/// <summary>
/// The client's busy count (0 = idle): the item actions and casts it sent that the server hasn't
/// answered. It can read above zero with nothing in flight (BusyGate says when it holds a use).
/// </summary>
int BusyCount { get; }
/// <summary>A cast or use gesture is animating.</summary>
bool Animating { get; }
/// <summary>RynthAi is waiting on the server for an action it sent (null = RynthAi isn't there).</summary>
@ -26,6 +29,8 @@ internal interface IDefWorld
bool? BotMacroRunning { get; }
/// <summary>Count of the server's UseDone events; 0 when the engine can't report them.</summary>
int UseDoneSeq { get; }
/// <summary>The error of the server's first UseDone after <paramref name="seqAtSend"/> (0x1D: "You're too busy"); 0 = none or unknown.</summary>
uint UseDoneError(int seqAtSend);
/// <summary>1 NonCombat, 2 Melee, 4 Missile, 8 Magic.</summary>
int CombatMode { get; }
/// <summary>The server's refusals so far (0x028A / 0x00A0 ... count), to tell a new one.</summary>
@ -41,18 +46,40 @@ internal interface IDefWorld
bool UseObject(uint id);
bool UseObjectOn(uint id, uint target);
bool SetCombatMode(int mode);
/// <summary>The engine can cast (CastSpell).</summary>
bool CanCast { get; }
/// <summary>Whether the character knows the spell; null = can't tell (the server refuses one it doesn't).</summary>
bool? KnowsSpell(uint spellId);
/// <summary>Casts the spell at <paramref name="target"/> (the player id for yourself).</summary>
bool CastSpell(uint target, uint spellId);
}
/// <summary>One thing the player asked to use: an exact item (a slot's) or a name typed in a command.</summary>
/// <summary>
/// One thing the player asked to use: an exact item (a slot's), a name typed in a command, or a spell
/// to cast (<see cref="Spell"/>, a spell slot's; Item and Name are null then).
/// </summary>
internal sealed record UseRequest(ItemRef? Item, string? Name, UseMode Mode, string Source, long AtMs)
{
/// <summary>Same item, same way: pressing the key again must not queue a second one.</summary>
/// <summary>Sent once already and answered "You're too busy": this is the one more try.</summary>
public bool Retry { get; init; }
/// <summary>The spell to cast (2026-10-28); 0 = an item.</summary>
public uint Spell { get; init; }
/// <summary>The spell's name as the slot has it.</summary>
public string SpellName { get; init; } = string.Empty;
/// <summary>A spell slot's cast for <paramref name="spellId"/>.</summary>
public static UseRequest Cast(uint spellId, string name, string source, long atMs) =>
new(null, null, UseMode.Auto, source, atMs) { Spell = spellId, SpellName = name };
/// <summary>Same item (or spell), same way: pressing the key again must not queue a second one.</summary>
public bool SameAs(UseRequest o) =>
Mode == o.Mode
&& ((Item != null && o.Item != null && Item.SameAs(o.Item))
|| (Name != null && o.Name != null && string.Equals(Name, o.Name, StringComparison.OrdinalIgnoreCase)));
|| (Name != null && o.Name != null && string.Equals(Name, o.Name, StringComparison.OrdinalIgnoreCase))
|| (Spell != 0 && Spell == o.Spell));
public string Label => Item?.FullName ?? Name ?? "item";
public string Label => Item?.FullName ?? (Spell != 0 ? (SpellName.Length > 0 ? SpellName : SpellTable.Name(Spell)) : Name) ?? "item";
}
/// <summary>The combat stance a weapon swap leaves the character in.</summary>
@ -104,8 +131,11 @@ internal static class Stance
/// is put right (<see cref="Stance.Wanted"/>) once the character is still.
/// Busy: nothing is sent while the client's busy count is up, a gesture animates, RynthAi waits on
/// the server, the last action is unanswered, or for <see cref="MinGapMs"/> after it - the "one item
/// action at a time" rule RynthAi's ActionPacer keeps. Weapon swaps also wait out a running RynthAi
/// macro unless the player allowed them (it would swap straight back).
/// action at a time" rule RynthAi's ActionPacer keeps. A busy reading that has sat unchanged with
/// nothing in flight (a count left by a death, a login or an interrupted action) is a leftover and
/// holds nothing (<see cref="BusyGate"/>, logged once); if the server really is busy it answers
/// "You're too busy" and the use is tried once more after <see cref="RetryAfterMs"/>. Weapon swaps
/// also wait out a running RynthAi macro unless the player allowed them (it would swap straight back).
/// </summary>
internal sealed class UseController
{
@ -119,25 +149,44 @@ internal sealed class UseController
public const long MinGapMs = 250;
public const long StanceSettleMs = 500;
public const long StanceTimeoutMs = 4000;
/// <summary>A cast waits this long after the client reads Magic mode (RynthAi's ActionPacer.ModeSettleMs: a cast
/// sent into the stance animation hangs).</summary>
public const long MagicSettleMs = 800;
/// <summary>A use the server answered "You're too busy" is tried once more after this.</summary>
public const long RetryAfterMs = 1000;
/// <summary>ACE's YoureTooBusy, as a UseDone error.</summary>
public const uint TooBusyError = 0x1D;
private enum Stage { Sent, WaitWield, Stance }
private enum Stage { Sent, WaitWield, Stance, Magic }
private sealed class Flight
{
public UseRequest Request = null!;
/// <summary>The item used (null for a cast).</summary>
public CarriedItem Item = null!;
/// <summary>What the player reads ("Peerless Healing Kit", "Heal Self VI") and what the log reads.</summary>
public string Name = string.Empty, What = string.Empty;
public UseAction Action;
public ItemKind Kind;
public long SentMs;
public int UseDoneAtSend, RefusalAtSend, ModeBefore;
public Stage Stage;
public long StageMs;
// A cast: the spell, its target, and the Magic stance it waits for.
public uint SpellId, Target;
public bool ModeAsked;
public long MagicSeenMs;
}
private UseRequest? _pending;
private Flight? _flight;
private long _lastDoneMs = long.MinValue / 4;
private long _retryNotBeforeMs = long.MinValue / 4;
private string _lastWait = string.Empty;
private readonly BusyGate _busy = new();
/// <summary>The busy readings' clocks (tests look at the leftover).</summary>
internal BusyGate Busy => _busy;
/// <summary>Plain information ("Using Peerless Healing Kit ..."): the status line, not the chat.</summary>
public Action<string>? Say;
@ -155,6 +204,10 @@ internal sealed class UseController
public bool Involves(ItemRef r) =>
(_pending?.Item != null && _pending.Item.SameAs(r)) || (_flight?.Request.Item != null && _flight.Request.Item.SameAs(r));
/// <summary>The spell a cast in flight or waiting is about.</summary>
public bool InvolvesSpell(uint spellId) =>
spellId != 0 && (_pending?.Spell == spellId || _flight?.Request.Spell == spellId);
public DefSettings Settings = new();
/// <summary>Queues a request. False when it is the one already waiting or in flight (a held key).</summary>
@ -167,22 +220,38 @@ internal sealed class UseController
return true;
}
/// <summary>Drops what is waiting and forgets what is in flight (logout, portal space, shutdown).</summary>
/// <summary>Drops what is waiting and forgets what is in flight (portal space).</summary>
public void Reset()
{
_pending = null;
_flight = null;
_lastWait = string.Empty;
_retryNotBeforeMs = long.MinValue / 4;
}
/// <summary>
/// <see cref="Reset"/>, and the busy readings' clocks start again (login, logout, shutdown). Not on
/// portal space: a count a death left has read the same all through the death portal, and that is
/// what shows it is a leftover once the character lands.
/// </summary>
public void ResetSession()
{
Reset();
_busy.Reset();
}
public void Tick(IDefWorld w)
{
long now = w.NowMs;
_busy.Observe(w.BusyCount, w.Animating, w.BotWaitingOnServer, now);
if (!w.InWorld)
{
// Portal space (a death's too): what was waiting is dropped, and said so (a key pressed in the
// portal did nothing). A use in flight is the server's now; nothing to say about it.
if (_pending != null) Warn?.Invoke($"{_pending.Label}: not used, the character is in portal space.");
if (_pending != null || _flight != null) Reset();
return;
}
long now = w.NowMs;
if (_flight != null && !AdvanceFlight(w, now)) return; // still in flight: nothing new goes out
if (_pending == null) return;
@ -205,16 +274,36 @@ internal sealed class UseController
private string? WaitReason(IDefWorld w, long now)
{
if (now - _lastDoneMs < MinGapMs) return "the last action just finished";
if (w.ClientBusy) return "the character is busy";
if (w.Animating) return "an animation is playing";
if (w.BotWaitingOnServer == true) return "RynthAi is waiting on the server";
return null;
if (now < _retryNotBeforeMs) return "the server said the character was busy";
return Hold(now) switch
{
BusyHold.Busy => "the character is busy",
BusyHold.Animation => "an animation is playing",
BusyHold.Bot => "RynthAi is waiting on the server",
_ => null,
};
}
/// <summary>The busy gate's verdict now; a leftover it ignores for the first time is logged.</summary>
private BusyHold Hold(long now)
{
BusyHold hold = _busy.Judge(now, out BusyStale ignored);
if (ignored != BusyStale.None) Log?.Invoke(_busy.Describe(ignored, now));
return hold;
}
/// <summary>The client's count or a gesture holds the character (RynthAi's bit doesn't: it is about RynthAi's own actions).</summary>
private bool CharacterHeld(long now) => Hold(now) is BusyHold.Busy or BusyHold.Animation;
// ── Sending ─────────────────────────────────────────────────────────────
private void Send(IDefWorld w, UseRequest req, long now)
{
if (req.Spell != 0)
{
SendSpell(w, req, now);
return;
}
IReadOnlyList<CarriedItem> items = w.Items();
CarriedItem? item = req.Item != null
? ItemMatcher.Find(req.Item, items, out _)
@ -268,11 +357,14 @@ internal sealed class UseController
Warn?.Invoke($"{name}: the client didn't take the request (nothing was sent).");
return;
}
_busy.NoteOwnSend(now);
_flight = new Flight
{
Request = req,
Item = item,
Name = name,
What = item.ToString(),
Action = action,
Kind = kind,
SentMs = now,
@ -282,10 +374,124 @@ internal sealed class UseController
ModeBefore = w.CombatMode,
Stage = action == UseAction.Equip ? Stage.WaitWield : Stage.Sent,
};
Log?.Invoke($"[RynthDefective] {req.Source}: {(action == UseAction.Equip ? "wield" : target != 0 ? "use on " + (target == w.PlayerId ? "you" : "0x" + target.ToString("X8")) : "use")} {item} (stack {item.Stack}, mode {Stance.Name(w.CombatMode)})");
Log?.Invoke($"[RynthDefective] {req.Source}: {(action == UseAction.Equip ? "wield" : target != 0 ? "use on " + (target == w.PlayerId ? "you" : "0x" + target.ToString("X8")) : "use")} {item} (stack {item.Stack}, mode {Stance.Name(w.CombatMode)}{(req.Retry ? ", the one more try" : "")})");
Say?.Invoke(action == UseAction.Equip ? $"Wielding {name}..." : $"Using {name}...");
}
/// <summary>
/// The server answered "You're too busy" (UseDone 0x1D) to <paramref name="f"/>'s use: it is tried
/// once more after <see cref="RetryAfterMs"/>, unless a newer request is waiting (the newest wish
/// wins) or this was the one more try already. Returns whether it was queued again.
/// </summary>
private bool RetryTooBusy(Flight f, long now)
{
string name = f.Name;
if (f.Request.Retry)
{
Warn?.Invoke($"{name}: not {(f.SpellId != 0 ? "cast" : "used")}, the server says the character is busy. Try again in a moment.");
return false;
}
if (_pending != null) return false;
_pending = f.Request with { Retry = true, AtMs = now };
_retryNotBeforeMs = now + RetryAfterMs;
Log?.Invoke($"[RynthDefective] {f.Request.Source}: the server answered 'too busy' to {f.What}; trying once more in {RetryAfterMs} ms");
Say?.Invoke($"{name}: the server said busy, trying again...");
return true;
}
// ── Casting (a spell slot) ──────────────────────────────────────────────
/// <summary>
/// A spell slot's cast: refused when the character doesn't know the spell or it needs a target
/// (SpellTargeting); else into Magic mode first (the client's stance for casting; RynthAi buffs the
/// same way), then cast once the stance has settled, answered by the server's UseDone like a use.
/// </summary>
private void SendSpell(IDefWorld w, UseRequest req, long now)
{
uint id = req.Spell;
SpellInfo? info = SpellTable.TryGet(id, out SpellInfo s) ? s : null;
string name = info?.Name ?? req.Label;
if (!w.CanCast)
{
Warn?.Invoke($"{name}: not cast, this RynthCore can't cast spells for a plugin.");
return;
}
if (w.KnowsSpell(id) == false)
{
Warn?.Invoke($"{name}: not cast, you don't know that spell.");
return;
}
if (SpellTargeting.Decide(info, w.SelectedId, w.PlayerId, out uint target, out string why) == CastAt.Refused)
{
Warn?.Invoke($"{name}: not cast, {why}.");
return;
}
var f = new Flight
{
Request = req,
Name = name,
What = $"spell {id} '{name}'",
Action = UseAction.Use,
SpellId = id,
Target = target,
SentMs = now,
StageMs = now,
ModeBefore = w.CombatMode,
Stage = Stage.Magic,
};
_flight = f;
if (w.CombatMode == Stance.Magic)
{
f.MagicSeenMs = now - MagicSettleMs; // already there and settled (nothing holds the character: WaitReason)
AdvanceMagic(w, f, now);
return;
}
f.ModeAsked = w.SetCombatMode(Stance.Magic);
Log?.Invoke($"[RynthDefective] {req.Source}: {f.What}: {Stance.Name(w.CombatMode)} -> magic first{(f.ModeAsked ? "" : " (the client turned it away; asking again)")}");
Say?.Invoke($"Magic mode for {name}...");
}
/// <summary>A cast waiting for Magic mode: cast once it has settled. True when finished (cast refused or failed).</summary>
private bool AdvanceMagic(IDefWorld w, Flight f, long now)
{
long age = now - f.StageMs;
if (w.CombatMode == Stance.Magic)
{
if (f.MagicSeenMs == 0) f.MagicSeenMs = now;
bool settling = now - f.MagicSeenMs < MagicSettleMs || CharacterHeld(now);
if (settling && age < WaitLimitMs) return false;
return Cast(w, f, now);
}
if (age >= StanceTimeoutMs)
{
Warn?.Invoke($"{f.Name}: not cast, the character didn't go into magic mode ({Stance.Name(w.CombatMode)} now). "
+ "A weapon in your hands? Wield a wand, or nothing, and try again.");
Finish(now);
return true;
}
if (!f.ModeAsked && !CharacterHeld(now)) f.ModeAsked = w.SetCombatMode(Stance.Magic);
return false;
}
private bool Cast(IDefWorld w, Flight f, long now)
{
f.UseDoneAtSend = w.UseDoneSeq;
f.RefusalAtSend = w.RefusalSeq;
if (!w.CastSpell(f.Target, f.SpellId))
{
Warn?.Invoke($"{f.Name}: the client didn't take the cast (nothing was sent).");
Finish(now);
return true;
}
_busy.NoteOwnSend(now);
f.Stage = Stage.Sent;
f.SentMs = now;
f.StageMs = now;
Log?.Invoke($"[RynthDefective] {f.Request.Source}: cast {f.What} on {(f.Target == w.PlayerId ? "you" : "0x" + f.Target.ToString("X8"))} (mode {Stance.Name(w.CombatMode)}{(f.Request.Retry ? ", the one more try" : "")})");
Say?.Invoke(f.Target == w.PlayerId ? $"Casting {f.Name}..." : $"Casting {f.Name} on the selection...");
return false;
}
// ── In flight ───────────────────────────────────────────────────────────
/// <summary>Steps the action in flight; true when it is finished (a new one may go out this tick).</summary>
@ -298,11 +504,12 @@ internal sealed class UseController
case Stage.Sent:
{
bool answered = w.UseDoneSeq != f.UseDoneAtSend;
bool quiet = age >= UseQuietMs && !w.ClientBusy && !w.Animating;
bool quiet = !answered && age >= UseQuietMs && !CharacterHeld(now);
if (answered || quiet || age >= UseTimeoutMs)
{
if (!answered && age >= UseTimeoutMs) Log?.Invoke($"[RynthDefective] no UseDone for {f.Item} after {age} ms; carrying on");
if (!answered && age >= UseTimeoutMs) Log?.Invoke($"[RynthDefective] no UseDone for {f.What} after {age} ms; carrying on");
Finish(now);
if (answered && w.UseDoneError(f.UseDoneAtSend) == TooBusyError) RetryTooBusy(f, now);
return true;
}
return false;
@ -332,6 +539,8 @@ internal sealed class UseController
}
return false;
}
case Stage.Magic:
return AdvanceMagic(w, f, now);
default:
return AdvanceStance(w, f, now);
}
@ -354,7 +563,7 @@ internal sealed class UseController
Finish(now);
return true;
}
if (since < StanceSettleMs || w.ClientBusy || w.Animating) return false;
if (since < StanceSettleMs || CharacterHeld(now)) return false;
if (w.SetCombatMode(want))
{
Log?.Invoke($"[RynthDefective] stance {Stance.Name(w.CombatMode)} -> {Stance.Name(want)} for {f.Item}");