Snapshot for release 2026.10.13.1 (internal d2b5fb3)

This commit is contained in:
Tom Bohar 2026-10-13 14:25:49 -04:00
commit 319740ff5d
291 changed files with 58505 additions and 2107 deletions

View file

@ -34,7 +34,7 @@
// queue (CMotionInterp pending motions, the engine's cast gate: GetCastBusyState) must
// be empty, for uses, kits, potions, casts, stance changes, wields and the item
// managers' moves (GestureHolds). Melee/missile attack repeats are exempt (MayStart
// with gestureGate false). Time limit GestureHoldMaxMs (GestureEmergencyMaxMs for an
// with animationGate false). Time limit GestureHoldMaxMs (GestureEmergencyMaxMs for an
// emergency heal), logged, like Combat/CastGateWatchdog for casts.
//
// Why the animation gate (2026-10-06 afternoon, ops/overnight/2026-10-06-turnto-stall.md,
@ -92,6 +92,8 @@ internal sealed class PacedAction
public long SentMs;
public int SeqAtSend;
public int ModeTarget;
public uint Target; // a cast's target (the held-cast turn faces it)
public bool Script; // a cast a script chose (the combat hook): the breaker waits ScriptCastMinBreakMs
public bool WieldedAtSend;
public bool ResultSeen; // a cast's result is in (enchantment / chat); the server is in its recoil
public bool HealQueued; // the one heal allowed behind that recoil went out
@ -165,6 +167,7 @@ internal static class ActionPacer
{
_cur = null;
_started = _answered = _timedOut = _sentOverOutstanding = _modeRefused = _modeSkipped = 0;
_refuseSince = 0; _refuseLast = 0; _refuseCount = 0; _engineRefusals = 0; _lastEngineRefusalMs = 0;
_heldStarts = _heldMoves = _healsAhead = 0;
_gestureHolds = _gestureLimits = 0;
_swingSentMs = 0; _swingSeenBusy = false; _swingHolds = 0; _swingLogged.Clear();
@ -175,13 +178,44 @@ internal static class ActionPacer
_maxWaitWhat = "";
_holdsByWho.Clear();
_lastTimeout = "";
ClearBusyLocked();
_stuckBreaks = 0;
_refusalHolds = 0;
_heldTurns = 0;
_forcedBreaks = 0;
_jumpAt = 0;
_cycleBySpell.Clear();
_lastSeenSeq = int.MinValue;
_lastFrameMs = 0;
_gapEnd = 0;
_gapLen = 0;
_errorAnswers.Clear();
_staleDrops = _latchExpiries = _burstHolds = 0;
}
}
/// <summary>
/// The plugin's heartbeat, every frame whatever the macro does. A gap of PollGapMs or more between
/// two calls (the client froze or loaded) makes a cast sent before the gap ENDED stale at the next
/// check (a cast sent in the tick just before a freeze is sent after that tick's NoteFrame), so
/// a teleport's or a freeze's gap is never mistaken for a stuck cast and broken by a jump. Never
/// called (a plugin without it, the tests that don't): no gap detection, only StaleCastMs.
/// </summary>
public static void NoteFrame()
{
long now = NowMs();
lock (Gate)
{
if (_lastFrameMs != 0 && now - _lastFrameMs >= PollGapMs) { _gapEnd = now; _gapLen = now - _lastFrameMs; }
_lastFrameMs = now;
}
}
/// <summary>Forget the outstanding action (logout, death, portal): the server dropped it.</summary>
public static void Forget(string why)
{
lock (Gate) { _cur = null; }
// A death, portal or logout also ends a refusal streak: a refusal before it must not make one after it look like a long streak.
lock (Gate) { _cur = null; ClearBusyLocked(); _refuseSince = 0; _refuseLast = 0; _refuseCount = 0; }
}
// ── Recording what went out ──────────────────────────────────────────────
@ -209,6 +243,8 @@ internal static class ActionPacer
{
_sentOverOutstanding++;
over = $"[Pace] {who}: {Describe(kind, label)} went out while {Describe(prev.Kind, prev.Label)} ({prev.Who}) was unanswered for {now - prev.SentMs} ms";
// Our cast is still the server's: a 0x1D to this send says it is open (the stuck-cast rules).
if (prev.Kind == PacedKind.Cast && _shadow == null && _hung == null) _shadow = prev;
}
_cur = a;
}
@ -254,6 +290,12 @@ internal static class ActionPacer
if (hasSeq && seq != a.SeqAtSend)
{
answeredHow = "UseDone";
if (a.Kind == PacedKind.Cast)
{
uint err = TooBusyErr;
try { if (host.TryGetLastUseDone(out int ls, out uint le) && ls == a.SeqAtSend + 1) err = le; } catch { }
if (err != TooBusyErr) NoteCycle(a.Id, age);
}
}
else if (a.Kind == PacedKind.ItemUse && IsWieldedByPlayer(host, a.Id) != a.WieldedAtSend)
{
@ -293,6 +335,7 @@ internal static class ActionPacer
{
_timedOut++;
_lastTimeout = $"{Describe(a.Kind, a.Label)} ({a.Who}) after {age} ms";
if (a.Kind == PacedKind.Cast && _hung == null) _hung = a; // still the server's: see the stuck-cast hold
line = $"[Pace] no answer from the server to {Describe(a.Kind, a.Label)} ({a.Who}) in {age} ms - going on (nothing cleared)";
}
else
@ -317,14 +360,31 @@ internal static class ActionPacer
/// May <paramref name="who"/> send a use, a cast or a mode change now? False (with why) while
/// another action waits for the server, except the heal rules in the file header, and while
/// the character is still animating (<see cref="GestureHolds"/>; skipped with
/// <paramref name="gestureGate"/> false: melee/missile attack repeats). One log line per
/// <paramref name="animationGate"/> false: melee/missile attack repeats). One log line per
/// outstanding action (or animation) and subsystem.
/// </summary>
public static bool MayStart(RynthCoreHost host, string who, HealNeed heal, out string why, bool gestureGate = true)
/// <param name="animationGate">False: skip <see cref="GestureHolds"/> (melee/missile attack repeats).</param>
/// <param name="settleGate">False: skip the movement settle (<see cref="MoveAudit.SettleHolds"/>; attack repeats only).</param>
/// <param name="attackRepeat">
/// A melee/missile attack repeat: never held by the 'too busy' latch. ACE sends no UseDone for a
/// swing, so a latch set by anything else (a refused pickup) would otherwise leave combat only the
/// probe slots.
/// </param>
public static bool MayStart(RynthCoreHost host, string who, HealNeed heal, out string why,
bool animationGate = true, bool settleGate = true, bool attackRepeat = false)
{
if (!Enabled) { why = ""; return true; }
if (ServerBusyHolds(host, who, attackRepeat, out why, healStart: heal != HealNeed.None)) return false;
if (settleGate && MoveAudit.SettleHolds(host, out why))
{
bool log;
lock (Gate) { _settleHolds++; log = _settleLogged.Add(who); }
if (log) Log(host, $"[Pace] {who} waits: {why}");
return false;
}
lock (Gate) _settleLogged.Clear();
if (!OutstandingAllows(host, who, heal, out why)) return false;
if (gestureGate && GestureHolds(host, who, heal, out why)) return false;
if (animationGate && GestureHolds(host, who, heal, out why)) return false;
return true;
}
@ -443,11 +503,16 @@ internal static class ActionPacer
private static readonly HashSet<string> _swingLogged = new();
public static long SwingHoldCount => _swingHolds;
/// <summary>Attacks CombatManager reported (NoteAttackSent): a caller that remembers the count can
/// tell whether a swing went out since (BuffCastChain). Not reset, only compared.</summary>
public static long AttacksSent { get; private set; }
/// <summary>CombatManager sent a melee or missile attack.</summary>
public static void NoteAttackSent()
{
lock (Gate)
{
AttacksSent++;
_swingSentMs = NowMs();
_swingSeenBusy = false;
_swingLogged.Clear();
@ -495,8 +560,471 @@ internal static class ActionPacer
return true;
}
// -- A cast the server holds open, and a server that answers "too busy" ----------------
// Two hangs in a client log, both ACE's fast-tick turn-to-cast wait (Player_Magic
// TurnTo_Magic / PendingTurnRelease: the cast waits until the character faces its target within
// spellcast_max_angle, with no time limit): a Bolt VII sent in the same tick as nav's autorun stop
// (answered 40.8 s later) and a Drain at a moving target (its
// incantation 2865 ms after the send, fizzled 37 s later on a client mode change). The server
// kept IsBusy, so every cast after it came back UseDone 0x1D, and the vitals path re-sent a heal
// every 2.5 s. So:
// * a cast that times out unanswered (CastMaxMs) is kept as the server's (hung);
// * a UseDone with 0x1D latches "server busy": nothing starts (MayStart) until a UseDone with
// another error arrives. With no cast of ours open, one probe goes after BusyProbeMs, then
// after twice that each time, up to BusyProbeMaxMs (the busy thing may have no UseDone of its
// own, e.g. a pickup). No timer re-sends into a server busy with our own cast;
// * a cast of ours still unanswered TurnAfterMs past its normal cycle: turn to face its target
// (the server's angle check then lets it finish), once, when RynthAi is not moving us;
// * still unanswered JumpAfterMs past its normal cycle (capped by StuckCastMs), or a 0x1D to
// another send while it is open past RefusalBreakMinMs: the breaker, a jump (0xF61B, TapJump):
// on fast tick ACE's HandleActionJump clears the pending motions and calls FailCast (origin/
// master Player.cs ~1195-1214), a 0x402 fizzle. Nothing starts until the character has landed
// (a cast in the air is refused). No UseDone BreakerWaitMaxMs after landing: a Peace mode
// request (HandleActionChangeCombatMode_Inner also calls FailCast, fast tick or not); then
// BreakerWaitMaxMs more and it goes on (logged).
/// <summary>ACE's YoureTooBusy, as a UseDone error.</summary>
public const uint TooBusyErr = 0x1D;
/// <summary>With no cast of ours open, one start is let through this long after a 0x1D (doubling per probe).</summary>
public const long BusyProbeMs = 1500;
public const long BusyProbeMaxMs = 6000;
/// <summary>A cast's normal send-to-UseDone time when none was seen for its spell, and the floor of a learned one.</summary>
public const long DefaultCycleMs = 3000;
/// <summary>Past its normal cycle: turn to face the target after this, jump after this.</summary>
public const long TurnAfterMs = 1000;
public const long JumpAfterMs = 2000;
/// <summary>A 0x1D to another send breaks our open cast only once it is this old (a recoil refusal is normal).</summary>
public const long RefusalBreakMinMs = 3000;
/// <summary>After the jump: landed once the height is back (and this long passed), or at the max.</summary>
public const long JumpLandMinMs = 400;
public const long JumpLandMaxMs = 1500;
/// <summary>After landing (or after the Peace request), the longest wait for a UseDone before the next step.</summary>
public const long BreakerWaitMaxMs = 3000;
/// <summary>The stuck-cast limit (ms from the send; 0 = no turn, no breaker). RynthAi sets it from its settings.</summary>
public static long StuckCastMs = 8000;
/// <summary>
/// A script-chosen cast is not broken by a jump before this (ms from the send), whatever its
/// cycle, Stuck Cast Break or a 'too busy' answer say: a script's slower spells (a siphon
/// answered about 5.5 s after the send) get 6 s from the send before the first jump; the
/// held-cast nudge, which counts from the incantation, comes later.
/// </summary>
public const long ScriptCastMinBreakMs = 6000;
/// <summary>
/// A cast of ours this old (or one sent before a gap of PollGapMs between NoteFrame calls: a
/// client freeze, a long load) is stale: dropped with the latch, never broken. Bounds every hold,
/// the breaker off (StuckCastMs 0) included.
/// </summary>
public const long StaleCastMs = 3 * (CastMaxMs > BusyProbeMaxMs ? CastMaxMs : BusyProbeMaxMs);
public const long PollGapMs = 5000;
/// <summary>A 'too busy' latch with no cast of ours open is cleared after this long (logged).</summary>
public const long LatchMaxMs = 15000;
/// <summary>'Too busy' UseDones in the last second at which every start but a heal waits (bounds refusal chat lines).</summary>
public const int RefusalBurstMax = 5;
public const int PeaceMode = 1, MagicMode = 8;
private enum BreakStage { None, Turned, Jumped, Landed, ModeSent }
private static PacedAction? _hung; // a cast past CastMaxMs with no UseDone
private static PacedAction? _shadow; // our cast still unanswered when another action went out over it
private static long _busySince; // first 0x1D of the latch (0 = no latch)
private static int _busyRefusals; // 0x1D answers in this latch
private static int _probes;
private static long _lastProbeAt;
private static BreakStage _stage;
private static long _stageAt;
private static PacedAction? _stageFor;
private static long _jumpAt; // 0 = not in the air after a breaker jump
private static float _jumpZ;
private static int _lastSeenSeq = int.MinValue;
private static long _lastFrameMs; // the last NoteFrame (gap detection; 0 = never)
private static long _gapEnd, _gapLen; // the frame that ended the last gap, and its length (0 = none)
private static readonly Queue<long> _errorAnswers = new(); // times of error UseDones (burst limiter)
private static long _staleDrops, _latchExpiries, _burstHolds;
public static long StaleDrops => _staleDrops;
public static long LatchExpiries => _latchExpiries;
public static long BurstHolds => _burstHolds;
private static long _stuckBreaks, _refusalHolds, _heldTurns, _forcedBreaks, _settleHolds;
private static readonly HashSet<string> _settleLogged = new();
public static long SettleHoldCount => _settleHolds;
private static readonly HashSet<string> _busyLogged = new();
private static readonly Dictionary<uint, long> _cycleBySpell = new();
public static long StuckBreaks => _stuckBreaks;
public static long RefusalHolds => _refusalHolds;
public static long HeldCastTurns => _heldTurns;
/// <summary>True while the server is taken as busy (a 0x1D latch or a hung cast).</summary>
public static bool ServerBusy { get { lock (Gate) return _busySince != 0 || _hung != null; } }
/// <summary>True while the character is in the air after a breaker jump.</summary>
public static bool BreakerAirborne { get { lock (Gate) return _jumpAt != 0; } }
private static void ClearBusyLocked()
{
_hung = null;
_shadow = null;
_busySince = 0;
_busyRefusals = 0;
_probes = 0;
_lastProbeAt = 0;
_stage = BreakStage.None;
_stageAt = 0;
_stageFor = null;
_busyLogged.Clear();
}
/// <summary>The normal send-to-UseDone time of <paramref name="spellId"/>: the longest of its last answers, at least DefaultCycleMs.</summary>
internal static long NormalCycleMs(uint spellId)
{
lock (Gate) return _cycleBySpell.TryGetValue(spellId, out long c) ? Math.Max(DefaultCycleMs, c) : DefaultCycleMs;
}
/// <summary>A cast of <paramref name="spellId"/> was answered (not 0x1D) <paramref name="ms"/> after its send.</summary>
private static void NoteCycle(uint spellId, long ms)
{
if (ms <= 0 || ms > CastMaxMs) return;
lock (Gate)
{
// The longest recent answer, easing down: a slow one counts at once, old slow ones fade.
_cycleBySpell[spellId] = _cycleBySpell.TryGetValue(spellId, out long c) ? Math.Max(ms, (c * 7 + ms) / 8) : ms;
}
}
/// <summary>Reads the last UseDone: a 0x1D starts or feeds the latch, any other answer clears it.</summary>
private static void ObserveUseDone(RynthCoreHost host, long now, out string? line)
{
line = null;
int seq; uint err;
try
{
if (!host.HasUseDoneSeq || !host.TryGetLastUseDone(out seq, out err)) return;
}
catch { return; }
lock (Gate)
{
if (_lastSeenSeq == int.MinValue) { _lastSeenSeq = seq; return; }
if (seq == _lastSeenSeq) return;
_lastSeenSeq = seq;
if (err == TooBusyErr) _errorAnswers.Enqueue(now); // the burst counts 'too busy' only (0x401 retries are paced on their own)
if (err == TooBusyErr)
{
if (_busySince == 0) { _busySince = now; if (_hung == null) _busyLogged.Clear(); }
_busyRefusals++;
return;
}
if (_busySince != 0 || _hung != null || _stage != BreakStage.None)
line = $"[Pace] the server answered again (UseDone 0x{err:X}): casting resumes" +
(_hung != null ? $" ({Describe(_hung.Kind, _hung.Label)} ended {now - _hung.SentMs} ms after its send)" : "");
ClearBusyLocked();
}
}
/// <summary>
/// True (with why) while the server is taken as busy (a 0x1D answer with no other answer since,
/// a hung cast) or the character is in the air after a breaker jump. Runs the held-cast turn and
/// the stuck-cast breaker. Called by MayStart.
/// </summary>
private static bool ServerBusyHolds(RynthCoreHost host, string who, bool attackRepeat, out string why, bool healStart = false)
{
why = "";
long now = NowMs();
long gapEnd, gapLen;
lock (Gate) { gapEnd = _gapEnd; gapLen = _gapLen; }
ObserveUseDone(host, now, out string? line);
if (line != null) Log(host, line);
if (AirborneHolds(host, now, out why)) return true;
PacedAction? open = Current(host);
PacedAction? stuck;
bool probe = false;
long age = 0;
string? staleLine = null;
lock (Gate)
{
if (_shadow != null && _hung == null && now - _shadow.SentMs >= CastMaxMs) { _hung = _shadow; _shadow = null; }
stuck = _hung ?? _shadow ?? (open is { Kind: PacedKind.Cast } ? open : null);
if (stuck != null) age = now - stuck.SentMs;
// Stale: too old to still be the server's, or sent before a gap with no checks (a freeze,
// portal space, the macro off). Dropped with the latch, never broken.
bool beforeGap = stuck != null && gapEnd != 0 && stuck.SentMs < gapEnd;
if (stuck != null && (age >= StaleCastMs || beforeGap))
{
staleLine = $"[Pace] {Describe(stuck.Kind, stuck.Label)} ({stuck.Who}) is stale ({age} ms" +
(beforeGap ? $", sent before a {gapLen} ms gap with no check" : "") + "): dropped, the server is taken as free";
if (ReferenceEquals(_cur, stuck)) _cur = null;
ClearBusyLocked();
_staleDrops++;
stuck = null;
}
// A 'too busy' latch with no cast of ours open: bounded, not probed for ever.
else if (stuck == null && _busySince != 0 && now - _busySince >= LatchMaxMs && _stage == BreakStage.None)
{
staleLine = $"[Pace] no answer cleared the 'too busy' latch in {now - _busySince} ms and no cast of ours is open: going on";
ClearBusyLocked();
_latchExpiries++;
}
if (_stageFor != null && !ReferenceEquals(_stageFor, stuck)) { _stage = BreakStage.None; _stageAt = 0; _stageFor = null; }
// A forced break with no cast of ours open (stage for nothing): once on the ground, it is
// over. Left set it would block the latch expiry and the probe for good.
else if (_stageFor == null && _stage != BreakStage.None && _jumpAt == 0) { _stage = BreakStage.None; _stageAt = 0; }
if (!attackRepeat && stuck == null && _busySince != 0 && _stage == BreakStage.None
&& now - Math.Max(_busySince, _lastProbeAt) >= Math.Min(BusyProbeMs << Math.Min(_probes, 8), BusyProbeMaxMs))
{
probe = true;
_probes++;
_lastProbeAt = now;
}
}
if (staleLine != null) Log(host, staleLine);
if (stuck != null && !IsPortaling(host)) StepBreaker(host, stuck, age, now);
if (AirborneHolds(host, now, out why)) return true;
// Any source: RefusalBurstMax 'too busy' answers in the last second hold every start but a heal for the rest
// of that second (each refusal is a chat line; a burst of them is the 0x00460D1D crash class).
int burst;
lock (Gate)
{
while (_errorAnswers.Count > 0 && now - _errorAnswers.Peek() >= 1000) _errorAnswers.Dequeue();
burst = _errorAnswers.Count;
if (burst >= RefusalBurstMax && !healStart) _burstHolds++;
}
// A heal is never held by the burst (an emergency must not wait on refusals of other starts).
if (burst >= RefusalBurstMax && !healStart)
{
why = $"{burst} refusals from the server in the last second";
return true;
}
// Attack repeats are never held by the latch (no UseDone ever comes for a swing).
if (attackRepeat) return false;
bool latched;
lock (Gate) latched = _busySince != 0 || _hung != null;
// Our cast still inside CastMaxMs with no 0x1D: OutstandingAllows holds it (heal rules included).
if (!latched) return false;
if (probe)
{
Log(host, $"[Pace] {who}: one try (#{_probes}) after the server's 'too busy' answer; no cast of ours is open");
return false;
}
int refusals;
BreakStage stage;
lock (Gate)
{
_refusalHolds++;
_holdsByWho[who] = _holdsByWho.TryGetValue(who, out int n) ? n + 1 : 1;
refusals = _busyRefusals;
stage = _stage;
}
string what = stuck != null ? $"{Describe(stuck.Kind, stuck.Label)} ({stuck.Who}) has had no answer for {age} ms" : "the server answered 'too busy'";
why = stage >= BreakStage.Jumped
? $"{what}; stuck-cast break sent, waiting for its UseDone"
: $"{what}{(refusals > 0 ? $" ({refusals} 'too busy' answer(s))" : "")}: nothing goes until the server answers";
bool log;
lock (Gate) log = _busyLogged.Add(who);
if (log) Log(host, $"[Pace] {who} waits: {why}");
return true;
}
/// <summary>The held-cast turn and the breaker steps for <paramref name="stuck"/> (one step per call at most).</summary>
private static void StepBreaker(RynthCoreHost host, PacedAction stuck, long age, long now)
{
if (StuckCastMs <= 0) return;
long cycle = NormalCycleMs(stuck.Id);
long jumpAt = Math.Min(cycle + JumpAfterMs, StuckCastMs);
long turnAt = Math.Min(cycle + TurnAfterMs, jumpAt);
long refusalBreakAt = RefusalBreakMinMs;
if (stuck.Script) { jumpAt = Math.Max(jumpAt, ScriptCastMinBreakMs); refusalBreakAt = Math.Max(refusalBreakAt, ScriptCastMinBreakMs); }
BreakStage stage; long stageAt; int refusals;
lock (Gate) { stage = _stage; stageAt = _stageAt; refusals = _busyRefusals; }
if (stage == BreakStage.None && age >= turnAt && age < jumpAt)
{
SetStage(BreakStage.Turned, now, stuck);
TurnToFace(host, stuck, age);
return;
}
if (stage <= BreakStage.Turned && (age >= jumpAt || (refusals > 0 && age >= refusalBreakAt)))
{
string why = age >= jumpAt ? $"{age} ms with no answer ({cycle} ms is normal for it)" : $"a send was refused 'too busy' while it was open {age} ms";
Jump(host, stuck, age, why, forced: false);
return;
}
if (stage == BreakStage.Landed && now - stageAt >= BreakerWaitMaxMs)
{
SetStage(BreakStage.ModeSent, now, stuck);
PeaceBreak(host, stuck, age);
return;
}
if (stage == BreakStage.ModeSent && now - stageAt >= BreakerWaitMaxMs)
{
lock (Gate) ClearBusyLocked();
Log(host, $"[Pace] no UseDone after the stuck-cast break ({Describe(stuck.Kind, stuck.Label)}, {age} ms) - going on");
}
}
private static void SetStage(BreakStage stage, long now, PacedAction? forAction)
{
lock (Gate) { _stage = stage; _stageAt = now; _stageFor = forAction; }
}
/// <summary>In the air after a breaker jump: hold until landed (height back, or JumpLandMaxMs).</summary>
private static bool AirborneHolds(RynthCoreHost host, long now, out string why)
{
why = "";
long jumpAt; float z0;
lock (Gate) { jumpAt = _jumpAt; z0 = _jumpZ; }
if (jumpAt == 0) return false;
long air = now - jumpAt;
bool landed = air >= JumpLandMaxMs;
if (!landed && air >= JumpLandMinMs)
{
try { landed = !host.HasGetPlayerPose || (host.TryGetPlayerPose(out _, out _, out _, out float z, out _, out _, out _, out _) && Math.Abs(z - z0) < 0.1f); }
catch { landed = true; }
}
if (!landed)
{
why = $"in the air after the stuck-cast jump ({air} ms)";
return true;
}
lock (Gate)
{
_jumpAt = 0;
if (_stage == BreakStage.Jumped)
{
if (_stageFor == null) { _stage = BreakStage.None; _stageAt = 0; } // a forced break with no cast of ours open
else { _stage = BreakStage.Landed; _stageAt = now; }
}
}
return false;
}
/// <summary>The breaker jump (TapJump: the keyboard jump, 0xF61B). No TapJump: the Peace request instead.</summary>
private static void Jump(RynthCoreHost host, PacedAction? stuck, long age, string why, bool forced)
{
long now = NowMs();
string what = stuck != null ? Describe(stuck.Kind, stuck.Label) : "the server's busy action";
if (!host.HasTapJump)
{
SetStage(BreakStage.ModeSent, now, stuck);
Log(host, $"[Pace] stuck cast: no TapJump on this engine; {what}: {why}");
PeaceBreak(host, stuck, age);
return;
}
float z = 0;
try { if (host.HasGetPlayerPose) host.TryGetPlayerPose(out _, out _, out _, out z, out _, out _, out _, out _); } catch { }
bool ok;
try { ok = host.TapJump(); } catch { ok = false; }
lock (Gate)
{
_stuckBreaks++;
if (forced) _forcedBreaks++;
_stage = BreakStage.Jumped;
_stageAt = now;
_stageFor = stuck;
if (ok) { _jumpAt = now; _jumpZ = z; }
}
Log(host, $"[Pace] stuck cast broken by jump after {age} ms: {what} - {why}{(ok ? "" : " (the jump was refused by the client)")}; nothing starts until landed and answered");
// Refused by the client: nothing in the air. For no cast of ours, nothing to wait for either.
if (!ok) { SetStage(stuck == null ? BreakStage.None : BreakStage.Landed, now, stuck); }
}
/// <summary>The Peace mode request (ACE fails a cast in progress on a mode change). Only from Magic.</summary>
private static void PeaceBreak(RynthCoreHost host, PacedAction? stuck, long age)
{
int mode = -1;
try { if (host.HasGetCurrentCombatMode) mode = host.GetCurrentCombatMode(); } catch { mode = -1; }
string what = stuck != null ? Describe(stuck.Kind, stuck.Label) : "the server's busy action";
if (mode == MagicMode && host.HasChangeCombatMode)
{
int seq = UseDoneSeqNow(host);
bool ok;
try { ok = host.ChangeCombatMode(PeaceMode); } catch { ok = false; }
lock (Gate) _stuckBreaks++;
if (ok)
{
PacedAction? keep;
lock (Gate) keep = _hung;
Begin(host, PacedKind.CombatMode, 0, ModeName(PeaceMode), "StuckCast", seq, PeaceMode);
lock (Gate) _hung = keep;
}
Log(host, $"[Pace] stuck cast broken by Peace mode after {age} ms: {what} - no answer after the jump; Peace {(ok ? "requested" : "refused by the client")}");
}
else
{
Log(host, $"[Pace] stuck cast: {what} still unanswered after the jump, not in Magic mode ({ModeName(mode)}): nothing more to cancel");
}
}
/// <summary>
/// Turn to face a held cast's target (once per cast), when RynthAi is not moving the character:
/// ACE's fast-tick cast waits for the facing to come within spellcast_max_angle.
/// </summary>
private static void TurnToFace(RynthCoreHost host, PacedAction stuck, long age)
{
uint target = stuck.Target;
uint player = 0;
try { if (host.HasGetPlayerId) player = host.GetPlayerId(); } catch { }
if (target == 0 || target == player || !host.HasTurnToHeading || MoveAudit.OwnMovementActive) return;
if (!TryHeadingTo(host, target, out double want, out double off)) return;
if (off < 10.0) return; // already facing it: the turn is not what holds it
try { host.TurnToHeading((float)want); } catch { return; }
lock (Gate) _heldTurns++;
Log(host, $"[Pace] held cast: {Describe(stuck.Kind, stuck.Label)} unanswered {age} ms; turning {off:0} deg to face 0x{target:X8} (heading {want:0})");
}
/// <summary>The heading to <paramref name="target"/> (AC degrees: 0 north, 90 east) and how far off the player faces.</summary>
internal static bool TryHeadingTo(RynthCoreHost host, uint target, out double heading, out double offDeg)
{
heading = 0; offDeg = 180;
try
{
if (!host.HasGetPlayerPose || !host.HasGetObjectPosition) return false;
if (!host.TryGetPlayerPose(out uint pcell, out float px, out float py, out _, out float qw, out _, out _, out float qz)) return false;
if (!host.TryGetObjectPosition(target, out uint tcell, out float tx, out float ty, out _)) return false;
double dx = (((tcell >> 24) & 0xFF) - (double)((pcell >> 24) & 0xFF)) * 192.0 + (tx - px);
double dy = (((tcell >> 16) & 0xFF) - (double)((pcell >> 16) & 0xFF)) * 192.0 + (ty - py);
if (Math.Abs(dx) < 0.01 && Math.Abs(dy) < 0.01) return false;
heading = Math.Atan2(dx, dy) * (180.0 / Math.PI);
if (heading < 0) heading += 360.0;
double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI);
double cur = ((-yaw) % 360.0 + 720.0) % 360.0;
double e = heading - cur;
while (e > 180) e -= 360;
while (e < -180) e += 360;
offDeg = Math.Abs(e);
return true;
}
catch { return false; }
}
/// <summary>
/// The HP failsafe's break (BuffManager): a jump now, whatever is open (on fast tick it fails a
/// cast in progress and clears the pending motions). False when one is already under way or
/// this engine has no TapJump.
/// </summary>
public static bool ForceBreak(RynthCoreHost host, string why)
{
if (!Enabled || !host.HasTapJump || IsPortaling(host)) return false;
PacedAction? stuck;
lock (Gate)
{
if (_jumpAt != 0 || _stage == BreakStage.Jumped) return false;
stuck = _hung ?? _shadow ?? (_cur is { Kind: PacedKind.Cast } ? _cur : null);
}
long age = stuck != null ? NowMs() - stuck.SentMs : 0;
Jump(host, stuck, age, why, forced: true);
return true;
}
// ── Helpers ─────────────────────────────────────────────────────────────
/// <summary>In portal space: no breaker step, no forced break (the server is moving us).</summary>
internal static bool IsPortaling(RynthCoreHost host)
{
try { return host.HasIsPortaling && host.IsPortaling(); } catch { return false; }
}
internal static string Describe(PacedKind kind, string label) => kind switch
{
PacedKind.WorldUse => $"the use of {label}",
@ -560,6 +1088,7 @@ internal static class ActionPacer
lines.Add($" Starts held {_heldStarts}, moves held {_heldMoves}, heals let ahead {_healsAhead}, sent over an unanswered one {_sentOverOutstanding}");
lines.Add($" Mode changes refused while waiting {_modeRefused}, skipped (already in that mode) {_modeSkipped}");
lines.Add($" Held while the character was animating {_gestureHolds}, animation time limits {_gestureLimits}");
lines.Add($" Held after a 'too busy' answer {_refusalHolds}, held casts turned to {_heldTurns}, stuck casts broken {_stuckBreaks} ({_forcedBreaks} by the HP failsafe; limit {StuckCastMs} ms)");
if (_maxWaitMs > 0) lines.Add($" Longest wait seen: {_maxWaitMs} ms ({_maxWaitWhat})");
if (_holdsByWho.Count > 0)
{
@ -585,18 +1114,44 @@ internal static class ActionPacer
MoveAudit.FlushPendingStops(host, "before a cast", force: true);
int seq = UseDoneSeqNow(host);
bool ok = host.CastSpell(targetId, spellId);
if (ok) Begin(host, PacedKind.Cast, unchecked((uint)spellId), label, who, seq);
if (ok)
{
CastsSent++;
LastCastSeqAtSend = host.HasUseDoneSeq ? seq : -1;
Begin(host, PacedKind.Cast, unchecked((uint)spellId), label, who, seq);
lock (Gate) { if (_cur is { Kind: PacedKind.Cast } c && c.Id == unchecked((uint)spellId)) c.Target = targetId; }
}
return ok;
}
/// <summary>The open cast of <paramref name="spellId"/> was chosen by a script (see <see cref="ScriptCastMinBreakMs"/>).</summary>
public static void MarkScriptCast(int spellId)
{
lock (Gate) { if (_cur is { Kind: PacedKind.Cast } c && c.Id == unchecked((uint)spellId)) c.Script = true; }
}
/// <summary>
/// The UseDone count read just before the last cast <see cref="CastSpellFor"/> sent (its answer is
/// the next UseDone after it); -1 when the engine has no UseDone count.
/// </summary>
public static int LastCastSeqAtSend { get; private set; } = -1;
/// <summary>
/// Casts sent through <see cref="CastSpellFor"/> in this plugin (every caller: combat, buffs,
/// nav, commands, meta): a caller that remembers the count at its own cast can tell whether
/// another cast went out since (a refusal then may be that one's).
/// </summary>
public static long CastsSent { get; private set; }
/// <summary>
/// ChangeCombatMode with the pacing rules: nothing is sent when the client already reads that
/// mode (the engine would push a raw 0x53 to the server anyway, and on ACE every mode change
/// cancels the walk/turn of a pending use and fails a cast in progress) unless
/// <paramref name="force"/>; and nothing while another server action is unanswered unless
/// <paramref name="force"/>. Returns false only when the pacing held the request back (or the
/// client already reads that mode); otherwise the request was made, as a plain ChangeCombatMode
/// call was before (whose result the callers never read), so their retry timers run as before.
/// <paramref name="force"/>. Returns false when nothing went out: the pacing held the request back,
/// the client already reads that mode, or the engine refused the call. True only when the request
/// was made (or the host has no ChangeCombatMode, where there is nothing to send or pace). Callers
/// count a try, a backoff step or a log line only on true.
/// </summary>
public static bool ChangeCombatModeFor(this RynthCoreHost host, int mode, string who, string why, bool force = false)
{
@ -630,8 +1185,63 @@ internal static class ActionPacer
}
}
int seq = UseDoneSeqNow(host);
if (host.ChangeCombatMode(mode))
Begin(host, PacedKind.CombatMode, 0, ModeName(mode), who, seq, mode);
if (!host.ChangeCombatMode(mode))
return NoteEngineRefusal(host, mode);
NoteEngineAccepted(host);
Begin(host, PacedKind.CombatMode, 0, ModeName(mode), who, seq, mode);
return true;
}
// -- The engine turning a mode change away -----------------------------------------------
// ChangeCombatMode returns false when the engine refused: it turns non-teardown actions away for
// a few seconds around a teleport or a death, its action ring can be full, or the hook is
// missing. Nothing was sent, so no action is outstanding and the callers must not count a try
// or a backoff step: ChangeCombatModeFor returns false and they ask again next tick. A refusal
// that lasts longer than EngineRefusalFailOpenMs is no longer a transition (a missing hook or a
// stuck ring never recovers): the call then returns true again, which puts the callers back on
// their own failure counting (NoWandFlipMaxFails and the potion fallbacks). One log line when a
// streak starts, one when it ends; any accepted call ends it.
/// <summary>A streak of consecutive engine refusals this long makes ChangeCombatModeFor return true again.</summary>
public const long EngineRefusalFailOpenMs = 30_000;
/// <summary>Refusals further apart than this are separate streaks (the streak never outlives a quiet spell).</summary>
public const long RefuseGapMs = 10_000;
private static long _refuseSince; // start of the current streak of engine refusals (0 = none)
private static long _refuseLast; // time of the newest refusal in the streak
private static long _lastEngineRefusalMs;
/// <summary>NowMs of the newest engine refusal (0 = none since Reset). Stuck-stance clocks restart when this is newer than their start.</summary>
public static long LastEngineRefusalMs { get { lock (Gate) return _lastEngineRefusalMs; } }
private static int _refuseCount;
private static long _engineRefusals; // lifetime
public static long EngineModeRefusals => _engineRefusals;
private static bool NoteEngineRefusal(RynthCoreHost host, int mode)
{
bool startLine = false, failOpen;
long now = NowMs();
lock (Gate)
{
_engineRefusals++;
if (_refuseSince != 0 && now - _refuseLast > RefuseGapMs) _refuseSince = 0;
if (_refuseSince == 0) { _refuseSince = now; _refuseCount = 0; startLine = true; }
_refuseLast = now; _lastEngineRefusalMs = now;
_refuseCount++;
failOpen = now - _refuseSince > EngineRefusalFailOpenMs;
}
if (startLine)
Log(host, $"[Pace] the engine refused the change to {ModeName(mode)} mode: asking again each tick (no try counted), counted as a failure after {EngineRefusalFailOpenMs / 1000} s");
return failOpen;
}
private static void NoteEngineAccepted(RynthCoreHost host)
{
int count; long span;
lock (Gate)
{
if (_refuseSince == 0) return;
count = _refuseCount; span = NowMs() - _refuseSince;
_refuseSince = 0; _refuseLast = 0; _refuseCount = 0;
}
Log(host, $"[Pace] the engine accepts mode changes again after {count} refusal(s) over {span} ms");
}
}

View file

@ -0,0 +1,189 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.Shared;
/// <summary>
/// Counts your kills, including the extra monsters a ring, wall, blast or chain spell kills.
/// Shared by RynthTracker and RynthAi's Mini Remote through <see cref="SessionStats"/>.
///
/// Two ways a kill is counted:
/// 1. The server's killer notification (it goes only to whoever landed the killing blow).
/// One notification is one kill, as before.
/// 2. A corpse ("Corpse of X") with no notification for it, when you hit an X with a
/// multi-target spell in the last <see cref="TokenLifeMs"/>. Some servers send no
/// notification for the extra monsters a spell kills (chain spells on Conquest), and on
/// ACE a killing blow sends no damage line either, so the corpse is the one sign left.
///
/// "Multi-target" is read from the combat log: one cast's damage lines (and kill notices)
/// arrive together, so lines no more than <see cref="VolleyGapMs"/> apart are one volley, and
/// a volley with two or more of them hit several monsters. Each name hit in such a volley may
/// be counted from its corpse as many times as that volley hit it (tokens). A single-target
/// hit never makes a corpse count: a monster you hit once that someone else then finished
/// isn't yours, the same as before.
///
/// A notification is matched to its corpse later (the corpse forms after the death animation),
/// so a kill counted by its notification isn't counted again by its corpse.
///
/// Pure logic, no host: the plugin passes every event with its time, so tests can drive it.
/// </summary>
internal sealed class KillCounter
{
/// <summary>Damage lines and kill notices this close together belong to one cast.</summary>
public const double VolleyGapMs = 800;
/// <summary>How long after a multi-target hit a monster's corpse still counts as your kill.</summary>
public const double TokenLifeMs = 15000;
/// <summary>How long a kill notice waits for its corpse.</summary>
public const double NoticeLifeMs = 20000;
/// <summary>How long a single-target hit is remembered (only to explain an uncounted corpse in the log).</summary>
public const double HitMemoryMs = 15000;
public int Kills { get; private set; }
public int NoticeKills { get; private set; }
public int CorpseKills { get; private set; }
private readonly List<(string Message, DateTime At)> _notices = new();
private readonly Dictionary<string, (int Count, DateTime Until)> _tokens = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DateTime> _lastHit = new(StringComparer.OrdinalIgnoreCase);
// The volley in progress: hits per name, and how many members (lines + notices) it has.
private readonly Dictionary<string, int> _volley = new(StringComparer.OrdinalIgnoreCase);
private int _volleyMembers;
private DateTime _volleyLast = DateTime.MinValue;
/// <summary>The server's killer notification: always one kill.</summary>
public void OnKillNotice(string? message, DateTime now)
{
Kills++;
NoticeKills++;
Prune(now);
_notices.Add((message ?? "", now));
JoinVolley(now);
// A notice is one of the volley's monsters too (the killing blow sends no damage line),
// under the name of a monster we hit that the message contains.
string? name = LongestRecentHitIn(message ?? "", now);
if (name != null) _volley[name] = _volley.TryGetValue(name, out int n) ? n + 1 : 1;
GrantTokens(now);
}
private string? LongestRecentHitIn(string message, DateTime now)
{
string? best = null;
foreach (var kv in _lastHit)
{
if ((now - kv.Value).TotalMilliseconds > HitMemoryMs) continue;
if (message.IndexOf(kv.Key, StringComparison.OrdinalIgnoreCase) < 0) continue;
if (best == null || kv.Key.Length > best.Length) best = kv.Key;
}
return best;
}
/// <summary>One of your damage lines, naming the monster it hurt.</summary>
public void OnHit(string victim, DateTime now)
{
if (string.IsNullOrEmpty(victim)) return;
JoinVolley(now);
_volley[victim] = _volley.TryGetValue(victim, out int n) ? n + 1 : 1;
_lastHit[victim] = now;
GrantTokens(now);
}
/// <summary>What a corpse turned out to be.</summary>
public enum CorpseResult
{
/// <summary>Its kill notice already counted it.</summary>
Notified,
/// <summary>No notice, but you hit it with a multi-target spell: counted now.</summary>
Counted,
/// <summary>You hit a monster of that name, but only single-target: not counted (someone else's kill?).</summary>
HitNotCounted,
/// <summary>Nothing of yours.</summary>
NotOurs,
}
/// <summary>A corpse appeared; <paramref name="monsterName"/> is the X of "Corpse of X".</summary>
public CorpseResult OnCorpse(string monsterName, DateTime now)
{
if (string.IsNullOrEmpty(monsterName)) return CorpseResult.NotOurs;
Prune(now);
// The oldest notice that names this monster.
int match = -1;
for (int i = 0; i < _notices.Count; i++)
if (_notices[i].Message.IndexOf(monsterName, StringComparison.OrdinalIgnoreCase) >= 0) { match = i; break; }
if (match >= 0)
{
_notices.RemoveAt(match);
// It was one of the monsters a multi-target volley hit: it no longer vouches for another.
if (_tokens.TryGetValue(monsterName, out var used) && used.Count > 0)
_tokens[monsterName] = (used.Count - 1, used.Until);
return CorpseResult.Notified;
}
if (_tokens.TryGetValue(monsterName, out var t) && t.Count > 0 && t.Until >= now)
{
_tokens[monsterName] = (t.Count - 1, t.Until);
Kills++;
CorpseKills++;
return CorpseResult.Counted;
}
return _lastHit.TryGetValue(monsterName, out DateTime h) && (now - h).TotalMilliseconds <= HitMemoryMs
? CorpseResult.HitNotCounted
: CorpseResult.NotOurs;
}
public void Reset()
{
Kills = NoticeKills = CorpseKills = 0;
_notices.Clear();
_tokens.Clear();
_lastHit.Clear();
_volley.Clear();
_volleyMembers = 0;
_volleyLast = DateTime.MinValue;
}
private void JoinVolley(DateTime now)
{
if ((now - _volleyLast).TotalMilliseconds > VolleyGapMs)
{
_volley.Clear();
_volleyMembers = 0;
}
_volleyMembers++;
_volleyLast = now;
}
// A volley that hit several monsters makes each name it hit countable from its corpse, as
// many times as the volley hit that name. Max, not sum: the next cast hits the same monsters
// again, and two casts at two monsters are still two monsters.
private void GrantTokens(DateTime now)
{
if (_volleyMembers < 2) return;
DateTime until = now.AddMilliseconds(TokenLifeMs);
foreach (var kv in _volley)
{
int have = _tokens.TryGetValue(kv.Key, out var t) && t.Until >= now ? t.Count : 0;
_tokens[kv.Key] = (Math.Max(have, kv.Value), until);
}
}
private readonly List<string> _pruneScratch = new();
private void Prune(DateTime now)
{
_notices.RemoveAll(n => (now - n.At).TotalMilliseconds > NoticeLifeMs);
if (_tokens.Count > 32)
{
_pruneScratch.Clear();
foreach (var kv in _tokens) if (kv.Value.Until < now) _pruneScratch.Add(kv.Key);
foreach (string k in _pruneScratch) _tokens.Remove(k);
}
if (_lastHit.Count > 64)
{
_pruneScratch.Clear();
foreach (var kv in _lastHit) if ((now - kv.Value).TotalMilliseconds > HitMemoryMs) _pruneScratch.Add(kv.Key);
foreach (string k in _pruneScratch) _lastHit.Remove(k);
}
}
}

View file

@ -45,6 +45,14 @@ internal static class MoveAudit
private static string _lastKey = "";
private static long _lastWrittenMs = long.MinValue;
private static int _repeats;
// Every movement call that reached the client (a start, a stop, a turn, a held stop sent later).
private static long _movementSends;
/// <summary>Movement calls that reached the client so far: a start, a stop, a turn, or a held stop
/// sent by FlushPendingStops. Only ever grows (Reset aside); a reader compares two values to know
/// whether anything moved in between (BuffCastChain: no fast-path buff right after a movement change).</summary>
internal static long MovementSends { get { lock (Gate) return _movementSends; } }
private static string _repeatLastArg = "";
private static long _repeatFirstMs;
@ -54,7 +62,8 @@ internal static class MoveAudit
if (HeldForAction(host, who, on ? "SetAutoRun(True)" : "SetAutoRun(False)", isStop: !on, deferAs: on ? null : PendingStop.AutoRunOff())) return false;
if (on) FlushPendingStops(host, "before a start");
Note(host, who, "SetAutoRun", on ? "True" : "False", collapseByKindOnly: false);
lock (Gate) { _autoRunOn = on; if (on) _lastStartMs = NowMs(); else _pendingAutoRunOff = null; }
lock (Gate) { _autoRunOn = on; if (on) _lastStartMs = NowMs(); else _pendingAutoRunOff = null; _movementSends++; }
Changed(on ? "SetAutoRun(True)" : "SetAutoRun(False)");
return host.SetAutoRun(on);
}
@ -62,7 +71,8 @@ internal static class MoveAudit
{
if (HeldForAction(host, who, "StopCompletely()", isStop: true, deferAs: PendingStop.Complete())) return false;
Note(host, who, "StopCompletely", "", collapseByKindOnly: false);
lock (Gate) { _autoRunOn = false; _motionsOn.Clear(); ClearPendingLocked(); } // clears everything AC has on
lock (Gate) { _autoRunOn = false; _motionsOn.Clear(); ClearPendingLocked(); _movementSends++; } // clears everything AC has on
Changed("StopCompletely()");
return host.StopCompletely();
}
@ -72,7 +82,8 @@ internal static class MoveAudit
if (HeldForAction(host, who, $"SetMotion(0x{motion:X8}, {(on ? "True" : "False")})", isStop: !on, motion, on ? null : PendingStop.MotionOff(motion))) return false;
if (on) FlushPendingStops(host, "before a start");
Note(host, who, "SetMotion", $"0x{motion:X8}, {(on ? "True" : "False")}", collapseByKindOnly: false);
lock (Gate) { if (on) { _motionsOn.Add(motion); _lastStartMs = NowMs(); } else { _motionsOn.Remove(motion); _pendingMotionOff.Remove(motion); } }
lock (Gate) { if (on) { _motionsOn.Add(motion); _lastStartMs = NowMs(); } else { _motionsOn.Remove(motion); _pendingMotionOff.Remove(motion); } _movementSends++; }
Changed($"SetMotion(0x{motion:X8}, {(on ? "True" : "False")})");
return host.SetMotion(motion, on);
}
@ -82,7 +93,8 @@ internal static class MoveAudit
if (HeldForAction(host, who, $"DoMovement(0x{motion:X8})", isStop: false)) return false;
FlushPendingStops(host, "before a start");
Note(host, who, "DoMovement", $"0x{motion:X8}, {speed:0.##}, {holdKey}", collapseByKindOnly: false);
lock (Gate) { _motionsOn.Add(motion); _lastStartMs = NowMs(); }
lock (Gate) { _motionsOn.Add(motion); _lastStartMs = NowMs(); _movementSends++; }
Changed($"DoMovement(0x{motion:X8})");
return host.DoMovement(motion, speed, holdKey);
}
@ -256,7 +268,7 @@ internal static class MoveAudit
if (host.HasStopCompletely)
{
host.StopCompletely();
lock (Gate) { _autoRunOn = false; _motionsOn.Clear(); _deferredStopsSent++; }
lock (Gate) { _autoRunOn = false; _motionsOn.Clear(); _deferredStopsSent++; _movementSends++; }
sent.Add($"StopCompletely() for {complete}");
}
else
@ -269,27 +281,30 @@ internal static class MoveAudit
if (autoRunOff != null)
{
host.SetAutoRun(false);
lock (Gate) { _autoRunOn = false; _deferredStopsSent++; }
lock (Gate) { _autoRunOn = false; _deferredStopsSent++; _movementSends++; }
sent.Add($"SetAutoRun(False) for {autoRunOff}");
}
foreach (var m in motionOff)
{
if (!host.HasSetMotion) break;
host.SetMotion(m.Key, false);
lock (Gate) { _motionsOn.Remove(m.Key); _deferredStopsSent++; }
lock (Gate) { _motionsOn.Remove(m.Key); _deferredStopsSent++; _movementSends++; }
sent.Add($"SetMotion(0x{m.Key:X8}, False) for {m.Value}");
}
foreach (var s in stopMovement)
{
if (!host.HasStopMovement) break;
host.StopMovement(s.Key, s.Value.holdKey);
lock (Gate) { _motionsOn.Remove(s.Key); _deferredStopsSent++; }
lock (Gate) { _motionsOn.Remove(s.Key); _deferredStopsSent++; _movementSends++; }
sent.Add($"StopMovement(0x{s.Key:X8}) for {s.Value.who}");
}
}
}
catch { }
// A held stop sent now is a movement change like any other: the settle wait applies to it.
if (sent.Count > 0) Changed(sent[sent.Count - 1]);
if (sent.Count > 0 && Enabled)
{
try { host.Log($"[Move] {PluginName} held stop(s) sent {why} after {waited} ms: {string.Join(", ", sent)}"); }
@ -331,7 +346,8 @@ internal static class MoveAudit
{
if (HeldForAction(host, who, $"StopMovement(0x{motion:X8})", isStop: true, motion, PendingStop.StopMovement(motion, holdKey))) return false;
Note(host, who, "StopMovement", $"0x{motion:X8}, {holdKey}", collapseByKindOnly: false);
lock (Gate) { _motionsOn.Remove(motion); _pendingStopMovement.Remove(motion); }
lock (Gate) { _motionsOn.Remove(motion); _pendingStopMovement.Remove(motion); _movementSends++; }
Changed($"StopMovement(0x{motion:X8})");
return host.StopMovement(motion, holdKey);
}
@ -341,6 +357,8 @@ internal static class MoveAudit
if (HeldForUse(host, who, "TurnToHeading")) return false;
if (HeldForAction(host, who, "TurnToHeading", isStop: false)) return false;
Note(host, who, "TurnToHeading", headingDegrees.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture), collapseByKindOnly: true);
Changed("TurnToHeading");
lock (Gate) _movementSends++;
return host.TurnToHeading(headingDegrees);
}
@ -400,6 +418,39 @@ internal static class MoveAudit
ClearPendingLocked();
_pendingSinceMs = 0;
_deferredStopsSent = 0;
_lastChangeMs = long.MinValue / 2;
_lastChangeWhat = "";
_movementSends = 0;
}
}
// -- Settle after a movement change -------------------------------------------------
// A Bolt VII went out in the same tick as nav's SetAutoRun(False), after nav's turns; on ACE's
// fast tick the movement packet cancelled the cast's turn and the server held the cast 40.8 s
// (ActionPacer's stuck-cast notes). After any movement call RynthAi sends (a start, a stop, a
// turn), nothing starts until MoveSettleMinMs has passed and the client's motion queue reads
// clear (GetCastBusyState), or MoveSettleMaxMs. ActionPacer.MayStart asks (not for attack repeats).
internal const long MoveSettleMinMs = 150;
internal const long MoveSettleMaxMs = 600;
private static long _lastChangeMs = long.MinValue / 2;
private static string _lastChangeWhat = "";
private static void Changed(string what)
{
lock (Gate) { _lastChangeMs = NowMs(); _lastChangeWhat = what; }
}
/// <summary>True (with why) while the last movement change has not settled.</summary>
internal static bool SettleHolds(RynthCoreHost host, out string why)
{
why = "";
long age; string what;
lock (Gate) { age = NowMs() - _lastChangeMs; what = _lastChangeWhat; }
if (age >= MoveSettleMaxMs) return false;
bool queueBusy;
try { queueBusy = host.HasGetCastBusyState && host.GetCastBusyState() != 0; } catch { queueBusy = false; }
if (age >= MoveSettleMinMs && !queueBusy) return false;
why = $"the movement change {what} sent {age} ms ago has not settled";
return true;
}
}

View file

@ -0,0 +1,189 @@
// ============================================================================
// RynthSuite - Plugins/Shared/RynthAiCombatApi.cs
// The "RynthAi.Combat" interface: lets a script plugin (RynthLua) choose the
// spell for RynthAi's next attack cast or vitals heal, while RynthAi keeps
// targeting, pacing, stance and the cast itself. Compiled into both plugins
// (linked source), so the layout and the constants can't drift between them.
//
// The exchange is polled, never a callback:
// 1. The script side calls Claim every tick for the kinds it handles (a
// lease: when it stops renewing, RynthAi goes native on its own).
// 2. When RynthAi reaches a cast choice it opens a request (a new Seq) and
// waits, holding that one cast, up to the request's deadline.
// 3. The script side sees it through Poll, decides, and answers with Decide.
// 4. RynthAi validates the answer and casts it, or (spell 0, an invalid
// answer, or no answer by the deadline) makes its own choice that tick.
//
// Rules (as RynthAi.Script, Shared/RynthAiScriptApi.cs):
// - Its own interface, so RynthAi.Script v1 (exact-version checked) and
// RynthAi.Status stay as they are.
// - Append-only: new functions go at the end, and Version goes up. New
// request fields also go at the end but do not bump Version: they are gated
// by StructSize. The caller sets CombatRequestV1.StructSize before Poll;
// RynthAi never writes past it and writes back how much it filled, so a
// reader uses an appended field only when that StructSize covers it.
// - Strings are UTF-8, NUL-terminated.
// - Call only from the plugin pump thread (OnTick), never from AC's thread or Render.
// - Every function returns safely (no exception crosses the boundary).
// - Times are Environment.TickCount64 milliseconds (one clock per process).
// ============================================================================
using System.Runtime.InteropServices;
namespace RynthCore.Plugin.Shared;
/// <summary>Constants of the "RynthAi.Combat" exchange: kinds, decision flags, lease and timeout bounds.</summary>
public static class RynthAiCombat
{
/// <summary>Kind bit: the spell of RynthAi's next attack cast (Magic mode, after its debuffs).</summary>
public const uint KindAttack = 1;
/// <summary>Kind bit: the spell of the next vitals heal (health under Heal At / Top Off HP), asked before kits.</summary>
public const uint KindHeal = 2;
/// <summary>Every kind this version knows.</summary>
public const uint KindsAll = KindAttack | KindHeal;
/// <summary>Decision flag: an area cast (ring, wall, chain): no blacklist or pending-offensive judgement on it.</summary>
public const uint FlagArea = 1;
/// <summary>
/// Decision flag: a single-target cast that is not meant to damage (a debuff, a drain, a
/// utility spell): no no-damage blacklist judgement on it. Flags are append-only; RynthAi
/// ignores bits it does not know.
/// </summary>
public const uint FlagNoJudge = 2;
/// <summary>Lease length when Claim passes 0, and its bounds (clamped).</summary>
public const uint DefaultLeaseMs = 1500;
public const uint MinLeaseMs = 500;
public const uint MaxLeaseMs = 3000;
/// <summary>How long RynthAi waits for an answer before casting its own choice (0 = default), and the bounds.</summary>
public const uint DefaultAttackTimeoutMs = 1000;
public const uint DefaultHealTimeoutMs = 750;
public const uint MinTimeoutMs = 100;
public const uint MaxTimeoutMs = 3000;
/// <summary>
/// A cast with no answer (UseDone) this long after its send is resolved with no answer (error -1).
/// The pacing's own cast limit (ActionPacer.CastMaxMs).
/// </summary>
public const long ResolveTimeoutMs = 7000;
/// <summary>Longest owner name RynthAi keeps (characters).</summary>
public const int MaxOwnerLength = 64;
/// <summary>"attack", "heal", "attack+heal" or "none".</summary>
public static string KindNames(uint kinds)
{
kinds &= KindsAll;
if (kinds == 0) return "none";
if (kinds == KindsAll) return "attack+heal";
return kinds == KindAttack ? "attack" : "heal";
}
/// <summary>A lease length within the bounds (0 = the default).</summary>
public static uint ClampLease(uint ms) => ms == 0 ? DefaultLeaseMs : ms < MinLeaseMs ? MinLeaseMs : ms > MaxLeaseMs ? MaxLeaseMs : ms;
/// <summary>A request timeout within the bounds (0 = <paramref name="fallback"/>).</summary>
public static uint ClampTimeout(uint ms, uint fallback) => ms == 0 ? fallback : ms < MinTimeoutMs ? MinTimeoutMs : ms > MaxTimeoutMs ? MaxTimeoutMs : ms;
}
/// <summary>
/// An open request, as Poll hands it out. Blittable; the caller sets StructSize to
/// sizeof(CombatRequestV1) before Poll and RynthAi fills at most that many bytes.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct CombatRequestV1
{
/// <summary>Set by the caller before Poll: the size of the struct it passes.</summary>
public uint StructSize;
/// <summary>The request's id; Decide must quote it. Never 0.</summary>
public uint Seq;
/// <summary>RynthAiCombat.KindAttack or KindHeal.</summary>
public uint Kind;
/// <summary>
/// Attack: RynthAi's locked target. Heal: RynthAi's current fight target, informational (0 when
/// none); a heal decision's target 0 still means the player.
/// </summary>
public uint TargetId;
/// <summary>That target's health, 0..1; -1 unknown or no target.</summary>
public float TargetHealth;
/// <summary>The player's vitals in percent; -1 unknown.</summary>
public int HealthPct;
public int StaminaPct;
public int ManaPct;
/// <summary>Heal: the health line it is under (Heal At in combat, Top Off HP idle). Attack: 0.</summary>
public int HealLine;
/// <summary>1 when a monster is engaged or within Monster Range.</summary>
public int InCombat;
/// <summary>AC's combat mode (1 NonCombat, 2 Melee, 4 Missile, 8 Magic).</summary>
public int CombatMode;
/// <summary>When the request was opened, and when RynthAi stops waiting for it.</summary>
public long IssuedAtMs;
public long DeadlineMs;
/// <summary>The last decision of this kind RynthAi consumed: its Seq, the spell cast (0 = declined or rejected), the target and when.</summary>
public uint LastSeq;
public uint LastSpell;
public uint LastTarget;
public long LastAtMs;
// Appended fields (present only when the StructSize RynthAi wrote back covers them; an older
// RynthAi does not). A cast of this kind is IN FLIGHT from its send until its answer, the first
// UseDone after the send, and RESOLVED after it. Declines and rejects are not casts.
/// <summary>The most recent resolved cast: Seq of its request, spell, target, send time (0s before the first).</summary>
public uint ResolvedSeq;
public uint ResolvedSpell;
public uint ResolvedTarget;
public long ResolvedAtMs;
/// <summary>
/// Its answer, final: the UseDone error (0 = done, 0x1D = refused 'too busy', 0x401 = not enough
/// mana, 0x402 = fizzled, ...); -1 = no answer could be read: no UseDone within
/// RynthAiCombat.ResolveTimeoutMs of the send, or another answer came first.
/// </summary>
public int ResolvedErr;
/// <summary>The cast still in flight (sent, no answer yet): Seq, spell, target, send time; Spell 0 = none.</summary>
public uint PendingSeq;
public uint PendingSpell;
public uint PendingTarget;
public long PendingAtMs;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct RynthAiCombatApiV1
{
public const string InterfaceName = "RynthAi.Combat";
public const uint InterfaceVersion = 1;
public uint Version; // InterfaceVersion of the table RynthAi filled
public uint StructSize; // sizeof(RynthAiCombatApiV1) as RynthAi built it
/// <summary>
/// Claim(kinds, leaseMs, attackTimeoutMs, healTimeoutMs, owner): take or renew the hook for
/// <c>kinds</c> (RynthAiCombat.Kind* bits) until now + leaseMs (clamped; 0 = default). Renew it
/// every tick. The kinds passed replace the ones held. Returns the kinds granted: 0 while another
/// owner's lease is live (the names compare case-sensitively).
/// </summary>
public delegate* unmanaged[Cdecl]<uint, uint, uint, uint, byte*, int> Claim;
/// <summary>Release(kinds): drop those kinds now (an open request of them is cancelled: native that tick).</summary>
public delegate* unmanaged[Cdecl]<uint, void> Release;
/// <summary>Poll(kind, request): 1 when a request of that kind is open and unanswered (filled in), else 0.</summary>
public delegate* unmanaged[Cdecl]<uint, CombatRequestV1*, int> Poll;
/// <summary>
/// Decide(seq, kind, spellId, targetId, flags): the answer to request <c>seq</c>. spellId 0 =
/// decline (RynthAi chooses); targetId 0 = the request's target (the player for a heal);
/// flags RynthAiCombat.Flag*. 1 = taken; 0 = stale (another seq, already answered, past its
/// deadline, or the kind isn't held). Taken is not cast: RynthAi still validates it.
/// </summary>
public delegate* unmanaged[Cdecl]<uint, uint, uint, uint, uint, int> Decide;
/// <summary>
/// GetScanned(ids, distances, capacity): RynthAi's current target candidates (in range,
/// attackable, line of sight), nearest first. Writes up to capacity and returns how many
/// there are in all (ids null: just the count).
/// </summary>
public delegate* unmanaged[Cdecl]<uint*, float*, int, int> GetScanned;
}

View file

@ -0,0 +1,414 @@
// ============================================================================
// RynthSuite - Plugins/Shared/SessionStats.cs
// One hunting session's numbers: experience, luminance (total, last five
// minutes, allegiance pass-up), kills, XP per kill, deaths and Radiance.
// Compiled into RynthTracker and RynthAi (linked source), so the Tracker
// panel and the Mini Remote count every number the same way (2026-10-11).
//
// Pure logic, no host: SessionStatsTracker feeds it property reads and
// events with their time, so tests can drive it.
//
// Luminance, by server:
// retail ACE lands on the character: AvailableLuminance (6) rises.
// Aelrynth the Bank mod's session totals: auto-banked (9102) adds what
// never landed, drawn (9103) takes out what the bank put on
// the character; Radiance earned is 9101.
// ACECustom every grant goes to the bank, BankedLuminance (9005), which
// the server pushes with the XP batch. AvailableLuminance only
// rises on a bank withdrawal there, so once 9005 is read its
// rises are ignored. "Deposited N luminance" and "Received N
// luminance from X" move lum into the bank without earning it:
// they are taken out of the next bank rises.
// Pass-up ACECustom never sends the allegiance counters (9013/9014).
// A vassal's pass-up lands in the bank silently, while your own
// kill and quest lum prints "You've banked N Luminance.", so
// pass-up = bank income minus that chat. Fellowship and Zone
// Share splits are silent too and fall into it.
// 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.
// ============================================================================
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.Shared;
/// <summary>One poll of the player's properties; null = not readable this poll.</summary>
internal readonly record struct SessionSample(
long? TotalXp,
long? AvailableLum,
long? BankLum,
long? AelBanked,
long? AelDrawn,
long? Radiance);
/// <summary>A session's numbers, computed once per poll for any thread to read.</summary>
internal sealed record SessionStatsView(
DateTime SessionStartUtc,
double SessionSeconds,
long Xp,
double XpPerHour,
long Lum,
double LumPerHour,
long LumLast5Min,
long LumPassUp,
double PassUpPerHour,
bool PassUpTracked,
int Kills,
double KillsPerHour,
long XpPerKill,
int Deaths,
long Rad,
double RadPerHour,
bool MaxLevel)
{
public static readonly SessionStatsView Empty =
new(DateTime.UtcNow, 0, 0, 0, 0, 0, 0, 0, 0, false, 0, 0, 0, 0, 0, 0, false);
}
/// <summary>The server's luminance chat lines that matter to the session.</summary>
internal static class SessionLumChat
{
/// <summary>"You've banked N Luminance." (ACECustom: your own kill / quest lum).</summary>
public static bool TryOwn(string? text, out long amount)
=> TryAmount(text, "You've banked ", " Luminance", out amount);
/// <summary>"Deposited N luminance" (character to bank) or "Received N luminance from X" (a transfer).</summary>
public static bool TryMovedIntoBank(string? text, out long amount)
=> TryAmount(text, "Deposited ", " luminance", out amount)
|| TryAmount(text, "Received ", " luminance from ", out amount);
// The line starts with the prefix (a player quoting it in a tell doesn't), then "1,234,567", then the suffix.
private static bool TryAmount(string? text, string prefix, string suffix, out long amount)
{
amount = 0;
if (string.IsNullOrEmpty(text)) return false;
int i = 0;
while (i < text.Length && char.IsWhiteSpace(text[i])) i++;
if (string.Compare(text, i, prefix, 0, prefix.Length, StringComparison.OrdinalIgnoreCase) != 0) return false;
i += prefix.Length;
int digits = 0;
long value = 0;
for (; i < text.Length; i++)
{
char c = text[i];
if (c == ',') continue;
if (c < '0' || c > '9') break;
if (value > (long.MaxValue - 9) / 10) return false;
value = value * 10 + (c - '0');
digits++;
}
if (digits == 0) return false;
if (string.Compare(text, i, suffix, 0, suffix.Length, StringComparison.OrdinalIgnoreCase) != 0) return false;
amount = value;
return true;
}
}
internal sealed class SessionStats
{
/// <summary>XP rises seen this long after one of your kill notices belong to it.</summary>
public const double KillWindowSec = 2.5;
/// <summary>A kill found by its corpse takes the unattributed XP of this many seconds before it.</summary>
public const double CorpseXpLookbackSec = 8.0;
/// <summary>Retail's level-275 total. Past it a character may still be earning (awakened caps).</summary>
public const long MaxLevelXp = 191_226_310_247;
/// <summary>The "Lum (5 min)" window.</summary>
public static readonly TimeSpan RecentLumWindow = TimeSpan.FromMinutes(5);
/// <summary>Recent-lum entries closer together than this share one bucket (bounded memory and save size).</summary>
private static readonly TimeSpan RecentLumBucket = TimeSpan.FromSeconds(5);
/// <summary>A deposit / transfer line whose bank rise hasn't arrived by then is forgotten.</summary>
private static readonly TimeSpan MovedIntoBankLife = TimeSpan.FromSeconds(60);
private readonly KillCounter _killCounter = new();
private DateTime _sessionStart;
private long _xpTotal, _lumTotal, _radTotal;
private int _kills, _deaths;
private bool _maxLevel;
// XP per kill counts only XP that lands just after one of YOUR kills (the killer
// notification goes only to whoever landed the killing blow), plus the XP before a kill
// found by its corpse (a multi-target spell's extra monsters, KillCounter).
private long _killXp;
private int _xpKills; // kills that closed their window (the per-kill divisor)
private int _openKills; // kills whose window is still open
private DateTime _killWindowUntil;
private readonly List<(DateTime At, long Xp)> _unattributedXp = new();
// Luminance.
private TrackerRise _xpRise, _lumRise, _radRise, _bankedRise, _drawnRise, _bankRise;
private long _lumOwn; // "You've banked" amounts, all session
private long _bankIncome; // bank rises, deposits and transfers taken out
private long _ownSinceBank; // "You've banked" amounts since the bank was first read
private long _movedIntoBank; // deposit / transfer amounts waiting for their bank rise
private DateTime _movedIntoBankUntil;
private readonly List<(DateTime At, long Amount)> _recentLum = new();
private long _recentLumSum;
public SessionStats() => Reset(DateTime.UtcNow);
public DateTime SessionStartUtc => _sessionStart;
public long XpTotal => _xpTotal;
public long LumTotal => _lumTotal;
public long LumOwn => _lumOwn;
public long RadTotal => _radTotal;
public int Kills => _kills;
public int Deaths => _deaths;
public bool MaxLevel => _maxLevel;
/// <summary>True once the ACECustom bank (9005) is read: only then can pass-up be told apart.</summary>
public bool BankTracked => _bankRise.Baseline.HasValue;
/// <summary>Silent bank income: allegiance pass-up (and fellowship / Zone Share splits).</summary>
public long LumPassUp => Math.Max(0, _bankIncome - _ownSinceBank);
/// <summary>Your kills' average XP (0 before a kill window has closed).</summary>
public long XpPerKill => _xpKills > 0 ? _killXp / _xpKills : 0;
/// <summary>A fresh session starting at <paramref name="now"/>; the next read of each property is its baseline.</summary>
public void Reset(DateTime now)
{
_sessionStart = now;
_xpTotal = _lumTotal = _radTotal = 0;
_kills = _deaths = 0;
_maxLevel = false;
_killXp = 0;
_xpKills = _openKills = 0;
_killWindowUntil = DateTime.MinValue;
_unattributedXp.Clear();
_killCounter.Reset();
_xpRise.Clear(); _lumRise.Clear(); _radRise.Clear(); _bankedRise.Clear(); _drawnRise.Clear(); _bankRise.Clear();
_lumOwn = _bankIncome = _ownSinceBank = 0;
_movedIntoBank = 0;
_movedIntoBankUntil = DateTime.MinValue;
_recentLum.Clear();
_recentLumSum = 0;
}
// ── Events ───────────────────────────────────────────────────────────────
/// <summary>The server's killer notification: you landed the killing blow.</summary>
public void OnKillNotice(string? deathMessage, DateTime now)
{
_kills++;
_openKills++;
_killWindowUntil = now.AddSeconds(KillWindowSec);
_killCounter.OnKillNotice(deathMessage, now);
}
/// <summary>A chat line: your damage lines (multi-target hits) and the luminance lines.</summary>
public void OnChat(string? text, DateTime now)
{
if (string.IsNullOrEmpty(text)) return;
if (CombatText.TryParseOutgoingHit(text, out string victim, out _))
{
_killCounter.OnHit(victim, now);
return;
}
if (SessionLumChat.TryOwn(text, out long own))
{
_lumOwn += own;
if (BankTracked) _ownSinceBank += own;
else if (!_bankedRise.Baseline.HasValue) AddLum(own, now); // no bank property yet: the line is all we have
return;
}
if (SessionLumChat.TryMovedIntoBank(text, out long moved))
{
_movedIntoBank += moved;
_movedIntoBankUntil = now + MovedIntoBankLife;
}
}
/// <summary>A corpse ("Corpse of X", X = <paramref name="monsterName"/>): counts a multi-target spell's extra kill.</summary>
public KillCounter.CorpseResult OnCorpse(string monsterName, DateTime now)
{
var result = _killCounter.OnCorpse(monsterName, now);
if (result == KillCounter.CorpseResult.Counted) CountCorpseKill(now);
return result;
}
/// <summary>The player's health reached 0.</summary>
public void OnPlayerDied() => _deaths++;
private void CountCorpseKill(DateTime now)
{
_kills++;
bool inKillWindow = _openKills > 0 && now <= _killWindowUntil;
if (inKillWindow) _openKills++; // closes with the window, its XP already in it
else _xpKills++;
for (int i = _unattributedXp.Count - 1; i >= 0; i--)
{
if ((now - _unattributedXp[i].At).TotalSeconds > CorpseXpLookbackSec) continue;
_killXp += _unattributedXp[i].Xp;
_unattributedXp.RemoveAt(i);
}
}
// ── Polling ──────────────────────────────────────────────────────────────
/// <summary>One read of the player's properties: adds what went up since the last read.</summary>
public void Sample(in SessionSample s, DateTime now)
{
bool inKillWindow = _openKills > 0 && now <= _killWindowUntil;
if (s.TotalXp is long xp && xp > 0)
{
long gained = _xpRise.Take(xp);
_xpTotal += gained;
if (inKillWindow) _killXp += gained;
else if (gained > 0)
{
_unattributedXp.RemoveAll(e => (now - e.At).TotalSeconds > CorpseXpLookbackSec);
_unattributedXp.Add((now, gained));
}
// Capped only when past retail's 275 total AND kills keep bringing nothing: an
// awakened character's cap is higher (Aelrynth), so the total alone can't say.
_maxLevel = xp >= MaxLevelXp && _xpKills >= 3 && _xpTotal == 0;
}
// Close the window once it has run out: its kills join the per-kill average.
if (_openKills > 0 && !inKillWindow)
{
_xpKills += _openKills;
_openKills = 0;
}
if (now > _movedIntoBankUntil) _movedIntoBank = 0;
long lumUp = 0;
// ACECustom's bank first, so the character rise below already knows the bank is tracked.
if (s.BankLum is long bank && bank >= 0)
{
long up = _bankRise.Take(bank);
long moved = Math.Min(up, _movedIntoBank);
_movedIntoBank -= moved;
up -= moved;
_bankIncome += up;
lumUp += up;
}
// Character luminance: the rise, minus what Aelrynth's bank put there, plus what it took
// before it landed. On ACECustom a rise is a withdrawal, not income.
long charUp = 0;
if (s.AvailableLum is long lum && lum >= 0)
{
long up = _lumRise.Take(lum);
if (!BankTracked) charUp += up;
}
if (s.AelDrawn is long drawn) charUp -= _drawnRise.Take(drawn);
if (s.AelBanked is long banked) charUp += _bankedRise.Take(banked);
if (charUp > 0) lumUp += charUp;
if (lumUp > 0) AddLum(lumUp, now);
if (s.Radiance is long rad) _radTotal += _radRise.Take(rad);
}
private void AddLum(long amount, DateTime now)
{
_lumTotal += amount;
_recentLumSum += amount;
int last = _recentLum.Count - 1;
if (last >= 0 && now - _recentLum[last].At < RecentLumBucket)
_recentLum[last] = (_recentLum[last].At, _recentLum[last].Amount + amount);
else
_recentLum.Add((now, amount));
PruneRecent(now);
}
/// <summary>Luminance earned in the last five minutes.</summary>
public long LumLast5Min(DateTime now)
{
PruneRecent(now);
return _recentLumSum;
}
private void PruneRecent(DateTime now)
{
int drop = 0;
while (drop < _recentLum.Count && now - _recentLum[drop].At > RecentLumWindow)
{
_recentLumSum -= _recentLum[drop].Amount;
drop++;
}
if (drop > 0) _recentLum.RemoveRange(0, drop);
}
// ── View ─────────────────────────────────────────────────────────────────
/// <summary>Totals and per-hour figures at <paramref name="now"/> (the clock floors at one second).</summary>
public SessionStatsView View(DateTime now)
{
double seconds = Math.Max(0, (now - _sessionStart).TotalSeconds);
double hours = Math.Max(seconds, 1) / 3600.0;
long passUp = LumPassUp;
return new SessionStatsView(
_sessionStart, seconds,
_xpTotal, _xpTotal / hours,
_lumTotal, _lumTotal / hours,
LumLast5Min(now),
passUp, passUp / hours, BankTracked,
_kills, _kills / hours,
XpPerKill,
_deaths,
_radTotal, _radTotal / hours,
_maxLevel);
}
// ── Persistence (TrackerSessionStore) ────────────────────────────────────
/// <summary>Copies the session into <paramref name="s"/> (identity fields are the caller's).</summary>
public void CaptureInto(TrackerSessionState s, DateTime now)
{
PruneRecent(now);
s.SessionStartUtcTicks = _sessionStart.Ticks;
s.XpTotal = _xpTotal;
s.LumTotal = _lumTotal;
s.RadTotal = _radTotal;
s.KillsTotal = _kills;
s.DeathsTotal = _deaths;
s.KillXp = _killXp;
s.XpKills = _xpKills;
s.OpenKills = _openKills;
s.KillWindowUntilUtcTicks = _killWindowUntil.Ticks;
s.MaxLevel = _maxLevel;
s.XpBase = _xpRise.Baseline;
s.LumBase = _lumRise.Baseline;
s.RadBase = _radRise.Baseline;
s.BankedBase = _bankedRise.Baseline;
s.DrawnBase = _drawnRise.Baseline;
s.BankLumBase = _bankRise.Baseline;
s.LumOwn = _lumOwn;
s.BankIncome = _bankIncome;
s.OwnSinceBank = _ownSinceBank;
s.RecentLum.Clear();
foreach (var (at, amount) in _recentLum) s.RecentLum.Add((at.Ticks, amount));
}
/// <summary>Carries on a saved session: the next read counts everything above the saved baselines.</summary>
public void ApplyFrom(TrackerSessionState s)
{
Reset(new DateTime(s.SessionStartUtcTicks, DateTimeKind.Utc));
_xpTotal = s.XpTotal;
_lumTotal = s.LumTotal;
_radTotal = s.RadTotal;
_kills = s.KillsTotal;
_deaths = s.DeathsTotal;
_killXp = s.KillXp;
_xpKills = s.XpKills;
_openKills = s.OpenKills; // an expired window closes on the first poll, as usual
_killWindowUntil = new DateTime(s.KillWindowUntilUtcTicks, DateTimeKind.Utc);
_maxLevel = s.MaxLevel;
_xpRise.Restore(s.XpBase);
_lumRise.Restore(s.LumBase);
_radRise.Restore(s.RadBase);
_bankedRise.Restore(s.BankedBase);
_drawnRise.Restore(s.DrawnBase);
_bankRise.Restore(s.BankLumBase);
_lumOwn = s.LumOwn;
_bankIncome = s.BankIncome;
_ownSinceBank = s.OwnSinceBank;
foreach (var (at, amount) in s.RecentLum)
{
_recentLum.Add((new DateTime(at, DateTimeKind.Utc), amount));
_recentLumSum += amount;
}
}
}

View file

@ -0,0 +1,330 @@
// ============================================================================
// 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).
//
// Threading: every call except RequestReset and View runs on the pump
// thread. RequestReset only sets a flag (any thread); View is an immutable
// record swapped in after each poll (any thread).
// ============================================================================
using System;
using System.Collections.Generic;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.Shared;
internal sealed class SessionStatsTracker
{
// The player's own Int64 properties (the engine serves them to the pump since 2026.9.29.3).
private const uint Int64TotalExperience = 1;
private const uint Int64AvailableLuminance = 6;
private const uint Int64BankedLuminance = 9005; // ACECustom bank
private const uint Int64RadianceEarned = 9101; // Aelrynth Bank mod session totals
private const uint Int64LuminanceBanked = 9102;
private const uint Int64LuminanceDrawn = 9103;
private const long PollIntervalMs = 500;
private static readonly TimeSpan SaveInterval = TimeSpan.FromSeconds(30);
// Corpses waiting for their name (the client may not have it on the create tick).
private const double CorpseNameWaitSec = 3.0;
private const int MaxPendingCorpses = 256;
private const int MaxCorpseLogLines = 40;
private readonly RynthCoreHost _host;
private readonly string _tag;
private readonly string _saveDirectory;
private readonly SessionStats _stats = new();
private readonly List<(uint Id, DateTime Seen)> _pendingCorpses = new();
private uint _playerId;
private bool _loggedIn; // between OnLoginComplete and OnLogout
private bool _active; // logged in and the session started (player id known)
private volatile bool _pendingReset;
private volatile SessionStatsView _view = SessionStatsView.Empty;
private long _nextPollMs;
private DateTime _nextSaveUtc;
private bool _saveFailedLogged;
private int _corpseLogCount;
/// <param name="tag">Log prefix, e.g. "[RynthTracker]".</param>
/// <param name="saveDirectory">This plugin's own session folder (TrackerSessionStore.DirectoryFor).</param>
public SessionStatsTracker(RynthCoreHost host, string tag, string saveDirectory)
{
_host = host;
_tag = tag;
_saveDirectory = saveDirectory;
}
/// <summary>The latest numbers (any thread). Zeros before login and after logout.</summary>
public SessionStatsView View => _view;
/// <summary>True while a session is running (pump thread).</summary>
public bool Active => _active;
/// <summary>Starts a fresh session on the next tick (any thread).</summary>
public void RequestReset() => _pendingReset = true;
// ── Lifecycle ────────────────────────────────────────────────────────────
/// <summary>
/// The engine calls OnLoginComplete on a real login AND on a freshly (re)loaded plugin while
/// already in game, so the saved file is what tells a reload from a new login. A player id
/// that isn't readable yet starts the session on the first tick that reads it.
/// </summary>
public void OnLoginComplete()
{
_loggedIn = true;
_active = false;
_playerId = _host.GetPlayerId();
if (_playerId != 0) Start();
}
/// <summary>A real logout ends the session: the next login starts fresh, never picks this up.</summary>
public void OnLogout()
{
if (_active) DeleteSavedSession();
_loggedIn = false;
_active = false;
_pendingCorpses.Clear();
_view = SessionStatsView.Empty;
_host.Log($"{_tag} Session ended.");
}
/// <summary>
/// Plugin unload (hot reload, RynthSuite update, client shutting down). Saves only while a
/// session runs, never deletes: a copy unloaded before its OnLoginComplete must not wipe the
/// save its predecessor left.
/// </summary>
public void Shutdown()
{
if (_active) SaveSession();
}
private void Start()
{
DateTime now = DateTime.UtcNow;
if (TryRestoreSession())
{
_host.Log($"{_tag} Session carried over from before the reload.");
}
else
{
_stats.Reset(now);
CleanupSavedSessions();
_host.Log($"{_tag} Session started.");
}
_active = true;
_nextSaveUtc = now + SaveInterval;
_nextPollMs = 0;
_view = _stats.View(now);
}
// ── Events (pump thread) ─────────────────────────────────────────────────
/// <summary>The server's killer notification (not chat): you landed the killing blow.</summary>
public void OnKillNotification(string? deathMessage)
{
if (_active) _stats.OnKillNotice(deathMessage, DateTime.UtcNow);
}
/// <summary>Damage lines (multi-target hits) and the luminance lines.</summary>
public void OnChatWindowText(string? text)
{
if (_active) _stats.OnChat(text, DateTime.UtcNow);
}
/// <summary>Corpses are read on the tick (their name may not be readable yet on the create).</summary>
public void OnCreateObject(uint objectId)
{
if (!_active || objectId == 0) return;
if (_pendingCorpses.Count >= MaxPendingCorpses) _pendingCorpses.RemoveAt(0);
_pendingCorpses.Add((objectId, DateTime.UtcNow));
}
public void OnDeleteObject(uint objectId)
{
for (int i = _pendingCorpses.Count - 1; i >= 0; i--)
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();
}
// ── Tick (pump thread) ───────────────────────────────────────────────────
public void Tick()
{
DateTime now = DateTime.UtcNow;
if (_pendingReset)
{
_pendingReset = false;
_stats.Reset(now);
_pendingCorpses.Clear();
_view = _active ? _stats.View(now) : SessionStatsView.Empty;
// Save the zeros now, so a reload right after a reset can't bring the old totals back.
if (_active) { SaveSession(); _nextSaveUtc = now + SaveInterval; }
_host.Log($"{_tag} Session reset.");
}
if (_loggedIn && !_active)
{
_playerId = _host.GetPlayerId();
if (_playerId == 0) return;
Start();
}
if (!_active) return;
CheckPendingCorpses(now);
long nowMs = Environment.TickCount64;
if (nowMs < _nextPollMs) return;
_nextPollMs = nowMs + PollIntervalMs;
Poll(now);
_view = _stats.View(now);
// Saved right after a poll, so totals and baselines in the file always match.
if (now >= _nextSaveUtc)
{
_nextSaveUtc = now + SaveInterval;
SaveSession();
}
}
private void Poll(DateTime now)
{
if (_playerId == 0 || !_host.HasGetObjectQuadProperty) return;
_stats.Sample(new SessionSample(
Read(Int64TotalExperience),
Read(Int64AvailableLuminance),
Read(Int64BankedLuminance),
Read(Int64LuminanceBanked),
Read(Int64LuminanceDrawn),
Read(Int64RadianceEarned)), now);
}
private long? Read(uint stype)
=> _host.TryGetObjectQuadProperty(_playerId, stype, out long value) ? value : null;
/// <summary>Reads the names of newly created objects; a "Corpse of X" goes to the kill counter.</summary>
private void CheckPendingCorpses(DateTime now)
{
if (_pendingCorpses.Count == 0) return;
if (!_host.HasGetObjectName) { _pendingCorpses.Clear(); return; }
for (int i = _pendingCorpses.Count - 1; i >= 0; i--)
{
var (id, seen) = _pendingCorpses[i];
if (!_host.TryGetObjectName(id, out string name) || string.IsNullOrEmpty(name))
{
if ((now - seen).TotalSeconds > CorpseNameWaitSec) _pendingCorpses.RemoveAt(i);
continue;
}
_pendingCorpses.RemoveAt(i);
string? monster = CombatText.CorpseOwnerName(name);
if (monster == null) continue;
var result = _stats.OnCorpse(monster, now);
if ((result == KillCounter.CorpseResult.Counted || result == KillCounter.CorpseResult.HitNotCounted)
&& _corpseLogCount < MaxCorpseLogLines)
{
_corpseLogCount++;
_host.Log(result == KillCounter.CorpseResult.Counted
? $"{_tag} Kill counted from its corpse (no kill notice): '{name}' 0x{id:X8}, hit by a multi-target spell. Kills {_stats.Kills}."
: $"{_tag} Not counted: '{name}' 0x{id:X8} - you hit it, single-target, and got no kill notice (someone else's kill?).");
}
}
}
// ── Session persistence ──────────────────────────────────────────────────
//
// Reload-gap rule: the Rise baselines are restored as saved, so the first read after a
// reload counts everything from the last save up to now, which includes what was earned
// while the plugin was unloaded. Totals and baselines are saved together after the same
// poll, so that span is counted exactly once. (Kills in the gap aren't seen, so the gap's
// XP joins the totals and XP/hour but not XP per kill.)
// The client's start time, so a new client that happens to get a closed one's process
// id never picks up its save. 0 if Windows won't say (both sides then match on id alone).
private static long? _processStartTicks;
private 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;
}
}
private void SaveSession()
{
if (_playerId == 0) return;
try
{
DateTime now = DateTime.UtcNow;
var s = new TrackerSessionState
{
ProcessId = Environment.ProcessId,
ProcessStartUtcTicks = ProcessStartTicks,
CharacterId = _playerId,
SavedUtcTicks = now.Ticks,
};
_stats.CaptureInto(s, now);
TrackerSessionStore.Save(_saveDirectory, s);
_saveFailedLogged = false;
}
catch (Exception ex)
{
// Every 30 s otherwise; one line until a save works again.
if (!_saveFailedLogged)
{
_saveFailedLogged = true;
_host.Log($"{_tag} Couldn't save the session: {ex.GetType().Name}: {ex.Message}");
}
}
}
private bool TryRestoreSession()
{
if (_playerId == 0) return false;
try
{
int pid = Environment.ProcessId;
if (!TrackerSessionStore.TryLoad(_saveDirectory, pid, _playerId, out TrackerSessionState s))
return false;
if (!TrackerSessionStore.ShouldRestore(s, pid, ProcessStartTicks, _playerId, DateTime.UtcNow))
return false;
_stats.ApplyFrom(s);
return true;
}
catch (Exception ex)
{
_host.Log($"{_tag} Couldn't read the saved session, starting fresh: {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private void DeleteSavedSession()
{
if (_playerId == 0) return;
try { TrackerSessionStore.Delete(_saveDirectory, Environment.ProcessId, _playerId); }
catch (Exception ex) { _host.Log($"{_tag} Couldn't delete the saved session: {ex.GetType().Name}: {ex.Message}"); }
}
/// <summary>A fresh session: this client's older saves (any character) and files left by clients closed long ago go.</summary>
private void CleanupSavedSessions()
{
try { TrackerSessionStore.Cleanup(_saveDirectory, Environment.ProcessId, DateTime.UtcNow); }
catch { }
}
}

View file

@ -0,0 +1,350 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace RynthCore.Plugin.Shared;
// Keeps a hunting session alive across a plugin reload (engine hot reload, RynthSuite
// update: plugins swap in place and the new copy starts from zero). The plugin saves its
// session to a small file every ~30 s and on Shutdown; the next copy picks it up in
// OnLoginComplete when it is the same client process, the same character and the save is
// recent. A real logout deletes the file, so the next login is a new session.
//
// Shared (2026-10-11): RynthTracker and RynthAi's Mini Remote both keep their session through
// SessionStatsTracker, each in its own folder (DirectoryFor), so the two never read each other's file.
//
// Dependency-free on purpose (no plugin SDK types): Tools\RynthCore.TrackerSessionTests
// compiles this file directly. Plain "key=value" lines, no System.Text.Json (plugin types
// and STJ leak across reloads).
/// <summary>How much a property went up since the last read. A drop (spending, a server-side
/// reset of a session total) only moves the baseline; the first read is the baseline.</summary>
internal struct TrackerRise
{
private long _last;
private bool _seen;
public long Take(long value)
{
long up = _seen && value > _last ? value - _last : 0;
_last = value;
_seen = true;
return up;
}
public void Clear() => _seen = false;
/// <summary>The last value read, or null before the first read.</summary>
public readonly long? Baseline => _seen ? _last : null;
/// <summary>Puts back a saved baseline: the next read counts everything above it,
/// including what was earned while the plugin was unloaded. Null = no baseline yet.</summary>
public void Restore(long? baseline)
{
_seen = baseline.HasValue;
_last = baseline ?? 0;
}
}
/// <summary>Everything a session needs to carry on after a reload. Times are UTC ticks.</summary>
internal sealed class TrackerSessionState
{
public int ProcessId;
// Process ids get reused once a client closes; the start time tells two apart.
public long ProcessStartUtcTicks;
public uint CharacterId;
public long SavedUtcTicks;
public long SessionStartUtcTicks;
public long XpTotal;
public long LumTotal;
public long RadTotal;
public int KillsTotal;
public int DeathsTotal;
public long KillXp;
public int XpKills;
public int OpenKills;
public long KillWindowUntilUtcTicks;
public bool MaxLevel;
// Rise baselines, saved together with the totals so the first read after a reload
// counts exactly what came in since this save (null = not read yet).
public long? XpBase;
public long? LumBase;
public long? RadBase;
public long? BankedBase;
public long? DrawnBase;
// Added 2026-10-11 (SessionStats). Optional in the file: a save from before them loads
// with these at their defaults instead of being thrown away.
/// <summary>ACECustom bank luminance (PropertyInt64 9005) baseline.</summary>
public long? BankLumBase;
/// <summary>Own kill / quest luminance from "You've banked N Luminance" lines.</summary>
public long LumOwn;
/// <summary>Bank luminance income (deposits and transfers taken out) since the bank was first read.</summary>
public long BankIncome;
/// <summary>Own luminance chat seen since the bank was first read (pass-up = BankIncome - this).</summary>
public long OwnSinceBank;
/// <summary>Luminance of the last five minutes, oldest first: (UTC ticks, amount).</summary>
public List<(long AtTicks, long Amount)> RecentLum = new();
}
internal static class TrackerSessionStore
{
public const string Header = "RynthTracker session v1";
/// <summary>A save older than this is a different session (or a dead client).</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 = "session-";
private const string FileSuffix = ".txt";
private static readonly CultureInfo Ic = CultureInfo.InvariantCulture;
/// <summary>One file per client process and character: another client, or another
/// character in this one, never reads it.</summary>
public static string FileName(int processId, uint characterId)
=> FilePrefix + processId.ToString(Ic) + "-" + characterId.ToString("X8", Ic) + FileSuffix;
/// <summary>RynthTracker's folder.</summary>
public static string DefaultDirectory() => DirectoryFor("tracker");
/// <summary>%LOCALAPPDATA%\RynthCore\&lt;name&gt;: one folder per plugin that keeps a session.</summary>
public static string DirectoryFor(string name)
=> Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"RynthCore", name);
// ── Format ───────────────────────────────────────────────────────────────
public static string Serialize(TrackerSessionState s)
{
var sb = new StringBuilder(512);
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, "start", s.SessionStartUtcTicks.ToString(Ic));
Line(sb, "xp", s.XpTotal.ToString(Ic));
Line(sb, "lum", s.LumTotal.ToString(Ic));
Line(sb, "rad", s.RadTotal.ToString(Ic));
Line(sb, "kills", s.KillsTotal.ToString(Ic));
Line(sb, "deaths", s.DeathsTotal.ToString(Ic));
Line(sb, "killxp", s.KillXp.ToString(Ic));
Line(sb, "xpkills", s.XpKills.ToString(Ic));
Line(sb, "openkills", s.OpenKills.ToString(Ic));
Line(sb, "killuntil", s.KillWindowUntilUtcTicks.ToString(Ic));
Line(sb, "maxlevel", s.MaxLevel ? "1" : "0");
Line(sb, "xpbase", Opt(s.XpBase));
Line(sb, "lumbase", Opt(s.LumBase));
Line(sb, "radbase", Opt(s.RadBase));
Line(sb, "bankedbase", Opt(s.BankedBase));
Line(sb, "drawnbase", Opt(s.DrawnBase));
Line(sb, "bankbase", Opt(s.BankLumBase));
Line(sb, "lumown", s.LumOwn.ToString(Ic));
Line(sb, "bankincome", s.BankIncome.ToString(Ic));
Line(sb, "ownsincebank", s.OwnSinceBank.ToString(Ic));
Line(sb, "recentlum", Recent(s.RecentLum));
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 = no
/// state (start fresh). Unknown keys are ignored so a later version can add fields.</summary>
public static bool TryParse(string? text, out TrackerSessionState state)
{
state = new TrackerSessionState();
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);
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;
map[line.Substring(0, eq)] = line.Substring(eq + 1);
}
if (!map.TryGetValue("end", out string? end) || end != "1") return false;
var s = state;
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, "start", out s.SessionStartUtcTicks) &&
Long(map, "xp", out s.XpTotal) &&
Long(map, "lum", out s.LumTotal) &&
Long(map, "rad", out s.RadTotal) &&
Int(map, "kills", out s.KillsTotal) &&
Int(map, "deaths", out s.DeathsTotal) &&
Long(map, "killxp", out s.KillXp) &&
Int(map, "xpkills", out s.XpKills) &&
Int(map, "openkills", out s.OpenKills) &&
Long(map, "killuntil", out s.KillWindowUntilUtcTicks) &&
Bool(map, "maxlevel", out s.MaxLevel) &&
OptLong(map, "xpbase", out s.XpBase) &&
OptLong(map, "lumbase", out s.LumBase) &&
OptLong(map, "radbase", out s.RadBase) &&
OptLong(map, "bankedbase", out s.BankedBase) &&
OptLong(map, "drawnbase", out s.DrawnBase) &&
// The 2026-10-11 keys may be absent (older save), never malformed.
(!map.ContainsKey("bankbase") || OptLong(map, "bankbase", out s.BankLumBase)) &&
(!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));
if (!ok) return false;
// Ticks outside DateTime's range would throw when the plugin builds a DateTime.
if (!ValidTicks(s.SavedUtcTicks) || !ValidTicks(s.SessionStartUtcTicks) || !ValidTicks(s.KillWindowUntilUtcTicks))
return false;
return true;
}
/// <summary>Carry the saved session on only for the same client process (id and start
/// time) and character, and only when the save is recent. 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(TrackerSessionState 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;
TimeSpan age = nowUtc - new DateTime(s.SavedUtcTicks, DateTimeKind.Utc);
if (age > MaxAge || age < TimeSpan.FromMinutes(-1)) return false;
if (s.SessionStartUtcTicks > s.SavedUtcTicks) return false;
return true;
}
// ── Files ────────────────────────────────────────────────────────────────
/// <summary>Writes to a temp file and swaps it in, so a crash mid-write leaves the last
/// good save (or nothing), never a half file.</summary>
public static void Save(string directory, TrackerSessionState 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 TrackerSessionState state)
{
state = new TrackerSessionState();
string path = Path.Combine(directory, FileName(processId, characterId));
if (!File.Exists(path)) return false;
return TryParse(File.ReadAllText(path), out state);
}
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 (one character per client
/// at a time, so they're all over) and any file left untouched past <see cref="PurgeAge"/>
/// by a client that has since closed. Returns how many files 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;
}
// ── Helpers ──────────────────────────────────────────────────────────────
private static void Line(StringBuilder sb, string key, string value)
=> sb.Append(key).Append('=').Append(value).Append('\n');
private static string Opt(long? v) => v.HasValue ? v.Value.ToString(Ic) : "-";
// "ticks:amount;ticks:amount", or "-" for none.
private static string Recent(List<(long AtTicks, long Amount)> entries)
{
if (entries.Count == 0) return "-";
var sb = new StringBuilder(entries.Count * 28);
for (int i = 0; i < entries.Count; i++)
{
if (i > 0) sb.Append(';');
sb.Append(entries[i].AtTicks.ToString(Ic)).Append(':').Append(entries[i].Amount.ToString(Ic));
}
return sb.ToString();
}
private static bool ParseRecent(string text, List<(long AtTicks, long Amount)> into)
{
into.Clear();
if (text == "-") return true;
foreach (string part in text.Split(';'))
{
int colon = part.IndexOf(':');
if (colon <= 0) return false;
if (!long.TryParse(part.AsSpan(0, colon), NumberStyles.None, Ic, out long at) || !ValidTicks(at)) return false;
if (!long.TryParse(part.AsSpan(colon + 1), NumberStyles.AllowLeadingSign, Ic, out long amount)) return false;
into.Add((at, amount));
}
return true;
}
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);
}
private static bool Bool(Dictionary<string, string> m, string k, out bool v)
{
v = false;
if (!m.TryGetValue(k, out string? s)) return false;
if (s == "1") { v = true; return true; }
return s == "0";
}
private static bool OptLong(Dictionary<string, string> m, string k, out long? v)
{
v = null;
if (!m.TryGetValue(k, out string? s)) return false;
if (s == "-") return true;
if (!long.TryParse(s, NumberStyles.AllowLeadingSign, Ic, out long x)) return false;
v = x;
return true;
}
}

View file

@ -84,6 +84,7 @@ internal static class UseAudit
_worldUseSentMs = 0;
_worldUseSeqAtSend = 0;
AfterSend = null;
WorldUseHold = null;
}
}
@ -96,6 +97,16 @@ internal static class UseAudit
Write(host, objectId, subsystem, $"BLOCKED 0x{objectId:X8} {what} macro=off auto - {why} (with the macro off nothing opens a door or corpse unless you ask)", force: true);
return false;
}
if (kind == UseKind.Auto && doorOrCorpse)
{
string? hold = null;
try { hold = WorldUseHold?.Invoke(); } catch { hold = null; }
if (!string.IsNullOrEmpty(hold))
{
Write(host, objectId, subsystem, $"HELD 0x{objectId:X8} {what} auto - {why} ({hold})", force: false);
return false;
}
}
Write(host, objectId, subsystem, $"0x{objectId:X8} {what} macro={MacroText} {KindText(kind)} - {why}", force: false);
int seqBefore = 0;
bool track = TrackWorldUses && doorOrCorpse;
@ -124,6 +135,13 @@ internal static class UseAudit
/// </summary>
public static Action<RynthCoreHost, SentUse>? AfterSend;
/// <summary>
/// Asked before an automatic door or corpse use: a reason to hold it back (nothing is sent, the
/// call returns false), or null/empty to send. RynthAi holds them while the salvage panel opens
/// (the client swallows the use then). A use the player asked for is never held. Cleared by Reset.
/// </summary>
public static Func<string?>? WorldUseHold;
// ── A door or corpse use the server hasn't answered yet (2026-10-06) ──────────
// The server walks/turns the character to a used door or corpse, and any movement packet
// from the client cancels that (ACE: a MoveToState stops the move-to chain, and a combat