Snapshot for release 2026.10.11.1 (internal d20160b)

This commit is contained in:
Tom Bohar 2026-10-11 15:00:56 -04:00
commit 504a6f080a
66 changed files with 7865 additions and 310 deletions

View file

@ -0,0 +1,98 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// RynthAi's side of the "RynthAi.Activity" interface (Shared/RynthAiActivityApi.cs): what the bot
/// is doing right now, as bits, for plugins that move items in the character's packs (RynthSort)
/// and must not land a move on top of a loot, salvage, buff, use or cast. Read only. Runs on the
/// plugin pump thread (the caller's OnTick), on the current plugin instance.
/// </summary>
internal static unsafe class ActivityInterface
{
private static RynthAiActivityApiV1* _table;
public static IntPtr Query(string iface, uint version)
{
if (iface != RynthAiActivityApiV1.InterfaceName || version == 0 || version > RynthAiActivityApiV1.InterfaceVersion) return IntPtr.Zero;
if (_table == null)
{
var t = (RynthAiActivityApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiActivityApiV1));
t->Version = RynthAiActivityApiV1.InterfaceVersion;
t->StructSize = (uint)sizeof(RynthAiActivityApiV1);
t->GetActivityFlags = &GetActivityFlags;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>Frees the table (plugin shutdown). Callers resolve it every tick.</summary>
public static void Release()
{
var t = _table;
_table = null;
if (t != null) NativeMemory.Free(t);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetActivityFlags(uint* flags)
{
try
{
if (flags == null) return 0;
*flags = 0;
RynthAiActivity? a = PluginExports.Runtime.Plugin?.CurrentActivityFlags();
if (a == null) return 0;
*flags = (uint)a.Value;
return 1;
}
catch
{
return 0;
}
}
/// <summary>The bits from RynthAi's state (pure, so the host tests check the mapping).</summary>
internal static RynthAiActivity Compose(BotActivity activity, bool macroRunning, bool corpseInHand, bool salvageBusy,
bool serverWait, bool crafting, bool autoCram)
{
RynthAiActivity f = RynthAiActivity.None;
if (macroRunning) f |= RynthAiActivity.MacroRunning;
switch (activity)
{
case BotActivity.Buffing: f |= RynthAiActivity.Buffing; break;
case BotActivity.Combat: f |= RynthAiActivity.Combat; break;
case BotActivity.Looting: f |= RynthAiActivity.Looting; break;
case BotActivity.Salvaging: f |= RynthAiActivity.Salvaging; break;
case BotActivity.Navigating: f |= RynthAiActivity.Navigating; break;
}
if (corpseInHand) f |= RynthAiActivity.Looting;
if (salvageBusy) f |= RynthAiActivity.Salvaging;
if (serverWait) f |= RynthAiActivity.ServerAction;
if (crafting) f |= RynthAiActivity.Crafting;
if (autoCram) f |= RynthAiActivity.AutoCram;
return f;
}
}
public sealed partial class RynthAiPlugin
{
/// <summary>What the bot is doing now (RynthAi.Activity); null before login.</summary>
internal RynthAiActivity? CurrentActivityFlags()
{
var st = _dashboard?.Settings;
if (st == null || !_loginComplete) return null;
bool serverWait = _busyCount > 0 || (ActionPacer.Enabled && ActionPacer.Current(Host) != null);
return ActivityInterface.Compose(
st.IsMacroRunning ? _activity : BotActivity.Idle,
st.IsMacroRunning,
corpseInHand: _openedContainerId != 0 || _targetCorpseId != 0,
salvageBusy: _salvageManager?.IsBusy == true,
serverWait: serverWait,
crafting: _missileCraftingManager?.IsCrafting == true,
autoCram: st.EnableAutocram);
}
}

View file

@ -1720,7 +1720,7 @@ public class BuffManager : IDisposable
if (_worldObjectCache == null) return false;
foreach (var rule in _settings.ConsumableRules)
if (Array.FindIndex(types, t => t.Equals(rule.Type, StringComparison.OrdinalIgnoreCase)) >= 0
&& _worldObjectCache[rule.Id] != null)
&& ConsumableLookup.Resolve(_worldObjectCache, rule) != null)
return true;
return false;
}
@ -1733,10 +1733,10 @@ public class BuffManager : IDisposable
foreach (var rule in _settings.ConsumableRules)
{
if (Array.FindIndex(types, t => t.Equals(rule.Type, StringComparison.OrdinalIgnoreCase)) < 0) continue;
if (_worldObjectCache[rule.Id] == null) continue;
if (ConsumableLookup.Resolve(_worldObjectCache, rule) is not WorldObject potion) continue;
if (HeldCastBlocksItemUse(out string heldWhy)) return VitalNo(heldWhy);
_host.Log($"[RynthAi] Vitals: drinking {rule.Name} ({rule.Type}).");
_host.UseFor(unchecked((uint)rule.Id), "Buff", $"vitals: drink {rule.Name} ({rule.Type}) from the Items list");
_host.Log($"[RynthAi] Vitals: drinking {rule.Name} ({rule.Type})" + (potion.Id != rule.Id ? " from a new stack." : "."));
_host.UseFor(unchecked((uint)potion.Id), "Buff", $"vitals: drink {rule.Name} ({rule.Type}) from the Items list");
_lastPotionAt = DateTime.Now;
_lastCastAttempt = DateTime.Now;
if (IsHealthPotionType(types)) _healLatency.HealSent(Now, rule.Name);
@ -1879,7 +1879,7 @@ public class BuffManager : IDisposable
WorldObject? kit = null;
bool fromPack = false;
foreach (var r in _settings.ConsumableRules)
if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase) && _worldObjectCache[r.Id] is WorldObject wo) { kit = wo; break; }
if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase) && ConsumableLookup.Resolve(_worldObjectCache, r) is WorldObject wo) { kit = wo; break; }
if (kit == null) { kit = BestPackHealingKit(); fromPack = true; }
if (kit == null) return VitalNo("no healing kit");
if (KitRetryWait(out string kitWait)) return VitalNo(kitWait);

View file

@ -256,9 +256,9 @@ public partial class CombatManager : IDisposable
private DateTime _targetLostScanTime = DateTime.MinValue;
private const double TARGET_SCAN_GRACE_MS = 1500.0;
// Target lock — once committed to a mob, hold it until confirmed dead/gone.
// Prevents spinning caused by target thrashing when world-filter has a transient null
// or when a second mob briefly becomes slightly closer between scan ticks.
// The locked target (see HandleCombatTrigger: with Target Lock on it is held until it dies,
// leaves Monster Range or a higher-priority monster shows up). Prevents spinning caused by
// target thrashing when the world filter has a transient null.
private int _lockedTargetId = 0;
private bool _wasMacroRunning;
@ -521,25 +521,26 @@ public partial class CombatManager : IDisposable
private DateTime _lastScanTime = DateTime.MinValue;
private const int SCAN_INTERVAL_MS = 50;
// Utility-AI target switching: every candidate is scored each tick.
// The currently-locked target gets this bonus so we don't flap on near-ties —
// an alternative must beat (locked_score + STICKINESS) to take over.
private const double TARGET_SWITCH_STICKINESS = 25.0;
// Target selection (2026-10-10): the Targeting setting (TargetSelection) ranks the
// candidates by one rule (lowest health, closest, farthest, least turning) and Target
// Lock keeps a pick until it is no longer valid. It replaced a blended utility score
// (distance + health + threat + facing, plus a stickiness and a commitment bonus for the
// incumbent), which still switched targets mid-fight. See HandleCombatTrigger.
//
// With Target Lock off, a monster must beat the incumbent by these margins under the
// Targeting rule to take over, so near-ties don't flap.
private const float MoreWoundedMargin = 0.05f; // Lowest health: 5 percentage points
private const double CloserFartherMarginM = 1.5; // Closest / Farthest: metres
private const double LessTurningMarginDeg = 20.0; // Least turning: degrees of facing change
// Extra hold applied ON TOP of stickiness once we have actually landed damage
// on the locked target — "finish what you started". Stickiness alone only
// breaks near-ties; this is what stops combat walking away from a half-dead
// mob because something undamaged wandered closer. Cleared with the rest of
// the fight state on switch/DropTarget. See HandleCombatTrigger.
private const double DAMAGE_COMMITMENT_BONUS = 20.0;
// A monster this much lower in health than the wounded target takes over (a predicted kill
// that survived). See HandleCombatTrigger.
private const float MoreWoundedMargin = 0.15f;
/// <summary>The Targeting setting's choices (LegacyUiSettings.TargetSelection).</summary>
internal enum TargetScheme { LowestHealth = 0, Closest = 1, Farthest = 2, LeastTurning = 3 }
// Monster priority is a strict tier, not a score bonus: when a monster of a higher
// Priority is in range (MonsterRange), only monsters of that Priority are candidates,
// and a lower-priority target is left for it at once. As a +5-per-level bonus it lost
// to stickiness (+25) and commitment (+20) and did "little to nothing" (2026-10-03).
// and a lower-priority target is left for it at once, Target Lock or not. As a
// +5-per-level score bonus it lost to the incumbent's bonuses and did "little to
// nothing" (2026-10-03).
// Priority comes from GetRuleForTarget (name, match expression, else the DEFAULT row),
// cached per monster for PriorityCacheMs because match expressions aren't free and
// HandleCombatTrigger runs every tick over every scanned monster.
@ -548,42 +549,36 @@ public partial class CombatManager : IDisposable
private const double PriorityCacheMs = 1000;
private int _lockedPriority;
/// <summary>How long a cast-issue commitment arm survives without damage
/// landing. Covers a projectile's flight (Force Arc confirms at a ~650ms
/// median, damage follows) without granting open-ended immunity to a target
/// that never takes damage. See the arming block in HandleCombatTrigger.</summary>
/// <summary>With Target Lock off, an attack at the locked target this recent, with no
/// damage landed since, is still on its way: no switch until it lands or this passes.
/// Covers a projectile's flight (Force Arc has ~2 s of travel; switching with a bolt in
/// the air walked away from the mob it was about to hit, 2026-09-03). See
/// <see cref="AttackInFlightAtLocked"/>.</summary>
private const double CastCommitmentWindowMs = 4000.0;
/// <summary>Ceiling on how long a target that has never taken damage may keep
/// the commitment bonus after being locked. Past this it competes on its own
/// merits again, so an unkillable or unreachable mob cannot hold the lock
/// forever — the 2026-09-05 stall, where one Olthoi absorbed 5+ hours and
/// ~3,100 casts because commitment never expired and
/// TargetNoProgressTimeoutSec defaults to 0 (disabled).</summary>
/// <summary>Ceiling on the in-flight hold: once nothing has landed on the locked target
/// for this long (since its last damage, or since the lock when it never took any), an
/// attack at it no longer holds off a switch. Without a ceiling the hold refreshes on
/// every cast, so a target that never takes damage could keep it forever (the
/// 2026-09-05 stall: one Olthoi, 5+ hours, ~3,100 casts, no damage).</summary>
private const double UndamagedCommitmentMaxMs = 15000.0;
/// <summary>When the last offensive action was issued at
/// <see cref="_lastAttackedTargetId"/>. Bounds the cast-issue commitment arm.</summary>
/// <see cref="_lastAttackedTargetId"/>. Bounds the in-flight hold.</summary>
private DateTime _lastAttackedAt = DateTime.MinValue;
// Distance (m) at which the melee-threat bonus reaches full value. The bonus
// ramps continuously to this range instead of switching on at a hard edge —
// as a step it was worth more than TARGET_SWITCH_STICKINESS, so a mob
// drifting across the line flipped the winner every tick. See ScoreCandidate.
private const double THREAT_RANGE_M = 5.0;
// Incumbent continuity across scan gaps. ScanNearbyTargets drops a target on
// a single bad LOS result or a transient miss — the candidate list has been
// observed oscillating 14<->17 entries tick to tick. HandleCombatTrigger
// scores only what is in the list, so an incumbent that blinks out scores
// NOTHING and loses to any challenger. That is the "score=gone" switch, and
// it defeats TARGET_SCAN_GRACE_MS, whose stated job is that "one bad LOS
// result or scan gap shouldn't hand control to navigation" — it protected
// the target from being DROPPED but not from being OUTSCORED while absent.
// Carry the last computed score for the grace window instead.
private double _lockedLastScore = double.MinValue;
// observed oscillating 14<->17 entries tick to tick. Picking only from what is
// in the list handed the fight to whoever was visible that tick and back again
// the next (the A->B->A flapping of 2026-09-03, logged as "score=gone"). The
// incumbent stays valid for TARGET_SCAN_GRACE_MS at its last seen values instead.
private ScannedTarget _lockedLastSeen;
private DateTime _lockedLastSeenInScan = DateTime.MinValue;
/// <summary>Tests: the clock target selection reads (scan grace, in-flight hold).</summary>
internal Func<DateTime> TargetClock { get; set; } = () => DateTime.Now;
public struct ScannedTarget
{
public int Id;
@ -594,8 +589,14 @@ public partial class CombatManager : IDisposable
}
/// <summary>List of nearby, attackable, LOS-clear creatures. Re-scanned every tick (≤50 ms).
/// Sorted by distance — selection itself is score-based via HandleCombatTrigger.</summary>
/// Sorted by distance — HandleCombatTrigger picks from it by the Targeting setting.</summary>
public IReadOnlyList<ScannedTarget> ScannedTargets => _scannedTargets;
/// <summary>Tests: replace the scan list (distances and facing angles as given).</summary>
internal void SetScannedTargetsForTests(IEnumerable<ScannedTarget> targets)
{
_scannedTargets.Clear();
_scannedTargets.AddRange(targets);
}
internal MonsterDamageStore? DamageStore => _damageStore; // per-monster pet choice (PetManager)
internal CreatureProfileStore? CreatureStore => _creatureStore; // learned resists (PetManager)
@ -1733,6 +1734,36 @@ public partial class CombatManager : IDisposable
/// consecutive misses → blacklist. Called every combat cycle and before
/// recording a new cast so the last cast is still judged.
/// </summary>
// ── No-damage casts: evidence for an intermittent report (2026-10-09) ─────────────
// A player's mage cast Nether Arc VII again and again (components used, every cast answered)
// and the target's health never moved; it comes and goes, so it can't be caught by asking
// for a dump afterwards. When the judge counts BlacklistAttempts no-damage casts in a row,
// this writes the flight recorder (the casts sent, their targets and every server answer)
// and one line with what the casts were and where things stood, before the blacklist moves on.
private string _lastOffensiveCastLine = "";
private DateTime _lastNoDamageReportAt = DateTime.MinValue;
private const double NoDamageReportGapMs = 10 * 60_000; // one report per 10 min per client
private void ReportNoDamageCasts(int tid)
{
DateTime now = DateTime.Now;
if ((now - _lastNoDamageReportAt).TotalMilliseconds < NoDamageReportGapMs) return;
_lastNoDamageReportAt = now;
try
{
int me = (int)_host.GetPlayerId();
WorldObject? t = tid != 0 ? _worldFilter[tid] : null;
double dist = me != 0 && tid != 0 ? _worldFilter.Distance(me, tid) : -1;
_host.Log($"[CombatCast] NO DAMAGE: {_consecutiveCastMisses} casts in a row at 0x{(uint)tid:X8} '{t?.Name ?? "?"}' " +
$"landed nothing (no hit, resist or evade line within {_settings.BlacklistCastSettleMs} ms each). " +
$"Last: {_lastOffensiveCastLine}; distance {dist:0.0} m, target {(t == null ? "gone from the client" : "still known")}, " +
$"active=0x{(uint)activeTargetId:X8} mode={CurrentCombatMode} busy={BusyCount} castsSinceKill={CastsSinceLastKill}. " +
"Flight recorder written (Logs/flight-*.txt).");
}
catch { }
FlightRecorderSignal.Dump(_host, $"casts with no damage at 0x{(uint)tid:X8}");
}
private void JudgePendingCast()
{
if (_pendingJudgeCastAt == DateTime.MinValue) return;
@ -1749,6 +1780,7 @@ public partial class CombatManager : IDisposable
_consecutiveCastMisses++;
if (_consecutiveCastMisses >= _settings.BlacklistAttempts)
{
if (CurrentCombatMode == CombatMode.Magic) ReportNoDamageCasts(tid);
_blacklistManager.ReportFailure(tid);
if (_blacklistManager.IsBlacklisted(tid))
{
@ -1802,7 +1834,7 @@ public partial class CombatManager : IDisposable
/// "N real attacks with no damage" for casts, missile shots, and melee
/// swings alike — never raw interval ticks.
/// </summary>
private void RecordOffensiveCast(int targetId)
internal void RecordOffensiveCast(int targetId) // internal for tests
{
if (_lastAttackedTargetId != targetId)
{
@ -1813,10 +1845,10 @@ public partial class CombatManager : IDisposable
}
// Stamped on EVERY offensive action, not just a target change, so the
// cast-issue commitment window tracks the most recent cast. Stamping only
// on change would expire commitment mid-fight while still casting at the
// same mob — reintroducing the in-flight abandonment this exists to stop.
_lastAttackedAt = DateTime.Now;
// in-flight hold (Target Lock off, AttackInFlightAtLocked) tracks the most
// recent cast. Stamping only on change would end the hold mid-fight while
// still casting at the same mob — the in-flight abandonment it exists to stop.
_lastAttackedAt = TargetClock(); // DateTime.Now outside tests
JudgePendingCast(); // verdict on the prior attack if its settle window elapsed
@ -1857,7 +1889,7 @@ public partial class CombatManager : IDisposable
_returnToPhysicalCombat = false;
_targetLockedAt = DateTime.MinValue;
_lastDamageDealtAt = DateTime.MinValue;
_lockedLastScore = double.MinValue;
_lockedLastSeen = default;
_lockedLastSeenInScan = DateTime.MinValue;
_targetLostScanTime = DateTime.MinValue;
_pendingJudgeCastAt = DateTime.MinValue;
@ -2535,8 +2567,8 @@ public partial class CombatManager : IDisposable
// the stillScanned grace period below will handle a truly dead/vanished mob.
}
// Score every candidate every tick — handles initial pick AND switching when
// a meaningfully better target appears (stickiness bonus prevents flapping).
// Pick every tick: the initial pick, and a switch when the target is no longer valid,
// a higher-priority monster is in range, or (Target Lock off) another is clearly better.
HandleCombatTrigger();
if (activeTargetId == 0)
@ -3366,18 +3398,21 @@ public partial class CombatManager : IDisposable
}
}
/// <summary>
/// Target selection, every tick. Candidates are the top monster-rule Priority among monsters
/// inside MonsterRange (or among all scanned ones when none is inside it), ranked by the
/// Targeting setting (<see cref="TargetScheme"/>). Target Lock on: a valid incumbent is kept,
/// full stop. Off: it is kept unless another candidate beats it by the scheme's margin, and
/// never while an attack at it is still in flight. A higher-priority monster in range always
/// takes over at once (the tier filter: the incumbent is no longer a candidate).
/// </summary>
public void HandleCombatTrigger()
{
// Utility-AI selection: score every visible candidate, pick the highest.
// The locked target carries a stickiness bonus so we only switch when a
// genuinely better option appears — no flapping on near-ties.
if (_scannedTargets.Count == 0) return;
int bestId = 0;
double bestScore = double.MinValue;
double heldScore = double.MinValue; // scored total for the incumbent, for the switch log
bool incumbentSeen = false;
DateTime now = TargetClock();
double acquireRange = Math.Max(1.0, _settings.MonsterRange);
var scheme = (TargetScheme)Math.Clamp(_settings.TargetSelection, 0, 3);
// Strict priority: the highest Priority among monsters inside MonsterRange (or among
// all scanned ones when none is inside it) is the only tier that may be picked.
@ -3388,149 +3423,87 @@ public partial class CombatManager : IDisposable
if (p > topAnyRange) topAnyRange = p;
if (c.Distance <= acquireRange && p > topPriority) topPriority = p;
}
if (topPriority == int.MinValue) topPriority = topAnyRange;
// Finish what you started: a target we have damaged (or whose health is known to be below
// full) is kept while it's within MonsterRange and in the top priority tier, whatever a
// closer fresh monster scores. As a score bonus (stickiness 25 + commitment 20) it lost to
// a fresh monster ~2 m closer (20 points a metre at Monster Range 5): Mob A hit twice,
// Mob B killed, back to A (2026-10-04). Only a clearly more wounded monster in range takes
// over: a predicted kill that survived. Stuck targets are still dropped by the stall
// watchdog (it suppresses them out of the scan).
int forcedId = 0;
if (_lockedTargetId != 0)
{
ScannedTarget? inc = null;
foreach (var c in _scannedTargets) if (c.Id == _lockedTargetId) { inc = c; break; }
if (inc is { } held && held.Distance <= acquireRange && PriorityOf(held.Id) >= topPriority)
{
float heldHp = _worldFilter.GetHealthRatio(held.Id);
bool wounded = _lastDamageDealtAt != DateTime.MinValue || (heldHp >= 0f && heldHp < 0.99f);
if (wounded)
{
float best = heldHp >= 0f ? heldHp : 1f;
foreach (var c in _scannedTargets)
{
if (c.Id == held.Id || c.Distance > acquireRange || PriorityOf(c.Id) < topPriority) continue;
float r = _worldFilter.GetHealthRatio(c.Id);
if (r > 0f && r < best - MoreWoundedMargin) { best = r; forcedId = c.Id; }
}
if (forcedId == 0)
{
_lockedLastSeenInScan = DateTime.Now;
return; // keep the wounded target
}
}
}
}
bool anyInRange = topPriority != int.MinValue;
if (!anyInRange) topPriority = topAnyRange;
// The best candidate by the scheme. Only monsters inside MonsterRange when any is: the
// scan holds a locked target out to DisengageDistance (MonsterRange+3 by default) so a
// lone mob at the edge doesn't flip engage/peace, not so it can hold off monsters inside
// the range the user set (2026-09-27, Olthoi swarm: a target at 5-8 m kept for over a
// minute while mobs stood at 3-5 m with Monster Range 5).
ScannedTarget best = default;
double bestKey = 0;
bool haveBest = false;
ScannedTarget? incInScan = null;
foreach (var c in _scannedTargets)
{
if (c.Id == _lockedTargetId) incInScan = c;
if (PriorityOf(c.Id) < topPriority) continue; // a higher-priority monster is in range
double s = ScoreCandidate(c);
// The incumbent keeps stickiness and commitment only inside MonsterRange. The
// scan holds a locked target out to DisengageDistance (MonsterRange+3 by default)
// so a lone mob at the edge doesn't flip engage/peace, not so it can out-score
// mobs inside the range the user set. Beyond MonsterRange it competes on its
// merits, and any reasonable in-range mob takes over. Before this a target at
// 5-8 m kept +45 and could hold off mobs at 3-5 m (2026-09-27, Olthoi swarm:
// Monster Range 5, one target kept for over a minute, never out of range).
if (c.Id == _lockedTargetId)
{
double meritScore = s;
s += TARGET_SWITCH_STICKINESS;
// Commitment: once we have COMMITTED to the locked target,
// finishing it outranks any small positional edge a fresh mob
// holds. Stickiness alone only settles near-ties — it loses to a
// full-health mob that simply walked closer, which is how the bot
// left a trail of half-dead mobs.
//
// Armed at cast ISSUE as well as on confirmed damage, because
// Force Arc has ~2s of travel time and keying only on damage
// landing left that window looking "untouched" — a 2.4-point
// margin could walk away from a mob with a bolt already in the
// air (observed 2026-09-03 02:22:45).
//
// The cast-issue arm MUST expire. The first version keyed on
// _lastAttackedTargetId alone, which is set at issue and never
// cleared while the lock holds — granting a permanent +20 on top
// of the +25 stickiness to a target that had never taken damage
// and might never take any. With TargetNoProgressTimeoutSec
// defaulting to 0 (disabled) nothing else breaks that loop: on
// 2026-09-05 the bot held one Olthoi for 5+ hours, ~3,100 casts,
// zero damage, zero kills, switches down from 126 to 3 per 4h.
//
// Bounded to the projectile flight window instead: long enough to
// cover a bolt in the air, short enough that a target which never
// takes damage returns to competing on its merits.
// Two bounds, and BOTH are needed:
// * since the last cast — covers the bolt currently in flight;
// * since the target was locked — caps how long we extend that
// courtesy to a target that has never actually taken damage.
// The second bound is the important one. Without it the window
// refreshes on every cast, so a target under continuous fire keeps
// the bonus indefinitely, which is the same permanent-immunity bug
// in a different guise.
//
// Once damage HAS landed, _lastDamageDealtAt grants commitment with
// no time bound — finishing a wounded mob is exactly the intent.
bool undamaged = _lastDamageDealtAt == DateTime.MinValue;
bool withinFlightWindow =
_lastAttackedTargetId == c.Id
&& _lastAttackedAt != DateTime.MinValue
&& (DateTime.Now - _lastAttackedAt).TotalMilliseconds <= CastCommitmentWindowMs;
bool withinUndamagedGrace =
_targetLockedAt != DateTime.MinValue
&& (DateTime.Now - _targetLockedAt).TotalMilliseconds <= UndamagedCommitmentMaxMs;
if (!undamaged || (withinFlightWindow && withinUndamagedGrace))
s += DAMAGE_COMMITMENT_BONUS;
if (c.Distance > acquireRange)
s = meritScore; // beyond MonsterRange: no stickiness, no commitment (see above)
heldScore = s;
incumbentSeen = true;
_lockedLastScore = s;
_lockedLastSeenInScan = DateTime.Now;
}
if (s > bestScore) { bestScore = s; bestId = c.Id; }
if (anyInRange && c.Distance > acquireRange) continue;
double key = SchemeKey(scheme, c);
if (!haveBest || BetterCandidate(key, c, bestKey, best)) { best = c; bestKey = key; haveBest = true; }
}
if (!haveBest) return;
// Incumbent briefly absent from the scan: keep it in the running at its
// last known score for the grace window rather than letting it score
// nothing. Without this a transient scan gap hands the fight to whoever
// happens to be visible this tick, then the next tick hands it back —
// the A->B->A flapping seen repeatedly on 2026-09-03.
if (!incumbentSeen
&& _lockedTargetId != 0
&& _lockedPriority >= topPriority
&& _lockedLastScore > double.MinValue
&& _lockedLastSeenInScan != DateTime.MinValue
&& (DateTime.Now - _lockedLastSeenInScan).TotalMilliseconds <= TARGET_SCAN_GRACE_MS)
{
heldScore = _lockedLastScore;
if (heldScore >= bestScore)
return; // incumbent still wins on its last known score — no switch
}
if (forcedId != 0) { bestId = forcedId; bestScore = double.NaN; heldScore = double.MinValue; }
if (bestId == 0 || bestId == _lockedTargetId) return;
// One line per real switch. After the scoring fixes a switch should be a
// genuine event (target died, left, or something decisively better showed
// up) — if this floods the log, selection is thrashing again and the two
// scores say by how much.
int bestPriority = PriorityOf(bestId);
// Is the incumbent still valid? In the scan (or briefly out of it, within the scan
// grace, at its last seen values), in the top tier, inside MonsterRange, not
// blacklisted or suppressed by a watchdog.
string? invalidWhy = null;
ScannedTarget inc = default;
if (_lockedTargetId != 0)
{
string held = forcedId != 0 ? "wounded, but another is more wounded"
: _lockedPriority < bestPriority ? $"priority {_lockedPriority} < {bestPriority}"
: heldScore == double.MinValue ? "gone" : heldScore.ToString("0.0");
_host.Log($"[CombatTarget] switch 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' (score={held}, {DescribeTargetPos(_lockedTargetId)}) " +
$"-> 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' (score={bestScore:0.0}, priority {bestPriority}, {DescribeTargetPos(bestId)})");
bool gone = false;
if (incInScan is { } seen)
{
inc = seen;
_lockedPriority = PriorityOf(seen.Id);
_lockedLastSeen = seen;
_lockedLastSeenInScan = now;
}
else
{
inc = _lockedLastSeen; // its priority stays the last one seen (_lockedPriority)
gone = _lockedLastSeenInScan == DateTime.MinValue || inc.Id != _lockedTargetId
|| (now - _lockedLastSeenInScan).TotalMilliseconds > TARGET_SCAN_GRACE_MS;
}
invalidWhy = gone ? "gone"
: _lockedPriority < topPriority ? $"priority {_lockedPriority} < {topPriority}"
: inc.Distance > acquireRange ? $"out of Monster Range, {inc.Distance:0.0} m"
: _blacklistManager.IsBlacklisted(_lockedTargetId) ? "blacklisted"
: _recentlyKilled.ContainsKey(_lockedTargetId) ? "suppressed"
: null;
}
string? switchWhy = null;
if (_lockedTargetId != 0 && invalidWhy == null)
{
// Target Lock on: keep it until it is no longer valid. Nothing to log.
if (_settings.TargetLock || best.Id == _lockedTargetId) return;
// Target Lock off: switch only to a clearly better one, and never with an attack
// at the incumbent still on its way.
double incKey = SchemeKey(scheme, inc);
if (incKey - bestKey < SchemeMargin(scheme)) return;
if (AttackInFlightAtLocked(now)) return;
switchWhy = $"{SchemeName(scheme)}: {DescribeSchemeValue(scheme, inc)}, another is clearly better";
}
else if (_lockedTargetId != 0)
{
if (best.Id == _lockedTargetId) return; // its own tier's only choice (e.g. alone past the range)
switchWhy = invalidWhy;
}
// One line per real switch. A switch should be a genuine event (target died, left,
// or a higher priority showed up; with the lock off, something clearly better). If
// this floods the log, selection is thrashing again.
int bestId = best.Id;
int bestPriority = PriorityOf(bestId);
string picked = $"{SchemeName(scheme)}: {DescribeSchemeValue(scheme, best)}, priority {bestPriority}, {DescribeTargetPos(bestId)}";
if (_lockedTargetId != 0)
_host.Log($"[CombatTarget] switch 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' ({switchWhy}, {DescribeTargetPos(_lockedTargetId)}) " +
$"-> 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' ({picked})");
else
_host.Log($"[CombatTarget] lock 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' (score={bestScore:0.0}, priority {bestPriority}, {DescribeTargetPos(bestId)})");
_host.Log($"[CombatTarget] lock 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' ({picked})");
// [CombatLatency]: time this engagement from the lock to its first attack.
double lockMs = Environment.TickCount64;
@ -3542,8 +3515,8 @@ public partial class CombatManager : IDisposable
_lockedPriority = bestPriority;
_targetLockedAt = DateTime.Now;
_lastDamageDealtAt = DateTime.MinValue;
_lockedLastScore = double.MinValue; // new incumbent — no carried score yet
_lockedLastSeenInScan = DateTime.MinValue;
_lockedLastSeen = best; // it was in this tick's scan: the grace covers a blink next tick
_lockedLastSeenInScan = now;
_consecutiveCastMisses = 0;
_pendingJudgeCastAt = DateTime.MinValue;
_facingTarget = false;
@ -3564,41 +3537,84 @@ public partial class CombatManager : IDisposable
// inventory selection and drops an off-thread SetSelectedObject mutation.
}
private double ScoreCandidate(in ScannedTarget c)
/// <summary>
/// A candidate's rank under <paramref name="scheme"/>: lower is better. Health that isn't
/// known (-1) counts as full. Combat is selection-free (SelectItem removed 2026-06-03), so
/// ACE pushes health only for the mob we are fighting and every other candidate reads -1;
/// reading that as 0 ("at death's door") made every untouched mob look nearly dead, and a
/// target's rank collapsed the moment we hit it and its real health arrived: pick, turn,
/// hit once, re-pick, turn again (the spin). An un-engaged mob is almost certainly at full
/// health.
/// </summary>
internal double SchemeKey(TargetScheme scheme, in ScannedTarget c) => scheme switch
{
double maxDist = Math.Max(1.0, _settings.MonsterRange);
double distScore = Math.Clamp((maxDist - c.Distance) / maxDist, 0.0, 1.0) * 100.0;
TargetScheme.LowestHealth => HealthOrFull(c.Id),
TargetScheme.Farthest => -c.Distance,
TargetScheme.LeastTurning => c.Angle,
_ => c.Distance,
};
// GetHealthRatio returns -1 for "no vitals received for this mob yet".
// Combat is selection-free (SelectItem removed 2026-06-03), so ACE only
// pushes health for the mob we are actually fighting — every other
// candidate reads -1. Math.Clamp(-1, 0, 1) folded that to 0.0, i.e. "at
// death's door", so every untouched mob collected the FULL 50-point
// wounded bonus while the mob we were burning down scored its real,
// smaller one.
//
// The nastier half: a target's score COLLAPSED by up to 45 points the
// instant we hit it and its true health finally arrived. Engaging a mob
// made it a worse choice than the untouched mob standing next to it, so
// combat was pushed off whatever it had just committed to and onto the
// next one — pick, turn, hit once, re-pick, turn again. That is the spin.
//
// Unknown health means "not engaged yet", and an un-engaged mob is almost
// certainly at full health. Score it that way.
float hpRatio = _worldFilter.GetHealthRatio(c.Id);
double hpScore = hpRatio < 0f ? 0.0 : (1.0 - Math.Clamp(hpRatio, 0f, 1f)) * 50.0;
private double HealthOrFull(int id)
{
float r = _worldFilter.GetHealthRatio(id);
return r < 0f ? 1.0 : Math.Clamp(r, 0f, 1f);
}
// Continuous ramp rather than a hard step at 3.0m. As a step this was
// worth 30 points the moment a mob crossed the line — more than
// TARGET_SWITCH_STICKINESS (25) — so a mob jittering either side of 3.0m
// could flip the winner every tick regardless of our commitment.
double threatScore = Math.Clamp((THREAT_RANGE_M - c.Distance) / THREAT_RANGE_M, 0.0, 1.0) * 30.0;
/// <summary>Ranks <paramref name="c"/> ahead of the best so far: a lower key, ties to the
/// closer one, then the lower id (so the pick is stable tick to tick).</summary>
private static bool BetterCandidate(double key, in ScannedTarget c, double bestKey, in ScannedTarget best)
{
if (key != bestKey) return key < bestKey;
if (c.Distance != best.Distance) return c.Distance < best.Distance;
return (uint)c.Id < (uint)best.Id;
}
double facingScore = (1.0 - Math.Min(1.0, c.Angle / 180.0)) * 10.0;
/// <summary>With Target Lock off, how much better (in <see cref="SchemeKey"/> units) another
/// candidate must be than the incumbent to take over.</summary>
private static double SchemeMargin(TargetScheme scheme) => scheme switch
{
TargetScheme.LowestHealth => MoreWoundedMargin,
TargetScheme.LeastTurning => LessTurningMarginDeg,
_ => CloserFartherMarginM,
};
// Monster priority is not scored here: HandleCombatTrigger only scores monsters of
// the top Priority in range (see PriorityOf), so within the field it's a constant.
return distScore + hpScore + threatScore + facingScore;
internal static string SchemeName(TargetScheme scheme) => scheme switch
{
TargetScheme.LowestHealth => "lowest health",
TargetScheme.Closest => "closest",
TargetScheme.Farthest => "farthest",
_ => "least turning",
};
private string DescribeSchemeValue(TargetScheme scheme, in ScannedTarget c)
{
switch (scheme)
{
case TargetScheme.LowestHealth:
float r = _worldFilter.GetHealthRatio(c.Id);
return r < 0f ? "health unknown (as full)" : $"health {Math.Clamp(r, 0f, 1f) * 100:0}%";
case TargetScheme.LeastTurning:
return $"turn {c.Angle:0} deg";
default:
return $"{c.Distance:0.0} m";
}
}
/// <summary>
/// True while an attack at the locked target is still on its way: issued at it within
/// <see cref="CastCommitmentWindowMs"/> with no damage landed since. Capped by
/// <see cref="UndamagedCommitmentMaxMs"/> since the last damage (or the lock, when it never
/// took any), so continuous fire at a target that never takes damage can't hold it forever.
/// Only Target Lock off asks: with the lock on nothing switches a valid target anyway.
/// </summary>
private bool AttackInFlightAtLocked(DateTime now)
{
if (_lockedTargetId == 0 || _lastAttackedTargetId != _lockedTargetId || _lastAttackedAt == DateTime.MinValue)
return false;
if ((now - _lastAttackedAt).TotalMilliseconds > CastCommitmentWindowMs) return false;
if (_lastDamageDealtAt != DateTime.MinValue && _lastDamageDealtAt >= _lastAttackedAt) return false; // it landed
DateTime progress = _lastDamageDealtAt != DateTime.MinValue ? _lastDamageDealtAt : _targetLockedAt;
return progress != DateTime.MinValue && (now - progress).TotalMilliseconds <= UndamagedCommitmentMaxMs;
}
/// <summary>The Priority of the monster rule that applies to <paramref name="id"/> (its own
@ -5178,9 +5194,10 @@ public partial class CombatManager : IDisposable
LastCombatSkipReason = "cast"; // D4 record-only: offensive cast issued this tick
// Visibility: log exactly what war/void spell we're about to cast
// (id + resolved name + element/tier/target). Diagnostic only.
_host.Log($"[CombatCast] offensive id={offensiveSpellId} " +
_lastOffensiveCastLine = $"offensive id={offensiveSpellId} " +
$"'{SpellTableStub.GetById(offensiveSpellId)?.Name}' elem={element} " +
$"shape={ShapeName(castShape)} ring={isRing} warTier={warTier} voidTier={voidTier} target='{target.Name}'");
$"shape={ShapeName(castShape)} ring={isRing} warTier={warTier} voidTier={voidTier} target='{target.Name}'";
_host.Log("[CombatCast] " + _lastOffensiveCastLine);
try
{
_host.CastSpellFor((uint)activeTargetId, offensiveSpellId, "Combat", SpellTableStub.GetById(offensiveSpellId)?.Name ?? $"spell {offensiveSpellId}");

View file

@ -0,0 +1,25 @@
using System;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// The item a Consumables rule means right now. A rule is saved with the stack it was added
/// from (its object id), and that stack disappears when it runs out: 200 Stamina Tinctures
/// used up, and the next stack was never touched until the player added it again (report
/// 2026-10-10). So: the listed stack while it is still known, else any carried item with the
/// same name. Potions, healing kits and lockpicks go through here; pets and mana stones
/// already matched by name.
/// </summary>
internal static class ConsumableLookup
{
public static WorldObject? Resolve(WorldObjectCache cache, ConsumableRule rule)
{
if (rule.Id != 0 && cache[rule.Id] is WorldObject byId) return byId;
if (string.IsNullOrWhiteSpace(rule.Name)) return null;
foreach (WorldObject wo in cache.GetInventory())
if (wo != null && wo.Name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase))
return wo;
return null;
}
}

View file

@ -1122,7 +1122,13 @@ public sealed partial class RynthAiPlugin
return trimmed.Trim();
}
private static string? ExtractCorpseKillerName(string longDesc)
/// <summary>
/// X from the "Killed by X." line of a corpse's LongDesc, or null. Only that line counts:
/// the server appends more lines ("Corpse will decay in 56s") as a corpse ages, and reading
/// them as part of the name failed the own-kill match, so late-reached own kills were
/// skipped unopened (2026-10-06, Silentkelpie). Shared with the radar's killer column.
/// </summary>
internal static string? ExtractCorpseKillerName(string? longDesc)
{
if (string.IsNullOrWhiteSpace(longDesc))
return null;
@ -1133,8 +1139,11 @@ public sealed partial class RynthAiPlugin
return null;
string remainder = longDesc[(idx + prefix.Length)..];
remainder = remainder.TrimEnd('.', ' ', '\n', '\r');
return string.IsNullOrWhiteSpace(remainder) ? null : remainder;
int lineEnd = remainder.IndexOfAny(new[] { '\r', '\n' });
if (lineEnd >= 0)
remainder = remainder[..lineEnd];
remainder = remainder.Trim().TrimEnd('.').Trim();
return remainder.Length == 0 ? null : remainder;
}
private static string GetLootOwnershipModeName(int lootOwnership)
@ -1357,6 +1366,9 @@ public sealed partial class RynthAiPlugin
// Evaluate against loot profile — pure classification, no UseObject.
bool classified = ClassifyItemAgainstProfile(item, settings, out string actionLabel, out bool isSalvage, out string ruleLabel);
// Nothing to salvage with: an item only a Salvage rule wants stays on the corpse.
bool noUst = classified && isSalvage && _salvageManager != null && !_salvageManager.HasUst();
if (noUst) { classified = false; NoteNoUstLeft(item.Name); }
// Per-item decision to the LOG, not just chat. The "Loot rule:" line
// below uses ChatLine (Host.WriteToChat), so nothing about WHY an item
@ -1372,7 +1384,7 @@ public sealed partial class RynthAiPlugin
// rule it should not. If keeps correlate with appraised=False, that
// is the cause.
LootDiag($"[LootEval] '{item.Name}' cls={item.ObjectClass} id=0x{(uint)item.Id:X8} value={item.Values(19, 0)} stack={item.Values(12, 0)} type=0x{item.Values(1, 0):X} wcid={item.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0)} appraised={hasAppraisalData} timedOut={assessTimedOut} -> " +
(classified ? $"KEEP [{actionLabel}] rule='{ruleLabel}'" : "leave"));
(classified ? $"KEEP [{actionLabel}] rule='{ruleLabel}'" : noUst ? $"leave (Salvage rule '{ruleLabel}', no UST carried)" : "leave"));
if (classified)
{
@ -1913,6 +1925,17 @@ public sealed partial class RynthAiPlugin
/// taken; actionLabel/ruleLabel are what [LootEval] logs. The looter's calls record
/// what they approve (pending sets, counters, chat); ClassifyLootItem has the preview.
/// </summary>
private long _noUstLeftSaidAt = long.MinValue / 2;
/// <summary>Says once every 5 minutes in chat that salvage items are being left for want of a UST.</summary>
private void NoteNoUstLeft(string? name)
{
long now = Environment.TickCount64;
if (now - _noUstLeftSaidAt < 5 * 60_000) return;
_noUstLeftSaidAt = now;
ChatLine($"[RynthAi] No UST in your pack: leaving salvage items on corpses (first: {name}). Carry a Ust to salvage.");
}
private bool ClassifyItemAgainstProfile(WorldObject item, LegacyUiSettings settings, out string actionLabel, out bool isSalvage, out string ruleLabel) =>
ClassifyLootItem(item, settings, preview: false, out actionLabel, out isSalvage, out ruleLabel, out _);

View file

@ -380,13 +380,16 @@ public sealed partial class RynthAiPlugin
return "no-state";
}
private ConsumableRule? FindLockpickInConsumables()
/// <summary>The first listed lockpick still carried: its own stack, else one of the same name (ConsumableLookup).</summary>
private WorldObject? FindLockpickInConsumables()
{
var settings = _dashboard?.Settings;
if (settings == null || _objectCache == null) return null;
return settings.ConsumableRules
.Where(r => r.Type.Equals("Lockpick", StringComparison.OrdinalIgnoreCase))
.FirstOrDefault(r => _objectCache[r.Id] != null);
foreach (var r in settings.ConsumableRules)
if (r.Type.Equals("Lockpick", StringComparison.OrdinalIgnoreCase)
&& ConsumableLookup.Resolve(_objectCache, r) is WorldObject pick)
return pick;
return null;
}
}

View file

@ -388,8 +388,9 @@ internal static partial class DungeonPathfinder
if (prev != null)
{
// Only the patrol looks into rooms; a path to somewhere (dunnav, a detour) doesn't.
bool revisit = i > 0 && (closed ? LooksIn(graph, rooms, lookedInto, steps[i - 1], steps[i], prev, approach) : steps[i - 1].Key == steps[i].Key);
CrossRoom(pts, graph, geo, rooms, rooms.RoomOf[steps[i].From], prev, prevCell, approach, steps[i].From, revisit);
string? why = null;
bool revisit = i > 0 && (closed ? LooksIn(graph, rooms, lookedInto, steps[i - 1], steps[i], prev, approach, out why) : steps[i - 1].Key == steps[i].Key);
CrossRoom(pts, graph, geo, rooms, rooms.RoomOf[steps[i].From], prev, prevCell, approach, steps[i].From, revisit, why);
}
else firstApproach = approach;
Append(pts, approach);
@ -402,8 +403,8 @@ internal static partial class DungeonPathfinder
if (closed && firstApproach != null && prev != null)
{
bool revisit = LooksIn(graph, rooms, lookedInto, steps[steps.Count - 1], steps[0], prev, firstApproach);
CrossRoom(pts, graph, geo, rooms, rooms.RoomOf[steps[0].From], prev, prevCell, firstApproach, steps[0].From, revisit);
bool revisit = LooksIn(graph, rooms, lookedInto, steps[steps.Count - 1], steps[0], prev, firstApproach, out string why);
CrossRoom(pts, graph, geo, rooms, rooms.RoomOf[steps[0].From], prev, prevCell, firstApproach, steps[0].From, revisit, why);
}
if (!closed && dest != null && prev != null && rooms.RoomOf.TryGetValue(destCell, out int rd))
CrossRoom(pts, graph, geo, rooms, rd, prev, prevCell, dest, destCell, revisit: false);
@ -521,13 +522,28 @@ internal static partial class DungeonPathfinder
// Once per room per lap: a hub room with many doorways was otherwise walked to its middle
// again every time the patrol passed between two of its doorways.
private static bool LooksIn(Dictionary<uint, DungeonNavNode> graph, DungeonRooms rooms, HashSet<int> lookedInto,
Step inStep, Step outStep, NavPoint entered, NavPoint leaving)
Step inStep, Step outStep, NavPoint entered, NavPoint leaving, out string why)
{
why = "cross";
if (!rooms.RoomOf.TryGetValue(outStep.From, out int r)) return false;
bool big = RoomSpreadMeters(graph, rooms.Cells[r]) >= LookInMinSpreadMeters;
bool look = (inStep.Key == outStep.Key && (big || rooms.Cells[r].Count == 1))
|| (big && NavPointYd(entered, leaving) < LookInMaxSkirtMeters);
return look && lookedInto.Add(r);
double spread = RoomSpreadMeters(graph, rooms.Cells[r]);
bool big = spread >= LookInMinSpreadMeters;
bool sameDoor = inStep.Key == outStep.Key;
double skirt = NavPointYd(entered, leaving);
bool look = (sameDoor && (big || rooms.Cells[r].Count == 1))
|| (big && skirt < LookInMaxSkirtMeters);
bool first = look && lookedInto.Add(r);
if (PointLog != null)
{
var inv = System.Globalization.CultureInfo.InvariantCulture;
string what = sameDoor && (big || rooms.Cells[r].Count == 1)
? (big ? "same-doorway,big" : "same-doorway,1-cell")
: "big,skirt" + skirt.ToString("F1", inv) + "m";
why = !look ? (sameDoor ? "cross(same-doorway,small)" : "cross(" + (big ? "big," : "small,") + "other-doorway)")
: first ? "look-in(" + what + ",spread" + spread.ToString("F0", inv) + "m)"
: "cross(already-looked-in)";
}
return first;
}
// The diagonal of the box round a room's cell origins: 0 for the pieces of one junction
@ -602,7 +618,7 @@ internal static partial class DungeonPathfinder
int prevStep = -1;
foreach (var (d, _, k) in doors)
{
var m = Tag(WorldPoint(d.X, d.Y, d.Z, !d.IsWide), "run-opening");
var m = Note(Tag(WorldPoint(d.X, d.Y, d.Z, !d.IsWide), "run-opening"), steps[k].From, steps[k].From, steps[k].To, "doorway-run");
if (prevM != null && k == prevStep + 1
&& rooms.RoomOf.TryGetValue(steps[prevStep].To, out int ra) && rooms.RoomOf.TryGetValue(steps[k].From, out int rb) && ra == rb)
PullThrough(middle, graph, geo, rooms, rooms.Cells[ra], prevM, steps[prevStep].To, m, steps[k].From);
@ -630,8 +646,8 @@ internal static partial class DungeonPathfinder
{
var (nx, ny) = d.NormalFrom(a);
narrow = !d.IsWide;
approach = Tag(DoorwayPoint(geo, rooms, a, d, -nx, -ny, narrow), "approach");
exit = Tag(DoorwayPoint(geo, rooms, b, d, nx, ny, narrow), "exit");
approach = Note(Tag(DoorwayPoint(geo, rooms, a, d, -nx, -ny, narrow), "approach"), a, a, b, "doorway");
exit = Note(Tag(DoorwayPoint(geo, rooms, b, d, nx, ny, narrow), "exit"), b, a, b, "doorway");
return true;
}
@ -639,6 +655,7 @@ internal static partial class DungeonPathfinder
double dNS = nb.NS - na.NS, dEW = nb.EW - na.EW, dZ = nb.Z - na.Z;
approach = Tag(new NavPoint { Type = NavPointType.Point, NS = na.NS + dNS * 0.3, EW = na.EW + dEW * 0.3, Z = (na.Z + dZ * 0.3) / 240.0 }, "cell-fallback");
exit = Tag(new NavPoint { Type = NavPointType.Point, NS = na.NS + dNS * 0.5, EW = na.EW + dEW * 0.5, Z = (na.Z + dZ * 0.5) / 240.0 }, "cell-fallback");
Note(approach, a, a, b, "doorway(no-opening)"); Note(exit, 0, a, b, "doorway(no-opening)");
PushOffWalls(geo, approach, RoomCells(rooms, a), CornerPushMax);
PushOffWalls(geo, exit, null, CornerPushMax); // on the line between the two rooms
return false;
@ -704,7 +721,7 @@ internal static partial class DungeonPathfinder
/// </summary>
private static void CrossRoom(List<NavPoint> pts, Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo,
DungeonRooms rooms, int room, NavPoint from, uint fromCell, NavPoint to, uint toCell,
bool revisit)
bool revisit, string? why = null)
{
var cells = rooms.Cells[room];
Trace?.Invoke($"cross room {room} ({cells.Count}) revisit={revisit} from={fromCell:X8} to={toCell:X8}");
@ -713,13 +730,18 @@ internal static partial class DungeonPathfinder
var mid = RoomMiddle(graph, geo, cells, out uint midCell);
if (mid != null)
{
int before = pts.Count;
Note(mid, midCell);
PullThrough(pts, graph, geo, rooms, cells, from, fromCell, mid, midCell);
Append(pts, mid);
PullThrough(pts, graph, geo, rooms, cells, mid, midCell, to, toCell);
NoteCrossing(pts, before, room, why ?? "look-in");
return;
}
}
int start = pts.Count;
PullThrough(pts, graph, geo, rooms, cells, from, fromCell, to, toCell);
NoteCrossing(pts, start, room, why ?? "cross");
}
internal static Action<string>? Trace;
@ -740,11 +762,11 @@ internal static partial class DungeonPathfinder
{
uint a = cellPath[i], b = cellPath[i + 1];
NavPoint corner;
if (geo.TryGetDoorway(a, b, out var d)) corner = Tag(WorldPoint(d.X, d.Y, d.Z, false), "pull-opening");
if (geo.TryGetDoorway(a, b, out var d)) corner = Note(Tag(WorldPoint(d.X, d.Y, d.Z, false), "pull-opening"), a, a, b);
else
{
var na = graph[a]; var nb = graph[b];
corner = Tag(new NavPoint { Type = NavPointType.Point, NS = (na.NS + nb.NS) * 0.5, EW = (na.EW + nb.EW) * 0.5, Z = (na.Z + nb.Z) * 0.5 / 240.0 }, "pull-midpoint");
corner = Note(Tag(new NavPoint { Type = NavPointType.Point, NS = (na.NS + nb.NS) * 0.5, EW = (na.EW + nb.EW) * 0.5, Z = (na.Z + nb.Z) * 0.5 / 240.0 }, "pull-midpoint"), a, a, b);
}
PushOffWalls(geo, corner, cells, CornerPushMax);
corners.Add(corner);
@ -861,12 +883,132 @@ internal static partial class DungeonPathfinder
/// cell-fallback.</summary>
internal static Dictionary<NavPoint, string>? KindLog;
/// <summary>Why one patrol point is where it is (diagnostics only; filled while
/// <see cref="PointLog"/> is set, never read by the route itself).</summary>
internal sealed class PatrolPointInfo
{
public string Kind = ""; // the rule that laid it (as KindLog)
public uint Cell; // the cell the rule put it in (0 = not known)
public uint OpenFrom, OpenTo; // the opening it belongs to (doorway-type points)
public int Room = -1; // the room being crossed, for points laid while crossing one
public string Why = ""; // doorway / cross / look-in reason
}
/// <summary>Set (per thread) around a route build to record a <see cref="PatrolPointInfo"/>
/// for every point laid: BuildDunPatrol's waypoint log, PatrolProof "waypoints".</summary>
[ThreadStatic] internal static Dictionary<NavPoint, PatrolPointInfo>? PointLog;
/// <summary>GetMainRouteNodes' sizes for the last build while <see cref="PointLog"/> was set.</summary>
[ThreadStatic] internal static string? MainRouteNote;
private static NavPoint Tag(NavPoint p, string kind)
{
if (KindLog != null) KindLog[p] = kind;
if (PointLog != null) Info(p).Kind = kind;
return p;
}
private static PatrolPointInfo Info(NavPoint p)
{
if (!PointLog!.TryGetValue(p, out var info)) PointLog[p] = info = new PatrolPointInfo();
return info;
}
// Records the cell (and opening) a point was laid for, when the point log is on.
private static NavPoint Note(NavPoint p, uint cell, uint openFrom = 0, uint openTo = 0, string? why = null)
{
if (PointLog == null) return p;
var info = Info(p);
info.Cell = cell;
if (openFrom != 0) { info.OpenFrom = openFrom; info.OpenTo = openTo; }
if (why != null) info.Why = why;
return p;
}
// Points added to pts from index `from` on were laid crossing `room` for `why`.
private static void NoteCrossing(List<NavPoint> pts, int from, int room, string why)
{
if (PointLog == null) return;
for (int k = Math.Max(0, from); k < pts.Count; k++)
{
var info = Info(pts[k]);
if (info.Room < 0) { info.Room = room; info.Why = why; }
}
}
/// <summary>The cell whose floor is under a point, else the nearest cell centre.</summary>
internal static uint CellAt(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry? geo, NavPoint p)
{
if (geo != null)
{
double x = DungeonGeometry.NavToWorld(p.EW), y = DungeonGeometry.NavToWorld(p.NS), z = p.Z * 240.0;
uint best = 0; double bestD = double.MaxValue;
foreach (var n in graph.Values)
{
if (!geo.OnCellFloor(n.CellId, x, y, z)) continue;
double d = Math.Abs(n.Z - z);
if (d < bestD) { bestD = d; best = n.CellId; }
}
if (best != 0) return best;
}
return NearestCell(graph, p.NS, p.EW, (float)(p.Z * 240.0));
}
/// <summary>
/// One line per patrol waypoint (index, world x/y/z, cell, room and its size, the rule that
/// laid it, the opening for doorway points, why) and a summary line, from the point log of
/// the build. Rooms are BuildRooms(graph, geo, hazards), as the builder used them.
/// Lines carry no prefix; the plugin adds "[RynthAi] DunNav-Patrol ".
/// </summary>
internal static List<string> DescribePatrol(NavRouteParser route, Dictionary<uint, DungeonNavNode> graph,
DungeonGeometry? geo, IReadOnlySet<uint>? hazards,
Dictionary<NavPoint, PatrolPointInfo>? log, int tinyMaxCells = 5)
{
var lines = new List<string>();
var rooms = geo != null ? BuildRooms(graph, geo, hazards) : null;
int tiny = 0, tinyEntered = 0, tinyLooked = 0;
var tinyRooms = new SortedDictionary<int, (int Cells, int Entered, int Looked)>();
var inv = System.Globalization.CultureInfo.InvariantCulture;
for (int i = 0; i < route.Points.Count; i++)
{
var p = route.Points[i];
PatrolPointInfo? info = null;
log?.TryGetValue(p, out info);
uint cell = info != null && info.Cell != 0 ? info.Cell : CellAt(graph, geo, p);
int room = rooms != null && rooms.RoomOf.TryGetValue(cell, out int rr) ? rr : -1;
int size = room >= 0 ? rooms!.Cells[room].Count : 0;
string kind = info?.Kind is { Length: > 0 } k ? k : "unlogged";
string why = info?.Why ?? "";
string open = "";
if (info != null && info.OpenFrom != 0)
{
string w = geo != null && geo.TryGetDoorway(info.OpenFrom, info.OpenTo, out var d)
? (d.IsWide ? " wide " : " narrow ") + d.Width.ToString("F1", inv) + "m" : "";
open = $" open {info.OpenFrom:X8}>{info.OpenTo:X8}{w}";
}
string crossed = info != null && info.Room >= 0 && info.Room != room && rooms != null
? $" crossing room {info.Room} ({rooms.Cells[info.Room].Count})" : "";
bool haz = hazards != null && hazards.Contains(cell);
lines.Add(string.Format(inv, "wp {0} ({1:F1},{2:F1},{3:F1}) cell {4:X8} room {5} ({6} cells){7} {8}{9}{10}{11}{12}",
i, DungeonGeometry.NavToWorld(p.EW), DungeonGeometry.NavToWorld(p.NS), p.Z * 240.0,
cell, room, size, haz ? " HAZARD" : "", kind, p.Doorway ? " [door]" : "", open, crossed,
why.Length > 0 ? " why=" + why : ""));
if (room >= 0 && size <= tinyMaxCells)
{
tiny++;
bool looked = why.StartsWith("look-in", StringComparison.Ordinal) && info!.Room == room;
if (looked) tinyLooked++; else tinyEntered++;
tinyRooms.TryGetValue(room, out var t);
tinyRooms[room] = (size, t.Entered + (looked ? 0 : 1), t.Looked + (looked ? 1 : 0));
}
}
string roomList = string.Join(" ", tinyRooms.Select(kv => $"{kv.Key}({kv.Value.Cells}c:{kv.Value.Entered}e/{kv.Value.Looked}l)"));
if (MainRouteNote != null) lines.Add("wp " + MainRouteNote);
lines.Add($"wp summary: {route.Points.Count} points, {rooms?.Cells.Count ?? 0} rooms, {hazards?.Count ?? 0} hazard cells; " +
$"in rooms of <= {tinyMaxCells} cells: {tiny} (entered {tinyEntered}, looked into {tinyLooked}) in {tinyRooms.Count} rooms: {roomList}");
return lines;
}
private static NavPoint WorldPoint(double wx, double wy, double wz, bool doorway) => new()
{
Type = NavPointType.Point,

View file

@ -464,6 +464,88 @@ internal static partial class DungeonPathfinder
private static HashSet<uint> GetMainRouteNodes(
Dictionary<uint, DungeonNavNode> graph, uint startCell,
IReadOnlySet<uint>? hazardCells = null)
{
var (reachable, pruned) = ReachableAndCore(graph, startCell, hazardCells);
int originalCount = reachable.Count;
// Fall back to full reachable set if pruning collapsed the graph - judged on the dungeon
// itself, not on what the hazards left. 2026-10-10, 0x6146: 3 acid cells + 35 lava-floor
// cells cut the loops (2-core 277 -> 68, under 20% of reachable), the fallback fired and
// the patrol walked into every dead-end 1-cell room. A dungeon with loops keeps its
// (smaller) 2-core around the hazards; only a dungeon that is linear without hazards, or
// a core under PatrolMinKeepNodes, falls back.
bool collapsed = pruned.Count < PatrolMinKeepNodes || pruned.Count < originalCount * PatrolMinKeepFraction;
HashSet<uint> result = pruned;
string how = "2-core used";
if (collapsed && hazardCells != null && hazardCells.Count > 0)
{
var (freeReach, freeCore) = ReachableAndCore(graph, startCell, null);
bool dungeonIsLinear = freeCore.Count < PatrolMinKeepNodes || freeCore.Count < freeReach.Count * PatrolMinKeepFraction;
if (!dungeonIsLinear)
{
// The hazards cut the loops; the rest of the dungeon hangs off them as long branches.
// Walk those, but not the short spurs (closets, 1-2 cell rooms behind a door).
result = TrimShortSpurs(graph, reachable, startCell, PatrolMaxSpurCells);
how = $"hazards cut the loops: all reachable cells but spurs of <= {PatrolMaxSpurCells} cells ({result.Count} kept)";
}
else { result = reachable; how = $"FALLBACK: patrol uses all {originalCount} reachable cells, dead ends included"; }
}
else if (collapsed) { result = reachable; how = $"FALLBACK: patrol uses all {originalCount} reachable cells, dead ends included"; }
if (PointLog != null)
MainRouteNote = $"main route from {startCell:X8}: {originalCount} reachable cells, 2-core {pruned.Count} "
+ $"({hazardCells?.Count ?? 0} hazard cells) -> " + how;
return result;
}
/// <summary>Dead-end spurs this short (cells from the tip to the first junction) are left out
/// when the hazards collapsed the 2-core.</summary>
internal const int PatrolMaxSpurCells = 3;
/// <summary>
/// <paramref name="cells"/> without every dead-end spur of at most <paramref name="maxSpur"/> cells:
/// from each tip (one walkable neighbour) walk inward through corridor cells (two neighbours)
/// to the first junction; a chain that short goes. One pass, so a long branch keeps its far end.
/// </summary>
internal static HashSet<uint> TrimShortSpurs(Dictionary<uint, DungeonNavNode> graph, HashSet<uint> cells, uint keep, int maxSpur)
{
int Degree(uint id)
{
if (!graph.TryGetValue(id, out var n)) return 0;
int d = 0;
foreach (uint nb in n.Neighbors)
if (cells.Contains(nb) && graph.TryGetValue(nb, out var o) && !IsDropEdge(n, o)) d++;
return d;
}
var drop = new HashSet<uint>();
foreach (uint tip in cells)
{
if (tip == keep || Degree(tip) != 1) continue;
var chain = new List<uint> { tip };
uint prev = 0, cur = tip;
bool shortSpur = false;
while (true)
{
uint next = 0;
foreach (uint nb in graph[cur].Neighbors)
if (nb != prev && cells.Contains(nb) && graph.TryGetValue(nb, out var o) && !IsDropEdge(graph[cur], o)) { next = nb; break; }
if (next == 0) break; // an isolated pair: leave it
int d = Degree(next);
if (d >= 3) { shortSpur = true; break; } // reached a junction
if (d <= 1 || next == keep) break; // the whole thing is a line, or runs into the start
chain.Add(next);
if (chain.Count > maxSpur) break; // long branch: keep it
prev = cur; cur = next;
}
if (shortSpur && chain.Count <= maxSpur) foreach (uint c in chain) drop.Add(c);
}
var result = new HashSet<uint>(cells);
result.ExceptWith(drop);
return result;
}
/// <summary>The cells reachable from startCell (no drops, no hazards) and their 2-core.</summary>
private static (HashSet<uint> Reachable, HashSet<uint> Core) ReachableAndCore(
Dictionary<uint, DungeonNavNode> graph, uint startCell, IReadOnlySet<uint>? hazardCells)
{
// BFS to collect all cells reachable from startCell without drops or hazards.
// The start cell is always kept (player is already standing there) even if
@ -490,7 +572,6 @@ internal static partial class DungeonPathfinder
}
}
int originalCount = reachable.Count;
var pruned = new HashSet<uint>(reachable);
// Prune to convergence: repeatedly remove every node whose effective
@ -521,12 +602,7 @@ internal static partial class DungeonPathfinder
foreach (uint id in toRemove) pruned.Remove(id);
}
// Fall back to full reachable set if pruning collapsed the graph.
if (pruned.Count < PatrolMinKeepNodes ||
pruned.Count < originalCount * PatrolMinKeepFraction)
return reachable;
return pruned;
return (reachable, pruned);
}
/// <summary>

View file

@ -14,6 +14,7 @@ internal sealed class LegacyAdvancedSettingsUi
private static readonly string[] AttackHeights = { "Low", "Medium", "High" };
private static readonly string[] NavLabelModeNames = { "Off", "Numbers", "Numbers and names" };
private static readonly string[] TargetSelectionNames = { "Lowest health", "Closest", "Farthest", "Least turning" };
private static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" };
public LegacyAdvancedSettingsUi(LegacyUiSettings settings)
@ -570,6 +571,17 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Approach Range", ref _settings.ApproachRange);
ImGui.Spacing();
ImGui.Text("Combat Targeting");
ImGui.Separator();
ImGui.SetNextItemWidth(160);
ImGui.Combo("Targeting", ref _settings.TargetSelection, TargetSelectionNames, TargetSelectionNames.Length);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Which monster to attack, among those of the highest priority inside Monster Range.\nLeast turning: the one needing the smallest turn to face. Unknown health counts as full.");
ImGui.Checkbox("Target Lock", ref _settings.TargetLock);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("On: keeps the target it picked until it dies, leaves Monster Range, or a higher-priority monster shows up.\nOff: switches whenever another monster is clearly better by the Targeting rule.");
ImGui.Spacing();
ImGui.Text("Corpse Acquisition (Yards)");
ImGui.Separator();

View file

@ -1002,6 +1002,8 @@ internal sealed class LegacyDashboardRenderer
// Ranges
MonsterRange = s.MonsterRange,
MonsterDisengageRange = s.MonsterDisengageRange,
TargetSelection = s.TargetSelection,
TargetLock = s.TargetLock,
RingRange = s.RingRange,
ApproachRange = s.ApproachRange,
CorpseApproachRangeMax = s.CorpseApproachRangeMax,
@ -1214,6 +1216,8 @@ internal sealed class LegacyDashboardRenderer
// Ranges
s.MonsterRange = p.MonsterRange;
if (p.MonsterDisengageRange >= 0) s.MonsterDisengageRange = p.MonsterDisengageRange; // -1 = not sent
if (p.TargetSelection is int targeting) s.TargetSelection = Math.Clamp(targeting, 0, 3); // absent = unchanged
if (p.TargetLock is bool targetLock) s.TargetLock = targetLock; // absent = unchanged
s.RingRange = p.RingRange;
s.ApproachRange = p.ApproachRange;
s.CorpseApproachRangeMax = p.CorpseApproachRangeMax;
@ -1652,6 +1656,8 @@ internal sealed class LegacyDashboardRenderer
dst.InfuseOthersAt = tmp.InfuseOthersAt;
dst.MonsterRange = tmp.MonsterRange;
dst.MonsterDisengageRange = tmp.MonsterDisengageRange;
dst.TargetSelection = Math.Clamp(tmp.TargetSelection, 0, 3);
dst.TargetLock = tmp.TargetLock;
dst.RingRange = tmp.RingRange;
dst.ApproachRange = tmp.ApproachRange;
dst.MinRingTargets = tmp.MinRingTargets;

View file

@ -151,6 +151,15 @@ public sealed class LegacyUiSettings
// can push a mob just past MonsterRange, dropping it and flipping to peace,
// then re-approaching — an endless engage/peace oscillation at the edge.
public int MonsterDisengageRange = 0;
// Targeting (2026-10-10): how combat ranks the monsters of the top Priority inside Monster
// Range (CombatManager.TargetScheme): 0 lowest health (unknown counts as full), 1 closest,
// 2 farthest, 3 least turning. Ties go to the closest.
public int TargetSelection;
// Target Lock: keep the picked target until it dies or goes, leaves Monster Range, is
// blacklisted or skipped by a watchdog, or a higher-priority monster is in range. Off: switch
// when another is clearly better by Targeting. On by default; a profile saved before this
// setting loads it as on.
public bool TargetLock = true;
public int RingRange = 5;
public int ApproachRange = 4;
public int MinRingTargets = 4;
@ -890,6 +899,9 @@ public sealed class SettingsBridgePayload
// Ranges
public int MonsterRange { get; set; }
public int MonsterDisengageRange { get; set; } = -1; // -1 = absent, see BlacklistCastSettleMs
// Nullable: an engine that predates them doesn't send them, and its save must leave them alone.
public int? TargetSelection { get; set; }
public bool? TargetLock { get; set; }
public int RingRange { get; set; }
public int ApproachRange { get; set; }
public double CorpseApproachRangeMax { get; set; }

View file

@ -582,13 +582,7 @@ internal sealed class RynthRadarUi
/// <summary>"Killed by X." in a corpse's LongDesc: X, or "" (read as CorpseOpenController reads it).</summary>
internal static string ExtractKiller(string? longDesc)
{
if (string.IsNullOrWhiteSpace(longDesc)) return string.Empty;
const string prefix = "Killed by ";
int idx = longDesc.IndexOf(prefix, StringComparison.OrdinalIgnoreCase);
if (idx < 0) return string.Empty;
return longDesc[(idx + prefix.Length)..].TrimEnd('.', ' ', '\n', '\r').Trim();
}
=> RynthAiPlugin.ExtractCorpseKillerName(longDesc) ?? string.Empty;
/// <summary>Without GM sigils (+, @, #): the server leaves them out of "Killed by X".</summary>
private static string NormalizeCharName(string name)

View file

@ -173,6 +173,26 @@ public sealed class SalvageManager
_cache = cache;
}
private const long HasUstCacheMs = 3000;
private long _hasUstCheckedAt = long.MinValue / 2;
private bool _hasUst;
/// <summary>
/// A UST is carried (cached 3 s; FindUst can force an inventory walk). Without one there is
/// nothing to salvage with: looting leaves items that only a Salvage rule wants, and the
/// combine sweep doesn't run (2026-10-10).
/// </summary>
public bool HasUst()
{
long now = NowMs;
if (now - _hasUstCheckedAt >= HasUstCacheMs)
{
_hasUstCheckedAt = now;
_hasUst = FindUst() != 0;
}
return _hasUst;
}
/// <summary>Returns true while a salvage operation is in flight.</summary>
public bool IsBusy => _phase != Phase.Idle || _queue.Count > 0;
@ -310,7 +330,7 @@ public sealed class SalvageManager
{
_pendingCombineScan = false;
_lastCombineSweepAt = now;
BeginCombineSalvage(now);
if (HasUst()) BeginCombineSalvage(now);
return;
}
// Periodic standalone sweep: if 30s have passed since the last
@ -323,7 +343,7 @@ public sealed class SalvageManager
&& now - _lastCombineSweepAt >= CombineSweepIntervalMs)
{
_lastCombineSweepAt = now;
BeginCombineSalvage(now);
if (HasUst()) BeginCombineSalvage(now);
}
return;
}
@ -344,6 +364,7 @@ public sealed class SalvageManager
return;
uint ustId = FindUst();
_hasUstCheckedAt = now; _hasUst = ustId != 0;
if (ustId == 0)
{
// Keep the items (they used to be dropped here for good) and look again later.

View file

@ -57,10 +57,37 @@ internal sealed class ManaStoneManager
// Stones we've positively confirmed are charged via AC chat ("is already
// full of mana"). Distinct from the cooldown so the cache's stale CurrentMana
// reading doesn't auto-clear them. Only cleared when the stone disappears
// from cache (consumed via use-on-player).
// reading doesn't auto-clear them. Cleared when the stone gives its mana away
// (see _stoneKnownEmpty below).
private readonly HashSet<int> _stoneKnownCharged = new();
// A stone's charge is read from its last appraisal, and the server never sends a change to it:
// after a stone pours its mana into worn gear the read still shows the old charge, and after a
// drain charges it the read still shows it empty (or can't be read at all). So what the server
// said about a stone since then wins over the read:
// * _stoneKnownCharged (above): "drains N points" into it, "already full of mana", or "no items
// equipped that need mana" (only said for a charged stone). It refills worn gear even when its
// charge can't be read; it never could, so a charged stone whose charge wasn't readable was
// tried as an empty stone, called charged by the server, and then never used on the gear
// (Khanda-handled Mace at 0% for over an hour with five charged stones in the pack, 2026-10-10).
// * _stoneKnownEmpty: it gave its mana ("The Mana Stone gives ..."). Value = the read at that
// moment; a different read later is a newer appraisal and supersedes the mark. Without it the
// same, now empty, stone was picked again 600 ms later (the read still said charged), the
// server cancelled the use without a word, and it timed out and was parked for 5 minutes, stone
// after stone (2026-10-08).
private readonly Dictionary<int, int?> _stoneKnownEmpty = new();
// Stones whose charge can't be read are identified (at most every 5 minutes each) so a charged one
// can refill gear with tapping off, where nothing else ever tells us it is charged.
private readonly Dictionary<int, long> _stoneIdRequestedAt = new();
private const long StoneIdRetryMs = 5 * 60 * 1000;
// The server said the worn gear is full ("Your items are fully charged." / "You have no items
// equipped that need mana."). Worn-item mana is read from appraisals too, so the gear can still read
// low; no refill for a while instead of a stone every think tick.
private long _refillHoldUntil;
private const long RefillHoldMs = 2 * 60 * 1000;
private long _lastNoStoneDiagAt;
// Worn equipment is only treated as "needs refill" when current mana drops
// below this fraction of its MaxMana. Prevents the bot from continually
// dumping stones on the player just because an item dipped slightly.
@ -74,7 +101,9 @@ internal sealed class ManaStoneManager
private const long ThinkIntervalMs = 600;
private const long ActionTimeoutMs = 8000;
private static long NowMs => Environment.TickCount64;
/// <summary>Clock (ms); tests replace it.</summary>
internal static Func<long> Clock { get; set; } = static () => Environment.TickCount64;
private static long NowMs => Clock();
/// <summary>
/// Set by the plugin: true when a Keep or Keep # rule in the active loot profile
@ -209,18 +238,31 @@ internal sealed class ManaStoneManager
|| text.Contains("is destroyed")
|| text.Contains("has been destroyed"))
{
// The stone is charged now; its read still shows it empty until it is appraised again.
if (text.Contains("The Mana Stone drains")) MarkStoneCharged(_activeStoneId);
if (_activeItemId != 0) _lootedForTap.Remove(_activeItemId); // drained and destroyed
GoIdle();
return;
}
// "The Mana Stone gives N points of mana to the X." - the stone was charged after all and
// poured its mana into the item (ACE does that for a charged stone used on an item that
// isn't full). The stone is empty now.
if (text.Contains("The Mana Stone gives"))
{
_host.Log($"[RynthAi] ManaStone: stone 0x{(uint)_activeStoneId:X8} was charged and gave its mana to the item instead - it is empty now.");
MarkStoneEmpty(_activeStoneId);
GoIdle();
return;
}
// "The X is already full of mana." — AC's response when we used a
// CHARGED stone on a non-equipped item (or a fully-loaded item). Our
// cache mis-read this stone as empty. Blacklist it for the tap path
// immediately so the next think tick picks a different stone.
if (text.Contains("is already full of mana") && _activeStoneId != 0)
{
_stoneKnownCharged.Add(_activeStoneId);
MarkStoneCharged(_activeStoneId);
_stoneTapCooldownUntil.Remove(_activeStoneId); // supersede cooldown
_host.Log($"[RynthAi] ManaStone: stone 0x{(uint)_activeStoneId:X8} is actually charged (server: 'already full') — marking known-charged.");
GoIdle();
@ -234,14 +276,62 @@ internal sealed class ManaStoneManager
// "The Mana Stone gives X points of mana to ..." — transfer complete.
// The stone may also have been destroyed in the process; either way
// reset and let the next tick pick a fresh stone.
if (text.Contains("The Mana Stone gives")
|| text.Contains("The Mana Stone is destroyed"))
if (text.Contains("The Mana Stone gives"))
{
// The stone gave its mana and is empty now (an Eternal charge refills itself), though
// its read still shows the old charge.
WorldObject? stone = _activeStoneId != 0 ? _objectCache[_activeStoneId] : null;
if (stone == null || !IsEternal(stone)) MarkStoneEmpty(_activeStoneId);
if (text.Contains("fully charged")) HoldRefills("the server says the worn items are fully charged");
Reset();
return;
}
if (text.Contains("The Mana Stone is destroyed"))
{
Reset();
return;
}
// ACE says this only for a charged stone: the stone keeps its charge, the gear is full.
if (text.Contains("no items equipped that need mana"))
{
MarkStoneCharged(_activeStoneId);
HoldRefills("the server says no worn item needs mana");
Reset();
}
}
}
private void HoldRefills(string why)
{
_refillHoldUntil = NowMs + RefillHoldMs;
_host.Log($"[RynthAi] ManaStone: no worn-gear refill for {RefillHoldMs / 1000}s ({why}; the gear's mana reads are from its last appraisal).");
}
private int? ReadStoneMana(int id) =>
_host.TryGetObjectIntProperty(unchecked((uint)id), (uint)AcIntProperty.CurrentMana, out int cur) ? cur : null;
/// <summary>The server showed this stone empty since its read was taken (and no newer read came in).</summary>
private bool IsKnownEmpty(int id, int? read)
{
if (!_stoneKnownEmpty.TryGetValue(id, out int? atMark)) return false;
if (read != atMark) { _stoneKnownEmpty.Remove(id); return false; } // a newer appraisal: trust it
return true;
}
private void MarkStoneEmpty(int id)
{
if (id == 0) return;
_stoneKnownCharged.Remove(id);
_stoneKnownEmpty[id] = ReadStoneMana(id);
}
private void MarkStoneCharged(int id)
{
if (id == 0) return;
_stoneKnownEmpty.Remove(id);
_stoneKnownCharged.Add(id);
}
/// <summary>
/// CorpseOpenController calls this when it picks an item up as "ManaTap" (no loot
/// rule matched, it holds enough mana and an empty stone is free): when the pickup
@ -316,7 +406,7 @@ internal sealed class ManaStoneManager
// Priority 2 (was 1): refill worn gear with a charged stone, but only
// when there is nothing to drain right now.
if (WornEquipmentNeedsMana(threshold))
if (WornEquipmentNeedsMana(threshold) && NowMs >= _refillHoldUntil)
{
int chargedStone = FindChargedStone();
if (chargedStone != 0)
@ -326,8 +416,13 @@ internal sealed class ManaStoneManager
IssueUseOnPlayer();
return;
}
long now = NowMs;
if (now - _lastNoStoneDiagAt > 60_000)
{
_lastNoStoneDiagAt = now;
_host.Log($"[RynthAi] ManaStone: worn gear needs mana but no charged stone is known ({_stoneKnownCharged.Count} known charged, {_stoneKnownEmpty.Count} known empty).");
}
}
}
private void IssueTapItem(int stoneId, int itemId)
@ -387,13 +482,13 @@ internal sealed class ManaStoneManager
if (!IsOwnedByPlayer(item, playerId)) continue;
if (_stoneKnownCharged.Contains(item.Id)) continue;
bool readMana = _host.TryGetObjectIntProperty(unchecked((uint)item.Id),
(uint)AcIntProperty.CurrentMana, out int cur);
if (readMana && cur == 0)
int? read = ReadStoneMana(item.Id);
bool knownEmpty = IsKnownEmpty(item.Id, read); // keep in sync with FindEmptyStone
if (knownEmpty || read == 0)
_stoneTapCooldownUntil.Remove(item.Id);
if (_stoneTapCooldownUntil.TryGetValue(item.Id, out long until) && now < until) continue;
if (readMana && cur > 0) continue;
if (!knownEmpty && read > 0) continue;
count++;
}
return count;
@ -608,13 +703,14 @@ internal sealed class ManaStoneManager
// mana") are never empty until they're consumed/destroyed.
if (_stoneKnownCharged.Contains(item.Id)) continue;
bool readMana = _host.TryGetObjectIntProperty(unchecked((uint)item.Id),
(uint)AcIntProperty.CurrentMana, out int curMana);
int? read = ReadStoneMana(item.Id);
// It gave its mana to worn gear: empty, whatever the (older) read says.
bool knownEmpty = IsKnownEmpty(item.Id, read);
// If we can read CurrentMana and it's truly 0, the stone IS empty —
// clear any stale blacklist entry. This makes the cooldown self-heal
// once the cache catches up to the actual state.
if (readMana && curMana == 0)
if (knownEmpty || read == 0)
_stoneTapCooldownUntil.Remove(item.Id);
// Skip stones that recently failed a tap so we don't loop on the
@ -629,8 +725,7 @@ internal sealed class ManaStoneManager
// strict here makes us blind to real empty stones; the stone-tap
// blacklist handles the misfires when an "empty-looking" stone
// is actually charged server-side.
if (_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int cur)
&& cur > 0)
if (!knownEmpty && read > 0)
continue;
return item.Id;
@ -648,6 +743,7 @@ internal sealed class ManaStoneManager
int bestId = 0;
int bestMana = 0;
bool requestedId = false;
foreach (var item in _objectCache.AllKnownObjects())
{
@ -661,16 +757,41 @@ internal sealed class ManaStoneManager
// Eternal: always charged (its mana often can't be read), never used up — first choice.
if (IsEternal(item)) return item.Id;
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int cur))
continue;
if (cur <= 0) continue;
int? read = ReadStoneMana(item.Id);
// It already gave its mana; the read is from before that.
if (IsKnownEmpty(item.Id, read)) continue;
if (cur > bestMana) { bestMana = cur; bestId = item.Id; }
int mana;
if (read > 0) mana = read.Value;
else if (_stoneKnownCharged.Contains(item.Id)) mana = 1; // the server said charged; amount unknown
else
{
if (read == null && !requestedId) requestedId = RequestStoneId(item.Id, now);
continue;
}
if (mana > bestMana) { bestMana = mana; bestId = item.Id; }
}
return bestId;
}
/// <summary>
/// Identifies a stone whose charge can't be read (at most every 5 minutes), so a charged one shows
/// its charge. Not when it already has appraisal data: ACE leaves CurrentMana out for an empty
/// stone, so an appraised stone with no readable charge is empty.
/// </summary>
private bool RequestStoneId(int id, long now)
{
if (!_host.HasRequestId) return false;
if (_host.HasHasAppraisalData && _host.HasAppraisalData(unchecked((uint)id))) return false;
if (_stoneIdRequestedAt.TryGetValue(id, out long at) && now - at < StoneIdRetryMs) return false;
_stoneIdRequestedAt[id] = now;
_host.Log($"[RynthAi] ManaStone: identifying stone 0x{(uint)id:X8} (its charge can't be read).");
_host.RequestId(unchecked((uint)id));
return true;
}
/// <summary>
/// The next item to drain. Only items the looter picked up as "ManaTap" are
/// candidates (the drain destroys the item); every check below is a second
@ -813,7 +934,8 @@ internal sealed class ManaStoneManager
{
_lastGearDiagAt = now;
_host.Log($"[RynthAi] ManaStone: gear check - worn={worn} manaReadable={readable} lowest={(readable > 0 ? $"{lowestPct}% ({lowestName})" : "n/a")} " +
$"refillBelow={(int)(pct * 100)}% eternal={eternal} needs={needs} tapping={_settings.EnableManaTapping}");
$"refillBelow={(int)(pct * 100)}% eternal={eternal} needs={needs} tapping={_settings.EnableManaTapping}" +
(now < _refillHoldUntil ? $" hold={(_refillHoldUntil - now) / 1000}s" : ""));
}
return needs;

View file

@ -3415,6 +3415,9 @@ internal sealed class ExpressionEngine
["OffhandDefault"] = (() => s.OffhandDefault, v => { if (OffhandRules.TryParse(v, out var m)) s.OffhandDefault = OffhandRules.SettingValue(m); }),
["PreferDualWield"] = (() => B(s.PreferDualWield), v => s.PreferDualWield = ToDouble(v) != 0),
["MonsterRange"] = (() => I(s.MonsterRange), v => { if (int.TryParse(v, out int i)) s.MonsterRange = i; }),
// Targeting: 0 lowest health, 1 closest, 2 farthest, 3 least turning.
["TargetSelection"] = (() => I(s.TargetSelection), v => { if (int.TryParse(v, out int i)) s.TargetSelection = Math.Clamp(i, 0, 3); }),
["TargetLock"] = (() => B(s.TargetLock), v => s.TargetLock = ToDouble(v) != 0),
["RingRange"] = (() => I(s.RingRange), v => { if (int.TryParse(v, out int i)) s.RingRange = i; }),
["ApproachRange"] = (() => I(s.ApproachRange), v => { if (int.TryParse(v, out int i)) s.ApproachRange = i; }),
["MinRingTargets"] = (() => I(s.MinRingTargets), v => { if (int.TryParse(v, out int i)) s.MinRingTargets = i; }),

View file

@ -14,7 +14,9 @@ public static unsafe class PluginExports
internal static readonly RynthPluginRuntime<RynthAiPlugin> Runtime = new();
// Typed interfaces for other plugins (host GetPluginInterface, API v68): "RynthAi.Script" v1
// for RynthLua, "RynthAi.Status" v1 for RynthNet (the bot state it shares with the other clients). Fixed signature: void* (const char* iface, uint version).
// for RynthLua, "RynthAi.Status" v1 for RynthNet (the bot state it shares with the other clients),
// "RynthAi.Activity" v1 for RynthSort (what the bot is doing, so pack moves stay out of its way).
// Fixed signature: void* (const char* iface, uint version).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version)
{
@ -22,7 +24,8 @@ public static unsafe class PluginExports
{
string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? "";
IntPtr table = ScriptInterface.Query(iface, version);
return table != IntPtr.Zero ? table : StatusInterface.Query(iface, version);
if (table == IntPtr.Zero) table = StatusInterface.Query(iface, version);
return table != IntPtr.Zero ? table : ActivityInterface.Query(iface, version);
}
catch
{
@ -38,6 +41,7 @@ public static unsafe class PluginExports
{
Runtime.Shutdown();
StatusInterface.Release();
ActivityInterface.Release();
// The loot editor's state can be a few hundred KB (LootSnobV4): don't leave it behind on a reload.
foreach (IntPtr p in new[] { Interlocked.Exchange(ref _lootStatePtr, IntPtr.Zero),
Interlocked.Exchange(ref _lootRulePtr, IntPtr.Zero), Interlocked.Exchange(ref _lootVocabPtr, IntPtr.Zero) })

View file

@ -1495,6 +1495,7 @@ public sealed partial class RynthAiPlugin
_dashboard.Settings.CurrentLootPath = candidatePath;
ChatLine($"[RynthAi] Loaded loot profile '{System.IO.Path.GetFileName(candidatePath)}' with {profile.Rules.Count} rule(s).");
ReportLootProfileProblems(profile, System.IO.Path.GetFileName(candidatePath));
return true;
}
catch (Exception ex)
@ -1504,6 +1505,42 @@ public sealed partial class RynthAiPlugin
}
}
/// <summary>
/// Reports, in chat and the log, a header rule count that disagrees with the rules
/// found, and names the rules that use condition types RynthAi cannot evaluate. The
/// evaluator treats such a rule as never matching, so the items it was written for
/// stay on corpses with nothing in chat or the log to say why.
/// </summary>
private void ReportLootProfileProblems(VTankLootProfile profile, string fileName)
{
if (profile.DeclaredRuleCount >= 0 && profile.DeclaredRuleCount != profile.Rules.Count)
{
string countMessage = $"[RynthAi] Loot profile '{fileName}': header declares {profile.DeclaredRuleCount} rule(s) " +
$"but the file holds {profile.Rules.Count}; all {profile.Rules.Count} are in use. " +
"Re-save the profile in the loot editor to correct the header.";
ChatLine(countMessage);
Host.Log(countMessage);
}
var bad = new List<string>();
foreach (VTankLootRule rule in profile.Rules)
{
var types = rule.Conditions
.Select(c => c.NodeType)
.Where(t => VTankNodeTypes.GetDataLineCount(t) < 0)
.Distinct()
.ToList();
if (types.Count > 0)
bad.Add($"'{rule.Name.Trim()}' (type {string.Join("/", types)})");
}
if (bad.Count == 0) return;
string message = $"[RynthAi] Loot profile '{fileName}': {bad.Count} rule(s) use condition types " +
$"RynthAi does not support and will never match: {string.Join(", ", bad)}.";
ChatLine(message);
Host.Log(message);
}
// ── Loot Editor (engine ImGui panel) ────────────────────────────────────
private LootEditorBridge? _lootEditor;
@ -2772,6 +2809,25 @@ public sealed partial class RynthAiPlugin
/// after a new hazard was sighted mid-patrol — it reroutes silently (no fresh
/// "patrol started" chatter, just a one-line note) and never flips IsMacroRunning.
/// </summary>
// One log line per patrol waypoint and a summary (diagnostics: which rule put each point
// where it is, e.g. the patrol walking into small rooms it should only look into).
private void LogPatrolWaypoints(NavRouteParser route, Dictionary<uint, DungeonNavNode> graph, DungeonGeometry? geometry,
IReadOnlySet<uint>? hazards, Dictionary<NavPoint, DungeonPathfinder.PatrolPointInfo> pointLog,
uint playerCell, uint startCell)
{
try
{
Host.Log($"[RynthAi] DunNav-Patrol wp build: player cell {playerCell:X8}, start cell {startCell:X8}, {route.Points.Count} points, geometry {(geometry != null ? "on" : "off")}"
+ (hazards is { Count: > 0 } ? $", hazards {string.Join(",", hazards.Where(c => c >> 16 == startCell >> 16).OrderBy(c => c).Select(c => (c & 0xFFFF).ToString("X4")))}" : ""));
foreach (string line in DungeonPathfinder.DescribePatrol(route, graph, geometry, hazards, pointLog))
Host.Log("[RynthAi] DunNav-Patrol " + line);
}
catch (Exception ex)
{
Host.Log($"[RynthAi] DunNav-Patrol wp log failed: {ex.Message}");
}
}
private void BuildDunPatrol(bool isRebuild)
{
var settings = _dashboard?.Settings;
@ -2857,11 +2913,21 @@ public sealed partial class RynthAiPlugin
// The dungeon map geometry (doorways, floors, walls): doorways taken straight on and
// big rooms crossed directly. Null (old cell walk) until DungeonLOS is up.
var geometry = DungeonPathfinder.GetGeometry(landblockKey, cellDat, _raycast?.GeometryLoader?.DungeonLOS);
var route = DungeonPathfinder.BuildPatrolRoute(graph, startCell, hazards, geometry);
// Diagnostics: record which rule laid each waypoint (logged below, one line each).
var pointLog = new Dictionary<NavPoint, DungeonPathfinder.PatrolPointInfo>(ReferenceEqualityComparer.Instance);
DungeonPathfinder.PointLog = pointLog;
NavRouteParser route;
try { route = DungeonPathfinder.BuildPatrolRoute(graph, startCell, hazards, geometry); }
finally { DungeonPathfinder.PointLog = null; }
// Lead the bot out of the hazard first.
if (evacuate)
route.Points.Insert(0, new NavPoint { Type = NavPointType.Point, NS = evacNS, EW = evacEW, Z = evacZ });
{
var lead = new NavPoint { Type = NavPointType.Point, NS = evacNS, EW = evacEW, Z = evacZ };
route.Points.Insert(0, lead);
pointLog[lead] = new DungeonPathfinder.PatrolPointInfo { Kind = "evacuate", Cell = startCell, Why = "start cell is a hazard" };
}
LogPatrolWaypoints(route, graph, geometry, hazards, pointLog, playerCell, startCell);
// Empty-route guard: a single-cell / hazard-locked start yields no waypoints. Do NOT claim the
// patrol started or enable nav — the bot would just stand in place (in the hazard) taking damage.

View file

@ -15,8 +15,9 @@ namespace RynthCore.Plugin.RynthAi;
/// looting, the route, the meta: OnTick returns here, like the death hold) and walks the character
/// back out along its own footsteps (the positions it just came through, so a path it could walk)
/// to where it stood just before the hit. It hands back once it got there and no hit came
/// for HazardQuietMs. A dungeon cell it was hurt in is a hazard from then on (persisted), so the
/// patrol reroutes around it now and on later visits.
/// for HazardQuietMs. The cell it was hurt in is NOT made a patrol hazard: from 2026-10-07 it was
/// (persisted, patrol rerouted around it), and the reroutes sent the patrol through doors into small
/// side rooms (2026-10-10). The patrol is back to how it was before; the escape alone stays.
/// </summary>
public sealed partial class RynthAiPlugin
{
@ -59,6 +60,8 @@ public sealed partial class RynthAiPlugin
private bool _hazardRunning;
private long _hazardRunBeatAt;
private string _hazardSource = "";
/// <summary>Cells hurt in this session: the escape steers its target out of them. Not patrol hazards.</summary>
private readonly System.Collections.Generic.HashSet<uint> _hazardHurtCells = new();
/// <summary>True while the escape owns the character.</summary>
internal bool HazardEscaping => _hazardEscapeSince != 0;
@ -79,17 +82,15 @@ public sealed partial class RynthAiPlugin
internal void NoteHotspotChat(string? text, int chatType)
{
if (chatType != 0 || !TryParseHotspotDamage(text, out int amount, out string source)) return;
// Off (Escape Acid and Lava): neither the escape nor the learning - a character that walks
// through acid on purpose doesn't want the patrol rerouted around it either.
// Off (Escape Acid and Lava): no escape.
if (_dashboard?.Settings is { EscapeHazards: false }) return;
long now = HazardClock();
bool fresh = _hazardLastHitAt == 0 || now - _hazardLastHitAt > HazardQuietMs;
if (fresh) _hazardFirstHitAt = now;
_hazardLastHitAt = now;
_hazardSource = source;
if (Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _))
_objectCache?.RegisterDamageHazardCell(cell, source);
if (Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _) && cell != 0)
_hazardHurtCells.Add(cell);
if (_dashboard?.Settings is not { IsMacroRunning: true }) return;
if (!HazardEscaping)
@ -155,7 +156,7 @@ public sealed partial class RynthAiPlugin
if (p.At >= olderThan || (p.Cell >> 16) != (cell >> 16)) continue;
double d = Math.Sqrt((p.X - px) * (p.X - px) + (p.Y - py) * (p.Y - py));
if (d < HazardMinBackMeters) continue;
if (_objectCache?.IsHazardCell(p.Cell) == true)
if (_objectCache?.IsHazardCell(p.Cell) == true || _hazardHurtCells.Contains(p.Cell))
{
if (fallback < 0) fallback = i;
continue;

View file

@ -152,7 +152,34 @@ public sealed partial class RynthAiPlugin
private void PrintItemInfo(uint id, bool identified)
{
var source = new HostItemInfoSource(Host, id);
ChatLine(ItemPrefix + ItemInfoText.Describe(source, SpellDatabase.GetSpellName, identified));
ChatLine(ItemPrefix + ItemInfoText.Describe(source, SpellDatabase.GetSpellName, identified) + LootVerdictSuffix(id));
}
/// <summary>
/// " | Loot: [Keep] (A) MajorSkill Set": the looter's own verdict on the item, as a preview
/// (nothing recorded), so it says exactly what [LootEval] would. Item info on select replaced
/// the separate verdict line (95df8ed), which was the only place it showed (Tom, 2026-10-10:
/// lots of Major armor kept and no way to tell which rule). "" when there's no loot profile,
/// or /ra lootcheck off (the toggle that hid the old verdict line too).
/// </summary>
private string LootVerdictSuffix(uint id)
{
try
{
LegacyUi.LegacyUiSettings? settings = _dashboard?.Settings;
WorldObject? wo = _objectCache?[unchecked((int)id)];
if (!_lootInspectMode || settings == null || wo == null || string.IsNullOrEmpty(settings.CurrentLootPath)) return "";
if (!ClassifyLootItem(wo, settings, preview: true, out string action, out _, out string rule, out string builtIn))
// A rule can match and still not take it (its Keep # reached, a Read rule on a non-scroll).
return rule.Length > 0 ? $" | Loot: leave ({rule} matched, not taken)" : " | Loot: no rule matched";
if (builtIn.Length > 0) return $" | Loot: [{action}] built-in - {builtIn}";
return $" | Loot: [{action}] {(rule.Length > 0 ? rule : "(unnamed rule)")}";
}
catch (Exception ex)
{
Host.Log($"[RynthAi] Item info: loot verdict failed for 0x{id:X8}: {ex.GetType().Name}: {ex.Message}");
return "";
}
}
/// <summary>The live appraisal through the host (tick thread).</summary>

View file

@ -887,7 +887,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
["SpellCastIntervalMs"] = (100, 1500), ["AttackSpellIntervalMs"] = (0, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100), ["MinWallTargets"] = (1, 20), ["WallRange"] = (0, 100),
["MinSkillLevelTier1"] = (1, 500), ["MinSkillLevelTier2"] = (1, 500), ["MinSkillLevelTier3"] = (1, 500), ["MinSkillLevelTier4"] = (1, 500),
["MinSkillLevelTier5"] = (1, 500), ["MinSkillLevelTier6"] = (1, 500), ["MinSkillLevelTier7"] = (1, 500), ["MinSkillLevelTier8"] = (1, 500),
["MonsterRange"] = (1, 200), ["MonsterDisengageRange"] = (0, 200), ["RingRange"] = (1, 50), ["ApproachRange"] = (1, 50),
["MonsterRange"] = (1, 200), ["MonsterDisengageRange"] = (0, 200), ["TargetSelection"] = (0, 3), ["RingRange"] = (1, 50), ["ApproachRange"] = (1, 50),
["CorpseApproachRangeMax"] = (0.5, 50), ["CorpseApproachRangeMin"] = (0.5, 20),
["FollowNavMin"] = (0.5, 20), ["NavRingThickness"] = (1, 16), ["NavLineThickness"] = (1, 16),
["NavHeightOffset"] = (-5, 5), ["NavSlopeSink"] = (0, 8), ["NavLabelMode"] = (0, 2), ["OpenDoorRange"] = (0.1, 70), ["MovementMode"] = (0, 0),

View file

@ -33,6 +33,8 @@
<Compile Include="..\Shared\RynthAiScriptApi.cs" Link="Shared\RynthAiScriptApi.cs" />
<!-- RynthNet reads the bot state through RynthAi.Status. -->
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<!-- RynthSort reads what the bot is doing through RynthAi.Activity (read only). -->
<Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<!-- RynthNav's navmesh path queries (stuck-recovery detours outdoors). -->
<Compile Include="..\Shared\RynthNavPathApi.cs" Link="Shared\RynthNavPathApi.cs" />
<!-- Reading our hits out of the combat log (victim + amount); RynthTracker reads the same lines. -->

View file

@ -0,0 +1,229 @@
// BountyParse.cs - Parses ACECustom's bounty output (BountyManager / BountyCommands).
//
// The progress itself (PropertyString BountyProgress) is server-only, so the tracker reads
// what the server prints. All lines are ChatMessageType.Broadcast:
// /bounty list "Bounties:" header, then one line per reward of every active area:
// " {where}: {amount} {item} every {N kill(s)}[ (at most every {wait})] - you: {status}."
// footer "Bounty: type /bounty to see the bounties where you stand."
// or "Bounty: there are no bounties anywhere right now."
// /bounty "Bounty[ (all zones)| ({region})]: {amount} {item} - {status}."
// or "Bounty: there is no bounty here."
// status "{k} of {n} kills" | "unlocks in {wait}, then {N kill(s)} required" | "needs {qb} QB (you have {n})"
// events "Bounty unlocked: {item} - {N kill(s)} required." "Bounty complete! +{n} {item} gained."
// "Next bounty unlocks in {wait} - {N kill(s)} required." "Next bounty requires {N kill(s)}."
// held rewards: "Bounty: +{n} ..." / "Bounty: Your inventory is full. ..."
// wait "45 sec", "5 min", "2 min 30 sec", "1 hr 15 sec" (FormatWait); numbers use N0 grouping.
// A server without the bounty system answers "Unknown command: bounty".
using System;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthILT.Bounty;
/// <summary>Where the player stands on one bounty reward.</summary>
internal enum BountyStatus
{
/// <summary>Kills are counting: Kills of KillsRequired.</summary>
Counting = 0,
/// <summary>The cooldown after the last award runs; kills do not count until UnlockAtUtc.</summary>
Cooldown = 1,
/// <summary>The player's QB is below the reward's minimum; kills do not count.</summary>
NeedsQb = 2,
}
/// <summary>One parsed status phrase.</summary>
internal readonly record struct BountyStatusInfo(BountyStatus Status, int Kills, int KillsRequired,
int WaitSeconds, long QbRequired, long QbHave);
/// <summary>One "/bounty list" line.</summary>
internal readonly record struct BountyListLine(string Where, long Amount, string Item, int KillsRequired,
int CooldownSeconds, BountyStatusInfo Status);
/// <summary>One "/bounty" (where you stand) line. Scope is "" (this dungeon/zone), "all zones" or a region name.</summary>
internal readonly record struct BountyHereLine(string Scope, long Amount, string Item, BountyStatusInfo Status);
/// <summary>Kind of a bounty chat event.</summary>
internal enum BountyEventKind { Unlocked, Complete, NextCooldown, NextReady, Held }
internal static class BountyParse
{
private const RegexOptions Opt = RegexOptions.Compiled | RegexOptions.CultureInvariant;
private const string Num = @"\d[\d,]*";
// Status alternatives are spelled out inside the line patterns so backtracking can place the
// " - " separator correctly when an item name itself contains " - ".
private const string StatusPattern =
@"(?<status>" + Num + @" of " + Num + @" kills?|unlocks in .+?, then " + Num + @" kills? required|needs "
+ Num + @" QB \(you have " + Num + @"\))";
/// <summary>"/bounty list" reward line (leading indentation already trimmed).</summary>
private static readonly Regex ListLine = new(
@"^(?<where>.+?): (?<amount>" + Num + @") (?<item>.+?) every (?<kills>" + Num + @") kills?"
+ @"(?: \(at most every (?<cd>[^)]+)\))? - you: " + StatusPattern + @"\.$", Opt);
/// <summary>"/bounty" reward line.</summary>
private static readonly Regex HereLine = new(
@"^Bounty(?: \((?<scope>[^)]+)\))?: (?<amount>" + Num + @") (?<item>.+?) - " + StatusPattern + @"\.$", Opt);
private static readonly Regex Counting = new(@"^(?<k>" + Num + @") of (?<n>" + Num + @") kills?$", Opt);
private static readonly Regex Cooldown = new(@"^unlocks in (?<wait>.+?), then (?<n>" + Num + @") kills? required$", Opt);
private static readonly Regex Qb = new(@"^needs (?<qb>" + Num + @") QB \(you have (?<have>" + Num + @")\)$", Opt);
private static readonly Regex WaitPart = new(@"(?<v>\d+)\s*(?<u>hr|min|sec)\b", Opt);
private static readonly Regex EvUnlocked = new(@"^Bounty unlocked: (?<item>.+) - (?<n>" + Num + @") kills? required\.$", Opt);
private static readonly Regex EvComplete = new(@"^Bounty complete! \+(?<n>" + Num + @") (?<item>.+) gained\.$", Opt);
private static readonly Regex EvNextWait = new(@"^Next bounty unlocks in (?<wait>.+?) - (?<n>" + Num + @") kills? required\.$", Opt);
private static readonly Regex EvNextReady = new(@"^Next bounty requires (?<n>" + Num + @") kills?\.$", Opt);
/// <summary>"/bounty list" header line.</summary>
public const string ListHeader = "Bounties:";
/// <summary>True for the line that ends a "/bounty list" reply (footer or "no bounties anywhere").</summary>
public static bool IsListTerminator(string text)
=> text.StartsWith("Bounty: type /bounty", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("Bounty: there are no bounties anywhere", StringComparison.OrdinalIgnoreCase);
/// <summary>True when the terminator says no bounty is active anywhere.</summary>
public static bool IsNoBountiesAnywhere(string text)
=> text.StartsWith("Bounty: there are no bounties anywhere", StringComparison.OrdinalIgnoreCase);
/// <summary>ACE's reply to a command the server doesn't register.</summary>
public static bool IsUnknownCommand(string text)
=> text.StartsWith("Unknown command: bounty", StringComparison.OrdinalIgnoreCase);
/// <summary>Parses a "/bounty list" reward line.</summary>
public static bool TryParseListLine(string text, out BountyListLine line)
{
line = default;
var m = ListLine.Match((text ?? string.Empty).Trim());
if (!m.Success || !TryParseStatus(m.Groups["status"].Value, out var status)) return false;
int required = ToInt(m.Groups["kills"].Value);
int cooldown = m.Groups["cd"].Success ? ParseWaitSeconds(m.Groups["cd"].Value) : 0;
line = new BountyListLine(m.Groups["where"].Value.Trim(), ParseLong(m.Groups["amount"].Value),
m.Groups["item"].Value.Trim(), required, cooldown, status);
return true;
}
/// <summary>Parses a "/bounty" (where you stand) reward line.</summary>
public static bool TryParseHereLine(string text, out BountyHereLine line)
{
line = default;
var m = HereLine.Match((text ?? string.Empty).Trim());
if (!m.Success || !TryParseStatus(m.Groups["status"].Value, out var status)) return false;
line = new BountyHereLine(m.Groups["scope"].Success ? m.Groups["scope"].Value.Trim() : string.Empty,
ParseLong(m.Groups["amount"].Value), m.Groups["item"].Value.Trim(), status);
return true;
}
/// <summary>Parses one status phrase (without the trailing period).</summary>
public static bool TryParseStatus(string text, out BountyStatusInfo status)
{
status = default;
string t = (text ?? string.Empty).Trim().TrimEnd('.');
var m = Counting.Match(t);
if (m.Success)
{
status = new BountyStatusInfo(BountyStatus.Counting, ToInt(m.Groups["k"].Value), ToInt(m.Groups["n"].Value), 0, 0, 0);
return true;
}
m = Cooldown.Match(t);
if (m.Success)
{
status = new BountyStatusInfo(BountyStatus.Cooldown, 0, ToInt(m.Groups["n"].Value),
ParseWaitSeconds(m.Groups["wait"].Value), 0, 0);
return true;
}
m = Qb.Match(t);
if (m.Success)
{
status = new BountyStatusInfo(BountyStatus.NeedsQb, 0, 0, 0,
ParseLong(m.Groups["qb"].Value), ParseLong(m.Groups["have"].Value));
return true;
}
return false;
}
/// <summary>"2 min 30 sec" → 150, "1 hr 15 sec" → 3615. 0 when nothing parses.</summary>
public static int ParseWaitSeconds(string text)
{
long total = 0;
foreach (Match m in WaitPart.Matches(text ?? string.Empty))
{
long v = ParseLong(m.Groups["v"].Value);
total += m.Groups["u"].Value switch { "hr" => v * 3600, "min" => v * 60, _ => v };
}
return (int)Math.Min(total, int.MaxValue);
}
/// <summary>
/// Recognises a bounty chat event (award, unlock, next cooldown, held reward). Item and
/// KillsRequired are filled when the line names them; WaitSeconds for "Next bounty unlocks in".
/// </summary>
public static bool TryParseEvent(string text, out BountyEventKind kind, out string item, out int killsRequired, out int waitSeconds)
{
kind = BountyEventKind.Held;
item = string.Empty;
killsRequired = 0;
waitSeconds = 0;
string t = (text ?? string.Empty).Trim();
if (t.Length == 0) return false;
Match m;
if ((m = EvUnlocked.Match(t)).Success)
{
kind = BountyEventKind.Unlocked;
item = m.Groups["item"].Value.Trim();
killsRequired = ToInt(m.Groups["n"].Value);
return true;
}
if ((m = EvComplete.Match(t)).Success)
{
kind = BountyEventKind.Complete;
item = m.Groups["item"].Value.Trim();
return true;
}
if ((m = EvNextWait.Match(t)).Success)
{
kind = BountyEventKind.NextCooldown;
waitSeconds = ParseWaitSeconds(m.Groups["wait"].Value);
killsRequired = ToInt(m.Groups["n"].Value);
return true;
}
if ((m = EvNextReady.Match(t)).Success)
{
kind = BountyEventKind.NextReady;
killsRequired = ToInt(m.Groups["n"].Value);
return true;
}
// Held-reward notices; the "/bounty" and "/bounty list" status lines also start with "Bounty: ".
if (t.StartsWith("Bounty: +", StringComparison.Ordinal)
|| t.StartsWith("Bounty: Your inventory is full", StringComparison.OrdinalIgnoreCase))
{
kind = BountyEventKind.Held;
return true;
}
return false;
}
/// <summary>Key that identifies one reward of one area across refreshes.</summary>
public static string Key(string where, long amount, string item, int killsRequired)
=> $"{where}|{amount}|{item}|{killsRequired}".ToLowerInvariant();
/// <summary>"1 hr 5 min", "45 sec", "2 days 3 hr". Negative spans read as 0 sec.</summary>
public static string Duration(TimeSpan span)
{
long s = Math.Max(0, (long)span.TotalSeconds);
if (s >= 86400) return $"{s / 86400} day{(s / 86400 == 1 ? "" : "s")}" + (s % 86400 >= 3600 ? $" {s % 86400 / 3600} hr" : "");
if (s >= 3600) return $"{s / 3600} hr" + (s % 3600 >= 60 ? $" {s % 3600 / 60} min" : "");
if (s >= 60) return $"{s / 60} min" + (s % 60 > 0 ? $" {s % 60} sec" : "");
return $"{s} sec";
}
/// <summary>Digits with "," grouping removed; 0 when nothing parses.</summary>
internal static long ParseLong(string text)
{
string digits = (text ?? string.Empty).Replace(",", string.Empty).Trim();
return long.TryParse(digits, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out long v) ? v : 0;
}
private static int ToInt(string text) => (int)Math.Min(ParseLong(text), int.MaxValue);
}

View file

@ -0,0 +1,708 @@
// BountyTracker.cs - Every ACECustom bounty and this character's progress, for the engine's Bounties window.
//
// The server keeps the counts (PropertyString BountyProgress is server-only), so the tracker reads
// "/bounty list", which reports every active bounty on the server - wherever the player stands -
// with the player's kills, cooldown or QB requirement for each. The read is a quiet capture (the
// reply is eaten from chat) and runs only while the engine's Bounties window polls the export:
// * when the window opens (and the list is old or kills happened while it was closed),
// * a moment after each of this character's kills,
// * after a bounty chat event ("Bounty complete!", "Bounty unlocked:", "Next bounty ..."),
// * every PeriodicRefreshMinutes as a backstop, and on Refresh / "/ilt bounty refresh".
// Every read, whatever asked for it, waits for MinRefreshSeconds (at least 5 s) since the last
// one, and none is sent while the window is closed (RynthILT review, 2026-10-09).
// Lines the player prints themselves ("/bounty list", "/bounty") update the list too, and are
// never eaten: a /bounty the player types (NoteTypedCommand) turns the capture it overlaps into
// a shown one, and a typed "/bounty list" stands in for the tracker's next read.
// Cooldowns count down locally from the read time; when one ends the bounty shows 0 of N kills,
// which is what the server says too (an award resets the count before the cooldown starts).
//
// Everything runs on the plugin's game thread: OnTick, chat, kills and the engine's export polls.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RynthCore.Plugin.RynthILT.Bounty;
/// <summary>Persisted per character (bounties.json): the window's options and the last list read.</summary>
internal sealed class BountyState
{
public bool RefreshOnKills = true;
public int MinRefreshSeconds = 10;
public int PeriodicRefreshMinutes = 5;
public bool HideQbLocked;
public bool SortByProgress;
public List<BountyEntry> Entries = new();
public DateTime ListedUtc;
public bool NoneAnywhere;
public string LastEvent = string.Empty;
public DateTime LastEventUtc;
}
/// <summary>One reward of one bounty area and where this character stands on it.</summary>
internal sealed class BountyEntry
{
public string Where = string.Empty;
public long Amount;
public string Item = string.Empty;
public int KillsRequired;
public int CooldownSeconds;
/// <summary>A <see cref="BountyStatus"/> value.</summary>
public int Status;
public int Kills;
public DateTime UnlockAtUtc;
public long QbRequired;
public long QbHave;
/// <summary>Last time the kills went up or an award reset them (row highlight).</summary>
public DateTime ChangedUtc;
}
/// <summary>
/// RynthPluginGetBountiesJson payload. Mirrored by RynthCore.Engine UI/Data/BountiesSnapshotJson.cs;
/// either side may add fields (unknown ones are skipped, missing ones keep their defaults).
/// </summary>
internal sealed class BountyBridgePayload
{
[JsonPropertyName("unsupported")] public bool Unsupported;
[JsonPropertyName("reading")] public bool Reading;
[JsonPropertyName("status")] public string Status = string.Empty;
/// <summary>Seconds since the last list read; -1 = never.</summary>
[JsonPropertyName("listedAgoSec")] public int ListedAgoSec = -1;
[JsonPropertyName("noneAnywhere")] public bool NoneAnywhere;
[JsonPropertyName("lastEvent")] public string LastEvent = string.Empty;
[JsonPropertyName("lastEventAgoSec")] public int LastEventAgoSec = -1;
[JsonPropertyName("refreshOnKills")] public bool RefreshOnKills;
[JsonPropertyName("minRefreshSeconds")] public int MinRefreshSeconds;
[JsonPropertyName("periodicRefreshMinutes")] public int PeriodicRefreshMinutes;
[JsonPropertyName("hideQbLocked")] public bool HideQbLocked;
[JsonPropertyName("sortByProgress")] public bool SortByProgress;
/// <summary>Rows not shown because of HideQbLocked.</summary>
[JsonPropertyName("hiddenCount")] public int HiddenCount;
[JsonPropertyName("rows")] public List<BountyRow> Rows = new();
}
/// <summary>One row of <see cref="BountyBridgePayload"/>, with the status as of the poll.</summary>
internal sealed class BountyRow
{
[JsonPropertyName("where")] public string Where = string.Empty;
[JsonPropertyName("amount")] public long Amount;
[JsonPropertyName("item")] public string Item = string.Empty;
[JsonPropertyName("killsRequired")] public int KillsRequired;
[JsonPropertyName("cooldownSeconds")] public int CooldownSeconds;
/// <summary>A <see cref="BountyStatus"/> value; an ended cooldown is already Counting.</summary>
[JsonPropertyName("status")] public int Status;
[JsonPropertyName("kills")] public int Kills;
[JsonPropertyName("unlockInSec")] public int UnlockInSec;
[JsonPropertyName("qbRequired")] public long QbRequired;
[JsonPropertyName("qbHave")] public long QbHave;
/// <summary>Kills went up (or an award reset them) in the last 15 seconds.</summary>
[JsonPropertyName("changed")] public bool Changed;
}
internal sealed class BountyTracker
{
/// <summary>The capture command; "/bounty all" is the same list.</summary>
public const string ListCommand = "/bounty list";
/// <summary>Lowest allowed MinRefreshSeconds (the server is asked at most this often after kills).</summary>
public const int MinRefreshFloorSeconds = 5;
public const int MinRefreshCeilingSeconds = 300;
public const int PeriodicCeilingMinutes = 60;
public const string FileName = "bounties.json";
/// <summary>Wait after a kill so a burst of kills (and the server's own award lines) lands in one read.</summary>
private const long KillDebounceMs = 2000;
/// <summary>Wait after a bounty chat event before re-reading.</summary>
private const long EventDebounceMs = 1500;
/// <summary>The window counts as open while the engine polled the export this recently (it polls every second).</summary>
private const long WindowPollWindowMs = 3000;
/// <summary>A capture with no reply line by then is abandoned.</summary>
private const long FirstLineTimeoutMs = 10000;
/// <summary>A capture whose footer never came ends this long after its last line.</summary>
private const long IdleEndMs = 1500;
/// <summary>The engine may pass our own /bounty list back through the chat bar hook this soon after sending it.</summary>
private const long OwnEchoMs = 2000;
/// <summary>Longer chat lines are never parsed (no bounty line is near this; bounds the regex work).</summary>
private const int MaxLineLength = 512;
private const long SaveDebounceMs = 5000;
/// <summary>A list older than this is re-read when the window opens.</summary>
private static readonly TimeSpan OpenRefreshAge = TimeSpan.FromSeconds(30);
/// <summary>How long a row stays highlighted after its kills went up.</summary>
private static readonly TimeSpan ChangedHighlight = TimeSpan.FromSeconds(15);
private readonly Action<string> _send;
private readonly Action<string> _chat;
private readonly Action<string> _log;
private readonly string _filePath;
private readonly Func<long> _clock;
private BountyState _s;
// Scheduling.
private long _dueAtMs; // 0 = no read scheduled
private long _lastSentMs; // 0 = never this session
private long _lastPollMs; // last engine poll of the export; 0 = never
private bool _wasOpen;
private bool _stale; // kills or bounty events happened while the window was closed
// The quiet "/bounty list" capture.
private bool _capActive;
private bool _capShown; // the player asked too (NoteTypedCommand): parse, never eat
private bool _expectEcho; // our /bounty list may come back through the chat bar hook
private long _capSentMs;
private long _capLastLineMs; // 0 = no reply line yet
private readonly List<BountyListLine> _capLines = new();
private bool _unsupported;
private string _status = string.Empty;
private bool _dirty;
private long _lastSaveMs;
/// <param name="send">Sends a chat command to the server (Host.InvokeChatParser).</param>
/// <param name="chat">Prints a line to the player's chat window.</param>
/// <param name="log">Writes to the RynthCore log.</param>
/// <param name="filePath">bounties.json in the character folder; empty = not persisted.</param>
/// <param name="clock">Milliseconds clock; Environment.TickCount64 unless a test supplies one.</param>
public BountyTracker(Action<string> send, Action<string> chat, Action<string> log, string filePath, Func<long>? clock = null)
{
_send = send;
_chat = chat;
_log = log;
_filePath = filePath ?? string.Empty;
_clock = clock ?? (() => Environment.TickCount64);
_s = Load();
}
private long NowMs => _clock();
/// <summary>The persisted state (host tests).</summary>
internal BountyState State => _s;
/// <summary>True once the server answered "Unknown command: bounty" (no bounty system on this server).</summary>
public bool Unsupported => _unsupported;
/// <summary>True while a "/bounty list" reply is being captured.</summary>
public bool Reading => _capActive;
/// <summary>True while the engine's Bounties window is polling the export.</summary>
public bool WindowOpen => _lastPollMs != 0 && NowMs - _lastPollMs < WindowPollWindowMs;
// ── Scheduling ──────────────────────────────────────────────────────────
/// <summary>
/// Schedules a "/bounty list" read; the earliest pending request wins. Every read waits for
/// MinRefreshSeconds since the last one; <paramref name="respectMinInterval"/> false (a manual
/// refresh) waits only for the MinRefreshFloorSeconds floor.
/// </summary>
private void Schedule(long nowMs, long delayMs, bool respectMinInterval)
{
long due = nowMs + delayMs;
if (_lastSentMs != 0)
due = Math.Max(due, _lastSentMs + (respectMinInterval ? _s.MinRefreshSeconds : MinRefreshFloorSeconds) * 1000L);
if (_dueAtMs == 0 || due < _dueAtMs) _dueAtMs = due;
}
/// <summary>
/// Manual refresh (window button, "/ilt bounty refresh"): retries an unsupported server and
/// reads as soon as the 5 s floor since the last read allows. Never sends with the window
/// closed: the next open reads instead.
/// </summary>
public string RequestRefresh()
{
_unsupported = false;
if (!WindowOpen)
{
_stale = true;
return "The list is read while the Bounties window is open (the ILT button, or /rc bounties).";
}
long now = NowMs;
Schedule(now, 0, respectMinInterval: false);
return "Reading /bounty list...";
}
/// <summary>One of this character's kills (RynthILTPlugin.OnKillNotification).</summary>
public void OnKill()
{
if (!_s.RefreshOnKills || _unsupported) return;
if (WindowOpen) Schedule(NowMs, KillDebounceMs, respectMinInterval: true);
else _stale = true;
}
private void Send(long nowMs)
{
if (_capActive) { _dueAtMs = 0; return; }
// The invariants, whatever scheduled this: the window is open, and the last read was at
// least MinRefreshFloorSeconds ago (else the read waits until then).
if (!WindowOpen) { _dueAtMs = 0; return; }
if (_lastSentMs != 0 && nowMs - _lastSentMs < MinRefreshFloorSeconds * 1000L)
{
_dueAtMs = _lastSentMs + MinRefreshFloorSeconds * 1000L;
return;
}
_dueAtMs = 0;
_lastSentMs = nowMs;
StartCapture(nowMs, shown: false);
_expectEcho = true;
try { _send(ListCommand); }
catch (Exception ex)
{
_capActive = false;
_expectEcho = false;
_status = "could not send /bounty list";
_log($"[RynthILT] Bounties: sending {ListCommand} failed: {ex.Message}");
}
}
private void StartCapture(long nowMs, bool shown)
{
_capActive = true;
_capShown = shown;
_capSentMs = nowMs;
_capLastLineMs = 0;
_capLines.Clear();
}
/// <summary>
/// A "/bounty ..." the player typed (the plugin's OnChatBarEnter, passed on on the pump).
/// Its reply is never eaten: an overlapping capture of ours becomes a shown one, and a typed
/// "/bounty list" (or "/bounty all") starts a shown capture that counts as the next read, so
/// the tracker doesn't send its own on top. Our own command coming back through the chat
/// bar hook right after we sent it is recognised and ignored.
/// </summary>
public void NoteTypedCommand(string text)
{
string t = (text ?? string.Empty).Trim();
long now = NowMs;
if (_expectEcho && now - _capSentMs <= OwnEchoMs && string.Equals(t, ListCommand, StringComparison.OrdinalIgnoreCase))
{
_expectEcho = false;
return;
}
_expectEcho = false;
if (_capActive) { _capShown = true; return; }
if (!IsListCommand(t)) return;
_lastSentMs = now;
_dueAtMs = 0;
StartCapture(now, shown: true);
}
/// <summary>"/bounty list" or "/bounty all" (or with ACE's '@' command prefix).</summary>
internal static bool IsListCommand(string text)
{
string[] parts = (text ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
return parts.Length == 2
&& (parts[0].Equals("/bounty", StringComparison.OrdinalIgnoreCase) || parts[0].Equals("@bounty", StringComparison.OrdinalIgnoreCase))
&& (parts[1].Equals("list", StringComparison.OrdinalIgnoreCase) || parts[1].Equals("all", StringComparison.OrdinalIgnoreCase));
}
/// <summary>True for a chat-bar line that is a /bounty command (what the plugin passes to NoteTypedCommand).</summary>
public static bool IsBountyCommand(string? text)
{
string t = (text ?? string.Empty).TrimStart();
if (!t.StartsWith("/bounty", StringComparison.OrdinalIgnoreCase) && !t.StartsWith("@bounty", StringComparison.OrdinalIgnoreCase))
return false;
return t.Length == 7 || t[7] == ' '; // "/bounty" or "/bounty ...", not "/bountyhunter"
}
public void Tick()
{
long now = NowMs;
if (_capActive)
{
if (_capLastLineMs == 0 && now - _capSentMs >= FirstLineTimeoutMs)
{
_capActive = false;
_expectEcho = false;
if (!_capShown) _status = "no reply to /bounty list";
}
else if (_capLastLineMs != 0 && now - _capLastLineMs >= IdleEndMs)
{
FinishCapture(terminator: null);
}
}
if (_dirty && now - _lastSaveMs >= SaveDebounceMs) Save();
bool open = WindowOpen;
if (!open) { _wasOpen = false; _dueAtMs = 0; return; }
if (!_wasOpen)
{
_wasOpen = true;
if (_stale || _lastSentMs == 0 || DateTime.UtcNow - _s.ListedUtc > OpenRefreshAge)
Schedule(now, 0, respectMinInterval: true);
_stale = false;
}
if (_s.PeriodicRefreshMinutes > 0 && _lastSentMs != 0 && now - _lastSentMs >= _s.PeriodicRefreshMinutes * 60_000L)
Schedule(now, 0, respectMinInterval: true);
if (_dueAtMs != 0 && now >= _dueAtMs && !_unsupported) Send(now);
}
private void FinishCapture(string? terminator)
{
_capActive = false;
_expectEcho = false;
bool complete = terminator != null;
bool none = complete && BountyParse.IsNoBountiesAnywhere(terminator!);
ApplyList(_capLines, complete, none, DateTime.UtcNow);
_status = complete ? string.Empty : "partial reply";
_capLines.Clear();
}
// ── Chat ────────────────────────────────────────────────────────────────
/// <summary>
/// One chat line. Returns true when it belongs to our own "/bounty list" read and should be
/// eaten; everything else (the player's own bounty output, award lines) stays in chat.
/// </summary>
public bool OnChat(string text)
{
string t = (text ?? string.Empty).Trim();
if (t.Length == 0 || t.Length > MaxLineLength) return false;
long now = NowMs;
if (_capActive)
{
// A shown capture (the player asked too) parses the same lines but eats none.
bool eat = !_capShown;
if (BountyParse.IsUnknownCommand(t))
{
_capActive = false;
_expectEcho = false;
_capLines.Clear();
_unsupported = true;
_status = "this server has no /bounty command";
_log("[RynthILT] Bounties: server has no /bounty command; automatic reads stopped.");
return eat;
}
if (t == BountyParse.ListHeader) { _capLastLineMs = now; return eat; }
if (BountyParse.TryParseListLine(t, out var captured)) { _capLines.Add(captured); _capLastLineMs = now; return eat; }
if (BountyParse.IsListTerminator(t)) { FinishCapture(t); return eat; }
}
if (BountyParse.TryParseListLine(t, out var listLine))
{
ApplyList(new[] { listLine }, complete: false, noneAnywhere: false, DateTime.UtcNow);
return false;
}
if (BountyParse.TryParseHereLine(t, out var here))
{
ApplyHere(here, DateTime.UtcNow);
return false;
}
if (BountyParse.TryParseEvent(t, out var kind, out _, out _, out _))
{
_s.LastEvent = t;
_s.LastEventUtc = DateTime.UtcNow;
_dirty = true;
if (kind != BountyEventKind.Held)
{
// Awards can come every kill (a 1-kill bounty with no cooldown): the interval holds.
if (WindowOpen) Schedule(now, EventDebounceMs, respectMinInterval: true);
else _stale = true;
}
}
return false;
}
// ── Applying server output (internal for the host tests) ────────────────
/// <summary>
/// Applies parsed "/bounty list" lines. A complete reply (footer seen) replaces the list in
/// server order; a partial one only updates or appends the rewards it names.
/// </summary>
internal void ApplyList(IReadOnlyList<BountyListLine> lines, bool complete, bool noneAnywhere, DateTime nowUtc)
{
var old = new Dictionary<string, BountyEntry>(StringComparer.OrdinalIgnoreCase);
foreach (var e in _s.Entries)
old[BountyParse.Key(e.Where, e.Amount, e.Item, e.KillsRequired)] = e;
var fresh = new List<BountyEntry>(lines.Count);
foreach (var l in lines)
{
old.TryGetValue(BountyParse.Key(l.Where, l.Amount, l.Item, l.KillsRequired), out var prev);
var e = new BountyEntry
{
Where = l.Where,
Amount = l.Amount,
Item = l.Item,
KillsRequired = l.KillsRequired,
CooldownSeconds = l.CooldownSeconds,
ChangedUtc = prev?.ChangedUtc ?? default,
};
ApplyStatus(e, l.Status, prev, nowUtc);
fresh.Add(e);
}
if (complete)
{
_s.Entries = fresh;
}
else
{
foreach (var e in fresh)
{
string key = BountyParse.Key(e.Where, e.Amount, e.Item, e.KillsRequired);
int i = _s.Entries.FindIndex(x => string.Equals(BountyParse.Key(x.Where, x.Amount, x.Item, x.KillsRequired),
key, StringComparison.OrdinalIgnoreCase));
if (i >= 0) _s.Entries[i] = e; else _s.Entries.Add(e);
}
}
if (complete || lines.Count > 0) _s.ListedUtc = nowUtc;
if (complete) _s.NoneAnywhere = noneAnywhere;
_dirty = true;
}
/// <summary>
/// Applies a "/bounty" (where you stand) line to the one listed reward it can only mean.
/// Returns false when no reward or more than one matches.
/// </summary>
internal bool ApplyHere(BountyHereLine h, DateTime nowUtc)
{
BountyEntry? match = null;
foreach (var e in _s.Entries)
{
if (e.Amount != h.Amount || !string.Equals(e.Item, h.Item, StringComparison.OrdinalIgnoreCase)) continue;
if (h.Status.KillsRequired > 0 && e.KillsRequired != h.Status.KillsRequired) continue;
bool allZones = string.Equals(e.Where, "All zones", StringComparison.OrdinalIgnoreCase);
bool scopeOk = h.Scope.Length == 0 ? !allZones
: h.Scope.Equals("all zones", StringComparison.OrdinalIgnoreCase) ? allZones
: string.Equals(e.Where, h.Scope, StringComparison.OrdinalIgnoreCase);
if (!scopeOk) continue;
if (match != null) return false; // ambiguous: two areas pay the same reward
match = e;
}
if (match == null) return false;
var prev = new BountyEntry { Status = match.Status, Kills = match.Kills };
ApplyStatus(match, h.Status, prev, nowUtc);
_dirty = true;
return true;
}
/// <summary>Copies a parsed status onto <paramref name="e"/> and stamps ChangedUtc when kills went up or an award reset them.</summary>
private static void ApplyStatus(BountyEntry e, BountyStatusInfo st, BountyEntry? prev, DateTime nowUtc)
{
e.Status = (int)st.Status;
e.Kills = st.Status == BountyStatus.Counting ? st.Kills : 0;
e.UnlockAtUtc = st.Status == BountyStatus.Cooldown ? nowUtc.AddSeconds(st.WaitSeconds) : default;
e.QbRequired = st.QbRequired;
e.QbHave = st.QbHave;
if (prev == null) return;
bool wasCounting = prev.Status == (int)BountyStatus.Counting;
bool gained = wasCounting && st.Status == BountyStatus.Counting && st.Kills > prev.Kills;
bool awarded = wasCounting && prev.Kills > 0
&& (st.Status == BountyStatus.Cooldown || (st.Status == BountyStatus.Counting && st.Kills < prev.Kills));
if (gained || awarded) e.ChangedUtc = nowUtc;
}
/// <summary>The status to show now: a cooldown that has ended is "0 of N kills".</summary>
internal static (BountyStatus Status, int Kills) Effective(BountyEntry e, DateTime nowUtc)
{
var st = (BountyStatus)e.Status;
if (st == BountyStatus.Cooldown && nowUtc >= e.UnlockAtUtc) return (BountyStatus.Counting, 0);
return (st, st == BountyStatus.Counting ? e.Kills : 0);
}
/// <summary>"Closest first" order: counting by fraction left, then cooldowns by time left, then QB-locked.</summary>
private static double SortKey(BountyEntry e, DateTime now)
{
var (st, kills) = Effective(e, now);
return st switch
{
BountyStatus.Counting => e.KillsRequired > 0 ? 1.0 - kills / (double)e.KillsRequired : 1.0,
BountyStatus.Cooldown => 2.0 + Math.Min((e.UnlockAtUtc - now).TotalSeconds, 1e9) / 1e9,
_ => 4.0,
};
}
// ── Engine bridge ───────────────────────────────────────────────────────
/// <summary>RynthPluginGetBountiesJson. Each call also marks the window open for the read schedule.</summary>
public string BuildJson()
{
_lastPollMs = NowMs;
var now = DateTime.UtcNow;
var p = new BountyBridgePayload
{
Unsupported = _unsupported,
Reading = _capActive,
Status = _status,
ListedAgoSec = _s.ListedUtc == default ? -1 : AgoSeconds(now - _s.ListedUtc),
NoneAnywhere = _s.NoneAnywhere,
LastEvent = _s.LastEvent,
LastEventAgoSec = _s.LastEventUtc == default ? -1 : AgoSeconds(now - _s.LastEventUtc),
RefreshOnKills = _s.RefreshOnKills,
MinRefreshSeconds = _s.MinRefreshSeconds,
PeriodicRefreshMinutes = _s.PeriodicRefreshMinutes,
HideQbLocked = _s.HideQbLocked,
SortByProgress = _s.SortByProgress,
};
IEnumerable<BountyEntry> shown = _s.Entries;
if (_s.HideQbLocked)
{
p.HiddenCount = _s.Entries.Count(e => e.Status == (int)BountyStatus.NeedsQb);
shown = shown.Where(e => e.Status != (int)BountyStatus.NeedsQb);
}
if (_s.SortByProgress) shown = shown.OrderBy(e => SortKey(e, now));
foreach (var e in shown)
{
var (st, kills) = Effective(e, now);
p.Rows.Add(new BountyRow
{
Where = e.Where,
Amount = e.Amount,
Item = e.Item,
KillsRequired = e.KillsRequired,
CooldownSeconds = e.CooldownSeconds,
Status = (int)st,
Kills = kills,
UnlockInSec = st == BountyStatus.Cooldown ? AgoSeconds(e.UnlockAtUtc - now) : 0,
QbRequired = e.QbRequired,
QbHave = e.QbHave,
Changed = e.ChangedUtc != default && now - e.ChangedUtc < ChangedHighlight,
});
}
return JsonSerializer.Serialize(p, RynthILTJsonContext.Default.BountyBridgePayload);
}
private static int AgoSeconds(TimeSpan span) => (int)Math.Clamp(span.TotalSeconds, 0, int.MaxValue);
/// <summary>
/// RynthPluginBountyCommand: "refresh", or "set {option} {value}" with option one of
/// refreshonkills, minrefreshseconds, periodicminutes, hideqblocked, sortbyprogress.
/// </summary>
public string Command(string text)
{
string[] parts = (text ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0) return string.Empty;
switch (parts[0].ToLowerInvariant())
{
case "refresh":
case "read":
return RequestRefresh();
case "set" when parts.Length >= 3:
return SetOption(parts[1], parts[2]);
default:
return $"unknown bounty command '{text}'";
}
}
private string SetOption(string name, string value)
{
bool on = value is "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase)
|| value.Equals("on", StringComparison.OrdinalIgnoreCase);
int.TryParse(value, out int n);
switch (name.ToLowerInvariant())
{
case "refreshonkills": _s.RefreshOnKills = on; break;
case "minrefreshseconds": _s.MinRefreshSeconds = Math.Clamp(n, MinRefreshFloorSeconds, MinRefreshCeilingSeconds); break;
case "periodicminutes": _s.PeriodicRefreshMinutes = Math.Clamp(n, 0, PeriodicCeilingMinutes); break;
case "hideqblocked": _s.HideQbLocked = on; break;
case "sortbyprogress": _s.SortByProgress = on; break;
default: return $"unknown bounty option '{name}'";
}
_dirty = true;
return string.Empty;
}
// ── Chat command ────────────────────────────────────────────────────────
/// <summary>"/ilt bounty [refresh|list]".</summary>
public void HandleChatCommand(string[] parts)
{
string verb = parts.Length >= 3 ? parts[2].ToLowerInvariant() : "list";
switch (verb)
{
case "refresh":
case "read":
_chat("[Bounties] " + RequestRefresh());
break;
case "list":
case "print":
case "show":
PrintList();
_chat("[Bounties] The Bounties window: the ILT button on the RynthCore bar, or /rc bounties.");
break;
default:
_chat("[Bounties] /ilt bounty [list|refresh] - list the tracked bounties, or re-read /bounty list (while the window is open).");
break;
}
}
/// <summary>One-line chat text for an entry.</summary>
internal static string Describe(BountyEntry e, DateTime nowUtc)
{
var (st, kills) = Effective(e, nowUtc);
string reward = $"{e.Amount:N0} {e.Item}";
return st switch
{
BountyStatus.Counting => $"{e.Where}: {kills:N0}/{e.KillsRequired:N0} kills -> {reward}",
BountyStatus.Cooldown => $"{e.Where}: unlocks in {BountyParse.Duration(e.UnlockAtUtc - nowUtc)}, then {e.KillsRequired:N0} kills -> {reward}",
_ => $"{e.Where}: needs {e.QbRequired:N0} QB (you have {e.QbHave:N0}) -> {reward}",
};
}
/// <summary>"/ilt bounty list": the tracked bounties in chat.</summary>
public void PrintList()
{
if (_unsupported) { _chat("[Bounties] This server has no /bounty command."); return; }
if (_s.Entries.Count == 0)
{
_chat(_s.NoneAnywhere ? "[Bounties] No bounties are active anywhere right now."
: "[Bounties] Nothing read yet. Open the Bounties window (the ILT button, or /rc bounties).");
return;
}
var now = DateTime.UtcNow;
string age = _s.ListedUtc == default ? "never" : BountyParse.Duration(now - _s.ListedUtc) + " ago";
_chat($"[Bounties] {_s.Entries.Count} bounty reward(s), read {age}:");
foreach (var e in _s.Entries) _chat("[Bounties] " + Describe(e, now));
}
// ── Persistence ─────────────────────────────────────────────────────────
private BountyState Load()
{
var s = new BountyState();
try
{
if (_filePath.Length > 0 && File.Exists(_filePath))
s = JsonSerializer.Deserialize(File.ReadAllText(_filePath), RynthILTJsonContext.Default.BountyState) ?? new BountyState();
}
catch (Exception ex)
{
_log($"[RynthILT] Bounties: {_filePath} unreadable, starting empty: {ex.Message}");
s = new BountyState();
}
s.Entries ??= new List<BountyEntry>();
s.Entries.RemoveAll(e => e == null);
s.LastEvent ??= string.Empty;
s.MinRefreshSeconds = Math.Clamp(s.MinRefreshSeconds, MinRefreshFloorSeconds, MinRefreshCeilingSeconds);
s.PeriodicRefreshMinutes = Math.Clamp(s.PeriodicRefreshMinutes, 0, PeriodicCeilingMinutes);
return s;
}
/// <summary>Writes bounties.json when something changed (also called at logout).</summary>
public void Save()
{
_lastSaveMs = NowMs;
if (!_dirty || _filePath.Length == 0) { _dirty = false; return; }
_dirty = false;
try
{
string? dir = Path.GetDirectoryName(_filePath);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
string tmp = _filePath + ".tmp";
File.WriteAllText(tmp, JsonSerializer.Serialize(_s, RynthILTJsonContext.Default.BountyState));
File.Move(tmp, _filePath, overwrite: true);
}
catch (Exception ex)
{
_log($"[RynthILT] Bounties: saving {_filePath} failed: {ex.Message}");
}
}
}

View file

@ -0,0 +1,89 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT;
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<RynthILTPlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => RynthILTPlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => RynthILTPlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
// Bounty lines (and eating the reply to the tracker's own /bounty list).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag)
=> Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
// "/ilt ..." commands, and noticing a /bounty the player typed (its reply is never eaten).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag)
=> Runtime.OnChatBarEnter(textUtf16, eatFlag);
// This character's kills re-read the bounty list (while the Bounties window is open).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnKillNotification", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnKillNotification(IntPtr textUtf16) => Runtime.OnKillNotification(textUtf16);
// ── Bounties bridge (the engine's ImGui Bounties window, UI/Data/BountiesData.cs) ──────
// UTF-8 both ways. Polling the getter is what keeps the tracker's reads running, so only
// the engine's Bounties source may call it (on the plugin pump, 1 s, on ILT only).
// Alloc-new → swap → free-old: the previous reply stays valid until the next call.
private static IntPtr _bountiesPtr = IntPtr.Zero;
/// <summary>The tracked bounties as JSON (BountyBridgePayload); 0 before login.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthILTGetBountiesJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetBountiesJson()
{
try
{
string? json = Runtime.Plugin?.Bounties?.BuildJson();
return json == null ? IntPtr.Zero : Utf8Swap(ref _bountiesPtr, json);
}
catch { return IntPtr.Zero; }
}
/// <summary>"refresh" or "set {option} {value}" (BountyTracker.Command).</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthILTBountyCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void BountyCommand(IntPtr utf8Text)
{
try
{
if (utf8Text == IntPtr.Zero) return;
string? text = Marshal.PtrToStringUTF8(utf8Text);
if (string.IsNullOrEmpty(text) || text.Length > 256) return;
Runtime.Plugin?.Bounties?.Command(text);
}
catch { }
}
private static IntPtr Utf8Swap(ref IntPtr slot, string json)
{
IntPtr newPtr = Marshal.StringToCoTaskMemUTF8(json);
IntPtr oldPtr = Interlocked.Exchange(ref slot, newPtr);
if (oldPtr != IntPtr.Zero) Marshal.FreeCoTaskMem(oldPtr);
return newPtr;
}
}

View file

@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
RynthILT: features for Infinite Leaftide (ILT), the ACECustom server. The engine shows its
panels (the bar's ILT button, /rc bounties) only on ILT (RynthCore Compatibility/IltInfo.cs).
First feature: the Bounties window's tracker (Bounty/, ported from SilentKelpie's
rynth/RynthSuite PR #11). ILT features live here, not in RynthAi or the engine core.
-->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.RynthILT</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthILT</AssemblyName>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Nothing above the v66 baseline: chat
commands, world and object names are behind HasInvokeChatParser / HasGetWorldName /
HasGetObjectName. -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Infinite Leaftide (ACECustom) features: the Bounties window.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,13 @@
using System.Text.Json.Serialization;
using RynthCore.Plugin.RynthILT.Bounty;
namespace RynthCore.Plugin.RynthILT;
// Source-generated System.Text.Json only: never reflection-serialize plugin types (the
// reflection cache keeps the old plugin generation alive across a hot reload).
[JsonSerializable(typeof(BountyState))]
[JsonSerializable(typeof(BountyBridgePayload))]
[JsonSourceGenerationOptions(
IncludeFields = true,
PropertyNameCaseInsensitive = true)]
internal partial class RynthILTJsonContext : JsonSerializerContext { }

View file

@ -0,0 +1,207 @@
// RynthILTPlugin.cs - Infinite Leaftide (ACECustom) features, kept out of RynthAi and the engine core.
//
// The engine shows RynthILT's panels only on ILT (RynthCore Compatibility/IltInfo.cs: the bar's ILT
// button, /rc bounties). First feature: the Bounties window's tracker (Bounty/BountyTracker.cs).
// Its reads run only while that window polls RynthILTGetBountiesJson, and the engine polls only on
// ILT, so on any other server this plugin sends nothing.
//
// Threads: OnTick, OnChatWindowText, OnKillNotification, login/logout and the engine's export calls
// run on the plugin pump. OnChatBarEnter runs on AC's main thread (the engine's dispatcher queues it
// there, our own InvokeChatParser too), so it only queues.
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Runtime.InteropServices;
using RynthCore.Plugin.RynthILT.Bounty;
using RynthCore.PluginCore;
namespace RynthCore.Plugin.RynthILT;
public sealed class RynthILTPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthILT");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.1.0");
/// <summary>Wait this long after login for the character's name before tracking without a save file.</summary>
private const long NameWaitMs = 30_000;
private const long NameRetryMs = 1_000;
private bool _loginComplete;
private long _loginAtMs;
private long _nextNameTryMs;
private BountyTracker? _bounties;
// "/ilt ..." lines from OnChatBarEnter, run on the next tick.
private readonly ConcurrentQueue<string[]> _commands = new();
// "/bounty ..." lines from OnChatBarEnter (typed by the player, or our own coming back through
// the engine's dispatcher), passed to the tracker before the next chat line or tick.
private readonly ConcurrentQueue<string> _typedBounty = new();
/// <summary>The Bounties window's tracker (PluginExports); null until login.</summary>
internal BountyTracker? Bounties => _bounties;
public override int Initialize()
{
Host.Log("[RynthILT] Plugin initialized.");
return 0;
}
// Also called on a freshly (re)loaded plugin while already in game.
public override void OnLoginComplete()
{
SaveBounties();
_bounties = null;
_loginComplete = true;
_loginAtMs = Environment.TickCount64;
_nextNameTryMs = 0;
TryStartBounties();
}
public override void OnLogout()
{
SaveBounties();
_bounties = null;
_loginComplete = false;
while (_commands.TryDequeue(out _)) { }
while (_typedBounty.TryDequeue(out _)) { }
}
// Plugin unload (hot reload, update, client closing): keep the list for the next copy.
public override void Shutdown() => SaveBounties();
public override void OnTick()
{
if (!_loginComplete) return;
if (_bounties == null) TryStartBounties();
DrainTypedBounty();
while (_commands.TryDequeue(out string[]? parts)) RunCommand(parts);
_bounties?.Tick();
}
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
if (_bounties == null || string.IsNullOrEmpty(text)) return;
DrainTypedBounty();
try
{
// Eats only the reply to the tracker's own /bounty list (BountyTracker.OnChat).
if (_bounties.OnChat(text)) eat = 1;
}
catch (Exception ex)
{
Host.Log($"[RynthILT] Bounty chat parse failed: {ex.Message}");
}
}
public override void OnChatBarEnter(string? text, ref int eat)
{
if (!_loginComplete || string.IsNullOrEmpty(text)) return;
string trimmed = text.Trim();
// A /bounty going out: its reply must not be eaten (BountyTracker.NoteTypedCommand). Never eaten here.
if (BountyTracker.IsBountyCommand(trimmed))
{
_typedBounty.Enqueue(trimmed);
return;
}
if (!trimmed.Equals("/ilt", StringComparison.OrdinalIgnoreCase)
&& !trimmed.StartsWith("/ilt ", StringComparison.OrdinalIgnoreCase))
return;
eat = 1;
_commands.Enqueue(trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries));
}
// The server's killer notification: this character landed the killing blow.
public override void OnKillNotification(string? deathMessage) => _bounties?.OnKill();
private void DrainTypedBounty()
{
while (_typedBounty.TryDequeue(out string? typed))
_bounties?.NoteTypedCommand(typed);
}
// ── Commands ─────────────────────────────────────────────────────────────
private void RunCommand(string[] parts)
{
string verb = parts.Length >= 2 ? parts[1].ToLowerInvariant() : "help";
switch (verb)
{
case "bounty":
case "bounties":
case "bountys":
if (_bounties == null) ChatLine("[RynthILT] Bounties not ready (not logged in yet).");
else _bounties.HandleChatCommand(parts);
break;
default:
ChatLine("[RynthILT] /ilt bounty [list|refresh] - the tracked ACECustom bounties. "
+ "The Bounties window: the ILT button on the RynthCore bar, or /rc bounties.");
break;
}
}
private void ChatLine(string text)
{
if (Host.HasWriteToChat) Host.WriteToChat(text, 1);
}
// ── Bounties ─────────────────────────────────────────────────────────────
/// <summary>Starts the tracker once the character's name is known (its save file is per character).</summary>
private void TryStartBounties()
{
long now = Environment.TickCount64;
if (now < _nextNameTryMs) return;
_nextNameTryMs = now + NameRetryMs;
string file = BountyFilePath(out bool named);
if (!named && now - _loginAtMs < NameWaitMs) return;
if (!named) Host.Log("[RynthILT] Bounties: no character name; the list won't be saved this session.");
_bounties = new BountyTracker(SendCommand, ChatLine, Host.Log, file);
}
private void SaveBounties()
{
try { _bounties?.Save(); }
catch (Exception ex) { Host.Log($"[RynthILT] Bounties: save failed: {ex.Message}"); }
}
/// <summary>The tracker's only way to the server: one chat command (Host.InvokeChatParser).</summary>
private void SendCommand(string command)
{
if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command))
throw new InvalidOperationException("the engine's chat parser is not available");
}
/// <summary>
/// %APPDATA%\RynthCore\RynthILT\{world}\{character}\bounties.json, or "" (no save file) while
/// the character's name is unknown. Both names are reduced to safe folder names.
/// </summary>
private string BountyFilePath(out bool named)
{
named = false;
uint me = Host.GetPlayerId();
if (me == 0 || !Host.HasGetObjectName || !Host.TryGetObjectName(me, out string charName)
|| string.IsNullOrWhiteSpace(charName))
return string.Empty;
string world = Host.HasGetWorldName && Host.TryGetWorldName(out string w) && !string.IsNullOrWhiteSpace(w)
? w : "UnknownWorld";
named = true;
return Path.Combine(SettingsRoot, SafeName(world), SafeName(charName), BountyTracker.FileName);
}
/// <summary>RynthILT's settings folder: %APPDATA%\RynthCore\RynthILT.</summary>
internal static string SettingsRoot => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "RynthILT");
/// <summary>A name safe as one folder: invalid characters become '_', no leading/trailing dots or spaces, at most 64 chars.</summary>
internal static string SafeName(string name)
{
char[] invalid = Path.GetInvalidFileNameChars();
var chars = name.Trim().ToCharArray();
for (int i = 0; i < chars.Length; i++)
if (Array.IndexOf(invalid, chars[i]) >= 0 || chars[i] == '/' || chars[i] == '\\') chars[i] = '_';
string s = new string(chars).Trim(' ', '.');
if (s.Length > 64) s = s.Substring(0, 64).TrimEnd(' ', '.');
return s.Length == 0 ? "_" : s;
}
}

View file

@ -0,0 +1,155 @@
using System;
using System.Runtime.InteropServices;
using System.Text.Json;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthSort;
/// <summary>
/// The controller's view of the game through the engine host. Plugin pump thread only (the
/// plugin's tick), which is also where RynthAi's interfaces may be called.
/// </summary>
internal sealed unsafe class HostSortWorld : ISortWorld
{
private readonly RynthCoreHost _host;
private readonly InventoryReader _reader;
private readonly LootWatch _loot;
private readonly Func<bool> _vendorOpenByEvent;
private uint[] _groundBuf = new uint[256];
public HostSortWorld(RynthCoreHost host, InventoryReader reader, LootWatch loot, Func<bool> vendorOpenByEvent)
{
_host = host;
_reader = reader;
_loot = loot;
_vendorOpenByEvent = vendorOpenByEvent;
}
public SortInventory? ReadInventory() => _reader.Read(_host);
public GateInputs ReadGate(bool sortInCombat, long nowMs)
{
var g = new GateInputs { SortInCombat = sortInCombat };
g.InPortalSpace = _host.HasIsPortaling && _host.IsPortaling();
uint ground = _host.HasGetGroundContainerId ? _host.GetGroundContainerId() : 0;
int count = 0;
if (ground != 0)
{
count = _host.HasGetNumContainedItems ? _host.GetNumContainedItems(ground) : -1;
if (count < 0) count = _host.GetContainerContents(ground, _groundBuf);
}
g.Looting = _loot.Update(ground, count, nowMs);
g.VendorOpen = _host.HasVendorTrade ? _host.TryGetVendorInfo(out _) : _vendorOpenByEvent();
g.TradeOpen = _host.HasTrade && _host.TryGetTradeState(out TradeState trade) && trade.IsOpen;
g.ClientBusy = _host.HasGetBusyState && _host.GetBusyState() != 0;
g.Animating = _host.HasGetCastBusyState && _host.GetCastBusyState() != 0;
g.Bot = ReadRynthAi(_host);
return g;
}
public bool SendMove(in SortMove move)
{
uint id = move.Item.Id;
if (move.MergeInto != 0 && _host.HasMergeStackInternal)
return _host.MergeStackInternal(id, move.MergeInto);
return _host.HasMoveItemInternal && _host.MoveItemInternal(id, move.Dest.Id, 0, Math.Max(1, move.Item.Stack));
}
public MoveObservation Observe(uint itemId)
{
var o = new MoveObservation();
if (_host.HasGetObjectOwnershipInfo && _host.TryGetObjectOwnershipInfo(itemId, out uint container, out uint wielder, out _))
{
o.Exists = true;
o.Container = container;
o.Wielder = wielder;
}
else
{
// No ownership info: the object is gone (merged into a stack) when it has no name either.
o.Exists = _host.TryGetObjectName(itemId, out string n) && n.Length > 0;
o.Container = 0xFFFFFFFF;
}
o.Stack = _host.TryGetObjectIntProperty(itemId, 12, out int s) && s > 0 ? s : 1;
if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out uint error, out uint type, out uint obj))
{
o.ErrorSeq = seq;
o.Error = error;
o.ErrorEventType = type;
o.ErrorObject = obj;
}
return o;
}
public int ErrorSeqNow() =>
_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0;
// ── RynthAi ─────────────────────────────────────────────────────────────
/// <summary>
/// RynthAi's activity bits: its "RynthAi.Activity" interface; on an older RynthAi without it,
/// the bot state from "RynthAi.Status" (macro and action); null when RynthAi isn't loaded or not
/// ready. Resolved again every call: a RynthAi reload frees the tables.
/// </summary>
internal static RynthAiActivity? ReadRynthAi(RynthCoreHost host)
{
if (!host.HasGetPluginInterface) return null;
try
{
var act = (RynthAiActivityApiV1*)host.GetPluginInterface("RynthAi", RynthAiActivityApiV1.InterfaceName, RynthAiActivityApiV1.InterfaceVersion);
if (act != null && act->Version >= 1 && act->StructSize >= (uint)sizeof(RynthAiActivityApiV1) && act->GetActivityFlags != null)
{
uint flags = 0;
return act->GetActivityFlags(&flags) != 0 ? (RynthAiActivity)flags : null;
}
var status = (RynthAiStatusApiV1*)host.GetPluginInterface("RynthAi", RynthAiStatusApiV1.InterfaceName, RynthAiStatusApiV1.InterfaceVersion);
if (status != null && status->Version >= 1 && status->StructSize >= (uint)sizeof(RynthAiStatusApiV1) && status->GetStatusJson != null)
{
byte* r = null;
if (status->GetStatusJson(&r) != 0 && r != null)
return FromStatusJson(Marshal.PtrToStringUTF8((IntPtr)r));
}
}
catch
{
// A RynthAi mid-reload: treat as not there this tick.
}
return null;
}
/// <summary>The bits an older RynthAi's status JSON ({macro, action, ...}) gives (no server-wait bit).</summary>
internal static RynthAiActivity? FromStatusJson(string? json)
{
if (string.IsNullOrEmpty(json) || json[0] != '{') return null;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
RynthAiActivity f = RynthAiActivity.None;
if (root.TryGetProperty("macro", out JsonElement m) && m.ValueKind == JsonValueKind.True) f |= RynthAiActivity.MacroRunning;
string action = root.TryGetProperty("action", out JsonElement a) && a.ValueKind == JsonValueKind.String ? a.GetString() ?? "" : "";
if ((f & RynthAiActivity.MacroRunning) != 0)
{
// The display label: Buffing shows as Healing / Restoring mana / Restoring stamina too.
f |= action switch
{
"" or "Default" => RynthAiActivity.None,
"Combat" => RynthAiActivity.Combat,
"Looting" => RynthAiActivity.Looting,
"Salvaging" => RynthAiActivity.Salvaging,
"Navigating" or "Following" => RynthAiActivity.Navigating,
_ => RynthAiActivity.Buffing,
};
}
return f;
}
catch (JsonException)
{
return null;
}
}
}

View file

@ -0,0 +1,56 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthSort;
/// <summary>
/// C ABI exports. Nothing may throw out of an [UnmanagedCallersOnly] method (it would take
/// acclient.exe down): every export goes through RynthPluginRuntime, which catches and logs.
/// RynthSort draws through the engine's script windows (host calls from its own tick), so it
/// exports no render callback and keeps no buffer the engine reads later.
/// </summary>
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<RynthSortPlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
// UTF-8 literals live in the module's read-only data: nothing to allocate or free.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => LiteralPointer("RynthSort"u8);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => LiteralPointer("0.1.0"u8);
private static IntPtr LiteralPointer(ReadOnlySpan<byte> literal)
{
fixed (byte* p = literal)
return (IntPtr)p;
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
// A vendor window (for engines without vendor info, API v67, these are the only signal).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnVendorOpen", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnVendorOpen(uint vendorId) => Runtime.OnVendorOpen(vendorId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnVendorClose", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnVendorClose(uint vendorId) => Runtime.OnVendorClose(vendorId);
}

View file

@ -0,0 +1,49 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
RynthSort: keeps a character's packs sorted while they play or while RynthAi hunts. New
items that land in the main pack move to the side pack their rule names, after a settle
time; Tidy, Clean and Unpack on demand; /rsort. Replaces the RynthSort Lua script (its saved
rules are imported on first run). Pack moves wait for RynthAi through its read-only
"RynthAi.Activity" interface (Shared/RynthAiActivityApi.cs). UI: the engine's script
windows (ImGui), no Avalonia.
-->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.RynthSort</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthSort</AssemblyName>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Script windows (v71, HasUi) draw the
window; vendor info (v67), plugin interfaces (v68), refusals (v70) and trade (v72) are
each checked first. Below v71 it still sorts (/rsort on|off|now|tidy|clean|unpack). -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Keeps your packs sorted: new loot goes to the pack its rule names.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>
<!-- What RynthAi is doing (read only), so pack moves stay out of its way. -->
<Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<!-- An older RynthAi without RynthAi.Activity: its RynthAi.Status bot state instead. -->
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,318 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Ui;
using RynthCore.Plugin.RynthSort.Views;
using RynthCore.PluginCore;
namespace RynthCore.Plugin.RynthSort;
/// <summary>
/// RynthSort: keeps your packs sorted while you play or RynthAi hunts. New items that land in the
/// main pack move to the side pack their rule names once they have sat there for the settle time;
/// Tidy also moves misplaced items between side packs, Clean sends items no rule wants back to the
/// main pack, Unpack empties the side packs. Rules are tried in order and the first that matches
/// wins: by item class or by part of the name. Rules and settings are kept per character; the
/// RynthSort Lua script's saved rules are taken over on a character's first run.
///
/// It stays out of the way (Sorting/SortGate.cs): nothing moves while a corpse or chest is being
/// looted, a vendor or trade window is open, the character is busy or animating, in portal space,
/// or while RynthAi is looting, salvaging, buffing, making ammo, waiting on the server or (unless
/// "Sort during fights" is on) fighting. One move at a time, each waited on, then a gap.
///
/// Everything runs on the plugin pump (OnTick and the events the engine drains into it) except
/// OnChatBarEnter, which the engine may call on AC's thread: it only queues the command.
/// </summary>
public sealed class RynthSortPlugin : RynthPluginBase
{
public const string Version = "0.1.0";
private const long IdentityRetryMs = 1000;
private const long SaveDelayMs = 750;
private const long PassIntervalMs = 500;
private readonly SortStore _store = new();
private readonly InventoryReader _reader = new();
private readonly LootWatch _loot = new();
private readonly SortController _sort = new();
private readonly UiHost _ui = new();
private readonly ConcurrentQueue<string> _commands = new();
private HostSortWorld? _world;
private UiWindow? _window;
private SortPanel? _panel;
private bool _inWorld;
private bool _identityKnown;
private long _nextIdentityTryMs;
private string _server = string.Empty;
private string _character = string.Empty;
private long _saveDueMs;
private bool _vendorOpen;
private bool _noUiLogged;
private readonly List<string> _warnings = new();
public override int Initialize()
{
_ui.Log = msg => Host.Log(msg);
_world = new HostSortWorld(Host, _reader, _loot, () => _vendorOpen);
_sort.SettingsChanged = RequestSave;
_panel = new SortPanel(_sort, RequestSave)
{
Warnings = () => _warnings,
Character = () => _identityKnown ? _character : string.Empty,
};
_window = _ui.Add(new UiWindow("RynthSort/Main", "RynthSort")
{
DefaultWidth = 360f, DefaultHeight = 420f, MinWidth = 300f, MinHeight = 200f,
});
Host.Log($"[RynthSort] {Version} initialized. /rsort shows or hides the window; /rsort on|off|now|tidy|clean|unpack. Files: {_store.Root}");
return 0;
}
// The engine calls this on a real login and on a freshly (re)loaded plugin already in game.
public override void OnLoginComplete()
{
_inWorld = true;
_identityKnown = false;
_nextIdentityTryMs = Environment.TickCount64;
_sort.Reset();
_reader.Reset();
_loot.Reset();
_warnings.Clear();
}
public override void OnLogout()
{
SaveNow();
_inWorld = false;
_identityKnown = false;
_sort.Reset();
_reader.Reset();
_loot.Reset();
_vendorOpen = false;
if (_window != null) { _window.Visible = false; _window.NeedsPass = true; }
_ui.SubmitEmpty(Host);
}
public override void Shutdown()
{
SaveNow();
_ui.SubmitEmpty(Host);
}
public override void OnVendorOpen(uint vendorId) => _vendorOpen = true;
public override void OnVendorClose(uint vendorId) => _vendorOpen = false;
// ── Chat ────────────────────────────────────────────────────────────────
// May run on AC's thread: classify and queue only.
public override void OnChatBarEnter(string? text, ref int eat)
{
if (string.IsNullOrWhiteSpace(text)) return;
string t = text.Trim();
if (!t.StartsWith("/rsort", StringComparison.OrdinalIgnoreCase) || (t.Length > 6 && !char.IsWhiteSpace(t[6])))
return;
eat = 1;
_commands.Enqueue(t.Length > 6 ? t.Substring(6).Trim() : string.Empty);
}
private void RunCommand(string arg)
{
string[] words = arg.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string word = words.Length > 0 ? words[0].ToLowerInvariant() : string.Empty;
if (word.Length > 0 && !_identityKnown && word is not ("help" or "?"))
{
Print("Log in first.");
return;
}
switch (word)
{
case "":
if (_window != null) { _window.Visible = !_window.Visible; _window.NeedsPass = true; }
if (_window != null && _window.Visible && !Host.HasUi && !_noUiLogged)
{
_noUiLogged = true;
Print("This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Sorting still runs: /rsort on|off|now|tidy|clean|unpack.");
}
break;
case "on":
case "off":
_sort.SetAuto(word == "on");
Print("Auto-sort " + word);
break;
case "now":
_sort.StartJob(SortScope.Main);
break;
case "tidy":
_sort.StartJob(SortScope.All);
break;
case "clean":
_sort.StartJob(SortScope.Clean);
break;
case "unpack":
{
int? n = words.Length > 1 && int.TryParse(words[1], out int p) && p > 0 ? p : null;
_sort.StartUnpack(n);
Print((n != null ? $"Emptying pack {n}" : "Emptying your side packs") + " into the main pack; auto-sort is off (/rsort on when done).");
break;
}
case "status":
PrintStatus();
break;
default:
Print("/rsort [on | off | now | tidy | clean | unpack [pack] | status]");
break;
}
if (_window != null) _window.NeedsPass = true;
}
private void PrintStatus()
{
SortView v = _sort.Planner.View;
Print($"{_character}: auto-sort {(_sort.Data.Settings.Auto ? "on" : "off")}, {_sort.Status}; {_sort.Data.Rules.Count} rules, "
+ $"{v.Packs.Count} side packs, main pack {v.MainUsed}/{v.MainCapacity}; moved {_sort.Moved}, failed {_sort.Failed} this session.");
}
private void Print(string text)
{
if (!Host.WriteToChat("[RynthSort] " + text, 1))
Host.Log("[RynthSort] " + text);
}
// ── Tick ────────────────────────────────────────────────────────────────
public override void OnTick()
{
long now = Environment.TickCount64;
while (_commands.TryDequeue(out string? cmd)) RunCommand(cmd);
_ui.Poll(Host);
if (_inWorld)
{
if (!_identityKnown && now >= _nextIdentityTryMs) TryStartCharacter(now);
if (_identityKnown && _world != null)
{
try { _sort.Tick(_world, now); }
catch (Exception ex)
{
Host.Log($"[RynthSort] sorting step failed: {ex.GetType().Name}: {ex.Message}");
}
}
}
if (_saveDueMs != 0 && now >= _saveDueMs) SaveNow();
if (!Host.HasUi || _window == null || _panel == null) return;
Record(_window, now);
_ui.Submit(Host, now);
if (_identityKnown && _window.Visible != _sort.Data.Settings.WindowOpen)
{
_sort.Data.Settings.WindowOpen = _window.Visible;
RequestSave();
}
}
private void TryStartCharacter(long now)
{
_nextIdentityTryMs = now + IdentityRetryMs;
uint player = Host.GetPlayerId();
if (player == 0 || !Host.TryGetObjectName(player, out string name) || string.IsNullOrWhiteSpace(name)) return;
string server = Host.TryGetWorldName(out string w) ? w : string.Empty;
_server = server;
_character = name;
CharacterSortData data = _store.Load(server, name, out string? problem);
if (problem != null) Host.Log($"[RynthSort] couldn't read the saved rules ({problem}); using defaults.");
_sort.Data = data;
_identityKnown = true;
string own = _store.PathFor(server, name);
if (data.ImportedFrom.Length > 0 && !File.Exists(own))
{
string? error = _store.Save(server, name, data);
Print(error == null
? $"Took over the RynthSort script's rules for {name} ({data.Rules.Count} rules, auto-sort {(data.Settings.Auto ? "on" : "off")})."
: $"Took over the RynthSort script's rules for {name}, but couldn't save them: {error}");
Host.Log($"[RynthSort] imported {data.ImportedFrom} -> {own}");
}
CheckLuaScriptAutostart(server, name);
if (_window != null) { _window.Visible = data.Settings.WindowOpen; _window.NeedsPass = true; }
Host.Log($"[RynthSort] sorting for {name} on {server}: {data.Rules.Count} rules, auto-sort {(data.Settings.Auto ? "on" : "off")}; file {own}");
}
/// <summary>The RynthSort Lua script set to start too would sort beside the plugin: say so.</summary>
private void CheckLuaScriptAutostart(string server, string character)
{
_warnings.Clear();
try
{
string path = Path.Combine(RynthCore.Install.RynthInstallPaths.SuiteDir, "RynthLua", "settings.json");
if (!File.Exists(path)) return;
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path));
if (!LuaScriptStarts(doc.RootElement, server + "|" + character)) return;
const string line = "The RynthSort Lua script is set to start too; stop it in RynthLua so only one sorts";
_warnings.Add(line);
Print(line + ".");
}
catch
{
// Only a warning.
}
}
/// <summary>True when RynthLua's settings start the "RynthSort" script for everyone or for this character.</summary>
internal static bool LuaScriptStarts(JsonElement root, string characterKey)
{
if (root.ValueKind != JsonValueKind.Object) return false;
static bool Has(JsonElement list)
{
if (list.ValueKind != JsonValueKind.Array) return false;
foreach (JsonElement e in list.EnumerateArray())
if (e.ValueKind == JsonValueKind.String && string.Equals(e.GetString(), "RynthSort", StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
if (root.TryGetProperty("GlobalScripts", out JsonElement g) && Has(g)) return true;
if (root.TryGetProperty("CharacterScripts", out JsonElement c) && c.ValueKind == JsonValueKind.Object)
foreach (JsonProperty p in c.EnumerateObject())
if (string.Equals(p.Name, characterKey, StringComparison.OrdinalIgnoreCase) && Has(p.Value)) return true;
return false;
}
private void RequestSave()
{
if (_window != null) _window.NeedsPass = true;
if (_saveDueMs == 0) _saveDueMs = Environment.TickCount64 + SaveDelayMs;
}
private void SaveNow()
{
_saveDueMs = 0;
if (!_identityKnown) return;
_sort.Data.Settings.Clamp();
string? error = _store.Save(_server, _character, _sort.Data);
if (error != null) Host.Log("[RynthSort] save failed: " + error);
}
/// <summary>A pass when one is wanted, or on the refresh interval while visible (the status ticks on).</summary>
private void Record(UiWindow w, long now)
{
bool due = w.NeedsPass || (w.Visible && now >= w.NextPassMs);
if (!due) return;
w.NeedsPass = false;
w.NextPassMs = now + PassIntervalMs;
w.Begin();
try
{
_panel!.Draw(w);
}
catch (Exception ex)
{
w.TextWrapped($"Something went wrong drawing this window: {ex.GetType().Name}: {ex.Message}");
Host.Log($"[RynthSort] {w.Key} pass failed: {ex}");
}
w.End();
}
}

View file

@ -0,0 +1,260 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthCore.Plugin.RynthSort;
/// <summary>RynthSort's settings for one character (the Lua script's DEFAULTS, plus what the plugin adds).</summary>
internal sealed class SortSettings
{
public const int SettleMin = 0, SettleMax = 30, GapMin = 100, GapMax = 3000;
/// <summary>Auto-sort: new items in the main pack go to their pack after the settle time.</summary>
public bool Auto = true;
/// <summary>How long a new item sits in the main pack before it moves (seconds).</summary>
public int SettleSec = 5;
/// <summary>Auto-sort's pause between two moves (ms), to leave the bot room.</summary>
public int GapMs = 300;
/// <summary>Moves may go while RynthAi fights (never while it waits on the server or animates).</summary>
public bool SortInCombat;
/// <summary>The window was open when last seen.</summary>
public bool WindowOpen = true;
public void Clamp()
{
SettleSec = Math.Clamp(SettleSec, SettleMin, SettleMax);
GapMs = Math.Clamp(GapMs, GapMin, GapMax);
}
}
/// <summary>One character's rules and settings.</summary>
internal sealed class CharacterSortData
{
public List<SortRule> Rules = SortRules.Defaults();
public SortSettings Settings = new();
/// <summary>Where these came from on first run ("" = defaults, else the Lua script's file).</summary>
public string ImportedFrom = string.Empty;
}
/// <summary>
/// Per-character files: &lt;SuiteDir&gt;\RynthSort\characters\&lt;server_character&gt;.json, written by
/// hand and read with JsonDocument (plugin types never go through System.Text.Json's serializer,
/// which roots them across hot reloads). The same shape as the Lua script's saved data
/// ({"rules":[...],"settings":{...}}), so its file (&lt;SuiteDir&gt;\RynthLua\Data\RynthSort\characters\...)
/// is read the same way when a character has no RynthSort file yet.
/// </summary>
internal sealed class SortStore
{
public const int MaxRules = 64;
public const int MaxPack = 32;
/// <summary>RynthSort's folder (tests point it at a temp folder).</summary>
public string Root;
/// <summary>The Lua script's data folder for RynthSort (tests point it at a temp folder).</summary>
public string LuaDataRoot;
public SortStore()
{
string suite = RynthCore.Install.RynthInstallPaths.SuiteDir;
Root = Path.Combine(suite, "RynthSort");
LuaDataRoot = Path.Combine(suite, "RynthLua", "Data", "RynthSort");
}
public SortStore(string root, string luaDataRoot)
{
Root = root;
LuaDataRoot = luaDataRoot;
}
/// <summary>"server_character" made safe as a file name, as the Lua script's storage names it.</summary>
public static string FileStem(string server, string character) => SafeFileName($"{server}_{character}");
public string PathFor(string server, string character) => Path.Combine(Root, "characters", FileStem(server, character) + ".json");
public string LuaPathFor(string server, string character) => Path.Combine(LuaDataRoot, "characters", FileStem(server, character) + ".json");
/// <summary>
/// The character's rules and settings: RynthSort's own file; else the Lua script's (imported:
/// <see cref="CharacterSortData.ImportedFrom"/> says so, and the caller saves it as RynthSort's);
/// else the defaults. A broken file reads as the defaults (the next save rewrites it).
/// </summary>
public CharacterSortData Load(string server, string character, out string? problem)
{
problem = null;
string own = PathFor(server, character);
if (File.Exists(own))
{
if (TryRead(own, out CharacterSortData? d, out problem)) return d!;
return new CharacterSortData();
}
string lua = LuaPathFor(server, character);
if (File.Exists(lua) && TryRead(lua, out CharacterSortData? imported, out problem))
{
imported!.ImportedFrom = lua;
return imported;
}
return new CharacterSortData();
}
public static bool TryRead(string path, out CharacterSortData? data, out string? problem)
{
data = null;
problem = null;
try
{
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path),
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
data = Parse(doc.RootElement);
return true;
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException or InvalidOperationException)
{
problem = $"{Path.GetFileName(path)}: {ex.Message}";
return false;
}
}
/// <summary>Rules and settings from the file's root object; anything missing or odd keeps its default.</summary>
internal static CharacterSortData Parse(JsonElement root)
{
var d = new CharacterSortData();
if (root.ValueKind != JsonValueKind.Object) throw new JsonException("the file isn't a JSON object");
if (root.TryGetProperty("rules", out JsonElement rules))
{
// The Lua script saved an empty rule list as {} (an empty Lua table): no rules either.
if (rules.ValueKind == JsonValueKind.Array)
{
d.Rules = new List<SortRule>();
foreach (JsonElement e in rules.EnumerateArray())
{
if (d.Rules.Count >= MaxRules) break;
SortRule? r = ParseRule(e);
if (r != null) d.Rules.Add(r);
}
}
else if (rules.ValueKind == JsonValueKind.Object && !rules.EnumerateObject().MoveNext())
{
d.Rules = new List<SortRule>();
}
}
if (root.TryGetProperty("settings", out JsonElement s) && s.ValueKind == JsonValueKind.Object)
{
SortSettings st = d.Settings;
st.Auto = Bool(s, "auto", st.Auto);
st.SettleSec = Int(s, "settleSec", st.SettleSec);
st.GapMs = Int(s, "gapMs", st.GapMs);
st.SortInCombat = Bool(s, "sortInCombat", st.SortInCombat);
st.WindowOpen = Bool(s, "windowOpen", st.WindowOpen);
st.Clamp();
}
if (root.TryGetProperty("importedFrom", out JsonElement f) && f.ValueKind == JsonValueKind.String)
d.ImportedFrom = f.GetString() ?? string.Empty;
return d;
}
private static SortRule? ParseRule(JsonElement e)
{
if (e.ValueKind != JsonValueKind.Object) return null;
var r = new SortRule
{
On = Bool(e, "on", true),
Kind = e.TryGetProperty("kind", out JsonElement k) && k.ValueKind == JsonValueKind.String
&& string.Equals(k.GetString(), "name", StringComparison.OrdinalIgnoreCase) ? RuleKind.Name : RuleKind.Class,
Class = Int(e, "class", ObjectClasses.SpellComponent),
Text = e.TryGetProperty("text", out JsonElement t) && t.ValueKind == JsonValueKind.String ? t.GetString() ?? string.Empty : string.Empty,
Pack = Math.Clamp(Int(e, "pack", 1), 1, MaxPack),
};
if (r.Text.Length > 64) r.Text = r.Text[..64];
return r;
}
/// <summary>Writes the character's file (temp file, then moved over the old one). Returns an error or null.</summary>
public string? Save(string server, string character, CharacterSortData d)
{
string path = PathFor(server, character);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp";
File.WriteAllText(tmp, ToJson(d), new UTF8Encoding(false));
File.Move(tmp, path, overwrite: true);
return null;
}
catch (Exception ex)
{
return ex.Message;
}
}
internal static string ToJson(CharacterSortData d)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteNumber("version", 1);
w.WriteStartArray("rules");
foreach (SortRule r in d.Rules)
{
w.WriteStartObject();
w.WriteBoolean("on", r.On);
w.WriteString("kind", r.Kind == RuleKind.Name ? "name" : "class");
w.WriteNumber("class", r.Class);
w.WriteString("text", r.Text ?? string.Empty);
w.WriteNumber("pack", r.Pack);
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteStartObject("settings");
w.WriteBoolean("auto", d.Settings.Auto);
w.WriteNumber("settleSec", d.Settings.SettleSec);
w.WriteNumber("gapMs", d.Settings.GapMs);
w.WriteBoolean("sortInCombat", d.Settings.SortInCombat);
w.WriteBoolean("windowOpen", d.Settings.WindowOpen);
w.WriteEndObject();
if (d.ImportedFrom.Length > 0) w.WriteString("importedFrom", d.ImportedFrom);
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray()) + "\n";
}
private static bool Bool(JsonElement o, string name, bool fallback) =>
o.TryGetProperty(name, out JsonElement v) && (v.ValueKind == JsonValueKind.True || v.ValueKind == JsonValueKind.False)
? v.GetBoolean()
: fallback;
private static int Int(JsonElement o, string name, int fallback)
{
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return fallback;
if (v.TryGetInt32(out int i)) return i;
// Lua numbers are doubles: 5.0 is 5.
return v.TryGetDouble(out double dbl) && dbl >= int.MinValue && dbl <= int.MaxValue ? (int)Math.Round(dbl) : fallback;
}
private static readonly HashSet<string> ReservedNames = new(StringComparer.OrdinalIgnoreCase)
{
"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$",
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
};
/// <summary>RynthLua's LibraryStorage.SafeFileName, so both name a character's file the same way.</summary>
public static string SafeFileName(string? name)
{
var invalid = Path.GetInvalidFileNameChars();
var chars = (name ?? string.Empty).Trim().ToCharArray();
for (int i = 0; i < chars.Length; i++)
if (Array.IndexOf(invalid, chars[i]) >= 0 || chars[i] < 32) chars[i] = '_';
string n = new string(chars).TrimEnd('.', ' ');
if (n.Length > 80) n = n[..80].TrimEnd('.', ' ');
if (n.Length == 0 || n.Trim('.').Length == 0) n = "_" + n;
string stem = n.Split('.')[0];
if (ReservedNames.Contains(stem)) n = "_" + n;
return n;
}
}

View file

@ -0,0 +1,191 @@
using System;
using System.Collections.Generic;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>
/// Reads the character's packs from the client into a <see cref="SortInventory"/>. Plugin pump
/// thread only. GetContainerContents(player) gives the main pack's items, the side packs and the
/// worn and wielded items; each side pack's items come from GetContainerContents(pack). A side
/// pack is a container that holds items (ItemsCapacity above 0); foci hold none and are skipped,
/// as are worn and wielded items. Names, classes and stack limits are kept per item id once read.
/// </summary>
internal sealed class InventoryReader
{
private const uint IntItemsCapacity = 6, IntMaxStackSize = 11, IntStackSize = 12;
private const uint ItemTypeMeleeWeapon = 0x00000001, ItemTypeArmor = 0x00000002, ItemTypeClothing = 0x00000004,
ItemTypeJewelry = 0x00000008, ItemTypeCreature = 0x00000010, ItemTypeFood = 0x00000020, ItemTypeMoney = 0x00000040,
ItemTypeMisc = 0x00000080, ItemTypeMissileWeapon = 0x00000100, ItemTypeContainer = 0x00000200,
ItemTypeGem = 0x00000800, ItemTypeSpellComponents = 0x00001000, ItemTypeWritable = 0x00002000,
ItemTypeKey = 0x00004000, ItemTypeCaster = 0x00008000, ItemTypePortal = 0x00010000,
ItemTypePromissoryNote = 0x00040000, ItemTypeManaStone = 0x00080000, ItemTypeService = 0x00100000,
ItemTypeCraftCookingBase = 0x00400000, ItemTypeCraftAlchemyBase = 0x00800000,
ItemTypeCraftFletchingBase = 0x02000000, ItemTypeCraftAlchemyIntermediate = 0x04000000,
ItemTypeCraftFletchingIntermediate = 0x08000000, ItemTypeLifeStone = 0x10000000,
ItemTypeTinkeringTool = 0x20000000, ItemTypeTinkeringMaterial = 0x40000000;
// PublicWeenieDesc bitfield bits RynthLua's classifier reads for items.
private const uint BfFood = 0x8000, BfHealer = 0x10000, BfLockpick = 0x20000;
private sealed class Known
{
public string Name = string.Empty;
public int Class;
public uint Wcid;
public int MaxStack = 1;
}
private readonly Dictionary<uint, Known> _known = new();
private uint[] _buf = new uint[512];
public void Reset() => _known.Clear();
/// <summary>The packs now, or null when the character or its inventory isn't readable yet.</summary>
public SortInventory? Read(RynthCoreHost host)
{
if (!host.HasGetPlayerId || !host.HasGetContainerContents) return null;
uint player = host.GetPlayerId();
if (player == 0) return null;
var inv = new SortInventory();
inv.Main.Id = player;
inv.Main.Name = "Main pack";
inv.Main.Capacity = host.TryGetObjectIntProperty(player, IntItemsCapacity, out int mainCap) && mainCap > 0 ? mainCap : 0;
uint[] top = Contents(host, player);
if (top.Length == 0) return null; // not loaded yet: never plan from an empty read
foreach (uint id in top)
{
if (id == 0) continue;
if (Wielded(host, id)) continue;
uint type = host.TryGetItemType(id, out uint t) ? t : 0;
if ((type & ItemTypeContainer) != 0)
{
// A side pack holds items; foci (containers that hold none) aren't packs or items.
if (host.TryGetObjectIntProperty(id, IntItemsCapacity, out int cap) && cap > 0)
{
var pack = new SortPack { Id = id, Capacity = cap, Name = host.TryGetObjectName(id, out string pn) ? pn : string.Empty };
foreach (uint inner in Contents(host, id))
{
if (inner == 0) continue;
uint it = host.TryGetItemType(inner, out uint itt) ? itt : 0;
if ((it & ItemTypeContainer) != 0) continue;
pack.Items.Add(Item(host, inner, it));
}
inv.Packs.Add(pack);
}
continue;
}
inv.Main.Items.Add(Item(host, id, type));
}
return inv;
}
private uint[] Contents(RynthCoreHost host, uint container)
{
int n = host.GetContainerContents(container, _buf);
if (n >= _buf.Length)
{
_buf = new uint[_buf.Length * 2];
n = host.GetContainerContents(container, _buf);
}
if (n <= 0) return Array.Empty<uint>();
var ids = new uint[n];
Array.Copy(_buf, ids, n);
return ids;
}
private static bool Wielded(RynthCoreHost host, uint id)
{
if (host.HasGetObjectOwnershipInfo && host.TryGetObjectOwnershipInfo(id, out _, out uint wielder, out _))
return wielder != 0;
return host.HasGetObjectWielderInfo && host.TryGetObjectWielderInfo(id, out uint w, out _) && w != 0;
}
private SortItem Item(RynthCoreHost host, uint id, uint type)
{
if (!_known.TryGetValue(id, out Known? k))
{
k = new Known();
k.Name = host.TryGetObjectName(id, out string name) ? name : string.Empty;
k.Wcid = host.HasGetObjectWcid && host.TryGetObjectWcid(id, out uint wcid) ? wcid : 0;
k.MaxStack = host.TryGetObjectIntProperty(id, IntMaxStackSize, out int max) && max > 0 ? max : 1;
k.Class = Classify(host, id, type, k.Name, out bool certain);
// Kept once the client had the data (a fresh object can lack its name or type for a tick).
if (certain && k.Name.Length > 0) _known[id] = k;
}
int stack = host.TryGetObjectIntProperty(id, IntStackSize, out int s) && s > 0 ? s : 1;
return new SortItem { Id = id, Name = k.Name, ObjectClass = k.Class, Wcid = k.Wcid, Stack = stack, MaxStack = k.MaxStack };
}
/// <summary>
/// The item's ObjectClass the way RynthLua's game.World classifies items (GameWorldObject.cs:
/// the healer / lockpick / food bits, then the ItemType flags most specific first, scrolls and
/// foci by name), so a rule means the same in both.
/// </summary>
internal static int Classify(RynthCoreHost host, uint id, uint type, string name, out bool certain)
{
certain = false;
uint bf = 0;
bool gotBf = host.HasGetObjectBitfield && host.TryGetObjectBitfield(id, out bf) && bf != 0;
if (!gotBf) bf = 0;
return ClassifyFrom(type, bf, name, out certain);
}
/// <summary>The classification from the raw data (pure).</summary>
internal static int ClassifyFrom(uint type, uint bitfield, string name, out bool certain)
{
certain = false;
name ??= string.Empty;
if (type != 0 && (type & ItemTypeCreature) != 0) { certain = true; return ObjectClasses.Monster; }
if (bitfield != 0)
{
if ((bitfield & BfHealer) != 0) { certain = true; return ObjectClasses.HealingKit; }
if ((bitfield & BfLockpick) != 0) { certain = true; return ObjectClasses.Lockpick; }
}
if (type != 0)
{
certain = true;
int cls = ClassifyByItemType(type);
if (cls == ObjectClasses.Book && name.Contains("Scroll", StringComparison.OrdinalIgnoreCase)) return ObjectClasses.Scroll;
if (name.StartsWith("Foci of", StringComparison.OrdinalIgnoreCase)) return ObjectClasses.Foci;
if (cls == ObjectClasses.Misc && (bitfield & BfFood) != 0) return ObjectClasses.Food;
return cls;
}
if ((bitfield & BfFood) != 0) { certain = true; return ObjectClasses.Food; }
return ObjectClasses.Unknown;
}
private static int ClassifyByItemType(uint t)
{
if ((t & ItemTypePromissoryNote) != 0) return ObjectClasses.TradeNote;
if ((t & ItemTypeManaStone) != 0) return ObjectClasses.ManaStone;
if ((t & ItemTypeSpellComponents) != 0) return ObjectClasses.SpellComponent;
if ((t & ItemTypeGem) != 0) return ObjectClasses.Gem;
if ((t & ItemTypeKey) != 0) return ObjectClasses.Key;
if ((t & ItemTypeLifeStone) != 0) return ObjectClasses.Lifestone;
if ((t & ItemTypeTinkeringMaterial) != 0) return ObjectClasses.Salvage;
if ((t & ItemTypeTinkeringTool) != 0) return ObjectClasses.Ust;
if ((t & ItemTypeCraftCookingBase) != 0) return ObjectClasses.BaseCooking;
if ((t & ItemTypeCraftAlchemyBase) != 0) return ObjectClasses.BaseAlchemy;
if ((t & ItemTypeCraftFletchingBase) != 0) return ObjectClasses.BaseFletching;
if ((t & ItemTypeCraftAlchemyIntermediate) != 0) return ObjectClasses.CraftedAlchemy;
if ((t & ItemTypeCraftFletchingIntermediate) != 0) return ObjectClasses.CraftedFletching;
if ((t & ItemTypeService) != 0) return ObjectClasses.Services;
if ((t & ItemTypePortal) != 0) return ObjectClasses.Portal;
if ((t & ItemTypeWritable) != 0) return ObjectClasses.Book;
if ((t & ItemTypeContainer) != 0) return ObjectClasses.Container;
if ((t & ItemTypeCaster) != 0) return ObjectClasses.WandStaffOrb;
if ((t & ItemTypeMissileWeapon) != 0) return ObjectClasses.MissileWeapon;
if ((t & ItemTypeArmor) != 0) return ObjectClasses.Armor;
if ((t & ItemTypeMeleeWeapon) != 0) return ObjectClasses.MeleeWeapon;
if ((t & ItemTypeClothing) != 0) return ObjectClasses.Clothing;
if ((t & ItemTypeJewelry) != 0) return ObjectClasses.Jewelry;
if ((t & ItemTypeFood) != 0) return ObjectClasses.Food;
if ((t & ItemTypeMoney) != 0) return ObjectClasses.Money;
if ((t & ItemTypeMisc) != 0) return ObjectClasses.Misc;
return ObjectClasses.Unknown;
}
}

View file

@ -0,0 +1,84 @@
using System;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>How a move in flight ended (or that it hasn't yet).</summary>
internal enum MoveOutcome
{
Pending,
/// <summary>The item is in the destination, or merged into a stack there.</summary>
Done,
/// <summary>The server refused it (InventoryServerSaveFailed, or a refusal naming the item).</summary>
Refused,
/// <summary>The server said "You're too busy" (or too many actions): try again later.</summary>
TooBusy,
/// <summary>No answer in <see cref="MoveTracker.TimeoutMs"/>.</summary>
TimedOut,
}
/// <summary>What the client says about the moved item and the server's last refusal, read each tick.</summary>
internal struct MoveObservation
{
public bool Exists;
public uint Container;
public uint Wielder;
public int Stack;
/// <summary>The engine's refusal counter (TryGetLastWeenieError seq; 0 when unknown).</summary>
public int ErrorSeq;
public uint Error;
public uint ErrorEventType;
public uint ErrorObject;
}
/// <summary>The one move RynthSort has out.</summary>
internal sealed class MoveInFlight
{
public SortMove Move;
public long SentMs;
public int ErrorSeqAtSend;
public int StackAtSend;
}
/// <summary>
/// One move at a time: what counts as its answer, and how long to hold off after a refusal.
/// Pure (no host calls), so the tests drive it with observations.
/// </summary>
internal static class MoveTracker
{
/// <summary>A move with no answer by then has failed (the Lua script's ObjectMove time limit).</summary>
public const long TimeoutMs = 5000;
/// <summary>An item that couldn't be moved is left alone this long.</summary>
public const long BlockMs = 60_000;
/// <summary>The longest hold after refusals in a row.</summary>
public const long MaxBackoffMs = 30_000;
public const uint EventInventoryServerSaveFailed = 0x00A0;
public const uint ErrorYoureTooBusy = 0x001D;
public const uint ErrorTooManyActions = 0x0045;
public static MoveOutcome Observe(MoveInFlight m, in MoveObservation o, long nowMs)
{
SortMove mv = m.Move;
if (!o.Exists) return MoveOutcome.Done; // merged on arrival
if (o.Container == mv.Dest.Id && o.Wielder == 0) return MoveOutcome.Done;
if (mv.MergeInto != 0 && o.Stack < m.StackAtSend) return MoveOutcome.Done; // part of it joined the stack
if (o.ErrorSeq != 0 && o.ErrorSeq != m.ErrorSeqAtSend)
{
if (o.Error == ErrorYoureTooBusy || o.Error == ErrorTooManyActions) return MoveOutcome.TooBusy;
if (o.ErrorObject == mv.Item.Id || o.ErrorEventType == EventInventoryServerSaveFailed) return MoveOutcome.Refused;
// Someone else's refusal (a fizzle, RynthAi's use): not ours; keep waiting.
}
return nowMs - m.SentMs >= TimeoutMs ? MoveOutcome.TimedOut : MoveOutcome.Pending;
}
/// <summary>
/// The hold before the next move after <paramref name="failuresInARow"/> failures: 2 s, 4 s,
/// 8 s ... up to <see cref="MaxBackoffMs"/>; 0 after a success.
/// </summary>
public static long BackoffMs(int failuresInARow)
{
if (failuresInARow <= 0) return 0;
int shift = Math.Min(failuresInARow - 1, 10);
return Math.Min(2000L << shift, MaxBackoffMs);
}
}

View file

@ -0,0 +1,236 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>What the controller needs from the game (the plugin's HostSortWorld; the tests' fake).</summary>
internal interface ISortWorld
{
/// <summary>The packs now, or null when they can't be read yet.</summary>
SortInventory? ReadInventory();
/// <summary>The "stay out of the way" inputs now.</summary>
GateInputs ReadGate(bool sortInCombat, long nowMs);
/// <summary>Sends the move to the client (merge or plain move). False = the engine refused it.</summary>
bool SendMove(in SortMove move);
/// <summary>The moved item and the server's last refusal.</summary>
MoveObservation Observe(uint itemId);
/// <summary>The engine's refusal counter now (0 when the engine can't say).</summary>
int ErrorSeqNow();
}
/// <summary>
/// The sorting loop, one step per plugin tick: one move at a time, each waited on until the
/// server answers it (the item lands, or it is refused, or the time limit passes), then a gap.
/// Auto-sort moves new main-pack items after the settle time, one per gap; a job asked for
/// (Sort now, Tidy, Clean, Unpack) goes as fast as the server answers. Nothing is sent while the
/// gate says why not (<see cref="SortGate"/>). An item that fails is left alone for a minute, and
/// failures in a row hold every move off longer and longer (<see cref="MoveTracker.BackoffMs"/>).
/// </summary>
internal sealed class SortController
{
/// <summary>Between two moves of a job asked for (the server's answer came already).</summary>
public const long JobGapMs = 100;
/// <summary>How often the gate is checked while paused (and auto-sort off is looked at).</summary>
public const long PollMs = 250;
/// <summary>How often the packs are read while nothing moves (and for the window while paused).</summary>
public const long ViewMs = 1000;
public const int LogLines = 6;
public CharacterSortData Data = new();
public readonly SortPlanner Planner = new();
public readonly SortGate Gate = new();
/// <summary>"watching", "off", "sorting", "unpacking", "paused: ..."; shown beside the auto-sort box.</summary>
public string Status { get; private set; } = "starting";
public bool Paused => Status.StartsWith("paused", StringComparison.Ordinal);
/// <summary>A one-off job asked for, or null.</summary>
public SortScope? Job { get; private set; }
/// <summary>The side pack Unpack empties (null = all).</summary>
public int? UnpackWhich { get; private set; }
/// <summary>RynthAi's bits from the last gate read (null = RynthAi not there or not ready).</summary>
public RynthAiActivity? LastBot { get; private set; }
/// <summary>The last few moves and job results, newest first.</summary>
public readonly List<string> Log = new();
public int Moved { get; private set; }
public int Failed { get; private set; }
/// <summary>Settings changed by a command (auto-sort off for Unpack): the plugin saves.</summary>
public Action? SettingsChanged;
private MoveInFlight? _inFlight;
private long _nextStepMs;
private long _nextViewMs;
private int _failuresInARow;
public bool HasMoveOut => _inFlight != null;
/// <summary>Forget the character (logout, another character's data).</summary>
public void Reset()
{
Planner.Reset();
Gate.Reset();
_inFlight = null;
_nextStepMs = _nextViewMs = 0;
_failuresInARow = 0;
Job = null;
UnpackWhich = null;
LastBot = null;
Status = "starting";
Log.Clear();
Moved = Failed = 0;
}
// ── Asking ──────────────────────────────────────────────────────────────
public void SetAuto(bool on)
{
Data.Settings.Auto = on;
SettingsChanged?.Invoke();
}
/// <summary>Sort now (Main), Tidy (All) or Clean, as soon as the way is clear.</summary>
public void StartJob(SortScope scope)
{
if (scope == SortScope.Unpack) { StartUnpack(null); return; }
Job = scope;
_nextStepMs = 0;
}
/// <summary>Empty every side pack (or pack <paramref name="which"/>) into the main pack; auto-sort goes off first so nothing moves straight back.</summary>
public void StartUnpack(int? which)
{
Data.Settings.Auto = false;
Job = SortScope.Unpack;
UnpackWhich = which;
_nextStepMs = 0;
SettingsChanged?.Invoke();
}
public void Note(string line)
{
Log.Insert(0, line);
while (Log.Count > LogLines) Log.RemoveAt(Log.Count - 1);
}
// ── The loop ────────────────────────────────────────────────────────────
public void Tick(ISortWorld world, long nowMs)
{
if (_inFlight != null)
{
MoveObservation o = world.Observe(_inFlight.Move.Item.Id);
MoveOutcome outcome = MoveTracker.Observe(_inFlight, in o, nowMs);
if (outcome == MoveOutcome.Pending) return;
Finish(_inFlight.Move, outcome, nowMs);
_inFlight = null;
return;
}
if (nowMs < _nextStepMs) return;
SortScope? scope = Job ?? (Data.Settings.Auto ? SortScope.Main : null);
if (scope == null)
{
Status = "off";
LastBot = null;
RefreshView(world, SortScope.Main, nowMs);
_nextStepMs = nowMs + PollMs;
return;
}
GateInputs g = world.ReadGate(Data.Settings.SortInCombat, nowMs);
LastBot = g.Bot;
string? why = Gate.Evaluate(in g, nowMs);
if (why != null)
{
Status = "paused: " + why;
RefreshView(world, scope == SortScope.Unpack ? SortScope.Main : scope.Value, nowMs);
_nextStepMs = nowMs + PollMs;
return;
}
SortInventory? inv = world.ReadInventory();
if (inv == null)
{
Status = "waiting for the inventory";
_nextStepMs = nowMs + ViewMs;
return;
}
_nextViewMs = nowMs + ViewMs;
List<SortMove> moves = scope == SortScope.Unpack
? Planner.PlanUnpack(inv, UnpackWhich, nowMs)
: Planner.Plan(inv, Data.Rules, scope.Value, force: Job != null, nowMs, Data.Settings.SettleSec * 1000);
if (moves.Count == 0)
{
if (Job != null) NoteJobDone(Job.Value);
Job = null;
UnpackWhich = null;
Status = Data.Settings.Auto ? "watching" : "off";
_nextStepMs = nowMs + ViewMs; // nothing to do: look again in a second (the Lua script's pace)
return;
}
Status = scope == SortScope.Unpack ? "unpacking" : "sorting";
SortMove m = moves[0];
int seq = world.ErrorSeqNow();
if (!world.SendMove(in m))
{
Finish(m, MoveOutcome.Refused, nowMs, "the engine refused the move");
return;
}
_inFlight = new MoveInFlight { Move = m, SentMs = nowMs, ErrorSeqAtSend = seq, StackAtSend = m.Item.Stack };
}
private void NoteJobDone(SortScope job)
{
SortView v = Planner.View;
switch (job)
{
case SortScope.Unpack: Note(v.MainFull ? "Main pack is full: unpacking stopped" : "Side packs emptied"); break;
case SortScope.Clean: Note(v.MainFull ? "Main pack is full: some strays left" : "Packs cleaned"); break;
case SortScope.All: Note(v.Waiting > 0 ? $"Packs tidied ({v.Waiting} can't move yet)" : "Packs tidied"); break;
default: Note(v.Waiting > 0 ? $"Main pack sorted ({v.Waiting} can't move yet)" : "Main pack sorted"); break;
}
}
private void Finish(SortMove m, MoveOutcome outcome, long nowMs, string? why = null)
{
string name = m.Item.Name.Length > 0 ? m.Item.Name : $"0x{m.Item.Id:X8}";
long gap = Job != null ? JobGapMs : Data.Settings.GapMs;
switch (outcome)
{
case MoveOutcome.Done:
Moved++;
_failuresInARow = 0;
Note($"{name} -> {m.DestLabel}");
_nextStepMs = nowMs + gap;
return;
case MoveOutcome.TooBusy:
// Not the item's fault: no block, just a longer hold.
_failuresInARow++;
Note($"{name}: the server is busy, trying again");
_nextStepMs = nowMs + Math.Max(gap, MoveTracker.BackoffMs(_failuresInARow));
return;
default:
Failed++;
_failuresInARow++;
Planner.Block(m.Item.Id, nowMs + MoveTracker.BlockMs);
why ??= outcome == MoveOutcome.TimedOut ? "no answer from the server" : "the server refused it";
Note($"{name}: not moved ({why})");
_nextStepMs = nowMs + Math.Max(gap, MoveTracker.BackoffMs(_failuresInARow));
return;
}
}
/// <summary>Re-reads the packs for the window now and then while nothing moves.</summary>
private void RefreshView(ISortWorld world, SortScope scope, long nowMs)
{
if (nowMs < _nextViewMs) return;
_nextViewMs = nowMs + ViewMs;
SortInventory? inv = world.ReadInventory();
if (inv == null) return;
if (scope == SortScope.Unpack) Planner.PlanUnpack(inv, UnpackWhich, nowMs);
else Planner.Plan(inv, Data.Rules, scope, force: false, nowMs, Data.Settings.SettleSec * 1000);
}
}

View file

@ -0,0 +1,124 @@
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>Everything the "stay out of the way" check looks at, read once per pass.</summary>
internal struct GateInputs
{
public bool InPortalSpace;
/// <summary>A corpse or chest is being looted (<see cref="LootWatch"/>).</summary>
public bool Looting;
public bool VendorOpen;
public bool TradeOpen;
/// <summary>The client's busy count is above zero (a use, a cast, or anyone's item move in flight).</summary>
public bool ClientBusy;
/// <summary>The character's motion queue isn't empty (a gesture, a cast animation, a stance change).</summary>
public bool Animating;
/// <summary>RynthAi's activity bits (RynthAi.Activity), or null when RynthAi isn't loaded or not ready.</summary>
public RynthAiActivity? Bot;
/// <summary>The "Sort during fights" setting: moves may go while RynthAi fights (still never mid-action).</summary>
public bool SortInCombat;
}
/// <summary>
/// Why no item may move right now, or null when it's fine. Never while a corpse or chest is
/// being looted, a vendor or trade window is open, the character is busy with a use or cast or
/// still animating, or in portal space; and never while RynthAi is looting, salvaging, buffing,
/// healing, making ammo or waiting on the server for something it sent. While RynthAi fights,
/// nothing moves either unless "Sort during fights" is on. After any pause, moves wait
/// <see cref="QuietMs"/> more (the next corpse, cast or buff is often a moment away).
/// </summary>
internal sealed class SortGate
{
/// <summary>How long the way must have been clear before the next move.</summary>
public const long QuietMs = 1500;
private long _pausedAt = long.MinValue / 2;
private string _lastReason = string.Empty;
/// <summary>The reason without the quiet time: pure, for the tests and the window.</summary>
public static string? Reason(in GateInputs g)
{
if (g.InPortalSpace) return "portal space";
if (g.Looting) return "looting";
if (g.VendorOpen) return "vendor open";
if (g.TradeOpen) return "trading";
if (g.ClientBusy || g.Animating) return "busy";
if (g.Bot is RynthAiActivity a)
{
if ((a & RynthAiActivity.Looting) != 0) return "RynthAi is looting";
if ((a & RynthAiActivity.Salvaging) != 0) return "RynthAi is salvaging";
if ((a & RynthAiActivity.Buffing) != 0) return "RynthAi is buffing";
if ((a & RynthAiActivity.Crafting) != 0) return "RynthAi is making ammo";
if ((a & RynthAiActivity.ServerAction) != 0) return "RynthAi is waiting on the server";
if ((a & RynthAiActivity.Combat) != 0 && !g.SortInCombat) return "RynthAi is fighting";
}
return null;
}
/// <summary>The reason, held for <see cref="QuietMs"/> after it clears.</summary>
public string? Evaluate(in GateInputs g, long nowMs)
{
string? why = Reason(in g);
if (why != null)
{
_pausedAt = nowMs;
_lastReason = why;
return why;
}
return nowMs - _pausedAt < QuietMs ? _lastReason : null;
}
public void Reset()
{
_pausedAt = long.MinValue / 2;
_lastReason = string.Empty;
}
}
/// <summary>
/// Whether the open corpse or chest is being looted. The client keeps reporting the last corpse
/// as open after it has been looted (until another opens or you walk away), so an open container
/// only counts while something is happening to it: it just opened, or its contents changed,
/// within <see cref="ActiveMs"/>; and for <see cref="AfterMs"/> after that (the next corpse is
/// often a moment away). The Lua script's rule, unchanged.
/// </summary>
internal sealed class LootWatch
{
public const long ActiveMs = 4000;
public const long AfterMs = 1500;
private uint _id;
private int _count = -1;
private long _changedAt = long.MinValue / 2;
private long _lastLootingAt = long.MinValue / 2;
/// <param name="containerId">The open ground container (0 = none).</param>
/// <param name="itemCount">How many items it holds now.</param>
public bool Update(uint containerId, int itemCount, long nowMs)
{
if (containerId != 0)
{
if (containerId != _id || itemCount != _count)
{
_id = containerId;
_count = itemCount;
_changedAt = nowMs;
}
if (nowMs - _changedAt < ActiveMs)
{
_lastLootingAt = nowMs;
return true;
}
}
return nowMs - _lastLootingAt < AfterMs;
}
public void Reset()
{
_id = 0;
_count = -1;
_changedAt = long.MinValue / 2;
_lastLootingAt = long.MinValue / 2;
}
}

View file

@ -0,0 +1,34 @@
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>One loose item in a pack, as read this pass (InventoryReader).</summary>
internal sealed class SortItem
{
public uint Id;
public string Name = string.Empty;
/// <summary>ObjectClass number (<see cref="ObjectClasses"/>).</summary>
public int ObjectClass;
public uint Wcid;
public int Stack = 1;
public int MaxStack = 1;
/// <summary>Worn or wielded (the reader leaves these out; kept so the planner can refuse them too).</summary>
public bool Wielded { get; set; }
}
/// <summary>The main pack or one side pack and its loose items (packs and foci are never items).</summary>
internal sealed class SortPack
{
public uint Id;
public string Name = string.Empty;
/// <summary>How many items it holds (ItemsCapacity; 102 for the main pack and 24 for a side pack when unknown).</summary>
public int Capacity;
public readonly List<SortItem> Items = new();
}
/// <summary>The character's packs: the main pack and the side packs in order, top to bottom (pack 1 first).</summary>
internal sealed class SortInventory
{
public SortPack Main = new();
public readonly List<SortPack> Packs = new();
}

View file

@ -0,0 +1,252 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>What a planning pass looks at.</summary>
internal enum SortScope
{
/// <summary>Only the main pack; an item moves once it has sat there for the settle time (unless forced).</summary>
Main,
/// <summary>Every pack, no settling: items in the wrong side pack move to theirs too ("Tidy").</summary>
All,
/// <summary>As <see cref="All"/>, and side-pack items no rule wants go back to the main pack ("Clean").</summary>
Clean,
/// <summary>Every side pack (or one) emptied into the main pack ("Unpack").</summary>
Unpack,
}
/// <summary>One move: <see cref="Item"/> into <see cref="Dest"/> (pack <see cref="DestIndex"/>, 0 = main pack).</summary>
internal readonly struct SortMove
{
public readonly SortItem Item;
public readonly SortPack Dest;
public readonly int DestIndex;
/// <summary>A stack in <see cref="Dest"/> the item joins (a merge), or 0 for a plain move.</summary>
public readonly uint MergeInto;
public SortMove(SortItem item, SortPack dest, int destIndex, uint mergeInto)
{
Item = item;
Dest = dest;
DestIndex = destIndex;
MergeInto = mergeInto;
}
public string DestLabel => DestIndex == 0 ? "main pack" : "pack " + DestIndex;
}
/// <summary>A side pack as the window lists it.</summary>
internal sealed class PackLine
{
public string Name = string.Empty;
public int Used;
public int Capacity;
}
/// <summary>What the window shows about the packs after a planning pass.</summary>
internal sealed class SortView
{
public readonly List<PackLine> Packs = new();
public int MainUsed;
public int MainCapacity;
/// <summary>Items a rule wants moved that can't go yet (settling, pack full, pack missing, main full).</summary>
public int Waiting;
/// <summary>Side packs (1-based) a rule wants to fill that are full.</summary>
public readonly SortedSet<int> Full = new();
/// <summary>Pack numbers rules use that the character doesn't have.</summary>
public readonly SortedSet<int> Missing = new();
/// <summary>Clean or Unpack found the main pack full.</summary>
public bool MainFull;
}
/// <summary>
/// The sorting rules applied to the packs: which items move where, one planning pass at a time.
/// A port of the Lua script's plan/planUnpack: rules are tried in order and the first match wins;
/// worn and wielded items, packs and foci never move; a full pack is only used when the item
/// joins a stack there; an item that failed to move is left alone until its block runs out.
/// Pure (no host calls): the tests drive it with hand-made inventories.
/// </summary>
internal sealed class SortPlanner
{
public const int SideCapacityFallback = 24;
public const int MainCapacityFallback = 102;
private readonly Dictionary<uint, long> _firstSeen = new();
private readonly Dictionary<uint, long> _blocked = new();
public SortView View { get; private set; } = new();
/// <summary>Forget everything (logout, another character).</summary>
public void Reset()
{
_firstSeen.Clear();
_blocked.Clear();
View = new SortView();
}
/// <summary>Leave <paramref name="itemId"/> alone until <paramref name="untilMs"/> (a move failed).</summary>
public void Block(uint itemId, long untilMs) => _blocked[itemId] = untilMs;
public bool IsBlocked(uint itemId, long nowMs) => _blocked.TryGetValue(itemId, out long until) && until > nowMs;
public int BlockedCount(long nowMs)
{
int n = 0;
foreach (long until in _blocked.Values) if (until > nowMs) n++;
return n;
}
/// <summary>Worn and wielded items, packs and foci never move.</summary>
public static bool Sortable(SortItem it) =>
!it.Wielded && it.ObjectClass != ObjectClasses.Container && it.ObjectClass != ObjectClasses.Foci;
public static int CapacityOf(SortPack p, int fallback) => p.Capacity > 0 ? p.Capacity : fallback;
/// <summary>
/// A stack in <paramref name="pack"/> that <paramref name="it"/> can join (the same kind, with room
/// left), or 0. That is what lets a full pack still take the item.
/// </summary>
public static uint StackTarget(SortItem it, SortPack pack)
{
if (it.MaxStack <= 1) return 0;
foreach (SortItem other in pack.Items)
{
if (other.Id == it.Id || !SameKind(it, other)) continue;
int max = other.MaxStack > 1 ? other.MaxStack : it.MaxStack;
if (other.Stack < max) return other.Id;
}
return 0;
}
private static bool SameKind(SortItem a, SortItem b) =>
a.Wcid != 0 && b.Wcid != 0 ? a.Wcid == b.Wcid : string.Equals(a.Name, b.Name, StringComparison.Ordinal) && a.Name.Length > 0;
/// <summary>
/// The moves to make now for <paramref name="scope"/> (not <see cref="SortScope.Unpack"/>: see
/// <see cref="PlanUnpack"/>), first one first. Also refreshes <see cref="View"/> and the main
/// pack's settle clock (an item's time starts when a pass first sees it in the main pack).
/// </summary>
public List<SortMove> Plan(SortInventory inv, IReadOnlyList<SortRule> rules, SortScope scope, bool force, long nowMs, int settleMs)
{
bool everyPack = scope != SortScope.Main;
bool evict = scope == SortScope.Clean;
var moves = new List<SortMove>();
var view = new SortView();
var used = new int[inv.Packs.Count + 1];
for (int i = 0; i < inv.Packs.Count; i++) used[i + 1] = inv.Packs[i].Items.Count;
int mainUsed = inv.Main.Items.Count;
int mainCap = CapacityOf(inv.Main, MainCapacityFallback);
void Consider(SortItem wo, int from, bool settled)
{
if (!Sortable(wo) || IsBlocked(wo.Id, nowMs)) return;
SortRule? r = SortRules.RuleFor(rules, wo);
if (r == null && evict && from > 0)
{
// In a side pack and no rule wants it: back to the main pack, while there is room.
uint joins = StackTarget(wo, inv.Main);
if (mainUsed < mainCap || joins != 0)
{
moves.Add(new SortMove(wo, inv.Main, 0, joins));
if (joins == 0) mainUsed++;
}
else
{
view.MainFull = true;
view.Waiting++;
}
return;
}
if (r == null || r.Pack == from) return;
if (r.Pack < 1 || r.Pack > inv.Packs.Count)
{
view.Missing.Add(r.Pack);
view.Waiting++;
return;
}
SortPack dest = inv.Packs[r.Pack - 1];
uint into = StackTarget(wo, dest);
if (used[r.Pack] >= CapacityOf(dest, SideCapacityFallback) && into == 0)
{
view.Full.Add(r.Pack);
view.Waiting++;
return;
}
if (!settled)
{
view.Waiting++;
return;
}
moves.Add(new SortMove(wo, dest, r.Pack, into));
if (into == 0) used[r.Pack]++;
}
var inMain = new HashSet<uint>();
foreach (SortItem wo in inv.Main.Items)
{
inMain.Add(wo.Id);
if (!_firstSeen.TryGetValue(wo.Id, out long seen)) _firstSeen[wo.Id] = seen = nowMs;
Consider(wo, 0, force || everyPack || nowMs - seen >= settleMs);
}
if (_firstSeen.Count > inMain.Count)
{
var gone = new List<uint>();
foreach (uint id in _firstSeen.Keys) if (!inMain.Contains(id)) gone.Add(id);
foreach (uint id in gone) _firstSeen.Remove(id);
}
if (everyPack)
{
for (int i = 0; i < inv.Packs.Count; i++)
foreach (SortItem wo in inv.Packs[i].Items) Consider(wo, i + 1, true);
}
FillPacks(view, inv);
View = view;
return moves;
}
/// <summary>
/// Emptying side packs into the main pack: every sortable item in side pack <paramref name="which"/>
/// (1-based; null = all of them), while the main pack has room or the item joins a stack there.
/// </summary>
public List<SortMove> PlanUnpack(SortInventory inv, int? which, long nowMs)
{
var moves = new List<SortMove>();
int used = inv.Main.Items.Count;
int cap = CapacityOf(inv.Main, MainCapacityFallback);
int waiting = 0;
for (int i = 0; i < inv.Packs.Count; i++)
{
if (which != null && which.Value != i + 1) continue;
foreach (SortItem wo in inv.Packs[i].Items)
{
if (!Sortable(wo) || IsBlocked(wo.Id, nowMs)) continue;
uint joins = StackTarget(wo, inv.Main);
if (used < cap || joins != 0)
{
moves.Add(new SortMove(wo, inv.Main, 0, joins));
if (joins == 0) used++;
}
else waiting++;
}
}
var view = new SortView { Waiting = waiting, MainFull = waiting > 0 };
FillPacks(view, inv);
View = view;
return moves;
}
private static void FillPacks(SortView view, SortInventory inv)
{
view.MainUsed = inv.Main.Items.Count;
view.MainCapacity = CapacityOf(inv.Main, MainCapacityFallback);
foreach (SortPack p in inv.Packs)
view.Packs.Add(new PackLine
{
Name = p.Name.Length > 0 ? p.Name : "Pack",
Used = p.Items.Count,
Capacity = CapacityOf(p, SideCapacityFallback),
});
}
}

View file

@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>Which test a rule makes.</summary>
internal enum RuleKind
{
/// <summary>The item's ObjectClass equals <see cref="SortRule.Class"/>.</summary>
Class = 0,
/// <summary>The item's name contains <see cref="SortRule.Text"/> (any case).</summary>
Name = 1,
}
/// <summary>
/// One rule: items it matches go to side pack <see cref="Pack"/> (1 = the first side pack, top to
/// bottom). The same fields as the Lua script's rules: { on, kind = "class" | "name", class, text, pack }.
/// </summary>
internal sealed class SortRule
{
public bool On = true;
public RuleKind Kind = RuleKind.Class;
/// <summary>An ObjectClass number (<see cref="ObjectClasses"/>).</summary>
public int Class = ObjectClasses.SpellComponent;
public string Text = string.Empty;
public int Pack = 1;
public SortRule Clone() => new() { On = On, Kind = Kind, Class = Class, Text = Text, Pack = Pack };
public static SortRule ForClass(int cls, int pack) => new() { Kind = RuleKind.Class, Class = cls, Pack = pack };
public static SortRule ForName(string text, int pack) => new() { Kind = RuleKind.Name, Text = text, Pack = pack };
}
/// <summary>
/// The ObjectClass numbers, as RynthLua's ObjectClass enum (LuaEnums.ObjectClass: Decal/UtilityBelt
/// order), so rules saved by the Lua script mean the same thing here.
/// </summary>
internal static class ObjectClasses
{
public static readonly string[] Names =
{
"Unknown", "MeleeWeapon", "Armor", "Clothing", "Jewelry", "Monster", "Food", "Money", "Misc",
"MissileWeapon", "Container", "Gem", "SpellComponent", "Key", "Portal", "TradeNote", "ManaStone",
"Plant", "BaseCooking", "BaseAlchemy", "BaseFletching", "CraftedCooking", "CraftedAlchemy",
"CraftedFletching", "Player", "Vendor", "Door", "Corpse", "Lifestone", "HealingKit", "Lockpick",
"WandStaffOrb", "Bundle", "Book", "Journal", "Sign", "Housing", "Npc", "Foci", "Salvage", "Ust",
"Services", "Scroll",
};
public const int Unknown = 0, MeleeWeapon = 1, Armor = 2, Clothing = 3, Jewelry = 4, Monster = 5, Food = 6,
Money = 7, Misc = 8, MissileWeapon = 9, Container = 10, Gem = 11, SpellComponent = 12, Key = 13, Portal = 14,
TradeNote = 15, ManaStone = 16, Plant = 17, BaseCooking = 18, BaseAlchemy = 19, BaseFletching = 20,
CraftedCooking = 21, CraftedAlchemy = 22, CraftedFletching = 23, Player = 24, Vendor = 25, Door = 26,
Corpse = 27, Lifestone = 28, HealingKit = 29, Lockpick = 30, WandStaffOrb = 31, Bundle = 32, Book = 33,
Journal = 34, Sign = 35, Housing = 36, Npc = 37, Foci = 38, Salvage = 39, Ust = 40, Services = 41, Scroll = 42;
/// <summary>The classes the rule editor offers, in the Lua script's order.</summary>
public static readonly int[] Choices =
{
SpellComponent, Salvage, Gem, ManaStone, Key, HealingKit, Lockpick, Food, Scroll, TradeNote, Money, Plant,
BaseAlchemy, BaseCooking, BaseFletching, CraftedAlchemy, CraftedCooking, CraftedFletching, Jewelry, Armor,
Clothing, MeleeWeapon, MissileWeapon, WandStaffOrb, Bundle, Book, Journal, Ust, Misc,
};
/// <summary>"Spell Component" for SpellComponent, as the Lua script showed them.</summary>
public static readonly string[] ChoiceLabels = BuildLabels();
private static string[] BuildLabels()
{
var labels = new string[Choices.Length];
for (int i = 0; i < Choices.Length; i++) labels[i] = Spaced(Names[Choices[i]]);
return labels;
}
/// <summary>A space before each capital that follows a small letter ("ManaStone" -> "Mana Stone").</summary>
public static string Spaced(string name)
{
var sb = new StringBuilder(name.Length + 4);
for (int i = 0; i < name.Length; i++)
{
if (i > 0 && char.IsUpper(name[i]) && char.IsLower(name[i - 1])) sb.Append(' ');
sb.Append(name[i]);
}
return sb.ToString();
}
/// <summary>The index of <paramref name="cls"/> in <see cref="Choices"/>, or -1.</summary>
public static int ChoiceIndex(int cls) => Array.IndexOf(Choices, cls);
public static string Label(int cls) =>
cls >= 0 && cls < Names.Length ? Spaced(Names[cls]) : "class " + cls;
}
internal static class SortRules
{
/// <summary>The Lua script's defaults: components, salvage, then gems, stones and keys together.</summary>
public static List<SortRule> Defaults() => new()
{
SortRule.ForClass(ObjectClasses.SpellComponent, 1),
SortRule.ForClass(ObjectClasses.Salvage, 2),
SortRule.ForClass(ObjectClasses.Gem, 3),
SortRule.ForClass(ObjectClasses.ManaStone, 3),
SortRule.ForClass(ObjectClasses.Key, 3),
};
public static bool Matches(SortRule r, SortItem item)
{
if (!r.On) return false;
if (r.Kind == RuleKind.Name)
{
string t = r.Text ?? string.Empty;
return t.Length > 0 && (item.Name ?? string.Empty).Contains(t, StringComparison.OrdinalIgnoreCase);
}
return item.ObjectClass == r.Class;
}
/// <summary>The first rule that matches (rules are tried in order), or null.</summary>
public static SortRule? RuleFor(IReadOnlyList<SortRule> rules, SortItem item)
{
for (int i = 0; i < rules.Count; i++)
if (Matches(rules[i], item)) return rules[i];
return null;
}
public static string Describe(SortRule r) =>
r.Kind == RuleKind.Name ? $"name has \"{r.Text}\"" : ObjectClasses.Label(r.Class);
}

View file

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

View file

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

View file

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

View file

@ -0,0 +1,197 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Ui;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthSort.Views;
/// <summary>
/// The RynthSort window: the auto-sort box and status, the job buttons, warnings, the rule list
/// (first match wins: enable, select to edit, add, move up or down, remove) and the settings.
/// Recorded on the pump thread, replayed by the engine.
/// </summary>
internal sealed class SortPanel
{
private static readonly string[] Kinds = { "Class", "Name has" };
private readonly SortController _c;
private readonly Action _save;
private int _selected = -1;
/// <summary>Extra warnings the plugin knows about (the Lua script set to start too).</summary>
public Func<IReadOnlyList<string>> Warnings = () => Array.Empty<string>();
/// <summary>The character (blank before login).</summary>
public Func<string> Character = () => string.Empty;
public SortPanel(SortController c, Action save)
{
_c = c;
_save = save;
}
public int Selected => _selected;
public void Draw(UiWindow w)
{
if (Character().Length == 0)
{
w.TextDisabled("Log in to sort your packs.");
return;
}
SortSettings s = _c.Data.Settings;
List<SortRule> rules = _c.Data.Rules;
w.Checkbox("Auto-sort", "auto", s.Auto, v => _c.SetAuto(v));
w.Tooltip("New items in the main pack go to their pack after the settle time");
w.SameLine();
w.TextColored(_c.Paused ? UiColors.Amber : UiColors.Grey, _c.Status);
if (_c.Planner.View.Waiting > 0)
{
w.SameLine();
w.TextDisabled($"({_c.Planner.View.Waiting} waiting)");
}
w.Button("Sort main pack", "job.main", () => _c.StartJob(SortScope.Main));
w.Tooltip("Sort the main pack now, without waiting for items to settle");
w.SameLine();
w.Button("Tidy all packs", "job.all", () => _c.StartJob(SortScope.All));
w.Tooltip("Also move items that are in the wrong side pack");
w.SameLine();
w.Button("Empty side packs", "job.unpack", () => _c.StartUnpack(null));
w.Tooltip("Move everything from your side packs into the main pack. Turns auto-sort off first, so nothing moves back.");
w.Button("Clean packs", "job.clean", () => _c.StartJob(SortScope.Clean));
w.Tooltip("Side-pack items no rule wants go to the main pack; items in the wrong side pack go to theirs");
SortView view = _c.Planner.View;
if (view.MainFull) w.TextColored(UiColors.Amber, "The main pack is full");
foreach (int p in view.Full) w.TextColored(UiColors.Amber, $"Pack {p} is full");
foreach (int p in view.Missing) w.TextColored(UiColors.Amber, $"A rule uses pack {p}, which you don't have");
if (s.Auto && _c.LastBot is RynthAiActivity bot && (bot & RynthAiActivity.AutoCram) != 0 && (bot & RynthAiActivity.MacroRunning) != 0)
w.TextColored(UiColors.Amber, "RynthAi's AutoCram also moves loot out of the main pack; turn one of them off");
foreach (string warning in Warnings()) w.TextColored(UiColors.Amber, warning);
if (w.CollapsingHeader("Rules (first match wins)", "rules", defaultOpen: true))
DrawRules(w, rules, view);
if (w.CollapsingHeader("Settings", "settings"))
{
w.SliderInt("Settle (s)", "settle", s.SettleSec, SortSettings.SettleMin, SortSettings.SettleMax, v => { s.SettleSec = v; _save(); });
w.Tooltip("How long a new item sits in the main pack before it is moved");
w.SliderInt("Gap (ms)", "gap", s.GapMs, SortSettings.GapMin, SortSettings.GapMax, v => { s.GapMs = v; _save(); });
w.Tooltip("Auto-sort's pause between two moves, to leave the bot room. Sort, Tidy, Clean and Unpack don't wait.");
w.Checkbox("Sort during fights", "combat", s.SortInCombat, v => { s.SortInCombat = v; _save(); });
w.Tooltip("Off: nothing moves while RynthAi fights. On: moves go between its attacks and casts (never while one is unanswered)");
}
if (_c.Log.Count > 0)
{
w.Separator();
foreach (string line in _c.Log) w.TextDisabled(line);
}
}
private void DrawRules(UiWindow w, List<SortRule> rules, SortView view)
{
if (_selected >= rules.Count) _selected = rules.Count - 1;
for (int i = 0; i < rules.Count; i++)
{
SortRule r = rules[i];
int index = i;
w.Checkbox("", "on." + i, r.On, v => { r.On = v; _save(); });
w.Tooltip("Rule on or off");
w.SameLine();
string pack = r.Pack >= 1 && r.Pack <= view.Packs.Count ? $"pack {r.Pack} ({view.Packs[r.Pack - 1].Name})" : $"pack {r.Pack}";
w.Selectable($"{i + 1}. {SortRules.Describe(r)} -> {pack}", "row." + i, _selected == i,
() => _selected = _selected == index ? -1 : index);
}
if (rules.Count == 0) w.TextDisabled("No rules: nothing moves.");
w.Button("Add rule", "rule.add", () =>
{
if (rules.Count >= SortStore.MaxRules) return;
rules.Add(SortRule.ForClass(ObjectClasses.SpellComponent, 1));
_selected = rules.Count - 1;
_save();
});
if (_selected < 0 || _selected >= rules.Count) return;
int sel = _selected;
w.SameLine();
w.Button("Up", "rule.up", () =>
{
if (sel <= 0) return;
(rules[sel - 1], rules[sel]) = (rules[sel], rules[sel - 1]);
_selected = sel - 1;
_save();
});
w.SameLine();
w.Button("Down", "rule.down", () =>
{
if (sel >= rules.Count - 1) return;
(rules[sel + 1], rules[sel]) = (rules[sel], rules[sel + 1]);
_selected = sel + 1;
_save();
});
w.SameLine();
w.Button("Remove", "rule.remove", () =>
{
rules.RemoveAt(sel);
_selected = Math.Min(sel, rules.Count - 1);
_save();
});
SortRule rule = rules[sel];
w.SeparatorText($"Rule {sel + 1}");
w.Combo("Match", "rule.kind", rule.Kind == RuleKind.Name ? 1 : 0, Kinds, v =>
{
rule.Kind = v == 1 ? RuleKind.Name : RuleKind.Class;
_save();
});
if (rule.Kind == RuleKind.Name)
{
w.InputText("Name has", "rule.text", rule.Text, 64, v => { rule.Text = v; _save(); });
w.Tooltip("Part of the item's name, any case");
}
else
{
int ci = ObjectClasses.ChoiceIndex(rule.Class);
var labels = new List<string>(ObjectClasses.ChoiceLabels);
if (ci < 0)
{
// A class the editor doesn't offer (set by hand or by the Lua script): keep it selectable.
labels.Add(ObjectClasses.Label(rule.Class));
ci = labels.Count - 1;
}
int keep = rule.Class;
w.Combo("Class", "rule.class", ci, labels, v =>
{
rule.Class = v < ObjectClasses.Choices.Length ? ObjectClasses.Choices[v] : keep;
_save();
});
}
w.Combo("Pack", "rule.pack", Math.Max(rule.Pack - 1, 0), PackChoices(view, rule.Pack), v =>
{
rule.Pack = Math.Clamp(v + 1, 1, SortStore.MaxPack);
_save();
});
w.Tooltip("Pack numbers are your side packs in order, top to bottom");
}
/// <summary>"Pack 1: Name (used/cap)" for each side pack, then "(none)" up to at least 7.</summary>
internal static List<string> PackChoices(SortView view, int atLeast)
{
int n = Math.Min(Math.Max(Math.Max(view.Packs.Count, 7), atLeast), SortStore.MaxPack);
var list = new List<string>(n);
for (int i = 1; i <= n; i++)
{
if (i <= view.Packs.Count)
{
PackLine p = view.Packs[i - 1];
list.Add($"Pack {i}: {p.Name} ({p.Used}/{p.Capacity})");
}
else list.Add($"Pack {i} (none)");
}
return list;
}
}

View file

@ -0,0 +1,63 @@
// ============================================================================
// RynthSuite - Plugins/Shared/RynthAiActivityApi.cs
// The "RynthAi.Activity" interface: what the bot is doing right now, as a few
// bits, for plugins that act on the character's inventory and must stay out
// of RynthAi's way (RynthSort's pack moves, 2026-10-11).
// Its own interface rather than a new field of RynthAi.Status, so a plugin
// built against the old RynthAi.Status v1 layout keeps working against any
// RynthAi build (the same reason RynthAi.Status is not part of RynthAi.Script).
//
// Rules: as RynthAi.Script (Shared/RynthAiScriptApi.cs): append-only, pump
// thread only (OnTick and the events it drains), resolve the table again
// every tick (a RynthAi reload frees it). Read only: nothing here changes
// what RynthAi does.
// ============================================================================
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Plugin.Shared;
[StructLayout(LayoutKind.Sequential)]
public unsafe struct RynthAiActivityApiV1
{
public const string InterfaceName = "RynthAi.Activity";
public const uint InterfaceVersion = 1;
public uint Version; // InterfaceVersion of the table RynthAi filled
public uint StructSize; // sizeof(RynthAiActivityApiV1) as RynthAi built it
/// <summary>
/// What RynthAi is doing now (<see cref="RynthAiActivity"/> bits in *flags).
/// 1 = ok, 0 = not ready (not logged in yet; *flags is 0).
/// </summary>
public delegate* unmanaged[Cdecl]<uint*, int> GetActivityFlags;
}
/// <summary>The bits <see cref="RynthAiActivityApiV1.GetActivityFlags"/> reports.</summary>
[Flags]
public enum RynthAiActivity : uint
{
None = 0,
/// <summary>The macro is running.</summary>
MacroRunning = 1u << 0,
/// <summary>The bot's tick belongs to buffing: buffs, heals, mana or stamina (casts and kits).</summary>
Buffing = 1u << 1,
/// <summary>The bot's tick belongs to combat (attacks and casts at a monster).</summary>
Combat = 1u << 2,
/// <summary>Looting: the tick belongs to looting, or RynthAi has a corpse open or claimed.</summary>
Looting = 1u << 3,
/// <summary>Salvaging: the tick belongs to salvage, or the salvage manager has work queued or under way.</summary>
Salvaging = 1u << 4,
/// <summary>The tick belongs to navigation (a route or following).</summary>
Navigating = 1u << 5,
/// <summary>
/// RynthAi is waiting on the server: its busy-count mirror is above zero, or a use, cast or
/// stance change it sent has no answer yet (Shared/ActionPacer.cs).
/// </summary>
ServerAction = 1u << 6,
/// <summary>Missile ammunition is being made (it moves and combines items).</summary>
Crafting = 1u << 7,
/// <summary>The AutoCram setting is on: RynthAi itself moves loose items out of the main pack.</summary>
AutoCram = 1u << 8,
}