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

@ -1,188 +0,0 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthTracker;
/// <summary>
/// Counts your kills, including the extra monsters a ring, wall, blast or chain spell kills.
///
/// 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

@ -15,13 +15,25 @@ public static unsafe class PluginExports
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
public static void Shutdown()
{
try { Runtime.Shutdown(); } // an exception out of a native export fail-fasts the client
catch { }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => RynthTrackerPlugin.NamePointer;
public static IntPtr GetName()
{
try { return RynthTrackerPlugin.NamePointer; }
catch { return IntPtr.Zero; }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => RynthTrackerPlugin.VersionPointer;
public static IntPtr GetVersion()
{
try { return RynthTrackerPlugin.VersionPointer; }
catch { return IntPtr.Zero; }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();

View file

@ -24,6 +24,11 @@
<ItemGroup>
<!-- Reading our hits out of the combat log (victim + amount); RynthAi reads the same lines. -->
<Compile Include="..\Shared\CombatText.cs" Link="Shared\CombatText.cs" />
<!-- Session stats shared with RynthAi's Mini Remote: the same numbers in both (2026-10-11). -->
<Compile Include="..\Shared\KillCounter.cs" Link="Shared\KillCounter.cs" />
<Compile Include="..\Shared\TrackerSessionStore.cs" Link="Shared\TrackerSessionStore.cs" />
<Compile Include="..\Shared\SessionStats.cs" Link="Shared\SessionStats.cs" />
<Compile Include="..\Shared\SessionStatsTracker.cs" Link="Shared\SessionStatsTracker.cs" />
</ItemGroup>
<ItemGroup>

View file

@ -1,473 +1,96 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
namespace RynthCore.Plugin.RynthTracker;
// The session's numbers come from SessionStats (Plugins\Shared), the same code RynthAi's Mini
// Remote uses, so the Tracker panel and the Mini Remote agree (0.4.0, 2026-10-11): experience,
// luminance (with ACECustom's bank and allegiance pass-up), luminance of the last five minutes,
// kills (including a multi-target spell's extra kills found by their corpses), XP per kill,
// deaths and Radiance. SessionStatsTracker reads the game and keeps the session across reloads.
public sealed class RynthTrackerPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthTracker");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.0");
private uint _playerId;
private bool _loginComplete;
private DateTime _sessionStart;
private long _xpTotal;
private long _lumTotal;
private int _killsTotal;
private int _deathsTotal;
// XP per kill counts only XP that lands just after one of YOUR kills. Kills are the
// server's killer notification, which goes only to the player who landed the killing
// blow: a fellow's kill, a summon's kill or a mob someone else finished never counts,
// and neither does the XP they bring (damage share, fellowship share, quests). That XP
// still counts toward the totals and XP/hour.
//
// 0.3.0: plus the extra monsters a ring, wall, blast or chain spell kills when the
// server sends no notification for them (chain spells on Conquest): their corpse counts
// when you hit that monster with a multi-target spell just before (KillCounter.cs).
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; // XP rises seen until then belong to those kills
private const double KillWindowSec = 2.5;
// Kill notices, our damage lines and corpses, for the kills a notice doesn't cover.
private readonly KillCounter _killCounter = new();
// Corpses waiting for their name (the client may not have it on the create tick).
private readonly List<(uint Id, DateTime Seen)> _pendingCorpses = new();
private const double CorpseNameWaitSec = 3.0;
private const int MaxPendingCorpses = 256;
// XP that landed outside any kill window: a kill found by its corpse (seconds after the
// death animation) takes the XP of the few seconds before it.
private readonly List<(DateTime At, long Xp)> _unattributedXp = new();
private const double CorpseXpLookbackSec = 8.0;
private int _corpseLogCount;
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.4.0"); // previous release: 0.3.0
private SessionStatsTracker? _session;
private int _tickCounter;
// Everything comes from the player's own properties, never from chat text:
// TotalExperience 1 and AvailableLuminance 6 (the engine serves them to the pump since
// 2026.9.29.3), and on Aelrynth the Bank mod's session totals (custom ids, 2026-09-30):
// Radiance earned, Luminance auto-banked (it never lands on the character) and
// Luminance drawn from the bank (it lands on the character but wasn't earned).
private const uint Int64TotalExperience = 1;
private const uint Int64AvailableLuminance = 6;
private const uint Int64RadianceEarned = 9101;
private const uint Int64LuminanceBanked = 9102;
private const uint Int64LuminanceDrawn = 9103;
// Retail's level-275 total. Past it a character may still be earning (awakened caps).
private const long MaxLevelXp = 191_226_310_247;
private long _radTotal;
private bool _maxLevel;
// TrackerRise (TrackerSessionStore.cs): the rise since the last read; drops only move the baseline.
private TrackerRise _xpRise, _lumRise, _radRise, _bankedRise, _drawnRise;
// Session persistence across plugin/engine reloads (TrackerSessionStore.cs). Saved every
// ~30 s and on Shutdown while logged in; restored in OnLoginComplete for the same client
// process and character within 10 minutes; deleted on a real logout.
private static readonly TimeSpan SaveInterval = TimeSpan.FromSeconds(30);
private DateTime _nextSaveUtc;
private bool _saveFailedLogged;
private string? _saveDirectory;
// Deep-audit finding #21 (2026-06-18): the RynthTrackerReset export used to
// call ResetSession() directly, which Clear()s _killedIds from the
// Avalonia UI thread (no Dispatcher hop) while the AC pump thread
// concurrently Add()s/Remove()s the same HashSet in
// OnUpdateHealth/OnDeleteObject — HashSet<uint> isn't concurrency-safe;
// a racing Clear() can throw or corrupt its internal arrays. Mirrors the
// engine's DispatchQueued* idiom: the export just sets a flag, OnTick
// (pump thread, same thread as the HashSet's other mutators) performs
// the actual reset.
private volatile bool _pendingReset;
// Written on the game thread every ~0.5s, read on the Avalonia UI thread.
// Written on the game thread every ~0.5s, read on the engine's UI thread.
// Reference reads are atomic on x86 so volatile is sufficient; no lock needed.
private volatile string _snapshot = EmptySnapshot;
private const string EmptySnapshot =
"{\"ss\":0.0,\"xt\":0,\"xh\":0,\"lt\":0,\"lh\":0,\"kt\":0,\"kh\":0.0,\"xk\":0,\"dt\":0,\"rt\":0,\"rh\":0,\"ml\":0}";
"{\"ss\":0.0,\"xt\":0,\"xh\":0,\"lt\":0,\"lh\":0,\"l5\":0,\"pt\":0,\"ph\":0,\"pk\":0,"
+ "\"kt\":0,\"kh\":0.0,\"xk\":0,\"dt\":0,\"rt\":0,\"rh\":0,\"ml\":0}";
public override int Initialize()
{
_session = new SessionStatsTracker(Host, "[RynthTracker]", TrackerSessionStore.DefaultDirectory());
Host.Log("[RynthTracker] Plugin initialized.");
return 0;
}
// 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.
public override void OnLoginComplete()
{
_playerId = Host.GetPlayerId();
if (TryRestoreSession())
{
_loginComplete = true;
_snapshot = BuildSnapshot();
Host.Log("[RynthTracker] Session carried over from before the reload.");
}
else
{
ResetSession();
_loginComplete = true;
CleanupSavedSessions();
Host.Log("[RynthTracker] Session started.");
}
_nextSaveUtc = DateTime.UtcNow + SaveInterval;
}
public override void OnLoginComplete() => _session?.OnLoginComplete();
public override void OnLogout()
{
_loginComplete = false;
// A real logout ends the session: the next login starts fresh, never picks this up.
DeleteSavedSession();
Host.Log("[RynthTracker] Session ended.");
_session?.OnLogout();
_snapshot = EmptySnapshot;
}
// Plugin unload (hot reload, RynthSuite update, client shutting down). Save only while
// logged in, never delete: a copy unloaded before its OnLoginComplete must not wipe the
// save its predecessor left.
public override void Shutdown()
{
if (_loginComplete) SaveSession();
}
public override void Shutdown() => _session?.Shutdown();
// The server's killer notification (not chat): you landed the killing blow.
public override void OnKillNotification(string? deathMessage)
{
if (!_loginComplete) return;
_killsTotal++;
_openKills++;
_killWindowUntil = DateTime.UtcNow.AddSeconds(KillWindowSec);
_killCounter.OnKillNotice(deathMessage, DateTime.UtcNow);
}
public override void OnKillNotification(string? deathMessage) => _session?.OnKillNotification(deathMessage);
// Our damage lines name each monster a spell hurt (one line per monster for rings, walls,
// blasts and chain spells): that is how a multi-target hit is recognised.
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
if (!_loginComplete) return;
if (CombatText.TryParseOutgoingHit(text, out string victim, out _))
_killCounter.OnHit(victim, DateTime.UtcNow);
}
public override void OnChatWindowText(string? text, int chatType, ref int eat) => _session?.OnChatWindowText(text);
// Corpses are read on the tick (their name may not be readable yet on the create).
public override void OnCreateObject(uint objectId)
{
if (!_loginComplete || objectId == 0) return;
if (_pendingCorpses.Count >= MaxPendingCorpses) _pendingCorpses.RemoveAt(0);
_pendingCorpses.Add((objectId, DateTime.UtcNow));
}
public override void OnCreateObject(uint objectId) => _session?.OnCreateObject(objectId);
public override void OnDeleteObject(uint objectId)
{
for (int i = _pendingCorpses.Count - 1; i >= 0; i--)
if (_pendingCorpses[i].Id == objectId) _pendingCorpses.RemoveAt(i);
}
/// <summary>Reads the names of newly created objects; a "Corpse of X" goes to the kill counter.</summary>
private void CheckPendingCorpses()
{
if (_pendingCorpses.Count == 0) return;
if (!Host.HasGetObjectName) { _pendingCorpses.Clear(); return; }
DateTime now = DateTime.UtcNow;
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 = _killCounter.OnCorpse(monster, now);
if (result == KillCounter.CorpseResult.Counted)
CountCorpseKill(now);
if ((result == KillCounter.CorpseResult.Counted || result == KillCounter.CorpseResult.HitNotCounted)
&& _corpseLogCount < 40)
{
_corpseLogCount++;
Host.Log(result == KillCounter.CorpseResult.Counted
? $"[RynthTracker] Kill counted from its corpse (no kill notice): '{name}' 0x{id:X8}, hit by a multi-target spell. Kills {_killsTotal}."
: $"[RynthTracker] Not counted: '{name}' 0x{id:X8} - you hit it, single-target, and got no kill notice (someone else's kill?).");
}
}
}
/// <summary>A kill found by its corpse: one more kill, and the XP of the seconds before it.</summary>
private void CountCorpseKill(DateTime now)
{
_killsTotal++;
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);
}
}
public override void OnDeleteObject(uint objectId) => _session?.OnDeleteObject(objectId);
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
{
if (!_loginComplete) return;
// maxHealth > 0 guards against spurious 0/0 packets during login.
if (targetId == _playerId && currentHealth == 0 && maxHealth > 0)
_deathsTotal++;
}
=> _session?.OnUpdateHealth(targetId, currentHealth, maxHealth);
public override void OnTick()
{
if (_pendingReset)
{
_pendingReset = false;
ResetSession();
// Save the zeros now, so a reload right after a reset can't bring the old totals back.
if (_loginComplete) { SaveSession(); _nextSaveUtc = DateTime.UtcNow + SaveInterval; }
Host.Log("[RynthTracker] Session reset.");
}
if (_loginComplete) CheckPendingCorpses();
var session = _session;
if (session == null) return;
session.Tick();
if (++_tickCounter < 30) return; // rebuild every ~0.5s at 60Hz
_tickCounter = 0;
if (_loginComplete) PollExperience();
_snapshot = BuildSnapshot();
// Saved right after a poll, so totals and baselines in the file always match.
if (_loginComplete && DateTime.UtcNow >= _nextSaveUtc)
{
_nextSaveUtc = DateTime.UtcNow + SaveInterval;
SaveSession();
}
}
/// <summary>Adds what experience, luminance and (on Aelrynth) Radiance went up by since the last read.</summary>
private void PollExperience()
{
if (_playerId == 0 || !Host.HasGetObjectQuadProperty) return;
bool inKillWindow = _openKills > 0 && DateTime.UtcNow <= _killWindowUntil;
if (Host.TryGetObjectQuadProperty(_playerId, Int64TotalExperience, out long xp) && xp > 0)
{
long gained = _xpRise.Take(xp);
_xpTotal += gained;
if (inKillWindow) _killXp += gained;
else if (gained > 0)
{
DateTime now = DateTime.UtcNow;
_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 (with
// whatever XP they brought, 0 at the level cap).
if (_openKills > 0 && !inKillWindow)
{
_xpKills += _openKills;
_openKills = 0;
}
// Luminance earned = the rise on the character, minus what the bank put there, plus
// what the bank took before it landed (auto-bank). Spending lowers it: only rises count.
long lumUp = Host.TryGetObjectQuadProperty(_playerId, Int64AvailableLuminance, out long lum) && lum >= 0
? _lumRise.Take(lum) : 0;
if (Host.TryGetObjectQuadProperty(_playerId, Int64LuminanceDrawn, out long drawn))
lumUp -= _drawnRise.Take(drawn);
if (Host.TryGetObjectQuadProperty(_playerId, Int64LuminanceBanked, out long banked))
lumUp += _bankedRise.Take(banked);
if (lumUp > 0) _lumTotal += lumUp;
if (Host.TryGetObjectQuadProperty(_playerId, Int64RadianceEarned, out long rad))
_radTotal += _radRise.Take(rad);
_snapshot = session.Active ? BuildSnapshot(session.View, DateTime.UtcNow) : EmptySnapshot;
}
internal string GetSnapshot() => _snapshot;
/// <summary>Called from the RynthTrackerReset export (Avalonia UI thread) —
/// just flags a reset; OnTick performs it on the pump thread.</summary>
internal void Reset() => _pendingReset = true;
/// <summary>Called from the RynthTrackerReset export (engine UI thread): just flags a reset;
/// the next OnTick performs it on the pump thread.</summary>
internal void Reset() => _session?.RequestReset();
private void ResetSession()
private static string BuildSnapshot(SessionStatsView v, DateTime now)
{
_sessionStart = DateTime.UtcNow;
_xpTotal = 0;
_lumTotal = 0;
_killsTotal = 0;
_deathsTotal = 0;
_killXp = 0;
_xpKills = 0;
_openKills = 0;
_radTotal = 0;
_killCounter.Reset();
_pendingCorpses.Clear();
_unattributedXp.Clear();
// The next read of each is the new baseline.
_xpRise.Clear(); _lumRise.Clear(); _radRise.Clear(); _bankedRise.Clear(); _drawnRise.Clear();
_snapshot = EmptySnapshot;
}
// ── 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 in neither the saved totals nor anywhere else: it is counted
// exactly once, never twice and never lost. (Kills in the gap aren't seen, since the
// kill notification went to no one, so the gap's XP joins the totals and XP/hour but not
// XP per kill.)
private string SaveDirectory => _saveDirectory ??= TrackerSessionStore.DefaultDirectory();
// 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
{
TrackerSessionStore.Save(SaveDirectory, CaptureState());
_saveFailedLogged = false;
}
catch (Exception ex)
{
// Every 30 s otherwise; one line until a save works again.
if (!_saveFailedLogged)
{
_saveFailedLogged = true;
Host.Log($"[RynthTracker] 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;
ApplyState(s);
return true;
}
catch (Exception ex)
{
Host.Log($"[RynthTracker] 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($"[RynthTracker] 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 { }
}
private TrackerSessionState CaptureState() => new()
{
ProcessId = Environment.ProcessId,
ProcessStartUtcTicks = ProcessStartTicks,
CharacterId = _playerId,
SavedUtcTicks = DateTime.UtcNow.Ticks,
SessionStartUtcTicks = _sessionStart.Ticks,
XpTotal = _xpTotal,
LumTotal = _lumTotal,
RadTotal = _radTotal,
KillsTotal = _killsTotal,
DeathsTotal = _deathsTotal,
KillXp = _killXp,
XpKills = _xpKills,
OpenKills = _openKills,
KillWindowUntilUtcTicks = _killWindowUntil.Ticks,
MaxLevel = _maxLevel,
XpBase = _xpRise.Baseline,
LumBase = _lumRise.Baseline,
RadBase = _radRise.Baseline,
BankedBase = _bankedRise.Baseline,
DrawnBase = _drawnRise.Baseline,
};
private void ApplyState(TrackerSessionState s)
{
_sessionStart = new DateTime(s.SessionStartUtcTicks, DateTimeKind.Utc);
_xpTotal = s.XpTotal;
_lumTotal = s.LumTotal;
_radTotal = s.RadTotal;
_killsTotal = s.KillsTotal;
_deathsTotal = 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);
}
private string BuildSnapshot()
{
double ss = _loginComplete ? (DateTime.UtcNow - _sessionStart).TotalSeconds : 0.0;
double hrs = ss / 3600.0;
long xpHr = hrs > 0.0 ? (long)(_xpTotal / hrs) : 0;
long lumHr = hrs > 0.0 ? (long)(_lumTotal / hrs) : 0;
double killHr = hrs > 0.0 ? _killsTotal / hrs : 0.0;
long xpKill = _xpKills > 0 ? _killXp / _xpKills : 0; // your kills only, see _killXp
long radHr = hrs > 0.0 ? (long)(_radTotal / hrs) : 0;
// The session clock runs between polls; the totals and rates are the poll's.
double ss = Math.Max(0, (now - v.SessionStartUtc).TotalSeconds);
var ic = System.Globalization.CultureInfo.InvariantCulture;
return "{\"ss\":" + ss.ToString("F1", ic)
+ ",\"xt\":" + _xpTotal
+ ",\"xh\":" + xpHr
+ ",\"lt\":" + _lumTotal
+ ",\"lh\":" + lumHr
+ ",\"kt\":" + _killsTotal
+ ",\"kh\":" + killHr.ToString("F1", ic)
+ ",\"xk\":" + xpKill
+ ",\"dt\":" + _deathsTotal
+ ",\"rt\":" + _radTotal // Radiance (Aelrynth); 0 elsewhere
+ ",\"rh\":" + radHr
+ ",\"ml\":" + (_maxLevel ? 1 : 0) // at the level cap: experience can't rise
+ ",\"xt\":" + v.Xp
+ ",\"xh\":" + (long)v.XpPerHour
+ ",\"lt\":" + v.Lum
+ ",\"lh\":" + (long)v.LumPerHour
+ ",\"l5\":" + v.LumLast5Min // luminance of the last five minutes
+ ",\"pt\":" + v.LumPassUp // allegiance pass-up (ACECustom bank)
+ ",\"ph\":" + (long)v.PassUpPerHour
+ ",\"pk\":" + (v.PassUpTracked ? 1 : 0) // 1 = the bank is read, pass-up is known
+ ",\"kt\":" + v.Kills
+ ",\"kh\":" + v.KillsPerHour.ToString("F1", ic)
+ ",\"xk\":" + v.XpPerKill // your kills only
+ ",\"dt\":" + v.Deaths
+ ",\"rt\":" + v.Rad // Radiance (Aelrynth); 0 elsewhere
+ ",\"rh\":" + (long)v.RadPerHour
+ ",\"ml\":" + (v.MaxLevel ? 1 : 0) // at the level cap: experience can't rise
+ "}";
}
}

View file

@ -1,291 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace RynthCore.Plugin.RynthTracker;
// 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.
//
// 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;
}
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;
public static string DefaultDirectory()
=> Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"RynthCore", "tracker");
// ── 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, "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);
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) : "-";
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;
}
}