Vitals: no wand swap for a vital spell while a kit or potion heals #28

Open
AwfulWaffle wants to merge 2 commits from AwfulWaffle/RynthSuite:vital-wand-gate into main
9 changed files with 957 additions and 37 deletions

View file

@ -238,7 +238,7 @@ public partial class BuffManager
foreach (var r in _settings.ConsumableRules)
if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase)
&& !(r.Name ?? "").Contains("Stamina Kit", StringComparison.OrdinalIgnoreCase)
&& ConsumableLookup.Resolve(_worldObjectCache, r) is WorldObject wo && IsUseOnSelfKit(wo)) { capable = true; break; }
&& ConsumableLookup.Resolve(_worldObjectCache, r, KitUsedUp) is WorldObject wo && IsUseOnSelfKit(wo)) { capable = true; break; }
}
if (!capable && _settings.UsePotions && HasListedPotion("HealthPotion")) capable = true;
}

View file

@ -0,0 +1,75 @@
// ============================================================================
// RynthSuite - Combat/BuffManager.KitUsedUp.cs
// A kit its own result line says is used up is not picked again.
//
// A kit's last heal ends "... Your Treated Healing Kit is used up." (ACE Healer.DoHealing), and the
// server removes the kit. A use of an item the player no longer has is answered with a bare UseDone
// and no chat, so no heal lands: a used-up kit picked again is a heal lost.
//
// Kit picks read the client's live pack walk (ConsumableLookup.Resolve, BestPackHealingKit,
// BestPackStaminaKit: WorldObjectCache.GetDirectInventory), which drops a removed kit, but that walk
// is reused for up to a second (DirectInventoryCooldownMs) and the next kit goes out KitLandGraceMs
// (700 ms) after the line, inside that reuse. An engine without GetContainerContents has no walk at
// all: its inventory view is the object cache, which can keep a removed kit for good.
//
// So: the line names the kit in flight -> every kit pick skips that kit. With the live walk the skip
// lasts UsedUpKitSkipMs, long enough for a fresh walk to have dropped it; without the walk it lasts
// for the session (the server deleted the object, and its id never comes back). Only a line naming
// the kit in flight counts: a late line from a kit that timed out can land while the next kit is out,
// and must not mark that one. Kit use itself is unchanged.
// ============================================================================
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi;
public partial class BuffManager
{
/// <summary>How long a kit its result line called used up is skipped while the live pack walk runs
/// (the walk's 1 s reuse, with margin). Without the walk the skip does not end.</summary>
internal const double UsedUpKitSkipMs = 3000;
// The kit in flight (its id and name), from the use until the next one.
private int _kitInFlightId;
private string _kitInFlightName = "";
// Kits called used up by their result line, and until when kit picks skip each.
private readonly Dictionary<int, DateTime> _usedUpKitUntil = new();
/// <summary>Kits skipped because their result line said they are used up (tests, status).</summary>
internal int KitsUsedUp { get; private set; }
/// <summary>Records which kit went out (AttemptHealthKitUse, AttemptStaminaKitUse).</summary>
private void NoteKitInFlight(WorldObject kit)
{
_kitInFlightId = kit.Id;
_kitInFlightName = kit.Name ?? "";
}
/// <summary>True while <paramref name="id"/> is a kit its result line called used up (see the header).</summary>
internal bool KitUsedUp(int id)
{
if (id == 0 || !_usedUpKitUntil.TryGetValue(id, out DateTime until)) return false;
if (until > Now) return true;
_usedUpKitUntil.Remove(id);
return false;
}
/// <summary>A kit result line arrived (OnChatWindowText): an "is used up" line naming the kit in flight marks it.</summary>
private void NoteKitResultLine(string text, string lower)
{
if (!lower.Contains(" is used up", StringComparison.Ordinal) || _kitInFlightId == 0) return;
if (_kitInFlightName.Length > 0 && lower.Contains(_kitInFlightName.ToLowerInvariant(), StringComparison.Ordinal))
{
bool walk = _host.HasGetContainerContents;
_usedUpKitUntil[_kitInFlightId] = walk ? Now.AddMilliseconds(UsedUpKitSkipMs) : DateTime.MaxValue;
KitsUsedUp++;
_host.Log($"[RynthAi] Vitals: kit 0x{(uint)_kitInFlightId:X8} '{_kitInFlightName}' is used up (its result line): " +
(walk ? $"kit picks skip it for {UsedUpKitSkipMs / 1000:0} s, until the pack walk has dropped it."
: "kit picks skip it from now on (no pack walk on this engine)."));
}
else
_host.Log($"[RynthAi] Vitals: an 'is used up' line that doesn't name the kit in flight " +
$"(0x{(uint)_kitInFlightId:X8} '{_kitInFlightName}') ignored: \"{text}\"");
}
}

View file

@ -0,0 +1,187 @@
// ============================================================================
// RynthSuite - Combat/BuffManager.VitalWandGate.cs
// No wand swap for a vital spell while a kit or potion can do the job.
//
// Kits are the standard heal, and the shield stays on: putting the shield away for a wand costs more
// damage than a small heal spell buys back. A melee character under Heal At used to put its shield away
// and pull a wand for Heal Self with kits in the pack (the wand was skipped only at Emergency Heal At).
//
// Out of Magic mode with no caster in hand, a vital spell (Heal Self, Stamina to Health, Revitalize,
// Stamina to Mana, the script hook's heal) would start a weapon swap to the wand. VitalSpellWouldSwap
// refuses it (CastVital: not handled), so the chain falls through to the potion, the kit, and the kit
// despite Kit Min Success. The exceptions:
// - nothing else can restore that vital (no usable kit, no potion Use Potions may drink): the swap is
// the only heal there is, so it goes;
// - a caster already wielded needs only the stance change (no weapon moves): allowed;
// - no wand found (FindWandInItems 0): the Magic stance goes bare-handed and no weapon moves: allowed;
// - a swap already under way finishes (refusing it mid-way left the shield in the pack);
// - Stamina to Mana never swaps in a fight (InCombatNow), potion or not; out of a fight it may, even
// with a mana potion carried (buffing is about to swap to the wand anyway).
// Buffing (EnsureMagicMode forBuff) is not gated and still swaps.
//
// A kit the gate counts is one the kit picks would use: the live pack walk (ConsumableLookup,
// GetDirectInventory), minus a kit its line called used up (BuffManager.KitUsedUp.cs), minus a kit the
// server refused KitRefusedStreakMax times within KitRefusedStreakMs (a UseDone error or "You're too
// busy!" is no answer the kit wait drops, so such a kit would block every spell heal forever). A streak
// with no refusal for KitRefusedStreakMs ages out; a kit landing, or the macro stopping, ends them all.
//
// The stamina sources share one order with a last resort (AttemptStaminaRestore): with Revitalize
// refused here, a stamina kit skipped for Stamina Kit Min Success % would leave nothing.
// ============================================================================
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
public partial class BuffManager
{
internal const int KitRefusedStreakMax = 3;
internal const double KitRefusedStreakMs = 10_000;
private readonly Dictionary<int, (int Count, DateTime First, DateTime Last)> _kitRefusedStreak = new();
/// <summary>True when the vital spell for <paramref name="label"/> must not start a wand swap now (see the header).</summary>
private bool VitalSpellWouldSwap(string label, out string why)
{
why = "";
if (_wandSwap.Active) return false; // a swap already under way finishes
if (CurrentCombatMode == CombatMode.Magic) return false;
int wandId = FindWandInItems();
if (wandId == 0 || IsBuffWandWielded(wandId)) return false; // bare-handed Magic, or the stance change only: no weapon moves
if (label == LabelMana)
{
if (!InCombatNow()) return false;
why = "no wand swap for Stamina to Mana in a fight (the shield stays on)";
return true;
}
bool other = label == LabelStamina
? HasUsableStaminaKit() || HasAnyPotion("StaminaPotion", "Stamina")
: HasUsableHealthKit() || HasAnyPotion("HealthPotion"); // Healing and the script heal
if (!other) return false;
why = "no wand swap for a vital spell (kits are the standard heal; the shield stays on)";
return true;
}
private void NoteKitRefusedStreak(int kitId)
{
if (kitId == 0) return;
DateTime now = Now;
PruneKitRefusedStreaks(now);
_kitRefusedStreak[kitId] = _kitRefusedStreak.TryGetValue(kitId, out var s) && (now - s.First).TotalMilliseconds <= KitRefusedStreakMs
? (s.Count + 1, s.First, now)
: (1, now, now);
}
/// <summary>Drops streaks with no refusal for KitRefusedStreakMs: the kit counts for the gate again.</summary>
private void PruneKitRefusedStreaks(DateTime now)
{
if (_kitRefusedStreak.Count == 0) return;
List<int>? stale = null;
foreach (var kv in _kitRefusedStreak)
if ((now - kv.Value.Last).TotalMilliseconds > KitRefusedStreakMs) (stale ??= new()).Add(kv.Key);
if (stale != null) foreach (int id in stale) _kitRefusedStreak.Remove(id);
}
/// <summary>Ends every refusal streak (a kit landed, or the macro stopped).</summary>
private void ClearKitRefusedStreaks() => _kitRefusedStreak.Clear();
/// <summary>A kit the gate does not count: called used up, or refused KitRefusedStreakMax times with the last
/// refusal under KitRefusedStreakMs ago.</summary>
private bool KitOutForGate(int id)
{
if (KitUsedUp(id)) return true;
PruneKitRefusedStreaks(Now);
return _kitRefusedStreak.TryGetValue(id, out var s) && s.Count >= KitRefusedStreakMax;
}
/// <summary>A healing kit AttemptHealthKitUse could pick (a listed one, else the pack's).</summary>
private bool HasUsableHealthKit()
{
if (_worldObjectCache == null) return false;
foreach (var r in _settings.ConsumableRules)
if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase)
&& !(r.Name ?? "").Contains("Stamina Kit", StringComparison.OrdinalIgnoreCase)
&& ConsumableLookup.Resolve(_worldObjectCache, r, KitOutForGate) is WorldObject wo
&& IsUseOnSelfKit(wo))
return true;
return HasPackKit("Healing Kit");
}
/// <summary>A stamina kit AttemptStaminaKitUse could pick.</summary>
private bool HasUsableStaminaKit() => _host.HasUseObjectOn && HasPackKit("Stamina Kit");
/// <summary>A kit named "... <paramref name="suffix"/>" in the pack the gate still counts (BestPack*Kit's match).</summary>
private bool HasPackKit(string suffix)
{
if (_worldObjectCache == null) return false;
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: false))
if ((wo.Name ?? "").EndsWith(suffix, StringComparison.OrdinalIgnoreCase) && !KitOutForGate(wo.Id))
return true;
return false;
}
/// <summary>A potion of <paramref name="types"/> AttemptPotion could drink (listed or in the pack), with Use Potions on.</summary>
private bool HasAnyPotion(params string[] types)
{
if (!_settings.UsePotions || _worldObjectCache == null) return false;
if (HasListedPotion(types)) return true;
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: false))
{
string? kind = LegacyWeaponsUi.PotionType(wo);
if (kind == null || Array.FindIndex(types, t => t.Equals(kind, StringComparison.OrdinalIgnoreCase)) < 0) continue;
if (IsKitName(wo.Name)) continue;
return true;
}
return false;
}
/// <summary>
/// The stamina sources in order, shared by the stamina step, the mana step's refill (AttemptManaRefill)
/// and the buffing mana floor: a kit, a listed potion first when <paramref name="listedPotionFirst"/>,
/// Revitalize, any potion, then the kit Stamina Kit Min Success % skipped as the last resort.
/// </summary>
private bool AttemptStaminaRestore(bool listedPotionFirst = false)
{
if (AttemptStaminaKit(false, out bool underMinSuccess)
|| (listedPotionFirst && AttemptPotion(true, "StaminaPotion", "Stamina"))
|| AttemptVitalCast("Revitalize Self")
|| AttemptPotion("StaminaPotion", "Stamina"))
return true;
// Last resort, as the heal chain's: the stamina kit Stamina Kit Min Success % skipped. With
// Revitalize refused by the wand gate and no potion, nothing else restores stamina.
if (underMinSuccess && AttemptStaminaKit(true, out _))
{
_host.Log("[RynthAi] Vitals: no spell or potion could restore stamina; using the stamina kit despite Stamina Kit Min Success %.");
return true;
}
return false;
}
/// <summary>
/// True when <paramref name="wandId"/> (FindWandInItems' pick) is in the player's hand: EnsureMagicMode
/// then needs no weapon move, only the stance change. Shared by EnsureMagicMode and VitalSpellWouldSwap.
/// </summary>
private bool IsBuffWandWielded(int wandId)
{
if (wandId == 0) return false;
// Primary check: CurrentWieldedLocation (stype=10) - works even before the
// phys-obj offset probe fires, mirrors CombatManager.EquipWeaponAndSetStance.
bool alreadyWielded = false;
var wandObj = _worldObjectCache?[wandId];
if (wandObj != null)
alreadyWielded = wandObj.Values(LongValueKey.CurrentWieldedLocation, 0) > 0;
// Secondary check via API if primary didn't confirm
if (EquippedState.IsWielded(_host, wandId) is bool trackedWand) alreadyWielded = trackedWand; // the server's word
else if (!alreadyWielded && _host.HasGetObjectWielderInfo)
{
uint playerId = _host.GetPlayerId();
if (playerId != 0 &&
_host.TryGetObjectWielderInfo((uint)wandId, out uint wielder, out _) &&
wielder == playerId && _worldObjectCache?.InPackWalk(wandId) != true) // a stale record (the wand in a pack)
alreadyWielded = true;
}
return alreadyWielded;
}
}

View file

@ -1382,6 +1382,7 @@ public partial class BuffManager : IDisposable
TickFailsafeRecall();
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) ClearKitRefusedStreaks(); // the macro is off: the vital wand gate's refusal streaks end
if (!_settings.IsMacroRunning) { DropWandSwap("the macro stopped"); return; }
@ -1825,8 +1826,7 @@ public partial class BuffManager : IDisposable
if (_vitals.StaminaPct <= 15)
{
_vitalWhy = "";
if (AttemptStaminaKitUse() || AttemptVitalCast("Revitalize Self")
|| AttemptPotion("StaminaPotion", "Stamina"))
if (AttemptStaminaRestore())
{
_isRechargingStamina = true;
return;
@ -2220,7 +2220,7 @@ public partial class BuffManager : IDisposable
// Stamina too low for Stamina to Mana (StaminaToManaFloorPct: Re-stam At, at least 15): a
// stamina kit, Revitalize or a potion first.
if (curStamPct <= StaminaToManaFloorPct() && TopStaminaToManaId() != 0
&& (AttemptStaminaKitUse() || AttemptVitalCast("Revitalize Self") || AttemptPotion("StaminaPotion", "Stamina")))
&& AttemptStaminaRestore())
{
refilledStamina = true;
return true;
@ -2238,11 +2238,7 @@ public partial class BuffManager : IDisposable
bool potionJustDrunk = potionFirst && _settings.UsePotions
&& (RynthClock.Now - _lastPotionAt).TotalMilliseconds < 2500
&& HasListedPotion("StaminaPotion", "Stamina");
return !potionJustDrunk
&& (AttemptStaminaKitUse()
|| (potionFirst && AttemptPotion(true, "StaminaPotion", "Stamina"))
|| AttemptVitalCast("Revitalize Self")
|| AttemptPotion("StaminaPotion", "Stamina"));
return !potionJustDrunk && AttemptStaminaRestore(potionFirst);
}
// Re-stam To (2026-10-06): a recharge started under Re-stam At carries on until stamina
@ -2438,6 +2434,9 @@ public partial class BuffManager : IDisposable
// A recovery vital retried after a mana refusal: its retry gap and the per-second ceiling.
if (IsRecoveryVital(what) && RecoveryRetryHolds(family) is { Length: > 0 } recoveryWhy)
return VitalNo(recoveryWhy);
// No wand swap for a vital spell while a kit or potion heals (BuffManager.VitalWandGate.cs).
if (VitalSpellWouldSwap(label, out string swapWhy))
return VitalNo(swapWhy);
if (CurrentCombatMode != CombatMode.Magic && RynthClock.Now < _vitalSwapBlockedUntil)
return VitalNo("wand swap blocked, retrying shortly");
bool urgentHeal = label == LabelHealing && (_oneTouchHealthScope || HealIsUrgent(_vitals.HealthPct, _vitals.StaminaPct));
@ -2684,7 +2683,7 @@ public partial class BuffManager : IDisposable
foreach (var r in _settings.ConsumableRules)
if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase)
&& !(r.Name ?? "").Contains("Stamina Kit", StringComparison.OrdinalIgnoreCase) // a stamina kit heals no health
&& ConsumableLookup.Resolve(_worldObjectCache, r) is WorldObject wo
&& ConsumableLookup.Resolve(_worldObjectCache, r, KitUsedUp) is WorldObject wo
&& IsUseOnSelfKit(wo)) { kit = wo; break; } // no kit: the potion step drinks it
if (kit == null) { kit = BestPackHealingKit(); fromPack = true; }
if (kit == null) return VitalNo("no healing kit");
@ -2711,6 +2710,7 @@ public partial class BuffManager : IDisposable
_host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: healing kit on yourself");
_lastCastAttempt = RynthClock.Now;
MarkKitUsed();
NoteKitInFlight(kit);
NoteHealSent(kit.Name ?? "healing kit");
return true;
}
@ -2719,8 +2719,13 @@ public partial class BuffManager : IDisposable
/// Uses the best stamina kit in the pack on the player, with the same rules as healing
/// kits: not in Magic mode unless UseKitsInMagicMode, peace mode first if PeaceModeForKits.
/// </summary>
private bool AttemptStaminaKitUse()
private bool AttemptStaminaKitUse() => AttemptStaminaKit(false, out _);
/// <summary><paramref name="underMinSuccess"/>: a kit was there and skipped only for Stamina Kit Min Success %;
/// <paramref name="ignoreMinSuccess"/> uses it anyway (AttemptStaminaRestore's last resort).</summary>
private bool AttemptStaminaKit(bool ignoreMinSuccess, out bool underMinSuccess)
{
underMinSuccess = false;
if (_worldObjectCache == null || !_host.HasUseObjectOn) return false;
int mode = CurrentCombatMode;
if (mode == CombatMode.Magic && !_settings.UseKitsInMagicMode) return false;
@ -2729,7 +2734,11 @@ public partial class BuffManager : IDisposable
if (KitRetryWait(out _)) return false;
uint missing = _vitals.MaxStamina > _vitals.CurrentStamina ? _vitals.MaxStamina - _vitals.CurrentStamina : 0;
// Its own line (Stamina Kit Min Success %): below it Revitalize Self or a potion goes.
if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits, _settings.StaminaKitMinSuccessPct)) return false;
if (!ignoreMinSuccess && !KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits, _settings.StaminaKitMinSuccessPct))
{
underMinSuccess = true;
return false;
}
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode)
{
if (_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the stamina kit"))
@ -2744,6 +2753,7 @@ public partial class BuffManager : IDisposable
_vitalActionsSent++;
_lastCastAttempt = RynthClock.Now;
MarkKitUsed(stamina: true);
NoteKitInFlight(kit);
return true;
}
@ -2807,6 +2817,7 @@ public partial class BuffManager : IDisposable
_kitUsedAt = DateTime.MinValue;
_kitRefusedAt = RynthClock.Now;
KitRefusals++;
NoteKitRefusedStreak(_kitInFlightId); // the vital wand gate stops counting a kit refused again and again
_host.Log($"[RynthAi] Vitals: the {(_kitIsStamina ? "stamina" : "healing")} kit was refused {ms:0} ms after use ({why}): " +
$"no result will come, vitals carry on (next kit in {KitRetryAfterRefusalMs:0} ms).");
}
@ -2898,6 +2909,7 @@ public partial class BuffManager : IDisposable
{
string name = wo.Name ?? "";
if (!name.EndsWith("Stamina Kit", StringComparison.OrdinalIgnoreCase)) continue;
if (KitUsedUp(wo.Id)) continue; // its line said used up; the walk may not show it yet
int rank = name.Contains("Greater", StringComparison.OrdinalIgnoreCase) ? 0
: name.Contains("Lesser", StringComparison.OrdinalIgnoreCase) ? 2 : 1;
if (rank < bestRank) { best = wo; bestRank = rank; }
@ -2917,6 +2929,7 @@ public partial class BuffManager : IDisposable
{
string name = wo.Name ?? "";
if (!name.EndsWith("Healing Kit", StringComparison.OrdinalIgnoreCase)) continue;
if (KitUsedUp(wo.Id)) continue; // its line said used up; the walk may not show it yet
int rank = Array.FindIndex(KitRanks, k => name.Contains(k, StringComparison.OrdinalIgnoreCase));
if (rank < 0) rank = name.Contains("Crude", StringComparison.OrdinalIgnoreCase) ? KitRanks.Length + 1 : KitRanks.Length;
if (rank < bestRank) { best = wo; bestRank = rank; }
@ -4522,7 +4535,11 @@ public partial class BuffManager : IDisposable
// A kit on yourself finished (see KitPending). After the speech filter: "heal yourself" in a tell is not one.
if (_kitUsedAt != DateTime.MinValue && _kitLandedAt == DateTime.MinValue && IsKitResultLine(lower))
{
_kitLandedAt = RynthClock.Now;
NoteKitResultLine(text, lower); // "... is used up." naming it: kit picks skip it (BuffManager.KitUsedUp.cs)
ClearKitRefusedStreaks(); // a kit landed: the refusal streaks end (BuffManager.VitalWandGate.cs)
}
// Real failure phrases. Note: bare "component" was removed — it false-matches
// the "consumed the following components" line, which fires for both success
@ -5390,23 +5407,7 @@ public partial class BuffManager : IDisposable
return false;
}
// Primary check: CurrentWieldedLocation (stype=10) — works even before the
// phys-obj offset probe fires, mirrors CombatManager.EquipWeaponAndSetStance.
bool alreadyWielded = false;
var wandObj = _worldObjectCache?[wandId];
if (wandObj != null)
alreadyWielded = wandObj.Values(LongValueKey.CurrentWieldedLocation, 0) > 0;
// Secondary check via API if primary didn't confirm
if (EquippedState.IsWielded(_host, wandId) is bool trackedWand) alreadyWielded = trackedWand; // the server's word
else if (!alreadyWielded && _host.HasGetObjectWielderInfo)
{
uint playerId = _host.GetPlayerId();
if (playerId != 0 &&
_host.TryGetObjectWielderInfo((uint)wandId, out uint wielder, out _) &&
wielder == playerId && _worldObjectCache?.InPackWalk(wandId) != true) // a stale record (the wand in a pack)
alreadyWielded = true;
}
bool alreadyWielded = IsBuffWandWielded(wandId); // shared with the vital wand gate (BuffManager.VitalWandGate.cs)
if (!_settings.FastWeaponSwap)
{

View file

@ -355,6 +355,8 @@ public class WorldObjectCache
private readonly Dictionary<int, int> _directInventoryIndex = new();
private DateTime _lastDirectInventoryScan = DateTime.MinValue;
private const int DirectInventoryCooldownMs = 1000;
/// <summary>The clock GetDirectInventory's reuse runs on (tests freeze it; RynthClock otherwise).</summary>
internal Func<DateTime> WalkClock { get; set; } = static () => RynthClock.Now;
private const int DirectInventoryForceRefreshMinMs = 250;
/// <summary>Mark inventory as changed — triggers a full container scan on next Tick.</summary>
@ -1390,7 +1392,7 @@ public class WorldObjectCache
// snapshot copy so the caller never iterates the live list a later call will clear.
lock (_gate)
{
DateTime now = RynthClock.Now;
DateTime now = WalkClock();
if (!_host.HasGetContainerContents)
{

View file

@ -18,31 +18,37 @@ namespace RynthCore.Plugin.RynthAi;
/// nothing happening (2026-11-03, DreamWeave: a used-up Treated Healing Kit was picked 70 times
/// after a respawn, every use answered at once with no heal, and only natural regeneration
/// raised health). Without the walk (an engine without GetContainerContents) the cache is used.
///
/// <paramref name="skip"/>: ids the caller knows are gone although the walk may still list them (a kit
/// its result line called used up, inside the walk's 1 s reuse; BuffManager.KitUsedUp). A skipped
/// listed id falls through to the name match, so the next stack of that name is used.
/// </summary>
internal static class ConsumableLookup
{
public static WorldObject? Resolve(WorldObjectCache cache, ConsumableRule rule)
public static WorldObject? Resolve(WorldObjectCache cache, ConsumableRule rule, Func<int, bool>? skip = null)
{
IReadOnlyList<WorldObject> carried = cache.GetDirectInventory();
if (carried.Count == 0)
return ResolveFromCache(cache, rule); // no walk yet (or none possible): the cache's view
return ResolveFromCache(cache, rule, skip); // no walk yet (or none possible): the cache's view
if (rule.Id != 0)
foreach (WorldObject wo in carried)
if (wo != null && wo.Id == rule.Id) return wo;
if (wo != null && wo.Id == rule.Id && !Skipped(skip, wo.Id)) return wo;
if (string.IsNullOrWhiteSpace(rule.Name)) return null;
foreach (WorldObject wo in carried)
if (wo != null && wo.Name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase))
if (wo != null && wo.Name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase) && !Skipped(skip, wo.Id))
return wo;
return null;
}
private static WorldObject? ResolveFromCache(WorldObjectCache cache, ConsumableRule rule)
private static WorldObject? ResolveFromCache(WorldObjectCache cache, ConsumableRule rule, Func<int, bool>? skip)
{
if (rule.Id != 0 && cache[rule.Id] is WorldObject byId) return byId;
if (rule.Id != 0 && !Skipped(skip, rule.Id) && cache[rule.Id] is WorldObject byId) return byId;
if (string.IsNullOrWhiteSpace(rule.Name)) return null;
foreach (WorldObject wo in cache.GetInventory())
if (wo != null && wo.Name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase))
if (wo != null && wo.Name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase) && !Skipped(skip, wo.Id))
return wo;
return null;
}
private static bool Skipped(Func<int, bool>? skip, int id) => skip != null && skip(id);
}

View file

@ -100,6 +100,8 @@ internal static class Program
ChestLootTests.Register(runner);
ItemToolTests.Register(runner);
VanishedItemTests.Register(runner);
KitUsedUpTests.Register(runner);
VitalWandGateTests.Register(runner);
OwnCorpseTests.Register(runner);
UseRefusalTests.Register(runner);
CorpseKillerTests.Register(runner);

View file

@ -0,0 +1,217 @@
using System;
using System.Linq;
using System.Threading;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// A kit its own result line calls used up ("... Your Treated Healing Kit is used up.", ACE
// Healer.DoHealing) is skipped by every kit pick (BuffManager.KitUsedUp.cs). The picks read the client's
// live pack walk, which drops the removed kit, but reuses a walk for up to 1 s, and the next kit goes out
// 700 ms after the line: inside that reuse the used-up kit was picked again (checked on main: the same
// rig picks Kit1). These rigs freeze the walk's clock (WorldObjectCache.WalkClock), so the walk is never
// refreshed and only the skip can keep the used-up kit out. Without GetContainerContents there is no walk
// at all, and the skip does not end.
internal static class KitUsedUpTests
{
private const uint Player = 0x500000C1;
private const uint GoneListed = 0x80088BDA; // the stack the Consumables rule was added from, long gone
private const uint Kit1 = 0x80073C1B;
private const uint Kit2 = 0x80073C1A;
private const uint Gem = 0x80073C19; // something else carried, so the walk is never empty
private const uint StamKit1 = 0x80073C18, StamKit2 = 0x80073C17;
private const string KitName = "Treated Healing Kit";
public static void Register(Runner r)
{
r.Add("kit used up: its result line skips that kit inside the pack walk's reuse; the next kit goes (rule and pack picks)", UsedUpLineNextKit);
r.Add("kit used up: a line with uses left keeps the kit (control)", UsesLeftKeepsKit);
r.Add("kit used up: a line naming another kit marks nothing; naming the kit in flight marks it", OtherKitLineIgnored);
r.Add("kit used up: with the pack walk the skip ends after 3 s (the BuffManager clock)", SkipExpires);
r.Add("kit used up: without GetContainerContents the skip does not end (no walk ever drops the kit)", NoWalkSkipLasts);
r.Add("kit used up: a stamina kit's used-up line skips it for the next stamina kit", StaminaKitUsedUp);
}
private static BuffManager Rig(bool withRule, string kit1Name = KitName, bool walk = true)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.UseOnCalls = true;
FakeHost.ContentsCalls = walk; // the client's pack walk (GetContainerContents)
FakeHost.CombatModeValue = CombatMode.Melee;
FakeHost.Names[Kit1] = kit1Name;
FakeHost.Names[Kit2] = KitName;
FakeHost.Names[Gem] = "Sapphire";
FakeHost.Containers[Kit1] = Player;
FakeHost.Containers[Kit2] = Player;
FakeHost.Containers[Gem] = Player;
FakeHost.Skills[(Player, 33)] = (10, 1); // Life Magic untrained: kits are the only heal
var host = FakeHost.Create(Player);
var s = new LegacyUiSettings
{
IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0,
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false,
KitMinSuccessPct = 0, PeaceModeForKits = false,
};
if (withRule)
s.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)GoneListed), Name = KitName, Type = "HealthKit" });
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, s);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
var b = new BuffManager(host, s, sm, v);
b.SetCharacterSkills(skills);
b.SetWorldObjectCache(Frozen(FakeHost.MakeCache(host, Player, new[] { Kit1, Kit2, Gem })));
return b;
}
/// <summary>The walk's reuse clock stopped: the first walk is reused for the whole test.</summary>
private static WorldObjectCache Frozen(WorldObjectCache cache)
{
var frozen = new DateTime(2026, 1, 1, 12, 0, 0);
cache.WalkClock = () => frozen;
return cache;
}
private static uint LastKit() => FakeHost.UsesOn.Count == 0 ? 0 : FakeHost.UsesOn[^1].Source;
/// <summary>The server removed the kit: the client deletes it (no pack, no name); the cache never hears.</summary>
private static void Gone(uint id) { FakeHost.Containers.Remove(id); FakeHost.Names.Remove(id); }
/// <summary>The kit's result line, then past KitLandGraceMs (real clock): the kit wait ends.</summary>
private static void ResultLine(BuffManager b, string line)
{
b.OnChatWindowText(line, 0);
Thread.Sleep(750);
Check.False(b.KitPending(), "the result line and 700 ms: the kit wait ends");
}
private static void UsedUpLineNextKit()
{
foreach (bool withRule in new[] { true, false })
{
string how = withRule ? "Consumables rule" : "best pack kit";
var b = Rig(withRule);
Check.True(b.CheckVitals(), $"{how}: 40% under Heal At 60%: acts");
Check.Eq(LastKit(), Kit1, $"{how}: Kit1 first (the walk is read now)");
Gone(Kit1);
ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} is used up.");
Check.Eq(b.KitsUsedUp, 1, $"{how}: the kit in flight is marked used up");
Check.True(b.CheckVitals(), $"{how}: acts again");
Check.Eq(LastKit(), Kit2, $"{how}: inside the walk's reuse the used-up kit is skipped: Kit2");
Check.True(FakeHost.Logs.Any(l => l.Contains("0x80073C1B", StringComparison.Ordinal) && l.Contains("is used up", StringComparison.Ordinal)),
$"{how}: logged with the id");
}
}
private static void UsesLeftKeepsKit()
{
var b = Rig(withRule: true);
Check.True(b.CheckVitals(), "acts");
Check.Eq(LastKit(), Kit1, "Kit1");
ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} has 3 uses left.");
Check.Eq(b.KitsUsedUp, 0, "uses left: nothing marked");
Check.True(b.CheckVitals(), "acts again");
Check.Eq(LastKit(), Kit1, "the same kit again");
}
// A late line from a kit that timed out can land while the next kit is in flight.
private static void OtherKitLineIgnored()
{
const string Adept = "Adept Healing Kit"; // ranked ahead of Treated: the pack pick takes it
var b = Rig(withRule: false, kit1Name: Adept);
Check.True(b.CheckVitals(), "acts");
Check.Eq(LastKit(), Kit1, "the Adept kit is in flight");
ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} is used up.");
Check.Eq(b.KitsUsedUp, 0, "the line names the Treated kit, not the one in flight: nothing marked");
Check.True(FakeHost.Logs.Any(l => l.Contains("ignored", StringComparison.Ordinal)), "logged as ignored");
Check.True(b.CheckVitals(), "acts again");
Check.Eq(LastKit(), Kit1, "the Adept kit is used again");
ResultLine(b, $"You heal yourself for 12 Health points. Your {Adept} is used up.");
Check.Eq(b.KitsUsedUp, 1, "control: the line naming the kit in flight marks it");
}
private static void SkipExpires()
{
var b = Rig(withRule: true);
var t0 = new DateTime(2026, 1, 1, 12, 1, 0);
DateTime now = t0;
b.Clock = () => now;
b.CheckVitals();
b.OnChatWindowText($"You heal yourself for 12 Health points. Your {KitName} is used up.", 0);
Check.True(b.KitUsedUp(unchecked((int)Kit1)), "marked");
now = t0.AddMilliseconds(2900);
Check.True(b.KitUsedUp(unchecked((int)Kit1)), "2.9 s later: still skipped");
now = t0.AddMilliseconds(3000); // 3 s as a literal: the test must not follow the constant
Check.False(b.KitUsedUp(unchecked((int)Kit1)), "3 s: no longer skipped (the walk has dropped a removed kit by now)");
Check.False(b.KitUsedUp(unchecked((int)Kit2)), "another kit was never skipped");
}
// No GetContainerContents: the inventory is the object cache's, which keeps the removed kit. A skip
// that ended at 3 s would pick it again for good.
private static void NoWalkSkipLasts()
{
var b = Rig(withRule: true, walk: false);
var t0 = new DateTime(2026, 1, 1, 12, 2, 0);
DateTime now = t0;
b.Clock = () => now;
Check.True(b.CheckVitals(), "acts");
Check.Eq(LastKit(), Kit1, "Kit1 first");
Gone(Kit1); // the client deletes it; the cache still lists it
ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} is used up.");
now = t0.AddMilliseconds(800);
Check.True(b.CheckVitals(), "acts again");
Check.Eq(LastKit(), Kit2, "in the window: Kit2");
ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} has 3 uses left.");
now = t0.AddMilliseconds(3200);
Check.True(b.CheckVitals(), "acts at +3.2 s");
Check.Eq(LastKit(), Kit2, "past 3 s with no walk: still Kit2, never the used-up Kit1");
Check.True(FakeHost.Logs.Any(l => l.Contains("from now on", StringComparison.Ordinal)), "logged as a lasting skip");
}
private static void StaminaKitUsedUp()
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.UseOnCalls = true;
FakeHost.ContentsCalls = true;
FakeHost.CombatModeValue = CombatMode.NonCombat;
FakeHost.Names[StamKit1] = "Greater Stamina Kit";
FakeHost.Names[StamKit2] = "Stamina Kit";
FakeHost.Names[Gem] = "Sapphire";
FakeHost.Containers[StamKit1] = Player;
FakeHost.Containers[StamKit2] = Player;
FakeHost.Containers[Gem] = Player;
FakeHost.Skills[(Player, 6)] = (300, 2); // Healing
var host = FakeHost.Create(Player);
var s = new LegacyUiSettings
{
IsMacroRunning = true, PeaceModeForKits = false, UseKitsInMagicMode = true,
KitMinSuccessPct = 0, StaminaKitMinSuccessPct = 0,
};
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, s);
sm.SetCharacterSkills(skills);
var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 1000, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
var b = new BuffManager(host, s, sm, v);
b.SetCharacterSkills(skills);
b.SetWorldObjectCache(Frozen(FakeHost.MakeCache(host, Player, new[] { StamKit1, StamKit2, Gem })));
var attempt = typeof(BuffManager).GetMethod("AttemptStaminaKitUse",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, Type.EmptyTypes)!;
Check.True((bool)attempt.Invoke(b, null)!, "the stamina kit goes out");
Check.Eq(LastKit(), StamKit1, "the Greater one first");
Gone(StamKit1);
b.OnChatWindowText("You heal yourself for 300 Stamina points. Your Greater Stamina Kit is used up.", 0);
Thread.Sleep(750);
Check.False(b.KitPending(), "the wait ends");
Check.True((bool)attempt.Invoke(b, null)!, "the next stamina kit goes out");
Check.Eq(LastKit(), StamKit2, "inside the walk's reuse: the used-up Greater kit is skipped");
}
}

View file

@ -0,0 +1,430 @@
using System;
using System.Linq;
using System.Reflection;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Kits are the standard heal, and the shield stays on.
// A vital spell out of Magic mode with no caster in hand starts no weapon swap while a kit or potion
// for that vital is carried (BuffManager.VitalSpellWouldSwap); buffing still swaps.
internal static class VitalWandGateTests
{
private const uint Player = 0x500000B7;
private const uint Wand = 0x80071001;
private const uint Kit = 0x80071002;
private const uint StamKit = 0x80071003;
private const uint ManaPot = 0x80071004;
private const uint HealPot = 0x80071005;
private const uint CurrentWieldedLocation = 10; // STypeInt CurrentWieldedLocation
private const uint HeldSlot = 0x01000000;
public static void Register(Runner r)
{
r.Add("vital wand gate: out of Magic with a healing kit carried, Heal Self starts no wand swap (not handled)", HealRefusedWithKit);
r.Add("vital wand gate: the refused Heal Self falls through to the kit despite Kit Min Success", KitDespiteMinSuccessAfterRefusal);
r.Add("vital wand gate: a caster already wielded in melee stance: the Magic stance change only, no weapon move", StanceOnlyWithCasterWielded);
r.Add("vital wand gate: no kit and no potion at all: the swap is allowed (the only heal there is)", SwapAllowedWithNothingElse);
r.Add("vital wand gate: Revitalize with a stamina kit, Stamina to Mana in a fight, the script heal with a health potion: no swap", OtherVitalsRefused);
r.Add("vital wand gate: a pure caster in Magic mode with a kit carried still casts Heal Self", PureCasterUnaffected);
r.Add("vital wand gate: buffing still swaps to the wand with a kit carried", BuffsStillSwap);
r.Add("vital wand gate: Revitalize refused, no stamina potion: the stamina kit is used despite Kit Min Success", StaminaKitDespiteMinSuccess);
r.Add("vital wand gate: Stamina to Mana never swaps in a fight; out of one with no mana potion it may", ManaInFightNoSwap);
r.Add("vital wand gate: in Magic stance with no wand in hand and a kit carried, Heal Self is not gated", MagicNoWandNotGated);
r.Add("vital wand gate: a kit its line called used up, or gone from the client's pack, is no kit: Heal Self is handled and the swap is allowed", GoneKitAllowsSwap);
r.Add("vital wand gate: a swap already under way finishes when a kit reappears (no abandoned swap, no kit mid-wield)", SwapInFlightFinishes);
r.Add("vital wand gate: a kit the server refused 3 times within 10 s is no kit for the gate; a kit landing counts it again", RefusedKitAllowsSwap);
r.Add("vital wand gate: the mana step's stamina refill also uses the stamina kit despite Kit Min Success", ManaRefillStaminaLastResort);
r.Add("vital wand gate: out of a fight Stamina to Mana may swap with a mana potion carried; in a fight it may not", ManaPotionOutOfFightSwaps);
r.Add("vital wand gate: a refusal streak ages out: 11 s after the last refusal the kit counts again", RefusedStreakAgesOut);
r.Add("vital wand gate: no wand found: Heal Self takes the bare-handed Magic stance, not gated", NoWandNotGated);
}
// Out of a fight buffing is about to swap to the wand anyway, so a
// mana potion drunk to spare the swap is a potion wasted. In a fight the refusal stands.
private static void ManaPotionOutOfFightSwaps()
{
var q = Rig(CombatMode.Melee, new[] { ManaPot }, usePotions: true);
q.InCombatOverride = () => false;
Check.True(VitalCast(q, "Stamina to Mana Self"), "out of a fight, mana potion carried: handled: " + Why(q));
Check.True(SwapActive(q), "the wand swap is under way");
var f = Rig(CombatMode.Melee, new[] { ManaPot }, usePotions: true);
f.InCombatOverride = () => true;
Check.False(VitalCast(f, "Stamina to Mana Self"), "in a fight, mana potion carried: not handled");
Check.True(Why(f).Contains("Stamina to Mana in a fight", StringComparison.Ordinal), "the in-fight reason: " + Why(f));
Check.Eq(SwapActivity(), 0, "in a fight: no swap");
}
// The stamina last resort covers every stamina path: the stamina step, the mana step's refill
// (AttemptManaRefill) and the buffing mana floor.
private static void ManaRefillStaminaLastResort()
{
var b = Rig(CombatMode.Melee, new[] { StamKit }, kitMinSuccess: 95);
SetVitals(b, 100, 10, 10); // stamina 10% <= the Stamina to Mana floor (15): refill stamina first
object[] args = { 10, false };
bool acted = (bool)typeof(BuffManager).GetMethod("AttemptManaRefill", Np)!.Invoke(b, args)!;
Check.True(acted, "the mana step acts");
Check.True((bool)args[1], "by refilling stamina");
Check.Eq(FakeHost.UsesOn.Count, 1, "one kit use");
Check.Eq(FakeHost.UsesOn[0].Source, StamKit, "the stamina kit Kit Min Success skipped");
Check.True(FakeHost.Logs.Any(l => l.Contains("using the stamina kit despite Stamina Kit Min Success", StringComparison.Ordinal)), "logged");
Check.Eq(SwapActivity(), 0, "no swap");
}
/// <summary>The kit sent and refused by the server (a UseDone with an error code).</summary>
private static void RefuseKit(BuffManager b, uint kit, bool stamina = false)
{
typeof(BuffManager).GetField("_kitRefusedAt", Np)!.SetValue(b, DateTime.MinValue); // past KitRetryAfterRefusalMs (real clock)
int uses = FakeHost.UsesOn.Count;
Check.True((bool)typeof(BuffManager).GetMethod(stamina ? "AttemptStaminaKitUse" : "AttemptHealthKitUse", Np,
stamina ? Type.EmptyTypes : new[] { typeof(bool) })!.Invoke(b, stamina ? null : new object[] { false })!, "the kit goes out");
Check.Eq(FakeHost.UsesOn.Count, uses + 1, "sent");
Check.Eq(FakeHost.UsesOn[^1].Source, kit, "that kit");
FakeHost.UseDone(0x1D); // YoureTooBusy
Check.False(b.KitPending(), "refused: the wait ends");
}
// A kit the server keeps refusing (a UseDone error, "You're too busy!") is no answer the kit wait
// drops: without a cap it would count for the gate forever and no spell heal could ever go.
private static void RefusedKitAllowsSwap()
{
var setNow = new Action<BuffManager, DateTime>((bm, t) => bm.Clock = () => t);
var t0 = new DateTime(2026, 1, 1, 18, 0, 0);
var b = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true);
FakeHost.UseDoneSeq = 10;
RefuseKit(b, Kit);
RefuseKit(b, Kit);
Check.False(VitalCast(b, "Heal Self"), "2 refusals: the kit still counts, Heal Self refused");
RefuseKit(b, Kit);
Check.True(VitalCast(b, "Heal Self"), "3 refusals within 10 s: the kit is no kit, Heal Self handled: " + Why(b));
Check.True(SwapActive(b), "the wand swap is under way");
// Spread over more than 10 s: no streak.
var s = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true);
FakeHost.UseDoneSeq = 10;
setNow(s, t0); RefuseKit(s, Kit);
setNow(s, t0.AddSeconds(6)); RefuseKit(s, Kit);
setNow(s, t0.AddSeconds(12)); RefuseKit(s, Kit);
Check.False(VitalCast(s, "Heal Self"), "3 refusals over 12 s: the kit still counts");
// A kit landing ends the streak.
var l = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true);
FakeHost.UseDoneSeq = 10;
RefuseKit(l, Kit); RefuseKit(l, Kit); RefuseKit(l, Kit);
typeof(BuffManager).GetField("_kitRefusedAt", Np)!.SetValue(l, DateTime.MinValue);
typeof(BuffManager).GetMethod("AttemptHealthKitUse", Np, new[] { typeof(bool) })!.Invoke(l, new object[] { false });
l.OnChatWindowText("You heal yourself for 40 Health points. Your Treated Healing Kit has 3 uses left.", 0);
Check.False(VitalCast(l, "Heal Self"), "a kit landed: it counts again, Heal Self refused");
// Stamina kits too: Revitalize may swap once the stamina kit is refused 3 times.
var st = Rig(CombatMode.Melee, new[] { StamKit }, kitMinSuccess: 0, kitAnswers: true);
FakeHost.UseDoneSeq = 10;
Check.False(VitalCast(st, "Revitalize Self"), "control: the stamina kit carried, Revitalize refused");
RefuseKit(st, StamKit, stamina: true); RefuseKit(st, StamKit, stamina: true); RefuseKit(st, StamKit, stamina: true);
Check.True(VitalCast(st, "Revitalize Self"), "stamina kit refused 3 times: Revitalize handled: " + Why(st));
}
// The gate allowed a swap (no kit), then a kit came back. Refusing now would leave the
// swap untouched until TickWandSwap abandons it, with the shield maybe already in the pack.
private static void SwapInFlightFinishes()
{
var b = Rig(CombatMode.Melee, Array.Empty<uint>());
Check.True(VitalCast(b, "Heal Self"), "no kit: Heal Self handled");
Check.True(SwapActive(b), "the swap started");
var cache = (WorldObjectCache)typeof(BuffManager).GetField("_worldObjectCache", Np)!.GetValue(b)!;
_ = cache[unchecked((int)Kit)]; // the kit is back in the pack
cache.GetDirectInventory(forceRefresh: true); // the fake host has no container walk: refresh the snapshot by hand
Check.True((bool)typeof(BuffManager).GetMethod("HasUsableHealthKit", Np)!.Invoke(b, null)!, "the rig: the kit counts as usable");
Check.True(VitalCast(b, "Heal Self"), "the kit back, the swap under way: still handled: " + Why(b));
Check.True(SwapActive(b), "the swap is still under way");
Check.Eq(FakeHost.UsesOn.Count, 0, "no kit sent mid-swap");
}
private static bool SwapActive(BuffManager b)
{
object swap = typeof(BuffManager).GetField("_wandSwap", Np)!.GetValue(b)!;
return (bool)swap.GetType().GetProperty("Active")!.GetValue(swap)!;
}
// A wand not in hand is no reason to gate
// a character already in Magic: no weapon moves for its cast.
private static void MagicNoWandNotGated()
{
var b = Rig(CombatMode.Magic, new[] { Kit });
VitalCast(b, "Heal Self");
Check.False(Why(b).Contains("no wand swap for a vital spell", StringComparison.Ordinal), "in Magic: not gated: " + Why(b));
}
// A kit the kit picks would not use must not count for the gate either: one its result line called
// used up (BuffManager.KitUsedUp.cs), or one the client's live pack walk no longer lists.
private static void GoneKitAllowsSwap()
{
var b = Rig(CombatMode.Melee, new[] { Kit });
Check.False(VitalCast(b, "Heal Self"), "control: the kit carried, Heal Self refused");
var u = Rig(CombatMode.Melee, new[] { Kit });
Check.True((bool)typeof(BuffManager).GetMethod("AttemptHealthKitUse", Np, new[] { typeof(bool) })!.Invoke(u, new object[] { false })!, "the kit goes out");
u.OnChatWindowText("You heal yourself for 12 Health points. Your Treated Healing Kit is used up.", 0);
Check.True(VitalCast(u, "Heal Self"), "the kit's line said used up: Heal Self handled: " + Why(u));
Check.True(SwapActive(u), "the wand swap is under way");
var w = Rig(CombatMode.Melee, new[] { Kit }, walk: true);
var wc = (WorldObjectCache)typeof(BuffManager).GetField("_worldObjectCache", Np)!.GetValue(w)!;
DateTime wt = new DateTime(2026, 1, 1, 18, 0, 0);
wc.WalkClock = () => wt; // the walk's reuse on a test clock
Check.False(VitalCast(w, "Heal Self"), "control, live walk: the kit carried, Heal Self refused");
FakeHost.Containers.Remove(Kit); // used up: the client deletes it; the cache never hears
FakeHost.Names.Remove(Kit);
wt = wt.AddMilliseconds(1100); // past the walk's 1 s reuse
Check.True(VitalCast(w, "Heal Self"), "the kit gone from the client's pack: Heal Self handled: " + Why(w));
Check.True(SwapActive(w), "the wand swap is under way");
}
// A refusal streak ages out: with no refusal for 10 s the kit counts for the gate again.
private static void RefusedStreakAgesOut()
{
var b = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true);
var t0 = new DateTime(2026, 1, 1, 18, 0, 0);
DateTime now = t0;
b.Clock = () => now;
FakeHost.UseDoneSeq = 10;
RefuseKit(b, Kit); RefuseKit(b, Kit); RefuseKit(b, Kit);
Check.True(VitalCast(b, "Heal Self"), "control: 3 refusals, the kit is no kit: Heal Self handled: " + Why(b));
var c = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true);
DateTime cnow = t0;
c.Clock = () => cnow;
FakeHost.UseDoneSeq = 10;
RefuseKit(c, Kit); RefuseKit(c, Kit); RefuseKit(c, Kit);
cnow = t0.AddSeconds(11);
Check.False(VitalCast(c, "Heal Self"), "11 s after the last refusal: the kit counts again, Heal Self refused");
Check.True(Why(c).Contains("no wand swap for a vital spell", StringComparison.Ordinal), "the gate's reason: " + Why(c));
}
// No wand found (no wand rule, none carried): the Magic stance goes bare-handed and no weapon moves.
private static void NoWandNotGated()
{
var b = Rig(CombatMode.Melee, new[] { Kit }, noWand: true);
VitalCast(b, "Heal Self");
Check.False(Why(b).Contains("no wand swap", StringComparison.Ordinal), "no wand: not refused by the gate: " + Why(b));
Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 1, "the bare-handed Magic stance request goes out");
Check.Eq(FakeHost.Wields.Count, 0, "no wield");
}
private static void SetVitals(BuffManager b, uint health, uint stamina, uint mana)
{
var v = (PlayerVitalsCache)typeof(BuffManager).GetField("_vitals", Np)!.GetValue(b)!;
v.CurrentHealth = health; v.CurrentStamina = stamina; v.CurrentMana = mana;
}
private static void StaminaKitDespiteMinSuccess()
{
foreach (int minSuccess in new[] { 95, 0 })
{
var b = Rig(CombatMode.Melee, new[] { StamKit }, kitMinSuccess: minSuccess);
S.RestamAt = 50;
SetVitals(b, 100, 20, 100);
Check.True(b.CheckVitals(), $"min {minSuccess}: stamina 20% under Re-stam At 50%: the chain acts");
Check.Eq(FakeHost.UsesOn.Count, 1, $"min {minSuccess}: one kit use");
Check.Eq(FakeHost.UsesOn[0].Source, StamKit, $"min {minSuccess}: the stamina kit");
bool lastResort = FakeHost.Logs.Any(l => l.Contains("using the stamina kit despite Stamina Kit Min Success", StringComparison.Ordinal));
if (minSuccess == 95) Check.True(lastResort, "under Kit Min Success: used as the last resort, logged");
else Check.False(lastResort, "control, chance fine: the normal kit use, no last-resort line");
Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 0, $"min {minSuccess}: no Magic stance");
Check.Eq(FakeHost.Casts.Count, 0, $"min {minSuccess}: no Revitalize");
}
}
private static void ManaInFightNoSwap()
{
// No mana potion, no kit: only the fight decides.
var f = Rig(CombatMode.Melee, Array.Empty<uint>(), usePotions: true);
f.InCombatOverride = () => true;
Check.False(VitalCast(f, "Stamina to Mana Self"), "in a fight: Stamina to Mana not handled");
Check.True(Why(f).Contains("Stamina to Mana in a fight", StringComparison.Ordinal), "the why says so: " + Why(f));
Check.Eq(SwapActivity(), 0, "in a fight: no swap");
var q = Rig(CombatMode.Melee, Array.Empty<uint>(), usePotions: true);
q.InCombatOverride = () => false;
int before = SwapActivity();
Check.True(VitalCast(q, "Stamina to Mana Self"), "out of a fight, no mana potion: handled (the swap step): " + Why(q));
Check.True(SwapActivity() > before, "out of a fight: the wand swap started");
// A caster in hand needs no swap: Stamina to Mana still goes in a fight.
var c = Rig(CombatMode.Melee, Array.Empty<uint>(), wandWielded: true);
c.InCombatOverride = () => true;
VitalCast(c, "Stamina to Mana Self");
Check.False(Why(c).Contains("no wand swap", StringComparison.Ordinal), "caster in hand, in a fight: not gated: " + Why(c));
}
private static LegacyUiSettings S = new();
private static BuffManager Rig(int mode, uint[] items, bool wandWielded = false, bool usePotions = false, int kitMinSuccess = 0, bool kitAnswers = false,
bool walk = false, bool noWand = false)
{
FakeHost.Reset();
uint[] carried = (noWand ? Array.Empty<uint>() : new[] { Wand }).Concat(items).ToArray();
if (walk)
{
FakeHost.ContentsCalls = true; // the client's pack walk (GetContainerContents)
foreach (uint id in carried) FakeHost.Containers[id] = Player;
}
FakeHost.WeaponCalls = true;
FakeHost.CombatModeCalls = true;
FakeHost.UseOnCalls = true;
if (kitAnswers) { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; } // a kit's UseDone answers
FakeHost.CombatModeValue = mode;
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, 33)] = (400, 2); // Life Magic
FakeHost.Skills[(Player, 21)] = (10, 2); // Healing, low: a kit chance under any real Kit Min Success
if (!noWand)
{
FakeHost.Names[Wand] = "Wand";
FakeHost.ItemTypes[Wand] = 0x8000; // a caster
FakeHost.Appraised.Add(Wand); // identified: FindWandInItems takes it (a real swap, not bare-handed Magic)
}
FakeHost.Names[Kit] = "Treated Healing Kit";
// Lesser (boost 100): (10 + 100) x 1.1 = 121 vs 80 missing x 2 x 1.1 = 176 in melee, 16%, under the
// weapon-out bar of 30 (a Greater kit's boost 200 clears it).
FakeHost.Names[StamKit] = "Lesser Stamina Kit";
FakeHost.Names[ManaPot] = "Mana Elixir";
FakeHost.Names[HealPot] = "Healing Elixir";
if (wandWielded) FakeHost.Ints[(Wand, CurrentWieldedLocation)] = unchecked((int)HeldSlot);
var host = FakeHost.Create(Player);
S = new LegacyUiSettings
{
IsMacroRunning = true, HealAt = 75, TopOffHP = 75, EmergencyHealAt = 0, StaminaToHealthAt = 0,
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = usePotions, EnableBuffing = false,
KitMinSuccessPct = kitMinSuccess, StaminaKitMinSuccessPct = kitMinSuccess, PeaceModeForKits = false,
};
if (!noWand) S.ItemRules.Add(new ItemRule { Id = unchecked((int)Wand), Name = "Wand", Element = "Fire" });
if (items.Contains(ManaPot)) S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)ManaPot), Name = "Mana Elixir", Type = "ManaPotion" });
if (items.Contains(HealPot)) S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)HealPot), Name = "Healing Elixir", Type = "HealthPotion" });
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, S);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
var b = new BuffManager(host, S, sm, v);
b.SetCharacterSkills(skills);
b.MarkLiveBuffsReadyForTests();
b.InCombatOverride = () => true;
b.SetWorldObjectCache(FakeHost.MakeCache(host, Player, carried));
DateTime now = new DateTime(2026, 1, 1, 18, 0, 0);
b.Clock = () => now;
return b;
}
private static readonly BindingFlags Np = BindingFlags.Instance | BindingFlags.NonPublic;
private static bool VitalCast(BuffManager b, string baseName)
=> (bool)typeof(BuffManager).GetMethod("AttemptVitalCast", Np)!.Invoke(b, new object[] { baseName })!;
private static string Why(BuffManager b) => (string)typeof(BuffManager).GetField("_vitalWhy", Np)!.GetValue(b)!;
/// <summary>Everything a wand swap or stance change sends or logs.</summary>
private static int SwapActivity() => FakeHost.CombatModeRequests.Count + FakeHost.Wields.Count + FakeHost.Uses.Count
+ FakeHost.Logs.Count(l => l.Contains("[WieldGate] switching to", StringComparison.Ordinal));
private static void HealRefusedWithKit()
{
foreach (int mode in new[] { CombatMode.Melee, CombatMode.Missile, CombatMode.NonCombat })
{
var b = Rig(mode, new[] { Kit });
int before = SwapActivity();
Check.False(VitalCast(b, "Heal Self"), $"mode {mode}, kit carried: Heal Self not handled");
Check.True(Why(b).Contains("no wand swap for a vital spell", StringComparison.Ordinal), $"mode {mode}: the why says so: {Why(b)}");
Check.Eq(SwapActivity(), before, $"mode {mode}: no stance change, wield or swap step");
Check.Eq(FakeHost.Casts.Count, 0, $"mode {mode}: nothing cast");
}
// A health potion alone (no kit) refuses it too.
var p = Rig(CombatMode.Melee, new[] { HealPot }, usePotions: true);
Check.False(VitalCast(p, "Stamina to Health Self"), "health potion carried: Stamina to Health not handled");
Check.Eq(SwapActivity(), 0, "and no swap");
}
private static void KitDespiteMinSuccessAfterRefusal()
{
var b = Rig(CombatMode.Melee, new[] { Kit }, kitMinSuccess: 95);
Check.True(b.CheckVitals(), "40% under Heal At 75%: the chain acts");
Check.Eq(FakeHost.UsesOn.Count, 1, "one kit use");
Check.Eq(FakeHost.UsesOn[0].Source, Kit, "the kit Kit Min Success skipped");
Check.True(FakeHost.Logs.Any(l => l.Contains("despite Kit Min Success", StringComparison.Ordinal)), "the last resort is logged");
Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 0, "no Magic stance asked for");
Check.Eq(FakeHost.Casts.Count, 0, "no Heal Self");
}
private static void StanceOnlyWithCasterWielded()
{
var b = Rig(CombatMode.Melee, new[] { Kit }, wandWielded: true);
Check.False(Why(b).Contains("no wand swap", StringComparison.Ordinal), "rig");
VitalCast(b, "Heal Self");
Check.False(Why(b).Contains("no wand swap for a vital spell", StringComparison.Ordinal), "caster in hand: not refused by the gate: " + Why(b));
Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 1, "the Magic stance change goes out");
Check.Eq(FakeHost.Wields.Count, 0, "no wield");
Check.Eq(FakeHost.Uses.Count, 0, "no use (no re-equip)");
Check.False(FakeHost.Logs.Any(l => l.Contains("[WieldGate] switching to", StringComparison.Ordinal)), "no swap started");
}
private static void SwapAllowedWithNothingElse()
{
// Control for HealRefusedWithKit: the same rig with nothing else to heal with.
var b = Rig(CombatMode.Melee, Array.Empty<uint>(), usePotions: true);
int before = SwapActivity();
bool handled = VitalCast(b, "Heal Self");
Check.True(handled, "no kit, no potion: Heal Self handled (its swap step in flight): " + Why(b));
Check.True(SwapActivity() > before, "the wand swap started");
// A potion only, with Use Potions off: nothing RynthAi may use, so the swap is allowed.
var k = Rig(CombatMode.Melee, new[] { HealPot }, usePotions: false);
Check.True(VitalCast(k, "Heal Self"), "a potion Use Potions may not drink is no heal: the swap is allowed");
}
private static void OtherVitalsRefused()
{
var s = Rig(CombatMode.Melee, new[] { StamKit });
Check.False(VitalCast(s, "Revitalize Self"), "stamina kit carried: Revitalize not handled");
Check.Eq(SwapActivity(), 0, "no swap for Revitalize");
var sc = Rig(CombatMode.Melee, new[] { Kit });
Check.True(VitalCast(sc, "Revitalize Self"), "control: a healing kit is no stamina restore: Revitalize may swap");
var m = Rig(CombatMode.Melee, new[] { ManaPot }, usePotions: true);
m.InCombatOverride = () => true; // the potion alone no longer refuses it (out of a fight it may swap): the fight does
Check.False(VitalCast(m, "Stamina to Mana Self"), "in a fight, mana potion carried: Stamina to Mana not handled");
Check.Eq(SwapActivity(), 0, "no swap for Stamina to Mana in a fight");
// The script hook's heal goes through CastVital with the Healing label.
var h = Rig(CombatMode.Melee, new[] { HealPot }, usePotions: true);
int heal = SpellTable.Rows.First(r => r.Name.StartsWith("Heal Self", StringComparison.Ordinal)).Id;
object[] args = { heal, Player, BuffManager.LabelHealing, "Heal Self (script)", false };
bool handled = (bool)typeof(BuffManager).GetMethod("CastVital", Np)!.Invoke(h, args)!;
Check.False(handled, "script heal, health potion carried: not handled");
Check.False((bool)args[4], "not sent");
Check.Eq(SwapActivity(), 0, "no swap for the script heal");
}
private static void PureCasterUnaffected()
{
var b = Rig(CombatMode.Magic, new[] { Kit }, wandWielded: true);
S.UseKitsInMagicMode = false; // the kit is skipped in Magic: the spell is the heal
Check.True(b.CheckVitals(), "a caster in Magic under Heal At: acts");
Check.True(FakeHost.Casts.Count > 0, "Heal Self is cast: " + Why(b));
Check.Eq(FakeHost.UsesOn.Count, 0, "no kit");
Check.Eq(FakeHost.Wields.Count, 0, "no wield");
}
private static void BuffsStillSwap()
{
var b = Rig(CombatMode.Melee, new[] { Kit, HealPot }, usePotions: true);
int before = SwapActivity();
var ensure = typeof(BuffManager).GetMethod("EnsureMagicMode", Np)!;
bool inMagic = (bool)ensure.Invoke(b, new object[] { true, false })!;
Check.False(inMagic, "not in Magic yet");
Check.True(SwapActivity() > before, "buffing starts the wand swap with a kit and potion carried");
}
}