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" />

View file

@ -0,0 +1,237 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Use;
namespace RynthCore.Plugin.RynthDefective;
/// <summary>
/// What the windows and the commands act on: the character's data, the use controller, and the
/// things a player does to slots (set one from the selected item, clear, move, bind a key). The
/// host-facing parts are delegates, so all of it runs offline in the tests.
/// </summary>
internal sealed class DefSession
{
public DefData Data = new();
public readonly UseController Use = new();
public readonly HotkeyLookup Keys;
/// <summary>Everything carried now (cached by the plugin; at most a moment old).</summary>
public Func<IReadOnlyList<CarriedItem>> Items = () => Array.Empty<CarriedItem>();
public Func<uint> SelectedId = () => 0;
public Func<long> Now = () => Environment.TickCount64;
/// <summary>Types a line to the engine's chat parser ("/rc hotkey add F9 /rdef use 3"); false when it can't.</summary>
public Func<string, bool> RunChat = _ => false;
/// <summary>Asks for the character's file to be written soon.</summary>
public Action Save = () => { };
/// <summary>The pictures and bar buttons need op level 2 script windows.</summary>
public bool IconsAvailable;
public bool LoggedIn;
public string Character = string.Empty;
// The line under the bar: the last thing that happened.
private string _status = string.Empty;
private long _statusAtMs;
private bool _statusIsWarning;
public const long StatusShownMs = 9000;
public DefSession(HotkeyLookup keys) => Keys = keys;
public DefSettings Settings => Data.Settings;
public void SetStatus(string text, bool warning = false)
{
_status = text;
_statusIsWarning = warning;
_statusAtMs = Now();
}
/// <summary>The status line while it is fresh; empty after <see cref="StatusShownMs"/>.</summary>
public string Status(out bool warning)
{
warning = _statusIsWarning;
return _status.Length > 0 && Now() - _statusAtMs < StatusShownMs ? _status : string.Empty;
}
// ── Using ───────────────────────────────────────────────────────────────
/// <summary>The slot's button or key: use what it holds. Returns what to tell the player when nothing could be queued.</summary>
public string? UseSlot(int slotNumber)
{
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
DefSlot slot = Data.Slots[slotNumber - 1];
if (slot.Item == null) return $"Slot {slotNumber} is empty. Set it from the bar (Edit slots) or with /rdef set {slotNumber}.";
Use.Request(new UseRequest(slot.Item, null, slot.Mode, "slot " + slotNumber, Now()));
return null;
}
/// <summary>/rdef use &lt;name&gt;: an item by what the player typed.</summary>
public void UseByName(string name) =>
Use.Request(new UseRequest(null, name, UseMode.Auto, "name '" + name + "'", Now()));
/// <summary>The picker: wield this weapon.</summary>
public void Wield(ItemRef item) =>
Use.Request(new UseRequest(item, null, UseMode.Equip, "picker", Now()));
// ── Slots ───────────────────────────────────────────────────────────────
public string SetFromSelected(int slotNumber)
{
uint sel = SelectedId();
if (sel == 0) return "Select the item in the game first (click it in your pack), then set the slot.";
CarriedItem? it = FindById(sel);
if (it == null) return "The selected object isn't in your pack, so it can't go in a slot.";
return SetSlot(slotNumber, it);
}
/// <summary>An item dragged onto the slot (its object id).</summary>
public string SetFromId(int slotNumber, uint objectId)
{
CarriedItem? it = FindById(objectId);
if (it == null) return "That isn't in your pack, so it can't go in a slot.";
return SetSlot(slotNumber, it);
}
public string SetFromName(int slotNumber, string name)
{
CarriedItem? it = ItemMatcher.FindByName(name, Items());
if (it == null) return $"No item named '{name}' in your pack.";
return SetSlot(slotNumber, it);
}
public string SetSlot(int slotNumber, CarriedItem it)
{
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
DefSlot slot = Data.Slots[slotNumber - 1];
slot.Item = ItemRef.From(it);
slot.Mode = UseMode.Auto;
Save();
ItemKind kind = ItemKinds.Classify(it);
return $"Slot {slotNumber}: {it.FullName} ({UseModes.Describe(ItemKinds.DefaultAction(kind))} when pressed).";
}
public string ClearSlot(int slotNumber)
{
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
Data.Slots[slotNumber - 1] = new DefSlot();
Save();
return $"Slot {slotNumber} cleared.";
}
/// <summary>Swaps slot <paramref name="a"/> with <paramref name="b"/> (1-based), as moving one place.</summary>
public bool SwapSlots(int a, int b)
{
int max = Settings.SlotCount;
if (a < 1 || b < 1 || a > max || b > max || a == b) return false;
(Data.Slots[a - 1], Data.Slots[b - 1]) = (Data.Slots[b - 1], Data.Slots[a - 1]);
Save();
return true;
}
public void SetSlotMode(int slotNumber, UseMode mode)
{
Data.Slots[slotNumber - 1].Mode = mode;
Save();
}
public void SetSlotCount(int count)
{
Settings.SlotCount = Math.Clamp(count, DefSettings.SlotsMin, DefSettings.SlotsMax);
Save();
}
public CarriedItem? FindById(uint id)
{
foreach (CarriedItem it in Items())
if (it.Id == id) return it;
return null;
}
/// <summary>
/// After an inventory read: every slot, favourite and recent entry follows the item it stands for
/// (a used-up stack's replacement, a new picture). Never clears anything. Returns whether a
/// save is due. Skipped while nothing at all is carried (the inventory isn't loaded yet).
/// </summary>
public bool Maintain(IReadOnlyList<CarriedItem> items)
{
if (items.Count == 0) return false;
bool changed = false;
foreach (DefSlot s in Data.Slots)
if (s.Item != null && ItemMatcher.Maintain(s.Item, items)) changed = true;
foreach (ItemRef f in Data.Favourites)
if (ItemMatcher.Maintain(f, items)) changed = true;
foreach (ItemRef r in Data.Recent)
if (ItemMatcher.Maintain(r, items)) changed = true;
return changed;
}
// ── Keys ────────────────────────────────────────────────────────────────
/// <summary>The key bound to slot <paramref name="slotNumber"/> or to its item by name, or null.</summary>
public string? KeyOfSlot(int slotNumber)
{
long now = Now();
string? key = Keys.KeyFor(DefCommandParser.UseCommand(slotNumber), now);
if (key != null) return key;
ItemRef? item = Data.Slots[slotNumber - 1].Item;
return item == null ? null : Keys.KeyFor(NameCommand(item), now);
}
public static string NameCommand(ItemRef item) => "/rdef use " + item.FullName;
/// <summary>Binds a key to the slot ("/rdef use 3") or, with <paramref name="byName"/>, to its item's name ("/rdef use Stamina Kit"). Returns the message.</summary>
public string BindKey(int slotNumber, string combo, bool byName)
{
combo = (combo ?? string.Empty).Trim();
if (combo.Length == 0) return "Type the key first, e.g. F9 or Ctrl+1.";
if (combo.IndexOf(' ') >= 0) return "A key has no spaces, e.g. Ctrl+F9.";
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
ItemRef? item = Data.Slots[slotNumber - 1].Item;
if (byName && item == null) return $"Slot {slotNumber} is empty: nothing to bind by name.";
string command = byName ? NameCommand(item!) : DefCommandParser.UseCommand(slotNumber);
UnbindQuiet(slotNumber);
if (!RunChat($"/rc hotkey add {combo} {command}"))
return $"This engine can't bind keys from here. Type: /rc hotkey add {combo} {command}";
Keys.Invalidate();
return $"Binding {combo} to {command} (the engine confirms in chat; Settings > Hotkeys lists it).";
}
public string UnbindKey(int slotNumber)
{
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
string? key = UnbindQuiet(slotNumber);
Keys.Invalidate();
return key == null ? $"Slot {slotNumber} has no key." : $"Key {key} removed from slot {slotNumber}.";
}
/// <summary>Removes the slot's current key (either way of binding); returns it.</summary>
private string? UnbindQuiet(int slotNumber)
{
string? key = KeyOfSlot(slotNumber);
if (key == null) return null;
string combo = key.EndsWith(" (off)", StringComparison.Ordinal) ? key[..^6] : key;
RunChat($"/rc hotkey remove {combo}");
return combo;
}
// ── Favourites ──────────────────────────────────────────────────────────
public string ToggleFavourite(ItemRef r)
{
bool now = Data.ToggleFavourite(r);
Save();
return now ? $"{r.FullName} is a favourite." : $"{r.FullName} is no longer a favourite.";
}
/// <summary>/rdef fav: the item selected in the game.</summary>
public string ToggleSelectedFavourite()
{
uint sel = SelectedId();
if (sel == 0) return "Select a weapon in the game first.";
CarriedItem? it = FindById(sel);
if (it == null) return "The selected object isn't in your pack.";
return ToggleFavourite(ItemRef.From(it));
}
}

View file

@ -0,0 +1,42 @@
using System;
namespace RynthCore.Plugin.RynthDefective.Items;
/// <summary>
/// One thing the character carries or wears, as the client reports it. A plain data holder: the
/// reader (HostInventory) fills it, everything else (slot matching, item kinds, the weapon picker)
/// works on it without the host, so it can be tested offline.
/// </summary>
internal sealed class CarriedItem
{
public uint Id;
public string Name = string.Empty;
public uint Wcid;
/// <summary>MaterialType (int 131): "Silver" in "Silver Wand"; 0 = none / unknown.</summary>
public int Material;
/// <summary>ItemType flags (the client's TryGetItemType).</summary>
public uint ItemType;
/// <summary>PublicWeenieDesc bitfield (healer, food ...); 0 when the engine can't read it.</summary>
public uint Bitfield;
/// <summary>Stack size (at least 1) and the largest stack (1 = not stackable).</summary>
public int Stack = 1, MaxStack = 1;
/// <summary>Uses left / most uses (Structure 92 / MaxStructure 91): kits, essences; MaxUses 0 = none.</summary>
public int Uses, MaxUses;
/// <summary>ValidLocations (int 9): the EquipMask slots it can go into; 0 = it can't be worn or wielded.</summary>
public int ValidLocations;
/// <summary>The slot it is wielded in now (0 = in a pack).</summary>
public int WieldedLocation;
/// <summary>CombatUse (int 51): 1 melee, 2 missile, 3 ammo, 4 shield, 5 two-handed.</summary>
public int CombatUse;
/// <summary>DamageType (int 45) and UiEffects (int 18): the element of a caster.</summary>
public int DamageType, UiEffects;
/// <summary>Icon, underlay and overlay texture ids (0x06......), 0 = none.</summary>
public uint Icon, Underlay, Overlay;
public bool Wielded => WieldedLocation != 0;
/// <summary>The name with the material in front ("Silver Wand"), as the character sees it in the game.</summary>
public string FullName => ItemNames.Full(Name, Material);
public override string ToString() => $"0x{Id:X8} {FullName}";
}

View file

@ -0,0 +1,169 @@
using System;
using System.Collections.Generic;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Items;
/// <summary>
/// Reads what the character carries and wears from the client into <see cref="CarriedItem"/>s.
/// Plugin pump thread only. Everything comes from what the client already has (the engine's
/// object snapshot and its property caches); nothing is sent to the server.
/// GetContainerContents(player) returns the main pack's items, the side packs and the worn and
/// wielded items; each side pack's items come from GetContainerContents(pack). What an item IS
/// (name, wcid, material, kind, picture) is kept per object id once read; what changes (stack,
/// uses left, whether it is in hand) is read every time.
/// </summary>
internal sealed class HostInventory
{
// STypeInt
private const uint StackSize = 12, MaxStackSize = 11, ValidLocations = 9, CurrentWieldedLocation = 10, UiEffects = 18,
DamageType = 45, CombatUse = 51, MaterialType = 131, Structure = 92, MaxStructure = 91;
// STypeDID
private const uint DidIcon = 8, DidIconOverlay = 50, DidIconUnderlay = 52;
private const int MaxContents = 1024;
private const int MaxNesting = 3;
private const uint ItemTypeContainer = 0x200;
/// <summary>A caster whose damage type has not arrived (it comes with an identify) is read again after this.</summary>
private const long RecheckMs = 15_000;
private sealed class Static
{
public string Name = string.Empty;
public uint Wcid;
public int Material;
public uint ItemType, Bitfield;
public int MaxStack = 1, MaxUses, ValidLocations, CombatUse, DamageType, UiEffects;
public uint Icon, Underlay, Overlay;
public bool IsContainer;
public long ReadMs;
}
private readonly Dictionary<uint, Static> _static = new();
private readonly uint[] _contents = new uint[MaxContents];
public void Reset() => _static.Clear();
/// <summary>Everything carried and worn; empty when the character or its inventory isn't readable yet.</summary>
public List<CarriedItem> Read(RynthCoreHost host, long nowMs)
{
var items = new List<CarriedItem>();
if (!host.HasGetPlayerId || !host.HasGetContainerContents) return items;
uint player = host.GetPlayerId();
if (player == 0) return items;
ScanInto(host, player, player, items, 0, nowMs);
return items;
}
private void ScanInto(RynthCoreHost host, uint container, uint player, List<CarriedItem> items, int depth, long nowMs)
{
int n = host.GetContainerContents(container, _contents);
if (n <= 0) return;
uint[] ids = new uint[n];
Array.Copy(_contents, ids, n);
var packs = new List<uint>();
foreach (uint id in ids)
{
if (id == 0) continue;
Ownership(host, id, out uint c, out uint w, out uint loc);
bool worn = w == player && w != 0;
if (!worn && c != container && c != 0) continue; // moved away since the engine's snapshot
CarriedItem? it = ReadItem(host, id, nowMs, out Static? st);
if (it == null) continue;
if (worn)
{
if (loc == 0 && host.TryGetObjectIntProperty(id, CurrentWieldedLocation, out int l)) loc = unchecked((uint)l);
it.WieldedLocation = loc == 0 ? 1 : unchecked((int)loc); // worn but the slot unreadable: still "in hand"
}
else if (st!.IsContainer && depth < MaxNesting)
{
packs.Add(id);
continue; // a pack is not something to use or wield
}
items.Add(it);
}
foreach (uint pack in packs)
ScanInto(host, pack, player, items, depth + 1, nowMs);
}
/// <summary>One item as the client has it now (null if it has no name yet or is gone).</summary>
public CarriedItem? ReadOne(RynthCoreHost host, uint id, long nowMs)
{
uint player = host.HasGetPlayerId ? host.GetPlayerId() : 0;
CarriedItem? it = ReadItem(host, id, nowMs, out _);
if (it == null) return null;
Ownership(host, id, out _, out uint w, out uint loc);
if (w != 0 && w == player)
{
if (loc == 0 && host.TryGetObjectIntProperty(id, CurrentWieldedLocation, out int l)) loc = unchecked((uint)l);
it.WieldedLocation = loc == 0 ? 1 : unchecked((int)loc);
}
return it;
}
private CarriedItem? ReadItem(RynthCoreHost host, uint id, long nowMs, out Static? st)
{
st = null;
if (!_static.TryGetValue(id, out st) || Stale(st, nowMs))
{
st = ReadStatic(host, id, nowMs);
if (st == null) return null;
_static[id] = st;
}
var it = new CarriedItem
{
Id = id,
Name = st.Name,
Wcid = st.Wcid,
Material = st.Material,
ItemType = st.ItemType,
Bitfield = st.Bitfield,
MaxStack = st.MaxStack,
MaxUses = st.MaxUses,
ValidLocations = st.ValidLocations,
CombatUse = st.CombatUse,
DamageType = st.DamageType,
UiEffects = st.UiEffects,
Icon = st.Icon,
Underlay = st.Underlay,
Overlay = st.Overlay,
};
if (host.TryGetObjectIntProperty(id, StackSize, out int stack) && stack > 0) it.Stack = stack;
if (st.MaxUses > 0 && host.TryGetObjectIntProperty(id, Structure, out int uses)) it.Uses = Math.Max(0, uses);
return it;
}
private static bool Stale(Static st, long nowMs) =>
(st.ItemType & ItemKinds.TypeCaster) != 0 && st.DamageType == 0 && nowMs - st.ReadMs >= RecheckMs;
private static Static? ReadStatic(RynthCoreHost host, uint id, long nowMs)
{
if (!host.TryGetObjectName(id, out string name) || string.IsNullOrWhiteSpace(name)) return null;
var st = new Static { Name = name.Trim(), ReadMs = nowMs };
if (host.TryGetItemType(id, out uint type)) st.ItemType = type;
st.IsContainer = (st.ItemType & ItemTypeContainer) != 0;
if (host.HasGetObjectWcid && host.TryGetObjectWcid(id, out uint wcid)) st.Wcid = wcid;
if (host.HasGetObjectBitfield && host.TryGetObjectBitfield(id, out uint bf)) st.Bitfield = bf;
if (host.TryGetObjectIntProperty(id, MaterialType, out int material)) st.Material = Math.Max(0, material);
if (host.TryGetObjectIntProperty(id, MaxStackSize, out int maxStack)) st.MaxStack = Math.Max(1, maxStack);
if (host.TryGetObjectIntProperty(id, MaxStructure, out int maxUses) && maxUses > 0) st.MaxUses = maxUses;
if (host.TryGetObjectIntProperty(id, ValidLocations, out int valid)) st.ValidLocations = valid;
if (host.TryGetObjectIntProperty(id, CombatUse, out int use)) st.CombatUse = use;
if (host.TryGetObjectIntProperty(id, DamageType, out int dt)) st.DamageType = dt;
if (host.TryGetObjectIntProperty(id, UiEffects, out int fx)) st.UiEffects = fx;
if (host.HasGetObjectDataIdProperty)
{
if (host.TryGetObjectDataIdProperty(id, DidIcon, out uint icon)) st.Icon = icon;
if (host.TryGetObjectDataIdProperty(id, DidIconUnderlay, out uint under)) st.Underlay = under;
if (host.TryGetObjectDataIdProperty(id, DidIconOverlay, out uint over)) st.Overlay = over;
}
return st;
}
private static void Ownership(RynthCoreHost host, uint id, out uint container, out uint wielder, out uint location)
{
container = wielder = location = 0;
if (host.HasGetObjectOwnershipInfo && host.TryGetObjectOwnershipInfo(id, out container, out wielder, out location)) return;
if (host.HasGetObjectWielderInfo && host.TryGetObjectWielderInfo(id, out uint w, out uint loc)) { wielder = w; location = loc; }
}
}

View file

@ -0,0 +1,145 @@
using System;
namespace RynthCore.Plugin.RynthDefective.Items;
/// <summary>What an item is, as far as using it goes.</summary>
internal enum ItemKind
{
/// <summary>Anything used by itself: potions, scrolls, food, gems, summons ...</summary>
Other,
/// <summary>A healing or stamina kit: used on yourself.</summary>
Kit,
Melee,
Missile,
/// <summary>A wand, staff or orb that casts war magic (any element but Nether).</summary>
WarWand,
/// <summary>A caster of Nether: void magic.</summary>
VoidWand,
Shield,
Armor,
Jewelry,
Ammo,
}
/// <summary>What pressing an item's slot does with it.</summary>
internal enum UseAction
{
/// <summary>UseObject: double-clicking it (potions, scrolls, food).</summary>
Use,
/// <summary>UseObjectOn(item, you): healing and stamina kits.</summary>
UseOnSelf,
/// <summary>UseObjectOn(item, the selected target).</summary>
UseOnSelected,
/// <summary>Wield or wear it (UseObject: the client's double-click takes what is in the way off).</summary>
Equip,
}
/// <summary>The weapon picker's groups, in the order they are listed.</summary>
internal enum WeaponGroup { Melee, Missile, WarMagic, VoidMagic, Shield, Ammo }
internal static class ItemKinds
{
// ItemType flags
public const uint TypeMelee = 0x1, TypeArmor = 0x2, TypeClothing = 0x4, TypeJewelry = 0x8, TypeMissile = 0x100, TypeCaster = 0x8000;
// PublicWeenieDesc bitfield: the healer bit
public const uint BitfieldHealer = 0x10000;
// EquipMask slots
public const int ShieldSlot = 0x00200000, AmmoSlot = 0x00800000;
// CombatUse values
public const int CombatUseAmmo = 3, CombatUseShield = 4;
// DamageType / UiEffects bits of Nether
public const int DamageNether = 0x400, EffectNether = 0x1000;
public static ItemKind Classify(CarriedItem it)
{
bool equippable = it.ValidLocations != 0;
if (!equippable)
{
if ((it.Bitfield & BitfieldHealer) != 0) return ItemKind.Kit;
// The engine couldn't read the bitfield: RynthAi's own test for the kits it uses.
if (it.Bitfield == 0 && it.Name.EndsWith(" Kit", StringComparison.OrdinalIgnoreCase)) return ItemKind.Kit;
return ItemKind.Other;
}
bool weaponClass = (it.ItemType & (TypeMelee | TypeMissile | TypeCaster)) != 0 || IsWandName(it.Name);
if (it.CombatUse == CombatUseAmmo || (it.ValidLocations & AmmoSlot) != 0) return ItemKind.Ammo;
if (it.CombatUse == CombatUseShield || (!weaponClass && (it.ValidLocations & ShieldSlot) != 0)) return ItemKind.Shield;
if ((it.ItemType & TypeCaster) != 0 || (weaponClass && (it.ItemType & (TypeMelee | TypeMissile)) == 0))
return IsNether(it) ? ItemKind.VoidWand : ItemKind.WarWand;
if ((it.ItemType & TypeMissile) != 0) return ItemKind.Missile;
if ((it.ItemType & TypeMelee) != 0) return ItemKind.Melee;
if ((it.ItemType & TypeJewelry) != 0) return ItemKind.Jewelry;
return ItemKind.Armor; // armor, clothing and anything else that is worn
}
/// <summary>What a slot does with the item when the player has set nothing else.</summary>
public static UseAction DefaultAction(ItemKind kind) => kind switch
{
ItemKind.Kit => UseAction.UseOnSelf,
ItemKind.Other => UseAction.Use,
_ => UseAction.Equip,
};
public static bool IsWeapon(ItemKind k) => k is ItemKind.Melee or ItemKind.Missile or ItemKind.WarWand or ItemKind.VoidWand;
/// <summary>The picker group of a kind, or null when the picker doesn't list it.</summary>
public static WeaponGroup? GroupOf(ItemKind k) => k switch
{
ItemKind.Melee => WeaponGroup.Melee,
ItemKind.Missile => WeaponGroup.Missile,
ItemKind.WarWand => WeaponGroup.WarMagic,
ItemKind.VoidWand => WeaponGroup.VoidMagic,
ItemKind.Shield => WeaponGroup.Shield,
ItemKind.Ammo => WeaponGroup.Ammo,
_ => null,
};
public static string Label(WeaponGroup g) => g switch
{
WeaponGroup.Melee => "Melee",
WeaponGroup.Missile => "Missile",
WeaponGroup.WarMagic => "War Magic",
WeaponGroup.VoidMagic => "Void Magic",
WeaponGroup.Shield => "Shields",
_ => "Ammunition",
};
/// <summary>A caster whose element is Nether (the damage type, the icon's glow, or the name).</summary>
public static bool IsNether(CarriedItem it) =>
(it.DamageType & DamageNether) != 0
|| (it.DamageType == 0 && (it.UiEffects & EffectNether) != 0)
|| (it.DamageType == 0 && it.UiEffects == 0 && HasWord(it.Name, "Nether", "Void"));
/// <summary>The element a caster is named or glows for, for the picker's second column ("" = none known).</summary>
public static string Element(CarriedItem it)
{
if ((it.DamageType & 0x400) != 0) return "Nether";
if ((it.DamageType & 0x10) != 0) return "Fire";
if ((it.DamageType & 0x08) != 0) return "Cold";
if ((it.DamageType & 0x40) != 0) return "Lightning";
if ((it.DamageType & 0x20) != 0) return "Acid";
int fx = it.UiEffects;
if ((fx & 0x1000) != 0) return "Nether";
if ((fx & 0x0020) != 0) return "Fire";
if ((fx & 0x0080) != 0) return "Cold";
if ((fx & 0x0040) != 0) return "Lightning";
if ((fx & 0x0100) != 0) return "Acid";
if ((fx & 0x0400) != 0) return "Slash";
if ((fx & 0x0800) != 0) return "Pierce";
if ((fx & 0x0200) != 0) return "Bludgeon";
return string.Empty;
}
public static bool IsWandName(string? name) => HasWord(name, "Orb", "Staff", "Wand", "Scepter", "Sceptre", "Baton", "Crozier");
private static bool HasWord(string? name, params string[] words)
{
if (string.IsNullOrEmpty(name)) return false;
foreach (string w in words)
if (name.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) return true;
return false;
}
/// <summary>A launcher needs ammunition in hand; a thrown weapon (a stack of darts) does not.</summary>
public static bool NeedsAmmo(CarriedItem it) => it.MaxStack <= 1;
}

View file

@ -0,0 +1,33 @@
using System;
namespace RynthCore.Plugin.RynthDefective.Items;
/// <summary>Display names: a weapon's material in front of the base name the client reports.</summary>
internal static class ItemNames
{
/// <summary>ACE's MaterialType names, index = the id (0 = none).</summary>
private static readonly string[] Materials =
{
"", "Ceramic", "Porcelain", "Cloth", "Linen", "Satin", "Silk", "Velvet", "Wool", "Gem",
"Agate", "Amber", "Amethyst", "Aquamarine", "Azurite", "Black Garnet", "Black Opal", "Bloodstone", "Carnelian", "Citrine",
"Diamond", "Emerald", "Fire Opal", "Green Garnet", "Green Jade", "Hematite", "Imperial Topaz", "Jet", "Lapis Lazuli", "Lavender Jade",
"Malachite", "Moonstone", "Onyx", "Opal", "Peridot", "Red Garnet", "Red Jade", "Rose Quartz", "Ruby", "Sapphire",
"Smokey Quartz", "Sunstone", "Tiger Eye", "Tourmaline", "Turquoise", "White Jade", "White Quartz", "White Sapphire", "Yellow Garnet", "Yellow Topaz",
"Zircon", "Ivory", "Leather", "Armoredillo Hide", "Gromnie Hide", "Reed Shark Hide", "Metal", "Brass", "Bronze", "Copper",
"Gold", "Iron", "Pyreal", "Silver", "Steel", "Stone", "Alabaster", "Granite", "Marble", "Obsidian",
"Sandstone", "Serpentine", "Wood", "Ebony", "Mahogany", "Oak", "Pine", "Teak",
};
public static string Material(int id) => id > 0 && id < Materials.Length ? Materials[id] : string.Empty;
/// <summary>"Silver Wand": the material in front, unless the name already starts with it.</summary>
public static string Full(string? baseName, int material)
{
string name = (baseName ?? string.Empty).Trim();
string mat = Material(material);
if (mat.Length == 0 || name.Length == 0) return name;
if (name.StartsWith(mat + " ", StringComparison.OrdinalIgnoreCase) || name.Equals(mat, StringComparison.OrdinalIgnoreCase))
return name;
return mat + " " + name;
}
}

View file

@ -0,0 +1,85 @@
using System;
namespace RynthCore.Plugin.RynthDefective.Model;
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection }
/// <summary>A parsed "/rdef ..." line. Use: <see cref="Slot"/> (1-based) or <see cref="Text"/> (an item name).</summary>
internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "");
internal static class DefCommandParser
{
public const string Usage =
"/rdef [use <slot or item name> | set <slot> [item name] | clear <slot> | bind <slot> <key> | unbind <slot> | "
+ "weapons [search] | fav | slots <count> | list | status | panels (the game panel buttons) | selection]";
/// <summary>Parses the arguments after "/rdef" (blank = show or hide the bar).</summary>
public static DefCommand Parse(string? args)
{
string a = (args ?? string.Empty).Trim();
if (a.Length == 0) return new DefCommand(DefVerb.Toggle);
int sp = a.IndexOf(' ');
string verb = (sp < 0 ? a : a[..sp]).ToLowerInvariant();
string rest = sp < 0 ? string.Empty : a[(sp + 1)..].Trim();
switch (verb)
{
case "help": case "?": return new DefCommand(DefVerb.Help);
case "list": case "ls": return new DefCommand(DefVerb.List);
case "status": return new DefCommand(DefVerb.Status);
case "panels": case "panel": return new DefCommand(DefVerb.Panels);
case "selection": case "target":
// "/rdef selection 0x80001234": select that object (a test hook for the Selection window).
return new DefCommand(DefVerb.Selection, Text: rest);
case "fav": case "favourite": case "favorite": return new DefCommand(DefVerb.Favourite);
case "weapons": case "weapon": case "picker": return new DefCommand(DefVerb.Weapons, Text: rest);
case "use": case "wield": case "equip":
if (rest.Length == 0) return Fail($"Use which slot or item? e.g. /rdef use 1 or /rdef use Peerless Healing Kit");
return TrySlot(rest, out int n) ? new DefCommand(DefVerb.Use, n) : new DefCommand(DefVerb.Use, Text: rest);
case "set":
{
SplitSlot(rest, out string? slotText, out string tail);
if (slotText == null || !TrySlot(slotText, out int slot)) return Fail("Which slot? e.g. /rdef set 3 (the item selected in the game goes in slot 3) or /rdef set 3 Peerless Healing Kit");
return new DefCommand(DefVerb.Set, slot, tail);
}
case "clear":
{
return TrySlot(rest, out int slot) ? new DefCommand(DefVerb.Clear, slot) : Fail("Which slot? e.g. /rdef clear 3");
}
case "bind":
{
SplitSlot(rest, out string? slotText, out string key);
if (slotText == null || !TrySlot(slotText, out int slot) || key.Length == 0)
return Fail("Usage: /rdef bind <slot> <key>, e.g. /rdef bind 3 F9 or /rdef bind 3 Ctrl+1");
return new DefCommand(DefVerb.Bind, slot, key);
}
case "unbind":
return TrySlot(rest, out int us) ? new DefCommand(DefVerb.Unbind, us) : Fail("Which slot? e.g. /rdef unbind 3");
case "slots":
return int.TryParse(rest, out int count) && count >= DefSettings.SlotsMin && count <= DefSettings.SlotsMax
? new DefCommand(DefVerb.Slots, count)
: Fail($"How many slots? {DefSettings.SlotsMin} to {DefSettings.SlotsMax}, e.g. /rdef slots 10");
default:
// "/rdef Stamina Kit" is a shorthand for use.
return new DefCommand(DefVerb.Use, Text: a);
}
}
/// <summary>The slot number a hotkey runs for slot <paramref name="slot"/> (1-based).</summary>
public static string UseCommand(int slot) => "/rdef use " + slot;
private static bool TrySlot(string text, out int slot)
{
slot = 0;
return int.TryParse(text.Trim(), out slot) && slot >= 1 && slot <= DefSettings.SlotsMax;
}
private static void SplitSlot(string rest, out string? first, out string tail)
{
int sp = rest.IndexOf(' ');
first = rest.Length == 0 ? null : (sp < 0 ? rest : rest[..sp]);
tail = sp < 0 ? string.Empty : rest[(sp + 1)..].Trim();
}
private static DefCommand Fail(string error) => new(DefVerb.Error, Error: error);
}

View file

@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>One slot of the bar: an item (or nothing) and how pressing it uses that item.</summary>
internal sealed class DefSlot
{
/// <summary>The item the slot holds; null = empty.</summary>
public ItemRef? Item;
/// <summary>How pressing it uses the item. <see cref="UseMode.Auto"/> picks by what the item is.</summary>
public UseMode Mode = UseMode.Auto;
public bool Empty => Item == null;
public DefSlot Clone() => new() { Item = Item?.Clone(), Mode = Mode };
}
/// <summary>The "use as" choice of a slot.</summary>
internal enum UseMode { Auto, Use, OnSelf, OnSelected, Equip }
internal static class UseModes
{
public static readonly string[] Labels =
{
"Automatic (by item)", "Use it", "Use it on me", "Use it on the selected target", "Wield / wear it",
};
/// <summary>The action for a slot's mode and the item's kind.</summary>
public static UseAction ActionFor(UseMode mode, ItemKind kind) => mode switch
{
UseMode.Use => UseAction.Use,
UseMode.OnSelf => UseAction.UseOnSelf,
UseMode.OnSelected => UseAction.UseOnSelected,
UseMode.Equip => UseAction.Equip,
_ => ItemKinds.DefaultAction(kind),
};
public static string Describe(UseAction a) => a switch
{
UseAction.Use => "used",
UseAction.UseOnSelf => "used on you",
UseAction.UseOnSelected => "used on the selected target",
_ => "wielded",
};
}
/// <summary>The kind of weapon the picker is narrowed to.</summary>
internal enum KindFilter { All, Melee, Missile, War, Void }
/// <summary>RynthDefective's settings for one character.</summary>
internal sealed class DefSettings
{
public const int SlotsMin = 1, SlotsMax = 24, PerRowMin = 1, PerRowMax = 12, ButtonMin = 20, ButtonMax = 64,
PickerIconMin = 20, PickerIconMax = 48;
/// <summary>
/// The shortcut bar (2026-10-22, plugin API v90): its first 18 slots are AC's own (the retail
/// toolbar's, its keys AC's keymap), the rest this plugin's own slots (Slots, keys the engine's
/// hotkeys). The player picks how many it shows.
/// </summary>
public const int RetailSlots = 18, BarSlotsMin = 1, BarSlotsMax = RetailSlots + SlotsMax;
public int BarSlots = RetailSlots;
public int SlotCount = 8;
public int SlotsPerRow = 8;
/// <summary>Icon size of the slot buttons, in logical units.</summary>
public int ButtonSize = 36;
/// <summary>Icon size in the weapon picker's rows.</summary>
public int PickerIconSize = 32;
public bool ShowIcons = true;
/// <summary>Counts and uses left under the slot buttons.</summary>
public bool ShowCounts = true;
/// <summary>The weapon kind the picker shows; All = every kind.</summary>
public KindFilter PreferredKind = KindFilter.All;
/// <summary>Weapon swaps are refused while RynthAi's macro runs (it picks the weapon itself); this lets them through.</summary>
public bool SwapWhileBotRuns;
public bool BarOpen;
public bool PickerOpen;
public void Clamp()
{
SlotCount = Math.Clamp(SlotCount, SlotsMin, SlotsMax);
BarSlots = Math.Clamp(BarSlots, BarSlotsMin, BarSlotsMax);
SlotsPerRow = Math.Clamp(SlotsPerRow, PerRowMin, PerRowMax);
ButtonSize = Math.Clamp(ButtonSize, ButtonMin, ButtonMax);
PickerIconSize = Math.Clamp(PickerIconSize, PickerIconMin, PickerIconMax);
if (!Enum.IsDefined(PreferredKind)) PreferredKind = KindFilter.All;
}
}
/// <summary>One character's slots, favourites, recent weapons and settings.</summary>
internal sealed class DefData
{
public const int MaxFavourites = 64, MaxRecent = 8;
public DefSettings Settings = new();
/// <summary>Always <see cref="DefSettings.SlotsMax"/> entries: shrinking the bar hides slots, it doesn't forget them.</summary>
public List<DefSlot> Slots = NewSlots();
public List<ItemRef> Favourites = new();
/// <summary>The weapons wielded from the picker or a slot, newest first.</summary>
public List<ItemRef> Recent = new();
public static List<DefSlot> NewSlots()
{
var l = new List<DefSlot>(DefSettings.SlotsMax);
for (int i = 0; i < DefSettings.SlotsMax; i++) l.Add(new DefSlot());
return l;
}
/// <summary>Pads or cuts the slot list to the fixed length.</summary>
public void FixLength()
{
while (Slots.Count < DefSettings.SlotsMax) Slots.Add(new DefSlot());
if (Slots.Count > DefSettings.SlotsMax) Slots.RemoveRange(DefSettings.SlotsMax, Slots.Count - DefSettings.SlotsMax);
}
public bool IsFavourite(ItemRef r) => Favourites.Exists(f => f.SameAs(r));
/// <summary>Adds or removes a favourite; returns whether it is one now.</summary>
public bool ToggleFavourite(ItemRef r)
{
int i = Favourites.FindIndex(f => f.SameAs(r));
if (i >= 0) { Favourites.RemoveAt(i); return false; }
if (Favourites.Count >= MaxFavourites) return false;
Favourites.Add(r.Clone());
return true;
}
/// <summary>Puts a weapon first in the recent list (once), at most <see cref="MaxRecent"/>.</summary>
public void NoteRecent(ItemRef r)
{
Recent.RemoveAll(x => x.SameAs(r));
Recent.Insert(0, r.Clone());
if (Recent.Count > MaxRecent) Recent.RemoveRange(MaxRecent, Recent.Count - MaxRecent);
}
/// <summary>The slot (1-based number) that holds an item of this identity, or 0.</summary>
public int SlotOf(ItemRef r)
{
for (int i = 0; i < Slots.Count; i++)
if (Slots[i].Item is { } x && x.SameAs(r)) return i + 1;
return 0;
}
}

View file

@ -0,0 +1,246 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>
/// Per-character files: &lt;SuiteDir&gt;\RynthDefective\characters\&lt;server_character&gt;.json, written by
/// hand and read with JsonDocument (plugin types never go through System.Text.Json's serializer,
/// which roots them across hot reloads). A broken or odd file reads as defaults for whatever is
/// wrong in it; the next save rewrites it.
/// </summary>
internal sealed class DefStore
{
/// <summary>RynthDefective's folder (tests point it at a temp folder).</summary>
public string Root;
public DefStore()
{
Root = Path.Combine(RynthCore.Install.RynthInstallPaths.SuiteDir, "RynthDefective");
}
public DefStore(string root) => Root = root;
/// <summary>"server_character" made safe as a file name (the same rule RynthSort and RynthLua use).</summary>
public static string FileStem(string server, string character) => SafeFileName($"{server}_{character}");
public string PathFor(string server, string character) => Path.Combine(Root, "characters", FileStem(server, character) + ".json");
/// <summary>The character's data; defaults for a new character or a broken file (<paramref name="problem"/> says which).</summary>
public DefData Load(string server, string character, out string? problem)
{
problem = null;
string path = PathFor(server, character);
if (!File.Exists(path)) return new DefData();
try
{
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path),
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
return Parse(doc.RootElement);
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException or InvalidOperationException)
{
problem = $"{Path.GetFileName(path)}: {ex.Message}";
return new DefData();
}
}
internal static DefData Parse(JsonElement root)
{
if (root.ValueKind != JsonValueKind.Object) throw new JsonException("the file isn't a JSON object");
var d = new DefData();
if (root.TryGetProperty("settings", out JsonElement s) && s.ValueKind == JsonValueKind.Object)
{
DefSettings st = d.Settings;
st.SlotCount = Int(s, "slotCount", st.SlotCount);
st.BarSlots = Int(s, "barSlots", st.BarSlots);
st.SlotsPerRow = Int(s, "slotsPerRow", st.SlotsPerRow);
st.ButtonSize = Int(s, "buttonSize", st.ButtonSize);
st.PickerIconSize = Int(s, "pickerIconSize", st.PickerIconSize);
st.ShowIcons = Bool(s, "showIcons", st.ShowIcons);
st.ShowCounts = Bool(s, "showCounts", st.ShowCounts);
st.PreferredKind = (KindFilter)Int(s, "preferredKind", (int)st.PreferredKind);
st.SwapWhileBotRuns = Bool(s, "swapWhileBotRuns", st.SwapWhileBotRuns);
st.BarOpen = Bool(s, "barOpen", st.BarOpen);
st.PickerOpen = Bool(s, "pickerOpen", st.PickerOpen);
st.Clamp();
}
if (root.TryGetProperty("slots", out JsonElement slots) && slots.ValueKind == JsonValueKind.Array)
{
int i = 0;
foreach (JsonElement e in slots.EnumerateArray())
{
if (i >= DefSettings.SlotsMax) break;
DefSlot slot = d.Slots[i++];
if (e.ValueKind != JsonValueKind.Object) continue;
slot.Item = ParseRef(e, "item");
int mode = Int(e, "mode", 0);
slot.Mode = mode >= 0 && mode <= (int)UseMode.Equip ? (UseMode)mode : UseMode.Auto;
}
}
ParseRefs(root, "favourites", d.Favourites, DefData.MaxFavourites);
ParseRefs(root, "recent", d.Recent, DefData.MaxRecent);
return d;
}
private static void ParseRefs(JsonElement root, string name, List<ItemRef> into, int max)
{
if (!root.TryGetProperty(name, out JsonElement arr) || arr.ValueKind != JsonValueKind.Array) return;
foreach (JsonElement e in arr.EnumerateArray())
{
if (into.Count >= max) break;
ItemRef? r = ParseRefObject(e);
if (r != null) into.Add(r);
}
}
private static ItemRef? ParseRef(JsonElement owner, string name) =>
owner.TryGetProperty(name, out JsonElement e) ? ParseRefObject(e) : null;
private static ItemRef? ParseRefObject(JsonElement e)
{
if (e.ValueKind != JsonValueKind.Object) return null;
string name = Str(e, "name");
if (name.Length == 0) return null; // an item with no name can't be found again
return new ItemRef
{
Id = UInt(e, "id"),
Name = name,
Wcid = UInt(e, "wcid"),
Material = Int(e, "material", 0),
Icon = UInt(e, "icon"),
Underlay = UInt(e, "underlay"),
Overlay = UInt(e, "overlay"),
};
}
/// <summary>Writes the character's file (temp file, then moved over the old one). Returns an error or null.</summary>
public string? Save(string server, string character, DefData d)
{
string path = PathFor(server, character);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp";
File.WriteAllText(tmp, ToJson(d), new UTF8Encoding(false));
File.Move(tmp, path, overwrite: true);
return null;
}
catch (Exception ex)
{
return ex.Message;
}
}
internal static string ToJson(DefData d)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteNumber("version", 1);
w.WriteStartObject("settings");
DefSettings s = d.Settings;
w.WriteNumber("slotCount", s.SlotCount);
w.WriteNumber("barSlots", s.BarSlots);
w.WriteNumber("slotsPerRow", s.SlotsPerRow);
w.WriteNumber("buttonSize", s.ButtonSize);
w.WriteNumber("pickerIconSize", s.PickerIconSize);
w.WriteBoolean("showIcons", s.ShowIcons);
w.WriteBoolean("showCounts", s.ShowCounts);
w.WriteNumber("preferredKind", (int)s.PreferredKind);
w.WriteBoolean("swapWhileBotRuns", s.SwapWhileBotRuns);
w.WriteBoolean("barOpen", s.BarOpen);
w.WriteBoolean("pickerOpen", s.PickerOpen);
w.WriteEndObject();
w.WriteStartArray("slots");
foreach (DefSlot slot in d.Slots)
{
w.WriteStartObject();
if (slot.Item != null) WriteRef(w, "item", slot.Item);
w.WriteNumber("mode", (int)slot.Mode);
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteStartArray("favourites");
foreach (ItemRef r in d.Favourites) WriteRefValue(w, r);
w.WriteEndArray();
w.WriteStartArray("recent");
foreach (ItemRef r in d.Recent) WriteRefValue(w, r);
w.WriteEndArray();
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray()) + "\n";
}
private static void WriteRef(Utf8JsonWriter w, string name, ItemRef r)
{
w.WritePropertyName(name);
WriteRefValue(w, r);
}
private static void WriteRefValue(Utf8JsonWriter w, ItemRef r)
{
w.WriteStartObject();
w.WriteNumber("id", r.Id);
w.WriteString("name", r.Name);
if (r.Wcid != 0) w.WriteNumber("wcid", r.Wcid);
if (r.Material != 0) w.WriteNumber("material", r.Material);
if (r.Icon != 0) w.WriteNumber("icon", r.Icon);
if (r.Underlay != 0) w.WriteNumber("underlay", r.Underlay);
if (r.Overlay != 0) w.WriteNumber("overlay", r.Overlay);
w.WriteEndObject();
}
private static bool Bool(JsonElement o, string name, bool fallback) =>
o.TryGetProperty(name, out JsonElement v) && (v.ValueKind == JsonValueKind.True || v.ValueKind == JsonValueKind.False)
? v.GetBoolean()
: fallback;
private static string Str(JsonElement o, string name) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? (v.GetString() ?? string.Empty).Trim() : string.Empty;
private static uint UInt(JsonElement o, string name)
{
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return 0;
if (v.TryGetUInt32(out uint u)) return u;
return v.TryGetDouble(out double dbl) && dbl >= 0 && dbl <= uint.MaxValue && dbl == Math.Floor(dbl) ? (uint)dbl : 0;
}
private static int Int(JsonElement o, string name, int fallback)
{
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return fallback;
if (v.TryGetInt32(out int i)) return i;
return v.TryGetDouble(out double dbl) && dbl >= int.MinValue && dbl <= int.MaxValue ? (int)Math.Round(dbl) : fallback;
}
private static readonly HashSet<string> ReservedNames = new(StringComparer.OrdinalIgnoreCase)
{
"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$",
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
};
/// <summary>RynthLua's LibraryStorage.SafeFileName, so the suite names a character's file one way.</summary>
public static string SafeFileName(string? name)
{
var invalid = Path.GetInvalidFileNameChars();
var chars = (name ?? string.Empty).Trim().ToCharArray();
for (int i = 0; i < chars.Length; i++)
if (Array.IndexOf(invalid, chars[i]) >= 0 || chars[i] < 32) chars[i] = '_';
string n = new string(chars).TrimEnd('.', ' ');
if (n.Length > 80) n = n[..80].TrimEnd('.', ' ');
if (n.Length == 0 || n.Trim('.').Length == 0) n = "_" + n;
string stem = n.Split('.')[0];
if (ReservedNames.Contains(stem)) n = "_" + n;
return n;
}
}

View file

@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>
/// Which keys the engine's hotkey system has bound to a chat command, read from its file
/// (%LOCALAPPDATA%\RynthCore\hotkeys.txt, one binding a line: "on|off TAB combo TAB command TAB text",
/// the action "command" for a chat command). Read only: the plugin adds and removes bindings by
/// typing "/rc hotkey add|remove ..." to the engine, never by writing the file. The file is
/// shared by every client on the PC and the engine picks up changes within 2 s, so a binding
/// shows here a moment after it was made.
/// </summary>
internal sealed class HotkeyLookup
{
public const string EnvOverride = "RYNTHCORE_HOTKEYS_FILE";
private readonly Func<string> _path;
private DateTime _stamp = DateTime.MinValue;
private long _nextCheckMs;
private List<(string Combo, string Command, bool On)> _bindings = new();
public HotkeyLookup() : this(DefaultPath) { }
public HotkeyLookup(Func<string> path) => _path = path;
public static string DefaultPath()
{
if (Environment.GetEnvironmentVariable(EnvOverride) is { Length: > 0 } p) return p;
string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return Path.Combine(root, "RynthCore", "hotkeys.txt");
}
/// <summary>The combo bound to exactly this chat command ("/rdef use 3"), or null. Looks at the file at most once a second.</summary>
public string? KeyFor(string command, long nowMs)
{
Refresh(nowMs);
string want = Normalize(command);
foreach (var b in _bindings)
if (b.On && b.Command == want) return b.Combo;
foreach (var b in _bindings)
if (b.Command == want) return b.Combo + " (off)";
return null;
}
/// <summary>Forget what was read: the next lookup reads the file again.</summary>
public void Invalidate() { _stamp = DateTime.MinValue; _nextCheckMs = 0; }
private void Refresh(long nowMs)
{
if (nowMs < _nextCheckMs) return;
_nextCheckMs = nowMs + 1000;
try
{
string path = _path();
if (!File.Exists(path))
{
_bindings = new();
_stamp = DateTime.MinValue;
return;
}
DateTime stamp = File.GetLastWriteTimeUtc(path);
if (stamp == _stamp) return;
_stamp = stamp;
_bindings = Parse(File.ReadAllText(path));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// The engine is writing it right now: the old list stays, the next look tries again.
}
}
internal static List<(string Combo, string Command, bool On)> Parse(string? text)
{
var list = new List<(string, string, bool)>();
if (string.IsNullOrEmpty(text)) return list;
foreach (string raw in text.Split('\n'))
{
string line = raw.TrimEnd('\r');
if (line.Trim().Length == 0 || line.TrimStart().StartsWith('#')) continue;
string[] f = line.Split('\t', 4);
if (f.Length < 4) continue;
if (!f[2].Trim().Equals("command", StringComparison.OrdinalIgnoreCase)) continue;
string combo = f[1].Trim();
if (combo.Length == 0) continue;
list.Add((combo, Normalize(f[3]), !f[0].Trim().Equals("off", StringComparison.OrdinalIgnoreCase)));
}
return list;
}
private static string Normalize(string command) =>
string.Join(' ', (command ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant();
}

View file

@ -0,0 +1,164 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>
/// One item identity, as a slot, a favourite or a recent weapon keeps it: the object id it was
/// last seen with, and what the item IS (name, wcid, material) so another carried item of the same
/// identity can stand in when the object is gone (a used-up kit stack, a replaced weapon). The
/// icon ids are the last ones seen, to draw the item dimmed while none is carried.
/// </summary>
internal sealed class ItemRef
{
public uint Id;
public string Name = string.Empty;
public uint Wcid;
public int Material;
public uint Icon, Underlay, Overlay;
public static ItemRef From(CarriedItem it)
{
var r = new ItemRef();
r.CopyFrom(it);
return r;
}
/// <summary>Takes the item's identity and picture (the slot follows the item it is bound to).</summary>
public void CopyFrom(CarriedItem it)
{
Id = it.Id;
Name = it.Name;
Wcid = it.Wcid;
Material = it.Material;
if (it.Icon != 0) { Icon = it.Icon; Underlay = it.Underlay; Overlay = it.Overlay; }
}
public ItemRef Clone() => (ItemRef)MemberwiseClone();
public string FullName => ItemNames.Full(Name, Material);
/// <summary>
/// Whether <paramref name="it"/> is this item or another of the same kind: the same name (any
/// case), and the same wcid and material wherever both sides know them. The id is not part of
/// it - that is how a stack that was used up is replaced by the next one.
/// </summary>
public bool Matches(CarriedItem it)
{
if (!string.Equals(Name, it.Name, StringComparison.OrdinalIgnoreCase)) return false;
if (Wcid != 0 && it.Wcid != 0 && Wcid != it.Wcid) return false;
if (Material != 0 && it.Material != 0 && Material != it.Material) return false;
return true;
}
/// <summary>Two references to the same thing (the same id, or the same identity).</summary>
public bool SameAs(ItemRef other) =>
(Id != 0 && Id == other.Id) || (string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase)
&& Wcid == other.Wcid && Material == other.Material);
}
/// <summary>What a slot shows: the item it is bound to now, how many of it there are, and its state.</summary>
internal readonly record struct SlotStatus(CarriedItem? Item, int Count, int Uses, bool Rebound)
{
public bool Missing => Item == null;
}
/// <summary>Finding the carried item for a reference, and the counts a slot shows.</summary>
internal static class ItemMatcher
{
/// <summary>
/// The carried item for <paramref name="r"/>: the very object when it is still carried (and still
/// the same kind of item - an id can be reused), else another item of the same identity:
/// not wielded before wielded, then the smaller stack (a used-up stack is gone sooner and the
/// pack stays tidier), then the lower id. Null when nothing matches.
/// </summary>
public static CarriedItem? Find(ItemRef r, IReadOnlyList<CarriedItem> items, out bool rebound)
{
rebound = false;
if (string.IsNullOrEmpty(r.Name)) return null;
CarriedItem? best = null;
foreach (CarriedItem it in items)
{
if (!r.Matches(it)) continue;
if (it.Id == r.Id) return it;
if (best == null || Better(it, best)) best = it;
}
rebound = best != null;
return best;
}
private static bool Better(CarriedItem a, CarriedItem b)
{
if (a.Wielded != b.Wielded) return !a.Wielded;
if (a.Stack != b.Stack) return a.Stack < b.Stack;
return a.Id < b.Id;
}
/// <summary>The slot's item, how many of it are carried (stack sizes added up) and the uses left on them all.</summary>
public static SlotStatus Status(ItemRef r, IReadOnlyList<CarriedItem> items)
{
CarriedItem? it = Find(r, items, out bool rebound);
if (it == null) return new SlotStatus(null, 0, 0, false);
int count = 0, uses = 0;
foreach (CarriedItem other in items)
{
if (!r.Matches(other)) continue;
count += Math.Max(1, other.Stack);
if (other.MaxUses > 0) uses += Math.Max(0, other.Uses);
}
return new SlotStatus(it, count, uses, rebound);
}
/// <summary>
/// Keeps a slot's reference up to date with what is carried: bound to the object found (a
/// replacement after the old one is gone), with that object's name, picture and so on. A
/// missing item changes nothing. Returns whether the reference changed (the caller saves).
/// </summary>
public static bool Maintain(ItemRef r, IReadOnlyList<CarriedItem> items)
{
CarriedItem? it = Find(r, items, out _);
if (it == null) return false;
uint id = r.Id, icon = r.Icon, under = r.Underlay, over = r.Overlay;
int material = r.Material;
uint wcid = r.Wcid;
r.CopyFrom(it);
return id != r.Id || icon != r.Icon || under != r.Underlay || over != r.Overlay || material != r.Material || wcid != r.Wcid;
}
/// <summary>
/// Finds an item by what the player typed (/rdef use Peerless Healing Kit): the full name, the
/// name, then names that start with the text, then ones that contain it (every word); the
/// first by the same order as <see cref="Find"/>.
/// </summary>
public static CarriedItem? FindByName(string text, IReadOnlyList<CarriedItem> items)
{
string q = (text ?? string.Empty).Trim();
if (q.Length == 0) return null;
string[] words = q.Split(' ', StringSplitOptions.RemoveEmptyEntries);
CarriedItem? best = null;
int bestRank = int.MaxValue;
foreach (CarriedItem it in items)
{
int rank = NameRank(it, q, words);
if (rank == int.MaxValue) continue;
if (best == null || rank < bestRank || (rank == bestRank && Better(it, best)))
{
best = it;
bestRank = rank;
}
}
return best;
}
private static int NameRank(CarriedItem it, string q, string[] words)
{
string full = it.FullName;
if (string.Equals(full, q, StringComparison.OrdinalIgnoreCase)) return 0;
if (string.Equals(it.Name, q, StringComparison.OrdinalIgnoreCase)) return 1;
if (full.StartsWith(q, StringComparison.OrdinalIgnoreCase) || it.Name.StartsWith(q, StringComparison.OrdinalIgnoreCase)) return 2;
foreach (string w in words)
if (full.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) return int.MaxValue;
return 3;
}
}

View file

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>One line of the "pick from your pack" list: an item kind and how many of it are carried.</summary>
internal sealed record PackChoice(CarriedItem Item, int Count);
internal static class PackList
{
/// <summary>
/// The carried items for a slot to choose from: one line per kind of item (the same name, wcid
/// and material), with the stack sizes added up, A-Z, narrowed by the search words (all of them
/// must be in the name). At most <paramref name="max"/> lines; <paramref name="total"/> says how many matched.
/// </summary>
public static List<PackChoice> Build(IReadOnlyList<CarriedItem> items, string search, int max, out int total)
{
string[] words = (search ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
var byKind = new Dictionary<string, (CarriedItem Rep, int Count)>(StringComparer.OrdinalIgnoreCase);
foreach (CarriedItem it in items)
{
string full = it.FullName;
bool all = true;
foreach (string w in words)
if (full.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) { all = false; break; }
if (!all) continue;
string key = $"{full}|{it.Wcid}";
if (byKind.TryGetValue(key, out var have))
{
// The representative: not in hand, then the smaller stack (what a slot would pick).
CarriedItem rep = have.Rep;
if ((rep.Wielded && !it.Wielded) || (rep.Wielded == it.Wielded && it.Stack < rep.Stack)) rep = it;
byKind[key] = (rep, have.Count + Math.Max(1, it.Stack));
}
else byKind[key] = (it, Math.Max(1, it.Stack));
}
var list = new List<PackChoice>(byKind.Count);
foreach (var kv in byKind) list.Add(new PackChoice(kv.Value.Rep, kv.Value.Count));
list.Sort((a, b) => string.Compare(a.Item.FullName, b.Item.FullName, StringComparison.OrdinalIgnoreCase));
total = list.Count;
if (list.Count > max) list.RemoveRange(max, list.Count - max);
return list;
}
}

View file

@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthDefective.Items;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>One row of the weapon picker.</summary>
internal sealed record PickerRow(CarriedItem Item, WeaponGroup Group, string Element, bool InHand, bool Favourite);
/// <summary>A picker group: a kind of weapon and the rows under it.</summary>
internal sealed record PickerGroup(WeaponGroup Group, List<PickerRow> Rows);
/// <summary>What the picker shows: favourites and recent weapons first, then every kind.</summary>
internal sealed class PickerModel
{
public List<PickerRow> Favourites = new();
public List<PickerRow> Recent = new();
public List<PickerGroup> Groups = new();
/// <summary>Weapons carried (before the search and kind filter).</summary>
public int Total;
/// <summary>Rows that passed the search and the kind filter.</summary>
public int Shown;
}
/// <summary>
/// The weapon picker's list, pure: the carried weapons and wands grouped by kind (melee, missile,
/// war magic, void magic, then shields and ammunition), narrowed by the search words and the kind
/// filter. Favourites and the recently wielded come first, as shortcuts: they are also listed under
/// their kind, so a weapon is always where its kind says. Inside a group, A-Z by full name.
/// </summary>
internal static class WeaponPicker
{
public static PickerModel Build(IReadOnlyList<CarriedItem> items, IReadOnlyList<ItemRef> favourites,
IReadOnlyList<ItemRef> recent, string search, KindFilter filter)
{
var model = new PickerModel();
string[] words = (search ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
var rows = new List<PickerRow>();
foreach (CarriedItem it in items)
{
ItemKind kind = ItemKinds.Classify(it);
if (ItemKinds.GroupOf(kind) is not { } group) continue;
model.Total++;
if (!PassesFilter(group, filter)) continue;
if (!MatchesSearch(it, group, words)) continue;
rows.Add(new PickerRow(it, group, ItemKinds.Element(it), it.Wielded, IsFavourite(it, favourites)));
}
model.Shown = rows.Count;
rows.Sort(CompareRows);
foreach (WeaponGroup g in Enum.GetValues<WeaponGroup>())
{
var inGroup = rows.Where(r => r.Group == g).ToList();
if (inGroup.Count > 0) model.Groups.Add(new PickerGroup(g, inGroup));
}
// Shortcuts keep their own order: favourites as the player listed them, recent newest first.
foreach (ItemRef f in favourites)
AddFirstMatch(model.Favourites, rows, f);
foreach (ItemRef r in recent)
AddFirstMatch(model.Recent, rows, r);
return model;
}
private static void AddFirstMatch(List<PickerRow> into, List<PickerRow> rows, ItemRef r)
{
PickerRow? best = null;
foreach (PickerRow row in rows)
{
if (!r.Matches(row.Item)) continue;
if (row.Item.Id == r.Id) { best = row; break; }
best ??= row;
}
if (best != null && !into.Contains(best)) into.Add(best);
}
public static bool IsFavourite(CarriedItem it, IReadOnlyList<ItemRef> favourites)
{
foreach (ItemRef f in favourites)
if (f.Id == it.Id || f.Matches(it)) return true;
return false;
}
private static bool PassesFilter(WeaponGroup g, KindFilter f) => f switch
{
KindFilter.Melee => g == WeaponGroup.Melee,
KindFilter.Missile => g == WeaponGroup.Missile || g == WeaponGroup.Ammo,
KindFilter.War => g == WeaponGroup.WarMagic,
KindFilter.Void => g == WeaponGroup.VoidMagic,
_ => true,
};
/// <summary>Every search word is in the weapon's full name, its element or its kind's label.</summary>
private static bool MatchesSearch(CarriedItem it, WeaponGroup group, string[] words)
{
if (words.Length == 0) return true;
string full = it.FullName;
string element = ItemKinds.Element(it);
string label = ItemKinds.Label(group);
foreach (string w in words)
{
if (full.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) continue;
if (element.Length > 0 && element.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) continue;
if (label.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) continue;
return false;
}
return true;
}
private static int CompareRows(PickerRow a, PickerRow b)
{
int c = string.Compare(a.Item.FullName, b.Item.FullName, StringComparison.OrdinalIgnoreCase);
return c != 0 ? c : a.Item.Id.CompareTo(b.Item.Id);
}
public static string KindLabel(KindFilter f) => f switch
{
KindFilter.Melee => "Melee",
KindFilter.Missile => "Missile",
KindFilter.War => "War",
KindFilter.Void => "Void",
_ => "All",
};
}

View file

@ -0,0 +1,103 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective;
/// <summary>
/// C ABI exports. Nothing may throw out of an [UnmanagedCallersOnly] method (it would take
/// acclient.exe down): every export goes through RynthPluginRuntime, which catches and logs.
/// RynthDefective draws through the engine's script windows (host calls from its own tick), so it
/// exports no render callback and keeps no buffer the engine reads later.
/// </summary>
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<RynthDefectivePlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
// UTF-8 literals live in the module's read-only data: nothing to allocate or free.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => LiteralPointer("RynthDefective"u8);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => LiteralPointer("0.1.0"u8);
private static IntPtr LiteralPointer(ReadOnlySpan<byte> literal)
{
fixed (byte* p = literal)
return (IntPtr)p;
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) =>
Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
// ── The shortcut bar's window (plugin API v90; RynthDefectivePlugin.Bar.cs) ──
private static string? _sectionsJson;
private static IntPtr _sectionsPtr;
/// <summary>The sections manifest (polled every ~2 s): the bar's window. Kept until it changes.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetSectionsJson()
{
try
{
RynthDefectivePlugin? plugin = Runtime.Plugin;
if (plugin == null) return IntPtr.Zero;
string json = plugin.SectionsJson();
if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr;
_sectionsJson = json;
IntPtr fresh = Marshal.StringToCoTaskMemUTF8(json);
IntPtr old = System.Threading.Interlocked.Exchange(ref _sectionsPtr, fresh);
if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old);
return fresh;
}
catch { return IntPtr.Zero; }
}
/// <summary>The bar's and the panel buttons' window bodies ("window:bar", "window:panels"; ":popout" when popped out). 1 drawn, 0 not ready, -2 failed.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })]
public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight)
{
try
{
if (surface == null) return 0;
string name = Marshal.PtrToStringUTF8((IntPtr)surface) ?? string.Empty;
bool popped = name.EndsWith(":popout", StringComparison.Ordinal);
if (popped) name = name[..^":popout".Length];
RynthDefectivePlugin? plugin = Runtime.Plugin;
if (plugin == null) return 0;
int result;
float wantH;
if (name == RynthDefectivePlugin.BarSurface) result = plugin.RenderBar(popped, out wantH);
else if (name == RynthDefectivePlugin.PanelsSurface) result = plugin.RenderPanels(out wantH);
else if (name == RynthDefectivePlugin.SelectionSurface) result = plugin.RenderSelection(out wantH);
else return 0;
if (result != 1) return result;
if (wantWidth != null) *wantWidth = width;
if (wantHeight != null) *wantHeight = wantH > 0 ? wantH : height;
return 1;
}
catch { return 0; }
}
}

View file

@ -0,0 +1,93 @@
# RynthDefective
An item bar for RynthCore with one-touch use, and a fast weapon picker. Version 0.1.0.
Credit: RynthDefective is an independent implementation of the ideas of **Defective**, the Decal
item-bar plugin written by Hazridi and modified by Aun (<https://github.com/aunrela/Defective>). It
contains no code from it: it was written from the plugin's public feature description
against RynthCore's own APIs. (Defective's repository states no licence; ask Aun if you want a
literal port or shared code.)
## What it does
**Slots.** The bar is a row (or grid) of slots, each holding one item: a healing kit, a stamina kit,
a potion, a scroll, a weapon, a wand, a shield... Click a slot, or press its key, and the item is used
**without selecting anything in the game**:
| Item | What a press does |
| --- | --- |
| Healing / stamina kit | used on yourself |
| Potion, scroll, food, gem, anything else | used (a double-click) |
| Weapon, wand, shield, armor, jewelry | wielded / worn (a double-click); an item already in hand is left alone |
A slot can be set to another way: use it, use it on me, use it on the selected target, or wield it.
**Put an item in a slot** (Edit slots in the bar): *Set from selected* takes the item you have selected
in the game, or *Pick from pack* chooses from a searchable list of what you carry. `/rdef set 3` does the
first, `/rdef set 3 Health Potion` the second.
**A slot keeps the item's identity, not just the object.** It remembers the item's name, wcid and
material as well as its object id. When the exact object is gone (a used-up stack, a replaced weapon)
the slot uses another carried item of the same identity: not in hand before in hand, the smaller stack
first. A slot with nothing to use shows the last picture seen, dimmed, and "none"; it fills itself again
when you carry another.
**Counts.** Under each slot: the uses left on all the kits of that kind (28), the stack count (x120), "in
hand" for the weapon you hold, "none" when none is carried, and the slot's key.
**Keys.** Keys are the engine's hotkeys running `/rdef use <slot>`. Type a key in the slot editor (F9,
Ctrl+1, Alt+Shift+Num3) and press *Bind to this slot* (follows the slot) or *Bind to this item* (runs
`/rdef use <the item's name>`, works for every character on this PC). The same from chat: `/rdef bind 3 F9`.
Any item can also be bound by name straight from Settings > Hotkeys or `/rc hotkey add F9 /rdef use Stamina Kit`.
`/rdef use <name>` takes a full name, the start of a name or words in it ("Greater Stamina Kit",
"stamina kit"); of several matches the one not in hand, with the smaller stack, then the lower id, is used.
**The weapon picker** (the *Weapons* button, `/rdef weapons [search]`): every weapon, wand, shield and ammunition
stack you carry, as big rows with the item's picture, grouped by kind (melee, missile, war magic, void
magic, shields, ammunition), A-Z. Type words in the search box ("fire wand", "axe", "void"); the kind
buttons (All, Melee, Missile, War, Void) narrow it, and the one you leave pressed is remembered. The weapon in
hand is highlighted. **One click wields.** `+` in front of a row adds a favourite; favourites and the last
weapons you wielded are listed first (they are also in their kind's group).
## Busy, combat and RynthAi
* One item action at a time: a request waits while the client is busy, a gesture animates, RynthAi waits on
the server, or the last action is unanswered (the server's UseDone; a wield is answered by the item
reading in hand). Pressing again while one waits does not queue a second; pressing another slot replaces the
waiting one. A request not sent within 6 s gives up and says why.
* After a wield from a fighting stance the stance follows the weapon (wand: magic, melee weapon: melee,
launcher with ammunition in hand: missile) once the character is still. At peace you stay at peace. A bow
without arrows in hand returns you to peace rather than leaving a stance it can't use. Shields, armor and
rings leave the stance alone.
* While RynthAi's macro runs, weapons/wands/shields are **not** wielded (it picks the weapon itself and would
swap back) unless *Allow weapon swaps while RynthAi's macro runs* is on. Kits, potions and the rest always work.
## Commands
```
/rdef show / hide the bar
/rdef use <slot | item name> use the slot's item, or the carried item with that name
/rdef set <slot> [item name] put the selected item (or the named one) in a slot
/rdef clear <slot> empty a slot
/rdef bind <slot> <key> bind a key (F9, Ctrl+1 ...) to the slot; /rdef unbind <slot>
/rdef weapons [search] show the weapon picker
/rdef fav make the selected weapon a favourite (or take it out)
/rdef slots <n> how many slots (1-24)
/rdef list | status | help
```
## Settings
Slots (1-24), slots per row, button size, picker row icon size, item icons on/off, counts and keys on/off,
allow weapon swaps under RynthAi. Kept per character with the slots, favourites and recent weapons in
`<RynthSuite>\RynthDefective\characters\<server>_<character>.json`.
## Not in 0.1
Pages, spell slots, arrow auto-equip, gear highlight, summon cooldown counters and the war-magic element
changer (Defective has them).
## Needs
RynthCore engine API 71 with ImGui for the windows (op level 2 for pictures; text buttons without it).
`/rdef use` works on any engine with UseObject.

View file

@ -0,0 +1,64 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
RynthDefective: an item bar with one-touch use, and a fast weapon picker. Slots hold one
item each (a kit, a potion, a weapon...): clicking a slot or pressing its key uses it without
selecting anything in the game; a slot that loses its exact item takes another carried item
of the same name. The picker lists every carried weapon and wand by kind, with a search box,
favourites and the recently used, and wields one with one click. Keys are the engine's
hotkeys running /rdef use <slot or item name>; /rdef. An independent implementation of the
ideas of Defective, the Decal plugin by Hazridi / Aun (no code from it). UI: the engine's
script windows (ImGui), no Avalonia.
-->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.RynthDefective</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthDefective</AssemblyName>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Script windows (v71, HasUi, op level 2 for
pictures) are checked first; so are the UseDone count (v63), wield/refusal info (v70) and
the chat parser the key binding goes through. Below v71 it still uses items (/rdef use). -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Item bar: one-touch use of kits, potions and weapons by slot or key, and a fast weapon picker.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>
<!-- What RynthAi is doing (read only), so a weapon swap stays out of its way. -->
<Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<!-- An older RynthAi without RynthAi.Activity: its RynthAi.Status macro bit instead. -->
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
</ItemGroup>
<ItemGroup>
<!-- The shortcut bar (2026-10-22): drawn with ImGui.NET bound to the engine's cimgui, in the
engine's look (Shared\RynthUi; plugin API v90 hosts the frameless window and gives AC's
shortcut slots, keys and item pictures). -->
<Compile Include="..\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<Compile Include="..\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
<Compile Include="..\Shared\RynthUi\RynthUi.cs" Link="Shared\RynthUi\RynthUi.cs" />
<Compile Include="..\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthUi\RynthIcons.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
<TrimmerRootAssembly Include="ImGui.NET" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,195 @@
// ============================================================================
// RynthDefective - RynthDefectivePlugin.Bar.cs
// The shortcut bar (2026-10-22), in place of AC's retail toolbar: RynthCore
// hosts a frameless window (sections manifest, plugin API v90) and RynthDefective
// draws it (ShortcutBar/ShortcutBarWindow.cs). Its first 18 slots are AC's own
// (the retail toolbar's items and AC's keys, so both always agree), the rest
// this plugin's slots. On an engine without v90's shortcuts the old script
// window bar stays.
//
// The tick: the window's clicks (queued from the render thread), the snapshot
// it draws (4 times a second while it shows).
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Globalization;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.ShortcutBar;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective;
public sealed partial class RynthDefectivePlugin : IBarActions
{
internal const string BarSurface = "window:bar", PanelsSurface = "window:panels";
private BarSnapshotBuilder? _barBuilder;
private ShortcutBarWindow? _shortcutBar; // render thread
private PanelButtonsWindow? _panelButtons; // render thread
private int _panelsFailures;
private volatile BarSnapshot _barView = BarSnapshot.NotReady; // tick writes, render reads
private readonly ConcurrentQueue<Action> _barActions = new();
private long _barDrawnMs = long.MinValue / 2, _nextBarBuildMs;
private int _barFailures;
/// <summary>The engine has v90's shortcuts and frameless windows: the new bar, not the script window one.</summary>
internal bool UsesShortcutBar => Host.HasShortcuts && Host.HasFramelessWindows;
/// <summary>AC's panels can be opened from here: the engine has v90's AcPanel (the buttons in the corner).</summary>
internal bool UsesPanelButtons => UsesShortcutBar && Host.HasAcPanels;
/// <summary>The sections manifest: the bar's window and the panel buttons' (only on an engine that has what they need).</summary>
internal string SectionsJson()
{
if (!UsesShortcutBar) return "{\"version\":1}";
string bar = "{\"id\":\"bar\",\"title\":\"" + ShortcutBarWindow.Title + "\",\"surface\":\"" + BarSurface +
"\",\"icon\":\"\\u" + ((int)RynthIcons.Lightning[0]).ToString("X4", CultureInfo.InvariantCulture) +
"\",\"width\":420,\"height\":120,\"minWidth\":90,\"minHeight\":40,\"bar\":true,\"edgeToEdge\":true," +
"\"chrome\":\"none\",\"fitHeight\":true,\"scale\":\"draw\"}";
// Nine 22-unit buttons and the grip in a row, first in the bottom-right corner.
string panels = !UsesPanelButtons ? "" :
",{\"id\":\"panels\",\"title\":\"" + PanelButtonsWindow.Title + "\",\"surface\":\"" + PanelsSurface +
"\",\"icon\":\"\\u" + ((int)RynthIcons.SquaresFour[0]).ToString("X4", CultureInfo.InvariantCulture) +
"\",\"width\":236,\"height\":30,\"minWidth\":30,\"minHeight\":20,\"bar\":false,\"edgeToEdge\":true," +
"\"chrome\":\"none\",\"fitHeight\":true,\"corner\":\"bottomRight\",\"scale\":\"draw\"}";
// What is selected and its health, first at the top centre.
string selection = ",{\"id\":\"selection\",\"title\":\"" + SelectionWindow.Title + "\",\"surface\":\"" + SelectionSurface +
"\",\"icon\":\"\\u" + ((int)RynthIcons.Crosshair[0]).ToString("X4", CultureInfo.InvariantCulture) +
"\",\"width\":280,\"height\":46,\"minWidth\":120,\"minHeight\":24,\"bar\":false,\"edgeToEdge\":true," +
"\"chrome\":\"none\",\"fitHeight\":true,\"corner\":\"top\",\"scale\":\"draw\"}";
return "{\"version\":1,\"windows\":[" + bar + panels + selection + "]}";
}
/// <summary>RynthPluginRenderEmbed "window:panels". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>
internal int RenderPanels(out float wantHeight)
{
wantHeight = 0;
if (!UsesPanelButtons) return 0;
try
{
_panelButtons ??= new PanelButtonsWindow(Host);
wantHeight = _panelButtons.Draw();
_panelsFailures = 0;
return 1;
}
catch (Exception ex)
{
Host.Log($"[RynthDefective] panel buttons draw failed: {ex.GetType().Name}: {ex.Message}");
return ++_panelsFailures >= 3 ? -2 : 0;
}
}
/// <summary>RynthPluginRenderEmbed "window:bar". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>
internal int RenderBar(bool popped, out float wantHeight)
{
wantHeight = 0;
if (!UsesShortcutBar) return 0;
System.Threading.Volatile.Write(ref _barDrawnMs, Environment.TickCount64);
try
{
_shortcutBar ??= new ShortcutBarWindow(Host, this);
wantHeight = _shortcutBar.Draw(_barView, popped);
_barFailures = 0;
return 1;
}
catch (Exception ex)
{
Host.Log($"[RynthDefective] shortcut bar draw failed: {ex.GetType().Name}: {ex.Message}");
return ++_barFailures >= 3 ? -2 : 0;
}
}
/// <summary>Plugin tick: the bar's clicks, then its snapshot while it shows.</summary>
private void TickBar(long now)
{
while (_barActions.TryDequeue(out Action? act))
{
try { act(); }
catch (Exception ex) { Host.Log($"[RynthDefective] bar action failed: {ex.GetType().Name}: {ex.Message}"); }
}
if (!UsesShortcutBar || !_identityKnown) return;
bool shown = now - System.Threading.Volatile.Read(ref _barDrawnMs) < 2000;
if (!shown || now < _nextBarBuildMs) return;
_nextBarBuildMs = now + 250;
_barBuilder ??= new BarSnapshotBuilder(Host);
_barView = _barBuilder.Build(_session, _session.Items(), now);
}
private void QueueBar(Action action)
{
if (_barActions.Count < 32) _barActions.Enqueue(action);
}
private static bool IsRetail(int number) => number <= DefSettings.RetailSlots;
// ── IBarActions (render thread: queue only) ─────────────────────────────
public void Use(int number) => QueueBar(() =>
{
if (IsRetail(number))
{
if (!Host.ShortcutAction(RynthShortcutOp.Use, number - 1)) _session.SetStatus($"Slot {number} can't be used now.", warning: true);
return;
}
string? problem = _session.UseSlot(number - DefSettings.RetailSlots);
if (problem != null) { _session.SetStatus(problem, warning: true); Print(problem); }
});
public void SetFromSelected(int number) => QueueBar(() =>
{
if (IsRetail(number))
{
uint sel = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0;
if (sel == 0) { Print("Select the item in the game first, then put it in the slot."); return; }
if (!Host.ShortcutAction(RynthShortcutOp.Set, number - 1, sel)) Print($"Slot {number} can't be changed now.");
_nextBarBuildMs = 0;
return;
}
Print(_session.SetFromSelected(number - DefSettings.RetailSlots));
_nextBarBuildMs = 0;
});
public void Clear(int number) => QueueBar(() =>
{
if (IsRetail(number))
{
if (!Host.ShortcutAction(RynthShortcutOp.Clear, number - 1)) Print($"Slot {number} can't be changed now.");
_nextBarBuildMs = 0;
return;
}
Print(_session.ClearSlot(number - DefSettings.RetailSlots));
_nextBarBuildMs = 0;
});
public void DropItem(int number, uint objectId) => QueueBar(() =>
{
if (IsRetail(number))
{
// The retail toolbar's own "make a shortcut": AC checks the item (and says why not).
if (!Host.ShortcutAction(RynthShortcutOp.Set, number - 1, objectId)) Print($"Slot {number} can't be changed now.");
}
else Print(_session.SetFromId(number - DefSettings.RetailSlots, objectId));
_nextBarBuildMs = 0;
});
public void ChangeSlotCount(int delta) => QueueBar(() =>
{
DefSettings st = _session.Settings;
st.BarSlots = Math.Clamp(st.BarSlots + delta, DefSettings.BarSlotsMin, DefSettings.BarSlotsMax);
RequestSave();
_nextBarBuildMs = 0;
});
public void KeysChanged() => QueueBar(() =>
{
_barBuilder?.InvalidateKeys();
_session.Keys.Invalidate();
_nextBarBuildMs = 0;
});
public void ShowWeapons() => QueueBar(() => ShowPicker(true));
public void Hide() => QueueBar(() => Host.SetPanelOpen(ShortcutBarWindow.Title, RynthPanelOpen.Close));
}

View file

@ -0,0 +1,120 @@
// ============================================================================
// RynthDefective - RynthDefectivePlugin.Selection.cs
// The Selection window (2026-10-22): what is selected, how far and which way,
// and a creature's health, as the retail toolbar showed it
// (ShortcutBar/SelectionWindow.cs draws it).
//
// The tick builds the view 10 times a second: the selected object
// (GetSelectedItemId), its name, where it is from the player (positions in
// landblock coordinates: 192 units a landblock; the facing from the player's
// pose, as RynthAi's combat turns), and its health from AC's health updates
// (OnUpdateHealth), asked for when a creature is selected and every 2 s after.
// ============================================================================
using System;
using System.Globalization;
using RynthCore.Plugin.RynthDefective.ShortcutBar;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective;
public sealed partial class RynthDefectivePlugin
{
internal const string SelectionSurface = "window:selection";
private SelectionWindow? _selectionWindow; // render thread
private volatile SelectionView _selectionView = SelectionView.NotReady;
private long _selectionDrawnMs = long.MinValue / 2, _nextSelectionMs, _nextHealthQueryMs;
private uint _selectionId;
private int _selectionFailures;
// The last health AC sent for the selected object (game thread writes, tick reads).
private volatile HealthSeen? _health;
private sealed record HealthSeen(uint Id, float Ratio, uint Current, uint Max);
private const uint CreatureType = 0x10; // ItemType.Creature
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
{
if (targetId != 0 && targetId == _selectionId)
_health = new HealthSeen(targetId, healthRatio, currentHealth, maxHealth);
}
/// <summary>RynthPluginRenderEmbed "window:selection". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>
internal int RenderSelection(out float wantHeight)
{
wantHeight = 0;
if (!UsesShortcutBar) return 0;
System.Threading.Volatile.Write(ref _selectionDrawnMs, Environment.TickCount64);
try
{
_selectionWindow ??= new SelectionWindow(Host, id => QueueBar(() => { if (!Host.UseObject(id)) Print("That can't be used now."); }));
wantHeight = _selectionWindow.Draw(_selectionView);
_selectionFailures = 0;
return 1;
}
catch (Exception ex)
{
Host.Log($"[RynthDefective] selection draw failed: {ex.GetType().Name}: {ex.Message}");
return ++_selectionFailures >= 3 ? -2 : 0;
}
}
/// <summary>Plugin tick: the selection's view while its window shows.</summary>
private void TickSelection(long now)
{
if (!UsesShortcutBar || !_identityKnown) return;
if (now - System.Threading.Volatile.Read(ref _selectionDrawnMs) > 2000 || now < _nextSelectionMs) return;
_nextSelectionMs = now + 100;
try { _selectionView = BuildSelection(now); }
catch (Exception ex) { Host.Log($"[RynthDefective] selection read failed: {ex.GetType().Name}: {ex.Message}"); }
}
private SelectionView BuildSelection(long now)
{
uint sel = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0;
bool changed = sel != _selectionId;
_selectionId = sel;
if (changed) _health = null;
if (sel == 0) return new SelectionView(true, 0, string.Empty, string.Empty, float.NaN, -1f, 0, 0);
string name = Host.TryGetObjectName(sel, out string n) && n.Length > 0 ? n : $"0x{sel:X8}";
bool creature = Host.TryGetItemType(sel, out uint type) && (type & CreatureType) != 0;
if (creature && (changed || now >= _nextHealthQueryMs))
{
_nextHealthQueryMs = now + 2000;
Host.QueryHealth(sel);
}
string where = string.Empty;
float relative = float.NaN;
bool carried = false;
foreach (var it in _session.Items()) if (it.Id == sel) { carried = true; break; }
if (carried) where = "in your pack";
else if (Host.TryGetObjectPosition(sel, out uint oc, out float ox, out float oy, out float oz) && oc != 0
&& Host.TryGetPlayerPose(out uint pc, out float px, out float py, out float pz, out float qw, out _, out _, out float qz) && pc != 0)
{
double dx = Global(oc, ox, true) - Global(pc, px, true), dy = Global(oc, oy, false) - Global(pc, py, false), dz = oz - pz;
double dist = Math.Sqrt(dx * dx + dy * dy + dz * dz);
double bearing = Math.Atan2(dx, dy) * 180.0 / Math.PI;
if (bearing < 0) bearing += 360.0;
double facing = ((-2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI) % 360.0 + 720.0) % 360.0;
double rel = bearing - facing;
while (rel > 180) rel -= 360;
while (rel < -180) rel += 360;
if (dist >= 0.5) relative = (float)rel;
where = $"{dist.ToString(dist < 10 ? "0.0" : "0", CultureInfo.InvariantCulture)} yd {Compass(bearing)}";
}
HealthSeen? h = _health;
float health = h != null && h.Id == sel ? h.Ratio : -1f;
return new SelectionView(true, sel, name, where, relative, health, h?.Current ?? 0, h?.Max ?? 0);
}
/// <summary>A landblock coordinate as a world one: 192 units a landblock (the cell's high bytes).</summary>
private static double Global(uint cell, float local, bool x) =>
((x ? cell >> 24 : cell >> 16) & 0xFF) * 192.0 + local;
private static readonly string[] Points = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" };
private static string Compass(double bearing) => Points[(int)Math.Round(bearing / 45.0) % 8];
}

View file

@ -0,0 +1,429 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
using RynthCore.Plugin.RynthDefective.Use;
using RynthCore.Plugin.RynthDefective.Views;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective;
/// <summary>
/// RynthDefective: an item bar with one-touch use, and a fast weapon picker.
///
/// A slot holds one item identity (Model/ItemRef.cs: the object id, plus name, wcid and material).
/// Pressing the slot, or the key the engine's hotkeys bind to "/rdef use N", uses the item without
/// anything selected in the game: a kit on yourself, a potion or scroll by itself, a weapon or wand
/// wielded (Use/UseController.cs has the rules, the busy handling and the stance). When the exact
/// object is gone the slot follows another carried item of the same identity.
///
/// The weapon picker window lists the carried weapons and wands by kind, with search, favourites and
/// the recently wielded, and wields one with one click.
///
/// Everything runs on the plugin pump (OnTick and the events the engine drains into it) except
/// OnChatBarEnter, which the engine may call on AC's thread: it only queues the command.
/// </summary>
public sealed partial class RynthDefectivePlugin : RynthPluginBase
{
public const string Version = "0.1.0";
private const long IdentityRetryMs = 1000;
private const long SaveDelayMs = 750;
private const long PassIntervalMs = 400;
private const long InventoryAgeMs = 700;
private readonly DefStore _store = new();
private readonly DefSession _session;
private readonly UiHost _ui = new();
private readonly ConcurrentQueue<string> _commands = new();
private HostDefWorld? _world;
private BarView? _bar;
private PickerView? _picker;
private UiWindow? _barWindow, _pickerWindow;
private bool _inWorld;
private bool _identityKnown;
private long _nextIdentityTryMs;
private string _server = string.Empty;
private string _character = string.Empty;
private long _saveDueMs;
private bool _noUiLogged;
private int _revisionSeen = -1;
public RynthDefectivePlugin()
{
_session = new DefSession(new HotkeyLookup());
}
public override int Initialize()
{
_ui.Log = msg => Host.Log(msg);
// The shortcut bar (plugin API v90) draws with ImGui.NET bound to the engine's cimgui, in its look.
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log("[RynthDefective] " + msg));
RynthCore.Plugin.Shared.RynthUi.RynthUi.Init(Host);
_world = new HostDefWorld(Host);
_session.Items = () => _world.Snapshot(InventoryAgeMs);
_session.SelectedId = () => Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0;
_session.RunChat = line => Host.HasInvokeChatParser && Host.InvokeChatParser(line);
_session.Save = RequestSave;
_session.Use.Say = text => { _session.SetStatus(text); Host.Log("[RynthDefective] " + text); };
_session.Use.Warn = text => { _session.SetStatus(text, warning: true); Print(text); };
_session.Use.Log = line => Host.Log(line);
_session.Use.Wielded = OnWielded;
_bar = new BarView(_session);
_picker = new PickerView(_session);
_barWindow = _ui.Add(new UiWindow("RynthDefective/Bar", "Defective") { DefaultWidth = 330f, DefaultHeight = 160f, MinWidth = 220f, MinHeight = 100f });
_pickerWindow = _ui.Add(new UiWindow("RynthDefective/Weapons", "Defective Weapons") { DefaultWidth = 360f, DefaultHeight = 480f, MinWidth = 260f, MinHeight = 160f });
_bar.RequestFit = FitBar;
_bar.ShowPicker = () => ShowPicker(true);
Host.Log($"[RynthDefective] {Version} initialized. /rdef shows or hides the bar; /rdef use <slot or item name>; /rdef help. Files: {_store.Root}");
return 0;
}
// The engine calls this on a real login and on a freshly (re)loaded plugin already in game.
public override void OnLoginComplete()
{
_inWorld = true;
_identityKnown = false;
_nextIdentityTryMs = Environment.TickCount64;
_session.Use.Reset();
_world?.Reset();
}
public override void OnLogout()
{
SaveNow();
_inWorld = false;
_identityKnown = false;
_session.LoggedIn = false;
_session.Use.Reset();
_world?.Reset();
_barView = RynthCore.Plugin.RynthDefective.ShortcutBar.BarSnapshot.NotReady;
foreach (UiWindow? w in new[] { _barWindow, _pickerWindow })
if (w != null) { w.Visible = false; w.NeedsPass = true; }
_ui.SubmitEmpty(Host);
}
public override void Shutdown()
{
SaveNow();
_session.Use.Reset();
_ui.SubmitEmpty(Host);
}
// ── Chat ────────────────────────────────────────────────────────────────
// May run on AC's thread: classify and queue only.
public override void OnChatBarEnter(string? text, ref int eat)
{
if (string.IsNullOrWhiteSpace(text)) return;
string t = text.Trim();
if (!t.StartsWith("/rdef", StringComparison.OrdinalIgnoreCase) || (t.Length > 5 && !char.IsWhiteSpace(t[5])))
return;
eat = 1;
_commands.Enqueue(t.Length > 5 ? t.Substring(5).Trim() : string.Empty);
}
private void RunCommand(string arg)
{
DefCommand c = DefCommandParser.Parse(arg);
if (c.Verb == DefVerb.Help)
{
PrintHelp();
return;
}
if (c.Verb == DefVerb.Error)
{
Print(c.Error);
return;
}
if (!_identityKnown)
{
Print("Log in first.");
return;
}
switch (c.Verb)
{
case DefVerb.Toggle:
if (UsesShortcutBar)
Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.ShortcutBarWindow.Title, RynthPanelOpen.Toggle);
else if (_barWindow != null) { _barWindow.Visible = !_barWindow.Visible; _barWindow.NeedsPass = true; NoteNoUi(_barWindow.Visible); }
break;
case DefVerb.Selection when c.Text.Length > 0:
if (uint.TryParse(c.Text.Replace("0x", "", StringComparison.OrdinalIgnoreCase), System.Globalization.NumberStyles.HexNumber, null, out uint pick))
Host.SelectItem(pick);
break;
case DefVerb.Selection:
if (UsesShortcutBar) Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.SelectionWindow.Title, RynthPanelOpen.Toggle);
else Print("This RynthCore can't show the selection window (it needs plugin API v90).");
break;
case DefVerb.Panels:
if (UsesPanelButtons) Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.PanelButtonsWindow.Title, RynthPanelOpen.Toggle);
else Print("This RynthCore can't open the game's panels from buttons (it needs plugin API v90).");
break;
case DefVerb.Weapons:
if (c.Text.Length > 0 && _picker != null) _picker.Search = c.Text;
ShowPicker(c.Text.Length > 0 || _pickerWindow?.Visible != true);
break;
case DefVerb.Use:
if (c.Slot > 0)
{
string? problem = _session.UseSlot(c.Slot);
if (problem != null) { _session.SetStatus(problem, warning: true); Print(problem); }
}
else _session.UseByName(c.Text);
break;
case DefVerb.Set:
Print(c.Text.Length > 0 ? _session.SetFromName(c.Slot, c.Text) : _session.SetFromSelected(c.Slot));
break;
case DefVerb.Clear:
Print(_session.ClearSlot(c.Slot));
break;
case DefVerb.Bind:
Print(_session.BindKey(c.Slot, c.Text, byName: false));
break;
case DefVerb.Unbind:
Print(_session.UnbindKey(c.Slot));
break;
case DefVerb.Favourite:
Print(_session.ToggleSelectedFavourite());
break;
case DefVerb.Slots:
_session.SetSlotCount(c.Slot);
FitBar();
Print($"{_session.Settings.SlotCount} slots.");
break;
case DefVerb.List:
PrintSlots();
break;
case DefVerb.Status:
PrintStatus();
break;
}
MarkAllForPass();
}
private void PrintHelp()
{
Print(DefCommandParser.Usage);
Print("A key for a slot: /rdef bind 1 F9 (or Edit slots in the bar). Any item by name from Settings > Hotkeys: /rc hotkey add F9 /rdef use Stamina Kit.");
}
private void PrintSlots()
{
IReadOnlyList<CarriedItem> items = _session.Items();
var sb = new StringBuilder();
for (int i = 1; i <= _session.Settings.SlotCount; i++)
{
DefSlot slot = _session.Data.Slots[i - 1];
if (slot.Item == null) { Print($"{i}: (empty)"); continue; }
SlotStatus s = ItemMatcher.Status(slot.Item, items);
sb.Clear();
sb.Append(i).Append(": ").Append(slot.Item.FullName);
string count = SlotText.Count(s, out _);
if (count.Length > 0) sb.Append(" (").Append(count).Append(')');
if (_session.KeyOfSlot(i) is { } key) sb.Append(" [").Append(key).Append(']');
Print(sb.ToString());
}
}
private void PrintStatus()
{
int filled = 0;
for (int i = 0; i < _session.Settings.SlotCount; i++) if (!_session.Data.Slots[i].Empty) filled++;
Print($"{_character}: {filled}/{_session.Settings.SlotCount} slots set, {_session.Data.Favourites.Count} favourite weapons; "
+ $"{(_session.Use.InFlight ? "an action is in flight" : _session.Use.HasPending ? "an action is waiting" : "idle")}; file {_store.PathFor(_server, _character)}");
}
private void Print(string text)
{
if (!Host.WriteToChat("[RynthDefective] " + text, 1))
Host.Log("[RynthDefective] " + text);
}
private void NoteNoUi(bool shown)
{
if (shown && !Host.HasUi && !_noUiLogged)
{
_noUiLogged = true;
Print("This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). /rdef use <slot or item name> still works.");
}
}
// ── Windows ─────────────────────────────────────────────────────────────
private void ShowPicker(bool visible)
{
if (_pickerWindow == null) return;
_pickerWindow.Visible = visible;
_pickerWindow.NeedsPass = true;
NoteNoUi(visible);
}
private void FitBar()
{
if (_barWindow == null || _bar == null) return;
(float w, float h) = _bar.WantedSize();
_barWindow.RequestWidth = w;
_barWindow.RequestHeight = h;
_barWindow.NeedsPass = true;
}
private void MarkAllForPass()
{
if (_barWindow != null) _barWindow.NeedsPass = true;
if (_pickerWindow != null) _pickerWindow.NeedsPass = true;
}
/// <summary>A weapon (or shield) went into the hands: first in the picker's recent list.</summary>
private void OnWielded(CarriedItem it)
{
ItemKind kind = ItemKinds.Classify(it);
if (!ItemKinds.IsWeapon(kind) && kind != ItemKind.Shield) return;
_session.Data.NoteRecent(ItemRef.From(it));
RequestSave();
}
// ── Tick ────────────────────────────────────────────────────────────────
public override void OnTick()
{
long now = Environment.TickCount64;
while (_commands.TryDequeue(out string? cmd))
{
try { RunCommand(cmd); }
catch (Exception ex) { Host.Log($"[RynthDefective] /rdef {cmd} failed: {ex.GetType().Name}: {ex.Message}"); }
}
_ui.Poll(Host);
if (_inWorld)
{
if (!_identityKnown && now >= _nextIdentityTryMs) TryStartCharacter(now);
if (_identityKnown && _world != null)
{
try
{
TickInventory();
_session.Use.Tick(_world);
}
catch (Exception ex)
{
Host.Log($"[RynthDefective] tick failed: {ex.GetType().Name}: {ex.Message}");
}
}
}
if (_saveDueMs != 0 && now >= _saveDueMs) SaveNow();
TickBar(now);
TickSelection(now);
// With the shortcut bar the old script-window bar stays shut (the weapon picker is still one).
if (UsesShortcutBar && _barWindow != null && _barWindow.Visible) { _barWindow.Visible = false; _barWindow.NeedsPass = true; }
if (!Host.HasUi || _barWindow == null || _pickerWindow == null || _bar == null || _picker == null) return;
if (_session.Use.HasPending || _session.Use.InFlight) _barWindow.NeedsPass = _pickerWindow.NeedsPass = true;
if (!_session.IconsAvailable) RefreshIconSupport();
Record(_barWindow, now, _bar.Draw);
Record(_pickerWindow, now, _picker.Draw);
_ui.Submit(Host, now);
if (_identityKnown)
{
DefSettings st = _session.Settings;
if (_barWindow.Visible != st.BarOpen || _pickerWindow.Visible != st.PickerOpen)
{
st.BarOpen = _barWindow.Visible;
st.PickerOpen = _pickerWindow.Visible;
RequestSave();
}
}
}
/// <summary>Re-reads the inventory while a window shows or an action waits; slots follow their items.</summary>
private void TickInventory()
{
bool barShown = Environment.TickCount64 - System.Threading.Volatile.Read(ref _barDrawnMs) < 2000;
bool wanted = (_barWindow?.Visible ?? false) || (_pickerWindow?.Visible ?? false) || barShown || _session.Use.HasPending;
if (!wanted || _world == null) return;
List<CarriedItem> items = _world.Snapshot(InventoryAgeMs);
if (_world.Revision == _revisionSeen) return;
_revisionSeen = _world.Revision;
if (_session.Maintain(items)) RequestSave();
MarkAllForPass();
}
private void TryStartCharacter(long now)
{
_nextIdentityTryMs = now + IdentityRetryMs;
uint player = Host.GetPlayerId();
if (player == 0 || !Host.TryGetObjectName(player, out string name) || string.IsNullOrWhiteSpace(name)) return;
string server = Host.TryGetWorldName(out string w) ? w : string.Empty;
_server = server;
_character = name;
DefData data = _store.Load(server, name, out string? problem);
if (problem != null) Host.Log($"[RynthDefective] couldn't read the saved slots ({problem}); using defaults.");
_session.Data = data;
_session.Use.Settings = data.Settings;
_session.Character = name;
_session.LoggedIn = true;
_identityKnown = true;
_revisionSeen = -1;
RefreshIconSupport();
if (_barWindow != null && _bar != null)
{
_barWindow.Visible = data.Settings.BarOpen;
(float bw, float bh) = _bar.WantedSize();
_barWindow.DefaultWidth = bw;
_barWindow.DefaultHeight = bh;
_barWindow.NeedsPass = true;
}
if (_pickerWindow != null) { _pickerWindow.Visible = data.Settings.PickerOpen; _pickerWindow.NeedsPass = true; }
Host.Log($"[RynthDefective] item bar for {name} on {server}: {data.Slots.FindAll(s => !s.Empty).Count} slots set; file {_store.PathFor(server, name)}");
}
private void RefreshIconSupport()
{
_session.IconsAvailable = Host.HasUi && Host.TryGetUiInfo(out UiInfoNative info) && info.OpLevel >= 2;
}
private void RequestSave()
{
MarkAllForPass();
if (_saveDueMs == 0) _saveDueMs = Environment.TickCount64 + SaveDelayMs;
}
private void SaveNow()
{
_saveDueMs = 0;
if (!_identityKnown) return;
_session.Settings.Clamp();
string? error = _store.Save(_server, _character, _session.Data);
if (error != null) Host.Log("[RynthDefective] save failed: " + error);
}
/// <summary>A pass when one is wanted, or on the refresh interval while visible (counts and the status tick on).</summary>
private void Record(UiWindow w, long now, Action<UiWindow> draw)
{
bool due = w.NeedsPass || (w.Visible && now >= w.NextPassMs);
if (!due) return;
w.NeedsPass = false;
w.NextPassMs = now + PassIntervalMs;
w.Begin();
try
{
draw(w);
}
catch (Exception ex)
{
w.TextWrapped($"Something went wrong drawing this window: {ex.GetType().Name}: {ex.Message}");
Host.Log($"[RynthDefective] {w.Key} pass failed: {ex}");
}
w.End();
}
}

View file

@ -0,0 +1,148 @@
// ============================================================================
// RynthDefective - ShortcutBar/BarSnapshot.cs
// What the shortcut bar shows, built on the plugin tick (BarSnapshotBuilder)
// and drawn on the render thread (ShortcutBarWindow): one immutable record per
// slot, swapped whole.
//
// Slots 1-18 are AC's own shortcut slots (RynthCoreHost.GetShortcuts, plugin
// API v90): the items the retail toolbar holds, the keys AC's keymap gives
// UseQuickSlot_1-18. Slots 19 and on are this plugin's own (DefData.Slots),
// their keys the engine's hotkeys (/rdef use N). The player chooses how many
// the bar shows (DefSettings.BarSlots).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Text;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Views;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.ShortcutBar;
/// <summary>How a slot's count line reads: plain, in hand / worn, or nothing carried.</summary>
internal enum CountTone { Plain, InHand, Missing }
/// <summary>One slot as drawn.</summary>
internal sealed record BarSlot(
int Number,
bool Retail,
uint ObjectId,
uint SpellId,
string Name,
string Count,
CountTone Tone,
string Key,
string AllKeys,
string Tooltip)
{
public bool Empty => ObjectId == 0 && SpellId == 0 && Name.Length == 0;
}
internal sealed record BarSnapshot(BarSlot[] Slots, bool Ready, int IconSize)
{
public static readonly BarSnapshot NotReady = new(Array.Empty<BarSlot>(), false, 36);
}
/// <summary>Builds the snapshot on the plugin tick (reads the host and the carried items).</summary>
internal sealed class BarSnapshotBuilder
{
private readonly RynthCoreHost _host;
private readonly uint[] _ids = new uint[DefSettings.RetailSlots], _spells = new uint[DefSettings.RetailSlots];
private readonly string[] _keys = new string[DefSettings.RetailSlots];
private long _keysReadMs = long.MinValue / 2, _fastKeysUntilMs;
public BarSnapshotBuilder(RynthCoreHost host)
{
_host = host;
Array.Fill(_keys, string.Empty);
}
/// <summary>A key was changed from the bar: ask again often for a few seconds (the change is made on the game's tick).</summary>
public void InvalidateKeys()
{
_keysReadMs = long.MinValue / 2;
_fastKeysUntilMs = Environment.TickCount64 + 4000;
}
/// <summary>AC's keys for the 18 retail slots (re-asked every 2 s: the keymap can change, from any client).</summary>
private void RefreshKeys(long now)
{
if (now - _keysReadMs < (now < _fastKeysUntilMs ? 250 : 2000)) return;
_keysReadMs = now;
for (int i = 0; i < _keys.Length; i++) _keys[i] = _host.GetActionKeys("UseQuickSlot_" + (i + 1));
}
public BarSnapshot Build(DefSession session, IReadOnlyList<CarriedItem> items, long now)
{
if (!_host.HasShortcuts || _host.GetShortcuts(_ids, _spells) == 0) return BarSnapshot.NotReady;
RefreshKeys(now);
DefSettings st = session.Settings;
var byId = new Dictionary<uint, CarriedItem>(items.Count);
foreach (CarriedItem it in items) byId[it.Id] = it;
var slots = new BarSlot[st.BarSlots];
for (int n = 1; n <= st.BarSlots; n++)
slots[n - 1] = n <= DefSettings.RetailSlots ? Retail(n, byId) : Own(n, session, items, _host);
return new BarSnapshot(slots, true, st.ButtonSize);
}
private BarSlot Retail(int n, Dictionary<uint, CarriedItem> byId)
{
uint id = _ids[n - 1], spell = _spells[n - 1];
string allKeys = _keys[n - 1];
string key = FirstKey(allKeys);
if (id == 0 && spell == 0)
return new BarSlot(n, true, 0, 0, string.Empty, string.Empty, CountTone.Plain, key, allKeys,
$"Slot {n} (the game's own): empty.{KeysLine(allKeys)}\nRight-click: put the selected item here, or change its keys.");
string name;
string count = string.Empty;
CountTone tone = CountTone.Plain;
if (id != 0 && byId.TryGetValue(id, out CarriedItem? it))
{
name = it.FullName;
count = SlotText.Count(new SlotStatus(it, it.Stack, it.Uses, false), out uint color);
tone = color == SlotText.InHand ? CountTone.InHand : color == SlotText.Missing ? CountTone.Missing : CountTone.Plain;
}
else if (id != 0)
{
name = _host.TryGetObjectName(id, out string n2) && n2.Length > 0 ? n2 : $"0x{id:X8}";
count = "none";
tone = CountTone.Missing;
}
else name = $"Spell {spell}";
string tip = $"Slot {n} (the game's own): {name}{(count.Length > 0 ? " - " + count : "")}.{KeysLine(allKeys)}\n" +
"Click: use it, as its key does. Right-click: change the slot or its keys.";
return new BarSlot(n, true, id, id == 0 ? spell : 0, name, count, tone, key, allKeys, tip);
}
private static BarSlot Own(int n, DefSession session, IReadOnlyList<CarriedItem> items, RynthCoreHost host)
{
int own = n - DefSettings.RetailSlots;
DefSlot slot = own <= session.Data.Slots.Count ? session.Data.Slots[own - 1] : new DefSlot();
// Every key of "/rdef use N" (the engine's hotkeys), else the one bound to the item by name.
string all = host.HasKeyBinding ? host.GetActionKeys(DefCommandParser.UseCommand(own)) : string.Empty;
string key = all.Length > 0 ? FirstKey(all) : session.KeyOfSlot(own) ?? string.Empty;
if (all.Length == 0) all = key;
if (slot.Item == null)
return new BarSlot(n, false, 0, 0, string.Empty, string.Empty, CountTone.Plain, SlotText.ShortKey(key), all,
$"Slot {n} (RynthCore's: the game holds 18): empty.{KeysLine(all)}\nRight-click: put the selected item here, or change its keys.");
SlotStatus s = ItemMatcher.Status(slot.Item, items);
string count = SlotText.Count(s, out uint color);
CountTone tone = color == SlotText.InHand ? CountTone.InHand : color == SlotText.Missing ? CountTone.Missing : CountTone.Plain;
string tip = SlotText.Tooltip(n, slot.Item, s, slot.Mode, key.Length > 0 ? key : null)
+ "\n(RynthCore's slot: the game's toolbar holds 18.)";
return new BarSlot(n, false, s.Item?.Id ?? 0, 0, s.Item?.FullName ?? slot.Item.FullName, count, tone,
SlotText.ShortKey(key), all, tip);
}
/// <summary>The first of "1, Ctrl+1": what fits on the slot.</summary>
private static string FirstKey(string keys)
{
int comma = keys.IndexOf(',');
return comma < 0 ? keys : keys[..comma];
}
private static string KeysLine(string keys) => keys.Length > 0 ? "\nKeys: " + keys : "\nNo key yet.";
}

View file

@ -0,0 +1,155 @@
// ============================================================================
// RynthDefective - ShortcutBar/PanelButtonsWindow.cs
// Tiny buttons for AC's own panels, in the bottom-right corner (Tom
// 2026-10-22: with the retail toolbar hidden, its panel buttons go with it).
// RynthCore hosts the frameless window (sections manifest "corner":
// "bottomRight", plugin API v90) and opens and closes the panels the way AC's
// toolbar and keys do (RynthCoreHost.AcPanel): one main panel at a time.
//
// grip the dots on the left: drag the strip; Ctrl+wheel: bigger or
// smaller; right-click: hide it (/rdef panels shows it again).
// buttons the pack, attributes & skills, the spellbook, fellowship &
// allegiance, the map, quests, spells on you, character info,
// options. Lit while their panel is open. They fill the window's
// width and wrap: drag it narrow for a column.
//
// AC's render thread; the panel calls are queued by the engine.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthDefective.ShortcutBar;
internal sealed class PanelButtonsWindow
{
public const string Title = "Game Panels";
private readonly RynthCoreHost _host;
private float _k = 1f, _r = 1f;
public PanelButtonsWindow(RynthCoreHost host) => _host = host;
private readonly record struct Button(RynthAcPanel Panel, string Icon, string Tip);
private static readonly Button[] Buttons =
[
new(RynthAcPanel.Inventory, RynthIcons.Backpack, "Pack"),
new(RynthAcPanel.Character, RynthIcons.User, "Attributes and skills"),
new(RynthAcPanel.Spellbook, RynthIcons.MagicWand, "Spellbook"),
new(RynthAcPanel.Social, RynthIcons.UsersThree, "Fellowship, allegiance and friends"),
new(RynthAcPanel.Map, RynthIcons.MapTrifold, "Map"),
new(RynthAcPanel.Quests, RynthIcons.Scroll, "Contracts and journal"),
new(RynthAcPanel.HelpfulSpells, RynthIcons.Sparkle, "Spells on you"),
new(RynthAcPanel.CharacterInfo, RynthIcons.Info, "Character information"),
new(RynthAcPanel.Options, RynthIcons.Gear, "Options"),
];
private const float Pad = 4, Cell = 22, Gap = 2, GripW = 9, Radius = 4;
private float Px(float v) => v * _k;
/// <summary>
/// The layout's scale and the text's against the baked font: the window's own size (Settings > UI >
/// Toolbar, Ctrl+wheel: 30-250%, PanelScale) or, unset, the text size the engine baked for it.
/// </summary>
private void Scale()
{
float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f);
int pct = _host.PanelScale(Title);
_k = pct > 0 ? pct / 100f : fontK;
_r = _k / fontK;
}
private uint _bg, _key, _line, _text, _faint, _accent;
private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
/// <summary>Draws the strip into the host's window; returns the height it needs (pixels). Render thread.</summary>
public float Draw()
{
Scale();
_bg = Color(RynthUiColor.Background);
_key = Color(RynthUiColor.KeyFace);
_line = Color(RynthUiColor.Hairline);
_text = Color(RynthUiColor.Text);
_faint = Color(RynthUiColor.Faint);
_accent = Color(RynthUiColor.Accent);
Vector2 origin = ImGui.GetCursorScreenPos();
origin = new Vector2(MathF.Round(origin.X), MathF.Round(origin.Y));
float width = MathF.Floor(ImGui.GetContentRegionAvail().X);
if (width < 20) return Px(Cell + 2 * Pad);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
float cell = Px(Cell), gap = Px(Gap), pad = Px(Pad), grip = Px(GripW);
float room = width - 2 * pad - grip - gap;
int perRow = Math.Max(1, (int)MathF.Floor((room + gap) / (cell + gap)));
int rows = (Buttons.Length + perRow - 1) / perRow;
float height = MathF.Ceiling(2 * pad + rows * cell + (rows - 1) * gap);
// The frame, as the shortcut bar's.
Vector2 max = origin + new Vector2(width, height);
dl.AddRectFilled(origin, max, A(_bg, 0.94f), Px(Radius));
dl.AddRect(origin, max, _line, Px(Radius));
// The grip: drag, Ctrl+wheel, right-click to hide.
Vector2 gp = origin + new Vector2(pad, pad);
ImGui.SetCursorScreenPos(gp);
ImGui.InvisibleButton("##gp_grip", new Vector2(grip, height - 2 * pad));
_host.PanelDragWithLastItem();
bool gripHot = ImGui.IsItemHovered();
if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) _host.SetPanelOpen(Title, RynthPanelOpen.Close);
SafeImGui.SetItemTooltip("Drag to move. Ctrl+wheel: bigger or smaller. Right-click: hide (/rdef panels shows it again).\nDrag the window's edge narrower for a column.");
DrawIcon(dl, RynthIcons.DotsSixVertical, gp, new Vector2(grip, height - 2 * pad), Px(11), gripHot ? _text : _faint);
float x0 = gp.X + grip + gap;
for (int i = 0; i < Buttons.Length; i++)
{
int col = i % perRow, row = i / perRow;
Vector2 p = new(MathF.Round(x0 + col * (cell + gap)), MathF.Round(origin.Y + pad + row * (cell + gap)));
DrawButton(dl, Buttons[i], p, cell);
}
ImGui.SetCursorScreenPos(origin);
ImGui.Dummy(new Vector2(width, height));
return height;
}
private void DrawButton(ImDrawListPtr dl, in Button b, Vector2 p, float cell)
{
Vector2 size = new(cell, cell);
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton("##gp_" + (int)b.Panel, size);
bool hot = ImGui.IsItemHovered();
bool? open = _host.IsAcPanelOpen(b.Panel);
SafeImGui.SetItemTooltip(open == null ? b.Tip + " (not in this client)" : b.Tip + (open == true ? " - open: click to close" : ""));
float r = Px(3);
if (hot || open == true) dl.AddRectFilled(p, p + size, _key, r);
if (open == true) dl.AddLine(new Vector2(p.X + Px(4), p.Y + cell - Px(1.5f)), new Vector2(p.X + cell - Px(4), p.Y + cell - Px(1.5f)), _accent, Px(1.5f));
uint color = open == null ? A(_faint, 0.5f) : open == true ? _accent : hot ? _text : A(_text, 0.72f);
DrawIcon(dl, b.Icon, p, size, Px(14), color);
if (clicked && open != null) _host.AcPanel(b.Panel, RynthAcPanelOp.Toggle);
}
/// <summary>A Phosphor glyph centred in the box, <paramref name="px"/> across its em (from Ui18's bake).</summary>
private static unsafe void DrawIcon(ImDrawListPtr dl, string glyph, Vector2 min, Vector2 size, float px, uint color)
{
if (string.IsNullOrEmpty(glyph)) return;
ImFontPtr font = Font(RynthUiFont.Ui18);
if (font.NativePtr == null) return;
byte* g = (byte*)ImGuiNative.ImFont_FindGlyphNoFallback(font.NativePtr, glyph[0]);
if (g == null) return;
float advance = *(float*)(g + 4);
if (advance <= 0) return;
float* box = (float*)(g + 8);
float scale = px / advance;
Vector2 centre = new((box[0] + box[2]) * 0.5f * scale, (box[1] + box[3]) * 0.5f * scale);
Vector2 at = min + size * 0.5f - centre;
dl.AddText(font, font.FontSize * scale, new Vector2(MathF.Round(at.X), MathF.Round(at.Y)), color, glyph);
}
}

View file

@ -0,0 +1,196 @@
// ============================================================================
// RynthDefective - ShortcutBar/SelectionWindow.cs
// What is selected, as the retail toolbar showed it (Tom 2026-10-22: "people
// use it all the time to find things near them: doors, monsters"): its
// picture and name, how far and which way it is (an arrow from where you
// face, and the compass point), and the health bar of a creature or player.
// USE uses it (opens a door, talks to an NPC). AC's own selection keys still
// pick what is selected; this only shows it.
//
// the name row drag to move; Ctrl+wheel: bigger or smaller (30-250%);
// right-click: hide it (Settings > UI > Toolbar, /rdef selection).
//
// AC's render thread; reads the view the tick built (SelectionView).
// ============================================================================
using System;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthDefective.ShortcutBar;
/// <summary>The selected object as drawn (built on the plugin tick).</summary>
internal sealed record SelectionView(
bool Ready,
uint Id,
string Name,
string Where,
float Relative, // degrees from where the player faces (0 ahead, + to the right); NaN = unknown
float Health, // 0-1, or -1 when it has none known
uint Current,
uint Max)
{
public static readonly SelectionView NotReady = new(false, 0, string.Empty, string.Empty, float.NaN, -1f, 0, 0);
}
internal sealed class SelectionWindow
{
public const string Title = "Selection";
private readonly RynthCoreHost _host;
private readonly Action<uint> _use;
private float _k = 1f, _r = 1f;
public SelectionWindow(RynthCoreHost host, Action<uint> use)
{
_host = host;
_use = use;
}
private float Px(float v) => v * _k;
private float Fs(ImFontPtr f) => f.FontSize * _r;
private void Scale()
{
float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f);
int pct = _host.PanelScale(Title);
_k = pct > 0 ? pct / 100f : fontK;
_r = _k / fontK;
}
private const float Pad = 6, Icon = 30, Gap = 6, Radius = 4, BarH = 6, UseW = 34, UseH = 16;
private uint _bg, _key, _inset, _line, _text, _dim, _faint, _accent;
private static readonly uint HealthColor = Argb(0xFFE0564E), HealthHigh = Argb(0xFF73D885), White = Argb(0xFFFFFFFF);
private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
/// <summary>Draws the selection into the host's window; returns the height it needs (pixels). Render thread.</summary>
public float Draw(SelectionView v)
{
Scale();
_bg = Color(RynthUiColor.Background);
_key = Color(RynthUiColor.KeyFace);
_inset = Color(RynthUiColor.Inset);
_line = Color(RynthUiColor.Hairline);
_text = Color(RynthUiColor.Text);
_dim = Color(RynthUiColor.Muted);
_faint = Color(RynthUiColor.Faint);
_accent = Color(RynthUiColor.Accent);
Vector2 origin = ImGui.GetCursorScreenPos();
origin = new Vector2(MathF.Round(origin.X), MathF.Round(origin.Y));
float width = MathF.Floor(ImGui.GetContentRegionAvail().X);
if (width < 40) return Px(40);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
float pad = Px(Pad), icon = Px(Icon);
float height = MathF.Ceiling(2 * pad + icon);
Vector2 max = origin + new Vector2(width, height);
dl.AddRectFilled(origin, max, A(_bg, 0.94f), Px(Radius));
dl.AddRect(origin, max, _line, Px(Radius));
bool hasUse = v.Ready && v.Id != 0;
float useW = hasUse ? Px(UseW) : 0f;
// The drag surface: everything but USE.
ImGui.SetCursorScreenPos(origin);
ImGui.InvisibleButton("##sel_drag", new Vector2(Math.Max(1, width - useW - (hasUse ? pad : 0)), height));
_host.PanelDragWithLastItem();
if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) _host.SetPanelOpen(Title, RynthPanelOpen.Close);
SafeImGui.SetItemTooltip(v.Id == 0
? "Nothing selected. Select with a click or the game's selection keys (- and = go through what's near you).\nDrag to move; Ctrl+wheel: bigger or smaller; right-click: hide."
: $"{v.Name}{(v.Where.Length > 0 ? " - " + v.Where : "")}\nDrag to move; Ctrl+wheel: bigger or smaller; right-click: hide.");
// The picture.
Vector2 ip = origin + new Vector2(pad, pad);
dl.AddRectFilled(ip, ip + new Vector2(icon, icon), v.Id == 0 ? _inset : _key, Px(3));
IntPtr tex = v.Id != 0 ? _host.GetIconTexture(RynthIconKind.Object, v.Id) : IntPtr.Zero;
if (tex != IntPtr.Zero)
dl.AddImageRounded(tex, ip + new Vector2(Px(2), Px(2)), ip + new Vector2(icon - Px(2), icon - Px(2)), Vector2.Zero, Vector2.One, White, Px(2));
dl.AddRect(ip, ip + new Vector2(icon, icon), _line, Px(3));
float tx = ip.X + icon + Px(Gap);
float right = origin.X + width - pad - (hasUse ? useW + Px(Gap) : 0f);
ImFontPtr nf = Font(RynthUiFont.NarrowBold11), sf = Font(RynthUiFont.Narrow9);
if (!v.Ready || v.Id == 0)
{
Clip(dl, nf, Fs(nf), new Vector2(tx, ip.Y + Px(1)), _faint, v.Ready ? "Nothing selected" : "Selection", right - tx);
Clip(dl, sf, Fs(sf), new Vector2(tx, ip.Y + icon - Fs(sf)), _faint, "- and = go through what's near you", right - tx);
ImGui.SetCursorScreenPos(origin);
ImGui.Dummy(new Vector2(width, height));
return height;
}
// Name, then the health bar (a creature or player) and where it is.
Clip(dl, nf, Fs(nf), new Vector2(tx, ip.Y), _text, v.Name, right - tx);
float lineY = ip.Y + icon - Fs(sf);
float x = tx;
if (!float.IsNaN(v.Relative))
{
float s = Fs(sf);
Arrow(dl, new Vector2(x + s * 0.5f, lineY + s * 0.5f), s * 0.5f, v.Relative, _accent);
x += s + Px(3);
}
if (v.Health >= 0f)
{
float barY = ip.Y + Fs(nf) + Px(3);
float barW = right - tx, barH = Px(BarH);
Vector2 b0 = new(tx, barY), b1 = new(tx + barW, barY + barH);
dl.AddRectFilled(b0, b1, _inset, Px(2));
float f = Math.Clamp(v.Health, 0f, 1f);
if (f > 0f) dl.AddRectFilled(b0, new Vector2(tx + barW * f, barY + barH), f > 0.6f ? A(HealthHigh, 0.9f) : HealthColor, Px(2));
dl.AddRect(b0, b1, _line, Px(2));
string pct = (v.Max > 0 ? $"{v.Current}/{v.Max} " : "") + MathF.Round(f * 100f).ToString(CultureInfo.InvariantCulture) + "%";
float pw = sf.CalcTextSizeA(Fs(sf), float.MaxValue, 0f, pct).X;
dl.AddText(sf, Fs(sf), new Vector2(right - pw, lineY), _dim, pct);
Clip(dl, sf, Fs(sf), new Vector2(x, lineY), _dim, v.Where, right - pw - Px(6) - x);
}
else Clip(dl, sf, Fs(sf), new Vector2(x, lineY), _dim, v.Where, right - x);
// USE.
Vector2 up = new(origin.X + width - pad - useW, origin.Y + (height - Px(UseH)) * 0.5f);
ImGui.SetCursorScreenPos(up);
bool use = ImGui.InvisibleButton("##sel_use", new Vector2(useW, Px(UseH)));
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip("Use it, as a double-click does (open a door, talk, pick up, use an item).");
dl.AddRectFilled(up, up + new Vector2(useW, Px(UseH)), hot ? _key : A(_key, 0.6f), Px(3));
dl.AddRect(up, up + new Vector2(useW, Px(UseH)), hot ? _accent : _line, Px(3));
ImFontPtr uf = Font(RynthUiFont.Dash9);
float uw = uf.CalcTextSizeA(Fs(uf), float.MaxValue, 0f, "USE").X;
dl.AddText(uf, Fs(uf), new Vector2(MathF.Round(up.X + (useW - uw) * 0.5f), MathF.Round(up.Y + (Px(UseH) - Fs(uf)) * 0.5f)), hot ? _text : _dim, "USE");
if (use) _use(v.Id);
ImGui.SetCursorScreenPos(origin);
ImGui.Dummy(new Vector2(width, height));
return height;
}
/// <summary>Text cut with "..." to <paramref name="room"/> pixels.</summary>
private static void Clip(ImDrawListPtr dl, ImFontPtr f, float size, Vector2 pos, uint color, string text, float room)
{
if (text.Length == 0 || room <= 4) return;
float w = f.CalcTextSizeA(size, float.MaxValue, 0f, text).X;
if (w > room)
{
int n = text.Length;
while (n > 1 && f.CalcTextSizeA(size, float.MaxValue, 0f, text[..n] + "...").X > room) n--;
text = text[..n] + "...";
}
dl.AddText(f, size, new Vector2(MathF.Round(pos.X), MathF.Round(pos.Y)), color, text);
}
/// <summary>A small arrow pointing <paramref name="degrees"/> from straight up (where the player faces), clockwise.</summary>
private static void Arrow(ImDrawListPtr dl, Vector2 c, float r, float degrees, uint color)
{
float a = degrees * MathF.PI / 180f;
Vector2 Dir(float t) => new(MathF.Sin(t), -MathF.Cos(t));
Vector2 tip = c + Dir(a) * r;
Vector2 left = c + Dir(a + 2.45f) * r * 0.85f, rightP = c + Dir(a - 2.45f) * r * 0.85f;
dl.AddTriangleFilled(tip, left, rightP, color);
}
}

View file

@ -0,0 +1,539 @@
// ============================================================================
// RynthDefective - ShortcutBar/ShortcutBarWindow.cs
// The shortcut bar, drawn by RynthDefective in its own frameless window
// (plugin API v90: RynthCore hosts it, "chrome": "none" + "fitHeight"), in
// the instrument look of RynthAi's dashboard and the player's colour theme.
//
// header SHORTCUTS and the slot count (the drag handle; Ctrl+wheel: the
// size), then Edit, Weapons (the weapon picker) and Hide.
// slots the item's picture, its key in the top-left corner (AC's keymap
// for slots 1-18, the engine's hotkeys after), the count or "in
// hand" under it. They fill the window's width and wrap: drag the
// window wider or narrower for one row or several.
// edit the slot numbers show, and - / + at the end take a slot off or
// add one (the player picks how many; 1-18 are the game's).
// Drag an item from AC's pack onto a slot: it goes there, as on the retail
// toolbar (the item stays in the pack). Click a slot: it is used as its key
// would. Right-click: put the selected item there, or empty it, and its keys: remove one, or add one by pressing
// it. A slot 1-18 key is AC's own (its keymap, so the retail toolbar answers
// to it too, in every client); a key past 18 is an engine hotkey running
// /rdef use N. A key comes off whatever had it, after the player says so.
//
// AC's render thread. Reads the snapshot the tick built; every click is
// queued for the tick (IBarActions).
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthDefective.ShortcutBar;
/// <summary>What the bar asks of the plugin: everything runs on its tick.</summary>
internal interface IBarActions
{
void Use(int number);
void SetFromSelected(int number);
void Clear(int number);
void ChangeSlotCount(int delta);
/// <summary>An item dragged out of AC's UI was let go over slot <paramref name="number"/>.</summary>
void DropItem(int number, uint objectId);
/// <summary>A key was bound or removed: the bar asks for its keys again.</summary>
void KeysChanged();
void ShowWeapons();
void Hide();
}
internal sealed class ShortcutBarWindow
{
public const string Title = "Shortcuts";
private readonly RynthCoreHost _host;
private readonly IBarActions _act;
private bool _edit;
private float _k = 1f, _r = 1f;
public ShortcutBarWindow(RynthCoreHost host, IBarActions actions)
{
_host = host;
_act = actions;
}
private float Px(float v) => v * _k;
/// <summary>A font's size at this scale (its baked size times the text ratio).</summary>
private float Fs(ImFontPtr f) => f.FontSize * _r;
/// <summary>
/// The layout's scale and the text's against the baked font: the window's own size (Settings > UI >
/// Toolbar, Ctrl+wheel: 30-250%, PanelScale) or, unset, the text size the engine baked for it.
/// </summary>
private void Scale()
{
float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f);
int pct = _host.PanelScale(Title);
_k = pct > 0 ? pct / 100f : fontK;
_r = _k / fontK;
}
private const float PadX = 7, PadTop = 6, PadBottom = 7, Radius = 4, HeaderH = 18, Gap = 3, ChipSize = 16;
private uint _bg, _key, _inset, _line, _text, _dim, _faint, _accent;
private static readonly uint InHandColor = Argb(0xFF73D885), MissingColor = Argb(0xFFF98075),
Black = Argb(0xFF000000), White = Argb(0xFFFFFFFF);
private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
/// <summary>Draws the bar into the host's window; returns the height it needs (pixels). Render thread.</summary>
public float Draw(BarSnapshot view, bool popped)
{
Scale();
_bg = Color(RynthUiColor.Background);
_key = Color(RynthUiColor.KeyFace);
_inset = Color(RynthUiColor.Inset);
_line = Color(RynthUiColor.Hairline);
_text = Color(RynthUiColor.Text);
_dim = Color(RynthUiColor.Muted);
_faint = Color(RynthUiColor.Faint);
_accent = Color(RynthUiColor.Accent);
Vector2 origin = ImGui.GetCursorScreenPos();
origin = new Vector2(MathF.Round(origin.X), MathF.Round(origin.Y));
float width = MathF.Floor(ImGui.GetContentRegionAvail().X);
if (width < 40) return Px(60);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
float height;
dl.ChannelsSplit(2);
bool merged = false;
try
{
dl.ChannelsSetCurrent(1);
float x0 = origin.X + Px(PadX), w = width - 2 * Px(PadX);
float y = origin.Y + Px(PadTop);
y = Header(dl, view, x0, y, w);
y += Px(5);
y = Slots(dl, view, x0, y, w);
y += Px(PadBottom);
height = MathF.Ceiling(y - origin.Y);
dl.ChannelsSetCurrent(0);
Frame(dl, origin, new Vector2(width, height));
dl.ChannelsMerge();
merged = true;
}
finally
{
if (!merged) dl.ChannelsMerge();
}
ImGui.SetCursorScreenPos(origin);
ImGui.Dummy(new Vector2(width, height));
SlotMenu(view);
if (_openKeyPopup)
{
_openKeyPopup = false;
ImGui.OpenPopup(KeyPopupId);
}
KeyPopup();
return height;
}
private void Frame(ImDrawListPtr dl, Vector2 min, Vector2 size)
{
Vector2 max = min + size;
float r = Px(Radius);
dl.AddRectFilled(min, max, A(_bg, 0.94f), r);
dl.AddLine(new Vector2(min.X + r, min.Y + 1.5f), new Vector2(max.X - r, min.Y + 1.5f), A(White, 0.05f));
dl.AddRect(min, max, _line, r);
}
// ── Header ────────────────────────────────────────────────────────────
private float Header(ImDrawListPtr dl, BarSnapshot view, float x0, float y, float w)
{
float h = Px(HeaderH), chip = Px(ChipSize);
const int chips = 3;
float chipsW = chips * chip + (chips - 1) * Px(1);
ImGui.SetCursorScreenPos(new Vector2(x0, y));
ImGui.InvisibleButton("##sb_drag", new Vector2(Math.Max(1, w - chipsW - Px(4)), h));
_host.PanelDragWithLastItem();
SafeImGui.SetItemTooltip("Drag to move the bar. Ctrl+wheel here: bigger or smaller.\nDrag the window's edge to change how many slots fit in a row.");
ImFontPtr tf = Font(RynthUiFont.NarrowBold11);
float size = Fs(tf) * 10f / 11f;
float tx = Tracked(dl, tf, size, new Vector2(x0, MathF.Round(y + (h - size) * 0.5f)), _text, "SHORTCUTS", 0.18f * size);
ImFontPtr nf = Font(RynthUiFont.Dash9);
string count = view.Ready ? view.Slots.Length.ToString(System.Globalization.CultureInfo.InvariantCulture) : "";
dl.AddText(nf, Fs(nf), new Vector2(MathF.Round(tx + Px(6)), MathF.Round(y + (h - Fs(nf)) * 0.5f + Px(1))), _faint, count);
float cx = x0 + w - chipsW, cy = y + (h - chip) * 0.5f;
if (Chip("##sb_edit", RynthIcons.PencilSimple, new Vector2(cx, cy), _edit ? _accent : _faint,
_edit ? "Done editing." : "Edit: the slot numbers, and - / + to take a slot off or add one.", _edit))
_edit = !_edit;
cx += chip + Px(1);
if (Chip("##sb_weapons", RynthIcons.Sword, new Vector2(cx, cy), _faint, "Weapons: every weapon and wand you carry, wield one with a click."))
_act.ShowWeapons();
cx += chip + Px(1);
if (Chip("##sb_hide", RynthIcons.X, new Vector2(cx, cy), _faint, "Hide the bar (/rdef shows it again). Its keys keep working."))
_act.Hide();
return y + h;
}
private bool Chip(string id, string icon, Vector2 pos, uint color, string tip, bool held = false)
{
Vector2 size = new(Px(ChipSize), Px(ChipSize));
ImGui.SetCursorScreenPos(pos);
bool clicked = ImGui.InvisibleButton(id, size);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(tip);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
if (hot || held) dl.AddRectFilled(pos, pos + size, _key, Px(3));
DrawIcon(dl, icon, pos, size, Px(11), hot ? _text : color);
return clicked;
}
// ── Slots ─────────────────────────────────────────────────────────────
private int _menuSlot;
private const string MenuId = "##sb_slot_menu";
private float Slots(ImDrawListPtr dl, BarSnapshot view, float x0, float y, float w)
{
if (!view.Ready)
{
ImFontPtr f = Font(RynthUiFont.Narrow10);
dl.AddText(f, Fs(f), new Vector2(x0, y), _faint, "Your shortcuts show once you're in the world.");
return y + Fs(f) + Px(2);
}
float cell = Px(Math.Clamp(view.IconSize, 20, 64)), gap = Px(Gap);
int cells = view.Slots.Length + (_edit ? 2 : 0);
int perRow = Math.Max(1, (int)MathF.Floor((w + gap) / (cell + gap)));
int rows = (cells + perRow - 1) / perRow;
// Items dragged out of AC's UI: the slots' area takes them (the engine keeps the drop from AC).
Vector2 areaMin = new(x0, y), areaMax = new(x0 + perRow * (cell + gap), y + rows * (cell + gap));
uint dropped = _host.HasDropTargets ? _host.DropTarget(Title, areaMin, areaMax, true, out _dragging) : 0;
int under = SlotAt(ImGui.GetIO().MousePos, x0, y, cell, gap, perRow, view.Slots.Length);
_dropSlot = _dragging ? under : 0;
if (dropped != 0 && under > 0) _act.DropItem(under, dropped);
for (int i = 0; i < cells; i++)
{
int col = i % perRow, row = i / perRow;
Vector2 p = new(MathF.Round(x0 + col * (cell + gap)), MathF.Round(y + row * (cell + gap)));
if (i < view.Slots.Length) Slot(dl, view.Slots[i], p, cell);
else EditButton(dl, i == view.Slots.Length ? -1 : 1, p, cell, view.Slots.Length);
}
return y + rows * (cell + gap) - gap;
}
private bool _dragging;
private int _dropSlot;
/// <summary>The slot number (1-based) under <paramref name="m"/>, or 0.</summary>
private static int SlotAt(Vector2 m, float x0, float y0, float cell, float gap, int perRow, int count)
{
if (m.X < x0 || m.Y < y0) return 0;
int col = (int)((m.X - x0) / (cell + gap)), row = (int)((m.Y - y0) / (cell + gap));
if (col >= perRow || m.X - x0 - col * (cell + gap) > cell || m.Y - y0 - row * (cell + gap) > cell) return 0;
int i = row * perRow + col;
return i < count ? i + 1 : 0;
}
private void Slot(ImDrawListPtr dl, BarSlot s, Vector2 p, float cell)
{
Vector2 size = new(cell, cell);
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton(Id("##sb_slot", s.Number), size, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight)
&& ImGui.IsMouseReleased(ImGuiMouseButton.Left);
bool right = ImGui.IsItemClicked(ImGuiMouseButton.Right);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(s.Tooltip);
float r = Px(3);
// The well, the picture, a hairline (the accent under the mouse; green while in hand).
dl.AddRectFilled(p, p + size, s.Empty ? _inset : _key, r);
if (!s.Empty)
{
uint id = s.ObjectId != 0 ? s.ObjectId : s.SpellId;
IntPtr tex = id == 0 ? IntPtr.Zero : _host.GetIconTexture(s.ObjectId != 0 ? RynthIconKind.Object : RynthIconKind.Spell, id);
float inset = Px(2);
if (tex != IntPtr.Zero)
dl.AddImageRounded(tex, p + new Vector2(inset, inset), p + size - new Vector2(inset, inset), Vector2.Zero, Vector2.One,
s.Tone == CountTone.Missing ? A(White, 0.35f) : White, Px(2));
else
{
ImFontPtr af = Font(RynthUiFont.Narrow9);
string abbr = Abbrev(s.Name);
float aw = af.CalcTextSizeA(Fs(af), float.MaxValue, 0f, abbr).X;
dl.AddText(af, Fs(af), new Vector2(MathF.Round(p.X + (cell - aw) * 0.5f), MathF.Round(p.Y + (cell - Fs(af)) * 0.5f)), _dim, abbr);
}
}
uint border = hot || _dropSlot == s.Number ? _accent : s.Tone == CountTone.InHand ? A(InHandColor, 0.8f) : _line;
dl.AddRect(p, p + size, border, r, ImDrawFlags.None, _dropSlot == s.Number ? Px(2) : 1f);
// The key, top left (a dark plate under it so it reads over any picture); edit: the slot number.
ImFontPtr kf = Font(RynthUiFont.Dash9);
string label = _edit ? s.Number.ToString(System.Globalization.CultureInfo.InvariantCulture) : s.Key;
if (label.Length > 0)
{
float lw = kf.CalcTextSizeA(Fs(kf), float.MaxValue, 0f, label).X;
Vector2 lp = p + new Vector2(Px(2), Px(1));
dl.AddRectFilled(lp - new Vector2(Px(1), 0), lp + new Vector2(lw + Px(1), Fs(kf)), A(Black, 0.55f), Px(2));
dl.AddText(kf, Fs(kf), lp, _edit ? _accent : s.Retail ? _text : _accent, label);
}
// The count, bottom right.
if (!_edit && s.Count.Length > 0)
{
string c = s.Count == "in hand" ? "hand" : s.Count;
float cw = kf.CalcTextSizeA(Fs(kf), float.MaxValue, 0f, c).X;
Vector2 cp = p + new Vector2(cell - cw - Px(2), cell - Fs(kf) - Px(1));
dl.AddRectFilled(cp - new Vector2(Px(1), 0), cp + new Vector2(cw + Px(1), Fs(kf)), A(Black, 0.55f), Px(2));
uint cc = s.Tone == CountTone.InHand ? InHandColor : s.Tone == CountTone.Missing ? MissingColor : _text;
dl.AddText(kf, Fs(kf), cp, cc, c);
}
if (clicked && !s.Empty) _act.Use(s.Number);
if (right)
{
_menuSlot = s.Number;
ImGui.OpenPopup(MenuId);
}
}
private void EditButton(ImDrawListPtr dl, int delta, Vector2 p, float cell, int count)
{
Vector2 size = new(cell, cell);
bool can = delta < 0 ? count > DefSettings.BarSlotsMin : count < DefSettings.BarSlotsMax;
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton(delta < 0 ? "##sb_less" : "##sb_more", size);
bool hot = can && ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(delta < 0
? "One slot fewer (the last one's item stays: add the slot back and it is there)."
: count < DefSettings.RetailSlots ? "One more slot (the game's own, up to 18)."
: "One more slot (RynthCore's: the game's toolbar holds 18).");
float r = Px(3);
dl.AddRect(p, p + size, hot ? _accent : A(_line, can ? 1f : 0.4f), r);
DrawIcon(dl, delta < 0 ? RynthIcons.Minus : RynthIcons.Plus, p, size, Px(12), can ? (hot ? _text : _dim) : A(_faint, 0.5f));
if (clicked && can) _act.ChangeSlotCount(delta);
}
private void SlotMenu(BarSnapshot view)
{
if (!ImGui.IsPopupOpen(MenuId)) return;
ImGui.PushStyleColor(ImGuiCol.PopupBg, WithAlpha(_bg, 0xFA));
ImGui.PushStyleColor(ImGuiCol.Border, _line);
ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, Px(4));
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(6), Px(5)));
bool open = ImGui.BeginPopup(MenuId);
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(2);
if (!open) return;
try
{
BarSlot? s = _menuSlot >= 1 && _menuSlot <= view.Slots.Length ? view.Slots[_menuSlot - 1] : null;
if (s == null) { ImGui.CloseCurrentPopup(); return; }
ImGui.TextDisabled($"Slot {s.Number}{(s.Retail ? " (the game's own)" : " (RynthCore's)")}");
if (s.Name.Length > 0) SafeImGui.Text(s.Name);
ImGui.Separator();
bool hasSelection = _host.HasGetSelectedItemId && _host.GetSelectedItemId() != 0;
if (ImGui.MenuItem("Put the selected item here", null, false, hasSelection)) _act.SetFromSelected(s.Number);
if (ImGui.MenuItem("Empty this slot", null, false, !s.Empty)) _act.Clear(s.Number);
ImGui.Separator();
if (!_host.HasKeyBinding)
{
ImGui.TextDisabled(s.AllKeys.Length > 0 ? "Keys: " + s.AllKeys
: s.Retail ? "No key: bind UseQuickSlot_" + s.Number + " in Configure Keyboard." : "No key: /rdef bind " + (s.Number - DefSettings.RetailSlots) + " F9");
return;
}
string[] keys = SplitKeys(s.AllKeys);
ImGui.TextDisabled(keys.Length == 0 ? "No key yet" : keys.Length == 1 ? "Key" : "Keys");
foreach (string key in keys)
{
if (!ImGui.MenuItem("Remove " + key)) continue;
if (_host.UnbindActionKey(KeyAction(s.Number), key, out string why)) _act.KeysChanged();
else ShowKeyMessage(s.Number, why);
}
if (ImGui.MenuItem(keys.Length == 0 ? "Add a key..." : "Add another key..."))
StartKeyCapture(s.Number);
SafeImGui.SetItemTooltip(s.Retail
? "Press the key: it becomes this slot's in the game's own keymap, so the retail toolbar and every client use it too."
: "Press the key: a RynthCore hotkey for this slot (the game's toolbar holds 18).");
}
finally { ImGui.EndPopup(); }
}
// ── Keys: "press a key" ───────────────────────────────────────────────
private enum KeyStep { Waiting, Confirm, Message }
private const string KeyPopupId = "##sb_key_popup";
private bool _openKeyPopup;
private int _keySlot;
private KeyStep _keyStep;
private string _keyName = string.Empty, _keyText = string.Empty;
/// <summary>The action a slot's keys run: AC's UseQuickSlot_N for 1-18, the engine command for the rest.</summary>
public static string KeyAction(int number) =>
number <= DefSettings.RetailSlots ? "UseQuickSlot_" + number : DefCommandParser.UseCommand(number - DefSettings.RetailSlots);
private static string[] SplitKeys(string keys) =>
keys.Length == 0 ? Array.Empty<string>() : keys.Split(", ", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
private void StartKeyCapture(int number)
{
_keySlot = number;
_keyStep = KeyStep.Waiting;
_keyName = _keyText = string.Empty;
_host.BeginKeyCapture();
_openKeyPopup = true;
}
private void ShowKeyMessage(int number, string text)
{
_keySlot = number;
_keyStep = KeyStep.Message;
_keyText = text;
_openKeyPopup = true;
}
private void KeyPopup()
{
if (!ImGui.IsPopupOpen(KeyPopupId))
{
if (_keyStep == KeyStep.Waiting && _keySlot != 0) { _host.CancelKeyCapture(); _keySlot = 0; } // clicked away
return;
}
ImGui.PushStyleColor(ImGuiCol.PopupBg, WithAlpha(_bg, 0xFA));
ImGui.PushStyleColor(ImGuiCol.Border, _line);
ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, Px(4));
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(8), Px(7)));
bool open = ImGui.BeginPopup(KeyPopupId);
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(2);
if (!open) return;
try
{
ImGui.PushTextWrapPos(ImGui.GetCursorPosX() + Px(230));
ImGui.TextDisabled($"Slot {_keySlot}{(_keySlot <= DefSettings.RetailSlots ? " (the game's own)" : " (RynthCore's)")}");
switch (_keyStep)
{
case KeyStep.Waiting:
SafeImGui.Text("Press the key for this slot.");
ImGui.TextDisabled("Hold Ctrl, Alt or Shift with it if you like. Esc cancels.");
RynthKeyCapture got = _host.PollKeyCapture(out string text);
if (got == RynthKeyCapture.Waiting)
{
if (text.Length > 0) ImGui.TextColored(new Vector4(0.98f, 0.5f, 0.46f, 1f), text);
break;
}
if (got == RynthKeyCapture.Cancelled) { _keySlot = 0; ImGui.CloseCurrentPopup(); break; }
_keyName = text;
RynthKeyCheck check = _host.CheckActionKey(KeyAction(_keySlot), _keyName, out string msg);
if (check == RynthKeyCheck.Free) Bind();
else
{
_keyStep = check == RynthKeyCheck.Taken ? KeyStep.Confirm : KeyStep.Message;
_keyText = msg;
}
break;
case KeyStep.Confirm:
SafeImGui.Text(_keyText);
ImGui.TextDisabled($"Use it for slot {_keySlot} instead? It comes off those.");
if (ImGui.Button($"Use {_keyName} here")) Bind();
ImGui.SameLine();
if (ImGui.Button("Another key")) StartKeyCapture(_keySlot);
ImGui.SameLine();
if (ImGui.Button("Cancel")) { _keySlot = 0; ImGui.CloseCurrentPopup(); }
break;
case KeyStep.Message:
SafeImGui.Text(_keyText);
if (ImGui.Button("Another key")) StartKeyCapture(_keySlot);
ImGui.SameLine();
if (ImGui.Button("Close")) { _keySlot = 0; ImGui.CloseCurrentPopup(); }
break;
}
ImGui.PopTextWrapPos();
}
finally { ImGui.EndPopup(); }
}
private void Bind()
{
if (_host.BindActionKey(KeyAction(_keySlot), _keyName, out string why))
{
_act.KeysChanged();
_keySlot = 0;
ImGui.CloseCurrentPopup();
return;
}
_keyStep = KeyStep.Message;
_keyText = why;
}
// ── Helpers ───────────────────────────────────────────────────────────
private static readonly System.Collections.Generic.Dictionary<(string, int), string> Ids = new();
private static string Id(string prefix, int n)
{
if (!Ids.TryGetValue((prefix, n), out string? id)) Ids[(prefix, n)] = id = prefix + n;
return id;
}
private static string Abbrev(string name)
{
if (name.Length == 0) return "?";
string[] words = name.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (words.Length >= 2) return string.Concat(char.ToUpperInvariant(words[0][0]), char.ToUpperInvariant(words[^1][0]));
return name.Length <= 3 ? name : name[..3];
}
private static readonly string[] Chars = BuildChars();
private static string[] BuildChars()
{
var a = new string[128];
for (int i = 32; i < 127; i++) a[i] = ((char)i).ToString();
return a;
}
/// <summary>Text with <paramref name="spacing"/> pixels between its letters. Returns the x after it.</summary>
private static float Tracked(ImDrawListPtr dl, ImFontPtr font, float size, Vector2 pos, uint color, string text, float spacing)
{
unsafe { if (font.NativePtr == null || text.Length == 0) return pos.X; }
float scale = size / font.FontSize;
float x = pos.X;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
string s = c < 128 && Chars[c] != null ? Chars[c] : c.ToString();
dl.AddText(font, size, new Vector2(MathF.Round(x), pos.Y), color, s);
x += font.GetCharAdvance(c) * scale;
if (i < text.Length - 1) x += spacing;
}
return x;
}
/// <summary>A Phosphor glyph centred in the box, <paramref name="px"/> across its em (from Ui18's bake).</summary>
private static unsafe void DrawIcon(ImDrawListPtr dl, string glyph, Vector2 min, Vector2 size, float px, uint color)
{
if (string.IsNullOrEmpty(glyph)) return;
ImFontPtr font = Font(RynthUiFont.Ui18);
if (font.NativePtr == null) return;
byte* g = (byte*)ImGuiNative.ImFont_FindGlyphNoFallback(font.NativePtr, glyph[0]);
if (g == null) return;
float advance = *(float*)(g + 4);
if (advance <= 0) return;
float* box = (float*)(g + 8);
float scale = px / advance;
Vector2 centre = new((box[0] + box[2]) * 0.5f * scale, (box[1] + box[3]) * 0.5f * scale);
Vector2 at = min + size * 0.5f - centre;
dl.AddText(font, font.FontSize * scale, new Vector2(MathF.Round(at.X), MathF.Round(at.Y)), color, glyph);
}
}

View file

@ -0,0 +1,132 @@
using System;
namespace RynthCore.Plugin.RynthDefective.Ui;
/// <summary>
/// Display-list format 1 for the engine's script windows (RynthSuite
/// Docs/RYNTHLUA_WINDOWS_DESIGN.md §4.2-4.3; the engine's DisplayListParser.cs is the source of
/// truth). Little-endian. Only the ops RynthDefective draws are listed.
/// </summary>
internal static class UiFormat
{
public const uint Magic = 0x31575352; // 'RSW1'
public const ushort FormatVersion = 1;
public const uint BodyUnchanged = 0xFFFFFFFF;
public const int MaxString = 4096;
public const int MaxStr8 = 128;
public const int MaxOps = 1500; // engine limit per window
public const int MaxBodyBytes = 64 * 1024; // engine limit per window
public const byte OpHasBlock = 1;
// Ops
public const byte OpEnd = 0x00;
public const byte OpText = 0x01;
public const byte OpTextColored = 0x02;
public const byte OpTextWrapped = 0x03;
public const byte OpTextDisabled = 0x04;
public const byte OpBulletText = 0x05;
public const byte OpSeparatorText = 0x06;
public const byte OpSeparator = 0x10;
public const byte OpSameLine = 0x11;
public const byte OpSpacing = 0x13;
public const byte OpDummy = 0x14;
public const byte OpIndent = 0x15;
public const byte OpUnindent = 0x16;
public const byte OpButton = 0x20;
public const byte OpCheckbox = 0x21;
public const byte OpSliderInt = 0x22;
public const byte OpInputText = 0x24;
public const byte OpCombo = 0x25;
public const byte OpSelectable = 0x26;
public const byte OpProgressBar = 0x27;
public const byte OpImage = 0x28; // op level 2 (engines from 2026-09-30)
public const byte OpImageButton = 0x29;
public const byte OpPushID = 0x30;
public const byte OpPopID = 0x31;
public const byte OpPushStyleColor = 0x32;
public const byte OpPopStyleColor = 0x33;
public const byte OpSetItemTooltip = 0x38;
public const byte OpChild = 0x40;
public const byte OpCollapsingHeader = 0x41;
// Window flags
public const uint FlagVisible = 1u << 0;
public const uint FlagShowInBar = 1u << 1;
/// <summary>With ShowInBar: a bar button of its own instead of a Scripts menu line (engines from
/// 2026-10-11; older ones ignore it and list the window in the Scripts menu).</summary>
public const uint FlagBarButton = 1u << 11;
public const uint FlagNoScrollbar = 1u << 5;
// Image icon kinds (op level 2)
public const byte IconKindIcon = 0; // a 0x06 texture id
public const byte IconKindObject = 1; // a live object's icon with underlay and overlay
// Selectable flags
public const uint SelectableAllowDoubleClick = 4;
// Event types
public const ushort EvClicked = 1;
public const ushort EvBool = 2;
public const ushort EvInt = 3;
public const ushort EvText = 5;
public const ushort EvOpen = 6;
public const ushort EvVisibility = 8;
public const ushort EvError = 10;
// ImGuiCol ids the engine accepts in PushStyleColor (ImGui.NET 1.91.6.1)
public const int ColText = 0;
public const int ColButton = 21;
public const int ColButtonActive = 23;
public const int ColButtonHovered = 22;
public const int ColHeader = 24;
// InputText flags
public const uint InputAutoSelectAll = 4096;
/// <summary>The text box reports Enter (its event carries submitted = true).</summary>
public const uint InputEnterReturnsTrue = 32;
// CollapsingHeader flags
public const uint TreeDefaultOpen = 32;
public static uint Fnv1a(ReadOnlySpan<byte> bytes, uint hash = 2166136261)
{
foreach (byte b in bytes)
{
hash ^= b;
hash *= 16777619;
}
return hash;
}
/// <summary>The length of <paramref name="s"/> cut to at most <paramref name="max"/> bytes without splitting a character.</summary>
public static int CutUtf8(ReadOnlySpan<byte> s, int max)
{
if (s.Length <= max) return s.Length;
int n = Math.Max(0, max);
while (n > 0 && (s[n] & 0xC0) == 0x80) n--;
return n;
}
/// <summary>An ImGui U32 colour (0xAABBGGRR) from RGB bytes.</summary>
public static uint Rgb(byte r, byte g, byte b, byte a = 255) =>
((uint)a << 24) | ((uint)b << 16) | ((uint)g << 8) | r;
}
/// <summary>Colours RynthDefective uses (0xAABBGGRR).</summary>
internal static class UiColors
{
public static readonly uint Green = UiFormat.Rgb(110, 210, 110);
public static readonly uint Red = UiFormat.Rgb(225, 95, 95);
public static readonly uint Yellow = UiFormat.Rgb(235, 205, 90);
public static readonly uint Grey = UiFormat.Rgb(150, 150, 150);
public static readonly uint Gold = UiFormat.Rgb(230, 180, 60);
/// <summary>Upstream's "destruction" highlight: deep pink brightened by half (255, 30, 220).</summary>
public static readonly uint Destruction = UiFormat.Rgb(255, 30, 220);
public static readonly uint TabActive = UiFormat.Rgb(60, 110, 170);
public static readonly uint TabActiveHover = UiFormat.Rgb(75, 130, 195);
public static readonly uint OtherServer = UiFormat.Rgb(150, 185, 235);
public static readonly uint Stale = UiFormat.Rgb(225, 150, 80);
public static readonly uint White = UiFormat.Rgb(255, 255, 255);
/// <summary>The Lua script's amber (paused, full packs): 1.0, 0.75, 0.25.</summary>
public static readonly uint Amber = UiFormat.Rgb(255, 191, 64);
}

View file

@ -0,0 +1,202 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Text;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Ui;
/// <summary>
/// The plugin's side of the engine's script windows (API v71): polls the engine's events into
/// the windows' handlers and submits the window set when something changed. Plugin pump thread
/// only (inside the plugin's own tick), as the engine requires.
/// </summary>
internal sealed class UiHost
{
private readonly List<UiWindow> _windows = new();
private readonly Dictionary<uint, UiWindow> _byHash = new();
private byte[] _events = new byte[8192];
private byte[] _submit = new byte[64 * 1024];
private uint _lastSeq;
private bool _submittedSomething;
private long _retryAtMs;
private long _lastErrorLogMs;
public Action<string>? Log;
public IReadOnlyList<UiWindow> Windows => _windows;
public UiWindow Add(UiWindow w)
{
_windows.Add(w);
_byHash[w.Hash] = w;
return w;
}
/// <summary>Drains the engine's queued events into the windows' handlers.</summary>
public void Poll(RynthCoreHost host)
{
if (!host.HasUi || !_submittedSomething) return;
for (int round = 0; round < 8; round++)
{
int n = host.UiPollEvents(_events, out int remaining);
if (n > 0) Apply(_events.AsSpan(0, n));
if (remaining == 0) break;
if (n == 0) Array.Resize(ref _events, _events.Length * 2); // one event didn't fit
}
}
private void Apply(ReadOnlySpan<byte> data)
{
int pos = 0;
while (data.Length - pos >= 16)
{
ushort type = BinaryPrimitives.ReadUInt16LittleEndian(data[pos..]);
int size = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 2)..]);
if (size < 16 || size > data.Length - pos) break;
uint seq = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 4)..]);
uint window = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 8)..]);
uint key = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 12)..]);
ReadOnlySpan<byte> p = data.Slice(pos + 16, size - 16);
pos += size;
if (seq > _lastSeq) _lastSeq = seq;
_byHash.TryGetValue(window, out UiWindow? w);
switch (type)
{
case UiFormat.EvClicked when w != null && p.Length >= 2:
int count = BinaryPrimitives.ReadUInt16LittleEndian(p);
for (int i = 0; i < Math.Min(count, 4); i++) w.Dispatch(key, new UiEvent(type));
break;
case UiFormat.EvBool when w != null && p.Length >= 1:
w.Dispatch(key, new UiEvent(type, b: p[0] != 0));
break;
case UiFormat.EvInt when w != null && p.Length >= 4:
w.Dispatch(key, new UiEvent(type, i: BinaryPrimitives.ReadInt32LittleEndian(p)));
break;
case UiFormat.EvText when w != null && p.Length >= 3:
{
int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p[1..]), p.Length - 3);
w.Dispatch(key, new UiEvent(type, text: Encoding.UTF8.GetString(p.Slice(3, n)), submitted: p[0] != 0));
break;
}
case UiFormat.EvOpen when w != null && p.Length >= 1:
w.Dispatch(key, new UiEvent(type, b: p[0] != 0));
break;
case UiFormat.EvVisibility when w != null && p.Length >= 1:
// The player closed it (X) or opened it (bar menu / command): theirs wins.
w.Visible = p[0] != 0;
w.NeedsPass = true;
break;
case UiFormat.EvError when p.Length >= 2:
{
int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p), p.Length - 2);
Log?.Invoke("[RynthDefective] window error: " + Encoding.UTF8.GetString(p.Slice(2, n)));
break;
}
}
}
}
/// <summary>Sends the window set when any window's list or header changed.</summary>
public void Submit(RynthCoreHost host, long nowMs)
{
if (!host.HasUi || nowMs < _retryAtMs) return;
bool changed = !_submittedSomething && _windows.Count > 0;
foreach (UiWindow w in _windows)
if (w.BodyDirty || w.HeaderDirty) { changed = true; break; }
if (!changed) return;
int pos = Write();
int rc = host.UiSubmit(_submit.AsSpan(0, pos));
if (rc == 0)
{
foreach (UiWindow w in _windows) w.MarkSubmitted(w.BodyDirty);
_submittedSomething = true;
}
else
{
// Nothing was applied; the engine keeps the previous lists. Try again in a second.
_retryAtMs = nowMs + 1000;
if (nowMs - _lastErrorLogMs > 10_000)
{
_lastErrorLogMs = nowMs;
Log?.Invoke($"[RynthDefective] the engine refused the window list ({rc}).");
}
}
}
/// <summary>Removes every window from the engine (logout, shutdown). Their placement is kept by the engine.</summary>
public void SubmitEmpty(RynthCoreHost host)
{
if (!host.HasUi || !_submittedSomething) return;
Span<byte> b = stackalloc byte[16];
BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic);
BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion);
BinaryPrimitives.WriteUInt16LittleEndian(b[6..], 0);
BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq);
BinaryPrimitives.WriteUInt32LittleEndian(b[12..], 16);
if (host.UiSubmit(b) == 0)
{
_submittedSomething = false;
foreach (UiWindow w in _windows) w.ForgetSubmitted();
}
}
private int Write()
{
int size = 16;
foreach (UiWindow w in _windows) size += 2 * (1 + UiFormat.MaxStr8) + 4 + 32 + 8 + (w.BodyDirty ? w.Body.Length : 0);
if (_submit.Length < size) _submit = new byte[Math.Max(size, _submit.Length * 2)];
Span<byte> b = _submit;
BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic);
BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion);
BinaryPrimitives.WriteUInt16LittleEndian(b[6..], (ushort)_windows.Count);
// Every event polled so far has been applied (handlers run as they arrive).
BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq);
int pos = 16;
foreach (UiWindow w in _windows)
{
pos = Str8(b, pos, w.KeyUtf8);
pos = Str8(b, pos, Encoding.UTF8.GetBytes(w.Title ?? string.Empty));
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.Flags); pos += 4;
pos = F32(b, pos, w.DefaultWidth);
pos = F32(b, pos, w.DefaultHeight);
pos = F32(b, pos, w.MinWidth);
pos = F32(b, pos, w.MinHeight);
pos = F32(b, pos, w.RequestWidth); // RequestSize: a one-shot, else none
pos = F32(b, pos, w.RequestHeight);
pos = F32(b, pos, float.NaN); // RequestPos: none
pos = F32(b, pos, float.NaN);
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.ListSeq); pos += 4;
if (w.BodyDirty)
{
ReadOnlySpan<byte> body = w.Body;
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], (uint)body.Length); pos += 4;
body.CopyTo(b[pos..]);
pos += body.Length;
}
else
{
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], UiFormat.BodyUnchanged); pos += 4;
}
}
BinaryPrimitives.WriteUInt32LittleEndian(b[12..], (uint)pos);
return pos;
}
private static int Str8(Span<byte> b, int pos, ReadOnlySpan<byte> s)
{
int n = UiFormat.CutUtf8(s, UiFormat.MaxStr8);
b[pos] = (byte)n;
s[..n].CopyTo(b[(pos + 1)..]);
return pos + 1 + n;
}
private static int F32(Span<byte> b, int pos, float v)
{
BinaryPrimitives.WriteSingleLittleEndian(b[pos..], v);
return pos + 4;
}
}

View file

@ -0,0 +1,543 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthDefective.Ui;
/// <summary>One input from the engine for a widget (a click, a new value, an open state).</summary>
internal readonly struct UiEvent
{
public readonly ushort Type;
public readonly bool Bool;
public readonly int Int;
public readonly string Text;
public readonly bool Submitted;
public UiEvent(ushort type, bool b = false, int i = 0, string? text = null, bool submitted = false)
{
Type = type;
Bool = b;
Int = i;
Text = text ?? string.Empty;
Submitted = submitted;
}
}
/// <summary>
/// One script window (engine API v71) and its recorder. A render pass records ImGui-style calls
/// into a display list; every widget's handler (click, value change) is kept by its widget key
/// until the next pass, so an event from the engine runs the code that drew that widget.
///
/// Widget keys are FNV-1a(id, window hash): RynthDefective names every widget itself, so it needs
/// no ID stack. ImGui sees "label###id": its ID comes from the id alone, so labels can change.
/// The engine echoes the key in events and keys its per-widget local values by it.
/// </summary>
internal sealed class UiWindow
{
public readonly string Key;
public readonly byte[] KeyUtf8;
public readonly uint Hash;
public string Title;
public bool Visible;
public bool ShowInBar = true;
/// <summary>With ShowInBar: the window has its own button on the RynthCore bar (title as the
/// tooltip) rather than a line in the Scripts menu.</summary>
public bool BarButton = true;
public float DefaultWidth, DefaultHeight, MinWidth, MinHeight;
/// <summary>
/// A one-shot request for the window's size (logical units; NaN = none). Sent with the next
/// submit and then forgotten: the engine re-applies a standing request on every re-recorded
/// list, which would undo the player's own resizing.
/// </summary>
public float RequestWidth = float.NaN, RequestHeight = float.NaN;
/// <summary>A pass is wanted at the next chance (input arrived, it was just shown, data changed).</summary>
public bool NeedsPass = true;
public long NextPassMs;
// The list as recorded by the last pass, and what the engine last accepted.
private byte[] _body = new byte[16 * 1024];
private int _len;
private int _ops;
private bool _cut;
private byte[] _sentBody = Array.Empty<byte>();
private int _sentLen = -1;
public uint ListSeq { get; private set; }
internal bool BodyDirty;
// Header as last accepted by the engine.
private string? _sentTitle;
private uint _sentFlags;
private float _sentDw = float.NaN, _sentDh, _sentMw, _sentMh;
private Dictionary<uint, Action<UiEvent>> _handlers = new();
private Dictionary<uint, Action<UiEvent>> _next = new();
private readonly Dictionary<uint, bool> _openStates = new();
// Child blocks: where each open block's u32 length sits, or -1 when the block was dropped.
private readonly int[] _blocks = new int[16];
private int _blockDepth;
private byte[] _tmp = new byte[512];
public UiWindow(string key, string title)
{
Key = key;
KeyUtf8 = Encoding.UTF8.GetBytes(key);
Hash = UiFormat.Fnv1a(KeyUtf8);
Title = title;
}
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0)
| (ShowInBar && BarButton ? UiFormat.FlagBarButton : 0);
public bool HeaderDirty =>
_sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight
|| _sentMw != MinWidth || _sentMh != MinHeight || !float.IsNaN(RequestWidth);
public ReadOnlySpan<byte> Body => _body.AsSpan(0, _len);
// ── Pass ────────────────────────────────────────────────────────────────
public void Begin()
{
_len = 0;
_ops = 0;
_cut = false;
_blockDepth = 0;
_next.Clear();
}
/// <summary>Ends the pass: closes open blocks, writes End, and notes whether the list changed.</summary>
public void End()
{
while (_blockDepth > 0) EndChild();
if (_cut)
{
// Room was kept for this line (see Room).
int p = BeginOp(UiFormat.OpTextDisabled);
Str("(more than fits in one window; narrow the list)");
EndOp(p);
}
Ensure(4);
_body[_len++] = UiFormat.OpEnd;
_body[_len++] = 0;
_body[_len++] = 0;
_body[_len++] = 0;
(_handlers, _next) = (_next, _handlers);
bool differs = _sentLen != _len || !_body.AsSpan(0, _len).SequenceEqual(_sentBody.AsSpan(0, _sentLen));
if (differs && !BodyDirty) ListSeq++;
BodyDirty = differs;
}
/// <summary>The engine accepted the last submit: remember what it now has.</summary>
internal void MarkSubmitted(bool bodySent)
{
if (bodySent)
{
if (_sentBody.Length < _len) _sentBody = new byte[_body.Length];
_body.AsSpan(0, _len).CopyTo(_sentBody);
_sentLen = _len;
BodyDirty = false;
}
_sentTitle = Title;
_sentFlags = Flags;
_sentDw = DefaultWidth; _sentDh = DefaultHeight; _sentMw = MinWidth; _sentMh = MinHeight;
RequestWidth = RequestHeight = float.NaN; // sent once
}
/// <summary>The engine dropped every window (logout, empty submit): send everything again next time.</summary>
internal void ForgetSubmitted()
{
_sentLen = -1;
_sentTitle = null;
BodyDirty = _len > 0;
}
internal void Dispatch(uint widgetKey, in UiEvent e)
{
if (_handlers.TryGetValue(widgetKey, out Action<UiEvent>? h))
h(e);
NeedsPass = true;
}
// ── Widgets ─────────────────────────────────────────────────────────────
public uint KeyOf(string id)
{
int max = Encoding.UTF8.GetMaxByteCount(id.Length);
if (_tmp.Length < max) _tmp = new byte[Math.Max(max, _tmp.Length * 2)];
int n = Encoding.UTF8.GetBytes(id, _tmp);
return UiFormat.Fnv1a(_tmp.AsSpan(0, n), Hash);
}
public void Text(string text) => WriteText(UiFormat.OpText, text);
public void TextDisabled(string text) => WriteText(UiFormat.OpTextDisabled, text);
public void TextWrapped(string text) => WriteText(UiFormat.OpTextWrapped, text);
public void BulletText(string text) => WriteText(UiFormat.OpBulletText, text);
public void SeparatorText(string text) => WriteText(UiFormat.OpSeparatorText, text);
public void TextColored(uint abgr, string text)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpTextColored);
U32(abgr);
Str(text);
EndOp(p);
}
public void Separator()
{
if (!Room()) return;
EndOp(BeginOp(UiFormat.OpSeparator));
}
public void Spacing()
{
if (!Room()) return;
EndOp(BeginOp(UiFormat.OpSpacing));
}
/// <summary>Next item on the same line, <paramref name="x"/> logical units from the content start (0 = right after).</summary>
public void SameLine(float x = 0f, float spacing = -1f)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpSameLine);
F32(x);
F32(spacing);
EndOp(p);
}
public void Dummy(float w, float h)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpDummy);
F32(w);
F32(h);
EndOp(p);
}
/// <summary>Moves the following items right by <paramref name="w"/> logical units, until <see cref="Unindent"/>.</summary>
public void Indent(float w)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpIndent);
F32(w);
EndOp(p);
}
public void Unindent(float w)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpUnindent);
F32(w);
EndOp(p);
}
public void Button(string label, string id, Action onClick, float w = 0f, float h = 0f, bool small = false)
{
if (!Room()) return;
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpButton);
U32(key);
Str(label + "###" + id);
F32(w);
F32(h);
U8(small ? (byte)1 : (byte)0);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
}
public void SmallButton(string label, string id, Action onClick) => Button(label, id, onClick, small: true);
/// <summary>A button drawn highlighted when <paramref name="active"/> (tabs, toggles).</summary>
public void ToggleButton(string label, string id, bool active, Action onClick, bool small = false)
{
if (active)
{
PushStyleColor(UiFormat.ColButton, UiColors.TabActive);
PushStyleColor(UiFormat.ColButtonHovered, UiColors.TabActiveHover);
}
Button(label, id, onClick, small: small);
if (active) PopStyleColor(2);
}
public void Checkbox(string label, string id, bool value, Action<bool> set)
{
if (!Room()) return;
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpCheckbox);
U32(key);
Str(label + "###" + id);
U8(value ? (byte)1 : (byte)0);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvBool) set(e.Bool); };
}
/// <summary>An integer slider from <paramref name="min"/> to <paramref name="max"/> (clamped by the engine).</summary>
public void SliderInt(string label, string id, int value, int min, int max, Action<int> set, string format = "%d")
{
if (!Room()) return;
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpSliderInt);
U32(key);
Str(label + "###" + id);
I32(value);
I32(min);
I32(max);
Str(format);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvInt) set(Math.Clamp(e.Int, min, max)); };
}
/// <summary>A text box; <paramref name="set"/> gets every edit (submitted = Enter was pressed).</summary>
public void InputText(string label, string id, string value, int maxLen, Action<string> set, uint flags = 0) =>
InputText(label, id, value, maxLen, (text, _) => set(text), flags);
/// <summary>A text box; <paramref name="set"/> gets every edit and whether Enter was pressed.</summary>
public void InputText(string label, string id, string value, int maxLen, Action<string, bool> set, uint flags = 0)
{
if (!Room()) return;
maxLen = Math.Clamp(maxLen, 1, UiFormat.MaxString);
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpInputText);
U32(key);
Str(label + "###" + id);
Str(value ?? string.Empty, maxLen);
U16((ushort)maxLen);
U32(flags);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvText) set(e.Text, e.Submitted); };
}
public void Combo(string label, string id, int index, IReadOnlyList<string> items, Action<int> set)
{
if (!Room()) return;
uint key = KeyOf(id);
int count = Math.Min(items.Count, 512);
int p = BeginOp(UiFormat.OpCombo);
U32(key);
Str(label + "###" + id);
I32(index);
U16((ushort)count);
for (int i = 0; i < count; i++) Str(items[i]);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvInt) set(e.Int); };
}
public void Selectable(string label, string id, bool selected, Action onClick, float w = 0f, float h = 0f)
{
if (!Room()) return;
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpSelectable);
U32(key);
Str(label + "###" + id);
U8(selected ? (byte)1 : (byte)0);
U32(0);
F32(w);
F32(h);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
}
public void ProgressBar(float fraction, float w, float h, string overlay)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpProgressBar);
F32(float.IsFinite(fraction) ? Math.Clamp(fraction, 0f, 1f) : 0f);
F32(w);
F32(h);
Str(overlay ?? string.Empty);
EndOp(p);
}
/// <summary>
/// An icon (op level 2): <paramref name="kind"/> <see cref="UiFormat.IconKindIcon"/> = a 0x06
/// texture id, <see cref="UiFormat.IconKindObject"/> = a live object (its icon with underlay and
/// overlay). Engines without op level 2 skip it (the caller checks first so the layout doesn't shift).
/// </summary>
public void Image(byte kind, uint id, float w, float h, uint tint = 0xFFFFFFFFu)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpImage);
U8(kind);
U32(id);
F32(w);
F32(h);
F32(0f); F32(0f); // uv0
F32(1f); F32(1f); // uv1
U32(tint);
U32(0u); // border: none
EndOp(p);
}
/// <summary>A button with an icon on it (op level 2); <paramref name="tint"/> dims or colours the picture, <paramref name="background"/> fills behind it.</summary>
public void ImageButton(byte kind, uint iconId, string id, Action onClick, float w, float h, uint tint = 0xFFFFFFFFu, uint background = 0u)
{
if (!Room()) return;
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpImageButton);
U32(key);
Str(id);
U8(kind);
U32(iconId);
F32(w);
F32(h);
F32(0f); F32(0f); // uv0
F32(1f); F32(1f); // uv1
U32(background); // background fill behind the picture (0 = none)
U32(tint);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
}
/// <summary>Tooltip for the item just drawn.</summary>
public void Tooltip(string text)
{
if (!Room() || string.IsNullOrEmpty(text)) return;
int p = BeginOp(UiFormat.OpSetItemTooltip);
Str(text);
EndOp(p);
}
public void PushStyleColor(int colId, uint abgr)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpPushStyleColor);
U16((ushort)colId);
U32(abgr);
EndOp(p);
}
/// <summary>Pops are dropped when the list is cut short; the engine pops leftovers at the scope's end.</summary>
public void PopStyleColor(int count = 1)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpPopStyleColor);
U8((byte)Math.Clamp(count, 1, 255));
EndOp(p);
}
/// <summary>
/// A collapsing header; returns whether to record its contents. The open state is the
/// player's (kept from the engine's Open events), so a header stays as they left it.
/// </summary>
public bool CollapsingHeader(string label, string id, bool defaultOpen = false)
{
uint key = KeyOf(id);
bool open = _openStates.TryGetValue(key, out bool o) ? o : defaultOpen;
if (!Room()) return false;
int p = BeginOp(UiFormat.OpCollapsingHeader);
U32(key);
Str(label + "###" + id);
U32(defaultOpen ? UiFormat.TreeDefaultOpen : 0);
U8(open ? (byte)1 : (byte)0);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvOpen) _openStates[key] = e.Bool; };
return open;
}
/// <summary>A scrolling region; h 0 = fill the rest of the window. Must be closed with <see cref="EndChild"/>.</summary>
public void BeginChild(string id, float w = 0f, float h = 0f, bool border = true)
{
if (_blockDepth >= _blocks.Length) throw new InvalidOperationException("child regions nested too deep");
if (!Room())
{
_blocks[_blockDepth++] = -1;
return;
}
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpChild, UiFormat.OpHasBlock);
U32(key);
Str(id);
F32(w);
F32(h);
U8(border ? (byte)1 : (byte)0);
U32(0);
EndOp(p);
_blocks[_blockDepth++] = _len;
U32(0); // BlockLength, patched by EndChild
}
public void EndChild()
{
if (_blockDepth == 0) return;
int at = _blocks[--_blockDepth];
if (at < 0) return;
BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(at), (uint)(_len - (at + 4)));
}
// ── Writing ─────────────────────────────────────────────────────────────
/// <summary>
/// Whether another op fits. Room is kept for the closing "list cut short" line and the End
/// op, so the list never goes over the engine's limits (it refuses an over-limit list whole).
/// </summary>
private bool Room()
{
if (_cut) return false;
if (_ops < UiFormat.MaxOps - 8 && _len < UiFormat.MaxBodyBytes - 4096) return true;
_cut = true;
return false;
}
private void WriteText(byte code, string text)
{
if (!Room()) return;
int p = BeginOp(code);
Str(text);
EndOp(p);
}
private int BeginOp(byte code, byte opFlags = 0)
{
_ops++;
Ensure(4);
_body[_len++] = code;
_body[_len++] = opFlags;
_len += 2; // PayloadLength, patched by EndOp
return _len;
}
private void EndOp(int payloadStart)
{
int length = _len - payloadStart;
BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(payloadStart - 2), (ushort)Math.Min(length, ushort.MaxValue));
}
private void Ensure(int extra)
{
if (_len + extra <= _body.Length) return;
int size = _body.Length;
while (size < _len + extra) size *= 2;
Array.Resize(ref _body, size);
}
private void U8(byte v) { Ensure(1); _body[_len++] = v; }
private void U16(ushort v) { Ensure(2); BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), v); _len += 2; }
private void U32(uint v) { Ensure(4); BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; }
private void I32(int v) { Ensure(4); BinaryPrimitives.WriteInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; }
private void F32(float v)
{
Ensure(4);
BinaryPrimitives.WriteSingleLittleEndian(_body.AsSpan(_len), float.IsFinite(v) ? v : 0f);
_len += 4;
}
/// <summary>str: u16 length + UTF-8, cut to <paramref name="maxBytes"/> on a character boundary.</summary>
private void Str(string s, int maxBytes = UiFormat.MaxString)
{
s ??= string.Empty;
ReadOnlySpan<char> src = s.Length > maxBytes ? s.AsSpan(0, maxBytes) : s.AsSpan();
Ensure(2 + Encoding.UTF8.GetMaxByteCount(src.Length));
int at = _len + 2;
Span<byte> dst = _body.AsSpan(at);
int n = UiFormat.CutUtf8(dst[..Encoding.UTF8.GetBytes(src, dst)], maxBytes);
BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), (ushort)n);
_len = at + n;
}
}

View file

@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.Json;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Use;
/// <summary>
/// The controller's view of the game through the engine host. Plugin pump thread only (the
/// plugin's tick), which is also where RynthAi's interfaces may be called.
/// </summary>
internal sealed unsafe class HostDefWorld : IDefWorld
{
private const long SnapshotMaxAgeMs = 250;
private readonly RynthCoreHost _host;
private readonly HostInventory _reader = new();
private List<CarriedItem> _items = new();
private long _itemsAtMs = long.MinValue / 4;
private int _revision;
public HostDefWorld(RynthCoreHost host) => _host = host;
public long NowMs => Environment.TickCount64;
public bool InWorld => _host.HasGetPlayerId && _host.GetPlayerId() != 0 && !(_host.HasIsPortaling && _host.IsPortaling());
public uint PlayerId => _host.HasGetPlayerId ? _host.GetPlayerId() : 0;
public uint SelectedId => _host.HasGetSelectedItemId ? _host.GetSelectedItemId() : 0;
public bool ClientBusy => _host.HasGetBusyState && _host.GetBusyState() != 0;
public bool Animating => _host.HasGetCastBusyState && _host.GetCastBusyState() != 0;
public int UseDoneSeq => _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
public int CombatMode => _host.GetCurrentCombatMode();
public bool? BotWaitingOnServer => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.ServerAction) != 0 : null;
public bool? BotMacroRunning => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.MacroRunning) != 0 : null;
public int RefusalSeq => _host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0;
public bool RefusalNamed(uint objectId) =>
_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out _, out _, out _, out uint obj) && obj == objectId;
/// <summary>The inventory, re-read when it is older than a quarter second.</summary>
public IReadOnlyList<CarriedItem> Items() => Snapshot(SnapshotMaxAgeMs);
/// <summary>The inventory, re-read when it is older than <paramref name="maxAgeMs"/>.</summary>
public List<CarriedItem> Snapshot(long maxAgeMs)
{
long now = NowMs;
if (now - _itemsAtMs >= maxAgeMs)
{
_items = _reader.Read(_host, now);
_itemsAtMs = now;
_revision++;
}
return _items;
}
/// <summary>Counts re-reads (the plugin redraws and re-binds slots when it moved).</summary>
public int Revision => _revision;
public CarriedItem? Live(uint id) => _reader.ReadOne(_host, id, NowMs);
public bool UseObject(uint id) => _host.HasUseObject && _host.UseObject(id);
public bool UseObjectOn(uint id, uint target) => _host.HasUseObjectOn && _host.UseObjectOn(id, target);
public bool SetCombatMode(int mode) => _host.HasChangeCombatMode && _host.ChangeCombatMode(mode);
public void Reset()
{
_reader.Reset();
_items = new List<CarriedItem>();
_itemsAtMs = long.MinValue / 4;
}
}
/// <summary>
/// RynthAi's activity bits: its "RynthAi.Activity" interface; on an older RynthAi without it, the
/// macro bit from "RynthAi.Status"; null when RynthAi isn't loaded or not ready. Resolved again every
/// call: a RynthAi reload frees the tables. Read only: nothing here changes what RynthAi does.
/// </summary>
internal static unsafe class BotActivity
{
public static RynthAiActivity? Read(RynthCoreHost host)
{
if (!host.HasGetPluginInterface) return null;
try
{
var act = (RynthAiActivityApiV1*)host.GetPluginInterface("RynthAi", RynthAiActivityApiV1.InterfaceName, RynthAiActivityApiV1.InterfaceVersion);
if (act != null && act->Version >= 1 && act->StructSize >= (uint)sizeof(RynthAiActivityApiV1) && act->GetActivityFlags != null)
{
uint flags = 0;
return act->GetActivityFlags(&flags) != 0 ? (RynthAiActivity)flags : null;
}
var status = (RynthAiStatusApiV1*)host.GetPluginInterface("RynthAi", RynthAiStatusApiV1.InterfaceName, RynthAiStatusApiV1.InterfaceVersion);
if (status != null && status->Version >= 1 && status->StructSize >= (uint)sizeof(RynthAiStatusApiV1) && status->GetStatusJson != null)
{
byte* r = null;
if (status->GetStatusJson(&r) != 0 && r != null)
return FromStatusJson(Marshal.PtrToStringUTF8((IntPtr)r));
}
}
catch
{
// A RynthAi mid-reload: treat as not there this tick.
}
return null;
}
/// <summary>The macro bit an older RynthAi's status JSON ({macro, action, ...}) gives (no server-wait bit).</summary>
internal static RynthAiActivity? FromStatusJson(string? json)
{
if (string.IsNullOrEmpty(json) || json[0] != '{') return null;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
bool macro = doc.RootElement.TryGetProperty("macro", out JsonElement m) && m.ValueKind == JsonValueKind.True;
return macro ? RynthAiActivity.MacroRunning : RynthAiActivity.None;
}
catch (JsonException)
{
return null;
}
}
}

View file

@ -0,0 +1,382 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
namespace RynthCore.Plugin.RynthDefective.Use;
/// <summary>
/// What the controller needs from the game. The host implements it (HostDefWorld); the tests
/// script it. Plugin pump thread only.
/// </summary>
internal interface IDefWorld
{
long NowMs { get; }
/// <summary>A character is in the world and not in portal space.</summary>
bool InWorld { get; }
uint PlayerId { get; }
uint SelectedId { get; }
/// <summary>The client's busy count is above zero (an item action it sent has not been answered).</summary>
bool ClientBusy { get; }
/// <summary>A cast or use gesture is animating.</summary>
bool Animating { get; }
/// <summary>RynthAi is waiting on the server for an action it sent (null = RynthAi isn't there).</summary>
bool? BotWaitingOnServer { get; }
/// <summary>RynthAi's macro is running (null = RynthAi isn't there).</summary>
bool? BotMacroRunning { get; }
/// <summary>Count of the server's UseDone events; 0 when the engine can't report them.</summary>
int UseDoneSeq { get; }
/// <summary>1 NonCombat, 2 Melee, 4 Missile, 8 Magic.</summary>
int CombatMode { get; }
/// <summary>The server's refusals so far (0x028A / 0x00A0 ... count), to tell a new one.</summary>
int RefusalSeq { get; }
/// <summary>The newest refusal named this object (a refused wield: InventoryServerSaveFailed).</summary>
bool RefusalNamed(uint objectId);
/// <summary>Everything carried and worn, as the client has it now.</summary>
IReadOnlyList<CarriedItem> Items();
/// <summary>The item as the client has it this instant (wielded or not); null if it is gone.</summary>
CarriedItem? Live(uint id);
bool UseObject(uint id);
bool UseObjectOn(uint id, uint target);
bool SetCombatMode(int mode);
}
/// <summary>One thing the player asked to use: an exact item (a slot's) or a name typed in a command.</summary>
internal sealed record UseRequest(ItemRef? Item, string? Name, UseMode Mode, string Source, long AtMs)
{
/// <summary>Same item, same way: pressing the key again must not queue a second one.</summary>
public bool SameAs(UseRequest o) =>
Mode == o.Mode
&& ((Item != null && o.Item != null && Item.SameAs(o.Item))
|| (Name != null && o.Name != null && string.Equals(Name, o.Name, StringComparison.OrdinalIgnoreCase)));
public string Label => Item?.FullName ?? Name ?? "item";
}
/// <summary>The combat stance a weapon swap leaves the character in.</summary>
internal static class Stance
{
public const int NonCombat = 1, Melee = 2, Missile = 4, Magic = 8;
/// <summary>
/// The stance to ask for after <paramref name="weapon"/> was wielded, 0 = leave it alone.
/// A character at peace stays at peace. One in a fighting stance goes to the new weapon's:
/// Melee, Missile (a launcher needs its ammunition in hand: without it the client refuses the
/// stance, so the character goes to peace rather than being left in a stance the weapon can't
/// use), or Magic for a caster. Shields, armor and ammunition keep the stance they are in.
/// </summary>
public static int Wanted(ItemKind kind, bool launcherNeedsAmmo, bool ammoInHand, int modeBefore)
{
if (modeBefore == NonCombat || modeBefore == 0) return 0;
switch (kind)
{
case ItemKind.Melee: return Melee;
case ItemKind.WarWand:
case ItemKind.VoidWand: return Magic;
case ItemKind.Missile: return launcherNeedsAmmo && !ammoInHand ? NonCombat : Missile;
default: return 0;
}
}
public static string Name(int mode) => mode switch
{
NonCombat => "peace",
Melee => "melee",
Missile => "missile",
Magic => "magic",
_ => "mode " + mode,
};
}
/// <summary>
/// One use at a time. A request (a slot pressed, /rdef use, the picker) is held until the
/// character is free, then sent; the next waits for the server's answer. A second request while one
/// is waiting replaces it (the newest wish wins) unless it is the same one (a key held down does
/// not queue twice). Nothing is retried in a loop: a refused or unanswered action is reported once.
///
/// What is sent (the host calls RynthAi's own one-touch heal and weapon swap use):
/// kits UseObjectOn(kit, you) answered by the server's UseDone
/// consumables UseObject(item) answered by UseDone
/// weapons etc. UseObject(item): the client's double-click, which takes what is in the way off;
/// answered when the item reads wielded (a wield sends no UseDone), then the stance
/// is put right (<see cref="Stance.Wanted"/>) once the character is still.
/// Busy: nothing is sent while the client's busy count is up, a gesture animates, RynthAi waits on
/// the server, the last action is unanswered, or for <see cref="MinGapMs"/> after it - the "one item
/// action at a time" rule RynthAi's ActionPacer keeps. Weapon swaps also wait out a running RynthAi
/// macro unless the player allowed them (it would swap straight back).
/// </summary>
internal sealed class UseController
{
/// <summary>How long a request waits for the character to be free before it gives up and says why.</summary>
public const long WaitLimitMs = 6000;
/// <summary>A use with no UseDone by now is let go (RynthAi waits 8 s for a kit's result).</summary>
public const long UseTimeoutMs = 8000;
/// <summary>A use the client no longer holds busy, with no UseDone, is let go after this.</summary>
public const long UseQuietMs = 1500;
public const long WieldTimeoutMs = 3500;
public const long MinGapMs = 250;
public const long StanceSettleMs = 500;
public const long StanceTimeoutMs = 4000;
private enum Stage { Sent, WaitWield, Stance }
private sealed class Flight
{
public UseRequest Request = null!;
public CarriedItem Item = null!;
public UseAction Action;
public ItemKind Kind;
public long SentMs;
public int UseDoneAtSend, RefusalAtSend, ModeBefore;
public Stage Stage;
public long StageMs;
}
private UseRequest? _pending;
private Flight? _flight;
private long _lastDoneMs = long.MinValue / 4;
private string _lastWait = string.Empty;
/// <summary>Plain information ("Using Peerless Healing Kit ..."): the status line, not the chat.</summary>
public Action<string>? Say;
/// <summary>Something went wrong or didn't happen: the status line and the chat.</summary>
public Action<string>? Warn;
public Action<string>? Log;
/// <summary>A weapon was wielded (the picker's recent list).</summary>
public Action<CarriedItem>? Wielded;
public bool HasPending => _pending != null;
public bool InFlight => _flight != null;
public UseRequest? Pending => _pending;
/// <summary>The item a request in flight or waiting is about, for highlighting its slot.</summary>
public bool Involves(ItemRef r) =>
(_pending?.Item != null && _pending.Item.SameAs(r)) || (_flight?.Request.Item != null && _flight.Request.Item.SameAs(r));
public DefSettings Settings = new();
/// <summary>Queues a request. False when it is the one already waiting or in flight (a held key).</summary>
public bool Request(UseRequest r)
{
if (_pending != null && _pending.SameAs(r)) return false;
if (_flight != null && _flight.Action == UseAction.Equip && _flight.Request.SameAs(r)) return false; // already wielding it
_pending = r;
_lastWait = string.Empty;
return true;
}
/// <summary>Drops what is waiting and forgets what is in flight (logout, portal space, shutdown).</summary>
public void Reset()
{
_pending = null;
_flight = null;
_lastWait = string.Empty;
}
public void Tick(IDefWorld w)
{
if (!w.InWorld)
{
if (_pending != null || _flight != null) Reset();
return;
}
long now = w.NowMs;
if (_flight != null && !AdvanceFlight(w, now)) return; // still in flight: nothing new goes out
if (_pending == null) return;
UseRequest req = _pending;
string? wait = WaitReason(w, now);
if (wait != null)
{
_lastWait = wait;
if (now - req.AtMs >= WaitLimitMs)
{
_pending = null;
Warn?.Invoke($"{req.Label}: not used, {wait}.");
}
return;
}
_pending = null;
Send(w, req, now);
}
private string? WaitReason(IDefWorld w, long now)
{
if (now - _lastDoneMs < MinGapMs) return "the last action just finished";
if (w.ClientBusy) return "the character is busy";
if (w.Animating) return "an animation is playing";
if (w.BotWaitingOnServer == true) return "RynthAi is waiting on the server";
return null;
}
// ── Sending ─────────────────────────────────────────────────────────────
private void Send(IDefWorld w, UseRequest req, long now)
{
IReadOnlyList<CarriedItem> items = w.Items();
CarriedItem? item = req.Item != null
? ItemMatcher.Find(req.Item, items, out _)
: ItemMatcher.FindByName(req.Name ?? string.Empty, items);
if (item == null)
{
Warn?.Invoke(req.Item != null
? $"{req.Label}: you aren't carrying one."
: $"No item named '{req.Name}' in your pack.");
return;
}
ItemKind kind = ItemKinds.Classify(item);
UseAction action = UseModes.ActionFor(req.Mode, kind);
string name = item.FullName;
if (action == UseAction.Equip)
{
if (item.Wielded)
{
Say?.Invoke($"{name} is already in your hands.");
return;
}
if (ItemKinds.IsWeapon(kind) && !Settings.SwapWhileBotRuns && w.BotMacroRunning == true)
{
Warn?.Invoke($"{name}: not wielded, RynthAi's macro is running and picks the weapon itself (stop it, or allow swaps in the Defective settings).");
return;
}
}
uint target = 0;
if (action == UseAction.UseOnSelf) target = w.PlayerId;
else if (action == UseAction.UseOnSelected)
{
target = w.SelectedId;
if (target == 0)
{
Warn?.Invoke($"{name}: select a target first.");
return;
}
}
if ((action == UseAction.UseOnSelf || action == UseAction.UseOnSelected) && target == 0)
{
Warn?.Invoke($"{name}: the character isn't ready.");
return;
}
bool sent = target != 0 ? w.UseObjectOn(item.Id, target) : w.UseObject(item.Id);
if (!sent)
{
Warn?.Invoke($"{name}: the client didn't take the request (nothing was sent).");
return;
}
_flight = new Flight
{
Request = req,
Item = item,
Action = action,
Kind = kind,
SentMs = now,
StageMs = now,
UseDoneAtSend = w.UseDoneSeq,
RefusalAtSend = w.RefusalSeq,
ModeBefore = w.CombatMode,
Stage = action == UseAction.Equip ? Stage.WaitWield : Stage.Sent,
};
Log?.Invoke($"[RynthDefective] {req.Source}: {(action == UseAction.Equip ? "wield" : target != 0 ? "use on " + (target == w.PlayerId ? "you" : "0x" + target.ToString("X8")) : "use")} {item} (stack {item.Stack}, mode {Stance.Name(w.CombatMode)})");
Say?.Invoke(action == UseAction.Equip ? $"Wielding {name}..." : $"Using {name}...");
}
// ── In flight ───────────────────────────────────────────────────────────
/// <summary>Steps the action in flight; true when it is finished (a new one may go out this tick).</summary>
private bool AdvanceFlight(IDefWorld w, long now)
{
Flight f = _flight!;
long age = now - f.SentMs;
switch (f.Stage)
{
case Stage.Sent:
{
bool answered = w.UseDoneSeq != f.UseDoneAtSend;
bool quiet = age >= UseQuietMs && !w.ClientBusy && !w.Animating;
if (answered || quiet || age >= UseTimeoutMs)
{
if (!answered && age >= UseTimeoutMs) Log?.Invoke($"[RynthDefective] no UseDone for {f.Item} after {age} ms; carrying on");
Finish(now);
return true;
}
return false;
}
case Stage.WaitWield:
{
CarriedItem? live = w.Live(f.Item.Id);
if (live != null && live.Wielded)
{
Wielded?.Invoke(live);
f.Item = live;
f.Stage = Stage.Stance;
f.StageMs = now;
return AdvanceStance(w, f, now);
}
if (w.RefusalSeq != f.RefusalAtSend && w.RefusalNamed(f.Item.Id))
{
Warn?.Invoke($"{f.Item.FullName}: the server wouldn't let you wield it (a skill, level or slot requirement?).");
Finish(now);
return true;
}
if (age >= WieldTimeoutMs)
{
Warn?.Invoke($"{f.Item.FullName}: not in your hands after {age / 1000.0:0.0} s - something may be in the way, or the character was busy. Try again.");
Finish(now);
return true;
}
return false;
}
default:
return AdvanceStance(w, f, now);
}
}
private bool AdvanceStance(IDefWorld w, Flight f, long now)
{
bool launcher = f.Kind == ItemKind.Missile && ItemKinds.NeedsAmmo(f.Item);
int want = Stance.Wanted(f.Kind, launcher, AmmoInHand(w), f.ModeBefore);
if (want == 0 || w.CombatMode == want)
{
Say?.Invoke($"{f.Item.FullName} is in your hands.");
Finish(now);
return true;
}
long since = now - f.StageMs;
if (since >= StanceTimeoutMs)
{
Warn?.Invoke($"{f.Item.FullName} is wielded but the {Stance.Name(want)} stance wasn't taken ({Stance.Name(w.CombatMode)} now).");
Finish(now);
return true;
}
if (since < StanceSettleMs || w.ClientBusy || w.Animating) return false;
if (w.SetCombatMode(want))
{
Log?.Invoke($"[RynthDefective] stance {Stance.Name(w.CombatMode)} -> {Stance.Name(want)} for {f.Item}");
Say?.Invoke(want == Stance.NonCombat && f.ModeBefore != Stance.NonCombat
? $"{f.Item.FullName} is in your hands; no ammunition in hand, so you are back at peace."
: $"{f.Item.FullName} is in your hands, {Stance.Name(want)} stance.");
Finish(now);
return true;
}
return false; // the engine turned the request away this tick (a teleport, a pending action): ask again
}
private static bool AmmoInHand(IDefWorld w)
{
foreach (CarriedItem it in w.Items())
if (it.Wielded && ItemKinds.Classify(it) == ItemKind.Ammo) return true;
return false;
}
private void Finish(long now)
{
_flight = null;
_lastDoneMs = now;
}
}

View file

@ -0,0 +1,195 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
using RynthCore.Plugin.RynthDefective.Use;
namespace RynthCore.Plugin.RynthDefective.Views;
/// <summary>
/// The item bar window: a grid of slot buttons (the item's picture, its count or uses left, its key
/// under it), a row with Edit, Settings and Weapons, and the status line. Edit opens the slot editor
/// below (set a slot from the item selected in the game, pick one from the pack, how it is used,
/// its key); Settings the sizes and switches. Recorded on the pump thread, replayed by the engine.
/// </summary>
internal sealed class BarView
{
/// <summary>Logical units a button needs besides its picture: the frame padding and the gap to the next.</summary>
public const float CellExtra = 16f;
private readonly DefSession _s;
private readonly SlotEditor _editor;
private readonly SettingsPanel _settings;
public bool EditOpen, SettingsOpen;
/// <summary>The window should be sized to its content (a setting changed, a section opened).</summary>
public Action RequestFit = () => { };
/// <summary>Show the weapon picker window.</summary>
public Action ShowPicker = () => { };
public BarView(DefSession session)
{
_s = session;
_editor = new SlotEditor(session);
_settings = new SettingsPanel(session, () => RequestFit());
}
public SlotEditor Editor => _editor;
/// <summary>The window size that fits the grid (and the sections that are open), in logical units.</summary>
public (float W, float H) WantedSize()
{
DefSettings st = _s.Settings;
int perRow = Math.Min(st.SlotsPerRow, st.SlotCount);
int rows = (st.SlotCount + st.SlotsPerRow - 1) / st.SlotsPerRow;
float cell = st.ButtonSize + CellExtra;
float w = Math.Max(250f, perRow * cell + 28f);
float h = rows * (st.ButtonSize + (st.ShowCounts ? 50f : 14f)) + 70f;
if (EditOpen) { h += 330f; w = Math.Max(w, 330f); }
if (SettingsOpen) h += 230f;
return (w, h);
}
public void Draw(UiWindow w)
{
if (!_s.LoggedIn)
{
w.TextDisabled("Log in to use the item bar.");
return;
}
IReadOnlyList<CarriedItem> items = _s.Items();
DrawGrid(w, items);
DrawToolbar(w);
DrawStatus(w);
if (EditOpen)
{
w.Separator();
_editor.Draw(w, items);
}
if (SettingsOpen)
{
w.Separator();
_settings.Draw(w);
}
}
// ── The grid ────────────────────────────────────────────────────────────
private void DrawGrid(UiWindow w, IReadOnlyList<CarriedItem> items)
{
DefSettings st = _s.Settings;
float size = st.ButtonSize;
float pitch = size + CellExtra;
var labels = new List<(string Text, uint Color)>();
var keys = new List<string>();
for (int rowStart = 0; rowStart < st.SlotCount; rowStart += st.SlotsPerRow)
{
int end = Math.Min(st.SlotCount, rowStart + st.SlotsPerRow);
labels.Clear();
keys.Clear();
for (int i = rowStart; i < end; i++)
{
if (i > rowStart) w.SameLine();
DrawSlotButton(w, i + 1, items, size, out string text, out uint color, out string key);
labels.Add((text, color));
keys.Add(key);
}
if (!st.ShowCounts) continue;
for (int j = 0; j < labels.Count; j++)
{
if (j > 0) w.SameLine(j * pitch);
w.TextColored(labels[j].Color, labels[j].Text.Length > 0 ? labels[j].Text : " ");
}
for (int j = 0; j < keys.Count; j++)
{
if (j > 0) w.SameLine(j * pitch);
w.TextColored(SlotText.KeyColor, keys[j].Length > 0 ? keys[j] : " ");
}
}
}
private void DrawSlotButton(UiWindow w, int number, IReadOnlyList<CarriedItem> items, float size,
out string text, out uint color, out string key)
{
DefSlot slot = _s.Data.Slots[number - 1];
string id = "slot" + number;
string? keyFull = _s.KeyOfSlot(number);
key = SlotText.ShortKey(keyFull);
text = string.Empty;
color = SlotText.Plain;
bool icons = _s.Settings.ShowIcons && _s.IconsAvailable;
if (slot.Item == null)
{
w.Button("+", id, () => Choose(number), size + 8f, size + 8f);
w.Tooltip(SlotText.Tooltip(number, null, default, slot.Mode, keyFull));
return;
}
SlotStatus s = ItemMatcher.Status(slot.Item, items);
text = SlotText.Count(s, out color);
string tip = SlotText.Tooltip(number, slot.Item, s, slot.Mode, keyFull);
bool busy = _s.Use.Involves(slot.Item);
bool inHand = s.Item is { Wielded: true };
uint? fill = busy ? SlotText.Waiting : inHand ? UiFormat.Rgb(40, 110, 40) : null;
if (icons && s.Item != null)
{
w.ImageButton(UiFormat.IconKindObject, s.Item.Id, id, () => Press(number), size, size, 0xFFFFFFFFu, fill ?? 0u);
}
else if (icons && slot.Item.Icon != 0)
{
// Not carried: the last picture seen, dimmed.
w.ImageButton(UiFormat.IconKindIcon, slot.Item.Icon, id, () => Press(number), size, size, UiFormat.Rgb(255, 255, 255, 90));
}
else
{
if (fill != null) w.PushStyleColor(UiFormat.ColButton, fill.Value);
else if (s.Item == null) w.PushStyleColor(UiFormat.ColText, SlotText.Missing);
w.Button(SlotText.Abbreviation(slot.Item.FullName), id, () => Press(number), size + 8f, size + 8f);
if (fill != null) w.PopStyleColor();
else if (s.Item == null) w.PopStyleColor();
}
w.Tooltip(tip);
}
private void Press(int number)
{
string? problem = _s.UseSlot(number);
if (problem != null) _s.SetStatus(problem, warning: true);
}
/// <summary>An empty slot's button: open the editor on it.</summary>
private void Choose(int number)
{
if (!EditOpen) { EditOpen = true; RequestFit(); }
_editor.Select(number);
}
// ── Toolbar and status ──────────────────────────────────────────────────
private void DrawToolbar(UiWindow w)
{
w.ToggleButton("Edit slots", "tb.edit", EditOpen, () => { EditOpen = !EditOpen; RequestFit(); }, small: true);
w.SameLine();
w.ToggleButton("Settings", "tb.settings", SettingsOpen, () => { SettingsOpen = !SettingsOpen; RequestFit(); }, small: true);
w.SameLine();
w.SmallButton("Weapons", "tb.weapons", () => ShowPicker());
w.Tooltip("The weapon picker: every weapon and wand you carry, one click to wield (/rdef weapons)");
}
private void DrawStatus(UiWindow w)
{
UseRequest? pending = _s.Use.Pending;
if (pending != null)
{
w.TextColored(SlotText.Waiting, $"Waiting to use {pending.Label}...");
return;
}
string status = _s.Status(out bool warning);
if (status.Length > 0) w.TextColored(warning ? SlotText.Missing : SlotText.Plain, status);
else w.TextDisabled("Click a slot, or press its key.");
}
}

View file

@ -0,0 +1,118 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
using RynthCore.Plugin.RynthDefective.Use;
namespace RynthCore.Plugin.RynthDefective.Views;
/// <summary>
/// The weapon picker window, for picking among dozens of weapons while playing by hand: a search
/// box, a row of kind buttons (All, Melee, Missile, War, Void - the kind the player prefers is kept),
/// then the carried weapons and wands as big rows with their picture. Favourites and the recently
/// wielded come first; below them every kind, A-Z. One click on a row wields it; the weapon in hand
/// is highlighted. The "+" / "-" in front of a row adds or takes out a favourite.
/// </summary>
internal sealed class PickerView
{
private static readonly uint InHandColor = UiFormat.Rgb(110, 210, 110);
private static readonly uint ElementColor = UiFormat.Rgb(150, 185, 235);
private readonly DefSession _s;
public string Search = string.Empty;
public PickerView(DefSession session) => _s = session;
public void Draw(UiWindow w)
{
if (!_s.LoggedIn)
{
w.TextDisabled("Log in to pick a weapon.");
return;
}
DefSettings st = _s.Settings;
IReadOnlyList<CarriedItem> items = _s.Items();
PickerModel m = WeaponPicker.Build(items, _s.Data.Favourites, _s.Data.Recent, Search, st.PreferredKind);
w.InputText("Search", "pk.search", Search, 48, v => Search = v);
w.Tooltip("Words in the name, the element or the kind: \"fire wand\", \"axe\", \"void\".");
foreach (KindFilter f in Enum.GetValues<KindFilter>())
{
KindFilter kind = f;
w.ToggleButton(WeaponPicker.KindLabel(f), "pk.kind" + (int)f, st.PreferredKind == f, () =>
{
st.PreferredKind = kind;
_s.Save();
}, small: true);
w.SameLine();
}
w.SmallButton("Clear", "pk.clear", () => Search = string.Empty);
w.Tooltip("Clears the search. The kind button you leave pressed is remembered.");
DrawHand(w, items);
if (st.PreferredKind != KindFilter.All || Search.Length > 0)
w.TextDisabled($"{m.Shown} of {m.Total} shown");
w.BeginChild("pk.list", 0f, 0f, true);
float icon = st.PickerIconSize;
bool icons = st.ShowIcons && _s.IconsAvailable;
if (m.Favourites.Count > 0)
{
w.SeparatorText("Favourites");
foreach (PickerRow r in m.Favourites) DrawRow(w, r, "f", icon, icons, showElement: true);
}
if (m.Recent.Count > 0)
{
w.SeparatorText("Recent");
foreach (PickerRow r in m.Recent) DrawRow(w, r, "r", icon, icons, showElement: true);
}
foreach (PickerGroup g in m.Groups)
{
w.SeparatorText($"{ItemKinds.Label(g.Group)} ({g.Rows.Count})");
foreach (PickerRow r in g.Rows) DrawRow(w, r, "g", icon, icons, showElement: g.Group is WeaponGroup.WarMagic or WeaponGroup.VoidMagic);
}
if (m.Groups.Count == 0)
w.TextDisabled(m.Total == 0 ? "No weapons or wands in your pack." : "Nothing matches. Clear the search or pick All.");
w.EndChild();
}
/// <summary>What is in the hands now, and the item's name for the title line.</summary>
private void DrawHand(UiWindow w, IReadOnlyList<CarriedItem> items)
{
string hand = string.Empty;
foreach (CarriedItem it in items)
{
if (!it.Wielded) continue;
ItemKind k = ItemKinds.Classify(it);
if (!ItemKinds.IsWeapon(k) && k != ItemKind.Shield) continue;
hand += (hand.Length > 0 ? ", " : string.Empty) + it.FullName;
}
UseRequest? pending = _s.Use.Pending;
if (pending != null) w.TextColored(SlotText.Waiting, $"Waiting to wield {pending.Label}...");
else w.TextColored(hand.Length > 0 ? InHandColor : SlotText.Plain, "In hand: " + (hand.Length > 0 ? hand : "nothing"));
}
private void DrawRow(UiWindow w, PickerRow r, string section, float icon, bool icons, bool showElement)
{
CarriedItem it = r.Item;
string idKey = section + it.Id;
ItemRef reference = ItemRef.From(it);
w.SmallButton(r.Favourite ? "-" : "+", "fav" + idKey, () => _s.SetStatus(_s.ToggleFavourite(reference)));
w.Tooltip(r.Favourite ? "Take out of the favourites" : "Add to the favourites (listed first)");
w.SameLine();
if (icons)
{
w.Image(UiFormat.IconKindObject, it.Id, icon, icon);
w.SameLine();
}
string label = it.FullName;
if (showElement && r.Element.Length > 0) label += $" ({r.Element})";
if (r.InHand) label += " [in hand]";
if (r.InHand) w.PushStyleColor(UiFormat.ColText, InHandColor);
w.Selectable(label, "pk" + idKey, r.InHand, () => _s.Wield(reference), 0f, icons ? icon : 0f);
if (r.InHand) w.PopStyleColor();
}
}

View file

@ -0,0 +1,49 @@
using System;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
namespace RynthCore.Plugin.RynthDefective.Views;
/// <summary>The settings under the bar: how many slots and how big, what is shown, and the credit.</summary>
internal sealed class SettingsPanel
{
/// <summary>The credit line, in the plugin's about text and the README.</summary>
public const string Credit =
"RynthDefective is an independent implementation of the ideas of Defective, the Decal item-bar plugin written by "
+ "Hazridi and modified by Aun (github.com/aunrela/Defective). It contains no code from it.";
private readonly DefSession _s;
private readonly Action _fit;
public SettingsPanel(DefSession session, Action fit)
{
_s = session;
_fit = fit;
}
public void Draw(UiWindow w)
{
DefSettings st = _s.Settings;
void Changed(bool fit)
{
st.Clamp();
_s.Save();
if (fit) _fit();
}
w.SeparatorText("Settings");
w.SliderInt("Slots", "set.slots", st.SlotCount, DefSettings.SlotsMin, DefSettings.SlotsMax, v => { st.SlotCount = v; Changed(true); });
w.SliderInt("Slots per row", "set.perrow", st.SlotsPerRow, DefSettings.PerRowMin, DefSettings.PerRowMax, v => { st.SlotsPerRow = v; Changed(true); });
w.SliderInt("Button size", "set.button", st.ButtonSize, DefSettings.ButtonMin, DefSettings.ButtonMax, v => { st.ButtonSize = v; Changed(true); });
w.SliderInt("Picker row icon", "set.picker", st.PickerIconSize, DefSettings.PickerIconMin, DefSettings.PickerIconMax, v => { st.PickerIconSize = v; Changed(false); });
w.Checkbox("Show item icons", "set.icons", st.ShowIcons, v => { st.ShowIcons = v; Changed(false); });
w.Tooltip(_s.IconsAvailable ? "Off: the slots are text buttons." : "This engine can't draw item pictures (it needs script window op level 2): the slots are text buttons.");
w.Checkbox("Show counts and keys under the slots", "set.counts", st.ShowCounts, v => { st.ShowCounts = v; Changed(true); });
w.Checkbox("Allow weapon swaps while RynthAi's macro runs", "set.swap", st.SwapWhileBotRuns, v => { st.SwapWhileBotRuns = v; Changed(false); });
w.Tooltip("Off (the default): a weapon, wand or shield is not wielded while the RynthAi macro runs - it picks the weapon itself and would swap back. Kits, potions and other items always work.");
w.SeparatorText("About");
w.TextWrapped(Credit);
w.TextDisabled("Commands: /rdef (show or hide), /rdef use <slot or name>, /rdef weapons, /rdef help.");
}
}

View file

@ -0,0 +1,172 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
namespace RynthCore.Plugin.RynthDefective.Views;
/// <summary>
/// The slot editor under the bar: every slot as a row (picture, name, key), and for the one picked
/// its buttons - Set from selected (the item selected in the game goes in the slot), Pick from pack
/// (a searchable list of what is carried), Clear, move up and down - how pressing it uses the item,
/// and its key (typed here, bound through the engine's hotkeys as "/rdef use N" or by the item's name).
/// </summary>
internal sealed class SlotEditor
{
private const float RowIcon = 22f;
private const int PackRows = 40;
private readonly DefSession _s;
private int _selected = 1;
private bool _picking;
private string _packSearch = string.Empty;
private string _keyDraft = string.Empty;
private string _note = string.Empty;
public SlotEditor(DefSession session) => _s = session;
public int SelectedSlot => _selected;
public bool Picking => _picking;
public string Note => _note;
public void Select(int number)
{
_selected = Math.Clamp(number, 1, DefSettings.SlotsMax);
_picking = false;
_keyDraft = string.Empty;
_note = string.Empty;
}
private void Say(string text)
{
_note = text;
_s.SetStatus(text);
}
public void Draw(UiWindow w, IReadOnlyList<CarriedItem> items)
{
DefSettings st = _s.Settings;
if (_selected > st.SlotCount) _selected = st.SlotCount;
bool icons = st.ShowIcons && _s.IconsAvailable;
w.TextDisabled("Pick a slot, then set it from the item selected in the game or from your pack.");
w.BeginChild("slotlist", 0f, Math.Min(st.SlotCount, 6) * (RowIcon + 6f) + 8f, true);
for (int n = 1; n <= st.SlotCount; n++)
{
DefSlot slot = _s.Data.Slots[n - 1];
int number = n;
string? key = _s.KeyOfSlot(n);
string name = slot.Item == null ? "(empty)" : slot.Item.FullName;
if (icons)
{
CarriedItem? have = slot.Item == null ? null : ItemMatcher.Find(slot.Item, items, out _);
if (have != null) w.Image(UiFormat.IconKindObject, have.Id, RowIcon, RowIcon);
else if (slot.Item != null && slot.Item.Icon != 0) w.Image(UiFormat.IconKindIcon, slot.Item.Icon, RowIcon, RowIcon, UiFormat.Rgb(255, 255, 255, 90));
else w.Dummy(RowIcon, RowIcon);
w.SameLine();
}
string label = $"{n}. {name}" + (key != null ? $" [{key}]" : string.Empty);
w.Selectable(label, "row" + n, _selected == n, () => Select(number), 0f, icons ? RowIcon : 0f);
}
w.EndChild();
DrawSlot(w, items);
}
private void DrawSlot(UiWindow w, IReadOnlyList<CarriedItem> items)
{
int n = _selected;
DefSlot slot = _s.Data.Slots[n - 1];
w.TextColored(UiColors.Gold, $"Slot {n}: " + (slot.Item == null ? "(empty)" : slot.Item.FullName));
w.Button("Set from selected", "ed.set", () => Say(_s.SetFromSelected(n)));
w.Tooltip("Select an item in the game (click it in your pack), then press this: it goes in this slot.");
w.SameLine();
w.ToggleButton("Pick from pack", "ed.pick", _picking, () => { _picking = !_picking; _packSearch = string.Empty; });
w.Tooltip("Choose from a list of what you carry.");
w.SameLine();
w.Button("Clear", "ed.clear", () => Say(_s.ClearSlot(n)));
w.SmallButton("Move up", "ed.up", () => { if (_s.SwapSlots(n, n - 1)) _selected = n - 1; });
w.SameLine();
w.SmallButton("Move down", "ed.down", () => { if (_s.SwapSlots(n, n + 1)) _selected = n + 1; });
uint sel = _s.SelectedId();
CarriedItem? selItem = sel == 0 ? null : _s.FindById(sel);
w.TextDisabled("Selected in the game: " + (sel == 0 ? "nothing" : selItem != null ? selItem.FullName : "(not in your pack)"));
if (_note.Length > 0) w.TextWrapped(_note);
if (_picking) DrawPackPicker(w, items, n);
if (slot.Item == null) return;
int mode = (int)slot.Mode;
w.Combo("Pressing it", "ed.mode", mode, UseModes.Labels, i => _s.SetSlotMode(n, (UseMode)Math.Clamp(i, 0, (int)UseMode.Equip)));
SlotStatus status = ItemMatcher.Status(slot.Item, items);
if (status.Item != null)
{
ItemKind kind = ItemKinds.Classify(status.Item);
UseAction action = UseModes.ActionFor(slot.Mode, kind);
w.TextDisabled($"It is {Describe(kind)}: pressing the slot has it {UseModes.Describe(action)}.");
}
else
{
w.TextColored(SlotText.Missing, "Not in your pack right now. The slot keeps the name and fills itself when you carry another.");
}
DrawKey(w, n, slot);
}
private void DrawKey(UiWindow w, int n, DefSlot slot)
{
string? key = _s.KeyOfSlot(n);
w.Text("Key: " + (key ?? "none"));
w.InputText("Key to bind", "ed.key", _keyDraft, 24, v => _keyDraft = v, UiFormat.InputEnterReturnsTrue);
w.Tooltip("A key with Ctrl, Alt or Shift if you like: F9, Ctrl+1, Alt+Shift+Num3.");
w.Button("Bind to this slot", "ed.bind", () => Say(_s.BindKey(n, _keyDraft, byName: false)));
w.Tooltip($"Runs {DefCommandParser.UseCommand(n)}. If you move or re-set the slot, the key follows the slot.");
w.SameLine();
w.Button("Bind to this item", "ed.bindname", () => Say(_s.BindKey(n, _keyDraft, byName: true)));
w.Tooltip("Runs /rdef use <the item's name>, whichever slot (or none) holds it. Works for every character on this PC.");
w.SameLine();
w.Button("Unbind", "ed.unbind", () => Say(_s.UnbindKey(n)));
w.TextDisabled("Any item can be bound by name from Settings > Hotkeys too: /rdef use <name>.");
}
private void DrawPackPicker(UiWindow w, IReadOnlyList<CarriedItem> items, int n)
{
bool icons = _s.Settings.ShowIcons && _s.IconsAvailable;
w.InputText("Search your pack", "ed.packsearch", _packSearch, 48, v => _packSearch = v);
List<PackChoice> choices = PackList.Build(items, _packSearch, PackRows, out int total);
w.BeginChild("packlist", 0f, 150f, true);
foreach (PackChoice c in choices)
{
CarriedItem it = c.Item;
if (icons) { w.Image(UiFormat.IconKindObject, it.Id, RowIcon, RowIcon); w.SameLine(); }
string label = it.FullName + (c.Count > 1 ? $" x{c.Count}" : string.Empty);
w.Selectable(label, "pk" + it.Id, false, () =>
{
Say(_s.SetSlot(n, it));
_picking = false;
}, 0f, icons ? RowIcon : 0f);
}
if (choices.Count == 0) w.TextDisabled("Nothing matches.");
if (total > choices.Count) w.TextDisabled($"{total - choices.Count} more - type to narrow the list.");
w.EndChild();
}
private static string Describe(ItemKind k) => k switch
{
ItemKind.Kit => "a healing or stamina kit",
ItemKind.Melee => "a melee weapon",
ItemKind.Missile => "a missile weapon",
ItemKind.WarWand => "a war magic wand",
ItemKind.VoidWand => "a void magic wand",
ItemKind.Shield => "a shield",
ItemKind.Armor => "armor or clothing",
ItemKind.Jewelry => "jewelry",
ItemKind.Ammo => "ammunition",
_ => "an item",
};
}

View file

@ -0,0 +1,80 @@
using System;
using System.Text;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
namespace RynthCore.Plugin.RynthDefective.Views;
/// <summary>The words a slot shows: the count under its button, its key, and its tooltip. Pure.</summary>
internal static class SlotText
{
public static readonly uint Missing = UiFormat.Rgb(225, 95, 95);
public static readonly uint InHand = UiFormat.Rgb(110, 210, 110);
public static readonly uint Plain = UiFormat.Rgb(220, 220, 220);
public static readonly uint KeyColor = UiFormat.Rgb(150, 185, 235);
public static readonly uint Waiting = UiFormat.Rgb(255, 191, 64);
/// <summary>The line under a slot button: uses left (kits), the count (stacks, several of a kind), "in hand", or "none".</summary>
public static string Count(SlotStatus s, out uint color)
{
color = Plain;
if (s.Item == null)
{
color = Missing;
return "none";
}
CarriedItem it = s.Item;
if (it.Wielded)
{
color = InHand;
return ItemKinds.IsWeapon(ItemKinds.Classify(it)) ? "in hand" : "worn";
}
if (it.MaxUses > 0) return s.Uses.ToString();
if (it.MaxStack > 1 || s.Count > 1) return "x" + s.Count;
return string.Empty;
}
/// <summary>A key as the cell under a slot has room for: "Ctrl+F9" is "C+F9".</summary>
public static string ShortKey(string? key)
{
if (string.IsNullOrEmpty(key)) return string.Empty;
string k = key.EndsWith(" (off)", StringComparison.Ordinal) ? key[..^6] : key;
return k.Replace("Ctrl+", "C+").Replace("Alt+", "A+").Replace("Shift+", "S+");
}
/// <summary>Up to <paramref name="max"/> letters for a slot drawn as text (icons off): "Peerless Healing Kit" is "PHK".</summary>
public static string Abbreviation(string name, int max = 4)
{
var sb = new StringBuilder();
foreach (string word in (name ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
if (word.Length == 0 || !char.IsLetterOrDigit(word[0])) continue;
sb.Append(char.ToUpperInvariant(word[0]));
if (sb.Length >= max) break;
}
return sb.Length == 0 ? "?" : sb.ToString();
}
public static string Tooltip(int number, ItemRef? item, SlotStatus s, UseMode mode, string? key)
{
if (item == null) return $"Slot {number}: empty. Click to set it up.";
var sb = new StringBuilder();
sb.Append("Slot ").Append(number).Append(": ").Append(s.Item?.FullName ?? item.FullName);
if (s.Item == null)
{
sb.Append("\nNot in your pack - nothing to use. It comes back by itself when you carry one of the same name.");
}
else
{
ItemKind kind = ItemKinds.Classify(s.Item);
UseAction action = UseModes.ActionFor(mode, kind);
sb.Append("\nClick or press the key: ").Append(UseModes.Describe(action).Replace("used", "use it").Replace("wielded", "wield it"));
if (s.Item.MaxUses > 0) sb.Append("\n").Append(s.Uses).Append(" uses left");
if (s.Count > 1 || s.Item.MaxStack > 1) sb.Append(s.Item.MaxUses > 0 ? ", " : "\n").Append(s.Count).Append(" carried");
if (s.Item.Wielded) sb.Append("\nIn your hands now.");
}
sb.Append(key != null ? "\nKey: " + key : "\nNo key yet (Edit slots).");
return sb.ToString();
}
}

View file

@ -99,6 +99,7 @@ internal static class RynthIcons
public const string Ruler = "\uE6B8";
public const string Scales = "\uE750";
public const string Scissors = "\uEAE0";
public const string Scroll = "\uEB7A";
public const string Shield = "\uE40A";
public const string ShieldSlash = "\uE410";
public const string ShieldWarning = "\uE412";

View file

@ -100,6 +100,12 @@ internal static unsafe class RynthUi
RynthUiColor.Red => 0xFFE05A5A,
RynthUiColor.TitleBar => 0xFF1A1A28,
RynthUiColor.WindowBorder => 0xFF008080,
// v90: the default theme's muted text and instrument shades (ThemePalette.DeriveInstrument).
RynthUiColor.Muted => 0xFFB8C8D8,
RynthUiColor.KeyFace => 0xFF111E2B,
RynthUiColor.Hairline => 0xFF1D3042,
RynthUiColor.Inset => 0xFF06080B,
RynthUiColor.Faint => 0xFF8794A1,
_ => 0xFFFFFFFF,
});