Snapshot for release 2026.10.30.1 (internal 50ae062)

This commit is contained in:
Tom Bohar 2026-10-31 06:01:30 -04:00
commit 76aca938b6
52 changed files with 6242 additions and 60 deletions

View file

@ -233,7 +233,7 @@ public partial class BuffManager
// Cast on the shield in this run: done, unless a higher level is castable now.
if (_shieldRunLevels.TryGetValue(spell.Family, out int ran)) return UpgradeParked(spell.Family) || level <= ran;
if (!_isAutoBatchRebuff) return false;
rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, _settings.RebuffSecondsRemaining);
rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, BatchRebuffLineSec);
}
int rebufferSec = Math.Max(0, rebufferSecOverride ?? _settings.RebuffSecondsRemaining);
if (!_shieldSpellTimers.TryGetValue(ShieldKey(shieldId, spell.Family), out ItemSpellRecord? rec)) return false;

View file

@ -352,6 +352,57 @@ public partial class BuffManager : IDisposable
private bool InCombatNow() => InCombatOverride?.Invoke()
?? _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true;
// ── Rebuff When Idle (RebuffWhenIdle + RebuffIdleMarginMinutes; VTank's "idlebufftopoff") ──
// The checkbox was saved and shown since the first version but nothing read it (a player asked,
// 2026-10-30, whether "buff only when idle" was implemented). What it means (the owner): an earlier
// timer for idle moments. The regular rebuff is unchanged: a buff at or under Rebuff With
// (RebuffSecondsRemaining), or dispelled, is recast as always, in a fight or not. With the option
// on and the bot idle (IdleForTopOff: no fight target, no monster within Monster Range, no corpse
// to loot, no salvage), a rebuff run also starts once a buff is at or under Rebuff With plus the
// margin (default 2 minutes). Such an early run never starts in a fight, and one under way stops
// at the next safe point (no cast in flight) when the bot stops being idle; the regular rules take
// over. Margin 0: nothing added. Force Buff, heals and vitals are not touched.
/// <summary>The bot is idle enough for an early top-off (set by RynthAiPlugin.IdleForBuffTopOff;
/// tests set it). Null = never: no early top-off.</summary>
internal Func<bool>? IdleForTopOff { get; set; }
/// <summary>Rebuff When Idle's margin in seconds (0 when off or set to 0).</summary>
internal int IdleMarginSec => _settings.RebuffWhenIdle ? Math.Max(0, _settings.RebuffIdleMarginMinutes) * 60 : 0;
/// <summary>An early top-off may run now: the option is on with a margin, and the bot is idle.</summary>
internal bool IdleTopOffNow()
{
if (IdleMarginSec <= 0 || IdleForTopOff == null) return false;
try { return IdleForTopOff(); } catch { return false; }
}
/// <summary>The line a buff is rebuffed at now: Rebuff With, plus the idle margin while an idle
/// top-off may run.</summary>
internal int RebuffLineSec() => _settings.RebuffSecondsRemaining + (IdleTopOffNow() ? IdleMarginSec : 0);
/// <summary>The rebuff run under way was started by the idle margin alone (nothing was at or under
/// Rebuff With): it stops when the bot stops being idle.</summary>
private bool _isIdleTopOffRun;
/// <summary>The line an automatic run tops off under (with RebuffTopOffSecondsRemaining): Rebuff With,
/// plus the margin for an early top-off run, so the buff that started it is always in it.</summary>
private int BatchRebuffLineSec => _settings.RebuffSecondsRemaining + (_isIdleTopOffRun ? IdleMarginSec : 0);
/// <summary>Early top-off runs started (tests, status).</summary>
internal int IdleTopOffRuns { get; private set; }
/// <summary>An early top-off run stops (a fight, a corpse, salvage): the regular rules take over.</summary>
private void EndIdleTopOffRun()
{
_isForceRebuffing = false;
_isAutoBatchRebuff = false;
_isIdleTopOffRun = false;
ClearRunFamilies();
_chain.PassEnd("idle top-off stopped", s => _host.Log(s));
_host.Log("[Buff] Rebuff When Idle: the bot is no longer idle (a fight, a corpse or salvage): the early top-off stops; buffs under Rebuff With are still rebuffed as usual.");
}
/// <summary>
/// A spell's mana cost: its BaseMana from the portal.dat SpellTable, the most it can cost
/// (ACE Creature.CalculateManaUsage; Mana Conversion only lowers it on a skill roll, so the
@ -1048,6 +1099,7 @@ public partial class BuffManager : IDisposable
{
_isForceRebuffing = true;
_isAutoBatchRebuff = false;
_isIdleTopOffRun = false;
ClearRunFamilies();
_buffFailCooldownUntil.Clear(); // explicit recast-all must not be blocked by stale cooldowns
_silentNoShowCounts.Clear(); // give parked families a fresh shot on FR too
@ -1076,6 +1128,7 @@ public partial class BuffManager : IDisposable
{
_isForceRebuffing = false;
_isAutoBatchRebuff = false;
_isIdleTopOffRun = false;
_isRechargingMana = false;
_isRechargingStamina = false;
_isHealingSelf = false;
@ -1348,6 +1401,12 @@ public partial class BuffManager : IDisposable
// A Magic stance we asked for: watch the client's mode every tick (see ObserveStance).
ObserveStance();
// Rebuff When Idle: an early top-off run stops once the bot isn't idle (a fight, a corpse,
// salvage), at the first heartbeat with no cast of ours in flight (a sent cast resolves first),
// and before the arbiter reads NeedsAnyBuff this tick. The regular rules take over.
if (_isIdleTopOffRun && _isForceRebuffing && _pendingSpellId == 0 && !IdleTopOffNow())
EndIdleTopOffRun();
// RefreshFromLiveMemory at OnLoginComplete fails when the server-time
// packet hasn't landed yet (GetServerTime returns 0). On those
// logins we have NO timers and would recast every buff that has
@ -1863,6 +1922,7 @@ public partial class BuffManager : IDisposable
bool wasAutoBatch = _isAutoBatchRebuff;
_isForceRebuffing = false;
_isAutoBatchRebuff = false;
_isIdleTopOffRun = false;
_host.Log($"[FR] complete — cast {_forceRebuffCastFamilies.Count} spell families{(wasAutoBatch ? " (auto batch)" : "")}");
// Order matters: the flag must already be false (IsBuffActive
// short-circuits on _forceRebuffCastFamilies while it is set, so
@ -2855,7 +2915,9 @@ public partial class BuffManager : IDisposable
public bool NeedsAnyBuff()
{
if (!_settings.EnableBuffing) return false;
return _isForceRebuffing || AnyBuffBelowThreshold(BuildDynamicBuffList(), _settings.RebuffSecondsRemaining);
// RebuffLineSec: Rebuff With, plus Rebuff When Idle's margin while the bot is idle. An early
// top-off run ends at the heartbeat (before the arbiter) once the bot isn't idle.
return _isForceRebuffing || AnyBuffBelowThreshold(BuildDynamicBuffList(), RebuffLineSec());
}
// Returns true if any castable buff in the list has < thresholdSec remaining.
@ -2904,8 +2966,18 @@ public partial class BuffManager : IDisposable
// Auto batch-rebuff: when any buff drops below the configured threshold,
// trigger a full rebuff so ALL timers re-align in one session rather than
// each buff trickling in one at a time as it individually expires.
if (!_isForceRebuffing && AnyBuffBelowThreshold(BuildDynamicBuffList(), _settings.RebuffSecondsRemaining))
int rebuffLine = _isForceRebuffing ? 0 : RebuffLineSec();
if (!_isForceRebuffing && AnyBuffBelowThreshold(BuildDynamicBuffList(), rebuffLine))
{
// Rebuff When Idle: a run the margin alone started (nothing at or under Rebuff With) is an
// early top-off, which stops if the bot stops being idle.
_isIdleTopOffRun = rebuffLine > _settings.RebuffSecondsRemaining
&& !AnyBuffBelowThreshold(BuildDynamicBuffList(), _settings.RebuffSecondsRemaining);
if (_isIdleTopOffRun)
{
IdleTopOffRuns++;
_host.Log($"[Buff] Rebuff When Idle: idle, and a buff has under {rebuffLine} s left (Rebuff With {_settings.RebuffSecondsRemaining} s + {_settings.RebuffIdleMarginMinutes} min): topping off early.");
}
// Batch trigger — reuse FR family-tracking but do NOT clear timers.
// ForceFullRebuff clears _ramBuffTimers, which causes an immediate
// re-trigger: any spell that can't be resolved (spellId=0) never
@ -3301,7 +3373,7 @@ public partial class BuffManager : IDisposable
return UpgradeParked(targetSpell.Family)
|| !(CastLevelThisRun(targetSpell.Family) is int ran && ran > 0 && GetSpellLevel(targetSpell) > ran);
if (!_isAutoBatchRebuff) return false;
rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, _settings.RebuffSecondsRemaining);
rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, BatchRebuffLineSec);
}
int targetLevel = GetSpellLevel(targetSpell);

View file

@ -107,6 +107,9 @@ internal sealed class HudController
/// <summary>The Mini Remote's session stats (the same SessionStats code as RynthTracker); null if it failed to start.</summary>
public RynthCore.Plugin.Shared.SessionStatsTracker? SessionStats { get; init; }
/// <summary>Opens or closes the Monster Stats window (the Session Stats view's "Monster stats" button); null without one.</summary>
public Action? ToggleMonsterStats { get; init; }
/// <summary>Latest pack view (render thread safe).</summary>
public HudPackSnapshot Pack => _pack;

View file

@ -524,6 +524,13 @@ internal sealed class MiniRemoteHud
ImGui.EndTable();
}
RenderStatButtons(_hud.Remote());
// Combat per kind of monster since login: the fallback Monster Stats window, only on an engine whose
// Damage panel doesn't show the numbers (RynthAiPlugin.MonsterStats.cs; null otherwise).
if (_hud.ToggleMonsterStats is Action toggle)
{
if (ImGui.Button("Monster stats", new Vector2(Math.Max(ImGui.GetContentRegionAvail().X, 140f), 0))) toggle();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Evades, resists, hits and kills per kind of monster since login (/ra mstats).");
}
}
/// <summary>One Session Stats row: label, session total, per hour (and an optional tooltip on the label).</summary>

View file

@ -77,19 +77,28 @@ internal static class SectionsManifest
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"/>.
/// The Monster Stats window (RynthAiPlugin.MonsterStats.cs, 2026-10-30): combat per kind of monster
/// since login, drawn by RynthAi in the engine's frame (plugin API v89), declared only where the
/// Damage panel doesn't show the numbers under each monster. No bar button: the Session Stats view's
/// "Monster stats" button and /ra mstats show open it.
/// </summary>
public static string Build(IReadOnlyList<View> views, IReadOnlyList<Section> sections, bool dashboard = false)
public const string MonsterStatsTitle = RynthAiPlugin.MonsterStatsTitle, MonsterStatsSurface = RynthAiPlugin.MonsterStatsSurface;
/// <summary>
/// The manifest JSON for <paramref name="views"/> (UTF-8 text, schema version 1), with the dashboard
/// window when <paramref name="dashboard"/> and the Monster Stats window when <paramref name="monsterStats"/>.
/// </summary>
public static string Build(IReadOnlyList<View> views, IReadOnlyList<Section> sections, bool dashboard = false, bool monsterStats = false)
{
using var stream = new MemoryStream(4096);
using (var w = new Utf8JsonWriter(stream))
{
w.WriteStartObject();
w.WriteNumber("version", 1);
if (dashboard || monsterStats)
w.WriteStartArray("windows");
if (dashboard)
{
w.WriteStartArray("windows");
w.WriteStartObject();
w.WriteString("id", "dashboard");
w.WriteString("title", DashboardTitle);
@ -105,8 +114,24 @@ internal static class SectionsManifest
w.WriteString("chrome", "none");
w.WriteBoolean("fitHeight", true);
w.WriteEndObject();
w.WriteEndArray();
}
if (monsterStats)
{
w.WriteStartObject();
w.WriteString("id", "monsterstats");
w.WriteString("title", MonsterStatsTitle);
w.WriteString("surface", MonsterStatsSurface);
w.WriteString("icon", RynthCore.Plugin.Shared.RynthUi.RynthIcons.ChartBar);
w.WriteNumber("width", 560);
w.WriteNumber("height", 360);
w.WriteNumber("minWidth", 380);
w.WriteNumber("minHeight", 160);
w.WriteBoolean("bar", false);
w.WriteBoolean("edgeToEdge", true);
w.WriteEndObject();
}
if (dashboard || monsterStats)
w.WriteEndArray();
w.WriteStartArray("sections");
foreach (Section s in sections)
{

View file

@ -926,6 +926,26 @@ internal sealed class LegacyAdvancedSettingsUi
case "Buffing":
ImGui.Checkbox("Enable Buffing", ref _settings.EnableBuffing);
ImGui.Checkbox("Rebuff When Idle", ref _settings.RebuffWhenIdle);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Top buffs off early between fights. When the bot is idle (no target, no\n" +
"monster within Monster Range, no corpse to loot), it rebuffs as soon as a\n" +
"buff has 'Rebuff With' + 'Idle Margin' left, instead of waiting for\n" +
"'Rebuff With'. So fewer buffs run out in the next fight.\n" +
"It never stops a rebuff: a buff under 'Rebuff With' (or dispelled) is\n" +
"recast as always, in a fight too. An early top-off never starts in a\n" +
"fight, and one under way stops when a fight starts.");
if (_settings.RebuffWhenIdle)
{
ImGui.SetNextItemWidth(180);
ImGui.SliderInt("Idle Margin (minutes)", ref _settings.RebuffIdleMarginMinutes, 0, 60);
if (_settings.RebuffIdleMarginMinutes < 0) _settings.RebuffIdleMarginMinutes = 0;
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"How much earlier than 'Rebuff With' an idle top-off may start.\n" +
"Default 2: with 'Rebuff With' 300 s, an idle bot rebuffs at 7 minutes\n" +
"left instead of 5. 0 = Rebuff When Idle adds nothing.");
}
ImGui.Spacing();
ImGui.SetNextItemWidth(180);

View file

@ -1303,6 +1303,7 @@ internal sealed partial class LegacyDashboardRenderer
RebuffWhenIdle = s.RebuffWhenIdle,
RebuffSecondsRemaining = s.RebuffSecondsRemaining,
RebuffTopOffSecondsRemaining = s.RebuffTopOffSecondsRemaining,
RebuffIdleMarginMinutes = s.RebuffIdleMarginMinutes,
CastBuffsOverItemBuffs = s.CastBuffsOverItemBuffs,
SkipUnusableBuffs = s.SkipUnusableBuffs,
DisabledBuffs = new List<string>(s.DisabledBuffs),
@ -1565,6 +1566,7 @@ internal sealed partial class LegacyDashboardRenderer
s.RebuffWhenIdle = p.RebuffWhenIdle;
s.RebuffSecondsRemaining = p.RebuffSecondsRemaining;
if (p.RebuffTopOffSecondsRemaining > 0) s.RebuffTopOffSecondsRemaining = p.RebuffTopOffSecondsRemaining;
if (p.RebuffIdleMarginMinutes is int idleMargin) s.RebuffIdleMarginMinutes = Math.Max(0, idleMargin); // absent = unchanged
if (p.CastBuffsOverItemBuffs is bool castOverItems) s.CastBuffsOverItemBuffs = castOverItems; // absent = unchanged
if (p.SkipUnusableBuffs is bool skipUnusable) s.SkipUnusableBuffs = skipUnusable; // absent = unchanged
if (p.DisabledBuffs is { } disabledBuffs) s.DisabledBuffs = new List<string>(disabledBuffs); // absent = unchanged
@ -2051,6 +2053,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.RebuffWhenIdle = tmp.RebuffWhenIdle;
dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining;
dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining;
dst.RebuffIdleMarginMinutes = tmp.RebuffIdleMarginMinutes;
dst.CastBuffsOverItemBuffs = tmp.CastBuffsOverItemBuffs;
dst.FastBuffChain = tmp.FastBuffChain;
dst.SkipUnusableBuffs = tmp.SkipUnusableBuffs;

View file

@ -319,8 +319,20 @@ public sealed class LegacyUiSettings
/// </summary>
[JsonPropertyName("FastWeaponSwapOn")]
public bool FastWeaponSwap = true;
/// <summary>
/// Rebuff When Idle (VTank's "idlebufftopoff"): between fights, top buffs off early. When the bot
/// is idle (no fight target, no monster within Monster Range, no corpse to loot, no salvage), a
/// rebuff starts once a buff has RebuffSecondsRemaining + RebuffIdleMarginMinutes left instead of
/// waiting for RebuffSecondsRemaining. The regular rebuff is unchanged, in a fight or not.
/// Read by BuffManager.RebuffLineSec (nothing read it before 2026-10-30). Off by default.
/// </summary>
public bool RebuffWhenIdle;
/// <summary>
/// Rebuff When Idle's margin, minutes: how much earlier than RebuffSecondsRemaining an idle
/// top-off may start. Default 2; 0 = the option adds nothing. A profile saved without it loads 2.
/// </summary>
public int RebuffIdleMarginMinutes = 2;
/// <summary>
/// Re-cast a self buff when its remaining duration drops below this many seconds.
/// Default 300 (5 minutes). Lower values rebuff more eagerly; very low values
/// (under ~60s) risk recasting between an old buff dropping and the new one
@ -1290,6 +1302,8 @@ public sealed class SettingsBridgePayload
public bool RebuffWhenIdle { get; set; }
public int RebuffSecondsRemaining { get; set; }
public int RebuffTopOffSecondsRemaining { get; set; } = 1200; // absent in older files
// Nullable: the engine's Settings face doesn't know it; absent = unchanged (0 is a real value).
public int? RebuffIdleMarginMinutes { get; set; }
// Nullable: an engine that predates the setting doesn't send it, and a save from its
// Settings face must leave the setting alone rather than force it either way.
public bool? CastBuffsOverItemBuffs { get; set; }

View file

@ -3698,6 +3698,7 @@ internal sealed partial class ExpressionEngine
["RebuffSecondsRemaining"] = (() => I(s.RebuffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffSecondsRemaining = i; }),
["BlacklistTimeoutSec"] = (() => I(s.BlacklistTimeoutSec), v => { if (double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) && d >= 0) s.BlacklistTimeoutSec = (int)Math.Round(d); }),
["RebuffTopOffSecondsRemaining"] = (() => I(s.RebuffTopOffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffTopOffSecondsRemaining = i; }),
["RebuffIdleMarginMinutes"] = (() => I(s.RebuffIdleMarginMinutes), v => { if (int.TryParse(v, out int i)) s.RebuffIdleMarginMinutes = Math.Max(0, i); }),
["CastBuffsOverItemBuffs"] = (() => B(s.CastBuffsOverItemBuffs), v => s.CastBuffsOverItemBuffs = ToDouble(v) != 0),
["FastBuffChain"] = (() => B(s.FastBuffChain), v => s.FastBuffChain = ToDouble(v) != 0),
["SkipUnusableBuffs"] = (() => B(s.SkipUnusableBuffs), v => s.SkipUnusableBuffs = ToDouble(v) != 0),

View file

@ -0,0 +1,83 @@
// ============================================================================
// RynthAi - MonsterStats/CombatEvents.cs
// Melee and missile attacks between you and a monster, from the server's own
// combat game events (plugin API v78 server messages, opcode 0xF7B0), which
// name the monster. The client turns the same events into chat lines ("X
// evaded your attack.", "You evaded X!", "You slash X for 12 points of ..."),
// which are not read: the typed event is exact and can't be imitated.
//
// 0x01B1 AttackerNotification you hit it (name, type, share, damage, crit, conditions)
// 0x01B2 DefenderNotification it hit you (name, type, share, damage, location, crit, conditions)
// 0x01B3 EvasionAttackerNotification it evaded your attack (name)
// 0x01B4 EvasionDefenderNotification you evaded its attack (name)
//
// The killing blow sends no 0x01B1: the kill notice comes instead (ACE
// Player_Combat.cs; MonsterCombatStats.OnKill counts it). Spells send none of
// these (CombatLines.cs reads theirs). Pure; uses the SDK's bounds-checked reader.
// ============================================================================
using System;
using RynthCore.PluginSdk.Net;
namespace RynthCore.Plugin.RynthAi.MonsterStats;
/// <summary>One melee or missile attack, from whose side.</summary>
internal enum PhysicalEvent
{
/// <summary>Your attack hit it.</summary>
YouHit,
/// <summary>It evaded your attack.</summary>
ItEvaded,
/// <summary>Its attack hit you.</summary>
ItHit,
/// <summary>You evaded its attack.</summary>
YouEvaded,
}
internal static class CombatEvents
{
public const uint AttackerNotification = 0x01B1;
public const uint DefenderNotification = 0x01B2;
public const uint EvasionAttackerNotification = 0x01B3;
public const uint EvasionDefenderNotification = 0x01B4;
/// <summary>The game events to ask the engine for (RynthAiPlugin.Initialize).</summary>
public static readonly uint[] GameEvents =
{ AttackerNotification, DefenderNotification, EvasionAttackerNotification, EvasionDefenderNotification };
public static bool IsCombatEvent(uint eventType) =>
eventType is AttackerNotification or DefenderNotification or EvasionAttackerNotification or EvasionDefenderNotification;
/// <summary>
/// Reads one combat game event's body (the bytes after its event type). True with what
/// happened, the monster's name and the damage of a hit (0 for an evade); false for another
/// event or a body too short to hold its fields.
/// </summary>
public static bool TryParse(uint eventType, ReadOnlySpan<byte> body, out PhysicalEvent kind, out string name, out int damage)
{
kind = default;
name = string.Empty;
damage = 0;
var r = new NetReader(body);
switch (eventType)
{
case AttackerNotification:
case DefenderNotification:
if (!r.String16L(out name) || !r.U32(out _) || !r.F64(out _) || !r.U32(out uint dmg)) return false;
damage = dmg > int.MaxValue ? int.MaxValue : (int)dmg;
kind = eventType == AttackerNotification ? PhysicalEvent.YouHit : PhysicalEvent.ItHit;
break;
case EvasionAttackerNotification:
if (!r.String16L(out name)) return false;
kind = PhysicalEvent.ItEvaded;
break;
case EvasionDefenderNotification:
if (!r.String16L(out name)) return false;
kind = PhysicalEvent.YouEvaded;
break;
default:
return false;
}
name = name.Trim();
return name.Length > 0;
}
}

View file

@ -0,0 +1,172 @@
// ============================================================================
// RynthAi - MonsterStats/CombatLines.cs
// The spell lines of the combat log that say what became of a spell between
// you and a monster: it landed, it was resisted, or it could do nothing. The
// server reports spells only as text (Magic chat, type 7); swings, hits and
// evades come as typed game events (CombatEvents.cs), so no melee or missile
// line is read here.
//
// One table, the server's exact strings (ACE's, which follow retail; the ACE
// source line is next to each row). MonsterStatsTests checks every row and the
// near-misses below. Lines whose form is also used for items ("Frost Hand
// Wraps cast ... on you") are marked MayBeItem: the plugin counts them only
// for a creature (RynthAiPlugin.MonsterStats.cs).
//
// Not counted, on purpose:
// "You cast X on yourself..." your own buffs
// "<item> cast X on you" an item's spell (MayBeItem rows)
// "X tried and failed to cast a spell at you!" a fizzle: it never reached you
// "You <verb> X for N points of periodic nether damage!" a damage-over-time tick, not a cast
// "You receive N points of periodic ..." the same, on you
// "With S you restore N points of V to X." / "X casts S and restores ..." heals
// "You lose N points of V due to casting S on X" an infusion you cast (it gives)
// "You gain N points of V due to X casting S on you" a gift to you
// "Your cloak reduced the damage ..." / "The cloak of X reduced ..." a cloak (player gear)
// "X evaded your attack." / "You evaded X!" / "You slash X for N points of slashing damage!"
// the client's own lines for the typed events
// Absorbs and partial resists: ACE reduces magic damage by absorb gear without a
// word (the damage line just shows less), and a resist is all or nothing; there
// is no line to count.
//
// Pure (no host), so the host tests drive it directly.
// ============================================================================
using System;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthAi.MonsterStats;
/// <summary>What became of one spell.</summary>
internal enum SpellOutcome
{
/// <summary>It reached its target and took hold (damage, a drain, an enchantment).</summary>
Landed,
/// <summary>The target's magic defense stopped it.</summary>
Resisted,
/// <summary>It passed the resist check but could do nothing (the target is immune to it).</summary>
NoEffect,
}
/// <summary>
/// One spell line: whose spell (<see cref="ByYou"/>: yours at <see cref="Name"/>, else
/// <see cref="Name"/>'s at you), what became of it, the health damage it did (0 when the line
/// gives none), and whether the name may be an item's (<see cref="MayBeItem"/>).
/// </summary>
internal readonly record struct CombatLine(string Rule, bool ByYou, SpellOutcome Outcome, string Name, int Damage, bool MayBeItem);
internal static class CombatLines
{
/// <summary>One form of line: its id, whose spell and its outcome, a word it must contain, and the pattern.</summary>
internal sealed record Row(string Id, bool ByYou, SpellOutcome Outcome, bool MayBeItem, string Hint, string Source, Regex Pattern);
private const RegexOptions Opt = RegexOptions.CultureInvariant;
// "Critical hit! ", "Overpower! ", "Sneak Attack! " in front of a damage line (SpellProjectile.cs critMsg etc.).
private const string Prefix = "(?:(?:Critical hit|Overpower|Sneak Attack)! )*";
private const string Num = @"(?<n>\d[\d,]*)";
private const string Vital = "(?<vital>health|stamina|mana)";
// What follows an enchantment that met one already there (WorldObject_Magic.cs suffix).
private const string EnchantTail = ", (?:refreshing|surpassing|but it is surpassed by) .+";
/// <summary>Every line counted, in the order tried.</summary>
internal static readonly Row[] Rows =
{
// ── Your spells at a monster ──
new("you-damage", true, SpellOutcome.Landed, false, " points with ",
"SpellProjectile.cs: {crit}{overpower}{sneak}You {verb} {target} for {amount} points with {spell}.{critProt}",
new Regex("^" + Prefix + "You (?<verb>[a-z]+) (?<name>.+?) for " + Num + " points? with (?<spell>.+?)\\."
+ "(?: Your critical hit was avoided with their augmentation!)?$", Opt)),
new("you-drain", true, SpellOutcome.Landed, false, " you drain ",
"SpellProjectile.cs / WorldObject_Magic.cs: With {spell} you drain {amount} points of {vital} from {target}.",
new Regex("^With (?<spell>.+?) you drain " + Num + " points? of " + Vital + " from (?<name>.+?)\\.$", Opt)),
new("you-transfer", true, SpellOutcome.Landed, false, " due to casting ",
"WorldObject_Magic.cs: You gain {n} points of {vital} due to casting {spell} on {target}",
new Regex("^You gain " + Num + " points? of " + Vital + " due to casting (?<spell>.+?) on (?<name>.+)$", Opt)),
new("you-enchant", true, SpellOutcome.Landed, true, "You cast ",
"WorldObject_Magic.cs: You cast {spell} on {target}{suffix} (and the dispel forms)",
new Regex("^You cast (?<spell>.+?) on (?<name>.+?)(?:" + EnchantTail + "| and dispel: .+|, but the dispel fails\\.)?$", Opt)),
new("you-resisted", true, SpellOutcome.Resisted, false, " resists your spell",
"WorldObject_Magic.cs: {target} resists your spell",
new Regex("^(?<name>.+) resists your spell$", Opt)),
new("you-noeffect", true, SpellOutcome.NoEffect, false, "You fail to affect ",
"Player_Magic.cs / WorldObject_Magic.cs: You fail to affect {target} with {spell}",
new Regex("^You fail to affect (?<name>.+?) with (?<spell>.+)$", Opt)),
// ── A monster's spells at you ──
new("it-damage", false, SpellOutcome.Landed, false, " you for ",
"SpellProjectile.cs: {crit}{overpower}{sneak}{caster} {verbs} you for {amount} points with {spell}.{critProt}",
new Regex("^" + Prefix + "(?<name>.+?) (?<verb>[a-z]+) you for " + Num + " points? with (?<spell>.+?)\\."
+ "(?: Your augmentation allows you to avoid a critical hit!)?$", Opt)),
new("it-drain", false, SpellOutcome.Landed, false, " and drains ",
"SpellProjectile.cs / WorldObject_Magic.cs: {caster} casts {spell} and drains {amount} points of your {vital}.",
new Regex("^(?<name>.+?) casts (?<spell>.+?) and drains " + Num + " points? of your " + Vital + "\\.$", Opt)),
new("it-transfer", false, SpellOutcome.Landed, false, " casting ",
"WorldObject_Magic.cs: You lose {n} points of {vital} due to {caster} casting {spell} on you",
new Regex("^You lose " + Num + " points? of " + Vital + " due to (?<name>.+?) casting (?<spell>.+?) on you$", Opt)),
new("it-resisted", false, SpellOutcome.Resisted, false, "You resist the spell cast by ",
"WorldObject_Magic.cs: You resist the spell cast by {caster}",
new Regex("^You resist the spell cast by (?<name>.+)$", Opt)),
new("it-enchant", false, SpellOutcome.Landed, true, " cast ",
"WorldObject_Magic.cs: {caster} cast {spell} on you{suffix} / on your {item}{suffix}",
new Regex("^(?<name>.+?) cast (?<spell>.+?) on (?:you|your (?<item>.+?))(?:" + EnchantTail + ")?$", Opt)),
new("it-dispel", false, SpellOutcome.Landed, true, " casts ",
"WorldObject_Magic.cs: {caster} casts {spell} on you and dispels: {list}. / , but the dispel fails.",
new Regex("^(?<name>.+?) casts (?<spell>.+?) on you(?: and dispels: .+|, but the dispel fails\\.)$", Opt)),
new("it-noeffect", false, SpellOutcome.NoEffect, false, " fails to affect you with ",
"WorldObject_Magic.cs: {caster} fails to affect you with {spell}",
new Regex("^(?<name>.+?) fails to affect you with (?<spell>.+)$", Opt)),
};
/// <summary>
/// Reads one chat line. True for a spell line of the table, with whose spell it was, its
/// outcome, the monster's name and the health damage; false for anything else (and for a
/// line about yourself). The caller has already left out lines in a player's chat types.
/// </summary>
public static bool TryParse(string? text, out CombatLine line)
{
line = default;
if (string.IsNullOrEmpty(text)) return false;
string t = text.Trim();
if (t.Length < 8) return false;
foreach (Row row in Rows)
{
if (t.IndexOf(row.Hint, StringComparison.Ordinal) < 0) continue;
Match m = row.Pattern.Match(t);
if (!m.Success) continue;
string name = m.Groups["name"].Value.Trim();
if (!IsMonsterName(name)) return false;
int damage = 0;
Group n = m.Groups["n"];
Group vital = m.Groups["vital"];
// Damage is health taken: a damage line's amount, a health drain's; not stamina or mana,
// and not what a transfer gave you (the line says what you gained, not what it lost).
bool health = !vital.Success || vital.Value == "health";
if (n.Success && health && row.Id is not "you-transfer") damage = ParseAmount(n.Value);
line = new CombatLine(row.Id, row.ByYou, row.Outcome, name, damage, row.MayBeItem);
return true;
}
return false;
}
/// <summary>Not you: "yourself" (and "yourself and lose ..."), "you", "your ...", or nothing.</summary>
private static bool IsMonsterName(string name)
{
if (name.Length == 0) return false;
if (name.Equals("You", StringComparison.OrdinalIgnoreCase)) return false;
if (name.StartsWith("yourself", StringComparison.OrdinalIgnoreCase)) return false;
if (name.StartsWith("your ", StringComparison.OrdinalIgnoreCase)) return false;
return true;
}
/// <summary>"1,234" as 1234; 0 for anything that isn't a number up to a million.</summary>
internal static int ParseAmount(string s)
{
long v = 0;
foreach (char c in s)
{
if (c == ',') continue;
if (c < '0' || c > '9') return 0;
v = v * 10 + (c - '0');
if (v > 1_000_000) return 0;
}
return (int)v;
}
}

View file

@ -0,0 +1,288 @@
// ============================================================================
// RynthAi - MonsterStats/MonsterCombatStats.cs
// The combat since login (or the last reset) between you and each kind of
// monster (by name: every Drudge Skulker together), in both directions:
//
// You at it swings = hits + its evades (melee and missile), with the
// killing blow counted as a hit; your spells that reached it
// = landed + resisted + no effect; kills; damage dealt.
// It at you attacks = hits + your evades; its spells that reached you
// = landed + resisted + no effect; damage taken.
// Rates it evades (its evades / your swings), it resists (its
// resists / your spells), you evade, you resist.
//
// Fed by CombatEvents (typed melee/missile events), CombatLines (spell lines)
// and the kill notice; shown under each monster in the Damage panel (the row's
// "mstats"), else by MonsterStatsWindow; printed by /ra mstats,
// kept across a hot reload by MonsterStatsStore. Pure: every call takes the
// time, so the tests drive it. One thread (the plugin pump); the window reads
// the immutable rows of Snapshot().
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
namespace RynthCore.Plugin.RynthAi.MonsterStats;
/// <summary>How the killing blow was struck (the player's combat mode at the kill notice).</summary>
internal enum KillBlow
{
/// <summary>Not known (peace mode): the kill is counted, the blow isn't.</summary>
None,
/// <summary>Melee or missile: a hit.</summary>
Physical,
/// <summary>Magic: a landed spell.</summary>
Spell,
}
/// <summary>One monster's numbers, as of one moment (immutable).</summary>
internal sealed record MonsterStatsRow(
string Name,
int Hits, int Evaded, int SpellsLanded, int Resisted, int NoEffect, int Kills, long DamageDealt,
int HitsTaken, int YouEvaded, int SpellsTaken, int YouResisted, int NoEffectOnYou, long DamageTaken,
long FirstUtcTicks, long LastUtcTicks)
{
/// <summary>Your melee and missile attacks at it: hits and the ones it evaded.</summary>
public int Swings => Hits + Evaded;
/// <summary>Your spells that reached it.</summary>
public int SpellsAtIt => SpellsLanded + Resisted + NoEffect;
/// <summary>Its melee and missile attacks at you.</summary>
public int Attacks => HitsTaken + YouEvaded;
/// <summary>Its spells that reached you.</summary>
public int SpellsAtYou => SpellsTaken + YouResisted + NoEffectOnYou;
public double? ItEvadesRate => MonsterCombatStats.Rate(Evaded, Swings);
public double? ItResistsRate => MonsterCombatStats.Rate(Resisted, SpellsAtIt);
public double? YouEvadeRate => MonsterCombatStats.Rate(YouEvaded, Attacks);
public double? YouResistRate => MonsterCombatStats.Rate(YouResisted, SpellsAtYou);
/// <summary>Nothing counted (a fresh row).</summary>
public bool IsEmpty => Swings == 0 && SpellsAtIt == 0 && Kills == 0 && Attacks == 0 && SpellsAtYou == 0;
}
internal sealed class MonsterCombatStats
{
/// <summary>Kinds of monster kept at once; past it the one seen longest ago goes.</summary>
public const int MaxMonsters = 400;
private sealed class Entry
{
public string Name = "";
public int Hits, Evaded, SpellsLanded, Resisted, NoEffect, Kills;
public long DamageDealt;
public int HitsTaken, YouEvaded, SpellsTaken, YouResisted, NoEffectOnYou;
public long DamageTaken;
public long FirstUtcTicks, LastUtcTicks;
public MonsterStatsRow ToRow() => new(Name, Hits, Evaded, SpellsLanded, Resisted, NoEffect, Kills, DamageDealt,
HitsTaken, YouEvaded, SpellsTaken, YouResisted, NoEffectOnYou, DamageTaken, FirstUtcTicks, LastUtcTicks);
}
private readonly Dictionary<string, Entry> _byName = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Goes up on every change (the window and the save follow it).</summary>
public int Version { get; private set; }
/// <summary>Kinds of monster with numbers.</summary>
public int Count => _byName.Count;
/// <summary>A share as 0..1, or null when there is nothing to divide by.</summary>
public static double? Rate(int part, int whole) => whole > 0 ? (double)part / whole : null;
/// <summary>"23%" (whole from 10% up), "4.5%" (one decimal below), or "-" with nothing to divide by.</summary>
public static string Percent(double? rate)
{
if (rate is not double r || !double.IsFinite(r)) return "-";
double p = Math.Clamp(r, 0, 1) * 100;
p = p >= 10 ? Math.Round(p, MidpointRounding.AwayFromZero) : Math.Round(p, 1, MidpointRounding.AwayFromZero);
return p.ToString("0.#", CultureInfo.InvariantCulture) + "%";
}
/// <summary>True when <paramref name="name"/> has numbers this session.</summary>
public bool IsTracked(string? name) => !string.IsNullOrEmpty(name) && _byName.ContainsKey(name);
// ── Events ───────────────────────────────────────────────────────────
/// <summary>A melee or missile attack, either way (CombatEvents).</summary>
public void OnPhysical(PhysicalEvent kind, string name, int damage, DateTime nowUtc)
{
Entry? e = Touch(name, nowUtc);
if (e == null) return;
int dmg = Math.Max(0, damage);
switch (kind)
{
case PhysicalEvent.YouHit: e.Hits++; e.DamageDealt += dmg; break;
case PhysicalEvent.ItEvaded: e.Evaded++; break;
case PhysicalEvent.ItHit: e.HitsTaken++; e.DamageTaken += dmg; break;
case PhysicalEvent.YouEvaded: e.YouEvaded++; break;
}
Version++;
}
/// <summary>A spell line (CombatLines), either way.</summary>
public void OnSpell(CombatLine line, DateTime nowUtc)
{
Entry? e = Touch(line.Name, nowUtc);
if (e == null) return;
int dmg = Math.Max(0, line.Damage);
if (line.ByYou)
{
switch (line.Outcome)
{
case SpellOutcome.Landed: e.SpellsLanded++; e.DamageDealt += dmg; break;
case SpellOutcome.Resisted: e.Resisted++; break;
case SpellOutcome.NoEffect: e.NoEffect++; break;
}
}
else
{
switch (line.Outcome)
{
case SpellOutcome.Landed: e.SpellsTaken++; e.DamageTaken += dmg; break;
case SpellOutcome.Resisted: e.YouResisted++; break;
case SpellOutcome.NoEffect: e.NoEffectOnYou++; break;
}
}
Version++;
}
/// <summary>
/// The server's kill notice ("You killed Drudge Skulker!", "Drudge Skulker died!", ...): one kill
/// for the monster it names, and the killing blow, which sent no hit or damage line, as a hit
/// (<see cref="KillBlow.Physical"/>) or a landed spell (<see cref="KillBlow.Spell"/>). The monster
/// is the longest name with numbers that the notice contains, else <paramref name="nameInNotice"/>'s
/// answer (the plugin looks among the creatures around: a monster killed by its first blow has
/// no numbers yet). Returns the name credited, or null when the notice names none.
/// </summary>
public string? OnKill(string? notice, KillBlow blow, DateTime nowUtc, Func<string, string?>? nameInNotice = null)
{
if (string.IsNullOrWhiteSpace(notice)) return null;
string? name = LongestNameIn(notice);
if (name == null && nameInNotice != null)
{
string? n = nameInNotice(notice);
if (!string.IsNullOrWhiteSpace(n) && notice.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0) name = n.Trim();
}
if (name == null) return null;
Entry? e = Touch(name, nowUtc);
if (e == null) return null;
e.Kills++;
if (blow == KillBlow.Physical) e.Hits++;
else if (blow == KillBlow.Spell) e.SpellsLanded++;
Version++;
return e.Name;
}
private string? LongestNameIn(string notice)
{
string? best = null;
foreach (string n in _byName.Keys)
if ((best == null || n.Length > best.Length) && notice.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0)
best = n;
return best;
}
/// <summary>Starts every monster over.</summary>
public void Reset()
{
_byName.Clear();
Version++;
}
// ── Reading ──────────────────────────────────────────────────────────
/// <summary>Every monster's numbers now, most recently fought first.</summary>
public MonsterStatsRow[] Snapshot()
{
var rows = new MonsterStatsRow[_byName.Count];
int i = 0;
foreach (Entry e in _byName.Values) rows[i++] = e.ToRow();
Array.Sort(rows, (a, b) =>
{
int c = b.LastUtcTicks.CompareTo(a.LastUtcTicks);
return c != 0 ? c : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
});
return rows;
}
/// <summary>One monster's numbers by its exact name (any case), or null.</summary>
public MonsterStatsRow? Get(string? name)
=> !string.IsNullOrEmpty(name) && _byName.TryGetValue(name, out Entry? e) ? e.ToRow() : null;
/// <summary>
/// The monster <paramref name="query"/> means: its exact name (any case), else the one name that
/// contains it. Null with the candidates (up to <paramref name="maxCandidates"/>, recent first)
/// when several do, and with none when nothing does.
/// </summary>
public MonsterStatsRow? Find(string? query, out List<string> candidates, int maxCandidates = 8)
{
candidates = new List<string>();
if (string.IsNullOrWhiteSpace(query)) return null;
string q = query.Trim();
if (_byName.TryGetValue(q, out Entry? exact)) return exact.ToRow();
MonsterStatsRow? only = null;
int matches = 0;
foreach (MonsterStatsRow r in Snapshot())
{
if (r.Name.IndexOf(q, StringComparison.OrdinalIgnoreCase) < 0) continue;
matches++;
only = r;
if (candidates.Count < maxCandidates) candidates.Add(r.Name);
}
if (matches == 1) { candidates.Clear(); return only; }
return null;
}
// ── Saving (MonsterStatsStore) ───────────────────────────────────────
/// <summary>Puts saved rows back in place of what there is (a hot reload's carried session).</summary>
public void Load(IEnumerable<MonsterStatsRow> rows)
{
_byName.Clear();
foreach (MonsterStatsRow r in rows)
{
if (string.IsNullOrWhiteSpace(r.Name) || _byName.ContainsKey(r.Name)) continue;
_byName[r.Name] = new Entry
{
Name = r.Name,
Hits = Math.Max(0, r.Hits), Evaded = Math.Max(0, r.Evaded),
SpellsLanded = Math.Max(0, r.SpellsLanded), Resisted = Math.Max(0, r.Resisted), NoEffect = Math.Max(0, r.NoEffect),
Kills = Math.Max(0, r.Kills), DamageDealt = Math.Max(0, r.DamageDealt),
HitsTaken = Math.Max(0, r.HitsTaken), YouEvaded = Math.Max(0, r.YouEvaded),
SpellsTaken = Math.Max(0, r.SpellsTaken), YouResisted = Math.Max(0, r.YouResisted), NoEffectOnYou = Math.Max(0, r.NoEffectOnYou),
DamageTaken = Math.Max(0, r.DamageTaken),
FirstUtcTicks = r.FirstUtcTicks, LastUtcTicks = r.LastUtcTicks,
};
if (_byName.Count >= MaxMonsters) break;
}
Version++;
}
// ── Internals ────────────────────────────────────────────────────────
/// <summary>The monster's entry (made on first sight), its last-seen time now; null for no name.</summary>
private Entry? Touch(string? name, DateTime nowUtc)
{
if (string.IsNullOrWhiteSpace(name)) return null;
string n = name.Trim();
if (n.Length > 64) n = n.Substring(0, 64);
long now = nowUtc.Ticks;
if (!_byName.TryGetValue(n, out Entry? e))
{
if (_byName.Count >= MaxMonsters) DropOldest();
e = new Entry { Name = n, FirstUtcTicks = now };
_byName[n] = e;
}
e.LastUtcTicks = now;
return e;
}
private void DropOldest()
{
string? oldest = null;
long at = long.MaxValue;
foreach (Entry e in _byName.Values)
if (e.LastUtcTicks < at) { at = e.LastUtcTicks; oldest = e.Name; }
if (oldest != null) _byName.Remove(oldest);
}
}

View file

@ -0,0 +1,250 @@
// ============================================================================
// RynthAi - MonsterStats/MonsterStatsStore.cs
// Keeps the monster stats (since login, or their last reset) across a plugin
// reload (engine hot reload, RynthSuite update), by TrackerSessionStore's rules:
// a small file saved every ~30 s, at a reset and on Shutdown, picked up by the
// next copy only for the same client process (id and start time), the same
// character and a recent save. A real logout deletes the file, so the next
// login starts fresh. The Mini Remote session's Reset XP doesn't touch it.
//
// %LOCALAPPDATA%\RynthCore\monster-stats\monsters-<pid>-<character>.txt, plain
// "key=value" lines with one "m=" line per monster (tab-separated), and an end
// marker so a torn write never loads. No System.Text.Json (plugin types and
// STJ leak across reloads). Pure apart from the file calls.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace RynthCore.Plugin.RynthAi.MonsterStats;
/// <summary>What a save holds. Times are UTC ticks.</summary>
internal sealed class MonsterStatsSave
{
public int ProcessId;
public long ProcessStartUtcTicks;
public uint CharacterId;
public long SavedUtcTicks;
/// <summary>When these numbers started (the login, or their last reset).</summary>
public long SinceUtcTicks;
public List<MonsterStatsRow> Rows = new();
}
internal static class MonsterStatsStore
{
public const string Header = "RynthAi monster stats v2";
/// <summary>A save older than this is from a client gone (the session store's rule).</summary>
public static readonly TimeSpan MaxAge = TimeSpan.FromMinutes(10);
/// <summary>Files untouched for this long are left over from closed clients.</summary>
public static readonly TimeSpan PurgeAge = TimeSpan.FromDays(1);
private const string FilePrefix = "monsters-";
private const string FileSuffix = ".txt";
private const int Fields = 16; // the name and 15 numbers
private static readonly CultureInfo Ic = CultureInfo.InvariantCulture;
/// <summary>One file per client process and character.</summary>
public static string FileName(int processId, uint characterId)
=> FilePrefix + processId.ToString(Ic) + "-" + characterId.ToString("X8", Ic) + FileSuffix;
/// <summary>%LOCALAPPDATA%\RynthCore\monster-stats.</summary>
public static string DefaultDirectory() => RynthCore.Plugin.Shared.TrackerSessionStore.DirectoryFor("monster-stats");
// ── Format ───────────────────────────────────────────────────────────
public static string Serialize(MonsterStatsSave s)
{
var sb = new StringBuilder(256 + s.Rows.Count * 96);
sb.Append(Header).Append('\n');
Line(sb, "pid", s.ProcessId.ToString(Ic));
Line(sb, "pstart", s.ProcessStartUtcTicks.ToString(Ic));
Line(sb, "char", s.CharacterId.ToString(Ic));
Line(sb, "saved", s.SavedUtcTicks.ToString(Ic));
Line(sb, "since", s.SinceUtcTicks.ToString(Ic));
foreach (MonsterStatsRow r in s.Rows)
{
sb.Append("m=").Append(Clean(r.Name));
foreach (long v in new long[]
{
r.Hits, r.Evaded, r.SpellsLanded, r.Resisted, r.NoEffect, r.Kills, r.DamageDealt,
r.HitsTaken, r.YouEvaded, r.SpellsTaken, r.YouResisted, r.NoEffectOnYou, r.DamageTaken,
r.FirstUtcTicks, r.LastUtcTicks,
})
sb.Append('\t').Append(v.ToString(Ic));
sb.Append('\n');
}
Line(sb, "end", "1"); // a torn write never parses
return sb.ToString();
}
/// <summary>Strict: wrong header, a missing or malformed field, or no end marker = nothing (start fresh).
/// Unknown keys are ignored so a later version can add some.</summary>
public static bool TryParse(string? text, out MonsterStatsSave save)
{
save = new MonsterStatsSave();
if (string.IsNullOrEmpty(text)) return false;
string[] lines = text.Replace("\r", "").Split('\n');
if (lines.Length == 0 || lines[0] != Header) return false;
var map = new Dictionary<string, string>(StringComparer.Ordinal);
var rows = new List<MonsterStatsRow>();
bool end = false;
for (int i = 1; i < lines.Length; i++)
{
string line = lines[i];
if (line.Length == 0) continue;
int eq = line.IndexOf('=');
if (eq <= 0) return false;
string key = line.Substring(0, eq), value = line.Substring(eq + 1);
if (key == "m")
{
if (!TryParseRow(value, out MonsterStatsRow? row)) return false;
rows.Add(row!);
continue;
}
if (key == "end") { end = value == "1"; continue; }
map[key] = value;
}
if (!end) return false;
var s = save;
bool ok = Int(map, "pid", out s.ProcessId)
&& Long(map, "pstart", out s.ProcessStartUtcTicks)
&& UInt(map, "char", out s.CharacterId)
&& Long(map, "saved", out s.SavedUtcTicks)
&& Long(map, "since", out s.SinceUtcTicks);
if (!ok || !ValidTicks(s.SavedUtcTicks) || !ValidTicks(s.SinceUtcTicks)) return false;
s.Rows = rows;
return true;
}
private static bool TryParseRow(string value, out MonsterStatsRow? row)
{
row = null;
string[] f = value.Split('\t');
if (f.Length < Fields || f[0].Trim().Length == 0) return false;
var n = new long[Fields - 1];
for (int i = 1; i < Fields; i++)
if (!long.TryParse(f[i], NumberStyles.None, Ic, out n[i - 1])) return false;
for (int i = 0; i < 13; i++)
if (i != 6 && i != 12 && n[i] > int.MaxValue) return false; // counts are ints; damage is long
if (!ValidTicks(n[13]) || !ValidTicks(n[14])) return false;
row = new MonsterStatsRow(f[0].Trim(),
(int)n[0], (int)n[1], (int)n[2], (int)n[3], (int)n[4], (int)n[5], n[6],
(int)n[7], (int)n[8], (int)n[9], (int)n[10], (int)n[11], n[12],
n[13], n[14]);
return true;
}
/// <summary>
/// Carry the saved stats on only for the same client process (id and start time) and character,
/// and a recent save (a real logout deleted it, so a save that is there is a reload's). A save
/// "from the future" (clock moved back) is treated like a stale one; a minute of slack covers
/// small clock adjustments.
/// </summary>
public static bool ShouldRestore(MonsterStatsSave s, int processId, long processStartUtcTicks, uint characterId, DateTime nowUtc)
{
if (characterId == 0) return false;
if (s.ProcessId != processId || s.ProcessStartUtcTicks != processStartUtcTicks) return false;
if (s.CharacterId != characterId) return false;
if (s.SinceUtcTicks > s.SavedUtcTicks) return false;
TimeSpan age = nowUtc - new DateTime(s.SavedUtcTicks, DateTimeKind.Utc);
return age <= MaxAge && age >= TimeSpan.FromMinutes(-1);
}
// ── Files ────────────────────────────────────────────────────────────
/// <summary>Writes to a temp file and swaps it in, so a crash mid-write leaves the last good save.</summary>
public static void Save(string directory, MonsterStatsSave s)
{
Directory.CreateDirectory(directory);
string path = Path.Combine(directory, FileName(s.ProcessId, s.CharacterId));
string tmp = path + ".tmp";
File.WriteAllText(tmp, Serialize(s));
File.Move(tmp, path, overwrite: true);
}
public static bool TryLoad(string directory, int processId, uint characterId, out MonsterStatsSave save)
{
save = new MonsterStatsSave();
string path = Path.Combine(directory, FileName(processId, characterId));
if (!File.Exists(path)) return false;
return TryParse(File.ReadAllText(path), out save);
}
public static void Delete(string directory, int processId, uint characterId)
{
string path = Path.Combine(directory, FileName(processId, characterId));
if (File.Exists(path)) File.Delete(path);
}
/// <summary>Deletes this process's saves for any character and files left untouched past
/// <see cref="PurgeAge"/> by clients that have closed. Returns how many went.</summary>
public static int Cleanup(string directory, int processId, DateTime nowUtc)
{
if (!Directory.Exists(directory)) return 0;
string mine = FilePrefix + processId.ToString(Ic) + "-";
int removed = 0;
foreach (string path in Directory.GetFiles(directory, FilePrefix + "*"))
{
string name = Path.GetFileName(path);
bool remove = name.StartsWith(mine, StringComparison.Ordinal) || nowUtc - File.GetLastWriteTimeUtc(path) > PurgeAge;
if (!remove) continue;
try { File.Delete(path); removed++; }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
return removed;
}
// The client's start time, so a new client that gets a closed one's process id never picks up
// its save. 0 if Windows won't say (both sides then match on the id alone).
private static long? _processStartTicks;
public static long ProcessStartTicks
{
get
{
if (_processStartTicks is long t) return t;
try
{
using var p = System.Diagnostics.Process.GetCurrentProcess();
t = p.StartTime.ToUniversalTime().Ticks;
}
catch { t = 0; }
_processStartTicks = t;
return t;
}
}
// ── Helpers ──────────────────────────────────────────────────────────
private static void Line(StringBuilder sb, string key, string value) => sb.Append(key).Append('=').Append(value).Append('\n');
/// <summary>A name with no tab or line break in it (AC names have none; be safe).</summary>
private static string Clean(string name) => name.Replace('\t', ' ').Replace('\r', ' ').Replace('\n', ' ').Trim();
private static bool ValidTicks(long t) => t >= DateTime.MinValue.Ticks && t <= DateTime.MaxValue.Ticks;
private static bool Long(Dictionary<string, string> m, string k, out long v)
{
v = 0;
return m.TryGetValue(k, out string? s) && long.TryParse(s, NumberStyles.AllowLeadingSign, Ic, out v);
}
private static bool Int(Dictionary<string, string> m, string k, out int v)
{
v = 0;
return m.TryGetValue(k, out string? s) && int.TryParse(s, NumberStyles.AllowLeadingSign, Ic, out v);
}
private static bool UInt(Dictionary<string, string> m, string k, out uint v)
{
v = 0;
return m.TryGetValue(k, out string? s) && uint.TryParse(s, NumberStyles.None, Ic, out v);
}
}

View file

@ -0,0 +1,372 @@
// ============================================================================
// RynthAi - MonsterStats/MonsterStatsWindow.cs
// The Monster Stats window, the FALLBACK for an engine whose Damage panel
// doesn't show the numbers under each monster (no GetUiHookFlags bit 8, e.g.
// plugin API 90): one line per kind of monster fought since login (kills, how
// often it evades and resists you, how often you evade and resist it), and
// under each monster, when clicked open, its numbers both ways. RynthCore hosts
// the window (the sections manifest's "monsterstats" window, plugin API v89:
// header, pop-out, resize, remembered place) and calls Draw through
// RynthPluginRenderEmbed. On an engine with the Damage panel's line it isn't
// declared at all.
//
// AC's render thread: it reads the view the tick published and queues what it
// does (Reset) for the tick. Looks: Shared/RynthUi (the player's theme).
// ============================================================================
using System;
using System.Collections.Generic;
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.RynthAi.MonsterStats;
/// <summary>What the window shows (immutable; the tick publishes a new one when something changed).</summary>
internal sealed record MonsterStatsView(MonsterStatsRow[] Rows, string FocusName, bool PhysicalCounted, bool InWorld)
{
public static readonly MonsterStatsView Empty = new(Array.Empty<MonsterStatsRow>(), string.Empty, true, false);
}
internal sealed class MonsterStatsWindow
{
private readonly Action _reset;
private readonly HashSet<string> _open = new(StringComparer.OrdinalIgnoreCase);
private string _filterEdit = string.Empty; // the box
private string _filter = string.Empty; // what it filters by (trimmed)
private int _sort; // 0 recent, 1 name, 2 kills
private static readonly string[] SortNames = { "Recent", "Name", "Kills" };
// The shown rows, built again only when the view, the sort or the filter changes.
private MonsterStatsView? _builtFor;
private int _builtSort = -1;
private string _builtFilter = string.Empty;
private readonly List<MonsterStatsRow> _shown = new();
private float _k = 1f;
private float Px(float v) => v * _k;
private const string HelpText =
"Your fights since login, one line per kind of monster (every Drudge Skulker together).\n\n" +
"It evades: of your melee and missile attacks, the share it evaded.\n" +
"It resists: of your spells that reached it, the share it resisted.\n" +
"You evade: of its melee and missile attacks, the share you evaded.\n" +
"You resist: of its spells that reached you, the share you resisted.\n\n" +
"Click a monster for its numbers both ways: attacks and hits, spells and how many landed, " +
"spells that could do nothing to it (immune), damage and kills. The killing blow counts as a hit " +
"(melee or missile) or a landed spell (magic).\n\n" +
"Melee and missile come from the server's combat events; spells from its spell lines in chat. " +
"A ring spell counts once for each monster it reaches.\n\n" +
"The numbers start over with Reset here, /ra mstats reset, the Damage panel's Reset stats, and at " +
"logout; Reset XP leaves them, and a hot reload keeps them.\n\n" +
"/ra mstats <name> prints a monster's numbers in chat; /ra mstats show opens this window.";
public MonsterStatsWindow(Action reset) => _reset = reset;
/// <summary>Draws the window body into the current ImGui window and returns the size it would like. Render thread.</summary>
public Vector2 Draw(MonsterStatsView view)
{
_k = Math.Max(0.5f, Font(RynthUiFont.Ui11).FontSize / 11f);
Vector2 origin = ImGui.GetCursorScreenPos();
Vector2 size = ImGui.GetContentRegionAvail();
var want = new Vector2(Px(560), Px(360));
if (size.X < 60 || size.Y < 40) return want;
ImDrawListPtr frame = ImGui.GetWindowDrawList();
frame.AddRectFilled(origin, origin + size, Background, 4);
using (PushFont(RynthUiFont.Ui11))
{
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4));
ImGui.SetCursorScreenPos(origin + new Vector2(6, 6));
ImGui.Indent(6);
float w = size.X - 12;
DrawTop(view, w);
DrawFilter(w);
Build(view);
DrawHeader(w);
// The host's resize grip sits over the bottom-right corner: the rows end above it.
float bodyH = Math.Max(Px(30), origin.Y + size.Y - 6 - ImGui.GetCursorScreenPos().Y - Px(10));
ImGui.PushStyleColor(ImGuiCol.ChildBg, Field);
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
ImGui.BeginChild("##ms_rows", new Vector2(w, bodyH));
DrawRows(view);
ImGui.EndChild();
ImGui.PopStyleVar();
ImGui.PopStyleColor();
ImGui.Unindent(6);
ImGui.PopStyleVar();
DrawResetPopup();
}
frame.AddRect(origin, origin + size, Border, 4);
return want;
}
// ── Top line: status, sort, reset, help ─────────────────────────────
private void DrawTop(MonsterStatsView view, float w)
{
Vector2 start = ImGui.GetCursorScreenPos();
float h = Px(20), iconW = Px(22);
string sortLabel = "Sort: " + SortNames[_sort];
float sortW = ButtonWidth(sortLabel), resetW = ButtonWidth("Reset");
float textW = Math.Max(10, w - sortW - resetW - iconW - Px(12));
ImDrawListPtr dl = ImGui.GetWindowDrawList();
string status = !view.InWorld ? "Monster stats start once you are in the world."
: view.Rows.Length == 0 ? "No fights yet since login."
: view.Rows.Length == 1 ? "1 kind of monster since login." : $"{view.Rows.Length} kinds of monster since login.";
dl.PushClipRect(start, start + new Vector2(textW, h), true);
dl.AddText(new Vector2(start.X, start.Y + (h - ImGui.GetFontSize()) * 0.5f), Mute, status);
dl.PopClipRect();
float x = start.X + w - iconW - resetW - sortW - Px(8);
if (Button("##ms_sort", sortLabel, new Vector2(x, start.Y), new Vector2(sortW, h), Text, ButtonFill))
_sort = (_sort + 1) % SortNames.Length;
ImGui.SetItemTooltip("Most recently fought first, by name, or by kills.");
x += sortW + Px(4);
if (Button("##ms_reset", "Reset", new Vector2(x, start.Y), new Vector2(resetW, h), Text, ButtonFill, enabled: view.Rows.Length > 0))
ImGui.OpenPopup("##ms_reset_confirm");
ImGui.SetItemTooltip("Start every monster's numbers over (the session's XP and kills and the learned damage stay).");
x += resetW + Px(4);
IconButton("##ms_help", RynthIcons.Info, new Vector2(x, start.Y), new Vector2(iconW, h), Mute, ButtonFill, font: RynthUiFont.Ui11);
if (ImGui.IsItemHovered())
{
ImGui.BeginTooltip();
ImGui.PushTextWrapPos(ImGui.GetFontSize() * 32);
ImGui.TextUnformatted(HelpText);
ImGui.PopTextWrapPos();
ImGui.EndTooltip();
}
ImGui.SetCursorScreenPos(new Vector2(start.X, start.Y + h + Px(4)));
if (!view.PhysicalCounted)
{
ImGui.PushTextWrapPos(start.X + w);
Label("RynthCore's server messages are off, so melee and missile attacks aren't counted (spells are). /rc net on turns them on; then reload RynthAi.", Highlight);
ImGui.PopTextWrapPos();
}
ImGui.Dummy(Vector2.Zero);
}
private void DrawFilter(float w)
{
ImGui.SetNextItemWidth(w);
ImGui.PushStyleColor(ImGuiCol.FrameBg, Field);
if (ImGui.InputTextWithHint("##ms_filter", "Find a monster", ref _filterEdit, 64u))
_filter = _filterEdit.Trim();
ImGui.PopStyleColor();
}
// ── Columns ─────────────────────────────────────────────────────────
private static readonly (string Head, string Tip)[] Columns =
{
("Kills", "Your kills since login."),
("It evades", "Of your melee and missile attacks, the share it evaded (hover a number for the counts)."),
("It resists", "Of your spells that reached it, the share it resisted."),
("You evade", "Of its melee and missile attacks, the share you evaded."),
("You resist", "Of its spells that reached you, the share you resisted."),
};
private float ColW => Px(66);
private float CaretW => Px(16);
/// <summary>Left edge of number column <paramref name="i"/> (0 = Kills), from the row's left edge.</summary>
private float ColX(float rowW, int i) => rowW - (Columns.Length - i) * ColW;
private void DrawHeader(float w)
{
Vector2 p = ImGui.GetCursorScreenPos();
float h = Px(18);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
dl.AddText(new Vector2(p.X + CaretW, p.Y + (h - ImGui.GetFontSize()) * 0.5f), Mute, "Monster");
for (int i = 0; i < Columns.Length; i++)
{
var at = new Vector2(p.X + ColX(w, i), p.Y);
ImGui.SetCursorScreenPos(at);
ImGui.InvisibleButton("##ms_col" + i.ToString(CultureInfo.InvariantCulture), new Vector2(ColW, h));
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(Columns[i].Tip);
float tw = ImGui.CalcTextSize(Columns[i].Head).X;
dl.AddText(new Vector2(at.X + ColW - tw - Px(6), at.Y + (h - ImGui.GetFontSize()) * 0.5f), Mute, Columns[i].Head);
}
ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h + Px(2)));
ImGui.Dummy(Vector2.Zero);
}
// ── Rows ────────────────────────────────────────────────────────────
private void Build(MonsterStatsView view)
{
if (ReferenceEquals(view, _builtFor) && _sort == _builtSort && _filter == _builtFilter) return;
_builtFor = view;
_builtSort = _sort;
_builtFilter = _filter;
_shown.Clear();
foreach (MonsterStatsRow r in view.Rows)
if (_filter.Length == 0 || r.Name.IndexOf(_filter, StringComparison.OrdinalIgnoreCase) >= 0)
_shown.Add(r);
if (_sort == 1) _shown.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
else if (_sort == 2) _shown.Sort((a, b) => b.Kills != a.Kills ? b.Kills.CompareTo(a.Kills) : b.LastUtcTicks.CompareTo(a.LastUtcTicks));
// 0: the view's own order, most recently fought first.
}
private void DrawRows(MonsterStatsView view)
{
float w = ImGui.GetContentRegionAvail().X;
ImDrawListPtr dl = ImGui.GetWindowDrawList();
if (_shown.Count == 0)
{
ImGui.SetCursorPos(new Vector2(Px(8), Px(8)));
Label(view.Rows.Length == 0
? "Fight something: each monster you fight gets a line here."
: "No monster's name has \"" + _filter + "\" in it.", Mute);
return;
}
float rowH = Px(22);
float fontH = ImGui.GetFontSize();
for (int i = 0; i < _shown.Count; i++)
{
MonsterStatsRow r = _shown[i];
ImGui.PushID(r.Name);
Vector2 p = ImGui.GetCursorScreenPos();
bool clicked = ImGui.InvisibleButton("##row", new Vector2(Math.Max(1, w), rowH));
bool hot = ImGui.IsItemHovered();
bool open = _open.Contains(r.Name);
if (clicked)
{
if (open) _open.Remove(r.Name); else _open.Add(r.Name);
open = !open;
}
uint fill = hot ? Selected : (i & 1) == 1 ? RowAlt : 0;
if (fill != 0) dl.AddRectFilled(p, p + new Vector2(w, rowH), fill);
float ty = p.Y + (rowH - fontH) * 0.5f;
DrawCentered(dl, Font(RynthUiFont.Ui11), open ? RynthIcons.CaretDown : RynthIcons.CaretRight,
new Vector2(p.X + Px(2), p.Y), new Vector2(CaretW - Px(2), rowH), Mute);
bool focus = view.FocusName.Length > 0 && r.Name.Equals(view.FocusName, StringComparison.OrdinalIgnoreCase);
dl.PushClipRect(new Vector2(p.X + CaretW, p.Y), new Vector2(p.X + ColX(w, 0) - Px(4), p.Y + rowH), true);
dl.AddText(new Vector2(p.X + CaretW, ty), focus ? Accent : Text, r.Name);
dl.PopClipRect();
string[] cells =
{
r.Kills.ToString("N0", CultureInfo.InvariantCulture),
MonsterCombatStats.Percent(r.ItEvadesRate),
MonsterCombatStats.Percent(r.ItResistsRate),
MonsterCombatStats.Percent(r.YouEvadeRate),
MonsterCombatStats.Percent(r.YouResistRate),
};
for (int c = 0; c < cells.Length; c++)
{
float tw = ImGui.CalcTextSize(cells[c]).X;
dl.AddText(new Vector2(p.X + ColX(w, c) + ColW - tw - Px(6), ty), cells[c] == "-" ? Faded(Mute) : Text, cells[c]);
}
if (hot)
{
float mx = ImGui.GetMousePos().X - p.X;
string? tip = mx >= ColX(w, 1) ? CellTip(r, (int)((mx - ColX(w, 0)) / ColW)) : null;
SafeImGui.SetTooltip(tip ?? (open ? "Click to fold " + r.Name + " away." : "Click for " + r.Name + "'s numbers both ways."));
}
if (open) DrawDetail(r, w);
ImGui.PopID();
}
}
/// <summary>The counts behind a rate cell (column 1..4).</summary>
private static string? CellTip(MonsterStatsRow r, int col) => col switch
{
1 => $"It evaded {r.Evaded:N0} of your {r.Swings:N0} melee and missile attacks.",
2 => $"It resisted {r.Resisted:N0} of your {r.SpellsAtIt:N0} spells that reached it.",
3 => $"You evaded {r.YouEvaded:N0} of its {r.Attacks:N0} melee and missile attacks.",
4 => $"You resisted {r.YouResisted:N0} of its {r.SpellsAtYou:N0} spells that reached you.",
_ => null,
};
/// <summary>One monster's numbers both ways, under its line.</summary>
private void DrawDetail(MonsterStatsRow r, float w)
{
ImGui.Indent(CaretW);
ImGui.Dummy(new Vector2(0, Px(2)));
var flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp;
ImGui.PushStyleVar(ImGuiStyleVar.CellPadding, new Vector2(Px(6), Px(2)));
if (ImGui.BeginTable("##detail", 3, flags, new Vector2(Math.Max(Px(200), w - CaretW - Px(8)), 0)))
{
ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthStretch, 0.8f);
ImGui.TableSetupColumn("You at it", ImGuiTableColumnFlags.WidthStretch, 1.2f);
ImGui.TableSetupColumn("It at you", ImGuiTableColumnFlags.WidthStretch, 1.2f);
ImGui.TableHeadersRow();
foreach (var (label, mine, its) in MonsterStatsText.DetailRows(r))
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
Label(label, Mute);
ImGui.TableNextColumn();
ImGui.TextUnformatted(mine);
ImGui.TableNextColumn();
ImGui.TextUnformatted(its);
}
ImGui.EndTable();
}
ImGui.PopStyleVar();
ImGui.Dummy(new Vector2(0, Px(6)));
ImGui.Unindent(CaretW);
}
private void DrawResetPopup()
{
if (!ImGui.BeginPopup("##ms_reset_confirm")) return;
ImGui.TextUnformatted("Start every monster's numbers over?");
Label("The session's XP and kills stay.", Mute);
if (ImGui.Button("Reset")) { _reset(); _open.Clear(); ImGui.CloseCurrentPopup(); }
ImGui.SameLine();
if (ImGui.Button("Cancel")) ImGui.CloseCurrentPopup();
ImGui.EndPopup();
}
}
/// <summary>The words for one monster's numbers: the window's detail rows and /ra mstats's lines. Pure.</summary>
internal static class MonsterStatsText
{
private static string N(long v) => v.ToString("N0", CultureInfo.InvariantCulture);
/// <summary>The detail table: a label, your side, its side.</summary>
public static List<(string Label, string Mine, string Its)> DetailRows(MonsterStatsRow r)
{
var rows = new List<(string, string, string)>
{
("Attacks", $"{N(r.Swings)} swings, {N(r.Hits)} hit", $"{N(r.Attacks)} attacks, {N(r.HitsTaken)} hit"),
("Evaded", $"it evaded {N(r.Evaded)} ({MonsterCombatStats.Percent(r.ItEvadesRate)})",
$"you evaded {N(r.YouEvaded)} ({MonsterCombatStats.Percent(r.YouEvadeRate)})"),
("Spells", $"{N(r.SpellsAtIt)} reached it, {N(r.SpellsLanded)} landed", $"{N(r.SpellsAtYou)} reached you, {N(r.SpellsTaken)} landed"),
("Resisted", $"it resisted {N(r.Resisted)} ({MonsterCombatStats.Percent(r.ItResistsRate)})",
$"you resisted {N(r.YouResisted)} ({MonsterCombatStats.Percent(r.YouResistRate)})"),
};
if (r.NoEffect > 0 || r.NoEffectOnYou > 0)
rows.Add(("No effect", $"{N(r.NoEffect)} (it is immune)", $"{N(r.NoEffectOnYou)} (you are immune)"));
rows.Add(("Damage", $"{N(r.DamageDealt)} dealt", $"{N(r.DamageTaken)} taken"));
rows.Add(("Kills", N(r.Kills), string.Empty));
return rows;
}
/// <summary>/ra mstats's answer: a title line, then your side and its side (three chat lines).</summary>
public static string[] ChatLines(MonsterStatsRow r) => new[]
{
$"[RynthAi] {r.Name} since login: {N(r.Kills)} {(r.Kills == 1 ? "kill" : "kills")}.",
$"[RynthAi] You at it: {N(r.Swings)} swings, {N(r.Hits)} hit, it evaded {N(r.Evaded)} ({MonsterCombatStats.Percent(r.ItEvadesRate)}); "
+ $"{N(r.SpellsAtIt)} spells reached it, it resisted {N(r.Resisted)} ({MonsterCombatStats.Percent(r.ItResistsRate)})"
+ (r.NoEffect > 0 ? $", {N(r.NoEffect)} no effect" : string.Empty)
+ $"; {N(r.DamageDealt)} damage.",
$"[RynthAi] It at you: {N(r.Attacks)} attacks, {N(r.HitsTaken)} hit, you evaded {N(r.YouEvaded)} ({MonsterCombatStats.Percent(r.YouEvadeRate)}); "
+ $"{N(r.SpellsAtYou)} spells reached you, you resisted {N(r.YouResisted)} ({MonsterCombatStats.Percent(r.YouResistRate)})"
+ (r.NoEffectOnYou > 0 ? $", {N(r.NoEffectOnYou)} no effect" : string.Empty)
+ $"; {N(r.DamageTaken)} damage.",
};
/// <summary>One short line for /ra mstats list.</summary>
public static string ListLine(MonsterStatsRow r) =>
$"[RynthAi] {r.Name}: {N(r.Kills)} {(r.Kills == 1 ? "kill" : "kills")}, it evades {MonsterCombatStats.Percent(r.ItEvadesRate)}, "
+ $"resists {MonsterCombatStats.Percent(r.ItResistsRate)}; you evade {MonsterCombatStats.Percent(r.YouEvadeRate)}, "
+ $"resist {MonsterCombatStats.Percent(r.YouResistRate)}";
}

View file

@ -161,6 +161,12 @@ public static unsafe class PluginExports
int drawn = plugin.RenderDashboard(popped, out want);
if (drawn != 1) return drawn;
}
else if (name.SequenceEqual("window:monsterstats"u8))
{
// The Monster Stats window (RynthAiPlugin.MonsterStats.cs): 1 drawn, 0 not ready, -2 failed.
int drawn = plugin.RenderMonsterStats(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.
@ -243,17 +249,21 @@ public static unsafe class PluginExports
public static void OnEnchantmentRemoved(uint enchantmentId) => Runtime.OnEnchantmentRemoved(enchantmentId);
// API v78 server messages: only what RynthAiPlugin asked for (SetServerMessageInterest in
// Initialize: the transient-text game event, for "The door is locked!"). `data` lives only
// during the call; the text is copied out by the parser.
// Initialize: the transient-text game event, for "The door is locked!", and the four combat
// events, for the Monster Stats). `data` lives only during the call; the parsers copy out what
// they keep (the text, the monster's name).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnServerMessage", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnServerMessage(uint opcode, byte* data, int length)
{
try
{
var msg = RynthCore.PluginSdk.Net.ServerMessage.FromCallback(opcode, data, length);
if (msg.IsGameEvent && msg.EventType == RynthCore.PluginSdk.Net.GameEventType.TransientString
if (!msg.IsGameEvent) return;
if (msg.EventType == RynthCore.PluginSdk.Net.GameEventType.TransientString
&& RynthCore.PluginSdk.Net.SystemText.TryParse(msg.EventBody, true, out var text))
Runtime.Plugin?.NoteDoorServerText(text.Text);
else if (MonsterStats.CombatEvents.IsCombatEvent(msg.EventType))
Runtime.Plugin?.NoteCombatEvent(msg.EventType, msg.EventBody);
}
catch { }
}

View file

@ -127,6 +127,7 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item");
ChatLine("[RynthAi] /ra dumpinv — dump all inventory items (cache + direct)");
ChatLine("[RynthAi] /ra combat — dump combat state machine snapshot");
ChatLine("[RynthAi] /ra mstats [monster] — its evades, resists, hits, spells and kills this session (list | reset | show | hide)");
ChatLine("[RynthAi] /ra why — one-glance diagnosis of why the bot is idle/attacking");
ChatLine("[RynthAi] /ra start | stop — start/stop the macro from chat");
ChatLine("[RynthAi] /ra pause [sec] — stop the macro, auto-resume after sec (default 60)");

View file

@ -24,6 +24,22 @@ public sealed partial class RynthAiPlugin
return combat != null && (combat.HasEngageableTarget || combat.IsUnderCloseAttack);
}
/// <summary>
/// Idle for Rebuff When Idle's early top-off (BuffManager.IdleForTopOff): the macro on, no fight
/// (the target combat is locked on, a monster within Monster Range or on top of us; read with
/// Enable Combat off too, so a fight by hand counts), no corpse to loot (the arbiter's looting
/// input, last tick) and no salvage. Navigating counts as idle: buffing pauses the route as always.
/// </summary>
internal bool IdleForBuffTopOff()
{
var s = _dashboard?.Settings;
if (s == null || !s.IsMacroRunning) return false;
var combat = _combatManager;
if (combat == null || combat.HasEngageableTarget || combat.IsUnderCloseAttack) return false;
if (_lastWantLoot || _openedContainerId != 0 || _targetCorpseId != 0) return false;
return _salvageManager?.IsBusy != true;
}
/// <summary>
/// AutoCram / AutoStack, one tick: not while a corpse is open or claimed, and not in a fight (a
/// pack move went out between melee swings). The manager itself waits for the busy count.

View file

@ -133,6 +133,7 @@ public sealed partial class RynthAiPlugin
() => _combatManager?.activeTargetId ?? 0)
{
SessionStats = _sessionStats,
ToggleMonsterStats = MonsterStatsWindowWanted ? ToggleMonsterStatsWindow : null,
};
if (_translateUi != null) _huds.Translate = _translateUi;
@ -192,6 +193,8 @@ public sealed partial class RynthAiPlugin
catch (Exception ex) { Host.Log($"[RynthAi] diagnostics pump: {ex.Message}"); }
try { _sessionStats?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats tick"); }
try { TickMonsterStats(); } // after the session's tick: follows its start (RynthAiPlugin.MonsterStats.cs)
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats tick"); }
try { _serverHub?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "server plugin hub lookup"); }
try { _miniRemote?.Tick(); }
@ -481,7 +484,7 @@ public sealed partial class RynthAiPlugin
{
if (!_initialized || !_loginComplete) return null;
return Huds.SectionsManifest.Build(Huds.SectionsManifest.Views(), Huds.SectionsManifest.OwnSections,
dashboard: DashboardWindowWanted);
dashboard: DashboardWindowWanted, monsterStats: MonsterStatsWindowWanted);
}
/// <summary>Chat Translate window in the dashboard colours (no-op while hidden).</summary>
private void RenderTranslateWindow()

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using RynthCore.Loot; // AcObjectClass
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
@ -26,6 +27,14 @@ public sealed partial class RynthAiPlugin
internal const string TaperKey = "tapers";
// The scarab kinds a spell can use (Diamond is left out of the check). Only for an item whose
// class isn't known yet: one known to be something else never counts.
private static readonly HashSet<string> ScarabKinds = new(StringComparer.OrdinalIgnoreCase)
{
"Lead Scarab", "Iron Scarab", "Copper Scarab", "Silver Scarab", "Gold Scarab",
"Pyreal Scarab", "Platinum Scarab", "Mana Scarab",
};
/// <summary>Every tick with the safety checks; does the work every LowCompsCheckMs.</summary>
private void CheckLowComponents(LegacyUiSettings s)
{
@ -50,16 +59,25 @@ public sealed partial class RynthAiPlugin
Log("[RynthAi] " + line);
}
/// <summary>Tapers (every kind together, under <see cref="TaperKey"/>) and each scarab kind but Diamond, by stack size.</summary>
/// <summary>
/// Tapers (every kind together, under <see cref="TaperKey"/>) and each scarab kind but Diamond, by stack size.
/// Spell components only: an item of another class never counts, whatever its name (the "Mechanical
/// Scarab" jewelry stopped the macro as "Mechanical Scarab 0" once it had left the pack, 2026-10-30).
/// An item whose class isn't known yet counts only under a real component's name.
/// </summary>
internal static Dictionary<string, int> CountComponents(IEnumerable<WorldObject> inventory)
{
var counts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (var wo in inventory)
{
string name = wo?.Name ?? "";
if (wo == null) continue;
bool component = wo.ObjectClass == AcObjectClass.SpellComponent;
if (!component && wo.ObjectClass != AcObjectClass.Unknown) continue;
string name = wo.Name ?? "";
string? key = name.EndsWith(" Taper", StringComparison.OrdinalIgnoreCase) ? TaperKey
: name.EndsWith(" Scarab", StringComparison.OrdinalIgnoreCase)
&& !name.StartsWith("Diamond", StringComparison.OrdinalIgnoreCase) ? name
&& !name.StartsWith("Diamond", StringComparison.OrdinalIgnoreCase)
&& (component || ScarabKinds.Contains(name)) ? name
: null;
if (key == null) continue;
int n = Math.Max(1, wo!.Values(LongValueKey.StackCount, 1));

View file

@ -0,0 +1,546 @@
// RynthAiPlugin.MonsterStats.cs — combat per kind of monster since login (MonsterStats/), shown
// under each monster in the Damage panel's Monsters tab, and /ra mstats (2026-10-30, a player's
// request: "combat statistics under individual monsters, evades/resists for both the player and
// the monster").
//
// Where it shows: the Damage panel (the dashboard's Monsters key) draws RynthAi's rows
// (BuildMonsterDamageJson); each monster row carries its numbers as "mstats", and an engine that
// draws them (RynthCore feature/monster-stats-tab: UI/Data/DamageRowStats.cs, GetUiHookFlags bit 8)
// puts a line under the monster. On an older engine (the owner's PC, plugin API 90) the field is
// ignored, so RynthAi's own Monster Stats window (a plugin window, API v89) is the fallback, with
// the Session Stats view's "Monster stats" button; on an engine with the tab neither is offered.
//
// Sources (MonsterStats/): melee and missile from the server's typed combat events (API v78
// server messages: 0x01B1..0x01B4, asked for in Initialize); spells from the server's spell lines
// in chat (CombatLines, one table); kills from the kill notice. Not a player's chat types, never a
// player's or a pet's name, and an enchantment line only for a creature (items cast the same line).
//
// Lifetime: from login to logout (per character), kept across a hot reload (MonsterStatsStore),
// started over only by /ra mstats reset, the window's Reset or the Damage panel's Reset stats; not
// by Reset XP (the owner's rule, 2026-10-30). Pump thread throughout, except the window (render
// thread, the published view) and the Damage panel's poll (the published rows).
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.Text;
using System.Threading;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.MonsterStats;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
/// <summary>The window's title (its panel key) and surface (Huds/SectionsManifest.cs).</summary>
internal const string MonsterStatsTitle = "Monster Stats", MonsterStatsSurface = "window:monsterstats";
/// <summary>The engine's Damage panel key (the dashboard's Monsters key opens it).</summary>
internal const string DamagePanelKey = "Monsters";
internal const string MonsterStatsUsage = "Usage: /ra mstats [monster] | list | reset | show | hide";
/// <summary>
/// GetUiHookFlags bit 8 (SDK RynthUiHookFlags.DamageRowStats on RynthCore feature/monster-stats-tab):
/// the engine's Damage panel draws a row's "mstats". Spelled here so RynthAi builds against an
/// SDK without the name.
/// </summary>
internal const uint DamageRowStatsFlag = 1u << 8;
private static readonly TimeSpan MonsterStatsSaveInterval = TimeSpan.FromSeconds(30);
private readonly MonsterCombatStats _monsterStats = new();
private volatile MonsterStatsView _monsterStatsView = MonsterStatsView.Empty; // tick writes, render reads
private int _monsterStatsViewVersion = -1;
private string _monsterStatsViewFocus = string.Empty;
private bool _monsterStatsViewInWorld;
private long _monsterStatsViewAtMs;
private long _monsterStatsDrawnMs = long.MinValue / 2; // render writes, tick reads
// The rows by name for the Damage panel's poll (BuildMonsterDamageJson, its own thread): swapped whole.
private volatile Dictionary<string, MonsterStatsRow> _monsterStatsByName = new(StringComparer.OrdinalIgnoreCase);
private int _monsterStatsByNameVersion = -1;
/// <summary>The counting has begun for this login (the save looked for); false before login and after logout.</summary>
private bool _monsterStatsStarted;
/// <summary>When the numbers started (login, or the last reset), UTC.</summary>
private DateTime _monsterStatsSinceUtc;
/// <summary>The Damage panel's Reset stats asked (its thread); done on the tick.</summary>
private volatile bool _monsterStatsResetWanted;
private int _monsterStatsSavedVersion = -1;
private DateTime _monsterStatsSaveAtUtc;
private bool _monsterStatsSaveFailedLogged;
/// <summary>The engine streams the combat game events (Initialize); false = melee and missile go uncounted.</summary>
private bool _combatEventsStreaming = true;
private MonsterStatsWindow? _monsterStatsWindow; // render thread
private int _monsterStatsFailures; // render thread
// Creature names around, by class (refreshed at most every 2 s): who a line's name is.
private readonly Dictionary<string, AcObjectClass> _creatureClassByName = new(StringComparer.OrdinalIgnoreCase);
private long _creatureNamesAtMs = long.MinValue / 2;
/// <summary>Where the save goes (tests point it at a temp folder).</summary>
internal string MonsterStatsDirectory { get; set; } = MonsterStatsStore.DefaultDirectory();
/// <summary>The counters (tests, and RynthAi's own readers).</summary>
internal MonsterCombatStats MonsterStatsForTests => _monsterStats;
/// <summary>The engine's Damage panel shows the numbers under each monster (GetUiHookFlags bit 8). Any thread.</summary>
internal bool EngineDrawsMonsterStats => Host.HasUiHooks && ((uint)Host.GetUiHookFlags() & DamageRowStatsFlag) != 0;
// ── Events (pump thread) ─────────────────────────────────────────────
/// <summary>One of the four combat game events (PluginExports.OnServerMessage).</summary>
internal void NoteCombatEvent(uint eventType, ReadOnlySpan<byte> body)
{
if (!_loginComplete) return;
if (!CombatEvents.TryParse(eventType, body, out PhysicalEvent kind, out string name, out int damage)) return;
if (!CountsAsMonster(name, mayBeItem: false)) return;
_monsterStats.OnPhysical(kind, name, damage, DateTime.UtcNow);
}
/// <summary>A chat line: one of the spell lines (CombatLines) about a monster, unless a player wrote it.</summary>
private void NoteMonsterStatsChat(string text, int chatType)
{
if (!_loginComplete || RynthCore.Plugin.Shared.ChatSource.IsPlayerAuthored(chatType)) return;
if (!CombatLines.TryParse(text, out CombatLine line)) return;
if (!CountsAsMonster(line.Name, line.MayBeItem)) return;
_monsterStats.OnSpell(line, DateTime.UtcNow);
}
/// <summary>The kill notice: a kill, and the killing blow by the combat mode it was struck in.</summary>
private void NoteMonsterStatsKill(string? notice)
{
if (!_loginComplete) return;
KillBlow blow = _currentCombatMode switch
{
CombatMode.Melee or CombatMode.Missile => KillBlow.Physical,
CombatMode.Magic => KillBlow.Spell,
_ => KillBlow.None,
};
_monsterStats.OnKill(notice, blow, DateTime.UtcNow, CreatureNameIn);
}
/// <summary>
/// A name the stats count: not a player's or a pet's (PvP, a summon), nor an NPC's; and for a line
/// an item could have sent (<paramref name="mayBeItem"/>), a creature around or a monster already
/// counted. A name the client doesn't know otherwise counts (a monster out of sight).
/// </summary>
private bool CountsAsMonster(string name, bool mayBeItem)
{
AcObjectClass? cls = CreatureClassOf(name);
if (cls is AcObjectClass.Player or AcObjectClass.CombatPet or AcObjectClass.Npc or AcObjectClass.Vendor) return false;
if (mayBeItem && cls == null && !_monsterStats.IsTracked(name)) return false;
return true;
}
/// <summary>The class of the creature around with that name, or null when none is known.</summary>
private AcObjectClass? CreatureClassOf(string name)
{
RefreshCreatureNames(false);
if (_creatureClassByName.TryGetValue(name, out AcObjectClass cls)) return cls;
// A creature that just came: look once more before calling it unknown (at most every 250 ms).
if (Environment.TickCount64 - _creatureNamesAtMs > 250)
{
RefreshCreatureNames(true);
if (_creatureClassByName.TryGetValue(name, out cls)) return cls;
}
return null;
}
private void RefreshCreatureNames(bool force)
{
long now = Environment.TickCount64;
if (!force && now - _creatureNamesAtMs < 2000) return;
_creatureNamesAtMs = now;
_creatureClassByName.Clear();
var cache = _objectCache;
if (cache == null) return;
foreach (WorldObject wo in cache.GetLandscape())
{
if (wo == null || string.IsNullOrEmpty(wo.Name)) continue;
// The cache can file a player as a monster (a creature whose kind wasn't readable yet):
// a player's guid says player. A player's name wins over a monster's of the same name.
AcObjectClass cls = CreatureData.PlayerWeenies.IsPlayerGuid(unchecked((uint)wo.Id)) ? AcObjectClass.Player : wo.ObjectClass;
if (_creatureClassByName.TryGetValue(wo.Name, out AcObjectClass had) && had == AcObjectClass.Player) continue;
_creatureClassByName[wo.Name] = cls;
}
// Players, NPCs and pets that aren't in the creature list (everything with a place in the
// world): never a monster. Items stay unknown (an enchantment line from one doesn't count).
foreach (WorldObject wo in cache.GetLandscapeObjects())
{
if (wo == null || string.IsNullOrEmpty(wo.Name)) continue;
AcObjectClass cls = CreatureData.PlayerWeenies.IsPlayerGuid(unchecked((uint)wo.Id)) ? AcObjectClass.Player : wo.ObjectClass;
if (cls is AcObjectClass.Player or AcObjectClass.Npc or AcObjectClass.Vendor or AcObjectClass.CombatPet)
_creatureClassByName[wo.Name] = cls;
}
}
/// <summary>The kill notice names a monster with no numbers yet (killed by its first blow): the longest creature name around in it.</summary>
private string? CreatureNameIn(string notice)
{
RefreshCreatureNames(true);
string? best = null;
foreach (var kv in _creatureClassByName)
{
if (kv.Value is AcObjectClass.Player or AcObjectClass.CombatPet or AcObjectClass.Npc or AcObjectClass.Vendor) continue;
if ((best == null || kv.Key.Length > best.Length) && notice.IndexOf(kv.Key, StringComparison.OrdinalIgnoreCase) >= 0)
best = kv.Key;
}
return best;
}
// ── Tick (pump thread) ───────────────────────────────────────────────
/// <summary>Starts the login's counting (or brings the save back after a reload), resets on asking, saves, publishes.</summary>
private void TickMonsterStats()
{
DateTime now = DateTime.UtcNow;
if (!_monsterStatsStarted && _loginComplete && _playerId != 0)
{
// The login's first tick with the character known: after a hot reload the save is there.
_monsterStatsStarted = true;
if (TryRestoreMonsterStats(now))
Host.Log($"[RynthAi] Monster stats carried over from before the reload ({_monsterStats.Count} kinds of monster).");
else
{
_monsterStatsSinceUtc = now;
CleanupMonsterStatsSaves(now);
}
_monsterStatsSaveAtUtc = now + MonsterStatsSaveInterval;
}
if (_monsterStatsResetWanted)
{
_monsterStatsResetWanted = false;
ResetMonsterStats("the Damage panel's Reset stats");
}
if (_monsterStatsStarted && now >= _monsterStatsSaveAtUtc)
{
_monsterStatsSaveAtUtc = now + MonsterStatsSaveInterval;
if (_monsterStats.Version != _monsterStatsSavedVersion) SaveMonsterStats(now);
}
PublishMonsterStatsRows();
PublishMonsterStatsView(Environment.TickCount64);
}
/// <summary>Every monster's numbers start over (/ra mstats reset, the window's Reset, the Damage panel's Reset stats). Pump thread.</summary>
private int ResetMonsterStats(string by)
{
int n = _monsterStats.Count;
_monsterStats.Reset();
DateTime now = DateTime.UtcNow;
_monsterStatsSinceUtc = now;
// Saved at once, so a reload right after a reset can't bring the old numbers back.
if (_monsterStatsStarted) SaveMonsterStats(now);
Host.Log($"[RynthAi] Monster stats started over ({by}; {n} kinds of monster cleared).");
return n;
}
/// <summary>The Damage panel's Reset stats (RynthPluginClearMonsterStats, its thread): the monster stats start over too.</summary>
internal void RequestMonsterStatsReset() => _monsterStatsResetWanted = true;
/// <summary>The rows by name for the Damage panel's poll, when something changed.</summary>
private void PublishMonsterStatsRows()
{
if (_monsterStats.Version == _monsterStatsByNameVersion) return;
_monsterStatsByNameVersion = _monsterStats.Version;
var byName = new Dictionary<string, MonsterStatsRow>(StringComparer.OrdinalIgnoreCase);
foreach (MonsterStatsRow r in _monsterStats.Snapshot()) byName[r.Name] = r;
_monsterStatsByName = byName;
}
/// <summary>
/// A Damage-panel row's "mstats" field and its comma, for the monster named <paramref name="name"/>
/// (UI/Data/DamageRowStats.cs in the engine reads it); "" for a monster without numbers. Any thread.
/// </summary>
internal string MonsterStatsJsonFor(string name)
{
if (!_monsterStatsByName.TryGetValue(name, out MonsterStatsRow? r) || r.IsEmpty) return string.Empty;
return MonsterStatsJson(r) + ",";
}
/// <summary>"mstats":{...} for one monster (the field names DamageRowStats reads).</summary>
internal static string MonsterStatsJson(MonsterStatsRow r)
{
CultureInfo ic = CultureInfo.InvariantCulture;
var sb = new StringBuilder(160);
sb.Append("\"mstats\":{")
.Append("\"sw\":").Append(r.Swings.ToString(ic)).Append(",\"ev\":").Append(r.Evaded.ToString(ic))
.Append(",\"sp\":").Append(r.SpellsAtIt.ToString(ic)).Append(",\"rs\":").Append(r.Resisted.ToString(ic))
.Append(",\"ne\":").Append(r.NoEffect.ToString(ic))
.Append(",\"at\":").Append(r.Attacks.ToString(ic)).Append(",\"yev\":").Append(r.YouEvaded.ToString(ic))
.Append(",\"ysp\":").Append(r.SpellsAtYou.ToString(ic)).Append(",\"yrs\":").Append(r.YouResisted.ToString(ic))
.Append(",\"yne\":").Append(r.NoEffectOnYou.ToString(ic))
.Append(",\"k\":").Append(r.Kills.ToString(ic))
.Append(",\"dd\":").Append(r.DamageDealt.ToString(ic)).Append(",\"dt\":").Append(r.DamageTaken.ToString(ic))
.Append('}');
return sb.ToString();
}
/// <summary>
/// A new view for the fallback window when something changed (at most 4 a second): while it is on
/// screen, and off screen only for a login or logout, so it never opens on the wrong one.
/// </summary>
private void PublishMonsterStatsView(long nowMs)
{
bool shown = nowMs - Volatile.Read(ref _monsterStatsDrawnMs) <= 2000;
if (!shown && _monsterStatsViewVersion != -1 && _monsterStatsViewInWorld == _loginComplete) return;
if (nowMs - _monsterStatsViewAtMs < 250) return;
string focus = MonsterStatsFocusName();
if (_monsterStats.Version == _monsterStatsViewVersion && focus == _monsterStatsViewFocus
&& _loginComplete == _monsterStatsViewInWorld) return;
_monsterStatsViewAtMs = nowMs;
_monsterStatsViewVersion = _monsterStats.Version;
_monsterStatsViewFocus = focus;
_monsterStatsViewInWorld = _loginComplete;
_monsterStatsView = new MonsterStatsView(_monsterStats.Snapshot(), focus, _combatEventsStreaming, _loginComplete);
}
/// <summary>The monster in focus: the one combat fights, else the selected creature; "" for none.</summary>
private string MonsterStatsFocusName()
{
int id = _combatManager?.activeTargetId ?? 0;
if (id == 0) id = unchecked((int)_currentTargetId);
if (id == 0) return string.Empty;
if (CreatureData.PlayerWeenies.IsPlayerGuid(unchecked((uint)id))) return string.Empty;
WorldObject? wo = _objectCache?[id];
return wo != null && wo.ObjectClass != AcObjectClass.Player ? wo.Name ?? string.Empty : string.Empty;
}
/// <summary>A real logout ends them (they are per character and login), and the save with them.</summary>
private void OnLogoutMonsterStats()
{
if (_monsterStatsStarted) DeleteMonsterStatsSave();
_monsterStats.Reset();
_monsterStatsStarted = false;
_monsterStatsSavedVersion = -1;
_creatureClassByName.Clear();
PublishMonsterStatsRows();
_monsterStatsView = MonsterStatsView.Empty;
_monsterStatsViewVersion = -1;
}
/// <summary>Plugin unload (hot reload, update, client closing): saved while counting, never deleted.</summary>
private void ShutdownMonsterStats()
{
if (_monsterStatsStarted) SaveMonsterStats(DateTime.UtcNow);
}
// ── Saving (MonsterStatsStore) ───────────────────────────────────────
private void SaveMonsterStats(DateTime now)
{
if (_playerId == 0 || !_monsterStatsStarted) return;
try
{
var save = new MonsterStatsSave
{
ProcessId = Environment.ProcessId,
ProcessStartUtcTicks = MonsterStatsStore.ProcessStartTicks,
CharacterId = _playerId,
SavedUtcTicks = now.Ticks,
SinceUtcTicks = _monsterStatsSinceUtc.Ticks,
Rows = new List<MonsterStatsRow>(_monsterStats.Snapshot()),
};
MonsterStatsStore.Save(MonsterStatsDirectory, save);
_monsterStatsSavedVersion = _monsterStats.Version;
_monsterStatsSaveFailedLogged = false;
}
catch (Exception ex)
{
if (_monsterStatsSaveFailedLogged) return; // one line until a save works again
_monsterStatsSaveFailedLogged = true;
Host.Log($"[RynthAi] Couldn't save the monster stats: {ex.GetType().Name}: {ex.Message}");
}
}
private bool TryRestoreMonsterStats(DateTime now)
{
if (_playerId == 0) return false;
try
{
int pid = Environment.ProcessId;
if (!MonsterStatsStore.TryLoad(MonsterStatsDirectory, pid, _playerId, out MonsterStatsSave save)) return false;
if (!MonsterStatsStore.ShouldRestore(save, pid, MonsterStatsStore.ProcessStartTicks, _playerId, now)) return false;
_monsterStats.Load(save.Rows);
_monsterStatsSinceUtc = new DateTime(save.SinceUtcTicks, DateTimeKind.Utc);
_monsterStatsSavedVersion = _monsterStats.Version;
return true;
}
catch (Exception ex)
{
Host.Log($"[RynthAi] Couldn't read the saved monster stats, starting fresh: {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private void DeleteMonsterStatsSave()
{
if (_playerId == 0) return;
try { MonsterStatsStore.Delete(MonsterStatsDirectory, Environment.ProcessId, _playerId); }
catch (Exception ex) { Host.Log($"[RynthAi] Couldn't delete the saved monster stats: {ex.GetType().Name}: {ex.Message}"); }
}
private void CleanupMonsterStatsSaves(DateTime now)
{
try { MonsterStatsStore.Cleanup(MonsterStatsDirectory, Environment.ProcessId, now); }
catch { }
}
// ── /ra mstats ───────────────────────────────────────────────────────
/// <summary>
/// "/ra mstats [monster]" prints a monster's numbers (no name: the monster combat fights, else
/// the selected one); "list" the monsters with numbers; "reset" starts them over; "show", "hide",
/// "toggle" the Damage panel (or, on an older engine, the Monster Stats window). Pump thread.
/// </summary>
private void HandleMonsterStatsCommand(string[] parts)
{
string arg = parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2).Trim() : string.Empty;
switch (arg.ToLowerInvariant())
{
case "list":
ListMonsterStats();
return;
case "reset":
case "clear":
{
int n = ResetMonsterStats("/ra mstats reset");
ReplyOk($"[RynthAi] Monster stats started over ({n} {(n == 1 ? "kind" : "kinds")} of monster cleared).");
return;
}
case "show":
case "open":
case "window":
case "hide":
case "close":
case "toggle":
SetMonsterStatsWindow(arg.ToLowerInvariant());
return;
case "help":
case "?":
ChatLine("[RynthAi] /ra mstats [monster] — a monster's evades, resists, hits, spells and kills since login (no name: the one you fight or have selected)");
ChatLine("[RynthAi] /ra mstats list | reset | show | hide — every monster, start over, where they show (the Damage panel's Monsters tab)");
return;
}
MonsterStatsRow? row;
if (arg.Length == 0)
{
string focus = MonsterStatsFocusName();
row = focus.Length > 0 ? _monsterStats.Get(focus) : null;
if (row == null)
{
ReplyFail((focus.Length > 0
? $"[RynthAi] No monster stats for {focus} since login yet."
: "[RynthAi] Select a monster or name one.")
+ KnownMonsters() + " " + MonsterStatsUsage);
return;
}
}
else
{
row = _monsterStats.Find(arg, out List<string> candidates);
if (row == null)
{
ReplyFail(candidates.Count > 1
? $"[RynthAi] '{arg}' matches {candidates.Count} monsters: {string.Join(", ", candidates)}. Name one exactly. {MonsterStatsUsage}"
: $"[RynthAi] No monster stats for '{arg}' since login.{KnownMonsters()} {MonsterStatsUsage}");
return;
}
}
foreach (string line in MonsterStatsText.ChatLines(row)) ChatLine(line);
}
/// <summary>" Monsters with stats: A, B, C." (the most recent few), or " No monster has stats yet."</summary>
private string KnownMonsters()
{
MonsterStatsRow[] rows = _monsterStats.Snapshot();
if (rows.Length == 0) return " No monster has stats yet.";
var names = new List<string>();
for (int i = 0; i < rows.Length && i < 6; i++) names.Add(rows[i].Name);
return " Monsters with stats: " + string.Join(", ", names) + (rows.Length > 6 ? ", ..." : "") + ".";
}
private void ListMonsterStats()
{
MonsterStatsRow[] rows = _monsterStats.Snapshot();
if (rows.Length == 0)
{
ChatLine("[RynthAi] No monster stats yet since login: fight something.");
return;
}
ChatLine($"[RynthAi] Monster stats since login ({rows.Length} {(rows.Length == 1 ? "kind" : "kinds")}, most recent first):");
for (int i = 0; i < rows.Length && i < 10; i++) ChatLine(MonsterStatsText.ListLine(rows[i]));
if (rows.Length > 10) ChatLine($"[RynthAi] ... and {rows.Length - 10} more (/ra mstats show).");
}
/// <summary>"show" / "hide" / "toggle": the Damage panel where it shows them, else the fallback window.</summary>
private void SetMonsterStatsWindow(string verb)
{
if (!Host.HasSetPanelOpen)
{
ReplyFail("[RynthAi] Opening a panel needs RynthCore with plugin windows (plugin API 89+); /ra mstats <monster> prints the numbers.");
return;
}
RynthPanelOpen mode = verb is "hide" or "close" ? RynthPanelOpen.Close : verb == "toggle" ? RynthPanelOpen.Toggle : RynthPanelOpen.Open;
bool tab = EngineDrawsMonsterStats;
string key = tab ? DamagePanelKey : MonsterStatsTitle;
string what = tab ? "Damage panel (Monsters)" : "Monster Stats window";
int open = Host.SetPanelOpen(key, mode);
if (open < 0)
{
ReplyFail(tab
? "[RynthAi] RynthCore has no Damage panel to open."
: "[RynthAi] The Monster Stats window isn't there yet (RynthCore adds it a few seconds after login). Try again in a moment.");
return;
}
ReplyOk(open == 1
? $"[RynthAi] {what} open{(tab ? ": each monster's evades and resists are under its line." : ".")}"
: $"[RynthAi] {what} closed.");
}
/// <summary>The window's Reset (queued from the render thread, run on the tick).</summary>
private void ResetMonsterStatsFromWindow() => ResetMonsterStats("the Monster Stats window");
/// <summary>The Session Stats view's "Monster stats" button (the fallback window only): open or closed. Any thread.</summary>
internal void ToggleMonsterStatsWindow()
{
if (Host.HasSetPanelOpen) Host.SetPanelOpen(MonsterStatsTitle, RynthPanelOpen.Toggle);
}
// ── Fallback window (render thread) ──────────────────────────────────
/// <summary>
/// RynthPluginRenderEmbed "window:monsterstats": the Monster Stats window body, docked or popped
/// out (the engine's current context). 1 drawn, 0 not ready, -2 failed (three draws in a row threw).
/// </summary>
internal int RenderMonsterStats(bool popped, out Vector2 want)
{
want = default;
if (!_initialized || Host.ImGuiContext == IntPtr.Zero) return 0;
Volatile.Write(ref _monsterStatsDrawnMs, Environment.TickCount64);
IntPtr previous = ImGui.GetCurrentContext();
ImGui.SetCurrentContext(EmbedContext());
try
{
_monsterStatsWindow ??= new MonsterStatsWindow(() => QueueDashAction(ResetMonsterStatsFromWindow));
want = _monsterStatsWindow.Draw(_monsterStatsView);
_monsterStatsFailures = 0;
return 1;
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.UI, ex, "RenderMonsterStats");
return ++_monsterStatsFailures >= 3 ? -2 : 0;
}
finally
{
ImGui.SetCurrentContext(previous);
}
}
/// <summary>
/// The fallback window goes in the sections manifest on an engine with plugin windows (v89) whose
/// Damage panel doesn't show the numbers (no GetUiHookFlags bit 8: the owner's API-90 core).
/// </summary>
private bool MonsterStatsWindowWanted => Host.HasUiTheme && Host.HasSetPanelOpen && !EngineDrawsMonsterStats;
}

View file

@ -244,13 +244,19 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
RynthCore.Plugin.Shared.UseAudit.WorldUseHold = SalvagePanelHold;
// "The door is locked!" comes as a transient string (ACE Door.ActOnUse): the door logic picks a
// lock only when the server says so (DoorInteractionController). The chat line is the fallback.
// The four combat events (hits and evades both ways, by name) feed the Monster Stats
// (RynthAiPlugin.MonsterStats.cs); without the stream melee and missile go uncounted there.
_combatEventsStreaming = false;
try
{
if (Host.HasServerMessages)
{
int sm = Host.SetServerMessageInterest(ReadOnlySpan<uint>.Empty,
new uint[] { RynthCore.PluginSdk.Net.GameEventType.TransientString });
if (sm != 1) Host.Log($"[RynthAi] Server messages: not streaming ({sm}); locked doors are read from chat only.");
var events = new uint[1 + MonsterStats.CombatEvents.GameEvents.Length];
events[0] = RynthCore.PluginSdk.Net.GameEventType.TransientString;
MonsterStats.CombatEvents.GameEvents.CopyTo(events, 1);
int sm = Host.SetServerMessageInterest(ReadOnlySpan<uint>.Empty, events);
_combatEventsStreaming = sm == 1;
if (sm != 1) Host.Log($"[RynthAi] Server messages: not streaming ({sm}); locked doors are read from chat only, and the Monster Stats count no melee or missile attacks.");
}
}
catch (Exception ex) { Host.Log($"[RynthAi] Server messages: {ex.Message}"); }
@ -286,6 +292,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
long t0 = Environment.TickCount64;
try { _dashboard?.SaveSettings(); } catch { }
try { _sessionStats?.Shutdown(); } catch { }
try { ShutdownMonsterStats(); } catch { } // kept for the next copy, with the session
try { GameInput.Shutdown(); } catch { } // keys still held for /mt movement | jump | strafe
// Release the Monster Editor process handle (if the toggle button
// launched one) rather than leaking it on plugin unload/hot-reload.
@ -341,6 +348,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
Log("RynthAi: logout — tearing down session.");
try { _dashboard?.SaveSettings(); } catch { }
try { _sessionStats?.OnLogout(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats logout"); }
try { OnLogoutMonsterStats(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats logout"); }
Loot.T11ItemSupport.Reset();
// A real logout: the next OnLoginComplete is a fresh login, not a hot reload.
ClearInGameMarker();
@ -757,7 +765,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager.JumpBusy = () => _jumper?.IsBusy == true;
_buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count
if (_buffManager != null)
{
_buffManager.OffhandStowed = id => _combatManager?.NoteOffhandStowed(id);
_buffManager.IdleForTopOff = IdleForBuffTopOff; // Rebuff When Idle's early top-off (RynthAiPlugin.Chores.cs)
}
_combatManager.SetCharacterSkills(_charSkills);
_combatManager.SetPlayerId(_playerId);
_combatManager.SetDamageStores(_creatureStore, _damageStore);
@ -1104,7 +1115,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
["DunPatrolSightYd"] = (DungeonPatrolOptions.SightMin, DungeonPatrolOptions.SightMax),
["T2Speed"] = (0.1, 5), ["T2WalkWithinYd"] = (1, 50), ["T2DistanceTo"] = (0.1, 10), ["T2ReissueMs"] = (100, 10000),
["T2MaxRangeYd"] = (50, 2000), ["T2MaxLandblocks"] = (1, 20),
["RebuffSecondsRemaining"] = (30, 1800), ["RebuffTopOffSecondsRemaining"] = (30, 3600),
["RebuffSecondsRemaining"] = (30, 1800), ["RebuffTopOffSecondsRemaining"] = (30, 3600), ["RebuffIdleMarginMinutes"] = (0, 60),
["AutoVendorTries"] = (1, 20), ["AutoVendorTriesTime"] = (500, 30000),
["BuffMinSkillLevelTier1"] = (1, 500), ["BuffMinSkillLevelTier2"] = (1, 500), ["BuffMinSkillLevelTier3"] = (1, 500), ["BuffMinSkillLevelTier4"] = (1, 500),
["BuffMinSkillLevelTier5"] = (1, 500), ["BuffMinSkillLevelTier6"] = (1, 500), ["BuffMinSkillLevelTier7"] = (1, 500), ["BuffMinSkillLevelTier8"] = (1, 500),
@ -2409,6 +2420,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
try { NoteServerPolicyChat(text); } catch { } // DreamWeave's Thread lines (ServerPolicy)
try { NoteDoorServerText(text); } catch { } // "The door is locked!" (the door logic)
try { _sessionStats?.OnChatWindowText(text); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats chat"); }
try { NoteMonsterStatsChat(text, chatType); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats chat"); }
// The Meta Manager eats the reply to its own /myquests poll (only that).
bool mmEat = false;
try { mmEat = MetaScheduleChat(text); } catch { }
@ -2441,6 +2453,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// Mini Remote stats count every notice, as RynthTracker does (an empty message is still a kill).
try { _sessionStats?.OnKillNotification(deathMessage); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats kill"); }
try { NoteMonsterStatsKill(deathMessage); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats kill"); }
if (string.IsNullOrEmpty(deathMessage)) return;
_killClock.RecordKill(); // the only kill source: KillerNotification goes to the killer alone
NoteBoostLootKill(); // before combat sees the kill: its next target waits for the corpse
@ -2494,7 +2508,6 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
{
float prevRatio = _objectCache?.GetHealthRatio(unchecked((int)targetId)) ?? -1f;
_sessionStats?.OnUpdateHealth(targetId, currentHealth, maxHealth);
_objectCache?.OnUpdateHealth(targetId, healthRatio);
_combatManager?.NoteServerHealth(unchecked((int)targetId), healthRatio); // kill-shot evidence (fight target only)
_dashboard?.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
@ -2786,6 +2799,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
.Append("\"petLabel\":").Append(JsonStr(PetChoiceLabel(pet))).Append(',')
.Append(WeakJson(wcid, name, wcids));
if (wcids.Length > 1) sb.Append("\"wcids\":[").Append(string.Join(",", wcids)).Append("],");
// Its evades and resists both ways since login (RynthAiPlugin.MonsterStats.cs): the line under
// the monster on an engine that draws it; an older one ignores the field.
sb.Append(MonsterStatsJsonFor(name));
sb.Append("\"key\":").Append(JsonStr(wcid.ToString())).Append(',')
.Append("\"tiers\":[");
@ -3222,9 +3238,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
return sb.ToString();
}
/// <summary>Master reset from the Damage panel: zero all learned stats, keep names + manual overrides. Persists.</summary>
/// <summary>Master reset from the Damage panel: zero all learned stats, keep names + manual overrides. Persists.
/// The evades and resists under each monster (RynthAiPlugin.MonsterStats.cs) start over too.</summary>
public void ClearMonsterStats()
{
RequestMonsterStatsReset();
if (_damageStore == null) return;
_damageStore.ClearAllStats();
_damageStore.SaveIfDirty();
@ -4009,6 +4027,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "fellowinfo": HandleFellowshipInfoCommand(); break;
case "dumpinv": HandleDumpInventoryCommand(); break;
case "combat": HandleCombatStateCommand(); break;
case "mstats": HandleMonsterStatsCommand(parts); break; // RynthAiPlugin.MonsterStats.cs
case "why": HandleWhyCommand(); break;
case "ghost":
case "ghosts": HandleGhostsCommand(cmd, parts); break;

View file

@ -2,16 +2,27 @@ 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, Settings, Spell, Corpses }
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings, Spell, Corpses,
Quantity, Split, Give, Buy }
/// <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 = "");
/// <summary>
/// A parsed "/rdef ..." line. Use: <see cref="Slot"/> (1-based) or <see cref="Text"/> (an item name).
/// The quantity box's verbs (qty, split, give, buy): <see cref="Amount"/> (null = the box's number) and
/// <see cref="Text"/> (split: the pack; buy: the item's name).
/// </summary>
internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "", QtyAmount? Amount = null);
internal static class DefCommandParser
{
public const string Usage =
"/rdef [use <slot or item name> | set <slot> [item name] | spell <slot> <spell name> | clear <slot> | bind <slot> <key> | unbind <slot> | "
+ "weapons [search] | fav | slots <count> | list | status | settings | panels (the game panel buttons) | selection | corpses [clear]]";
+ "weapons [search] | fav | slots <count> | list | status | settings | panels (the game panel buttons) | selection | corpses [clear] | "
+ "qty [number|max|half] | split [number] [into <pack>] | give [number] | buy [number] [item name]]";
public const string QtyUsage = "Usage: /rdef qty <number|max|half>, e.g. /rdef qty 25 (the Selection window's number)";
public const string SplitUsage = "Usage: /rdef split [number|max|half] [into <pack>], e.g. /rdef split 25 or /rdef split 25 into Sack";
public const string GiveUsage = "Usage: /rdef give [number|max|half], e.g. /rdef give 10 (to the last player or NPC you selected)";
public const string BuyUsage = "Usage: /rdef buy [number|max|half] [item name], e.g. /rdef buy 25 or /rdef buy 25 Mana Scarab (a vendor open)";
/// <summary>Parses the arguments after "/rdef" (blank = show or hide the bar).</summary>
public static DefCommand Parse(string? args)
@ -68,6 +79,31 @@ internal static class DefCommandParser
return int.TryParse(rest, out int count) && count >= DefSettings.SlotsMin && count <= DefSettings.SlotCountMax
? new DefCommand(DefVerb.Slots, count)
: Fail($"How many slots? {DefSettings.SlotsMin} to {DefSettings.SlotCountMax}, e.g. /rdef slots 10");
// The quantity box (2026-10-30, Quantity/QuantityController.cs).
case "qty": case "quantity": case "amount":
{
if (rest.Length == 0) return new DefCommand(DefVerb.Quantity);
return QuantityRules.TryParse(rest, out QtyAmount q, out string why)
? new DefCommand(DefVerb.Quantity, Amount: q)
: Fail(why + " " + QtyUsage);
}
case "split":
{
if (!QuantityRules.TryParseLeading(rest, out QtyAmount? q, out string tail, out string why)) return Fail(why + " " + SplitUsage);
string into = StripWord(tail, "into", "in", "to");
return new DefCommand(DefVerb.Split, Text: into, Amount: q);
}
case "give":
{
if (!QuantityRules.TryParseLeading(rest, out QtyAmount? q, out string tail, out string why)) return Fail(why + " " + GiveUsage);
if (tail.Length > 0) return Fail($"'{tail}' isn't a quantity. {GiveUsage}");
return new DefCommand(DefVerb.Give, Amount: q);
}
case "buy":
{
if (!QuantityRules.TryParseLeading(rest, out QtyAmount? q, out string tail, out string why)) return Fail(why + " " + BuyUsage);
return new DefCommand(DefVerb.Buy, Text: StripWord(tail, "of"), Amount: q);
}
default:
// "/rdef Stamina Kit" is a shorthand for use.
return new DefCommand(DefVerb.Use, Text: a);
@ -91,4 +127,14 @@ internal static class DefCommandParser
}
private static DefCommand Fail(string error) => new(DefVerb.Error, Error: error);
/// <summary>The text without a leading word ("into Sack" -> "Sack").</summary>
private static string StripWord(string text, params string[] words)
{
string t = text.Trim();
foreach (string w in words)
if (t.Length > w.Length && t.StartsWith(w, StringComparison.OrdinalIgnoreCase) && char.IsWhiteSpace(t[w.Length]))
return t[(w.Length + 1)..].Trim();
return t;
}
}

View file

@ -111,6 +111,12 @@ internal sealed class DefSettings
/// the picker opens from the settings window, the bar's right-click menu and /rdef weapons.
/// </summary>
public bool WeaponsButtonOnBar;
/// <summary>
/// The quantity box under a stack or a vendor's item in the Selection window (2026-10-30): how many,
/// and Split / Give / Buy that many. On (the default, and what a file from before reads as).
/// /rdef qty, split, give and buy work either way.
/// </summary>
public bool QuantityBox = true;
public bool BarOpen;
public bool PickerOpen;

View file

@ -68,6 +68,7 @@ internal sealed class DefStore
st.SwapWhileBotRuns = Bool(s, "swapWhileBotRuns", st.SwapWhileBotRuns);
st.WeaponsButtonOnBar = Bool(s, "weaponsButtonOnBar", st.WeaponsButtonOnBar); // missing (a file from before 2026-10-29): off
st.IndependentBar = Bool(s, "independentBar", st.IndependentBar); // missing (a file from before 2026-10-27): off
st.QuantityBox = Bool(s, "quantityBox", st.QuantityBox); // missing (a file from before 2026-10-30): on
st.BarOpen = Bool(s, "barOpen", st.BarOpen);
st.PickerOpen = Bool(s, "pickerOpen", st.PickerOpen);
st.Clamp();
@ -166,6 +167,7 @@ internal sealed class DefStore
w.WriteBoolean("swapWhileBotRuns", s.SwapWhileBotRuns);
w.WriteBoolean("weaponsButtonOnBar", s.WeaponsButtonOnBar);
w.WriteBoolean("independentBar", s.IndependentBar);
w.WriteBoolean("quantityBox", s.QuantityBox);
w.WriteBoolean("barOpen", s.BarOpen);
w.WriteBoolean("pickerOpen", s.PickerOpen);
w.WriteEndObject();

View file

@ -0,0 +1,406 @@
// ============================================================================
// RynthDefective - Model/Quantity.cs
// The quantity box's rules (2026-10-30): how many of a stack a split or a
// give takes, how many of a vendor's item a buy asks for, what that costs and
// why it can't go. Pure (no host), so RynthDefective.Tests checks every rule.
//
// Retail AC keeps this number in its toolbar: the stack slider and the number
// beside the selected item's name (the client's split_amount global, which a
// drag and the vendor's buy list read). RynthCore's "Hide retail toolbar"
// hides it with the rest of the toolbar, and the plugin API can't read or set
// it (API 92), so the box keeps a number of its own and acts through the
// engine's calls: SplitStackInternal, GiveObjectTo and VendorBuy.
//
// The counts:
// split takes 1 .. stack-1 (one always stays: the whole stack is a move);
// "max" is stack-1, "half" is half the stack.
// give hands over 1 .. the whole stack; "max" is the whole stack.
// buy asks for exactly the number; "max" is the most the vendor has, you
// can pay for, and your packs and burden take (VendorQuote.MaxBuy).
// box a typed number stays as typed (1 .. MaxAmount); "max" and "half"
// are of what is selected: the whole stack, or the most you can buy.
// ============================================================================
using System;
using System.Globalization;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Model;
internal enum QtyWord { Number, Max, Half }
/// <summary>A quantity as typed: a number, "max" or "half".</summary>
internal readonly record struct QtyAmount(QtyWord Word, int Number = 0)
{
public static QtyAmount Of(int n) => new(QtyWord.Number, n);
public static readonly QtyAmount Max = new(QtyWord.Max);
public static readonly QtyAmount Half = new(QtyWord.Half);
public override string ToString() => Word switch
{
QtyWord.Max => "max",
QtyWord.Half => "half",
_ => Number.ToString(CultureInfo.InvariantCulture),
};
}
internal static class QuantityRules
{
/// <summary>The most one request carries: the engine's vendor limit (an ItemProfile packs 24 bits).</summary>
public const int MaxAmount = 0x7FFFFF;
public const string Usage = "a number (25, 1,000), max or half";
/// <summary>"25", "1,000", "max" / "all", "half" / "1/2". False with the reason and the usage.</summary>
public static bool TryParse(string? text, out QtyAmount amount, out string why)
{
amount = default;
why = string.Empty;
string t = (text ?? string.Empty).Trim();
switch (t.ToLowerInvariant())
{
case "max": case "all": case "most":
amount = QtyAmount.Max;
return true;
case "half": case "1/2":
amount = QtyAmount.Half;
return true;
}
string digits = t.Replace(",", "", StringComparison.Ordinal).Replace("_", "", StringComparison.Ordinal);
if (digits.Length > 0 && (char.IsDigit(digits[0]) || digits[0] == '-' || digits[0] == '+')
&& long.TryParse(digits, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out long n))
{
if (n < 1) { why = $"The quantity is at least 1 (not {t})."; return false; }
if (n > MaxAmount) { why = $"{t} is more than one request can carry (at most {MaxAmount.ToString("N0", CultureInfo.InvariantCulture)})."; return false; }
amount = QtyAmount.Of((int)n);
return true;
}
why = t.Length == 0 ? $"How many? {Usage}." : $"'{t}' isn't a quantity: {Usage}.";
return false;
}
/// <summary>Whether a word reads as a quantity (a number of any size, or max / half), so "25 into Sack" splits off the 25.</summary>
public static bool LooksLikeAmount(string word)
{
string w = word.Trim().ToLowerInvariant();
if (w is "max" or "all" or "most" or "half" or "1/2") return true;
return w.Length > 0 && (char.IsDigit(w[0]) || ((w[0] == '-' || w[0] == '+') && w.Length > 1 && char.IsDigit(w[1])));
}
/// <summary>
/// The arguments of split / give / buy: an optional quantity first, then the rest ("into Sack", an
/// item name). False only when the first word reads as a quantity and is a wrong one ("0", "-3").
/// </summary>
public static bool TryParseLeading(string? args, out QtyAmount? amount, out string rest, out string why)
{
amount = null;
why = string.Empty;
string a = (args ?? string.Empty).Trim();
int sp = a.IndexOf(' ');
string first = sp < 0 ? a : a[..sp];
rest = sp < 0 ? string.Empty : a[(sp + 1)..].Trim();
if (first.Length == 0 || !LooksLikeAmount(first))
{
rest = a;
return true;
}
if (!TryParse(first, out QtyAmount q, out why)) return false;
amount = q;
return true;
}
/// <summary><paramref name="n"/> within 1 .. <paramref name="max"/> (1 when max is below 1).</summary>
public static int Clamp(int n, int max) => max < 1 ? 1 : Math.Clamp(n, 1, max);
/// <summary>Half of <paramref name="of"/>, at least 1.</summary>
public static int HalfOf(int of) => Math.Max(1, of / 2);
/// <summary>How many a split takes from a stack of <paramref name="stack"/>: at least one stays; 0 = not a stack.</summary>
public static int SplitCount(int n, int stack) => stack < 2 ? 0 : Clamp(n, stack - 1);
/// <summary>How many a give hands over: up to the whole stack; 0 = nothing there.</summary>
public static int GiveCount(int n, int stack) => stack < 1 ? 0 : Clamp(n, stack);
/// <summary>A split's count from what was typed (or the box's number): "max" stack-1, "half" half the stack.</summary>
public static int ForSplit(QtyAmount a, int stack) => stack < 2 ? 0 : a.Word switch
{
QtyWord.Max => stack - 1,
QtyWord.Half => SplitCount(HalfOf(stack), stack),
_ => SplitCount(a.Number, stack),
};
/// <summary>A give's count: "max" the whole stack, "half" half of it.</summary>
public static int ForGive(QtyAmount a, int stack) => stack < 1 ? 0 : a.Word switch
{
QtyWord.Max => stack,
QtyWord.Half => HalfOf(stack),
_ => GiveCount(a.Number, stack),
};
/// <summary>
/// The box's number after /rdef qty or a button: a typed number as typed (1 .. MaxAmount); "max"
/// and "half" of <paramref name="max"/> (the whole stack, or the most you can buy). 0 when max or
/// half has nothing to be of.
/// </summary>
public static int ForBox(QtyAmount a, int max) => a.Word switch
{
QtyWord.Max => max >= 1 ? Math.Min(max, MaxAmount) : 0,
QtyWord.Half => max >= 1 ? HalfOf(Math.Min(max, MaxAmount)) : 0,
_ => Math.Clamp(a.Number, 1, MaxAmount),
};
/// <summary>A buy's count: exactly the number typed (VendorQuote.Refusal says when it can't go); "max" the most you can buy.</summary>
public static int ForBuy(QtyAmount a, int maxBuy) => a.Word switch
{
QtyWord.Max => Math.Max(0, maxBuy),
QtyWord.Half => maxBuy >= 1 ? HalfOf(maxBuy) : 0,
_ => a.Number,
};
public static string N(long n) => n.ToString("N0", CultureInfo.InvariantCulture);
}
/// <summary>
/// One vendor item and what the player has: the box's price, its "max" and why a buy can't go. The
/// rules are ACE's, as the engine's VendorTrade.EstimateBuy applies them (the engine checks again
/// before it sends): a stackable item comes in stacks of MaxStack, each priced on its own
/// (max(1, ceil(value x rate - 0.1)), promissory notes at 1.15), anything else one per slot; a
/// limited listing (usually what another player sold, handed over whole) costs at least the whole
/// listing. Unknown funds, slots or burden (-1) aren't held against the buy.
/// </summary>
internal sealed record VendorQuote
{
public const uint ItemTypePromissoryNote = 0x00040000;
public string Name { get; init; } = string.Empty;
public uint ItemType { get; init; }
public int UnitValue { get; init; }
/// <summary>What one costs at this vendor (the engine's server-rounded figure; shown, not summed).</summary>
public int UnitPrice { get; init; }
public int ListingValue { get; init; }
public int UnitBurden { get; init; }
public int ListingBurden { get; init; }
/// <summary>The largest stack (above 0 = stackable, ACE's rule).</summary>
public int MaxStack { get; init; }
public bool Unlimited { get; init; }
/// <summary>How many the vendor has (a limited listing).</summary>
public int Stock { get; init; }
public float SellRate { get; init; } = 1f;
public bool NeedsContainerSlot { get; init; }
public string Currency { get; init; } = "pyreals";
/// <summary>Pyreals (or the vendor's own currency) you have; -1 = unknown.</summary>
public long Funds { get; init; } = -1;
public int FreeItemSlots { get; init; } = -1;
public int FreeContainerSlots { get; init; } = -1;
public long FreeBurden { get; init; } = -1;
public bool Stackable => MaxStack > 0;
/// <summary>From the engine's vendor snapshot (API v67) and what the player has.</summary>
public static VendorQuote From(VendorInfo info, VendorItem item, int freeItemSlots, int freeContainerSlots, long freeBurden)
{
int stack = Math.Max(1, item.StackSize);
bool alt = info.UsesAltCurrency;
return new VendorQuote
{
Name = item.Name,
ItemType = item.ItemType,
UnitValue = item.UnitValue,
UnitPrice = item.UnitPrice,
ListingValue = item.Value,
UnitBurden = stack > 1 ? item.Burden / stack : item.Burden,
ListingBurden = item.Burden,
MaxStack = item.MaxStackSize,
Unlimited = item.Unlimited || item.Amount < 0,
Stock = Math.Max(0, item.Amount),
SellRate = info.SellRate,
NeedsContainerSlot = item.NeedsContainerSlot,
Currency = alt ? (info.AltCurrencyName.Length > 0 ? info.AltCurrencyName : "the vendor's currency") : "pyreals",
Funds = alt ? info.AltCurrencyHave : info.PlayerCoins,
FreeItemSlots = freeItemSlots,
FreeContainerSlots = freeContainerSlots,
FreeBurden = freeBurden,
};
}
/// <summary>What the player pays for one created stack worth <paramref name="stackValue"/> (ACE Vendor.GetSellCost).</summary>
public long PaysForStack(long stackValue)
{
float rate = ItemType == ItemTypePromissoryNote ? 1.15f : SellRate;
float product = rate * stackValue;
return Math.Max(1L, (long)Math.Ceiling(product - 0.1));
}
/// <summary>Cost, pack slots and burden of buying <paramref name="n"/>.</summary>
public void Estimate(int n, out long cost, out long slots, out long burden)
{
long unitValue = Math.Max(0, UnitValue), unitBurden = Math.Max(0, UnitBurden);
if (n < 1) { cost = slots = burden = 0; return; }
if (Stackable)
{
long max = MaxStack, full = n / max, rem = n % max;
cost = full * PaysForStack(unitValue * max) + (rem > 0 ? PaysForStack(unitValue * rem) : 0);
slots = full + (rem > 0 ? 1 : 0);
}
else
{
cost = n * PaysForStack(unitValue);
slots = n;
}
burden = n * unitBurden;
if (!Unlimited)
{
cost = Math.Max(cost, PaysForStack(Math.Max(0, ListingValue)));
slots = Math.Max(slots, 1);
burden = Math.Max(burden, Math.Max(0, ListingBurden));
}
}
public long Cost(int n)
{
Estimate(n, out long cost, out _, out _);
return cost;
}
private int FreeSlots => NeedsContainerSlot ? FreeContainerSlots : FreeItemSlots;
/// <summary>Money, room and burden allow <paramref name="n"/> (the vendor's stock aside).</summary>
private bool Fits(int n)
{
Estimate(n, out long cost, out long slots, out long burden);
if (Funds >= 0 && cost > Funds) return false;
if (FreeSlots >= 0 && slots > FreeSlots) return false;
if (FreeBurden >= 0 && burden > FreeBurden) return false;
return true;
}
/// <summary>
/// The most you can buy now: what the vendor has, you can pay for, and your packs and burden take
/// (cost, slots and burden only grow with the count, so a halving search finds it). With nothing
/// known to limit an unlimited item, one full stack (one, for an item that doesn't stack). 0 = not even one.
/// </summary>
public int MaxBuy()
{
int cap = Unlimited ? QuantityRules.MaxAmount : Math.Min(Stock, QuantityRules.MaxAmount);
if (Unlimited && Funds < 0 && FreeSlots < 0 && FreeBurden < 0) cap = Stackable ? Math.Max(1, MaxStack) : 1;
if (cap < 1 || !Fits(1)) return 0;
int lo = 1, hi = cap;
while (lo < hi)
{
int mid = lo + (hi - lo + 1) / 2;
if (Fits(mid)) lo = mid; else hi = mid - 1;
}
return lo;
}
/// <summary>Why buying <paramref name="n"/> can't go, or null when it can (as far as the plugin can tell).</summary>
public string? Refusal(int n)
{
if (n < 1) return "The quantity is at least 1.";
if (n > QuantityRules.MaxAmount) return $"{QuantityRules.N(n)} is more than one buy can carry (at most {QuantityRules.N(QuantityRules.MaxAmount)}).";
if (!Unlimited && n > Stock)
return Stock < 1 ? $"The vendor has no {Name} left." : $"The vendor has only {QuantityRules.N(Stock)} {Name}.";
Estimate(n, out long cost, out long slots, out long burden);
string what = $"{QuantityRules.N(n)} {Name}";
if (Funds >= 0 && cost > Funds)
return $"Not enough {Currency}: {what} cost {QuantityRules.N(cost)}, you have {QuantityRules.N(Funds)}{CanBuy()}.";
int free = FreeSlots;
if (free >= 0 && slots > free)
{
if (NeedsContainerSlot)
return free == 0 ? $"No room for another pack: {what} need a container slot of their own."
: $"Not enough container slots: {what} need {QuantityRules.N(slots)}, you have {free}{CanBuy()}.";
return free == 0 ? "The pack is full: no free slot for " + what + "."
: $"Not enough room in your packs: {what} need {QuantityRules.N(slots)} free slots, you have {free}{CanBuy()}.";
}
if (FreeBurden >= 0 && burden > FreeBurden)
return $"Too heavy: {what} weigh {QuantityRules.N(burden)} burden, you can carry {QuantityRules.N(FreeBurden)} more{CanBuy()}.";
return null;
}
private string CanBuy()
{
int max = MaxBuy();
return max >= 1 ? $" (you can buy {QuantityRules.N(max)})" : string.Empty;
}
/// <summary>The price line under the Buy button: "300 pyreals · you have 1,250".</summary>
public string PriceLine(int n)
{
string cost = n >= 1 ? QuantityRules.N(Cost(n)) + " " + Currency : "-";
return Funds >= 0 ? $"{cost} · you have {QuantityRules.N(Funds)}" : cost;
}
}
/// <summary>What the quantity box's actions say (chat and the Selection window). Pure.</summary>
internal static class QtyReplies
{
public const string NothingSelected = "Nothing is selected. Select a stack in your pack (or an item in a vendor's list) first.";
public const string Busy = "Wait a moment: the last split, give or buy is still waiting for the server.";
public const string NoSplitApi = "This RynthCore can't split stacks for a plugin.";
public const string NoGiveApi = "This RynthCore can't give items for a plugin (it needs plugin API v62).";
public const string NoTradeApi = "This RynthCore can't trade with vendors for a plugin (it needs plugin API v67).";
public const string NoVendor = "No vendor is open: talk to a vendor first.";
public const string NoVendorItem = "Select the item in the vendor's list first (or type its name: /rdef buy 25 Mana Scarab).";
public const string VendorUnreadable = "RynthCore can't trade with this vendor (its list couldn't be read): use the game's own Buy.";
public const string VendorBusy = "A trade with the vendor is still going: wait a moment.";
public const string NoGiveTarget = "Who to? Select the player or NPC first, then the stack: Give goes to the last one you selected.";
public const string MaxNeedsSelection = "max and half are of what is selected: select a stack or a vendor's item first. Usage: /rdef qty <number|max|half>";
public static string NotAStack(string name) => $"That's not a stack: {name} is a single item.";
public static string Wielded(string name) => $"{name} is wielded: take it off first.";
public static string NotReachable(string name) => $"{name} isn't in your packs or in the container you have open.";
public static string NotCarried(string name) => $"{name} isn't in your packs: pick it up first.";
public static string VendorsItem(string name) => $"{name} is the vendor's: Buy takes it (/rdef buy N).";
public static string PackFull(string where) =>
$"{Cap(where)} is full. Pick another pack for the split (the 'into' button, or /rdef split 25 into <pack>).";
public static string NoSuchPack(string typed, string packs) => $"No pack called '{typed}'. Your packs: {packs}.";
public static string NotSent(string what) => $"The {what} couldn't be sent (the game isn't ready for it): nothing changed.";
public static string Splitting(int n, string name, string into) => $"Split {QuantityRules.N(n)} {name} into {into}.";
public static string Gave(int n, string name, string to) => $"Gave {QuantityRules.N(n)} {name} to {to}.";
public static string Bought(int n, string name, long cost, string currency) =>
cost > 0 ? $"Bought {QuantityRules.N(n)} {name} for {QuantityRules.N(cost)} {currency}." : $"Bought {QuantityRules.N(n)} {name}.";
public static string Refused(string what, uint error) =>
error != 0 ? $"The server refused the {what} (error 0x{error:X4}): nothing changed." : $"The server refused the {what}: nothing changed.";
public static string NoAnswer(string what) => $"No answer from the server for the {what}: check your pack before trying again.";
/// <summary>
/// The engine's refusal of a buy (VendorTradeStatus.Message, Compatibility/VendorTrade.cs) in the
/// player's words. Unknown messages are passed on as they are.
/// </summary>
public static string VendorRefusal(string? message)
{
string m = (message ?? string.Empty).Trim();
if (m.Length == 0) return "The vendor didn't sell it.";
if (m.StartsWith("costs ", StringComparison.Ordinal))
{
// "costs 300 pyreals, you have 200" / "costs 3 Ancient Mattekar Claws, you have 1"
int comma = m.IndexOf(", you have ", StringComparison.Ordinal);
string head = comma > 0 ? m[6..comma] : m[6..];
int sp = head.IndexOf(' ');
string currency = sp > 0 ? head[(sp + 1)..] : "pyreals";
return $"Not enough {currency}: it {m}.";
}
if (m.StartsWith("needs ", StringComparison.Ordinal) && m.Contains("free pack slots", StringComparison.Ordinal))
return m.EndsWith("you have 0", StringComparison.Ordinal) ? $"The pack is full: it {m}." : $"Not enough room in your packs: it {m}.";
if (m.StartsWith("needs ", StringComparison.Ordinal) && m.Contains("container slots", StringComparison.Ordinal))
return $"No room for another pack: it {m}.";
if (m.StartsWith("adds ", StringComparison.Ordinal) && m.Contains("burden", StringComparison.Ordinal))
return $"Too heavy: it {m}.";
if (m.Contains("vendor only has", StringComparison.Ordinal) || m.StartsWith("bad amount", StringComparison.Ordinal))
return "The vendor doesn't have that many.";
if (m.Contains("no vendor open", StringComparison.Ordinal) || m.Contains("vendor window is closed", StringComparison.Ordinal)
|| m.Contains("vendor closed", StringComparison.Ordinal) || m.Contains("is not the open vendor", StringComparison.Ordinal))
return "The vendor is closed: talk to it again.";
if (m.Contains("not on this vendor's list", StringComparison.Ordinal) || m.Contains("no longer on the vendor's list", StringComparison.Ordinal))
return "The vendor doesn't sell that any more.";
if (m.Contains("requests already waiting", StringComparison.Ordinal))
return VendorBusy;
if (m.Contains("could not read your", StringComparison.Ordinal) || m.Contains("could not count your", StringComparison.Ordinal))
return $"RynthCore couldn't count your money ({m}): try again in a moment.";
return $"The vendor didn't sell it: {m}.";
}
private static string Cap(string s) => s.Length == 0 ? s : char.ToUpperInvariant(s[0]) + s[1..];
}

View file

@ -0,0 +1,252 @@
// ============================================================================
// RynthDefective - Quantity/QtyWorld.cs
// What the quantity box (QuantityController) needs from the game, as an
// interface so the tests drive it offline (RynthDefective.Tests), and the
// engine host's side of it. Plugin pump thread only.
//
// Every call is behind its Has* check: splitting (SplitStackInternal, as old
// as the plugin API), giving with a count (GiveObjectTo, v62), vendor trading
// (v67), the server's refusals (v70) and the pack column's order (v80) are
// each used only where the engine has them. Nothing here needs more than the
// live release's API 92, and the Selection window itself needs v90.
// ============================================================================
using System;
using System.Collections.Generic;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Quantity;
internal enum QtyPackKind { Main, Side, Open }
/// <summary>A place a split can go: the main pack, a side pack, or the container you have open.</summary>
internal readonly record struct QtyPack(uint Id, string Name, int Capacity, int Count, QtyPackKind Kind)
{
/// <summary>Free item slots; -1 = unknown (the server decides).</summary>
public int Free => Capacity > 0 && Count >= 0 ? Math.Max(0, Capacity - Count) : -1;
/// <summary>In a sentence: "the main pack", "Sack", "Chest".</summary>
public string Where => Kind == QtyPackKind.Main ? "the main pack" : Name;
/// <summary>On a button: "Main pack", "Sack", "Chest (open)".</summary>
public string Label => Kind switch
{
QtyPackKind.Main => "Main pack",
QtyPackKind.Open => Name + " (open)",
_ => Name,
};
}
internal interface IQtyWorld
{
long NowMs { get; }
uint PlayerId { get; }
uint SelectedId { get; }
/// <summary>AC's selection before this one (0 = none or unknown).</summary>
uint PreviousSelectedId { get; }
/// <summary>The chest or corpse you have open (0 = none).</summary>
uint OpenContainerId { get; }
bool TryGetName(uint id, out string name);
/// <summary>The client knows the object.</summary>
bool Exists(uint id);
/// <summary>Someone to give to: a player or an NPC (a creature that isn't a monster).</summary>
bool CanReceive(uint id);
/// <summary>Where it is: its container and its wielder (0 = none). False = the client doesn't know it.</summary>
bool TryGetOwner(uint id, out uint container, out uint wielder);
/// <summary>Its stack size; 0 = unknown.</summary>
int StackOf(uint id);
/// <summary>The main pack first, then the side packs (the pack column's order), then the open container.</summary>
IReadOnlyList<QtyPack> Packs();
bool CanSplit { get; }
/// <summary>Splits <paramref name="n"/> off the stack into <paramref name="into"/> (a new stack there).</summary>
bool Split(uint id, uint into, int n);
bool CanGive { get; }
/// <summary>Gives <paramref name="n"/> of it (0 = the whole of it) to a player or NPC.</summary>
bool Give(uint id, uint to, int n);
/// <summary>Counts the server's refusals (0 when the engine can't say): note it before a send, compare after.</summary>
int RefusalSeq { get; }
bool LastRefusal(out uint error, out uint eventType, out uint objectId);
bool CanTrade { get; }
/// <summary>The vendor open now (false = none).</summary>
bool TryGetVendor(out VendorInfo info);
IReadOnlyList<VendorItem> VendorItems();
/// <summary>Asks the engine to buy; the request id, or 0 when it refused at once (the trade status says why).</summary>
uint Buy(uint vendorId, uint itemId, int n);
bool TryGetTradeStatus(out VendorTradeStatus status);
/// <summary>Free container slots (for packs and foci bought); -1 = unknown.</summary>
int FreeContainerSlots();
/// <summary>Burden you can still carry (three times your capacity, as ACE); -1 = unknown.</summary>
long FreeBurden();
}
/// <summary>The engine host's side (RynthCoreHost). Plugin pump thread only.</summary>
internal sealed class HostQtyWorld : IQtyWorld
{
// STypeInt
private const uint EncumbranceVal = 5, ItemsCapacity = 6, ContainersCapacity = 7, StackSize = 12, EncumbranceCapacity = 96;
private const uint ItemTypeCreature = 0x10, ItemTypeContainer = 0x200;
// PublicWeenieDesc bitfield (ObjectDescriptionFlag).
private const uint BitPlayer = 0x8, BitAttackable = 0x10;
private const int MainPackDefault = 102, ContainerSlotsDefault = 7;
private readonly RynthCoreHost _h;
private uint[] _contents = new uint[256];
private uint[] _order = new uint[16];
private uint _vendorId, _vendorGeneration;
private VendorItem[] _vendorItems = Array.Empty<VendorItem>();
public HostQtyWorld(RynthCoreHost host) => _h = host;
public long NowMs => Environment.TickCount64;
public uint PlayerId => _h.HasGetPlayerId ? _h.GetPlayerId() : 0;
public uint SelectedId => _h.HasGetSelectedItemId ? _h.GetSelectedItemId() : 0;
public uint PreviousSelectedId => _h.HasGetPreviousSelectedItemId ? _h.GetPreviousSelectedItemId() : 0;
public uint OpenContainerId => _h.HasGetGroundContainerId ? _h.GetGroundContainerId() : 0;
public bool TryGetName(uint id, out string name)
{
name = string.Empty;
if (id == 0 || !_h.TryGetObjectName(id, out string n) || string.IsNullOrWhiteSpace(n)) return false;
name = n.Trim();
return true;
}
public bool Exists(uint id) => id != 0 && _h.TryGetItemType(id, out _);
/// <summary>
/// A creature that is a player (description bit Player 0x8) or isn't attackable (Attackable 0x10: a
/// monster): a monster selected in a fight never becomes the give target. Without the description
/// bits (an older engine) any creature; the server refuses a give it doesn't take.
/// </summary>
public bool CanReceive(uint id)
{
if (id == 0 || !_h.TryGetItemType(id, out uint t) || (t & ItemTypeCreature) == 0) return false;
if (!_h.HasGetObjectBitfield || !_h.TryGetObjectBitfield(id, out uint bits)) return true;
return (bits & BitPlayer) != 0 || (bits & BitAttackable) == 0;
}
public bool TryGetOwner(uint id, out uint container, out uint wielder)
{
container = wielder = 0;
if (id == 0) return false;
if (_h.HasGetObjectOwnershipInfo && _h.TryGetObjectOwnershipInfo(id, out container, out wielder, out _)) return true;
return false;
}
public int StackOf(uint id) => id != 0 && _h.TryGetObjectIntProperty(id, StackSize, out int s) && s > 0 ? s : 0;
private int Int(uint id, uint stype) => _h.TryGetObjectIntProperty(id, stype, out int v) ? v : -1;
public IReadOnlyList<QtyPack> Packs()
{
var packs = new List<QtyPack>(8);
uint player = PlayerId;
if (player == 0) return packs;
int mainCap = Int(player, ItemsCapacity);
packs.Add(new QtyPack(player, "Main pack", mainCap > 0 ? mainCap : MainPackDefault, Count(player), QtyPackKind.Main));
// The side packs, in the pack column's order when the engine knows it (v80), else as the client lists them.
var ids = new List<uint>(8);
if (_h.HasContainerOrder && _h.TryGetContainerOrder(player, true, ref _order, out int ordered) && ordered > 0)
for (int i = 0; i < ordered && i < _order.Length; i++) ids.Add(_order[i]);
else if (_h.HasGetContainerContents)
{
int n = _h.GetContainerContents(player, _contents);
if (n > _contents.Length && n <= 4096) { _contents = new uint[n]; n = _h.GetContainerContents(player, _contents); }
for (int i = 0; i < n && i < _contents.Length; i++) ids.Add(_contents[i]);
}
var names = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (uint id in ids)
{
if (id == 0 || !_h.TryGetItemType(id, out uint type) || (type & ItemTypeContainer) == 0) continue;
int cap = Int(id, ItemsCapacity);
if (cap <= 0) continue; // a focus holds no items
if (TryGetOwner(id, out uint c, out uint w) && (c != player || w != 0)) continue;
string name = TryGetName(id, out string nm) ? nm : "Pack";
names[name] = names.TryGetValue(name, out int seen) ? seen + 1 : 1;
if (names[name] > 1) name += " " + names[name];
packs.Add(new QtyPack(id, name, cap, Count(id), QtyPackKind.Side));
}
uint open = OpenContainerId;
if (open != 0 && open != player && !packs.Exists(p => p.Id == open))
{
string name = TryGetName(open, out string nm) ? nm : "The open container";
packs.Add(new QtyPack(open, name, Int(open, ItemsCapacity), Count(open), QtyPackKind.Open));
}
return packs;
}
private int Count(uint container) => _h.HasGetNumContainedItems ? _h.GetNumContainedItems(container) : -1;
public bool CanSplit => _h.HasSplitStackInternal;
// Slot 0 with a count below the stack: the client's StackableSplitToContainer, as the engine's own
// Inventory panel splits (InventoryModel). The new stack takes a free slot of the target.
public bool Split(uint id, uint into, int n) => CanSplit && n >= 1 && _h.SplitStackInternal(id, into, 0, n);
public bool CanGive => _h.HasGiveObjectTo;
public bool Give(uint id, uint to, int n) => CanGive && _h.GiveObjectTo(id, to, Math.Max(0, n));
public int RefusalSeq => _h.HasGetLastWeenieError && _h.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0;
public bool LastRefusal(out uint error, out uint eventType, out uint objectId)
{
error = eventType = objectId = 0;
return _h.HasGetLastWeenieError && _h.TryGetLastWeenieError(out _, out error, out eventType, out objectId);
}
public bool CanTrade => _h.HasVendorTrade;
public bool TryGetVendor(out VendorInfo info)
{
info = null!;
return CanTrade && _h.TryGetVendorInfo(out info) && info.VendorId != 0;
}
/// <summary>The open vendor's list, read again only when the vendor or its list (Generation) changed.</summary>
public IReadOnlyList<VendorItem> VendorItems()
{
if (!TryGetVendor(out VendorInfo info))
{
_vendorId = 0;
_vendorItems = Array.Empty<VendorItem>();
return _vendorItems;
}
if (info.VendorId != _vendorId || info.Generation != _vendorGeneration || _vendorItems.Length == 0)
{
_vendorItems = _h.GetVendorItems();
_vendorId = info.VendorId;
_vendorGeneration = info.Generation;
}
return _vendorItems;
}
public uint Buy(uint vendorId, uint itemId, int n) => CanTrade ? _h.VendorBuy(itemId, n, vendorId) : 0;
public bool TryGetTradeStatus(out VendorTradeStatus status)
{
status = null!;
return CanTrade && _h.TryGetVendorTradeStatus(out status);
}
public int FreeContainerSlots()
{
uint player = PlayerId;
if (player == 0 || !_h.HasGetNumContainedContainers) return -1;
int n = _h.GetNumContainedContainers(player);
if (n < 0) return -1;
int cap = Int(player, ContainersCapacity);
return Math.Max(0, (cap > 0 ? cap : ContainerSlotsDefault) - n);
}
public long FreeBurden()
{
uint player = PlayerId;
if (player == 0) return -1;
int carried = Int(player, EncumbranceVal), cap = Int(player, EncumbranceCapacity);
if (carried < 0 || cap <= 0) return -1; // unknown: the engine checks with its own reading
return Math.Max(0, 3L * cap - carried);
}
}

View file

@ -0,0 +1,552 @@
// ============================================================================
// RynthDefective - Quantity/QuantityController.cs
// The quantity box (2026-10-30): one number, and what it does to what is
// selected. Asked for by a player: "to select a portion of a stack, or buy
// multiple of an item from a vendor, I need a place to type in the number".
//
// a stack you carry Split N into the main pack, a side pack or the
// (or in the chest you have container you have open; Give N to the player
// open) or NPC you selected last
// an item in a vendor's list Buy N, with the price, your pyreals, the room
// in your packs and your burden checked first
//
// The Selection window shows the box under what is selected (QuantityRow);
// /rdef qty, split, give and buy do the same from chat, hotkeys and metas.
// Nothing here needs the engine's Inventory panel or RynthInventory.
//
// One action at a time. Each one answers once: at once when it can't go
// (why, in the player's words), or when the game answers (the stack got
// smaller, the item left your packs, the vendor's trade finished) or doesn't
// (a refusal from the server, or no answer in time).
//
// Threads: everything on the plugin pump, except Value and Into, which the
// Selection window sets from the render thread (single ints).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Threading;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Quantity;
internal enum QtyMode { None, Single, Stack, Vendor }
/// <summary>Where the selected item is, for a split or a give.</summary>
internal enum QtyWhere { Unknown, Carried, Wielded, Open, Elsewhere }
/// <summary>What is selected, as the box sees it.</summary>
internal sealed record QtySubject(QtyMode Mode, uint Id, string Name, int Stack, QtyWhere Where)
{
public static readonly QtySubject Nothing = new(QtyMode.None, 0, string.Empty, 0, QtyWhere.Unknown);
/// <summary>A vendor's item: its price and what you have.</summary>
public VendorQuote? Quote { get; init; }
public uint VendorId { get; init; }
/// <summary>The most you can buy now (vendor items).</summary>
public int MaxBuy { get; init; }
/// <summary>What the box's "max" is of: the whole stack, or the most you can buy; 0 = nothing.</summary>
public int BoxMax => Mode switch
{
QtyMode.Stack => Stack,
QtyMode.Vendor => MaxBuy,
_ => 0,
};
}
/// <summary>The box as the Selection window draws it (built on the tick).</summary>
internal sealed record QuantityView(QtySubject Subject, QtyPack[] Targets, int TargetIndex, uint GiveTo, string GiveName,
bool Busy, bool CanSplit, bool CanGive)
{
public QtyPack? Target => TargetIndex >= 0 && TargetIndex < Targets.Length ? Targets[TargetIndex] : null;
}
/// <summary>The last thing the box did, for the Selection window's line.</summary>
internal sealed record QtyStatus(string Text, bool Ok, long AtMs);
internal sealed class QuantityController
{
/// <summary>How long a split, a give (the server may walk you to the NPC first) and a buy wait for the game.</summary>
public const long SplitAnswerMs = 6000, GiveAnswerMs = 20_000, BuyAnswerMs = 15_000;
/// <summary>A refusal that doesn't name the item is ours if nothing changed this long after it.</summary>
public const long RefusalGraceMs = 1500;
/// <summary>The last player or NPC selected stays the give target this long.</summary>
public const long GiveTargetMs = 10 * 60 * 1000;
public const long StatusShownMs = 8000;
/// <summary>InventoryServerSaveFailed: the server refused a move, split or give of this item.</summary>
private const uint InventorySaveFailed = 0x00A0;
private int _value = 1;
private uint _into;
private volatile QtyStatus? _status;
private uint _lastSelection, _giveId;
private string _giveName = string.Empty;
private long _giveAtMs;
private Pending? _pending;
/// <summary>Every answer (ok, text): the plugin writes it in chat.</summary>
public Action<bool, string> Report = (_, _) => { };
/// <summary>The box's number (1 .. MaxAmount). Any thread.</summary>
public int Value
{
get => Volatile.Read(ref _value);
set => Volatile.Write(ref _value, Math.Clamp(value, 1, QuantityRules.MaxAmount));
}
/// <summary>The pack a split goes into (its id); 0 or a pack that's gone = the main pack. Any thread.</summary>
public uint Into
{
get => Volatile.Read(ref _into);
set => Volatile.Write(ref _into, value);
}
public bool Busy => _pending != null;
/// <summary>The last answer while it is fresh. Any thread.</summary>
public QtyStatus? StatusAt(long nowMs)
{
QtyStatus? s = _status;
return s != null && nowMs - s.AtMs < StatusShownMs ? s : null;
}
public void Reset()
{
_pending = null;
_status = null;
_giveId = _lastSelection = 0;
_giveName = string.Empty;
Into = 0;
}
private void Say(IQtyWorld w, bool ok, string text)
{
_status = new QtyStatus(text, ok, w.NowMs);
Report(ok, text);
}
// ── What is selected ────────────────────────────────────────────────────
public QtySubject Analyze(IQtyWorld w)
{
uint sel = w.SelectedId;
if (sel == 0) return QtySubject.Nothing;
string name = w.TryGetName(sel, out string n) ? n : $"0x{sel:X8}";
if (w.CanTrade && w.TryGetVendor(out VendorInfo info))
{
foreach (VendorItem it in w.VendorItems())
{
if (it.ObjectId != sel) continue;
VendorQuote q = Quote(w, info, it);
return new QtySubject(QtyMode.Vendor, sel, it.Name.Length > 0 ? it.Name : name, Math.Max(1, it.StackSize), QtyWhere.Elsewhere)
{
Quote = q,
VendorId = info.VendorId,
MaxBuy = q.MaxBuy(),
};
}
}
int stack = w.StackOf(sel);
return new QtySubject(stack >= 2 ? QtyMode.Stack : QtyMode.Single, sel, name, Math.Max(1, stack), WhereIs(w, sel));
}
private static QtyWhere WhereIs(IQtyWorld w, uint id)
{
uint player = w.PlayerId;
if (player == 0 || !w.TryGetOwner(id, out uint c, out uint wielder)) return QtyWhere.Unknown;
if (wielder != 0 && wielder == player) return QtyWhere.Wielded;
if (c == player) return QtyWhere.Carried;
if (c != 0 && w.TryGetOwner(c, out uint outer, out uint outerWielder) && outer == player && outerWielder == 0) return QtyWhere.Carried;
if (c != 0 && c == w.OpenContainerId) return QtyWhere.Open;
return QtyWhere.Elsewhere;
}
private static bool Owned(IQtyWorld w, uint id)
{
QtyWhere where = WhereIs(w, id);
return where is QtyWhere.Carried or QtyWhere.Wielded;
}
private static VendorQuote Quote(IQtyWorld w, VendorInfo info, VendorItem item)
{
int free = 0;
foreach (QtyPack p in w.Packs())
{
if (p.Kind == QtyPackKind.Open) continue;
if (p.Free < 0) { free = -1; break; }
free += p.Free;
}
return VendorQuote.From(info, item, free, w.FreeContainerSlots(), w.FreeBurden());
}
/// <summary>
/// The Selection window's box: for a vendor's item, or a stack you carry, wield (it says to take it
/// off) or have in the open container. Not for a stack on the ground or in someone else's hands. Plugin tick.
/// </summary>
public QuantityView? View(IQtyWorld w)
{
QtySubject s = Analyze(w);
if (s.Mode is not (QtyMode.Stack or QtyMode.Vendor)) return null;
if (s.Mode == QtyMode.Stack && s.Where is not (QtyWhere.Carried or QtyWhere.Wielded or QtyWhere.Open)) return null;
QtyPack[] targets = s.Mode == QtyMode.Stack ? new List<QtyPack>(w.Packs()).ToArray() : Array.Empty<QtyPack>();
int index = 0;
uint into = Into;
for (int i = 0; i < targets.Length; i++) if (targets[i].Id == into) { index = i; break; }
TryGiveTarget(w, s.Id, out uint to, out string toName);
return new QuantityView(s, targets, targets.Length == 0 ? -1 : index, to, toName, Busy, w.CanSplit, w.CanGive);
}
// ── The give target: the last player or NPC selected ─────────────────────
/// <summary>Notes a newly selected player or NPC (not you, not a monster) as the give target. Plugin tick, a few times a second.</summary>
public void NoteSelection(IQtyWorld w)
{
uint sel = w.SelectedId;
if (sel == _lastSelection) return;
_lastSelection = sel;
if (sel == 0 || sel == w.PlayerId || !w.CanReceive(sel)) return;
_giveId = sel;
_giveName = w.TryGetName(sel, out string n) ? n : $"0x{sel:X8}";
_giveAtMs = w.NowMs;
}
/// <summary>Who a give goes to: the last player or NPC selected (within GiveTargetMs and still there), else AC's previous selection.</summary>
public bool TryGiveTarget(IQtyWorld w, uint item, out uint to, out string name)
{
uint player = w.PlayerId;
if (_giveId != 0 && _giveId != item && w.NowMs - _giveAtMs < GiveTargetMs && w.Exists(_giveId))
{
to = _giveId;
name = _giveName;
return true;
}
uint prev = w.PreviousSelectedId;
if (prev != 0 && prev != item && prev != player && w.CanReceive(prev))
{
to = prev;
name = w.TryGetName(prev, out string n) ? n : $"0x{prev:X8}";
return true;
}
to = 0;
name = string.Empty;
return false;
}
// ── /rdef qty ───────────────────────────────────────────────────────────
/// <summary>Sets the box (null: says what it is). "max" and "half" are of what is selected.</summary>
public void SetBox(IQtyWorld w, QtyAmount? amount)
{
QtySubject s = Analyze(w);
if (amount is { } a)
{
if (a.Word != QtyWord.Number && s.BoxMax < 1)
{
Say(w, false, s.Mode == QtyMode.Vendor ? s.Quote?.Refusal(1) ?? QtyReplies.MaxNeedsSelection : QtyReplies.MaxNeedsSelection);
return;
}
Value = QuantityRules.ForBox(a, s.BoxMax);
}
Say(w, true, $"Quantity {QuantityRules.N(Value)}{About(s)}.");
}
private string About(QtySubject s) => s.Mode switch
{
QtyMode.Stack => $" (the selected {s.Name}: a stack of {QuantityRules.N(s.Stack)}; a split takes up to {QuantityRules.N(s.Stack - 1)})",
QtyMode.Vendor when s.Quote != null => $" (the vendor's {s.Name}: {s.Quote.PriceLine(Value)}; you can buy {QuantityRules.N(s.MaxBuy)})",
_ => string.Empty,
};
// ── Split ───────────────────────────────────────────────────────────────
/// <summary>
/// Splits the box's number (or <paramref name="amount"/>) off the selected stack into
/// <paramref name="into"/> (a pack's name; empty = the pack chosen in the window, else the main pack).
/// </summary>
public void Split(IQtyWorld w, QtyAmount? amount, string into)
{
if (_pending != null) { Say(w, false, QtyReplies.Busy); return; }
if (!w.CanSplit) { Say(w, false, QtyReplies.NoSplitApi); return; }
QtySubject s = Analyze(w);
string? why = s.Mode switch
{
QtyMode.None => QtyReplies.NothingSelected,
QtyMode.Vendor => QtyReplies.VendorsItem(s.Name),
QtyMode.Single => QtyReplies.NotAStack(s.Name),
_ => s.Where switch
{
QtyWhere.Wielded => QtyReplies.Wielded(s.Name),
QtyWhere.Carried or QtyWhere.Open => null,
_ => QtyReplies.NotReachable(s.Name),
},
};
if (why != null) { Say(w, false, why); return; }
IReadOnlyList<QtyPack> packs = w.Packs();
if (!TryPickTarget(packs, into, out QtyPack target, out why)) { Say(w, false, why); return; }
if (target.Free == 0) { Say(w, false, QtyReplies.PackFull(target.Where)); return; }
int n = QuantityRules.ForSplit(amount ?? QtyAmount.Of(Value), s.Stack);
var p = new Pending
{
Kind = PendingKind.Split, Id = s.Id, Name = s.Name, N = n, Where = target.Where,
StackBefore = s.Stack, RefusalSeq = w.RefusalSeq, AtMs = w.NowMs,
};
if (!w.Split(s.Id, target.Id, n)) { Say(w, false, QtyReplies.NotSent("split")); return; }
_pending = p;
}
/// <summary>The split's pack: the one named, else the one chosen in the window (if it's still there), else the main pack.</summary>
internal bool TryPickTarget(IReadOnlyList<QtyPack> packs, string typed, out QtyPack target, out string why)
{
target = default;
why = string.Empty;
if (packs.Count == 0) { why = "Your packs can't be read yet: try again in a moment."; return false; }
string t = (typed ?? string.Empty).Trim();
if (t.Length == 0)
{
uint into = Into;
target = packs[0];
foreach (QtyPack p in packs) if (p.Id == into) { target = p; break; }
return true;
}
string low = t.ToLowerInvariant();
if (low is "main" or "main pack" or "mainpack" or "pack" or "me" or "inventory")
{
target = packs[0];
return true;
}
if (low is "open" or "chest" or "container" or "the chest" or "the open container")
{
foreach (QtyPack p in packs) if (p.Kind == QtyPackKind.Open) { target = p; return true; }
why = "No chest or other container is open: open it first, or split into one of your packs.";
return false;
}
// The pack's own name: the whole of it, then its start, then any part of it.
foreach (QtyPack p in packs) if (p.Name.Equals(t, StringComparison.OrdinalIgnoreCase) || p.Label.Equals(t, StringComparison.OrdinalIgnoreCase)) { target = p; return true; }
foreach (QtyPack p in packs) if (p.Name.StartsWith(t, StringComparison.OrdinalIgnoreCase)) { target = p; return true; }
foreach (QtyPack p in packs) if (p.Name.Contains(t, StringComparison.OrdinalIgnoreCase)) { target = p; return true; }
var names = new List<string>(packs.Count);
foreach (QtyPack p in packs) names.Add(p.Label);
why = QtyReplies.NoSuchPack(t, string.Join(", ", names));
return false;
}
// ── Give ────────────────────────────────────────────────────────────────
/// <summary>Gives the box's number (or <paramref name="amount"/>) of the selected stack to the last player or NPC selected.</summary>
public void Give(IQtyWorld w, QtyAmount? amount)
{
if (_pending != null) { Say(w, false, QtyReplies.Busy); return; }
if (!w.CanGive) { Say(w, false, QtyReplies.NoGiveApi); return; }
QtySubject s = Analyze(w);
string? why = s.Mode switch
{
QtyMode.None => QtyReplies.NothingSelected,
QtyMode.Vendor => QtyReplies.VendorsItem(s.Name),
_ => s.Where switch
{
QtyWhere.Wielded => QtyReplies.Wielded(s.Name),
QtyWhere.Carried => null,
_ => QtyReplies.NotCarried(s.Name),
},
};
if (why != null) { Say(w, false, why); return; }
if (!TryGiveTarget(w, s.Id, out uint to, out string toName)) { Say(w, false, QtyReplies.NoGiveTarget); return; }
int n = QuantityRules.ForGive(amount ?? QtyAmount.Of(Value), s.Stack);
var p = new Pending
{
Kind = PendingKind.Give, Id = s.Id, Name = s.Name, N = n, Where = toName,
StackBefore = s.Stack, RefusalSeq = w.RefusalSeq, AtMs = w.NowMs,
};
// 0 = the whole of it (the give the client sends for a drag of the whole stack).
if (!w.Give(s.Id, to, n >= s.Stack ? 0 : n)) { Say(w, false, QtyReplies.NotSent("give")); return; }
_pending = p;
}
// ── Buy ─────────────────────────────────────────────────────────────────
/// <summary>Buys the box's number (or <paramref name="amount"/>) of the selected vendor item, or the one named.</summary>
public void Buy(IQtyWorld w, QtyAmount? amount, string itemName)
{
if (_pending != null) { Say(w, false, QtyReplies.Busy); return; }
if (!w.CanTrade) { Say(w, false, QtyReplies.NoTradeApi); return; }
if (!w.TryGetVendor(out VendorInfo info)) { Say(w, false, QtyReplies.NoVendor); return; }
if (!info.TradingAvailable) { Say(w, false, QtyReplies.VendorUnreadable); return; }
if (info.TradeInFlight) { Say(w, false, QtyReplies.VendorBusy); return; }
IReadOnlyList<VendorItem> items = w.VendorItems();
VendorItem? item;
string name = (itemName ?? string.Empty).Trim();
if (name.Length > 0)
{
item = FindVendorItem(items, name, out string? why);
if (item == null) { Say(w, false, why!); return; }
}
else
{
item = null;
uint sel = w.SelectedId;
foreach (VendorItem it in items) if (it.ObjectId == sel && sel != 0) { item = it; break; }
if (item == null) { Say(w, false, QtyReplies.NoVendorItem); return; }
}
VendorQuote q = Quote(w, info, item);
int n = amount is { } a ? QuantityRules.ForBuy(a, q.MaxBuy()) : Value;
if (n < 1) { Say(w, false, q.Refusal(1) ?? $"You can't buy any {item.Name} now."); return; }
string? refusal = q.Refusal(n);
if (refusal != null) { Say(w, false, refusal); return; }
uint request = w.Buy(info.VendorId, item.ObjectId, n);
if (request == 0)
{
Say(w, false, QtyReplies.VendorRefusal(w.TryGetTradeStatus(out VendorTradeStatus st) ? st.Message : null));
return;
}
_pending = new Pending
{
Kind = PendingKind.Buy, Id = item.ObjectId, Name = item.Name, N = n, RequestId = request,
Cost = q.Cost(n), Currency = q.Currency, AtMs = w.NowMs,
};
}
/// <summary>A vendor's item by name: the whole name, else the one whose name starts so, else the one that holds it. Several = ask for more.</summary>
internal static VendorItem? FindVendorItem(IReadOnlyList<VendorItem> items, string name, out string? why)
{
why = null;
foreach (VendorItem it in items) if (it.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) return it;
foreach (bool starts in new[] { true, false })
{
VendorItem? found = null;
var names = new List<string>();
foreach (VendorItem it in items)
{
bool match = starts ? it.Name.StartsWith(name, StringComparison.OrdinalIgnoreCase) : it.Name.Contains(name, StringComparison.OrdinalIgnoreCase);
if (!match) continue;
if (!names.Exists(x => x.Equals(it.Name, StringComparison.OrdinalIgnoreCase))) names.Add(it.Name);
found ??= it;
}
if (names.Count == 1) return found;
if (names.Count > 1)
{
why = $"'{name}' could be {string.Join(", ", names.GetRange(0, Math.Min(5, names.Count)))}{(names.Count > 5 ? ", ..." : "")}: type more of the name.";
return null;
}
}
why = $"The vendor doesn't sell '{name}'.";
return null;
}
// ── Waiting for the game ────────────────────────────────────────────────
private enum PendingKind { Split, Give, Buy }
private sealed class Pending
{
public PendingKind Kind;
public uint Id;
public string Name = string.Empty;
public int N;
/// <summary>Split: the pack ("the main pack"); give: who to.</summary>
public string Where = string.Empty;
public int StackBefore;
public int RefusalSeq;
public long AtMs;
public long RefusedAtMs;
public uint Error;
public bool RefusalNamesItem;
public uint RequestId;
public long Cost;
public string Currency = string.Empty;
}
/// <summary>Plugin tick: the give target, and the answer to the action in flight.</summary>
public void Tick(IQtyWorld w)
{
NoteSelection(w);
Pending? p = _pending;
if (p == null) return;
long now = w.NowMs;
switch (p.Kind)
{
case PendingKind.Split:
{
int stack = w.StackOf(p.Id);
if (stack > 0 && stack < p.StackBefore) Finish(w, true, QtyReplies.Splitting(p.N, p.Name, p.Where));
else if (RefusedNow(w, p, now)) Finish(w, false, QtyReplies.Refused("split", p.Error));
else if (now - p.AtMs >= SplitAnswerMs) Finish(w, false, QtyReplies.NoAnswer("split"));
break;
}
case PendingKind.Give:
{
int stack = w.StackOf(p.Id);
bool left = !w.Exists(p.Id) || !Owned(w, p.Id);
if (left || (stack > 0 && stack < p.StackBefore)) Finish(w, true, QtyReplies.Gave(p.N, p.Name, p.Where));
else if (RefusedNow(w, p, now)) Finish(w, false, QtyReplies.Refused("give", p.Error));
else if (now - p.AtMs >= GiveAnswerMs) Finish(w, false, QtyReplies.NoAnswer("give"));
break;
}
case PendingKind.Buy:
WatchBuy(w, p, now);
break;
}
}
private void WatchBuy(IQtyWorld w, Pending p, long now)
{
if (w.TryGetTradeStatus(out VendorTradeStatus s))
{
if (s.RequestId == p.RequestId)
{
if (s.State == VendorTradeState.Refused) { Finish(w, false, QtyReplies.VendorRefusal(s.Message)); return; }
if (s.State == VendorTradeState.Done)
{
if (s.Result == VendorTradeResult.Accepted)
Finish(w, true, QtyReplies.Bought(p.N, p.Name, s.Estimate > 0 ? s.Estimate : p.Cost, p.Currency));
else if (s.Result == VendorTradeResult.TimedOut)
Finish(w, false, $"No answer from the vendor about {QuantityRules.N(p.N)} {p.Name}: check your pack and {p.Currency} before trying again.");
else
Finish(w, false, $"The vendor didn't sell {QuantityRules.N(p.N)} {p.Name}: the server said no (money, room, or too busy).");
return;
}
}
else if (s.RequestId > p.RequestId)
{
// Another plugin's trade came after ours: the engine keeps only the newest one's status.
Finish(w, true, $"Asked the vendor for {QuantityRules.N(p.N)} {p.Name}; another trade followed it, so check your pack.");
return;
}
}
if (now - p.AtMs >= BuyAnswerMs)
Finish(w, false, $"No answer about {QuantityRules.N(p.N)} {p.Name}: check your pack and {p.Currency} before trying again.");
}
/// <summary>
/// The server refused it: a refusal naming the item (InventoryServerSaveFailed) at once, any other
/// new refusal once nothing changed for RefusalGraceMs after it (a fight's own errors pass by).
/// </summary>
private static bool RefusedNow(IQtyWorld w, Pending p, long now)
{
int seq = w.RefusalSeq;
if (p.RefusedAtMs == 0 && seq != 0 && seq != p.RefusalSeq && w.LastRefusal(out uint error, out uint eventType, out uint obj))
{
p.RefusalSeq = seq;
bool names = eventType == InventorySaveFailed && obj != 0;
if (names && obj != p.Id) return false; // another item's
p.RefusedAtMs = now;
p.Error = error;
p.RefusalNamesItem = names;
}
return p.RefusedAtMs != 0 && (p.RefusalNamesItem || now - p.RefusedAtMs >= RefusalGraceMs);
}
private void Finish(IQtyWorld w, bool ok, string text)
{
_pending = null;
Say(w, ok, text);
}
}

View file

@ -89,6 +89,25 @@ buttons (All, Melee, Missile, War, Void) narrow it, and the one you leave presse
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).
## The quantity box
Under a selected stack, or an item in an open vendor's list, the Selection window shows how many: type the
number (the game gets no keys while the box has the keyboard) or pick 1, 10, 100, half or max.
* **A stack you carry** (or one in the chest you have open): **Split N** puts N into a new stack in the main
pack, a side pack or the open container (*into ...* picks; the number is its free slots). One always stays in
the stack, so more than the stack splits all but one. **Give N** hands N (up to the whole stack) to the last
player or NPC you selected: select them, then the stack.
* **An item in a vendor's list**: **Buy N**, with its price and your pyreals (or the vendor's own currency).
*max* is the most you can buy: what the vendor has, what you can pay for, what your packs and burden take.
A buy that can't go says why before anything is sent ("Not enough pyreals: 100 Mana Scarab cost 1,200, you
have 1,000 (you can buy 83)", "The pack is full ..."); the engine checks again before it sends.
* Every action answers once, in chat and on the box's last line: done, the server's refusal, or no answer.
One action at a time.
* The same from chat, hotkeys and metas, with the window hidden: `/rdef qty`, `/rdef split`, `/rdef give`,
`/rdef buy` (below). It doesn't need the Inventory panel or RynthInventory.
* Retail AC kept this number in its toolbar; RynthCore's *Hide retail toolbar* hides it with the toolbar.
## Busy, combat and RynthAi
* One item action at a time: a request waits while the client is busy, a gesture animates, RynthAi waits on
@ -123,6 +142,11 @@ weapons you wielded are listed first (they are also in their kind's group).
/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 the script-window bar shows (1-24)
/rdef qty [n | max | half] the quantity box's number (alone: what it is and what it's of)
/rdef split [n] [into <pack>] split n (or the box's number) off the selected stack; pack: main, a side
pack's name, or open (the chest you have open)
/rdef give [n] give n of the selected stack to the last player or NPC you selected
/rdef buy [n] [item name] buy n of the selected vendor item (or the one named) from the open vendor
/rdef list | status | help
```
@ -131,8 +155,8 @@ slot N is bar slot 18+N, or bar slot N when the bar is independent of the game's
## Settings
Shortcuts bar: the windows shown, independent of the game's toolbar, slot picture size, allow weapon swaps
under RynthAi, picker row icon size. Script-window bar: slots (1-24), slots per row, button size, picker row
Shortcuts bar: the windows shown, the quantity box under the selection (on by default), independent of the
game's toolbar, slot picture size, allow weapon swaps under RynthAi, picker row icon size. Script-window bar: 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`.
@ -146,3 +170,4 @@ Pages, arrow auto-equip, gear highlight, summon cooldown counters and the war-ma
RynthCore engine API 71 with ImGui for the windows (op level 2 for pictures; text buttons without it);
API 90 for the Shortcuts bar, Game Panels and Selection. `/rdef use` works on any engine with UseObject.
The quantity commands: splitting on any engine, giving with a count API 62, buying API 67.

View file

@ -31,7 +31,7 @@
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>Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window: one-touch kits, potions, weapons and spells by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings.</RynthPluginDescription>
<RynthPluginDescription>Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window (with a quantity box: split, give or buy that many): one-touch kits, potions, weapons and spells by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>

View file

@ -0,0 +1,76 @@
// ============================================================================
// RynthDefective - RynthDefectivePlugin.Quantity.cs
// The quantity box (2026-10-30, Quantity/QuantityController.cs): its commands
// (/rdef qty, split, give, buy), the Selection window's buttons, and the tick
// that notes the give target and watches the action in flight.
//
// It lives here, with the Selection window, because the number is about what
// is selected (as retail's toolbar had it): it needs no inventory panel, and
// every command works with the window hidden or on an engine without it.
// ============================================================================
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Quantity;
using RynthCore.Plugin.RynthDefective.ShortcutBar;
namespace RynthCore.Plugin.RynthDefective;
public sealed partial class RynthDefectivePlugin
{
private readonly QuantityController _qty = new();
private HostQtyWorld? _qtyWorld;
private long _nextQtyTickMs;
private HostQtyWorld QtyWorld => _qtyWorld ??= new HostQtyWorld(Host);
/// <summary>Every answer of the box goes to chat (and to the window's line).</summary>
private void InitQuantity()
{
_qty.Report = (ok, text) => Reply.Say(ok, text);
}
private void RunQuantityCommand(DefCommand c)
{
switch (c.Verb)
{
case DefVerb.Quantity: _qty.SetBox(QtyWorld, c.Amount); break;
case DefVerb.Split: _qty.Split(QtyWorld, c.Amount, c.Text); break;
case DefVerb.Give: _qty.Give(QtyWorld, c.Amount); break;
case DefVerb.Buy: _qty.Buy(QtyWorld, c.Amount, c.Text); break;
}
}
/// <summary>A button in the Selection window's box, with the count it showed (queued from the render thread).</summary>
private void RunQuantityClick(QtyClick click, int n)
{
if (!_identityKnown) return;
QtyAmount amount = QtyAmount.Of(n);
switch (click)
{
case QtyClick.Split: _qty.Split(QtyWorld, amount, string.Empty); break;
case QtyClick.Give: _qty.Give(QtyWorld, amount); break;
case QtyClick.Buy: _qty.Buy(QtyWorld, amount, string.Empty); break;
}
}
/// <summary>Plugin tick, ten times a second: the give target and the answer to the action in flight.</summary>
private void TickQuantity(long now)
{
if (!_inWorld || !_identityKnown || now < _nextQtyTickMs) return;
_nextQtyTickMs = now + 100;
try { _qty.Tick(QtyWorld); }
catch (System.Exception ex) { Host.Log($"[RynthDefective] quantity tick failed: {ex.GetType().Name}: {ex.Message}"); }
}
/// <summary>The Selection window's box for what is selected (null: none, or the setting is off).</summary>
private QuantityView? QuantityViewNow()
{
if (!_session.Settings.QuantityBox) return null;
try { return _qty.View(QtyWorld); }
catch (System.Exception ex)
{
Host.Log($"[RynthDefective] quantity view failed: {ex.GetType().Name}: {ex.Message}");
return null;
}
}
}

View file

@ -48,7 +48,11 @@ public sealed partial class RynthDefectivePlugin
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."); }));
_selectionWindow ??= new SelectionWindow(Host, id => QueueBar(() => { if (!Host.UseObject(id)) Print("That can't be used now."); }))
{
Quantity = _qty,
QuantityAction = (click, n) => QueueBar(() => RunQuantityClick(click, n)),
};
wantHeight = _selectionWindow.Draw(_selectionView);
_selectionFailures = 0;
return 1;
@ -86,11 +90,16 @@ public sealed partial class RynthDefectivePlugin
Host.QueryHealth(sel);
}
// The quantity box (a stack, or an item in the open vendor's list).
Quantity.QuantityView? qty = QuantityViewNow();
string where = string.Empty;
float relative = float.NaN;
Items.CarriedItem? carried = null;
foreach (var it in _session.Items()) if (it.Id == sel) { carried = it; break; }
if (carried != null) where = CarriedText(carried);
if (qty?.Subject.Mode == Quantity.QtyMode.Vendor && qty.Subject.Quote is { } quote)
where = "the vendor's" + (quote.UnitPrice > 0 ? $" · {quote.UnitPrice.ToString("N0", CultureInfo.InvariantCulture)} {quote.Currency} each" : "");
else if (carried != null) where = CarriedText(carried);
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)
{
@ -106,12 +115,13 @@ public sealed partial class RynthDefectivePlugin
where = $"{dist.ToString(dist < 10 ? "0.0" : "0", CultureInfo.InvariantCulture)} yd {Compass(bearing)}";
}
// Not carried (on the ground, in a corpse or chest): AC's own stack size.
if (carried == null && Host.TryGetObjectIntProperty(sel, StackSizeProperty, out int stack) && stack > 1)
if (carried == null && qty?.Subject.Mode != Quantity.QtyMode.Vendor
&& Host.TryGetObjectIntProperty(sel, StackSizeProperty, out int stack) && stack > 1)
where = "stack of " + stack.ToString("N0", CultureInfo.InvariantCulture) + (where.Length > 0 ? " · " + where : "");
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);
return new SelectionView(true, sel, name, where, relative, health, h?.Current ?? 0, h?.Max ?? 0) { Qty = qty };
}
private const uint StackSizeProperty = 12; // PropertyInt.StackSize

View file

@ -63,6 +63,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
public override int Initialize()
{
_reply = new CommandReply("[RynthDefective]", (t, c) => Host.WriteToChat(t, c), t => Host.Log(t));
InitQuantity();
_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));
@ -115,6 +116,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
_nextIdentityTryMs = Environment.TickCount64;
_session.Use.ResetSession();
_world?.Reset();
_qty.Reset();
}
public override void OnLogout()
@ -126,6 +128,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
_session.LoggedIn = false;
_session.Use.ResetSession();
_world?.Reset();
_qty.Reset();
_barView = RynthCore.Plugin.RynthDefective.ShortcutBar.BarSnapshot.NotReady;
foreach (UiWindow? w in new[] { _barWindow, _pickerWindow, _settingsWindow })
if (w != null) { w.Visible = false; w.NeedsPass = true; }
@ -276,6 +279,13 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
case DefVerb.Status:
PrintStatus();
break;
case DefVerb.Quantity:
case DefVerb.Split:
case DefVerb.Give:
case DefVerb.Buy:
// The quantity box: each answers once, at once when it can't go, else when the game answers.
RunQuantityCommand(c);
break;
}
MarkAllForPass();
}
@ -287,6 +297,8 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
Print("RynthDefective draws the Shortcuts bar, the Game Panels buttons and the Selection window. Its settings: /rdef settings, "
+ "or the gear on the bar; right-click the bar's title to show or hide Game Panels and Selection.");
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.");
Print("How many of a stack or a vendor's item: the box under it in the Selection window, or /rdef qty 25, then /rdef split, /rdef give "
+ "(to the last player or NPC you selected) or /rdef buy (the selected vendor item, or /rdef buy 25 <item name>).");
}
private void PrintSlots()
@ -440,6 +452,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
if (_saveDueMs != 0 && now >= _saveDueMs) SaveNow();
TickBar(now);
TickSelection(now);
TickQuantity(now);
TickCorpses(now);
// With the shortcut bar the old script-window bar stays shut (the weapon picker is still one), and

View file

@ -0,0 +1,290 @@
// ============================================================================
// RynthDefective - ShortcutBar/SelectionWindow.Quantity.cs
// The quantity box under the selection (2026-10-30, Quantity/QuantityController):
// for a stack, a number with 1 / 10 / 100 / half / max, Split N into a pack
// and Give N to the last player or NPC selected; for an item in a vendor's
// list, Buy N with its price and what you have. Retail AC had this number in
// its toolbar (gone with "Hide retail toolbar"); this one is RynthDefective's.
//
// line 1 the number (typed: the game gets no keys while it has the
// keyboard) and the quick numbers
// line 2 Split N | into <pack> | Give N or Buy N | the price
// line 3 what the last action did, or what the buttons will do
//
// Render thread: draws the view the tick built. The number and the pack are
// set at once (QuantityController.Value / Into); the actions go to the tick.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Quantity;
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>A click on one of the box's buttons.</summary>
internal enum QtyClick { Split, Give, Buy }
internal sealed partial class SelectionWindow
{
/// <summary>The box's number and pack (set from here) and its last answer; null = no box.</summary>
public QuantityController? Quantity { get; set; }
/// <summary>A Split / Give / Buy click, with the count on the button (queued to the tick).</summary>
public Action<QtyClick, int>? QuantityAction { get; set; }
private const float QRow = 18, QGap = 4, QField = 54, QChipGap = 3;
private const string IntoPopupId = "##qty_into";
private static readonly uint OkColor = Argb(0xFF73D885), BadColor = Argb(0xFFE0564E), WarnColor = Argb(0xFFE8B04A);
/// <summary>The box's height under the selection (pixels); 0 = none.</summary>
private float QuantityHeight(QuantityView? q) =>
q == null || Quantity == null ? 0f
: MathF.Ceiling(Px(QGap) + Px(QRow) + Px(QGap) + Px(QRow) + Px(QGap) + Fs(Font(RynthUiFont.Narrow9)) + Px(Pad));
private void DrawQuantity(ImDrawListPtr dl, QuantityView q, Vector2 top, float width)
{
QuantityController ctl = Quantity!;
float pad = Px(Pad), rowH = Px(QRow), gap = Px(QGap);
float left = top.X + pad, right = top.X + width - pad;
dl.AddLine(new Vector2(left, top.Y), new Vector2(right, top.Y), A(_line, 0.8f));
QtySubject s = q.Subject;
int value = ctl.Value;
float y = top.Y + gap;
// Line 1: the number and the quick numbers.
float fieldW = Math.Min(Px(QField), Math.Max(Px(30), right - left));
NumberField(ctl, new Vector2(left, y), fieldW, rowH, s);
float x = left + fieldW + Px(QChipGap + 2);
int max = s.BoxMax;
string none = s.Mode == QtyMode.Vendor ? s.Quote?.Refusal(1) ?? "You can't buy any now." : "Nothing to count.";
if (Chip(dl, "##qty_1", "1", ref x, y, rowH, right, true, "One.")) ctl.Value = 1;
if (Chip(dl, "##qty_10", "10", ref x, y, rowH, right, true, "Ten.")) ctl.Value = 10;
if (Chip(dl, "##qty_100", "100", ref x, y, rowH, right, true, "A hundred.")) ctl.Value = 100;
string halfTip = max < 1 ? none
: s.Mode == QtyMode.Vendor ? $"Half of the most you can buy now ({QuantityRules.N(QuantityRules.HalfOf(max))})."
: $"Half the stack ({QuantityRules.N(QuantityRules.HalfOf(max))}).";
if (Chip(dl, "##qty_half", "half", ref x, y, rowH, right, max >= 1, halfTip)) ctl.Value = QuantityRules.ForBox(QtyAmount.Half, max);
string maxTip = max < 1 ? none
: s.Mode == QtyMode.Vendor ? $"The most you can buy now ({QuantityRules.N(max)}): what the vendor has, you can pay for and your packs take."
: $"The whole stack ({QuantityRules.N(max)}). A split still leaves one.";
if (Chip(dl, "##qty_max", "max", ref x, y, rowH, right, max >= 1, maxTip)) ctl.Value = QuantityRules.ForBox(QtyAmount.Max, max);
ImFontPtr sf = Font(RynthUiFont.Narrow9);
string of = s.Mode == QtyMode.Stack ? "of " + QuantityRules.N(s.Stack) : max >= 1 ? "up to " + QuantityRules.N(max) : string.Empty;
float ofW = of.Length > 0 ? sf.CalcTextSizeA(Fs(sf), float.MaxValue, 0f, of).X : 0f;
if (of.Length > 0 && x + ofW <= right + 0.5f)
dl.AddText(sf, Fs(sf), new Vector2(MathF.Round(right - ofW), MathF.Round(y + (rowH - Fs(sf)) * 0.5f)), _faint, of);
// Line 2: what the number does.
y += rowH + gap;
x = left;
if (s.Mode == QtyMode.Stack) StackButtons(dl, q, ctl, value, ref x, y, rowH, right);
else VendorButtons(dl, q, value, ref x, y, rowH, right);
// Line 3: the last answer, or what the buttons do.
y += rowH + gap;
QtyStatus? st = ctl.StatusAt(Environment.TickCount64);
string line;
uint color;
if (st != null) { line = st.Text; color = st.Ok ? OkColor : BadColor; }
else if (q.Busy) { line = "Waiting for the server..."; color = _dim; }
else Hint(q, value, out line, out color);
if (line.Length > 0)
{
ImGui.SetCursorScreenPos(new Vector2(left, y));
ImGui.InvisibleButton("##qty_line", new Vector2(Math.Max(1, right - left), Math.Max(1, Fs(sf))));
SafeImGui.SetItemTooltip(line);
Clip(dl, sf, Fs(sf), new Vector2(left, y), color, line, right - left);
}
}
private void StackButtons(ImDrawListPtr dl, QuantityView q, QuantityController ctl, int value, ref float x, float y, float h, float right)
{
QtySubject s = q.Subject;
bool reach = s.Where is QtyWhere.Carried or QtyWhere.Open;
int split = QuantityRules.SplitCount(value, s.Stack);
QtyPack? into = q.Target;
string splitTip = !q.CanSplit ? QtyReplies.NoSplitApi
: q.Busy ? QtyReplies.Busy
: s.Where == QtyWhere.Wielded ? QtyReplies.Wielded(s.Name)
: !reach ? QtyReplies.NotReachable(s.Name)
: into is { Free: 0 } full ? QtyReplies.PackFull(full.Where)
: $"Split {QuantityRules.N(split)} off the stack of {QuantityRules.N(s.Stack)} into {into?.Where ?? "the main pack"}: a new stack there."
+ (value >= s.Stack ? " One always stays in the stack." : string.Empty);
bool canSplit = q.CanSplit && !q.Busy && reach;
if (Chip(dl, "##qty_split", "Split " + QuantityRules.N(split), ref x, y, h, right, canSplit, splitTip, primary: true))
QuantityAction?.Invoke(QtyClick.Split, split);
// Where the split goes.
if (into is { } t)
{
string free = t.Free >= 0 ? " · " + t.Free.ToString(System.Globalization.CultureInfo.InvariantCulture) : string.Empty;
string label = "into " + t.Label + free;
float before = x;
if (Chip(dl, "##qty_into_btn", label, ref x, y, h, right, q.Targets.Length > 1 && !q.Busy,
q.Targets.Length > 1 ? "Where the split goes: the main pack, a side pack or the container you have open (the number is its free slots)."
: "Where the split goes (your only pack).", textColor: t.Free == 0 ? BadColor : null, caret: q.Targets.Length > 1))
ImGui.OpenPopup(IntoPopupId);
if (x == before && right - x > Px(40))
{
// No room for the whole label: the pack's name cut short.
if (Chip(dl, "##qty_into_btn2", "into...", ref x, y, h, right, q.Targets.Length > 1 && !q.Busy, "Into " + t.Label + free + ".", caret: q.Targets.Length > 1))
ImGui.OpenPopup(IntoPopupId);
}
IntoMenu(q, ctl);
}
// Give to the last player or NPC selected.
int give = QuantityRules.GiveCount(value, s.Stack);
bool canGive = q.CanGive && !q.Busy && s.Where == QtyWhere.Carried && q.GiveTo != 0;
string giveTip = !q.CanGive ? QtyReplies.NoGiveApi
: q.Busy ? QtyReplies.Busy
: s.Where == QtyWhere.Wielded ? QtyReplies.Wielded(s.Name)
: s.Where != QtyWhere.Carried ? QtyReplies.NotCarried(s.Name)
: q.GiveTo == 0 ? QtyReplies.NoGiveTarget
: $"Give {QuantityRules.N(give)} {s.Name} to {q.GiveName} (the last player or NPC you selected).";
if (Chip(dl, "##qty_give", "Give " + QuantityRules.N(give), ref x, y, h, right, canGive, giveTip))
QuantityAction?.Invoke(QtyClick.Give, give);
}
private void IntoMenu(QuantityView q, QuantityController ctl)
{
if (!ImGui.IsPopupOpen(IntoPopupId)) 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(IntoPopupId);
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(2);
if (!open) return;
try
{
ImGui.TextDisabled("Split into");
ImGui.Separator();
for (int i = 0; i < q.Targets.Length; i++)
{
QtyPack p = q.Targets[i];
string free = p.Free < 0 ? "" : p.Free == 0 ? " (full)" : $" ({p.Free} free)";
// A menu item's label is drawn as it is (not a printf format); "##" keeps two packs of one name apart.
if (ImGui.MenuItem(p.Label + free + "##qty_into_" + i, null, i == q.TargetIndex, p.Free != 0))
ctl.Into = p.Kind == QtyPackKind.Main ? 0 : p.Id;
}
}
finally { ImGui.EndPopup(); }
}
private void VendorButtons(ImDrawListPtr dl, QuantityView q, int value, ref float x, float y, float h, float right)
{
QtySubject s = q.Subject;
VendorQuote? quote = s.Quote;
string? why = quote?.Refusal(value);
string tip = q.Busy ? QtyReplies.Busy
: why ?? (quote != null ? $"Buy {QuantityRules.N(value)} {s.Name} for {QuantityRules.N(quote.Cost(value))} {quote.Currency}. The vendor checks again before it sells." : "Buy.");
if (Chip(dl, "##qty_buy", "Buy " + QuantityRules.N(value), ref x, y, h, right, !q.Busy, tip, primary: why == null))
QuantityAction?.Invoke(QtyClick.Buy, value);
if (quote == null) return;
ImFontPtr sf = Font(RynthUiFont.Narrow9);
string price = quote.PriceLine(value);
Clip(dl, sf, Fs(sf), new Vector2(x + Px(2), MathF.Round(y + (h - Fs(sf)) * 0.5f)), why != null ? WarnColor : _dim, price, right - x - Px(2));
}
private void Hint(QuantityView q, int value, out string line, out uint color)
{
QtySubject s = q.Subject;
color = _faint;
if (s.Mode == QtyMode.Vendor)
{
string? why = s.Quote?.Refusal(value);
if (why != null) { line = why; color = WarnColor; return; }
line = s.Quote is { UnitPrice: > 0 } qq ? $"{QuantityRules.N(qq.UnitPrice)} {qq.Currency} each. /rdef buy N does the same." : "/rdef buy N does the same.";
return;
}
line = s.Where switch
{
QtyWhere.Wielded => QtyReplies.Wielded(s.Name),
QtyWhere.Open => "In the open container: Split takes them into your pack.",
QtyWhere.Carried when q.GiveTo != 0 => $"Give goes to {q.GiveName}.",
QtyWhere.Carried => "Split makes a new stack. To give: select the NPC, then this.",
_ => QtyReplies.NotReachable(s.Name),
};
if (s.Where is QtyWhere.Wielded or QtyWhere.Elsewhere or QtyWhere.Unknown) color = WarnColor;
}
/// <summary>The number: typed (keys stay out of the game while it has the keyboard), 1 or more.</summary>
private void NumberField(QuantityController ctl, Vector2 p, float w, float h, QtySubject s)
{
ImDrawListPtr dl = ImGui.GetWindowDrawList();
Vector2 size = new(w, h);
dl.AddRectFilled(p, p + size, _inset, Px(3));
ImFontPtr f = Font(RynthUiFont.Dash10);
ImGui.PushFont(f);
ImGui.SetWindowFontScale(_r);
float fs = ImGui.GetFontSize();
ImGui.PushStyleColor(ImGuiCol.FrameBg, 0u);
ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, 0u);
ImGui.PushStyleColor(ImGuiCol.FrameBgActive, 0u);
ImGui.PushStyleColor(ImGuiCol.Border, 0u);
ImGui.PushStyleColor(ImGuiCol.Text, _text);
ImGui.PushStyleColor(ImGuiCol.TextSelectedBg, A(_accent, 0.45f));
ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 0f);
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(Px(4), Math.Max(0f, (h - fs) * 0.5f)));
bool active, hovered;
try
{
ImGui.SetCursorScreenPos(p);
ImGui.SetNextItemWidth(w);
int v = ctl.Value;
if (ImGui.InputInt("##qty_n", ref v, 0, 0, ImGuiInputTextFlags.AutoSelectAll | ImGuiInputTextFlags.CharsDecimal) && v >= 1)
ctl.Value = v;
active = ImGui.IsItemActive();
hovered = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(s.Mode == QtyMode.Vendor
? "How many to buy. Type it, or pick one beside it."
: "How many: Split and Give use this number. Type it, or pick one beside it.");
}
finally
{
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(6);
ImGui.SetWindowFontScale(1f);
ImGui.PopFont();
}
dl.AddRect(p, p + size, active ? _accent : hovered ? A(_accent, 0.6f) : _line, Px(3));
}
/// <summary>A small flat button at x (moved past it); left out (false) when it doesn't fit before <paramref name="right"/>.</summary>
private bool Chip(ImDrawListPtr dl, string id, string label, ref float x, float y, float h, float right, bool enabled, string tip,
bool primary = false, uint? textColor = null, bool caret = false)
{
ImFontPtr f = Font(RynthUiFont.Narrow10);
float tw = f.CalcTextSizeA(Fs(f), float.MaxValue, 0f, label).X;
float caretW = caret ? Px(9) : 0f;
float w = MathF.Ceiling(tw + caretW + Px(10));
if (x + w > right + 0.5f) return false;
Vector2 p = new(MathF.Round(x), y), size = new(w, h);
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton(id, size);
bool hot = enabled && ImGui.IsItemHovered();
if (tip.Length > 0) SafeImGui.SetItemTooltip(tip);
uint fill = primary ? A(_accent, hot ? 0.45f : 0.28f) : hot ? _key : A(_key, 0.6f);
dl.AddRectFilled(p, p + size, enabled ? fill : A(_key, 0.25f), Px(3));
dl.AddRect(p, p + size, hot ? _accent : A(_line, enabled ? 1f : 0.5f), Px(3));
uint tc = !enabled ? _faint : textColor ?? (hot || primary ? _text : _dim);
float tx = MathF.Round(p.X + (w - tw - caretW) * 0.5f);
dl.AddText(f, Fs(f), new Vector2(tx, MathF.Round(p.Y + (h - Fs(f)) * 0.5f)), tc, label);
if (caret)
{
// A small down arrow after the label.
float cx = tx + tw + Px(5), cy = p.Y + h * 0.5f, r = Px(2.5f);
dl.AddTriangleFilled(new Vector2(cx - r, cy - r * 0.5f), new Vector2(cx + r, cy - r * 0.5f), new Vector2(cx, cy + r * 0.7f), tc);
}
x += w + Px(QChipGap);
return clicked && enabled;
}
}

View file

@ -9,6 +9,8 @@
//
// the name row drag to move; Ctrl+wheel: bigger or smaller (30-250%);
// right-click: hide it (Settings > UI > Toolbar, /rdef selection).
// the quantity under a stack or a vendor's item (2026-10-30): how many, and
// Split / Give / Buy that many (SelectionWindow.Quantity.cs).
//
// AC's render thread; reads the view the tick built (SelectionView).
// ============================================================================
@ -17,6 +19,7 @@ using System;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthDefective.Quantity;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
@ -36,9 +39,12 @@ internal sealed record SelectionView(
uint Max)
{
public static readonly SelectionView NotReady = new(false, 0, string.Empty, string.Empty, float.NaN, -1f, 0, 0);
/// <summary>The quantity box for a stack or a vendor's item; null = none.</summary>
public QuantityView? Qty { get; init; }
}
internal sealed class SelectionWindow
internal sealed partial class SelectionWindow
{
public const string Title = "Selection";
@ -90,7 +96,10 @@ internal sealed class SelectionWindow
float pad = Px(Pad), icon = Px(Icon);
float height = MathF.Ceiling(2 * pad + icon);
Vector2 max = origin + new Vector2(width, height);
// The quantity box under it (a stack, or a vendor's item): one background for both.
QuantityView? qty = v.Ready && v.Id != 0 ? v.Qty : null;
float qtyH = QuantityHeight(qty);
Vector2 max = origin + new Vector2(width, height + qtyH);
dl.AddRectFilled(origin, max, A(_bg, 0.94f), Px(Radius));
dl.AddRect(origin, max, _line, Px(Radius));
@ -165,9 +174,11 @@ internal sealed class SelectionWindow
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);
if (qty != null && qtyH > 0) DrawQuantity(dl, qty, new Vector2(origin.X, origin.Y + height), width);
ImGui.SetCursorScreenPos(origin);
ImGui.Dummy(new Vector2(width, height));
return height;
ImGui.Dummy(new Vector2(width, height + qtyH));
return height + qtyH;
}
/// <summary>Text cut with "..." to <paramref name="room"/> pixels.</summary>

View file

@ -51,6 +51,13 @@ internal sealed class BarSettingsView
WindowBox(w, BarTitle, "Shortcuts bar", "set.win.bar", "The item bar (/rdef). Its RynthCore bar button is the lightning bolt.");
WindowBox(w, PanelsTitle, "Game panel buttons", "set.win.panels", "Buttons for the game's own panels: pack, spellbook, map ... (/rdef panels).");
WindowBox(w, SelectionTitle, "Selection", "set.win.sel", "What is selected, how far and which way, and a creature's health (/rdef selection).");
if (WindowShown(SelectionTitle) != null)
{
w.Checkbox("Quantity box under a stack or a vendor's item", "set.qty", st.QuantityBox, v => { st.QuantityBox = v; Changed(); });
w.Tooltip("In the Selection window: how many, with 1 / 10 / 100 / half / max, then Split that many into a pack, "
+ "Give that many to the last player or NPC you selected, or Buy that many from the open vendor.\n"
+ "/rdef qty, /rdef split, /rdef give and /rdef buy do the same with it off. Kept for this character.");
}
w.SeparatorText("Shortcuts bar");
w.Checkbox("Independent of the game's toolbar", "set.indep", st.IndependentBar, v => Tell(_s.SetIndependent(v)));
@ -86,7 +93,8 @@ internal sealed class BarSettingsView
w.SeparatorText("About");
w.TextWrapped(SettingsPanel.Credit);
w.TextDisabled("Commands: /rdef (show or hide the bar), /rdef settings, /rdef panels, /rdef selection, /rdef weapons, /rdef use <slot or name>, /rdef help.");
w.TextDisabled("Commands: /rdef (show or hide the bar), /rdef settings, /rdef panels, /rdef selection, /rdef weapons, /rdef use <slot or name>, "
+ "/rdef qty, /rdef split, /rdef give, /rdef buy, /rdef help.");
}
private void WindowBox(UiWindow w, string title, string label, string id, string tip)

View file

@ -48,9 +48,7 @@ public static unsafe class PluginExports
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag)
=> Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
[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);
// No RynthPluginOnUpdateHealth (0.4.2): deaths come from the vitals the session reads each tick.
// Corpses (0.3.0): a kill a ring, wall or chain spell made without a kill notice is found by its corpse.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]

View file

@ -16,10 +16,14 @@ namespace RynthCore.Plugin.RynthTracker;
// RynthOracle and RynthILT count the same session from the same start, and Reset starts that one
// over. Without RynthAi (or before its login) the Tracker's own session, kept running all along,
// is shown instead.
//
// Deaths (0.4.2, 2026-10-30): counted from the player's vitals and the server's death counter,
// read each tick (SessionStatsTracker). They used to wait for the player's health in
// OnUpdateHealth, which the engine never sends for the player, so the count stayed 0.
public sealed class RynthTrackerPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthTracker");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.4.1"); // previous release: 0.4.0
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.4.2"); // previous release: 0.4.1
private SessionStatsTracker? _session;
private readonly RynthAiSessionClient _ai = new();
@ -63,9 +67,6 @@ public sealed class RynthTrackerPlugin : RynthPluginBase
public override void OnDeleteObject(uint objectId) => _session?.OnDeleteObject(objectId);
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
=> _session?.OnUpdateHealth(targetId, currentHealth, maxHealth);
public override void OnTick()
{
var session = _session;

View file

@ -27,6 +27,18 @@
// Fallback "You've banked N Luminance." counts on its own only until a
// bank property (9005 or 9102) is read; after that the property
// covers every source and the chat line would double-count.
//
// Deaths (2026-10-30), from two readings of the player each tick:
// health the engine's own vitals: 0 (with a max) after a reading above
// 0. The player's health never comes through OnUpdateHealth (that
// is a target's health), which is why the count used to stay 0.
// 0/0 (a login, before the vitals) is no reading.
// NumDeaths the server's death counter (PropertyInt 43): a rise counts,
// so a death while the plugin was unloaded (a reload) is not lost.
// A character that never died has no counter until its first death.
// ACE sends both in one packet (Player.Die: health 0, then NumDeaths), so one
// death shows on both: the first to show it counts it, the other is matched to
// it until the player reads alive again. Kill notices never count a death.
// ============================================================================
using System;
using System.Collections.Generic;
@ -146,6 +158,13 @@ internal sealed class SessionStats
private readonly List<(DateTime At, long Amount)> _recentLum = new();
private long _recentLumSum;
// Deaths (see the header): the last health reading, the NumDeaths baseline, and the death
// each reading has counted that the other one hasn't shown yet.
private bool? _alive; // null = no reading yet this session (or since a reload)
private TrackerRise _deathCountRise;
private bool _deathOpenByHealth; // counted from health 0; its NumDeaths rise hasn't come
private int _deathsOpenByCount; // counted from NumDeaths; their health 0 hasn't been read
public SessionStats() => Reset(DateTime.UtcNow);
public DateTime SessionStartUtc => _sessionStart;
@ -184,6 +203,10 @@ internal sealed class SessionStats
_movedIntoBankUntil = DateTime.MinValue;
_recentLum.Clear();
_recentLumSum = 0;
_alive = null;
_deathCountRise.Clear();
_deathOpenByHealth = false;
_deathsOpenByCount = 0;
}
// ── Events ───────────────────────────────────────────────────────────────
@ -228,8 +251,41 @@ internal sealed class SessionStats
return result;
}
/// <summary>The player's health reached 0.</summary>
public void OnPlayerDied() => _deaths++;
/// <summary>
/// The player's health from the engine's vitals. 0 after a reading above 0 is a death, unless
/// NumDeaths already counted it; max 0 (the 0/0 before a login's vitals) is no reading. Read
/// before <see cref="OnDeathCount"/> in the same tick: the server sends the health first.
/// </summary>
public void OnPlayerHealth(uint current, uint max)
{
if (max == 0) return;
bool alive = current > 0;
if (alive)
{
// Alive again (or still): whatever comes from now on is a new death.
_deathOpenByHealth = false;
_deathsOpenByCount = 0;
}
else if (_alive == true)
{
if (_deathsOpenByCount > 0) _deathsOpenByCount--;
else { _deaths++; _deathOpenByHealth = true; }
}
_alive = alive;
}
/// <summary>
/// The server's death counter (NumDeaths). Its first read is the baseline; a rise is that many
/// deaths, less the one health 0 has already counted.
/// </summary>
public void OnDeathCount(int numDeaths)
{
long up = _deathCountRise.Take(numDeaths);
if (up <= 0) return;
if (_deathOpenByHealth) { _deathOpenByHealth = false; up--; }
_deaths += (int)up;
_deathsOpenByCount += (int)up;
}
private void CountCorpseKill(DateTime now)
{
@ -378,6 +434,8 @@ internal sealed class SessionStats
s.LumOwn = _lumOwn;
s.BankIncome = _bankIncome;
s.OwnSinceBank = _ownSinceBank;
s.DeathCountBase = _deathCountRise.Baseline;
s.DeathOpen = _deathOpenByHealth;
s.RecentLum.Clear();
foreach (var (at, amount) in _recentLum) s.RecentLum.Add((at.Ticks, amount));
}
@ -405,6 +463,11 @@ internal sealed class SessionStats
_lumOwn = s.LumOwn;
_bankIncome = s.BankIncome;
_ownSinceBank = s.OwnSinceBank;
// The last health reading is not carried over: after an engine reload the vitals can read
// 0 with a max for a moment before the health is seeded, and that is no death. A death the
// reload hid comes in through NumDeaths' saved baseline instead.
_deathCountRise.Restore(s.DeathCountBase);
_deathOpenByHealth = s.DeathOpen;
foreach (var (at, amount) in s.RecentLum)
{
_recentLum.Add((new DateTime(at, DateTimeKind.Utc), amount));

View file

@ -1,9 +1,10 @@
// ============================================================================
// RynthSuite - Plugins/Shared/SessionStatsTracker.cs
// Feeds a SessionStats from the game: the player's properties every 0.5 s,
// kill notices, chat, corpses and the player's health, and keeps the session
// across plugin reloads (TrackerSessionStore). RynthTracker and RynthAi's
// Mini Remote each own one, so both show the same numbers (2026-10-11).
// kill notices, chat, corpses, and the player's health and death counter
// every tick, and keeps the session across plugin reloads
// (TrackerSessionStore). RynthTracker and RynthAi's Mini Remote each own one,
// so both show the same numbers (2026-10-11).
//
// Threading: every call except RequestReset and View runs on the pump
// thread. RequestReset only sets a flag (any thread); View is an immutable
@ -24,6 +25,8 @@ internal sealed class SessionStatsTracker
private const uint Int64RadianceEarned = 9101; // Aelrynth Bank mod session totals
private const uint Int64LuminanceBanked = 9102;
private const uint Int64LuminanceDrawn = 9103;
// The server's death counter (PropertyInt). The engine serves the player's own record to any thread.
private const uint IntNumDeaths = 43;
private const long PollIntervalMs = 500;
private static readonly TimeSpan SaveInterval = TimeSpan.FromSeconds(30);
@ -149,12 +152,9 @@ internal sealed class SessionStatsTracker
if (_pendingCorpses[i].Id == objectId) _pendingCorpses.RemoveAt(i);
}
/// <summary>The player's health reaching 0 is a death (maxHealth &gt; 0 skips spurious 0/0 packets at login).</summary>
public void OnUpdateHealth(uint targetId, uint currentHealth, uint maxHealth)
{
if (_active && targetId == _playerId && currentHealth == 0 && maxHealth > 0)
_stats.OnPlayerDied();
}
// Deaths are read every tick (CheckDeaths), not from OnUpdateHealth: the engine never sends the
// player's own health through it (that is a target's health: 0x01C0 and creature vitals), so the
// death count stayed 0 (2026-10-30).
// ── Tick (pump thread) ───────────────────────────────────────────────────
@ -180,6 +180,7 @@ internal sealed class SessionStatsTracker
}
if (!_active) return;
CheckDeaths();
CheckPendingCorpses(now);
long nowMs = Environment.TickCount64;
@ -211,6 +212,27 @@ internal sealed class SessionStatsTracker
private long? Read(uint stype)
=> _host.TryGetObjectQuadProperty(_playerId, stype, out long value) ? value : null;
/// <summary>
/// The player's health from the engine's vitals (the same reading RynthAi's death hold uses),
/// then the server's death counter, in the order the server sends them (SessionStats counts
/// each death once). Every tick: the health reads 0 for a few seconds only.
/// </summary>
private void CheckDeaths()
{
int before = _stats.Deaths;
if (_host.HasGetPlayerVitals
&& _host.TryGetPlayerVitals(out uint health, out uint maxHealth, out _, out _, out _, out _))
_stats.OnPlayerHealth(health, maxHealth);
if (_host.HasGetObjectIntProperty
&& _host.TryGetObjectIntProperty(_playerId, IntNumDeaths, out int numDeaths))
_stats.OnDeathCount(numDeaths);
if (_stats.Deaths != before)
{
_view = _stats.View(DateTime.UtcNow); // shown at once, not at the next poll
_host.Log($"{_tag} Death counted ({_stats.Deaths} this session).");
}
}
/// <summary>Reads the names of newly created objects; a "Corpse of X" goes to the kill counter.</summary>
private void CheckPendingCorpses(DateTime now)
{

View file

@ -90,6 +90,12 @@ internal sealed class TrackerSessionState
public long OwnSinceBank;
/// <summary>Luminance of the last five minutes, oldest first: (UTC ticks, amount).</summary>
public List<(long AtTicks, long Amount)> RecentLum = new();
// Added 2026-10-30 (deaths from the vitals and NumDeaths). Optional in the file, like the above.
/// <summary>The server's death counter (PropertyInt 43, NumDeaths) baseline.</summary>
public long? DeathCountBase;
/// <summary>A death counted from health 0 whose NumDeaths rise hadn't been read yet.</summary>
public bool DeathOpen;
}
internal static class TrackerSessionStore
@ -152,6 +158,8 @@ internal static class TrackerSessionStore
Line(sb, "bankincome", s.BankIncome.ToString(Ic));
Line(sb, "ownsincebank", s.OwnSinceBank.ToString(Ic));
Line(sb, "recentlum", Recent(s.RecentLum));
Line(sb, "deathsbase", Opt(s.DeathCountBase));
Line(sb, "deathopen", s.DeathOpen ? "1" : "0");
Line(sb, "end", "1"); // a torn write never parses
return sb.ToString();
}
@ -204,7 +212,10 @@ internal static class TrackerSessionStore
(!map.ContainsKey("lumown") || Long(map, "lumown", out s.LumOwn)) &&
(!map.ContainsKey("bankincome") || Long(map, "bankincome", out s.BankIncome)) &&
(!map.ContainsKey("ownsincebank") || Long(map, "ownsincebank", out s.OwnSinceBank)) &&
(!map.ContainsKey("recentlum") || ParseRecent(map["recentlum"], s.RecentLum));
(!map.ContainsKey("recentlum") || ParseRecent(map["recentlum"], s.RecentLum)) &&
// The 2026-10-30 keys may be absent too.
(!map.ContainsKey("deathsbase") || OptLong(map, "deathsbase", out s.DeathCountBase)) &&
(!map.ContainsKey("deathopen") || Bool(map, "deathopen", out s.DeathOpen));
if (!ok) return false;
// Ticks outside DateTime's range would throw when the plugin builds a DateTime.