Snapshot for release 2026.10.23.1 (internal 7581cff)

This commit is contained in:
Tom Bohar 2026-10-23 16:34:02 -04:00
commit 92f28bd243
73 changed files with 12203 additions and 308 deletions

View file

@ -370,14 +370,14 @@ public partial class BuffManager
/// </summary>
/// <summary>
/// A death or a portal dropped whatever the server had open: a wand use in flight is forgotten,
/// not judged a failed swap (see _directSwapMisses). RynthAiPlugin calls it with the death hold
/// and on entering portal space.
/// not judged a failed swap. RynthAiPlugin calls it with the death hold and on entering portal space.
/// </summary>
internal void ForgetPendingWield(string why)
{
DropWandSwap(why);
if (_pendingWieldId == 0) return;
_pendingWieldId = 0;
_host.Log($"[WieldGate] the wand's use in flight was cut short ({why}): not counted as a failed swap");
_host.Log($"[WieldGate] the wand's wield in flight was cut short ({why}): not counted as a failed swap");
}
internal void CancelPendingRecall(string why)

View file

@ -0,0 +1,202 @@
using System;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// The wand swap as it was before 2026-10-22 (RynthSuite e613280), kept for Fast Weapon Swap off: a
/// use of the wand while a weapon is in hand (the client puts the weapon away), the pack route after
/// a miss, and the swap gate's flat 3 s after every pack move. Fast Weapon Swap on goes through
/// HandSwapSequence instead (BuffManager.WandSwapStep). Off is the default until the new swap has run
/// a night on Drakkon; this file goes once it is the only way.
/// </summary>
public partial class BuffManager
{
private int _directSwapMisses; // direct swaps in a row that didn't get the wand into the hand
private bool _packFirstNext; // the next swap goes through the pack (one miss)
private bool _pendingWieldDirect; // the wand's use in flight was a direct swap (a weapon in hand)
internal const int DirectSwapMissesToStick = 2;
private bool PackFirst => _packFirstNext || _directSwapMisses >= DirectSwapMissesToStick;
// The swap gate's claim count when the wand's use went out: a later claim means another swap
// (combat putting the axe back, 12:39 on 10-06) changed the hands, so the result says nothing.
private long _pendingWieldClaim;
private int _bowDequipPendingId;
private DateTime _bowDequipAt = DateTime.MinValue;
private int _bowDequipAttempts;
private const int BowDequipMaxAttempts = 3;
/// <summary>EnsureMagicMode's branch for a wand not yet in hand, before 2026-10-22.</summary>
private bool LegacyWandSwap(int wandId, bool forBuff)
{
// Wield gate: don't spam UseObject. Hold off after the first issue
// until either the wielded check confirms (cleared on the Magic-mode
// branch above) or the resolve timeout elapses, then cool down
// before retrying. Mirrors the no-chat-timeout pattern used for
// spell casts at the top of OnHeartbeat. Checked BEFORE the shared
// swap gate so a denied attempt never claims the cross-subsystem slot.
DateTime now = Now;
if (now < _wieldCooldownUntil)
return false;
if (_pendingWieldId != 0)
{
if ((now - _pendingWieldAt).TotalMilliseconds < WieldResolveTimeoutMs)
return false;
if (_weaponSwapGate != null && _weaponSwapGate.Claims != _pendingWieldClaim)
{
_pendingWieldId = 0; // another swap since ours: not a failed wield
return false;
}
int stillInHand = _pendingWieldDirect ? FindWieldedNonWandWeapon(wandId) : 0;
if (stillInHand != 0 && IsWieldedLive(stillInHand))
{
_directSwapMisses++;
_packFirstNext = true;
_pendingWieldId = 0;
_host.Log($"[WieldGate] using the wand didn't put 0x{(uint)stillInHand:X8} away in {WieldResolveTimeoutMs:0} ms; " +
(_directSwapMisses >= DirectSwapMissesToStick
? $"{_directSwapMisses} in a row: from now on the weapon goes into a pack first"
: "the next swap puts the weapon into a pack first, then the use is tried again"));
return false;
}
_host.Log($"[WieldGate] UseObject(0x{(uint)_pendingWieldId:X8}) not confirmed in " +
$"{WieldResolveTimeoutMs:0}ms — cooling down {WieldCooldownMs:0}ms");
NoteWandWieldFailed(_pendingWieldId);
_pendingWieldId = 0;
_wieldCooldownUntil = now.AddMilliseconds(WieldCooldownMs);
// FIX: bound the previously-infinite wield loop. If the wand still won't
// wield after a few cooldowns (e.g. no pack to free the bow, or an
// unresolvable collision), degrade so buffing yields and combat runs.
if (++_wieldGateFailCount >= WieldGateFailMax)
return SignalSwapFailure(forBuff, FindWieldedNonWandWeapon(wandId), wandId);
return false;
}
// Shared weapon-swap gate: if CombatManager (or anything else) swapped
// a weapon within the last few seconds, wait — two equips in flight
// collide ("you can only move or use one item at a time" / AV).
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("buff-wand"))
return false;
// Tear down any in-flight physical combat BEFORE the UseObject. The
// transition Melee/Missile → Magic-via-wand must explicitly cancel the
// pending attack, or AC gets a UseObject while m_bAttacking is still
// set and wedges the item-action gate. Done only after we've claimed
// the swap slot above, so we don't cancel an attack then fail to swap.
if (!_combatTeardownDoneForCurrentBuffCycle &&
(CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile))
{
if (_host.HasCancelAttack) _host.CancelAttack();
if (_host.HasStopCompletely) _host.StopCompletelyBy("Buff/WandSwap");
_combatTeardownDoneForCurrentBuffCycle = true;
_host.Log($"[BuffPre] CancelAttack+StopCompletely before wand equip (mode was {CurrentCombatMode})");
}
// FIX: stock ACE will NOT auto-dequip the bow for a Held-slot wand
// (CheckWeaponCollision refuses while mainhand != null). Stow the wielded
// non-wand weapon into a capacity-verified open pack FIRST (AutoCram pattern,
// AV-safe), then UseObject(wand) once the hand is free. Fully bounded.
int bowId = FindWieldedNonWandWeapon(wandId);
if (bowId != 0 && (PackFirst || !IsWieldedLive(bowId))) // else the use swaps (see _directSwapMisses)
{
if (_bowDequipPendingId == bowId
&& (now - _bowDequipAt).TotalMilliseconds < WieldResolveTimeoutMs
&& IsWieldedLive(bowId))
return false; // dequip still resolving
if (IsWieldedLive(bowId))
{
int openPack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1);
if (openPack == 0 || _bowDequipAttempts >= BowDequipMaxAttempts)
{
// No verified-open pack to receive the bow, or repeated dequip
// failures -> the swap provably can't complete now. Degrade.
_host.Log($"[WieldGate] bow 0x{(uint)bowId:X8} dequip blocked (openPack=0x{(uint)openPack:X8}, attempts={_bowDequipAttempts}/{BowDequipMaxAttempts}) — degrading");
if (openPack == 0)
WorldObjectCache.WarnPackFull(_host, "can't put the weapon away to switch to the wand, so buffs and spell heals can't cast");
return SignalSwapFailure(forBuff, bowId, wandId);
}
_bowDequipAttempts++;
if (_worldObjectCache?[bowId] is WorldObject blocker && IsInOffhandSlot(blocker))
OffhandStowed?.Invoke(bowId); // a shield: combat puts it back after
_host.MoveItemInternal((uint)bowId, (uint)openPack, 0, 1); // amount>=1 (engine rejects 0)
_weaponSwapGate?.NoteMove(bowId, wieldedNow: true);
_bowDequipPendingId = bowId;
_bowDequipAt = now;
_lastCastAttempt = now;
_host.Log($"[WieldGate] dequip bow 0x{(uint)bowId:X8} -> pack 0x{(uint)openPack:X8} (attempt {_bowDequipAttempts}/{BowDequipMaxAttempts}) before wand equip");
return false; // yield until the bow is out of hand
}
_bowDequipPendingId = 0; // bow confirmed unwielded — fall through to wield the wand
}
_pendingWieldDirect = bowId != 0 && !PackFirst;
// Hands free: wield the caster into the Held slot (GetAndWieldItem, the paperdoll drag),
// as the off hand does. A use only wields a plain caster: a caster with a spell of its own
// (Electric Baton, Acid Staff) takes the use as "cast it" and the client says it must be
// wielded first (Drakkon, 2026-10-18 14:00). With a weapon still in hand the use stays
// (the client swaps); when that misses, the next swap empties the hands first.
if (!_pendingWieldDirect && _host.HasWieldItem)
{
_host.WieldItem((uint)wandId, HeldSlot);
_host.Log($"[WieldGate] wielding 0x{(uint)wandId:X8} '{_worldObjectCache?[wandId]?.Name}' into the Held slot");
}
else
_host.UseFor((uint)wandId, "Buff", _pendingWieldDirect ? "buffing: switch to the wand" : "buffing: wield the wand");
NoteStanceRequest();
_pendingWieldClaim = _weaponSwapGate?.Claims ?? 0;
_pendingWieldId = wandId;
_pendingWieldAt = now;
_lastCastAttempt = now;
return false; // Yield — let the server equip the wand
}
/// <summary>EnsureMagicMode's first step once the wand reads wielded, before 2026-10-22.</summary>
private void LegacyWandWielded(int wandId)
{
if (_pendingWieldId == wandId)
{
_pendingWieldId = 0;
_wieldCooldownUntil = DateTime.MinValue;
if (_pendingWieldDirect) _directSwapMisses = 0; // the use swapped: back to direct swaps
_packFirstNext = false; // a pack-route swap done: the next one tries the use
}
}
// The currently-wielded non-wand weapon (the bow) that blocks the Held-slot wand; else
// what is in the off hand (a shield, or an off-hand weapon): ACE refuses a Held-slot caster
// beside either. With the global Offhand setting None the off hand is never touched (the
// wand then can't be wielded; logged once).
private int FindWieldedNonWandWeapon(int wandId)
{
if (_worldObjectCache == null) return 0;
int offhand = 0;
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: true))
{
if (wo.Id == wandId) continue;
if (IsWandObject(wo)) continue;
if (WorldObjectCache.IsAmmo(wo)) continue; // arrows stay on; only the bow blocks the wand
if (IsInOffhandSlot(wo)) { offhand = wo.Id; continue; }
if ((wo.ObjectClass == AcObjectClass.MeleeWeapon
|| wo.ObjectClass == AcObjectClass.MissileWeapon)
&& WorldObjectCache.IsWieldedByPlayer(_host, wo))
return wo.Id;
}
if (offhand != 0 && OffhandRules.Parse(_settings.OffhandDefault, OffhandMode.Auto) == OffhandMode.None)
{
if (!_offhandNoneNoted)
{
_offhandNoneNoted = true;
_host.Log($"[WieldGate] 0x{(uint)offhand:X8} '{_worldObjectCache[offhand]?.Name}' is in the off hand and Offhand is None — leaving it; the server won't wield the wand beside it");
}
return 0;
}
return offhand;
}
private static bool IsInOffhandSlot(WorldObject wo) =>
(wo.Values(LongValueKey.CurrentWieldedLocation, 0) & OffhandRules.ShieldSlot) != 0;
}

View file

@ -0,0 +1,90 @@
using System;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
using System.Threading;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// /ra swaptest [spell] (2026-10-22): the wand swap and one cast of a self spell, timed, by the
/// same EnsureMagicMode a heal or a buff goes through. With no spell named, the first known of a
/// few spells every caster school has (Lifestone Recall, Portal Recall, the level 1 item auras).
/// A fizzle is as good as a cast here: what it measures is the swap and the stance before it.
/// </summary>
public partial class BuffManager
{
private string? _swapTestRequest; // set on AC's thread by the command, taken on the pump
private int _swapTestSpellId;
private string _swapTestName = "";
private DateTime _swapTestAt = DateTime.MinValue;
private const double SwapTestGiveUpSec = 20;
private static readonly string[] SwapTestDefaults =
{
"Lifestone Recall", "Portal Recall", "Aura of Blood Drinker Self I", "Aura of Swift Killer Self I",
"Aura of Heart Seeker Self I", "Aura of Defender Self I", "Aura of Hermetic Link Self I",
};
/// <summary>The /ra swaptest command (any thread).</summary>
internal void RequestSwapTest(string spell) => Interlocked.Exchange(ref _swapTestRequest, spell ?? "");
/// <summary>Behind the same gates as the vitals step. True while the test holds the tick.</summary>
private bool TickSwapTest()
{
string? req = Interlocked.Exchange(ref _swapTestRequest, null);
if (req != null) StartSwapTest(req.Trim());
if (_swapTestSpellId == 0) return false;
if ((Now - _swapTestAt).TotalSeconds > SwapTestGiveUpSec)
{
_host.WriteToChat($"[RynthAi] Swap test: no Magic stance in {SwapTestGiveUpSec:0} s ({LastWandSwapTrail}).", 2);
_host.Log($"[SwapTest] gave up after {SwapTestGiveUpSec:0} s");
_swapTestSpellId = 0;
return false;
}
if (!EnsureMagicMode()) return true; // a swap step or the stance is on its way
int id = _swapTestSpellId;
_swapTestSpellId = 0;
double ms = (Now - _swapTestAt).TotalMilliseconds;
bool sent = _host.CastSpellFor((uint)_host.GetPlayerId(), id, "Buff", _swapTestName);
_lastCastAttempt = Now;
string swap = LastWandSwapTrail.Length > 0 ? $"; the swap took {LastWandSwapMs:0} ms ({LastWandSwapTrail})" : "; no swap needed";
_host.Log($"[SwapTest] '{_swapTestName}' {(sent ? "cast" : "refused by the client")} {ms:0} ms after the request{swap}");
_host.WriteToChat($"[RynthAi] Swap test: {_swapTestName} {(sent ? "cast" : "refused")} {ms / 1000:0.00} s after the request{swap}.", 1);
LastWandSwapTrail = "";
return true;
}
private void StartSwapTest(string spell)
{
if (spell.StartsWith("burst", StringComparison.OrdinalIgnoreCase))
{
SwapBurst = !spell.EndsWith("off", StringComparison.OrdinalIgnoreCase);
_host.WriteToChat($"[RynthAi] Swap test: the burst is {(SwapBurst ? "on" : "off")} until the next reload (with Fast Weapon Swap it is on by itself).", 1);
_host.Log($"[SwapTest] burst {(SwapBurst ? "on" : "off")}");
return;
}
int id = 0;
string name = "";
foreach (string candidate in spell.Length > 0 ? new[] { spell } : SwapTestDefaults)
{
var e = SpellCatalog.GetByName(candidate);
if (e == null || !_spellManager.IsKnownSpellId(e.Id)) continue;
id = e.Id;
name = e.Name;
break;
}
if (id == 0)
{
_host.WriteToChat(spell.Length > 0
? $"[RynthAi] Swap test: '{spell}' isn't a spell this character knows."
: "[RynthAi] Swap test: none of the default test spells is known; name one: /ra swaptest <spell>.", 2);
return;
}
_swapTestSpellId = id;
_swapTestName = name;
_swapTestAt = Now;
LastWandSwapTrail = "";
_host.Log($"[SwapTest] start: '{name}' (mode {CurrentCombatMode})");
}
}

View file

@ -692,30 +692,34 @@ public partial class BuffManager : IDisposable
// stow the bow into a capacity-verified open pack FIRST (AutoCram pattern), then wield
// the wand. All paths are bounded so a stale/no-op dequip or unwieldable wand can never
// loop forever; on exhaustion the buff family is parked and the bot fights unbuffed.
// Switch like a player (2026-10-06): a use of the wand goes through ClientUISystem::UseObject,
// the client's double-click, which puts the weapon in hand away by itself (ACE's
// DoHandleActionGetAndWieldItem: "the client handles dequipping a lot of conflicting items
// automatically"). Drakkon's axe -> wand took 4.2 s with the pack move first (1.2 s for it,
// then the swap gate's flat 3 s). The pack move stays as the fallback: once a use hasn't
// got the wand into the hand in WieldResolveTimeoutMs, the weapon goes into a pack first.
// Not for the rest of the session on one miss (2026-10-14): a swap the server never finished
// because Drakkon died (13:40) set it, and every later heal from melee took the pack route, the
// move plus the swap gate's flat 3 s, 4+ s with nothing healing; he died twice more. Now one miss
// sends the next swap through the pack and the one after tries the use again; two misses in a
// row keep the pack route. A swap a death or a portal cut short counts for nothing
// (ForgetPendingWield).
private int _directSwapMisses; // direct swaps in a row that didn't get the wand into the hand
private bool _packFirstNext; // the next swap goes through the pack (one miss)
private bool _pendingWieldDirect; // the wand's use in flight was a direct swap (a weapon in hand)
internal const int DirectSwapMissesToStick = 2;
private bool PackFirst => _packFirstNext || _directSwapMisses >= DirectSwapMissesToStick;
// The swap gate's claim count when the wand's use went out: a later claim means another swap
// (combat putting the axe back, 12:39 on 10-06) changed the hands, so the result says nothing.
private long _pendingWieldClaim;
private int _bowDequipPendingId;
private DateTime _bowDequipAt = DateTime.MinValue;
private int _bowDequipAttempts;
private const int BowDequipMaxAttempts = 3;
// The wand swap, as fast as the server allows (2026-10-22, HandSwapSequence): the off hand into
// a pack, then the main hand, then the wand wielded into the Held slot, each the moment the
// server's wielded list says the last step landed. One claim of the swap gate is held for all
// of it. Before, Drakkon's two Hand Wraps -> Sceptre took 7.2 s to the first cast: each pack
// move held the next step the gate's flat 3 s, and the client's own use of the wand (the route
// tried first) takes the main hand first, which costs the off hand a second stance change.
// The why, step by step, is at the top of HandSwapSequence.
private readonly HandSwapSequence _wandSwap = new();
private bool _wandSwapOpen; // started and not yet finished (its log line and the gate's release are owed)
private int _wandSwapWandId;
private bool _wandSwapForBuff;
private int _wandSwapMainAtStart; // the main hand's weapon when it began (put back if the swap fails)
private int _wandSwapLastMoved; // its last pack move or wield: the gate holds the next swap after it
private DateTime _wandSwapTouchedAt = DateTime.MinValue; // EnsureMagicMode last asked for it
// Not asked for this long (the heal or buff no longer needs it): the swap stops, not a failure.
// Longer than the pacer holds the vitals step for our own peace request (ModeMaxMs 2 s).
private const double WandSwapAbandonMs = 3000;
// The wand went on in a combat mode: the server switches to Magic itself (ACE TryShuffleStance),
// after the stance change of the last unwield. Our own ChangeCombatMode(Magic) waits this long for
// it: a second stance change queued behind the server's is how a cast gets held open.
private DateTime _serverMagicDueUntil = DateTime.MinValue;
private const double ServerMagicWaitMs = 2500;
// A swap that went through peace just put the wand in hand: Magic is asked for at once (see the request).
private DateTime _magicAfterPeaceUntil = DateTime.MinValue;
private const double MagicAfterPeaceMs = 2500;
/// <summary>The last wand swap: how long it took and its steps with the server's answer times.</summary>
internal double LastWandSwapMs { get; private set; }
internal string LastWandSwapTrail { get; private set; } = "";
private int _wieldGateFailCount;
private const int WieldGateFailMax = 3;
private bool _wandSwapExhausted; // per-EnsureMagicMode(forBuff) signal: swap can't succeed now
@ -1104,7 +1108,7 @@ public partial class BuffManager : IDisposable
/// </summary>
private string ActiveHealLine(int hp, int stamPct, out int value, out bool inCombat)
{
inCombat = _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true;
inCombat = InCombatNow();
value = 0;
if (_settings.EmergencyHealAt > 0 && hp <= _settings.EmergencyHealAt) { value = _settings.EmergencyHealAt; return "Emergency Heal At"; }
if (StaminaToHealthAllowed(_settings, hp, stamPct)) { value = _settings.StaminaToHealthAt; return "Stamina To Health At"; }
@ -1287,7 +1291,11 @@ public partial class BuffManager : IDisposable
TickRechargeRequest(); // /ra recharge: one vitals pass, macro on or off (BuffManager.Recharge.cs)
TickOneTouchRequest(); // /ra heal, /ra stam, /ra mana: one-touch recharge, macro on or off (BuffManager.OneTouch.cs)
if (!_settings.IsMacroRunning) return;
if (!_settings.IsMacroRunning) { DropWandSwap("the macro stopped"); return; }
// A wand swap's next step goes as soon as the server has answered the last (before the cast gates).
NoteModeChange();
TickWandSwap();
// Close casts the server reports finished, and say once when one is being held open.
PollCastTracker();
@ -1640,6 +1648,13 @@ public partial class BuffManager : IDisposable
return;
}
// /ra swaptest: the wand swap and one cast, timed (BuffManager.SwapTest.cs). After the vitals.
if (TickSwapTest())
{
Hold("swap test");
return;
}
// Only a recovery retry got past Spell Interval; nothing else goes inside it.
if (intervalHeld)
{
@ -5099,6 +5114,9 @@ public partial class BuffManager : IDisposable
_bowDequipAttempts = 0;
_wieldGateFailCount = 0;
_wandWieldFails.Clear();
_serverMagicDueUntil = DateTime.MinValue;
if (_wandSwap.Active) FinishWandSwap(Now, done: true); // the wand went on and Magic came: the swap is over
_magicAfterPeaceUntil = DateTime.MinValue;
// In Magic, but the stance we asked for may still be settling: yield the tick.
return StanceSettled(urgentHeal);
}
@ -5113,12 +5131,12 @@ public partial class BuffManager : IDisposable
// _lastBuffStanceAttempt), while buffing held the bot.
int noWandShift = Math.Min(_buffStanceConsecutiveFails, 5);
int noWandGateMs = Math.Min(1000 << noWandShift, 30000);
if ((RynthClock.Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs
if ((Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "no wand: Magic mode bare-handed"))
{
NoteStanceRequest();
_lastBuffStanceAttempt = RynthClock.Now;
_lastCastAttempt = RynthClock.Now;
_lastBuffStanceAttempt = Now;
_lastCastAttempt = Now;
if (_buffStanceConsecutiveFails < 6) _buffStanceConsecutiveFails++;
if (_buffStanceConsecutiveFails > 1)
_host.Log($"[BuffStance] no wand: ChangeCombatMode(Magic) retry #{_buffStanceConsecutiveFails} (next retry in {noWandGateMs / 1000}s)");
@ -5158,130 +5176,22 @@ public partial class BuffManager : IDisposable
alreadyWielded = true;
}
if (!alreadyWielded)
if (!_settings.FastWeaponSwap)
{
// Wield gate: don't spam UseObject. Hold off after the first issue
// until either the wielded check confirms (cleared on the Magic-mode
// branch above) or the resolve timeout elapses, then cool down
// before retrying. Mirrors the no-chat-timeout pattern used for
// spell casts at the top of OnHeartbeat. Checked BEFORE the shared
// swap gate so a denied attempt never claims the cross-subsystem slot.
DateTime now = RynthClock.Now;
if (now < _wieldCooldownUntil)
// Fast Weapon Swap off: the swap as before 2026-10-22 (BuffManager.LegacySwap.cs).
if (!alreadyWielded) return LegacyWandSwap(wandId, forBuff);
LegacyWandWielded(wandId);
}
else if (_wandSwap.Active || !alreadyWielded)
{
// A cooldown after a swap that didn't finish: no new swap until it ends.
if (!_wandSwap.Active && Now < _wieldCooldownUntil)
return false;
if (_pendingWieldId != 0)
{
if ((now - _pendingWieldAt).TotalMilliseconds < WieldResolveTimeoutMs)
return false;
if (_weaponSwapGate != null && _weaponSwapGate.Claims != _pendingWieldClaim)
{
_pendingWieldId = 0; // another swap since ours: not a failed wield
return false;
}
int stillInHand = _pendingWieldDirect ? FindWieldedNonWandWeapon(wandId) : 0;
if (stillInHand != 0 && IsWieldedLive(stillInHand))
{
_directSwapMisses++;
_packFirstNext = true;
_pendingWieldId = 0;
_host.Log($"[WieldGate] using the wand didn't put 0x{(uint)stillInHand:X8} away in {WieldResolveTimeoutMs:0} ms; " +
(_directSwapMisses >= DirectSwapMissesToStick
? $"{_directSwapMisses} in a row: from now on the weapon goes into a pack first"
: "the next swap puts the weapon into a pack first, then the use is tried again"));
return false;
}
_host.Log($"[WieldGate] UseObject(0x{(uint)_pendingWieldId:X8}) not confirmed in " +
$"{WieldResolveTimeoutMs:0}ms — cooling down {WieldCooldownMs:0}ms");
NoteWandWieldFailed(_pendingWieldId);
_pendingWieldId = 0;
_wieldCooldownUntil = now.AddMilliseconds(WieldCooldownMs);
// FIX: bound the previously-infinite wield loop. If the wand still won't
// wield after a few cooldowns (e.g. no pack to free the bow, or an
// unresolvable collision), degrade so buffing yields and combat runs.
if (++_wieldGateFailCount >= WieldGateFailMax)
return SignalSwapFailure(forBuff, FindWieldedNonWandWeapon(wandId), wandId);
// The wand swap's next step (HandSwapSequence): the off hand, the main hand, then the
// wand, each as soon as the server answers the last. True once the wand is in hand.
_wandSwapTouchedAt = Now;
if (!WandSwapStep(wandId, forBuff, Now))
return false;
}
// Shared weapon-swap gate: if CombatManager (or anything else) swapped
// a weapon within the last few seconds, wait — two equips in flight
// collide ("you can only move or use one item at a time" / AV).
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("buff-wand"))
return false;
// Tear down any in-flight physical combat BEFORE the UseObject. The
// transition Melee/Missile → Magic-via-wand must explicitly cancel the
// pending attack, or AC gets a UseObject while m_bAttacking is still
// set and wedges the item-action gate. Done only after we've claimed
// the swap slot above, so we don't cancel an attack then fail to swap.
if (!_combatTeardownDoneForCurrentBuffCycle &&
(CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile))
{
if (_host.HasCancelAttack) _host.CancelAttack();
if (_host.HasStopCompletely) _host.StopCompletelyBy("Buff/WandSwap");
_combatTeardownDoneForCurrentBuffCycle = true;
_host.Log($"[BuffPre] CancelAttack+StopCompletely before wand equip (mode was {CurrentCombatMode})");
}
// FIX: stock ACE will NOT auto-dequip the bow for a Held-slot wand
// (CheckWeaponCollision refuses while mainhand != null). Stow the wielded
// non-wand weapon into a capacity-verified open pack FIRST (AutoCram pattern,
// AV-safe), then UseObject(wand) once the hand is free. Fully bounded.
int bowId = FindWieldedNonWandWeapon(wandId);
if (bowId != 0 && (PackFirst || !IsWieldedLive(bowId))) // else the use swaps (see _directSwapMisses)
{
if (_bowDequipPendingId == bowId
&& (now - _bowDequipAt).TotalMilliseconds < WieldResolveTimeoutMs
&& IsWieldedLive(bowId))
return false; // dequip still resolving
if (IsWieldedLive(bowId))
{
int openPack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1);
if (openPack == 0 || _bowDequipAttempts >= BowDequipMaxAttempts)
{
// No verified-open pack to receive the bow, or repeated dequip
// failures -> the swap provably can't complete now. Degrade.
_host.Log($"[WieldGate] bow 0x{(uint)bowId:X8} dequip blocked (openPack=0x{(uint)openPack:X8}, attempts={_bowDequipAttempts}/{BowDequipMaxAttempts}) — degrading");
if (openPack == 0)
WorldObjectCache.WarnPackFull(_host, "can't put the weapon away to switch to the wand, so buffs and spell heals can't cast");
return SignalSwapFailure(forBuff, bowId, wandId);
}
_bowDequipAttempts++;
if (_worldObjectCache?[bowId] is WorldObject blocker && IsInOffhandSlot(blocker))
OffhandStowed?.Invoke(bowId); // a shield: combat puts it back after
_host.MoveItemInternal((uint)bowId, (uint)openPack, 0, 1); // amount>=1 (engine rejects 0)
_weaponSwapGate?.NoteMove(bowId, wieldedNow: true);
_bowDequipPendingId = bowId;
_bowDequipAt = now;
_lastCastAttempt = now;
_host.Log($"[WieldGate] dequip bow 0x{(uint)bowId:X8} -> pack 0x{(uint)openPack:X8} (attempt {_bowDequipAttempts}/{BowDequipMaxAttempts}) before wand equip");
return false; // yield until the bow is out of hand
}
_bowDequipPendingId = 0; // bow confirmed unwielded — fall through to wield the wand
}
_pendingWieldDirect = bowId != 0 && !PackFirst;
// Hands free: wield the caster into the Held slot (GetAndWieldItem, the paperdoll drag),
// as the off hand does. A use only wields a plain caster: a caster with a spell of its own
// (Electric Baton, Acid Staff) takes the use as "cast it" and the client says it must be
// wielded first (Drakkon, 2026-10-18 14:00). With a weapon still in hand the use stays
// (the client swaps); when that misses, the next swap empties the hands first.
if (!_pendingWieldDirect && _host.HasWieldItem)
{
_host.WieldItem((uint)wandId, HeldSlot);
_host.Log($"[WieldGate] wielding 0x{(uint)wandId:X8} '{_worldObjectCache?[wandId]?.Name}' into the Held slot");
}
else
_host.UseFor((uint)wandId, "Buff", _pendingWieldDirect ? "buffing: switch to the wand" : "buffing: wield the wand");
NoteStanceRequest();
_pendingWieldClaim = _weaponSwapGate?.Claims ?? 0;
_pendingWieldId = wandId;
_pendingWieldAt = now;
_lastCastAttempt = now;
return false; // Yield — let the server equip the wand
}
// Wand is wielded — clear the gate and switch stance.
@ -5289,8 +5199,15 @@ public partial class BuffManager : IDisposable
{
_pendingWieldId = 0;
_wieldCooldownUntil = DateTime.MinValue;
if (_pendingWieldDirect) _directSwapMisses = 0; // the use swapped: back to direct swaps
_packFirstNext = false; // a pack-route swap done: the next one tries the use
}
// The wand went on in a combat mode: the server switches to Magic by itself once the stance
// change of the last unwield is done (TryShuffleStance). Wait for that rather than queue a
// second stance change behind it.
if (Now < _serverMagicDueUntil)
{
LastBuffSkipReason = "the server is switching to Magic";
return false;
}
// Deadlock episode tracking: wand wielded but mode refuses to flip.
@ -5301,10 +5218,10 @@ public partial class BuffManager : IDisposable
// the clock restarts, so the refusals that follow are not counted as a wedged stance.
if (_buffStanceStuckSince != DateTime.MinValue && ActionPacer.LastEngineRefusalMs > _buffStanceStuckStartMs)
{
_buffStanceStuckSince = RynthClock.Now;
_buffStanceStuckSince = Now;
_buffStanceStuckStartMs = ActionPacer.NowMs();
}
double stuckMs = _buffStanceStuckSince == DateTime.MinValue ? 0 : (RynthClock.Now - _buffStanceStuckSince).TotalMilliseconds;
double stuckMs = _buffStanceStuckSince == DateTime.MinValue ? 0 : (Now - _buffStanceStuckSince).TotalMilliseconds;
// Capped re-equip recovery (mirrors CombatManager): handles the rare
// stale "wielded reads true" by resyncing the wield once or twice.
@ -5312,15 +5229,15 @@ public partial class BuffManager : IDisposable
// and unbounded re-equip jams the item-action queue permanently.
if (_buffStanceReEquips < BuffStanceReEquipMax
&& stuckMs > BuffStanceStuckRecoverMs
&& (RynthClock.Now - _buffStanceLastRecoverAt).TotalMilliseconds > BuffStanceStuckRecoverMs
&& (Now - _buffStanceLastRecoverAt).TotalMilliseconds > BuffStanceStuckRecoverMs
&& (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("buff-stance-recovery")))
{
_buffStanceLastRecoverAt = RynthClock.Now;
_buffStanceLastRecoverAt = Now;
_buffStanceReEquips++;
_host.Log($"[BuffStance] STUCK {stuckMs:0}ms (wielded, mode={CurrentCombatMode}≠Magic) — re-equip attempt {_buffStanceReEquips}/{BuffStanceReEquipMax} 0x{(uint)wandId:X8}");
_host.UseFor((uint)wandId, "Buff", "buffing: stance stuck, wield the wand again");
NoteStanceRequest();
_lastCastAttempt = RynthClock.Now;
_lastCastAttempt = Now;
return false;
}
// Past the cap and clearly wedged: warn ONCE so a multi-hour silent
@ -5340,13 +5257,17 @@ public partial class BuffManager : IDisposable
if (shift > 5) shift = 5;
int gateMs = 1000 << shift; // 1s, 2s, 4s, 8s, 16s, 32s
if (gateMs > 30000) gateMs = 30000; // cap at 30s
if ((RynthClock.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode"))
// Right after a swap through peace, Magic goes as soon as the wand is in hand: the server holds a
// Magic change until its peace animation ends by itself (NextUseTime), and on that route no
// other stance change can be queued. Only past our own peace request, never past anything else.
bool magicAfterPeace = Now < _magicAfterPeaceUntil && OnlyOurPeaceRequestPending();
if ((Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode", force: magicAfterPeace))
{
if (_buffStanceStuckSince == DateTime.MinValue) { _buffStanceStuckSince = RynthClock.Now; _buffStanceStuckStartMs = ActionPacer.NowMs(); }
if (_buffStanceStuckSince == DateTime.MinValue) { _buffStanceStuckSince = Now; _buffStanceStuckStartMs = ActionPacer.NowMs(); }
NoteStanceRequest();
_lastBuffStanceAttempt = RynthClock.Now;
_lastCastAttempt = RynthClock.Now;
_lastBuffStanceAttempt = Now;
_lastCastAttempt = Now;
if (_buffStanceConsecutiveFails < 6) _buffStanceConsecutiveFails++;
// Visible retry line (throttled by the backoff itself): the
// 2026-06-12 coma produced ZERO log output from this path.
@ -5360,40 +5281,6 @@ public partial class BuffManager : IDisposable
public Action<int>? OffhandStowed { get; set; }
private bool _offhandNoneNoted;
// The currently-wielded non-wand weapon (the bow) that blocks the Held-slot wand; else
// what is in the off hand (a shield, or an off-hand weapon): ACE refuses a Held-slot caster
// beside either. With the global Offhand setting None the off hand is never touched (the
// wand then can't be wielded; logged once).
private int FindWieldedNonWandWeapon(int wandId)
{
if (_worldObjectCache == null) return 0;
int offhand = 0;
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: true))
{
if (wo.Id == wandId) continue;
if (IsWandObject(wo)) continue;
if (WorldObjectCache.IsAmmo(wo)) continue; // arrows stay on; only the bow blocks the wand
if (IsInOffhandSlot(wo)) { offhand = wo.Id; continue; }
if ((wo.ObjectClass == AcObjectClass.MeleeWeapon
|| wo.ObjectClass == AcObjectClass.MissileWeapon)
&& WorldObjectCache.IsWieldedByPlayer(_host, wo))
return wo.Id;
}
if (offhand != 0 && OffhandRules.Parse(_settings.OffhandDefault, OffhandMode.Auto) == OffhandMode.None)
{
if (!_offhandNoneNoted)
{
_offhandNoneNoted = true;
_host.Log($"[WieldGate] 0x{(uint)offhand:X8} '{_worldObjectCache[offhand]?.Name}' is in the off hand and Offhand is None — leaving it; the server won't wield the wand beside it");
}
return 0;
}
return offhand;
}
private static bool IsInOffhandSlot(WorldObject wo) =>
(wo.Values(LongValueKey.CurrentWieldedLocation, 0) & OffhandRules.ShieldSlot) != 0;
// Live (forceRefresh) wielded check — never trusts a stale cache snapshot.
private bool IsWieldedLive(int id)
{
@ -5445,6 +5332,306 @@ public partial class BuffManager : IDisposable
return false;
}
// ── The wand swap's steps (HandSwapSequence) ────────────────────────────
/// <summary>
/// The wand swap's next step. True once the wand is in hand (the caller then sees to the Magic
/// stance); false while a step is on its way, or when the swap stopped (_magicModeBlocked then
/// lets a vital's kit or potion go, and _wandSwapExhausted parks a buff).
/// </summary>
private bool WandSwapStep(int wandId, bool forBuff, DateTime now)
{
if (_wandSwap.Active && _wandSwapWandId != wandId)
FinishWandSwap(now, done: false, why: "another wand was chosen");
if (!_wandSwap.Active)
{
// Shared weapon-swap gate: one claim for the whole swap, held until it ends, so combat
// can't put a weapon back between its steps (two item actions in flight collide).
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("buff-wand"))
return false;
var start = ReadHands();
int off = HandAt(start, HandSwapSequence.ShieldSlot);
// With the global Offhand setting None the off hand is never touched, and the server won't
// wield a caster beside it: no swap, said once (the kit or potion gets its turn).
if (off != 0 && OffhandRules.Parse(_settings.OffhandDefault, OffhandMode.Auto) == OffhandMode.None)
{
if (!_offhandNoneNoted)
{
_offhandNoneNoted = true;
_host.Log($"[WieldGate] 0x{(uint)off:X8} '{ItemName(off)}' is in the off hand and Offhand is None — leaving it; the server won't wield the wand beside it");
}
return SignalSwapFailure(forBuff, 0, wandId);
}
// Tear down any in-flight physical combat BEFORE the first step: an item action while
// m_bAttacking is still set wedges the client's item-action gate.
if (!_combatTeardownDoneForCurrentBuffCycle &&
(CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile))
{
if (_host.HasCancelAttack) _host.CancelAttack();
if (_host.HasStopCompletely) _host.StopCompletelyBy("Buff/WandSwap");
_combatTeardownDoneForCurrentBuffCycle = true;
_host.Log($"[BuffPre] CancelAttack+StopCompletely before wand equip (mode was {CurrentCombatMode})");
}
// From a combat mode, peace first (HandSwapSequence: one stance leg, then every move is
// answered at once, and no stance change is ever queued behind another).
int mode0 = CurrentCombatMode;
_wandSwap.Start("wand", now, new[] { (wandId, (int)HeldSlot) },
peaceFirst: mode0 == CombatMode.Melee || mode0 == CombatMode.Missile);
_weaponSwapGate?.Hold("buff-wand", (long)_wandSwap.GiveUpMs + 1000);
_wandSwapOpen = true;
_wandSwapWandId = wandId;
_wandSwapForBuff = forBuff;
_wandSwapMainAtStart = MainHandIn(start, wandId);
_wandSwapLastMoved = 0;
_host.Log($"[WieldGate] switching to 0x{(uint)wandId:X8} '{ItemName(wandId)}' ({DescribeHands(start)}, mode {CurrentCombatMode})");
}
var hands = ReadHands();
var step = _wandSwap.Next(hands, CurrentCombatMode, now);
switch (step.Act)
{
case HandSwapSequence.Act.Wait:
return false;
case HandSwapSequence.Act.Stance:
{
// The burst (test toggle /ra swaptest burst on): peace, both hands and the wand in one frame.
int burst = SwapBurst ? TryWandBurst(hands, wandId, now) : 0;
if (burst != 0) return false;
// Refused while the server owes an answer or the character animates (ActionPacer): next tick.
if (_host.ChangeCombatModeFor(step.Slot, "Buff", "wand swap: peace first, then the hands"))
{
_wandSwap.Sent(step, now);
_host.Log($"[WieldGate] peace first {(now - _wandSwap.StartedAt).TotalMilliseconds:0} ms into the switch (the moves are then answered at once)");
}
return false;
}
case HandSwapSequence.Act.MoveToPack:
{
int pack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1);
if (pack == 0)
{
WorldObjectCache.WarnPackFull(_host, "can't put the weapon away to switch to the wand, so buffs and spell heals can't cast");
return WandSwapFailed(_wandSwap.Abandon("no pack with room"), forBuff, wandId, now);
}
bool offhand = hands.TryGetValue(step.Id, out int slot) && (slot & HandSwapSequence.ShieldSlot) != 0;
if (offhand) OffhandStowed?.Invoke(step.Id); // combat puts it back after
_host.MoveItemInternal((uint)step.Id, (uint)pack, 0, 1); // amount>=1 (engine rejects 0)
_wandSwap.Sent(step, now);
_wandSwapLastMoved = step.Id;
_host.Log($"[WieldGate] 0x{(uint)step.Id:X8} '{ItemName(step.Id)}' ({(offhand ? "off hand" : "main hand")}) -> pack 0x{(uint)pack:X8} " +
$"{(now - _wandSwap.StartedAt).TotalMilliseconds:0} ms into the switch");
return false;
}
case HandSwapSequence.Act.Wield:
{
// GetAndWieldItem into the Held slot (the paperdoll drag). A use only wields a plain
// caster: one with a spell of its own (Electric Baton, Acid Staff) takes the use as
// "cast it" (Drakkon, 2026-10-18 14:00).
if (_host.HasWieldItem) _host.WieldItem((uint)step.Id, (uint)step.Slot);
else _host.UseFor((uint)step.Id, "Buff", "buffing: wield the wand");
_wandSwap.Sent(step, now);
_wandSwapLastMoved = step.Id;
NoteStanceRequest();
_pendingWieldId = step.Id;
_pendingWieldAt = now;
// No _lastCastAttempt here: the cast interval would hold the Magic request 400 ms (seen on
// Freya, 10-22 22:36); the first cast waits for the stance to settle anyway.
int mode = CurrentCombatMode;
_serverMagicDueUntil = mode == CombatMode.Melee || mode == CombatMode.Missile
? now.AddMilliseconds(ServerMagicWaitMs) : DateTime.MinValue;
_host.Log($"[WieldGate] wielding 0x{(uint)step.Id:X8} '{ItemName(step.Id)}' into the Held slot " +
$"{(now - _wandSwap.StartedAt).TotalMilliseconds:0} ms into the switch");
return false;
}
case HandSwapSequence.Act.Done:
FinishWandSwap(now, done: true);
MagicAfterPeace(now);
return true;
default:
return WandSwapFailed(step, forBuff, wandId, now);
}
}
/// <summary>The swap stopped short: bounded retries, then the degrade (kits and potions for vitals, parked buffs).</summary>
private bool WandSwapFailed(HandSwapSequence.Step step, bool forBuff, int wandId, DateTime now)
{
int mainAtStart = _wandSwapMainAtStart;
bool wandUnanswered = _wandSwap.FailedId == wandId;
FinishWandSwap(now, done: false, why: step.Why);
if (step.Why == "no pack with room") return SignalSwapFailure(forBuff, mainAtStart, wandId);
if (wandUnanswered) NoteWandWieldFailed(wandId);
_pendingWieldId = 0;
_serverMagicDueUntil = DateTime.MinValue;
_wieldCooldownUntil = now.AddMilliseconds(WieldCooldownMs);
// A vital's kit or potion gets its turn now, not after the retries.
_magicModeBlocked = true;
if (++_wieldGateFailCount >= WieldGateFailMax)
return SignalSwapFailure(forBuff, mainAtStart, wandId);
return false;
}
/// <summary>The swap is over (<paramref name="done"/>: the wand is in hand): the gate is free again, and the log says how long it took.</summary>
private void FinishWandSwap(DateTime now, bool done, string why = "")
{
if (!_wandSwapOpen) return; // once per swap (a failed sequence has already stopped itself)
_wandSwapOpen = false;
double ms = (now - _wandSwap.StartedAt).TotalMilliseconds;
string trail = _wandSwap.Trail;
_magicAfterPeaceUntil = done && _wandSwap.WentThroughPeace ? now.AddMilliseconds(MagicAfterPeaceMs) : DateTime.MinValue;
_wandSwap.Cancel();
_weaponSwapGate?.Release("buff-wand", _wandSwapLastMoved);
LastWandSwapMs = ms;
LastWandSwapTrail = trail;
_host.Log(done
? $"[WieldGate] wand in hand {ms:0} ms after the switch began ({trail})"
: $"[WieldGate] the switch to the wand stopped after {ms:0} ms: {why} ({trail})");
}
/// <summary>
/// Each heartbeat, before the cast gates: a swap step the server has answered is followed at once
/// (the cast interval, a gesture or a busy count hold casts, not item moves), and a swap nothing
/// asks for any more (the heal or buff went away) stops, without counting as a failure.
/// </summary>
private void TickWandSwap()
{
if (!_wandSwap.Active) return;
DateTime now = Now;
if ((now - _wandSwapTouchedAt).TotalMilliseconds > WandSwapAbandonMs)
{
FinishWandSwap(now, done: false, why: "nothing needs the wand now");
return;
}
WandSwapStep(_wandSwapWandId, _wandSwapForBuff, now);
}
/// <summary>A death, a portal or the macro stopping ended the swap: not a failed swap.</summary>
private void DropWandSwap(string why)
{
if (!_wandSwap.Active) return;
FinishWandSwap(Now, done: false, why: why);
_pendingWieldId = 0;
_serverMagicDueUntil = DateTime.MinValue;
}
/// <summary>What the server says is wielded (item id -> EquipMask), read fresh.</summary>
private Dictionary<int, int> ReadHands() => EquippedState.ReadFresh(_host, _worldObjectCache);
/// <summary>
/// The burst: peace, the moves out of the hands (raw PutItemInContainer, which the client doesn't
/// gate on a pending item request) and the wand's wield, queued in one tick so they go out in one
/// frame, before the client starts the peace animation that holds item actions (0.6 s a step on
/// the step route). In peace the server answers every one at once. Only when the server can't be
/// mid-animation: no combat-mode change for BurstQuietMs (ACE NextUseTime is set by stance changes,
/// uses and kits; the pacer refuses the peace request while a use is unanswered). Anything that
/// hasn't landed in HandSwapSequence.BurstResolveMs goes on one step at a time.
/// 0 = not tried (the step route), 1 = held this tick, 2 = sent.
/// </summary>
private int TryWandBurst(IReadOnlyDictionary<int, int> hands, int wandId, DateTime now)
{
if (!_host.HasPutItemInContainer || !_host.HasWieldItem) return 0;
if ((now - _modeChangedAt).TotalMilliseconds < BurstQuietMs) return 0;
var moves = _wandSwap.Blockers(hands);
if (moves.Count == 0 || moves.Count > 2) return 0;
int pack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: moves.Count);
if (pack == 0) return 0;
if (!_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "wand swap burst: peace, the hands and the wand at once")) return 1;
foreach (int id in moves)
{
if (hands.TryGetValue(id, out int slot) && (slot & HandSwapSequence.ShieldSlot) != 0) OffhandStowed?.Invoke(id);
_host.PutItemInContainer(unchecked((uint)id), unchecked((uint)pack), 0);
}
_host.WieldItem(unchecked((uint)wandId), HeldSlot);
_wandSwap.SentBurst(moves, now);
_wandSwapLastMoved = wandId;
NoteStanceRequest();
_pendingWieldId = wandId;
_pendingWieldAt = now;
_host.Log($"[WieldGate] burst {(now - _wandSwap.StartedAt).TotalMilliseconds:0} ms into the switch: peace, " +
string.Join(", ", moves.ConvertAll(id => $"0x{(uint)id:X8} '{ItemName(id)}'")) +
$" -> pack 0x{(uint)pack:X8}, 0x{(uint)wandId:X8} '{ItemName(wandId)}' -> Held, in one frame");
return 2;
}
/// <summary>
/// The burst goes with Fast Weapon Swap (when the server is quiet; else the step route). /ra swaptest
/// burst on|off overrides it until the next reload, to compare the two routes.
/// </summary>
internal bool SwapBurst { get => _swapBurstOverride ?? _settings.FastWeaponSwap; set => _swapBurstOverride = value; }
private bool? _swapBurstOverride;
private const double BurstQuietMs = 1300;
private int _lastSeenMode = -1;
private DateTime _modeChangedAt = DateTime.MinValue;
/// <summary>When the combat mode last changed, read every heartbeat (combat's tick doesn't run while buffing has it).</summary>
internal DateTime LastModeChangeAt => _modeChangedAt;
/// <summary>Each heartbeat: when the combat mode last changed (the burst waits out a stance change's animation).</summary>
private void NoteModeChange()
{
int m = CurrentCombatMode;
if (m == _lastSeenMode) return;
bool first = _lastSeenMode == -1; // the first read after a load is not a change
_lastSeenMode = m;
if (!first) _modeChangedAt = Now;
}
/// <summary>
/// The wand is in hand after a swap through peace: Magic is asked for now, from the swap itself (it
/// can run before the cast gates, which the pacer holds while our own peace request settles: 0.75 s
/// on Freya, 10-22 22:49). The server holds the change until the peace animation ends by itself.
/// The same bookkeeping as the Magic request in EnsureMagicMode, which won't send it twice.
/// </summary>
private void MagicAfterPeace(DateTime now)
{
if (now >= _magicAfterPeaceUntil || CurrentCombatMode != CombatMode.NonCombat || !OnlyOurPeaceRequestPending()) return;
if (!_host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand in hand after peace: Magic mode", force: true)) return;
if (_buffStanceStuckSince == DateTime.MinValue) { _buffStanceStuckSince = now; _buffStanceStuckStartMs = ActionPacer.NowMs(); }
NoteStanceRequest();
_lastBuffStanceAttempt = now;
_lastCastAttempt = now;
if (_buffStanceConsecutiveFails < 6) _buffStanceConsecutiveFails++;
_host.Log($"[WieldGate] Magic asked for {(now - _wandSwap.StartedAt).TotalMilliseconds:0} ms into the switch (the server starts it when the peace animation ends)");
}
/// <summary>Nothing the pacer waits on but our own request for peace (or nothing at all).</summary>
private bool OnlyOurPeaceRequestPending()
{
var a = ActionPacer.Current(_host);
return a == null || (a.Kind == PacedKind.CombatMode && a.ModeTarget == CombatMode.NonCombat && a.Who == "Buff");
}
private static int HandAt(IReadOnlyDictionary<int, int> hands, int slot)
{
foreach (var kv in hands) if ((kv.Value & slot) != 0) return kv.Key;
return 0;
}
/// <summary>The weapon in the main hand (not the wand being wielded, not the off hand); 0 = none.</summary>
private static int MainHandIn(IReadOnlyDictionary<int, int> hands, int wandId)
{
const int main = HandSwapSequence.MeleeSlot | HandSwapSequence.MissileSlot | HandSwapSequence.TwoHandedSlot | HandSwapSequence.HeldSlot;
foreach (var kv in hands) if (kv.Key != wandId && (kv.Value & main) != 0) return kv.Key;
return 0;
}
private string DescribeHands(IReadOnlyDictionary<int, int> hands)
{
var parts = new List<string>();
foreach (var kv in hands)
{
if ((kv.Value & HandSwapSequence.HandSlots) == 0) continue;
string where = (kv.Value & HandSwapSequence.ShieldSlot) != 0 ? "off hand" : "main hand";
parts.Add($"{where} 0x{(uint)kv.Key:X8} '{ItemName(kv.Key)}'");
}
return parts.Count == 0 ? "hands empty" : string.Join(", ", parts);
}
private string ItemName(int id) => _worldObjectCache?[id]?.Name ?? "?";
/// <summary>
/// Locates a wand to equip: a listed wand, the one already in hand first (so buffing
/// doesn't swap one listed wand for another). The pack is searched only when the Items list

View file

@ -0,0 +1,170 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Fast Weapon Swap, combat's own equip (2026-10-23): a monster to fight with a caster still in hand
/// (it came while healing). Before, combat used the main weapon (the client's own swap): the wand went
/// into the pack after a forced stance change in Magic mode (about 1.2 s), the main weapon landed at
/// about 1.4 s and the off hand at 1.7 s (Drakkon, 10-22 night, about half his swaps back). Now the same
/// hands swap as weapons back after heals (HandSwapSequence): peace, the wand out, the main weapon and
/// the off hand on (one frame when the server is quiet), then the fight's stance at once.
///
/// A weapons-back swap under way when the target comes goes on, pointed at the fight's weapons when they
/// differ; a fight with the wand ends it. A failed fight swap leaves that weapon to the client's own swap
/// for <see cref="FightSwapFallbackSec"/>. Setting off: none of this runs.
/// </summary>
public partial class CombatManager
{
// The hands swap (_rearmSwap) is for the fight's weapons, not weapons back after heals.
private bool _handsSwapForFight;
private int _handsSwapFightMode;
private string _handsGateBy = "rearm-after-vitals";
// The stance owed after the swap is the fight's (asked for with a target, PeaceModeWhenIdle or not).
private bool _rearmStanceForFight;
// A fight swap that failed: the client's own swap for that weapon for a while.
private int _fightSwapFallbackFor;
private DateTime _fightSwapFallbackUntil = DateTime.MinValue;
private const double FightSwapFallbackSec = 20;
private string HandsSwapLabel => _handsSwapForFight ? "weapons for the fight" : "weapons back";
/// <summary>
/// The fight's main weapon and the off hand to go with it: the planned one, else what is in the off
/// hand already when it may stay (a hands swap takes off everything it doesn't want).
/// </summary>
private List<(int Id, int Slot)> FightWants(WorldObject target, MonsterRule? rule, int mainId)
{
var wants = new List<(int Id, int Slot)> { (mainId, MainSlotFor(mainId)) };
int off = OffhandPlanFor(target, rule, mainId).Id;
if (off != 0 && off != mainId && _worldFilter[off] is WorldObject offWo && (_host.HasWieldItem || IsShieldItem(offWo)))
{
wants.Add((off, HandSwapSequence.ShieldSlot));
return wants;
}
int inOff = OffhandInSlot(fresh: true);
if (inOff != 0 && inOff != mainId && _worldFilter[inOff] is WorldObject inOffWo
&& OffhandRules.OffhandAllowed(MainKindOf(_worldFilter[mainId]), IsShieldItem(inOffWo)))
wants.Add((inOff, HandSwapSequence.ShieldSlot));
return wants;
}
private static bool SameWants(IReadOnlyList<(int Id, int Slot)> a, IReadOnlyList<(int Id, int Slot)> b)
{
if (a.Count != b.Count) return false;
for (int i = 0; i < a.Count; i++)
if (a[i] != b[i]) return false;
return true;
}
/// <summary>
/// A caster in hand and <paramref name="mainId"/> (melee or a launcher) wanted: start the hands swap.
/// True = started, or waiting to (the gate, ammo going into the pack); false = the old route this tick.
/// </summary>
private bool TryStartFightHandsSwap(WorldObject target, MonsterRule? rule, int mainId, int desiredMode)
{
DateTime now = RynthClock.Now;
if (_fightSwapFallbackFor == mainId && now < _fightSwapFallbackUntil) return false;
if (!_host.HasMoveItemInternal) return false;
if (desiredMode == CombatMode.Missile)
{
var prep = PrepareAmmoFor(mainId); // the wrong ammo into the pack first; arms the ammo follow-up
if (prep == AmmoPrep.Busy) return true;
if (prep == AmmoPrep.Blocked) return false;
}
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("combat-hands-swap")) return true;
StartHandsSwapForFight(now, FightWants(target, rule, mainId), desiredMode, target);
RearmSwapAdvance(now);
return true;
}
private void StartHandsSwapForFight(DateTime now, List<(int Id, int Slot)> wants, int desiredMode, WorldObject target)
{
int mode = CurrentCombatMode;
_rearmWants = wants;
_rearmSwap.Start("weapons for the fight", now, wants, peaceFirst: mode != CombatMode.NonCombat);
_handsSwapForFight = true;
_handsSwapFightMode = desiredMode;
_handsGateBy = "combat-hands-swap";
_weaponSwapGate?.Hold(_handsGateBy, (long)_rearmSwap.GiveUpMs + 1000);
_rearmSwapOpen = true;
_rearmLastMoved = 0;
_rearmStanceWanted = 0;
_host.Log($"[EquipDiag] weapons for the fight ('{target.Name}'): " +
string.Join(" + ", wants.Select(w => $"0x{(uint)w.Id:X8} '{WeaponName(w.Id)}'{(w.Slot == HandSwapSequence.ShieldSlot ? " (off hand)" : "")}")) +
$" (mode {mode})");
}
/// <summary>
/// A hands swap is under way and combat has a target: true = wait for it (it goes on, now with the
/// fight's weapons); false = it ended (the fight wants a caster, or another launcher) and combat's
/// own equip goes on this tick.
/// </summary>
private bool FightJoinsHandsSwap(WorldObject target, MonsterRule? rule, int mainId, WorldObject mainObj)
{
DateTime now = RynthClock.Now;
bool wasFight = _handsSwapForFight;
if (IsWandObject(mainObj))
{
FinishRearmSwap(now, done: false, why: $"'{target.Name}' is fought with the wand");
if (!wasFight) _rearmedFor = _rearmVital;
return false;
}
_curOffhandMode = OffhandChoiceFor(target, rule).Mode;
var wants = FightWants(target, rule, mainId);
int mode = WeaponKind(mainId);
if (SameWants(_rearmSwap.Wants, wants))
{
if (!wasFight) _host.Log($"[EquipDiag] weapons back: the same weapons for '{target.Name}', going on");
_handsSwapForFight = true;
_handsSwapFightMode = mode;
return true;
}
if (_rearmSwap.InFlight) return true; // the step on its way lands first, then the new weapons
if (mode == CombatMode.Missile)
{
// A launcher needs its ammo seen to first: combat's own launcher swap does that.
FinishRearmSwap(now, done: false, why: $"a launcher for '{target.Name}'");
if (!wasFight) _rearmedFor = _rearmVital;
return false;
}
_host.Log($"[EquipDiag] {HandsSwapLabel}: other weapons for '{target.Name}' ({_rearmSwap.Trail})");
StartHandsSwapForFight(now, wants, mode, target);
RearmSwapAdvance(now);
return true;
}
/// <summary>Everything the fight wants is in hand: its stance at once (past our own peace request).</summary>
private void FightSwapDone(DateTime now)
{
int main = _rearmWants.Count > 0 ? _rearmWants[0].Id : 0;
int mode = _handsSwapFightMode;
if (main != 0) SwapTracker.Confirmed(main, now);
_inHandReadAt = DateTime.MinValue; // read the hands fresh next tick
_offSlotReadAt = DateTime.MinValue;
// A launcher: only with fitting ammo on; otherwise the wielded branch puts it on, then asks.
bool ammoReady = mode != CombatMode.Missile || (HasWieldedAmmo() && !LauncherSwapHoldsStance(main));
_rearmStanceWanted = mode != 0 && mode != CombatMode.Magic && CurrentCombatMode != mode && ammoReady ? mode : 0;
_rearmStanceSince = now;
_rearmStanceForFight = true;
FinishRearmSwap(now, done: true);
RearmStanceStep(now);
}
/// <summary>The fight swap stopped: the client's own swap for that weapon for a while.</summary>
private void NoteFightSwapFailed(DateTime now, bool counted = true)
{
if (!counted) return;
int main = _rearmWants.Count > 0 ? _rearmWants[0].Id : 0;
if (main == 0) return;
_fightSwapFallbackFor = main;
_fightSwapFallbackUntil = now.AddSeconds(FightSwapFallbackSec);
_host.Log($"[EquipDiag] weapons for the fight: the client's own swap for 0x{(uint)main:X8} '{WeaponName(main)}' for {FightSwapFallbackSec:0} s");
}
}

View file

@ -0,0 +1,65 @@
using System;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
using System.Linq;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Weapons Back After Heals as it was before 2026-10-22 (RynthSuite e613280), kept for Fast Weapon
/// Swap off: a use of the main weapon (the client puts the wand away), then the off hand once the
/// swap gate lets it go. Fast Weapon Swap on goes through HandSwapSequence (RearmAfterVitalsStep).
/// </summary>
public partial class CombatManager
{
private bool LegacyRearmSwap(DateTime now, DateTime vital)
{
int inHand = InHandWeaponId();
if (inHand != _fightMainId)
{
if (SwapTracker.PendingId != 0) { FoldServerAnswer(SwapTracker, now); return true; } // our wield is on its way
var step = SwapStep(_fightMainId, inHand);
if (step == WeaponSwapTracker.Step.Wait) return true;
if (step != WeaponSwapTracker.Step.Swap) { _rearmedFor = vital; return false; }
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("rearm-after-vitals")) return true;
var prep = ClearOffhandFor(_fightMainId, OffhandMode.Auto, gateHeld: true);
if (prep == OffPrep.Busy) return true;
if (prep == OffPrep.Blocked) { _rearmedFor = vital; return false; }
SendWield(_fightMainId, inHand, "weapons back after heals");
return true;
}
int off = OffhandInSlot();
if (_fightOffId != 0 && off != _fightOffId && _fightOffId != _fightMainId
&& _worldFilter.PlayerHas(_fightOffId) != false && _settings.ItemRules.Any(r => r.Id == _fightOffId))
{
FoldServerAnswer(OffhandTracker, now);
if (OffhandTracker.PendingId != 0) return true;
if (off != 0) { DequipOffhand(off, $"to put 0x{(uint)_fightOffId:X8} '{WeaponName(_fightOffId)}' back"); return true; }
var wo = _worldFilter[_fightOffId];
if (wo != null && _host.HasWieldItem && (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("rearm-after-vitals-offhand")))
{
var stepOff = OffhandTracker.Next(_fightOffId, off, now, WeaponName);
if (stepOff == WeaponSwapTracker.Step.Swap && _host.WieldItem(unchecked((uint)_fightOffId), OffhandRules.ShieldSlot))
{
if (_host.HasGetLastUseDone && _host.TryGetLastUseDone(out int uSeq, out _)) _swapUseDoneSeq = uSeq;
if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int wSeq, out _, out _, out _)) _swapWeenieSeq = wSeq;
OffhandTracker.Sent(_fightOffId, 0, now);
_weaponSwapGate?.NoteMove(_fightOffId, wieldedNow: false);
_offhandSentId = _fightOffId;
_lastEquipTime = now;
_host.Log($"[EquipDiag] weapons back after heals: off hand 0x{(uint)_fightOffId:X8} '{wo.Name}'");
return true;
}
if (stepOff == WeaponSwapTracker.Step.Wait) return true;
}
_rearmedFor = vital; // the off hand can't go on now: the main hand is back, that will do
return false;
}
_rearmedFor = vital;
_host.Log($"[EquipDiag] weapons back after heals: 0x{(uint)_fightMainId:X8} '{WeaponName(_fightMainId)}'" +
(_fightOffId != 0 ? $" and 0x{(uint)_fightOffId:X8} '{WeaponName(_fightOffId)}'" : "") + " in hand");
return false;
}
}

View file

@ -4097,6 +4097,8 @@ public partial class CombatManager : IDisposable
public void OnHeartbeat()
{
NoteSwapPortal();
// The hands swap's steps (weapons back, or the fight's weapons) go before the gates; the macro stopping ends it (freeing the gate).
TickRearmSwap();
if (!_settings.IsMacroRunning)
{
@ -4481,7 +4483,8 @@ public partial class CombatManager : IDisposable
/// <summary>
/// The weapon to fight <paramref name="target"/> with (0 = none), and the element in
/// <paramref name="desired"/>. See WeaponPlanner for the order: this monster's Damage tab
/// weapon (listed only), a slayer of the monster, the Damage tab DEFAULT row's weapon, the
/// weapon, else its Monsters rule's weapon (listed or not), a slayer of the monster, the Damage
/// tab DEFAULT row's weapon, else the Monsters Default row's, the
/// Monsters rule's damage type, the weakness (weakest element a listed
/// weapon of the main kind has), else the weapon in hand, the learned best, the first.
/// Casters are skipped when the character has no War/Void Magic (IsUsableCombatWeapon).
@ -4495,10 +4498,11 @@ public partial class CombatManager : IDisposable
}
/// <summary>
/// The weapon and element for <paramref name="target"/> (WeaponPlanner's rule). Only weapons
/// in the Items list are candidates: a Damage-tab pick or a learned "best" weapon that is no
/// The weapon and element for <paramref name="target"/> (WeaponPlanner's rule). The candidates
/// are the Items list's weapons: a Damage-tab pick or a learned "best" weapon that is no
/// longer listed is ignored (logged once), which is how an unlisted fire wand used to be
/// wielded after the user removed it from the list (2026-09-30).
/// wielded after the user removed it from the list (2026-09-30). The one exception is a
/// weapon set on the Monsters tab, used listed or not (2026-10-22).
/// </summary>
internal WeaponPlan PlanFor(WorldObject target, MonsterRule? rule)
{
@ -4537,18 +4541,59 @@ public partial class CombatManager : IDisposable
uint wcid = 0;
if (_host.HasGetObjectWcid && _host.TryGetObjectWcid((uint)target.Id, out uint tw)) wcid = tw;
// The weapon the player fixed, the first usable of (owner's rule, 2026-10-22, problem report
// R-20261022-193411-fb72 "ignoring monster rules, specifically which weapon is set for the
// mob type": a Monsters rule's weapon was imported, shown and kept from trade/sell, but
// combat never read it, so the weakness pick wielded something else):
// 1. this monster's own Damage tab pick (by wcid) - WeaponPlanner step 1
// 2. the matched Monsters rule's weapon (not the Default row) - step 1
// 3. the Damage tab DEFAULT row's weapon - step 3 (a slayer beats it)
// 4. the Monsters tab Default row's weapon - step 3
// Only 1 needs the wcid: a rule weapon still applies to a monster whose wcid isn't known.
// One the character can't wield now (a requirement, or refused) is left out quietly, it is
// logged where the list drops it. A Damage tab pick must be in the Items list (an unlisted
// fire wand was wielded that way, 2026-09-30); one that isn't is logged once. A Monsters tab
// weapon (2 and 4) need not be (owner, 2026-10-22: "if it is in the monsters tab but not
// item list it should still use it"): it joins the candidates when carried and usable.
// Either way, when one can't be used the next is tried. A listed weapon for another build
// stays listed.
int fixedId = 0, learnedId = 0;
string fixedSource = "Damage tab";
bool fixedIsDefault = false;
var defaultRule = DefaultMonsterRule();
bool ownRule = rule != null && !ReferenceEquals(rule, defaultRule)
&& !rule.Name.Equals("Default", StringComparison.OrdinalIgnoreCase);
bool TryFixed(int id, string source, string noteAs, bool isDefault, bool listOnly)
{
if (fixedId != 0 || id == 0 || !CanWieldNow(id)) return false;
if (!listed.Any(c => c.Id == id))
{
if (listOnly) { NoteUnlisted(id, noteAs); return false; }
var extra = CandidateFor(id, null, InHandWeaponId(), admitCasters: false, noteAs + " weapon", out bool caster);
if (extra == null)
{
if (caster && _unlistedNoted.Add(id))
_host.Log($"[EquipDiag] {noteAs} weapon 0x{(uint)id:X8} '{WeaponName(id)}' is a caster and the character can't fight with magic: {CanMagicDiag()}");
return false;
}
if (_unlistedNoted.Add(id))
_host.Log($"[EquipDiag] {noteAs} weapon 0x{(uint)id:X8} '{extra.Name}' isn't in the Items list — using it (set on the Monsters tab)");
listed.Add(extra);
}
fixedId = id; fixedSource = source; fixedIsDefault = isDefault;
return true;
}
if (wcid != 0 && _damageStore != null)
TryFixed((int)_damageStore.GetManualWeapon(wcid), "Damage tab", "Damage tab", false, listOnly: true);
if (ownRule)
TryFixed(rule!.WeaponId, "Monsters rule weapon", $"Monsters rule '{rule.Name}'", false, listOnly: false);
if (_damageStore != null)
TryFixed((int)_damageStore.GetDefaultWeapon(), "Damage tab default", "Damage tab default", true, listOnly: true);
if (defaultRule != null)
TryFixed(defaultRule.WeaponId, "Monsters Default weapon", "Monsters Default row", true, listOnly: false);
if (wcid != 0 && _damageStore != null)
{
uint pick = _damageStore.GetManualWeapon(wcid);
if (pick == 0) { pick = _damageStore.GetDefaultWeapon(); fixedSource = "Damage tab default"; fixedIsDefault = true; }
// Not usable by this character right now (a requirement, or refused): left out quietly, it
// is logged where the list drops it. A listed weapon for another build stays listed.
if (pick != 0 && !CanWieldNow((int)pick)) pick = 0;
if (pick != 0 && !listed.Any(c => c.Id == (int)pick)) { NoteUnlisted((int)pick, fixedSource); pick = 0; }
fixedId = (int)pick;
uint best = _damageStore.GetBestWeapon(wcid);
if (best != 0 && !CanWieldNow((int)best)) best = 0;
if (best != 0 && !listed.Any(c => c.Id == (int)best)) { NoteUnlisted((int)best, "Damage tab learned"); best = 0; }
@ -4684,49 +4729,69 @@ public partial class CombatManager : IDisposable
var list = new List<WeaponCandidate>();
foreach (var r in _settings.ItemRules)
{
if (r.Id == 0) continue;
var wo = _worldFilter[r.Id];
if (wo == null) continue;
// Sold, dropped or traded: still known to the client, but not ours to wield (a sold
// Flaming Greataxe was tried three times, the character standing in the fight, 2026-10-14).
if (r.Id != inHand && _worldFilter.PlayerHas(r.Id) == false)
{
// Not within NotCarriedGraceMs of a wield or move of ours: mid-swap a weapon is
// briefly in neither hand nor the pack walk. Drakkon's Acid Hand Wraps were dropped
// from the choice that way on 2026-10-17 and he fought bare-handed.
if ((RynthClock.Now - _lastEquipTime).TotalMilliseconds >= NotCarriedGraceMs)
{
if (_notCarriedNoted.Add(r.Id))
_host.Log($"[EquipDiag] listed weapon 0x{(uint)r.Id:X8} '{wo.Name}' isn't in your pack (sold, dropped or traded?): skipped");
continue;
}
}
else _notCarriedNoted.Remove(r.Id);
if (!admitCasters && !IsUsableCombatWeapon(r.Id)) { (leftOut ??= new List<int>()).Add(r.Id); continue; }
if (r.Id != inHand && SkillTooLowFor(r.Id)) continue;
// A wield requirement the character doesn't meet: the client refuses the wield without
// asking the server, so no "skill too low" answer ever comes (the Tetsubo, 2026-10-18).
if (r.Id != inHand && WieldRequirements.Unmet(_host, _charSkills, unchecked((uint)r.Id)) is string unmet)
{
if (_wieldReqNoted.Add(r.Id))
{
_host.Log($"[EquipDiag] listed weapon 0x{(uint)r.Id:X8} '{wo.Name}' can't be wielded ({unmet}): left out of the weapon choice");
_host.WriteToChat($"[RynthAi] {wo.Name} can't be wielded ({unmet}), so combat doesn't use it.", 1);
}
continue;
}
if (list.Any(c => c.Id == r.Id)) continue;
if (wo.ObjectClass == AcObjectClass.MissileWeapon && IsAmmoItem(wo)) continue; // listed arrows are the ammo choice, never a weapon to wield
if (IsShieldItem(wo)) continue; // listed shields are the off hand's (CombatManager.Offhand.cs)
var info = ElementTracker.Read(r.Id, wo.Name);
string elem = WeaponElements.Normalize(r.Element);
if (elem.Length == 0) elem = info.Element;
var (slayType, slayBonus) = SlayerOf(r.Id);
list.Add(new WeaponCandidate(r.Id, wo.Name, WeaponKind(r.Id), elem, info.Rending, r.Id == inHand, slayType, slayBonus));
if (r.Id == 0 || list.Any(c => c.Id == r.Id)) continue;
var c = CandidateFor(r.Id, r.Element, inHand, admitCasters, "listed weapon", out bool casterLeftOut);
if (casterLeftOut) (leftOut ??= new List<int>()).Add(r.Id);
if (c != null) list.Add(c);
}
return list;
}
/// <summary>
/// One weapon as a candidate for the weapon choice, or null when it isn't one now: not known,
/// not carried, a caster the character can't fight with (<paramref name="casterLeftOut"/>),
/// a requirement not met, ammo or a shield. <paramref name="what"/> names it in the log
/// ("listed weapon", "Monsters rule 'X' weapon").
/// </summary>
private WeaponCandidate? CandidateFor(int id, string? setElement, int inHand, bool admitCasters, string what, out bool casterLeftOut)
{
casterLeftOut = false;
var wo = _worldFilter[id];
if (wo == null) return null;
// Sold, dropped or traded: still known to the client, but not ours to wield (a sold
// Flaming Greataxe was tried three times, the character standing in the fight, 2026-10-14).
if (id != inHand && _worldFilter.PlayerHas(id) == false)
{
// Not within NotCarriedGraceMs of a wield or move of ours: mid-swap a weapon is
// briefly in neither hand nor the pack walk. Drakkon's Acid Hand Wraps were dropped
// from the choice that way on 2026-10-17 and he fought bare-handed.
if ((RynthClock.Now - _lastEquipTime).TotalMilliseconds >= NotCarriedGraceMs)
{
if (_notCarriedNoted.Add(id))
_host.Log($"[EquipDiag] {what} 0x{(uint)id:X8} '{wo.Name}' isn't in your pack (sold, dropped or traded?): skipped");
return null;
}
}
else _notCarriedNoted.Remove(id);
if (!admitCasters && !IsUsableCombatWeapon(id)) { casterLeftOut = true; return null; }
if (id != inHand && SkillTooLowFor(id)) return null;
// A wield requirement the character doesn't meet: the client refuses the wield without
// asking the server, so no "skill too low" answer ever comes (the Tetsubo, 2026-10-18).
if (id != inHand && WieldRequirements.Unmet(_host, _charSkills, unchecked((uint)id)) is string unmet)
{
if (_wieldReqNoted.Add(id))
{
_host.Log($"[EquipDiag] {what} 0x{(uint)id:X8} '{wo.Name}' can't be wielded ({unmet}): left out of the weapon choice");
_host.WriteToChat($"[RynthAi] {wo.Name} can't be wielded ({unmet}), so combat doesn't use it.", 1);
}
return null;
}
if (wo.ObjectClass == AcObjectClass.MissileWeapon && IsAmmoItem(wo)) return null; // listed arrows are the ammo choice, never a weapon to wield
if (IsShieldItem(wo)) return null; // listed shields are the off hand's (CombatManager.Offhand.cs)
var info = ElementTracker.Read(id, wo.Name);
string elem = WeaponElements.Normalize(setElement);
if (elem.Length == 0) elem = info.Element;
var (slayType, slayBonus) = SlayerOf(id);
return new WeaponCandidate(id, wo.Name, WeaponKind(id), elem, info.Rending, id == inHand, slayType, slayBonus);
}
/// <summary>
/// A weapon the player picked on the Monsters tab (any rule's, the Default row's included).
/// It is theirs to fight with even when it isn't in the Items list (owner, 2026-10-22).
/// </summary>
internal bool IsMonstersTabWeapon(int id) =>
id != 0 && _settings.MonsterRules.Exists(m => m.WeaponId == id);
// The weapon in hand, read live at most every InHandReadMs (the read walks the inventory).
private int _inHandId;
private DateTime _inHandReadAt = DateTime.MinValue;
@ -4835,62 +4900,286 @@ public partial class CombatManager : IDisposable
_host.Log($"[EquipDiag] weapons back after heals: gave up after {RearmGiveUpMs / 1000:0} s (main 0x{(uint)_fightMainId:X8} '{WeaponName(_fightMainId)}', off hand 0x{(uint)_fightOffId:X8} '{WeaponName(_fightOffId)}')");
return false;
}
// Still ours to wield: listed, carried, not refused for skill.
if (!_settings.ItemRules.Any(r => r.Id == _fightMainId) || _worldFilter.PlayerHas(_fightMainId) == false || SkillTooLowFor(_fightMainId))
// Still ours to wield: listed (or set on the Monsters tab), carried, not refused for skill.
if (!(_settings.ItemRules.Any(r => r.Id == _fightMainId) || IsMonstersTabWeapon(_fightMainId))
|| _worldFilter.PlayerHas(_fightMainId) == false || SkillTooLowFor(_fightMainId))
{
_rearmedFor = vital;
return false;
}
int inHand = InHandWeaponId();
if (inHand != _fightMainId)
{
if (SwapTracker.PendingId != 0) { FoldServerAnswer(SwapTracker, now); return true; } // our wield is on its way
var step = SwapStep(_fightMainId, inHand);
if (step == WeaponSwapTracker.Step.Wait) return true;
if (step != WeaponSwapTracker.Step.Swap) { _rearmedFor = vital; return false; }
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("rearm-after-vitals")) return true;
var prep = ClearOffhandFor(_fightMainId, OffhandMode.Auto, gateHeld: true);
if (prep == OffPrep.Busy) return true;
if (prep == OffPrep.Blocked) { _rearmedFor = vital; return false; }
SendWield(_fightMainId, inHand, "weapons back after heals");
return true;
}
// Fast Weapon Swap off: as before 2026-10-22 (CombatManager.LegacySwap.cs).
if (!_settings.FastWeaponSwap) return LegacyRearmSwap(now, vital);
var hands = EquippedState.ReadFresh(_host, _worldFilter);
bool offWanted = _fightOffId != 0 && _fightOffId != _fightMainId
&& _worldFilter.PlayerHas(_fightOffId) != false && _settings.ItemRules.Any(r => r.Id == _fightOffId);
const int mainHand = HandSwapSequence.HandSlots & ~HandSwapSequence.ShieldSlot;
bool mainIn = hands.TryGetValue(_fightMainId, out int mainAt) && (mainAt & mainHand) != 0;
bool offIn = !offWanted || (hands.TryGetValue(_fightOffId, out int offAt) && (offAt & HandSwapSequence.ShieldSlot) != 0);
int off = OffhandInSlot();
if (_fightOffId != 0 && off != _fightOffId && _fightOffId != _fightMainId
&& _worldFilter.PlayerHas(_fightOffId) != false && _settings.ItemRules.Any(r => r.Id == _fightOffId))
// The weapons are back: the fight's stance, once, when the swap went through peace (a weapon
// wielded in a combat mode is put into its stance by the server itself; in peace it isn't).
if (!_rearmSwap.Active && mainIn && offIn)
{
FoldServerAnswer(OffhandTracker, now);
if (OffhandTracker.PendingId != 0) return true;
if (off != 0) { DequipOffhand(off, $"to put 0x{(uint)_fightOffId:X8} '{WeaponName(_fightOffId)}' back"); return true; }
var wo = _worldFilter[_fightOffId];
if (wo != null && _host.HasWieldItem && (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("rearm-after-vitals-offhand")))
{
var stepOff = OffhandTracker.Next(_fightOffId, off, now, WeaponName);
if (stepOff == WeaponSwapTracker.Step.Swap && _host.WieldItem(unchecked((uint)_fightOffId), OffhandRules.ShieldSlot))
{
if (_host.HasGetLastUseDone && _host.TryGetLastUseDone(out int uSeq, out _)) _swapUseDoneSeq = uSeq;
if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int wSeq, out _, out _, out _)) _swapWeenieSeq = wSeq;
OffhandTracker.Sent(_fightOffId, 0, now);
_weaponSwapGate?.NoteMove(_fightOffId, wieldedNow: false);
_offhandSentId = _fightOffId;
_lastEquipTime = now;
_host.Log($"[EquipDiag] weapons back after heals: off hand 0x{(uint)_fightOffId:X8} '{wo.Name}'");
return true;
}
if (stepOff == WeaponSwapTracker.Step.Wait) return true;
}
_rearmedFor = vital; // the off hand can't go on now: the main hand is back, that will do
if (_rearmStanceWanted != 0 && !RearmStanceStep(now)) return true; // held a moment (the pacer): next tick
_rearmedFor = vital;
_host.Log($"[EquipDiag] weapons back after heals: 0x{(uint)_fightMainId:X8} '{WeaponName(_fightMainId)}'" +
(offWanted ? $" and 0x{(uint)_fightOffId:X8} '{WeaponName(_fightOffId)}'" : "") + " in hand");
return false;
}
_rearmedFor = vital;
_host.Log($"[EquipDiag] weapons back after heals: 0x{(uint)_fightMainId:X8} '{WeaponName(_fightMainId)}'" +
(_fightOffId != 0 ? $" and 0x{(uint)_fightOffId:X8} '{WeaponName(_fightOffId)}'" : "") + " in hand");
return false;
// Weapons back as fast as the server allows (2026-10-22, HandSwapSequence): from Magic, peace
// first (one stance leg), the wand into a pack, the main weapon and the off hand, each the moment
// the server answers the last, then the fight's stance. Drakkon's Sceptre -> two Hand Wraps took
// 2.3 s: the use of the main weapon (the client puts the wand away after a forced stance change,
// 1.2 s), then the off hand once the gate let it go (a corpse open went first). The gate is held
// for the whole swap, so nothing else swaps between its steps.
if (!_rearmSwap.Active)
{
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("rearm-after-vitals")) return true;
var wants = new List<(int Id, int Slot)> { (_fightMainId, MainSlotFor(_fightMainId)) };
if (offWanted) wants.Add((_fightOffId, HandSwapSequence.ShieldSlot));
_rearmWants = wants;
int mode = CurrentCombatMode;
_rearmSwap.Start("weapons back", now, wants, peaceFirst: mode != CombatMode.NonCombat);
_handsSwapForFight = false;
_handsGateBy = "rearm-after-vitals";
_weaponSwapGate?.Hold(_handsGateBy, (long)_rearmSwap.GiveUpMs + 1000);
_rearmSwapOpen = true;
_rearmLastMoved = 0;
_host.Log($"[EquipDiag] weapons back after heals: 0x{(uint)_fightMainId:X8} '{WeaponName(_fightMainId)}'" +
(offWanted ? $" + off hand 0x{(uint)_fightOffId:X8} '{WeaponName(_fightOffId)}'" : "") + $" (mode {mode})");
}
_rearmVital = vital;
return RearmSwapAdvance(now);
}
/// <summary>
/// The weapons-back swap's next step. Called from RearmAfterVitalsStep and, so the steps don't wait
/// on the combat tick's gates (the pacer holds them while our own peace request settles, and a
/// corpse open slipped in between on Drakkon, 10-22 22:45), from the top of each heartbeat.
/// True while it is under way.
/// </summary>
private bool RearmSwapAdvance(DateTime now)
{
var hands = EquippedState.ReadFresh(_host, _worldFilter);
var step = _rearmSwap.Next(hands, CurrentCombatMode, now);
switch (step.Act)
{
case HandSwapSequence.Act.Wait:
return true;
case HandSwapSequence.Act.Stance:
{
int burst = SwapBurstEnabled?.Invoke() == true ? TryRearmBurst(hands, now) : 0;
if (burst != 0) return true;
if (_host.ChangeCombatModeFor(step.Slot, "Combat", "weapons back: peace first, then the hands"))
_rearmSwap.Sent(step, now);
return true;
}
case HandSwapSequence.Act.MoveToPack:
{
int pack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1);
if (pack == 0)
{
WorldObjectCache.WarnPackFull(_host, "can't put the wand away to put the weapons back");
bool fight = _handsSwapForFight;
FinishRearmSwap(now, done: false, why: "no pack with room");
if (fight) NoteFightSwapFailed(now); else _rearmedFor = _rearmVital;
return false;
}
_host.MoveItemInternal((uint)step.Id, (uint)pack, 0, 1); // amount>=1 (engine rejects 0)
_rearmSwap.Sent(step, now);
_rearmLastMoved = step.Id;
EquippedState.Invalidate();
_host.Log($"[EquipDiag] {HandsSwapLabel}: 0x{(uint)step.Id:X8} '{WeaponName(step.Id)}' -> pack 0x{(uint)pack:X8} {(now - _rearmSwap.StartedAt).TotalMilliseconds:0} ms in");
return true;
}
case HandSwapSequence.Act.Wield:
{
bool off = step.Slot == HandSwapSequence.ShieldSlot;
if (_host.HasWieldItem) _host.WieldItem((uint)step.Id, (uint)step.Slot);
else _host.UseFor((uint)step.Id, "Combat", $"wield: {HandsSwapLabel}");
_rearmSwap.Sent(step, now);
_rearmLastMoved = step.Id;
NoteRearmWield(step.Id, off, now);
_host.Log($"[EquipDiag] {HandsSwapLabel}: wielding 0x{(uint)step.Id:X8} '{WeaponName(step.Id)}' ({(off ? "off hand" : "main hand")}) {(now - _rearmSwap.StartedAt).TotalMilliseconds:0} ms in");
return true;
}
case HandSwapSequence.Act.Done:
if (_handsSwapForFight)
{
FightSwapDone(now);
return true;
}
_rearmStanceWanted = _rearmSwap.WentThroughPeace ? WeaponKind(_fightMainId) : 0;
if (_rearmStanceWanted == CombatMode.Magic) _rearmStanceWanted = 0;
_rearmStanceSince = now;
_rearmStanceForFight = false;
FinishRearmSwap(now, done: true);
RearmStanceStep(now); // at once: the server starts it when the peace animation ends
return true;
default:
{
bool fight = _handsSwapForFight;
FinishRearmSwap(now, done: false, why: step.Why);
if (fight) NoteFightSwapFailed(now);
else _rearmedFor = _rearmVital; // combat's own equip step takes it from here
return false;
}
}
}
private void NoteRearmWield(int id, bool off, DateTime now)
{
if (off) { _offhandSentId = id; _lastEquipTime = now; EquippedState.Invalidate(); }
else MarkWieldSent(id, InHandWeaponId());
}
/// <summary>
/// The fight's stance after a weapons-back swap through peace, once (past our own peace request
/// only: the server holds it until the peace animation ends). True when it went or isn't wanted.
/// </summary>
private bool RearmStanceStep(DateTime now)
{
if (_rearmStanceWanted == 0 || (_settings.PeaceModeWhenIdle && !_rearmStanceForFight) || CurrentCombatMode != CombatMode.NonCombat
|| (now - _rearmStanceSince).TotalMilliseconds >= RearmStanceWaitMs)
{
_rearmStanceWanted = 0;
return true;
}
var a = ActionPacer.Current(_host);
bool onlyOurPeace = a == null || (a.Kind == PacedKind.CombatMode && a.ModeTarget == CombatMode.NonCombat && a.Who == "Combat");
if (!_host.ChangeCombatModeFor(_rearmStanceWanted, "Combat", "weapons back: the fight's stance", force: onlyOurPeace))
return false;
_host.Log($"[EquipDiag] {(_rearmStanceForFight ? "weapons for the fight" : "weapons back after heals")}: {(_rearmStanceWanted == CombatMode.Missile ? "Missile" : "Melee")} mode");
if (_rearmStanceForFight)
{
// Combat's own stance request (the wielded branch) waits its retry delay behind this one.
lastStanceAttempt = RynthClock.Now;
NoteStanceFlipSent();
}
_rearmStanceWanted = 0;
return true;
}
/// <summary>
/// The weapons-back burst (test toggle, /ra swaptest burst on): peace, the wand out (raw
/// PutItemInContainer) and the main hand and the off hand wielded, queued in one tick so they go
/// out in one frame. Only with no combat-mode change for BurstQuietMs. 0 = not tried, 1 = held this
/// tick, 2 = sent. See BuffManager.TryWandBurst.
/// </summary>
private int TryRearmBurst(IReadOnlyDictionary<int, int> hands, DateTime now)
{
if (!_host.HasPutItemInContainer || !_host.HasWieldItem) return 0;
// BuffManager's read when the plugin wired it (every heartbeat); this manager's own tick doesn't run
// while buffing has the tick, so its read saw the switch to Magic only at the weapons-back tick
// and held every burst (Drakkon, 10-22 23:06-23:21).
DateTime changed = LastModeChangeAt?.Invoke() ?? _cmModeChangedAt;
if ((now - changed).TotalMilliseconds < RearmBurstQuietMs) return 0;
var moves = _rearmSwap.Blockers(hands);
if (moves.Count > 2) return 0;
int pack = 0;
if (moves.Count > 0)
{
pack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: moves.Count);
if (pack == 0) return 0;
}
if (!_host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", $"{HandsSwapLabel} burst: peace, the wand out and the weapons on at once")) return 1;
foreach (int id in moves) _host.PutItemInContainer(unchecked((uint)id), unchecked((uint)pack), 0);
var wants = _rearmWants;
foreach (var (id, slot) in wants)
{
_host.WieldItem(unchecked((uint)id), unchecked((uint)slot));
NoteRearmWield(id, slot == HandSwapSequence.ShieldSlot, now);
}
_rearmSwap.SentBurst(moves, now);
_rearmLastMoved = wants.Count > 0 ? wants[^1].Id : 0;
_host.Log($"[EquipDiag] {HandsSwapLabel} burst {(now - _rearmSwap.StartedAt).TotalMilliseconds:0} ms in: peace, " +
(moves.Count > 0 ? string.Join(", ", moves.ConvertAll(id => $"0x{(uint)id:X8} '{WeaponName(id)}'")) + $" -> pack 0x{(uint)pack:X8}, " : "") +
string.Join(", ", wants.ConvertAll(w => $"0x{(uint)w.Id:X8} '{WeaponName(w.Id)}' on")) + ", in one frame");
return 2;
}
/// <summary>The test toggle for the burst (/ra swaptest burst on), from BuffManager; set by the plugin.</summary>
public Func<bool>? SwapBurstEnabled { get; set; }
/// <summary>When the combat mode last changed (BuffManager's every-heartbeat read); set by the plugin.</summary>
public Func<DateTime>? LastModeChangeAt { get; set; }
private const double RearmBurstQuietMs = 1300;
private int _cmLastSeenMode = -1;
private DateTime _cmModeChangedAt = DateTime.MinValue;
private DateTime _rearmVital = DateTime.MinValue;
private List<(int Id, int Slot)> _rearmWants = new();
/// <summary>Each heartbeat: the weapons-back swap's steps, and when the combat mode last changed.</summary>
private void TickRearmSwap()
{
DateTime now = RynthClock.Now;
int m = CurrentCombatMode;
if (m != _cmLastSeenMode)
{
if (_cmLastSeenMode != -1) _cmModeChangedAt = now;
_cmLastSeenMode = m;
}
if (_rearmSwap.Active)
{
if (!_settings.IsMacroRunning)
{
bool fight = _handsSwapForFight;
FinishRearmSwap(now, done: false, why: "the macro stopped");
if (fight) NoteFightSwapFailed(now, counted: false);
}
// A target arriving doesn't end it: combat's equip points it at the fight's weapons, or ends
// it for a wand (FightJoinsHandsSwap). Ending it freed the gate only after the full 3 s.
else RearmSwapAdvance(now);
}
else if (_rearmStanceWanted != 0 && (_activeTargetId == 0 || _rearmStanceForFight) && _settings.IsMacroRunning)
RearmStanceStep(now);
}
// The weapons-back swap (HandSwapSequence) and what it owes once it ends.
private readonly HandSwapSequence _rearmSwap = new();
private bool _rearmSwapOpen;
private int _rearmLastMoved;
private int _rearmStanceWanted;
private DateTime _rearmStanceSince = DateTime.MinValue;
private const double RearmStanceWaitMs = 3000;
/// <summary>The slot a weapon goes back into: its own (two-handed, missile, held), else the main hand.</summary>
private int MainSlotFor(int id)
{
int valid = _worldFilter[id]?.Values(LongValueKey.Locations, 0) ?? 0;
if ((valid & HandSwapSequence.TwoHandedSlot) != 0) return HandSwapSequence.TwoHandedSlot;
if ((valid & HandSwapSequence.MissileSlot) != 0) return HandSwapSequence.MissileSlot;
if ((valid & HandSwapSequence.MeleeSlot) != 0) return HandSwapSequence.MeleeSlot;
if ((valid & HandSwapSequence.HeldSlot) != 0) return HandSwapSequence.HeldSlot;
return HandSwapSequence.MeleeSlot;
}
private void FinishRearmSwap(DateTime now, bool done, string why = "")
{
if (!_rearmSwapOpen) return;
_rearmSwapOpen = false;
double ms = (now - _rearmSwap.StartedAt).TotalMilliseconds;
string trail = _rearmSwap.Trail;
string what = HandsSwapLabel;
_rearmSwap.Cancel();
_handsSwapForFight = false;
_weaponSwapGate?.Release(_handsGateBy, _rearmLastMoved);
LastRearmSwapMs = ms;
_host.Log(done
? $"[EquipDiag] {what} in hand {ms:0} ms after the swap began ({trail})"
: $"[EquipDiag] {what} stopped after {ms:0} ms: {why} ({trail})");
}
/// <summary>The last weapons-back swap's length (ms).</summary>
internal double LastRearmSwapMs { get; private set; }
// Logged once per pair: what the slot reads say for two wielded weapons (the off-hand diagnosis).
private readonly HashSet<string> _twoInHandNoted = new();
@ -5346,6 +5635,14 @@ public partial class CombatManager : IDisposable
return EnsureUnarmedStance();
}
// Fast Weapon Swap: a hands swap is under way (weapons back after heals, or this one): it goes on
// with this fight's weapons, or ends for a wand. True = wait for it.
if (_settings.FastWeaponSwap && _rearmSwap.Active && FightJoinsHandsSwap(target, rule, targetWeaponId, weaponObj))
{
LastCombatSkipReason = "hand-swap";
return false;
}
// Another weapon in hand: one swap at a time, capped, no flip-flop. When the tracker
// says hold (the chosen one failed its tries, or it is the weapon just swapped away
// from), carry on with the one in hand.
@ -5426,6 +5723,16 @@ public partial class CombatManager : IDisposable
: CombatMode.Melee;
_chosenWeaponMode = desiredMode;
// Fast Weapon Swap: a caster in hand and a melee weapon or launcher wanted (a monster came while
// healing): peace, the wand out, the weapons on (one frame when the server is quiet), then the
// fight's stance. The client's own use took 1.4-1.7 s and paid a forced stance change.
if (_settings.FastWeaponSwap && allowWield && desiredMode != CombatMode.Magic && inHand != 0 && inHand != targetWeaponId
&& WeaponKind(inHand) == CombatMode.Magic && TryStartFightHandsSwap(target, rule, targetWeaponId, desiredMode))
{
LastCombatSkipReason = "hand-swap";
return false;
}
bool diagNow = (RynthClock.Now - _lastEquipDiagAt).TotalSeconds > 5;
// Use CurrentWieldedLocation (stype=10) — has an InqInt fallback that works even

View file

@ -53,4 +53,28 @@ internal static class EquippedState
/// <summary>Drop the cached read (a wield or move was just sent, or tests).</summary>
public static void Invalidate() { lock (Gate) _fresh = false; }
/// <summary>
/// What is wielded and where (item id -> EquipMask), read fresh: the tracker's list, or without
/// it (an engine before v87) the client's own fields, a slot read 0 guessed from the item's kind.
/// A copy, safe to hold across ticks (the hand swaps, HandSwapSequence).
/// </summary>
public static Dictionary<int, int> ReadFresh(RynthCoreHost host, WorldObjectCache? cache)
{
Invalidate();
if (TryGet(host, out var map)) return new Dictionary<int, int>(map);
var m = new Dictionary<int, int>();
if (cache == null) return m;
foreach (var wo in cache.GetDirectInventory(forceRefresh: true))
{
if (!WorldObjectCache.IsWieldedByPlayer(host, wo)) continue;
int slot = wo.Values(LongValueKey.CurrentWieldedLocation, 0);
if (slot == 0)
slot = WeaponList.IsWand(wo) ? HandSwapSequence.HeldSlot
: wo.ObjectClass == AcObjectClass.MissileWeapon ? HandSwapSequence.MissileSlot
: wo.ObjectClass == AcObjectClass.MeleeWeapon ? HandSwapSequence.MeleeSlot : 0;
if (slot != 0) m[wo.Id] = slot;
}
return m;
}
}

View file

@ -0,0 +1,314 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// One weapon swap as a short list of server steps, each sent the moment the server has answered
/// the last (2026-10-22). Pure: the caller reads the hands (EquippedState, id -> EquipMask), the
/// combat mode and the clock, does what <see cref="Next"/> says and reports it with <see cref="Sent"/>.
///
/// Why (Drakkon, DreamWeave, 2026-10-22 21:25): Acid + Frost Hand Wraps -> Sceptre took 7.2 s to
/// the first cast and about 3 s with no weapon in hand. The off hand went into the pack (answered in
/// 1.24 s), then 1.8 s of nothing, the main hand (answered in 2 ms), 2.9 s of nothing, the wand. The
/// waits were the swap gate's flat 3 s after every pack move. The client's own use of the wand was
/// no better while dual wielding: it takes the main hand first, one server answer per step (3.7 s).
///
/// What ACE does (Player_Inventory.cs, Player_Combat.cs, Creature_Combat.cs; the stance lengths from
/// the human motion table, 0x09000001):
/// * Every stance change goes through peace: melee -> Magic is melee -> peace (0.55 s) plus
/// peace -> Magic (0.52 s). A change to or from peace is one leg.
/// * Putting a wielded weapon into a pack in a combat mode first plays a forced change to bare
/// hands (1.15 s) and moves the item when it ends; after the move the server picks a stance for
/// what is left in hand, another change (and two weapons bounce between stances). In peace the
/// move is answered at once, with no stance change.
/// * A Held-slot caster needs both hands empty (CheckWeaponCollision); a wield runs at once.
/// * A cast that arrives while a stance change is still queued is cancelled by it; on a PK
/// character (DreamWeave casts that way) a cast can be left hanging behind an overlapping stance
/// animation (the 2 min 45 s hold on 10-06 13:58).
/// So, from a combat mode: peace first (one stance leg), both hands into the pack (each answered in a
/// round trip), the wand, then Magic (one leg). Magic is up about 0.6 s in instead of 2.4 s (the best
/// order in melee mode) or 6 s (before), and no stance change is ever queued behind another. Peace
/// drops weapon defense, for about 0.6 s; the melee route keeps it up to the last weapon but gets
/// to Magic 1.2-3.6 s later, and the old route went without a weapon in hand for about 3 s.
///
/// Bounded: a step unanswered in <see cref="StepResolveMs"/> is sent again, at most
/// <see cref="MaxSendsPerStep"/> times; the whole swap gives up after <see cref="GiveUpMs"/>.
/// </summary>
internal sealed class HandSwapSequence
{
public const int MeleeSlot = 0x00100000, ShieldSlot = 0x00200000, MissileSlot = 0x00400000,
AmmoSlot = 0x00800000, HeldSlot = 0x01000000, TwoHandedSlot = 0x02000000;
/// <summary>The slots that hold a hand (ammo is not one: arrows stay on).</summary>
public const int HandSlots = MeleeSlot | ShieldSlot | MissileSlot | HeldSlot | TwoHandedSlot;
/// <summary>AC combat modes (CombatMode).</summary>
public const int NonCombat = 1, Melee = 2, Missile = 4, Magic = 8;
public enum Act
{
/// <summary>A step is on its way to the server: nothing to send.</summary>
Wait,
/// <summary>Ask for combat mode <see cref="Step.Slot"/> (peace before the hands are cleared).</summary>
Stance,
/// <summary>Put <see cref="Step.Id"/> into a pack.</summary>
MoveToPack,
/// <summary>Wield <see cref="Step.Id"/> into <see cref="Step.Slot"/>.</summary>
Wield,
/// <summary>Everything wanted is in hand (or the sequence isn't running).</summary>
Done,
/// <summary>It can't finish now (<see cref="Step.Why"/>); the sequence has stopped.</summary>
Failed,
}
public readonly record struct Step(Act Act, int Id = 0, int Slot = 0, string Why = "");
/// <summary>A step's answer: the engine may hold an item action while the character animates (up to
/// 2.5 s, AcMainThreadQueue), then the server's answer (a forced stance change, about 1.2 s, if it
/// isn't in peace) and the round trip.</summary>
public double StepResolveMs { get; set; } = 4000;
/// <summary>The peace step: the mode reads peace within this, or the swap goes on without it.</summary>
public double PeaceResolveMs { get; set; } = 1500;
public int MaxSendsPerStep { get; set; } = 2;
public double GiveUpMs { get; set; } = 12_000;
private readonly List<(int Id, int Slot)> _wants = new();
private readonly HashSet<int> _keep = new();
private readonly Dictionary<int, int> _sends = new();
private readonly StringBuilder _trail = new();
private DateTime _startedAt, _flightAt;
private Act _flightAct = Act.Wait; // Wait = nothing in flight
private int _flightId, _flightSlot;
private bool _peaceWanted, _peaceDone;
// The burst (SentBurst): peace, every move and the wield sent in one frame.
private bool _burst;
private DateTime _burstAt;
private readonly HashSet<int> _burstPending = new();
/// <summary>A burst's steps all land within this, or the rest goes one step at a time.</summary>
public double BurstResolveMs { get; set; } = 2500;
public bool Active { get; private set; }
public string Label { get; private set; } = "";
public DateTime StartedAt => _startedAt;
/// <summary>The item of the step on its way (0 = none, or a stance step).</summary>
public int InFlightId => _flightAct == Act.Wait ? 0 : _flightId;
/// <summary>A step or a burst is on its way to the server (a new Start now could send it twice).</summary>
public bool InFlight => _burst || _flightAct != Act.Wait;
/// <summary>What the swap ends with, in order.</summary>
public IReadOnlyList<(int Id, int Slot)> Wants => _wants;
/// <summary>The item whose step went unanswered when the swap failed (0 = it failed some other way).</summary>
public int FailedId { get; private set; }
/// <summary>The steps so far with the server's answer times, for the log.</summary>
public string Trail => _trail.ToString();
/// <summary>The swap went through peace (the caller then asks for the stance its wants need).</summary>
public bool WentThroughPeace { get; private set; }
/// <summary>
/// Begins a swap that ends with each of <paramref name="wants"/> wielded in its slot, in order.
/// <paramref name="peaceFirst"/>: from a combat mode, ask for peace before anything leaves a hand.
/// Items in <paramref name="keep"/> are never taken off: one blocking a want fails the swap.
/// </summary>
public void Start(string label, DateTime now, IReadOnlyList<(int Id, int Slot)> wants, bool peaceFirst = false, IEnumerable<int>? keep = null)
{
_wants.Clear();
_wants.AddRange(wants);
_keep.Clear();
if (keep != null) foreach (int k in keep) if (k != 0) _keep.Add(k);
_sends.Clear();
_trail.Clear();
_startedAt = now;
_flightAct = Act.Wait;
_flightId = _flightSlot = 0;
_peaceWanted = peaceFirst;
_peaceDone = false;
_burst = false;
_burstPending.Clear();
WentThroughPeace = false;
FailedId = 0;
Label = label;
Active = true;
}
public void Cancel()
{
Active = false;
_flightAct = Act.Wait;
_flightId = _flightSlot = 0;
}
/// <summary>What to do now, given what the server says is wielded (item id -> EquipMask) and the combat mode.</summary>
public Step Next(IReadOnlyDictionary<int, int> wielded, int combatMode, DateTime now)
{
if (!Active) return new Step(Act.Done);
if (_burst)
{
double bms = (now - _burstAt).TotalMilliseconds;
if (combatMode == NonCombat) WentThroughPeace = true;
foreach (int id in new List<int>(_burstPending))
{
int slot = WantedSlot(id);
bool landed = slot != 0 ? wielded.TryGetValue(id, out int at) && (at & slot) != 0 : !wielded.ContainsKey(id);
if (!landed) continue;
Note($"{(slot != 0 ? "on" : "off")} 0x{(uint)id:X8} {bms / 1000:0.00} s");
_burstPending.Remove(id);
}
if (_burstPending.Count > 0 && bms < BurstResolveMs) return new Step(Act.Wait);
if (_burstPending.Count > 0) Note($"burst incomplete after {bms / 1000:0.0} s: the rest one step at a time");
_burst = false;
}
if (_flightAct != Act.Wait)
{
double ms = (now - _flightAt).TotalMilliseconds;
bool landed = _flightAct switch
{
Act.Stance => combatMode == _flightSlot,
Act.MoveToPack => !wielded.ContainsKey(_flightId),
_ => wielded.TryGetValue(_flightId, out int at) && (at & _flightSlot) != 0,
};
if (landed)
{
Note(_flightAct switch
{
Act.Stance => $"peace {ms / 1000:0.00} s",
Act.MoveToPack => $"off 0x{(uint)_flightId:X8} {ms / 1000:0.00} s",
_ => $"on 0x{(uint)_flightId:X8} {ms / 1000:0.00} s",
});
if (_flightAct == Act.Stance) { _peaceDone = true; WentThroughPeace = true; }
_flightAct = Act.Wait;
}
else if (_flightAct == Act.Stance)
{
if (ms < PeaceResolveMs) return new Step(Act.Wait, 0, _flightSlot);
// Not read in time: go on without it (the moves still work in a combat mode, slower).
Note($"peace not read in {ms / 1000:0.0} s");
_peaceDone = true;
_flightAct = Act.Wait;
}
else if (ms < StepResolveMs)
return new Step(Act.Wait, _flightId, _flightSlot);
else
{
Note($"0x{(uint)_flightId:X8} no answer in {ms / 1000:0.0} s");
int id = _flightId;
_flightAct = Act.Wait;
if (_sends.TryGetValue(id, out int n) && n >= MaxSendsPerStep)
{
FailedId = id;
return Fail($"0x{(uint)id:X8} wasn't answered after {n} sends");
}
}
}
if ((now - _startedAt).TotalMilliseconds > GiveUpMs)
return Fail($"not done in {GiveUpMs / 1000:0} s");
// Anything in a hand that isn't wanted there comes off first: the off hand before the rest.
int blocker = 0;
foreach (var kv in wielded)
{
if ((kv.Value & HandSlots) == 0 || WantedThere(kv.Key, kv.Value)) continue;
if (blocker == 0 || (kv.Value & ShieldSlot) != 0) blocker = kv.Key;
if ((kv.Value & ShieldSlot) != 0) break;
}
if (blocker != 0 && _keep.Contains(blocker))
return Fail($"0x{(uint)blocker:X8} is in the way and may not be taken off");
// Peace before the first item leaves a hand: the moves are then answered at once, and the
// stance changes the server makes around a combat-mode unwield never happen.
if (blocker != 0 && _peaceWanted && !_peaceDone)
{
if (combatMode == NonCombat) _peaceDone = true;
else return new Step(Act.Stance, 0, NonCombat);
}
if (blocker != 0) return new Step(Act.MoveToPack, blocker, 0);
foreach (var (id, slot) in _wants)
{
if (wielded.TryGetValue(id, out int at) && (at & slot) != 0) continue;
return new Step(Act.Wield, id, slot);
}
Active = false;
return new Step(Act.Done);
}
/// <summary>The caller sent <paramref name="step"/> (a stance request, a pack move or a wield).</summary>
public void Sent(Step step, DateTime now)
{
if (step.Act is not (Act.Stance or Act.MoveToPack or Act.Wield)) return;
_flightAct = step.Act;
_flightId = step.Id;
_flightSlot = step.Slot;
_flightAt = now;
if (step.Act != Act.Stance)
_sends[step.Id] = (_sends.TryGetValue(step.Id, out int n) ? n : 0) + 1;
}
/// <summary>
/// What would come off first, in order (the off hand before the rest), for a burst: every item in a
/// hand that isn't wanted where it is. Empty when one may not be taken off.
/// </summary>
public List<int> Blockers(IReadOnlyDictionary<int, int> wielded)
{
var off = new List<int>();
var rest = new List<int>();
foreach (var kv in wielded)
{
if ((kv.Value & HandSlots) == 0 || WantedThere(kv.Key, kv.Value)) continue;
if (_keep.Contains(kv.Key)) return new List<int>();
((kv.Value & ShieldSlot) != 0 ? off : rest).Add(kv.Key);
}
off.AddRange(rest);
return off;
}
/// <summary>
/// The caller sent peace, every move in <paramref name="moved"/> and the wield of each want in one
/// frame (BuffManager's burst). Next waits for all of them to land (<see cref="BurstResolveMs"/>),
/// then goes on one step at a time with whatever didn't.
/// </summary>
public void SentBurst(IEnumerable<int> moved, DateTime now)
{
_burst = true;
_burstAt = now;
_peaceDone = true;
_burstPending.Clear();
foreach (int id in moved) _burstPending.Add(id);
foreach (var (id, _) in _wants) _burstPending.Add(id);
foreach (int id in _burstPending) _sends[id] = (_sends.TryGetValue(id, out int n) ? n : 0) + 1;
_flightAct = Act.Wait;
Note("burst");
}
private int WantedSlot(int id)
{
foreach (var w in _wants) if (w.Id == id) return w.Slot;
return 0;
}
/// <summary>The caller couldn't send the step (no pack with room, no wield call): stop here.</summary>
public Step Abandon(string why) => Fail(why);
private bool WantedThere(int id, int slot)
{
foreach (var w in _wants)
if (w.Id == id && (slot & w.Slot) != 0) return true;
return false;
}
private Step Fail(string why)
{
Note("failed: " + why);
Cancel();
return new Step(Act.Failed, Why: why);
}
private void Note(string s)
{
if (_trail.Length > 0) _trail.Append(", ");
_trail.Append(s);
}
}

View file

@ -66,9 +66,12 @@ internal static class DamageStyles
/// other way round, except for a slayer (owner's rule, 2026-10-05: a monster is always
/// attacked with a slayer of it before an element choice, even when another weapon's element
/// meets a lower resistance; only a weapon the player set for that monster trumps it):
/// 1. The weapon set on THIS monster's own Damage tab row is used as set, slayer or not; it
/// must be in the Items list. Its element is the rule's, else its own, else the weakest
/// the character can cast.
/// 1. The weapon set on THIS monster's own Damage tab row, else on the Monsters rule that
/// matched it (not the Default row), is used as set, slayer or not (2026-10-22: the
/// rule's weapon used to be ignored, report R-20261022-193411-fb72). A Damage tab pick
/// must be in the Items list; a Monsters tab weapon need not be (CombatManager adds it to
/// the candidates). Its element is the rule's, else its own, else the weakest the
/// character can cast.
/// 2. A slayer: a listed weapon of the character's main kind whose SlayerCreatureType is
/// the monster's CreatureType and whose SlayerDamageBonus is above 1 or not known (ACE
/// multiplies the whole hit by it, so it beats any element choice, and never sends the
@ -78,7 +81,8 @@ internal static class DamageStyles
/// is the wand's own, else a melee/missile weapon's own, else the rule's, else the
/// weakest the character can cast. Creature type unknown: no slayer step.
/// A slayer of another kind (a melee slayer for a mage) is not a candidate.
/// 3. The Damage tab DEFAULT row's weapon (listed only): above the element steps, below a slayer.
/// 3. The Damage tab DEFAULT row's weapon (listed only), else the Monsters tab Default row's:
/// above the element steps, below a slayer.
/// 4. A Monsters rule damage type (not Auto) is the element; wield the listed weapon of that
/// element (a matching rending first, then the one in hand, then list order).
/// Whatever is chosen, a wand casts its own element when it has one (owner's rule,
@ -100,8 +104,11 @@ internal static class DamageStyles
/// Void Magic) replaces that: the pool is the listed weapons of that style, for a character
/// who uses two kinds and wants to choose. With none listed (or none the character can use,
/// e.g. Void without Void Magic) it falls back to Auto, the main kind, rather than not fighting.
/// The monster's own Damage tab weapon (step 1) still wins; the DEFAULT row's weapon only when
/// it is of the preferred style; War Magic never casts Nether and Void Magic nothing else.
/// The monster's own Damage tab or Monsters rule weapon (step 1) still wins; the DEFAULT row's
/// weapon only when it is of the preferred style; War Magic never casts Nether and Void Magic nothing else.
/// Which fixed weapon is passed in (and whether it is a step-1 pick or a DEFAULT one) is
/// CombatManager.ComputePlan's: this monster's Damage tab pick, its Monsters rule's weapon, the
/// Damage tab DEFAULT row's, the Monsters Default row's, the first one usable and listed.
/// </summary>
internal static class WeaponPlanner
{
@ -154,10 +161,11 @@ internal static class WeaponPlanner
bool ruleSet = rule.Length > 0;
WeaponCandidate? fixedPick = fixedWeaponId != 0 ? Find(listed, fixedWeaponId) : null;
// 1. The weapon the player set on this monster's own Damage tab row (listed only): honoured,
// slayer or not (owner, 2026-10-05: "the only time a slayer property gets trumped is if
// the player manually inputs a weapon without it"). The DEFAULT row's weapon is not a
// pick for this monster: a slayer of it beats that one (step 3).
// 1. The weapon the player set on this monster's own Damage tab row, or on the Monsters
// rule that matched it (a candidate; see the class note): honoured, slayer or not (owner, 2026-10-05: "the
// only time a slayer property gets trumped is if the player manually inputs a weapon
// without it"). A DEFAULT row's weapon (Damage tab or Monsters tab) is not a pick for
// this monster: a slayer of it beats that one (step 3).
if (fixedPick != null && !fixedIsDefault)
return FixedPlan(fixedPick, Slays(fixedPick, creatureType)
? fixedSource + ", " + SlayerSource(creatureType, fixedPick.SlayerBonus) : fixedSource, rule, weak, canCast);
@ -202,7 +210,8 @@ internal static class WeaponPlanner
}
}
// 3. The Damage tab DEFAULT row's weapon (listed only): no slayer of this monster is listed.
// 3. The Damage tab DEFAULT row's weapon, else the Monsters Default row's:
// no slayer of this monster is listed.
if (fixedPick != null && (!styled || pool.Contains(fixedPick)))
return FixedPlan(fixedPick, fixedSource, rule, weak, canCast);

View file

@ -26,6 +26,8 @@ public sealed class WeaponSwapGate
private string _lastSwapBy = "";
private int _movingId;
private long _claims;
private string _heldBy = "";
private long _heldUntilMs;
/// <summary>Swaps claimed so far: a caller can tell whether another swap went out after its own.</summary>
public long Claims { get { lock (_lock) { return _claims; } } }
@ -62,6 +64,7 @@ public sealed class WeaponSwapGate
long now = NowMs();
lock (_lock)
{
if (_heldBy.Length > 0 && now < _heldUntilMs) return false; // a multi-step swap is running (Hold)
long since = now - _lastSwapTickMs;
if (since < MinIntervalMs && !LastSwapDone(since))
return false;
@ -73,6 +76,38 @@ public sealed class WeaponSwapGate
}
}
/// <summary>
/// A multi-step swap (HandSwapSequence, 2026-10-22) that has claimed the gate keeps it for its
/// steps: no other swap goes until <see cref="Release"/>, or <paramref name="maxMs"/> as a backstop.
/// Its own steps are paced on the server's answers, not by this gate.
/// </summary>
public void Hold(string by, long maxMs)
{
lock (_lock)
{
_heldBy = by ?? "?";
_heldUntilMs = NowMs() + maxMs;
}
}
/// <summary>
/// The held swap is over. <paramref name="lastMovedId"/> (its last pack move or slot wield, 0 =
/// none) holds the next swap the full <see cref="MinIntervalMs"/> from now, as a noted move does.
/// </summary>
public void Release(string by, int lastMovedId)
{
lock (_lock)
{
if (_heldBy != (by ?? "?")) return;
_heldBy = "";
_lastSwapTickMs = NowMs();
_movingId = lastMovedId;
}
}
/// <summary>Who holds the gate for a multi-step swap ("" = no one; diagnostics).</summary>
public string HeldBy { get { lock (_lock) { return _heldBy.Length > 0 && NowMs() < _heldUntilMs ? _heldBy : ""; } } }
/// <summary>
/// The claimed swap moved <paramref name="itemId"/> into or out of a hand without a use (a
/// pack move or a slot wield): the next swap waits the full MinIntervalMs, as before.

View file

@ -10,7 +10,8 @@ namespace RynthCore.Plugin.RynthAi;
/// server, so a refused wield never got an answer and was retried: Drakkon's Tetsubo (Two Handed
/// Combat, untrained) took the off-hand weapon off for every fight (2026-10-18), his Electric Baton
/// and Acid Staff (War Magic) held up buffing. Read from the item's appraisal; unknown = not known
/// (the caller decides), never "met".
/// (the caller decides), never "met". A Skill requirement is checked against the buffed skill (vitae
/// lowers it, as on the server); a RawSkill one against the base skill (vitae doesn't).
/// </summary>
internal static class WieldRequirements
{
@ -30,7 +31,7 @@ internal static class WieldRequirements
host.TryGetObjectIntProperty(itemId, pDiff, out int diff);
switch (req)
{
case 1: case 2: case 8: // Skill (buffed), RawSkill (base: only the buffed one is read), Training
case 1: case 2: case 8: // Skill (buffed), RawSkill (base), Training
{
if (skills == null || !host.TryGetObjectIntProperty(itemId, pSkill, out int stype)) continue;
AcSkillType? skill = SkillOf((uint)stype);
@ -38,8 +39,23 @@ internal static class WieldRequirements
var s = skills[skill.Value];
string name = Name(skill.Value);
if (s.Training < 2) return $"needs {name}, untrained";
if (req == 8) continue;
if (diff > 0 && s.Buffed > 0 && s.Buffed < diff) return $"needs {name} {diff}, you have {s.Buffed}";
if (req == 8 || diff <= 0) continue;
if (req == 2)
{
// RawSkill: the base skill, without buffs and without vitae (ACE CreatureSkill.Base;
// the client's own raw read, which is what the client checks before it sends the
// wield). The buffed read carries the vitae penalty: at 40% vitae a Shashqa
// (base Two Handed Combat 420) read as 371 and was left out of the weapon choice,
// though it wields fine (2026-10-23). Base not readable: not known.
uint pid = host.GetPlayerId();
if (pid != 0 && host.HasGetObjectSkillBuffed
&& host.TryGetObjectSkillLevel(pid, (uint)stype, raw: 1, out int baseLevel) && baseLevel > 0
&& baseLevel < diff)
return $"needs base {name} {diff}, you have {baseLevel}";
continue;
}
// Skill: the buffed skill, vitae included (ACE CreatureSkill.Current), as read.
if (s.Buffed > 0 && s.Buffed < diff) return $"needs {name} {diff}, you have {s.Buffed}";
continue;
}
case 7: // Level

View file

@ -0,0 +1,176 @@
// ============================================================================
// RynthAi - Dashboard/DashboardPrefs.cs
// The dashboard window's own choices: minimized, the target bar, the vitals, the
// open drawers (one per side) and the drawers moved to the side they don't start
// on. One file for the PC, like the engine's dashboard state was (every client
// shows the dashboard the same way): %AppData%\RynthCore\rynthai_dashboard.txt,
// "key=value" lines. The first time, it starts from the engine dashboard's file
// (rynthai_avalonia.cache: line 1 minimized, 3 the target bar, 4 the vitals, 12
// the moved drawers), so the switch to RynthAi's own window keeps them.
// The engine's file also says which look is on (line 14, classic|modern): the
// Classic look is still RynthCore's face, so RynthAi's window steps aside for it
// (ClassicLook).
//
// The window sets the fields on the render thread; the plugin tick saves them
// (SaveIfChanged), never the render thread.
// ============================================================================
using System;
using System.IO;
using System.Linq;
namespace RynthCore.Plugin.RynthAi.Dashboard;
internal sealed class DashboardPrefs
{
// The drawers, in the order their tabs stack (the engine dashboard's keys, so its moves carry over).
public const string RangesDrawer = "ranges", FilesDrawer = "files", PatrolDrawer = "patrol",
RemoteDrawer = "remote", PinnedDrawer = "quick";
/// <summary>Every drawer key; My settings (quick) starts on the right, the rest on the left.</summary>
public static readonly string[] Drawers = { RangesDrawer, FilesDrawer, PatrolDrawer, RemoteDrawer, PinnedDrawer };
public static bool StartsRight(string key) => key == PinnedDrawer;
private static string Folder => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
private static string FilePath => Path.Combine(Folder, "rynthai_dashboard.txt");
/// <summary>The engine dashboard's state (RynthCore UI/RynthAiDashboardState.cs).</summary>
private static string EngineStatePath => Path.Combine(Folder, "rynthai_avalonia.cache");
private volatile bool _minimized, _showTarget = true, _showVitals = true;
private volatile string _left = string.Empty, _right = string.Empty;
private volatile string[] _moved = Array.Empty<string>();
private volatile bool _dirty;
public bool Minimized => _minimized;
public bool ShowTarget => _showTarget;
public bool ShowVitals => _showVitals;
public void SetMinimized(bool v) { _minimized = v; _dirty = true; }
public void SetShowTarget(bool v) { _showTarget = v; _dirty = true; }
public void SetShowVitals(bool v) { _showVitals = v; _dirty = true; }
/// <summary>The drawer is on the right edge now (its start side, or the other one when moved).</summary>
public bool OnRight(string key) => StartsRight(key) != (Array.IndexOf(_moved, key) >= 0);
/// <summary>The drawer open on that side, or "".</summary>
public string OpenOn(bool right) => right ? _right : _left;
public bool IsOpen(string key) => (OnRight(key) ? _right : _left) == key;
/// <summary>Opens <paramref name="key"/>'s drawer (closing the one open on its side), or closes it when it is open.</summary>
public void ToggleDrawer(string key)
{
if (OnRight(key)) _right = _right == key ? string.Empty : key;
else _left = _left == key ? string.Empty : key;
_dirty = true;
}
public void CloseDrawer(string key)
{
if (_left == key) _left = string.Empty;
if (_right == key) _right = string.Empty;
_dirty = true;
}
/// <summary>Moves the drawer to the other edge; open, it opens there (closing the one open there).</summary>
public void MoveDrawer(string key)
{
bool wasOpen = IsOpen(key);
CloseDrawer(key);
_moved = Array.IndexOf(_moved, key) >= 0 ? _moved.Where(k => k != key).ToArray() : _moved.Append(key).ToArray();
if (wasOpen) ToggleDrawer(key);
_dirty = true;
}
private static bool IsDrawer(string key) => Array.IndexOf(Drawers, key) >= 0;
/// <summary>Reads the file, or starts from the engine dashboard's state. Plugin init.</summary>
public static DashboardPrefs Load()
{
var p = new DashboardPrefs();
try
{
string[] engine = File.Exists(EngineStatePath) ? File.ReadAllLines(EngineStatePath) : Array.Empty<string>();
bool movedRead = false;
if (File.Exists(FilePath))
{
string legacyDrawer = string.Empty;
foreach (string raw in File.ReadAllLines(FilePath))
{
int eq = raw.IndexOf('=');
if (eq <= 0) continue;
string key = raw[..eq].Trim(), value = raw[(eq + 1)..].Trim();
bool on = value == "1";
switch (key)
{
case "minimized": p._minimized = on; break;
case "target": p._showTarget = on; break;
case "vitals": p._showVitals = on; break;
case "left": p._left = IsDrawer(value) ? value : string.Empty; break;
case "right": p._right = IsDrawer(value) ? value : string.Empty; break;
case "drawer": legacyDrawer = value; break; // before 2026-10-21's two sides
case "moved":
movedRead = true;
p._moved = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Where(IsDrawer).ToArray();
break;
}
}
if (!movedRead) p._moved = EngineMoved(engine);
if (legacyDrawer.Length > 0 && IsDrawer(legacyDrawer) && p.OpenOn(p.OnRight(legacyDrawer)).Length == 0)
p.ToggleDrawer(legacyDrawer);
p._dirty = !movedRead || legacyDrawer.Length > 0;
return p;
}
// First time: the engine dashboard's choices, so nothing changes at the switch.
if (engine.Length > 0) p._minimized = engine[0].Trim() == "minimized";
if (engine.Length > 2) p._showTarget = engine[2].Trim() != "notarget";
if (engine.Length > 3) p._showVitals = engine[3].Trim() != "novitals";
p._moved = EngineMoved(engine);
p._dirty = true;
}
catch { /* unreadable: the defaults */ }
return p;
}
/// <summary>The engine dashboard's moved drawers (line 12, "moved:files,patrol").</summary>
private static string[] EngineMoved(string[] engine)
{
if (engine.Length < 12) return Array.Empty<string>();
string line = engine[11].Trim();
if (!line.StartsWith("moved:", StringComparison.OrdinalIgnoreCase)) return Array.Empty<string>();
return line[6..].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Where(IsDrawer).ToArray();
}
/// <summary>Writes the file when something changed. Plugin tick.</summary>
public void SaveIfChanged()
{
if (!_dirty) return;
_dirty = false;
try
{
Directory.CreateDirectory(Folder);
File.WriteAllText(FilePath,
"minimized=" + (_minimized ? 1 : 0) + "\n" +
"target=" + (_showTarget ? 1 : 0) + "\n" +
"vitals=" + (_showVitals ? 1 : 0) + "\n" +
"left=" + _left + "\n" +
"right=" + _right + "\n" +
"moved=" + string.Join(",", _moved) + "\n");
}
catch { /* best effort: the next change tries again */ }
}
/// <summary>
/// True while the engine dashboard's look is Classic (its file's line 14), the retail-style window
/// RynthCore still draws: RynthAi's window then steps aside. Plugin tick (a small file read).
/// </summary>
public static bool ClassicLook()
{
try
{
if (!File.Exists(EngineStatePath)) return false;
string[] lines = File.ReadAllLines(EngineStatePath);
return lines.Length > 13 && lines[13].Trim().Equals("classic", StringComparison.OrdinalIgnoreCase);
}
catch { return false; }
}
}

File diff suppressed because it is too large Load diff

View file

@ -26,6 +26,7 @@ internal enum TickStep
LocalFeatures,
GiveQueue,
Jumper,
Dashboard,
// In world.
VTankYield,
VitalsRead,
@ -112,6 +113,7 @@ internal sealed class TickGuard
Add(TickStep.LocalFeatures, "HUDs and panels", LogCat.Huds);
Add(TickStep.GiveQueue, "give queue", LogCat.Inventory);
Add(TickStep.Jumper, "jumper", LogCat.Jumper, essential: true);
Add(TickStep.Dashboard, "dashboard window", LogCat.UI);
Add(TickStep.VTankYield, "VTank yield", LogCat.General, essential: true);
Add(TickStep.VitalsRead, "vitals read", LogCat.Buffing, essential: true);

View file

@ -719,7 +719,10 @@ internal sealed class MiniRemoteHud
// Ctrl+wheel over the grid: bigger / smaller boxes (the window / drawer refits to them).
var io = ImGui.GetIO();
if (io.KeyCtrl && io.MouseWheel != 0f && ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem))
{
ResizeSlots(s, io.MouseWheel > 0f ? SlotSizeStep : -SlotSizeStep);
io.MouseWheel = 0f; // the boxes took it: not the panel's size too
}
}
/// <summary>

View file

@ -68,14 +68,45 @@ internal static class SectionsManifest
return views;
}
/// <summary>The manifest JSON for <paramref name="views"/> (UTF-8 text, schema version 1).</summary>
public static string Build(IReadOnlyList<View> views, IReadOnlyList<Section> sections)
/// <summary>
/// RynthAi's dashboard window (RynthAiPlugin.Dashboard.cs, 2026-10-21): the engine's "RynthAi" panel's
/// place ("takeOver": its saved spot, bar button, hotkeys and /rc commands), drawn whole by RynthAi
/// ("chrome": "none") and as tall as it draws ("fitHeight"), plugin API v90. The Robot icon is the
/// engine bar's for RynthAi.
/// </summary>
public const string DashboardTitle = "RynthAi", DashboardSurface = "window:dashboard";
/// <summary>
/// The manifest JSON for <paramref name="views"/> (UTF-8 text, schema version 1), with the dashboard
/// window when <paramref name="dashboard"/>.
/// </summary>
public static string Build(IReadOnlyList<View> views, IReadOnlyList<Section> sections, bool dashboard = false)
{
using var stream = new MemoryStream(4096);
using (var w = new Utf8JsonWriter(stream))
{
w.WriteStartObject();
w.WriteNumber("version", 1);
if (dashboard)
{
w.WriteStartArray("windows");
w.WriteStartObject();
w.WriteString("id", "dashboard");
w.WriteString("title", DashboardTitle);
w.WriteString("surface", DashboardSurface);
w.WriteString("icon", "");
w.WriteNumber("width", 296);
w.WriteNumber("height", 240);
w.WriteNumber("minWidth", 280);
w.WriteNumber("minHeight", 54);
w.WriteBoolean("bar", true);
w.WriteBoolean("edgeToEdge", true);
w.WriteBoolean("takeOver", true);
w.WriteString("chrome", "none");
w.WriteBoolean("fitHeight", true);
w.WriteEndObject();
w.WriteEndArray();
}
w.WriteStartArray("sections");
foreach (Section s in sections)
{

View file

@ -340,6 +340,9 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Checkbox("Weapons Back After Heals", ref _settings.RearmAfterVitals);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("After a heal, restam or remana spell with nothing to fight, put the last fight's weapons (main hand and off hand) back on.");
ImGui.Checkbox("Fast Weapon Swap", ref _settings.FastWeaponSwap);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Switch weapons through peace mode, every step the moment the server allows:\nthe wand is in hand about 0.2 s after the switch begins (4-7 s without),\nand the weapons go back as fast, also when a monster comes while the wand\nis out (swinging again in about 1 s). On by default. Peace mode costs your weapon's defense\nfor about half a second; the slow way goes without a weapon for about 3 s.");
ImGui.Checkbox("Start Macro On Login", ref _settings.StartMacroOnLogin);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Automatically starts the macro when RynthAi loads.");

View file

@ -0,0 +1,84 @@
// LegacyDashboardRenderer.Instrument.cs — what RynthAi's own dashboard window shows (Dashboard/
// InstrumentDashboard.cs, 2026-10-21): the fields the engine's dashboard read from the snapshot JSON,
// read directly, plus the vitals refresh that the engine's snapshot poll used to drive.
using System;
using System.IO;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// <summary>
/// One frame of the dashboard: the macro, the subsystems, the bot's activity, the target and the vitals.
/// The target is the selection, or the monster RynthAi is fighting (TargetIsFight: combat doesn't
/// select it). TargetHealth is 0..1, or -1 while the server hasn't said.
/// </summary>
internal readonly record struct DashboardReadout(
bool MacroRunning,
string MetaState,
string Activity,
bool Combat, bool Buffing, bool Navigation, bool Looting, bool Meta,
uint TargetId, string TargetLabel, float TargetHealth,
bool ShowTargetStaminaMana, uint TargetStamina, uint TargetMaxStamina, uint TargetMana, uint TargetMaxMana,
uint Health, uint MaxHealth, uint Stamina, uint MaxStamina, uint Mana, uint MaxMana,
bool Locked, float Opacity,
string LootPath,
bool TargetIsFight = false);
/// <summary>The loaded-files pickers: each list, and the entry in use.</summary>
internal sealed record DashboardFiles(
string[] Profiles, int ProfileIdx,
string[] Navs, int NavIdx,
string[] Loots, int LootIdx,
string[] Metas, int MetaIdx,
string[] Buffs, int BuffIdx,
string ProfileName, string NavName, string LootName, string MetaName, string BuffName);
internal sealed partial class LegacyDashboardRenderer
{
/// <summary>The dashboard's frame. Any thread: plain field reads (strings are replaced, never changed).</summary>
internal DashboardReadout ReadDashboard()
{
string activity = ActivityArbiter.DisplayLabel(_settings.BotAction, _settings.BuffingLabel);
if (string.IsNullOrWhiteSpace(activity) || activity == "Default") activity = "Idle";
string state = string.IsNullOrWhiteSpace(_settings.CurrentState) ? "Default" : _settings.CurrentState;
return new DashboardReadout(
_settings.IsMacroRunning, state, activity,
_settings.EnableCombat, _settings.EnableBuffing, _settings.EnableNavigation, _settings.EnableLooting, _settings.EnableMeta,
_currentTargetId, _targetLabel ?? "NO TARGET", _targetHealthPercent,
_settings.ShowTargetStaminaMana, _targetStamina, _targetMaxStamina, _targetMana, _targetMaxMana,
_playerHealth, _playerMaxHealth, _playerStamina, _playerMaxStamina, _playerMana, _playerMaxMana,
_isLocked, _bgOpacity,
!string.IsNullOrEmpty(_vendorProfilePath?.Invoke()) ? _vendorProfilePath!.Invoke() : _settings.CurrentLootPath ?? string.Empty);
}
/// <summary>The five pickers' lists (copied under the lists' lock) and the entry in use. Any thread.</summary>
internal DashboardFiles ReadDashboardFiles()
{
string[] profiles, navs, loots, metas, buffs;
lock (_profileListsLock)
{
profiles = _profiles.ToArray();
navs = _navFiles.ToArray();
loots = _lootFiles.ToArray();
metas = _metaFiles.ToArray();
buffs = _buffFiles.ToArray();
}
string profile = _settings.SelectedProfile ?? "Default";
return new DashboardFiles(
profiles, Math.Max(0, Array.IndexOf(profiles, profile)),
navs, _selectedNavIdx,
loots, _settings.LootProfileIdx,
metas, _settings.MetaProfileIdx,
buffs, _settings.BuffProfileIdx,
profile,
string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentNavPath),
string.IsNullOrEmpty(_settings.CurrentLootPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentLootPath),
string.IsNullOrEmpty(_settings.CurrentMetaPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentMetaPath),
string.IsNullOrEmpty(_settings.CurrentBuffProfilePath) ? BuiltInBuffProfileLabel : Path.GetFileNameWithoutExtension(_settings.CurrentBuffProfilePath));
}
/// <summary>
/// The player's vitals from the engine, for the dashboard. The engine's snapshot poll did this
/// (BuildSnapshotJson) while its dashboard was open; RynthAi's own window has no poll. Pump thread.
/// </summary>
internal void RefreshDashboardVitals() => RefreshPlayerVitals();
}

View file

@ -2025,6 +2025,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.EnableGroundLoot = tmp.EnableGroundLoot;
dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle;
dst.RearmAfterVitals = tmp.RearmAfterVitals;
dst.FastWeaponSwap = tmp.FastWeaponSwap;
dst.RebuffWhenIdle = tmp.RebuffWhenIdle;
dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining;
dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining;

View file

@ -308,6 +308,17 @@ public sealed class LegacyUiSettings
/// <summary>After a heal, restam or remana spell with no monster to fight, put the last fight's
/// weapons (main hand and off hand) back on instead of waiting for the next target.</summary>
public bool RearmAfterVitals;
/// <summary>
/// Weapon swaps (to the wand for a heal or a buff, and Weapons Back After Heals) through peace
/// mode (2026-10-22, HandSwapSequence): with the server quiet, peace, the moves out of the hands and
/// the wields go in one frame (the burst: the wand in hand 0.1-0.26 s after the swap begins on
/// Drakkon); else each step the moment the server answers the last (about 1 s). Before: 4-7 s.
/// Also combat's own equip when a monster comes with the wand in hand (2026-10-23).
/// On by default since 2026-10-23, saved under a new name: the opt-in build saved "FastWeaponSwap":
/// false into every profile it touched, and that no longer loads. Off: the swap as before (*.LegacySwap.cs).
/// </summary>
[JsonPropertyName("FastWeaponSwapOn")]
public bool FastWeaponSwap = true;
public bool RebuffWhenIdle;
/// <summary>
/// Re-cast a self buff when its remaining duration drops below this many seconds.

View file

@ -183,6 +183,7 @@ public sealed partial class RynthAiPlugin
["enablemeta"] = "EnableMeta",
["opendoors"] = "OpenDoors",
["idlepeacemode"] = "PeaceModeWhenIdle",
["fastweaponswap"] = "FastWeaponSwap",
["idlebufftopoff"] = "RebuffWhenIdle",
["summonpets"] = "SummonPets",
["combinesalvage"] = "EnableCombineSalvage",

View file

@ -3618,6 +3618,7 @@ internal sealed partial class ExpressionEngine
["SalvageWithoutPanel"] = (() => B(s.SalvageWithoutPanel), v => s.SalvageWithoutPanel = ToDouble(v) != 0),
["PeaceModeWhenIdle"] = (() => B(s.PeaceModeWhenIdle), v => s.PeaceModeWhenIdle = ToDouble(v) != 0),
["RearmAfterVitals"] = (() => B(s.RearmAfterVitals), v => s.RearmAfterVitals = ToDouble(v) != 0),
["FastWeaponSwap"] = (() => B(s.FastWeaponSwap), v => s.FastWeaponSwap = ToDouble(v) != 0),
["RebuffWhenIdle"] = (() => B(s.RebuffWhenIdle), v => s.RebuffWhenIdle = ToDouble(v) != 0),
["UsePotions"] = (() => B(s.UsePotions), v => s.UsePotions = ToDouble(v) != 0),
["UseBuffItems"] = (() => B(s.UseBuffItems), v => s.UseBuffItems = ToDouble(v) != 0),

View file

@ -140,7 +140,8 @@ public static unsafe class PluginExports
{
if (surface == null) return 0;
ReadOnlySpan<byte> name = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(surface);
if (name.EndsWith(":popout"u8)) name = name[..^":popout"u8.Length];
bool popped = name.EndsWith(":popout"u8);
if (popped) name = name[..^":popout"u8.Length];
var plugin = Runtime.Plugin;
if (plugin == null) return 0;
System.Numerics.Vector2 want;
@ -149,6 +150,12 @@ public static unsafe class PluginExports
{
return plugin.MarkEngineMiniRemote() ? 1 : 0;
}
else if (name.SequenceEqual("window:dashboard"u8))
{
// RynthAi's own dashboard window (RynthAiPlugin.Dashboard.cs): 1 drawn, 0 not ready, -2 failed.
int drawn = plugin.RenderDashboard(popped, out want);
if (drawn != 1) return drawn;
}
else if (name.StartsWith("section:"u8))
{
// Section names are short ASCII ids (Huds/SectionsManifest.cs); anything longer isn't ours.

View file

@ -0,0 +1,222 @@
// RynthAiPlugin.Dashboard.cs — RynthAi's dashboard window (Dashboard/InstrumentDashboard.cs, 2026-10-21).
//
// RynthAi draws its dashboard itself now: the sections manifest declares the window (Huds/
// SectionsManifest.cs, DashboardWindow) as "RynthAi" with "takeOver", so it takes the engine
// panel's place (its saved spot, bar button, hotkeys and /rc commands), and with RynthCore's
// plugin API v90 "chrome": "none" and "fitHeight": RynthAi draws the whole window, frame
// included, and the engine fits its height. On an older engine the window isn't declared and
// RynthCore's own dashboard stays.
//
// The Classic (retail) look is still RynthCore's face: picking it here runs "/rc dashboard
// classic" and drops the window, so the engine's face comes back for it; switching back to the
// modern look there brings this window back (the engine's state file says which look is on).
//
// The tick side: the window's queued clicks, the player's vitals (the engine's snapshot poll
// refreshed them while its dashboard was open), the monster RynthAi is fighting for the target
// bar (combat doesn't select it since 2026-06-03, so the selection alone left the bar empty in a
// fight), the prefs' save, and the settings' save after an opacity or lock change.
using System;
using System.Collections.Concurrent;
using System.Numerics;
using System.Threading;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.Dashboard;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
internal const string DashboardSurface = "window:dashboard";
private InstrumentDashboard? _instrument; // render thread
private DashboardBridge? _dashBridge; // render thread
private DashboardPrefs _dashPrefs = new(); // loaded in Initialize
private readonly ConcurrentQueue<Action> _dashActions = new();
private readonly DateTime _dashLoadedUtc = DateTime.UtcNow;
private long _dashDrawnMs = long.MinValue / 2; // render thread writes, tick reads
private long _nextDashVitalsMs, _nextDashClassicMs, _dashSaveAtMs;
private volatile bool _classicLook; // the engine's look is Classic (its file)
private long _classicAskedMs; // "Classic look" clicked: the window steps aside now
private volatile FightTarget? _dashFight; // tick writes, render reads
private int _dashFailures; // draws in a row that threw
/// <summary>The monster RynthAi is fighting, for the target bar: its name, health (0..1, -1 unknown) and vitals.</summary>
internal sealed record FightTarget(uint Id, string Name, float Health, uint Stamina, uint MaxStamina, uint Mana, uint MaxMana);
internal DashboardPrefs DashPrefs => _dashPrefs;
internal DateTime DashLoadedUtc => _dashLoadedUtc;
/// <summary>The engine (RynthPluginBase.Host is protected).</summary>
internal RynthCoreHost DashHost => Host;
/// <summary>
/// The dashboard window goes in the manifest: an engine with frameless windows (v90), and not
/// while the Classic look is on (RynthCore's face draws that). Render thread (the manifest poll).
/// </summary>
private bool DashboardWindowWanted =>
Host.HasFramelessWindows && !_classicLook && Interlocked.Read(ref _classicAskedMs) == 0;
/// <summary>
/// RynthPluginRenderEmbed "window:dashboard": the dashboard, into the host's window (docked, or
/// popped out in its own context). 1 drawn, 0 not ready, -2 failed (three draws in a row threw:
/// the engine switches the surface off and says so). Render thread.
/// </summary>
internal int RenderDashboard(bool popped, out Vector2 want)
{
want = default;
if (!_initialized || !_loginComplete || _dashboard == null || Host.ImGuiContext == IntPtr.Zero) return 0;
Volatile.Write(ref _dashDrawnMs, Environment.TickCount64);
IntPtr previous = ImGui.GetCurrentContext();
ImGui.SetCurrentContext(EmbedContext());
try
{
_dashBridge ??= new DashboardBridge(this);
_instrument ??= new InstrumentDashboard(_dashBridge);
want = _instrument.Draw(popped);
_dashFailures = 0;
return 1;
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.UI, ex, "RenderDashboard");
return ++_dashFailures >= 3 ? -2 : 0;
}
finally
{
ImGui.SetCurrentContext(previous);
}
}
/// <summary>Plugin tick: the window's clicks, the vitals and the fight while it shows, the look, the saves.</summary>
private void TickDashboard()
{
while (_dashActions.TryDequeue(out Action? act))
{
try { act(); }
catch (Exception ex) { Host.Log("[RynthAi] Dashboard: " + ex.Message); }
}
long now = Environment.TickCount64;
bool shown = now - Volatile.Read(ref _dashDrawnMs) < 2000;
if (shown && now >= _nextDashVitalsMs)
{
_nextDashVitalsMs = now + 100;
_dashboard?.RefreshDashboardVitals();
_dashFight = ReadFightTarget(_dashFight);
}
if (now >= _nextDashClassicMs)
{
_nextDashClassicMs = now + 2000;
bool classic = DashboardPrefs.ClassicLook();
_classicLook = classic;
long asked = Interlocked.Read(ref _classicAskedMs);
// Once the engine's file says Classic (or 10 s on, if it never does) the click has landed.
if (asked != 0 && (classic || now - asked > 10_000)) Interlocked.Exchange(ref _classicAskedMs, 0);
}
_dashPrefs.SaveIfChanged();
// An opacity or lock change from the window, saved with the profile a moment later (a few
// clicks on the opacity buttons make one save).
if (_dashSaveAtMs != 0 && now >= _dashSaveAtMs)
{
_dashSaveAtMs = 0;
_dashboard?.SaveSettings();
}
}
/// <summary>The window changed something the settings profile keeps (opacity, lock). Plugin tick.</summary>
internal void ScheduleDashSave() => _dashSaveAtMs = Environment.TickCount64 + 1000;
/// <summary>
/// The monster combat is on while the macro runs, or null: its name, the health the server sends
/// for the mob we fight, and its stamina and mana when known. The last one again when nothing
/// changed (no allocation). Plugin tick.
/// </summary>
private FightTarget? ReadFightTarget(FightTarget? last)
{
var settings = _dashboard?.Settings;
int id = _combatManager?.activeTargetId ?? 0;
if (id == 0 || settings == null || !settings.IsMacroRunning || !settings.EnableCombat) return null;
uint uid = unchecked((uint)id);
float health = _objectCache?.GetHealthRatio(id) ?? -1f;
uint st = 0, maxSt = 0, mn = 0, maxMn = 0;
if (Host.HasGetTargetVitals) Host.TryGetTargetVitals(uid, out _, out _, out st, out maxSt, out mn, out maxMn);
if (last != null && last.Id == uid && last.Health == health && last.Stamina == st && last.MaxStamina == maxSt
&& last.Mana == mn && last.MaxMana == maxMn)
return last;
string name = last != null && last.Id == uid ? last.Name : _objectCache?[id]?.Name ?? string.Empty;
if (name.Length == 0) name = "0x" + uid.ToString("X8");
return new FightTarget(uid, name, health, st, maxSt, mn, maxMn);
}
/// <summary>The readout with the target bar on the monster RynthAi is fighting, when it is fighting one. Render thread.</summary>
internal DashboardReadout WithFightTarget(DashboardReadout r)
{
FightTarget? f = _dashFight;
if (f == null) return r;
return r with
{
TargetId = f.Id, TargetLabel = f.Name, TargetHealth = f.Health, TargetIsFight = true,
TargetStamina = f.Stamina, TargetMaxStamina = f.MaxStamina, TargetMana = f.Mana, TargetMaxMana = f.MaxMana,
};
}
/// <summary>"Classic look": RynthCore's face draws it; this window steps aside at once. Render thread.</summary>
internal void UseClassicLook()
{
Interlocked.Exchange(ref _classicAskedMs, Math.Max(1, Environment.TickCount64));
QueueDashCommand("/rc dashboard classic");
}
internal void QueueDashAction(Action action)
{
if (_dashActions.Count < 64) _dashActions.Enqueue(action);
}
/// <summary>A chat command for the tick (RynthCore's /rc, another plugin's /ro ...).</summary>
internal void QueueDashCommand(string command)
{
if (!Host.HasInvokeChatParser || _engineCommands.Count >= MaxQueuedEngineCommands) return;
_engineCommands.Enqueue(command);
}
/// <summary>The Mini Remote drawer: RynthAi's remote, into the current window. Render thread.</summary>
internal bool DrawDashMiniRemote(out Vector2 want)
{
want = default;
var huds = _huds;
if (huds == null) return false;
want = huds.RenderEmbedded(false, true);
return true;
}
}
/// <summary>What the dashboard window reads and asks (Dashboard/InstrumentDashboard.cs): RynthAi, queued for its tick.</summary>
internal sealed class DashboardBridge : IDashboardHost
{
private readonly RynthAiPlugin _p;
public DashboardBridge(RynthAiPlugin plugin) => _p = plugin;
private LegacyDashboardRenderer Renderer => _p.DashboardRenderer ?? throw new InvalidOperationException("RynthAi's dashboard isn't ready.");
public RynthCoreHost Host => _p.DashHost;
public DashboardReadout Read() => _p.WithFightTarget(Renderer.ReadDashboard());
public DashboardFiles ReadFiles() => Renderer.ReadDashboardFiles();
public DashboardPrefs Prefs => _p.DashPrefs;
public string Version => RynthPluginInfo.Version;
public DateTime LoadedUtc => _p.DashLoadedUtc;
public void Queue(Action action) => _p.QueueDashAction(action);
public void Command(string command) => _p.QueueDashCommand(command);
public void ToggleMacro() => Queue(_p.ToggleMacroFromPanel); // refuses a start while VTank runs
public void SetSubsystem(int id, bool on) => Queue(() => _p.DashboardRenderer?.SetSubsystemEnabled(id, on));
public void ForceRebuff() => Queue(() => _p.DashboardRenderer?.RequestForceRebuff());
public void CancelForceRebuff() => Queue(() => _p.DashboardRenderer?.RequestCancelForceRebuff());
public void AdjustOpacity(float delta) => Queue(() => { _p.DashboardRenderer?.AdjustOpacity(delta); _p.ScheduleDashSave(); });
public void ToggleLock() => Queue(() => { _p.DashboardRenderer?.TogglePanelLock(); _p.ScheduleDashSave(); });
public void SelectProfile(int kind, int index) => Queue(() => _p.DashboardRenderer?.SelectProfileAtIndex(kind, index));
public void StartPatrol() => Queue(_p.HandleDungeonNavPatrol);
public void ToggleSpells() => _p.EnqueueRemoteCommand("spells", "toggle");
public void UseClassicLook() => _p.UseClassicLook();
public bool DrawMiniRemote(out Vector2 want) => _p.DrawDashMiniRemote(out want);
}

View file

@ -480,7 +480,8 @@ public sealed partial class RynthAiPlugin
public string? BuildSectionsJson()
{
if (!_initialized || !_loginComplete) return null;
return Huds.SectionsManifest.Build(Huds.SectionsManifest.Views(), Huds.SectionsManifest.OwnSections);
return Huds.SectionsManifest.Build(Huds.SectionsManifest.Views(), Huds.SectionsManifest.OwnSections,
dashboard: DashboardWindowWanted);
}
/// <summary>Chat Translate window in the dashboard colours (no-op while hidden).</summary>
private void RenderTranslateWindow()

View file

@ -220,6 +220,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
InitSessionStats();
// The overlay windows (OnRenderOverlay) must draw through the engine's cimgui module.
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => RynthLog.Write(LogCat.UI, msg));
// RynthAi's own dashboard window (RynthAiPlugin.Dashboard.cs): the engine's look, and its prefs.
RynthCore.Plugin.Shared.RynthUi.RynthUi.Init(Host);
_dashPrefs = RynthCore.Plugin.RynthAi.Dashboard.DashboardPrefs.Load();
_dashboard = new LegacyDashboardRenderer(Host);
_killClock.MacroRunning = () => _dashboard?.Settings.IsMacroRunning == true;
_dashboard.KillClock = _killClock;
@ -737,6 +740,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager.Vitals = _vitals; // the script hook's request carries the player's vitals
_combatManager.HoldIdlePeace = LootHoldsIdlePeace;
_combatManager.LastVitalCastAt = () => _buffManager?.LastVitalCastAt ?? DateTime.MinValue;
_combatManager.SwapBurstEnabled = () => _buffManager?.SwapBurst == true;
_combatManager.LastModeChangeAt = () => _buffManager?.LastModeChangeAt ?? DateTime.MinValue;
_combatManager.BuffingWantsTick = () => _buffManager != null
&& (_buffManager.PendingSpellId != 0 || _buffManager.WantsVitalRecharge
|| (_dashboard?.Settings?.EnableBuffing == true && _buffManager.NeedsAnyBuff()));
@ -1454,6 +1459,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
Guard(TickStep.CombatHook, CombatHook.ObserveUseDone); // ctx.last.err: the answer to the hook's last cast
Guard(TickStep.DelayedCommands, TickDelayedCommands); // /ub delay
Guard(TickStep.GameInput, GameInput.Pump); // release keys held for /mt movement | jump | strafe
Guard(TickStep.Dashboard, TickDashboard); // the dashboard window's clicks, vitals and prefs
Guard(TickStep.EngineCommands, DrainEngineCommands); // fellowship command buttons (RynthCore's Fellowship section)
Guard(TickStep.PropertyDump, () => TickPropertyDump()); // /ub propertydump: waits for the ID, chat in chunks
if (_loginComplete) Guard(TickStep.PackSetup, () => _dashboard?.TickPackSetup(_objectCache, _playerId)); // new/copied profile items
@ -3996,6 +4002,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "forcebuff": HandleForceBuff(); break;
case "cancelforcebuff": HandleCancelForceBuff(); break;
case "buff": HandleBuffCommand(parts); break;
case "swaptest":
if (_buffManager == null) { ChatLine("[RynthAi] BuffManager not ready (not logged in yet)."); break; }
_buffManager.RequestSwapTest(parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2) : "");
break;
case "bufftest":
if (_buffManager == null) { ChatLine("[RynthAi] BuffManager not ready (not logged in yet)."); break; }
_buffManager.EnableCastRegistryDiagnostic = !_buffManager.EnableCastRegistryDiagnostic;

View file

@ -67,6 +67,9 @@
<Compile Include="..\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<!-- ImGui text calls for non-literal text ('%' escaped; RynthILT links the same file). -->
<Compile Include="..\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
<!-- The engine's look for RynthAi's own windows (the instrument dashboard, 2026-10-21; RynthNet links them too). -->
<Compile Include="..\Shared\RynthUi\RynthUi.cs" Link="Shared\RynthUi\RynthUi.cs" />
<Compile Include="..\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthUi\RynthIcons.cs" />
<!-- A server plugin's part of the Mini Remote (RynthServer.Hub) and RynthAi.Hub (what server plugins borrow). -->
<Compile Include="..\Shared\RynthServerHubApi.cs" Link="Shared\RynthServerHubApi.cs" />
<Compile Include="..\Shared\RynthAiHubApi.cs" Link="Shared\RynthAiHubApi.cs" />