From 504a6f080a44b039f4c96be3cebbcf75e7ed1041 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Sun, 11 Oct 2026 15:00:56 -0400 Subject: [PATCH] Snapshot for release 2026.10.11.1 (internal d20160b) --- .../ActivityInterface.cs | 98 ++ .../Combat/BuffManager.cs | 10 +- .../Combat/CombatManager.cs | 469 +++++---- .../ConsumableLookup.cs | 25 + .../CorpseOpenController.cs | 31 +- .../DoorInteractionController.cs | 11 +- .../DungeonPathfinder.Rooms.cs | 172 ++- .../DungeonPathfinder.cs | 90 +- .../LegacyUi/LegacyAdvancedSettingsUi.cs | 12 + .../LegacyUi/LegacyDashboardRenderer.cs | 6 + .../LegacyUi/LegacyUiSettings.cs | 12 + .../LegacyUi/RynthRadarUi.cs | 8 +- .../Loot/SalvageManager.cs | 25 +- .../ManaStoneManager.cs | 166 ++- .../Meta/ExpressionEngine.cs | 3 + .../RynthCore.Plugin.RynthAi/PluginExports.cs | 8 +- .../RynthAiCommands.cs | 70 +- .../RynthAiPlugin.HazardEscape.cs | 17 +- .../RynthAiPlugin.ItemInfo.cs | 29 +- .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 2 +- .../RynthCore.Plugin.RynthAi.csproj | 2 + .../Bounty/BountyParse.cs | 229 ++++ .../Bounty/BountyTracker.cs | 708 +++++++++++++ .../PluginExports.cs | 89 ++ .../RynthCore.Plugin.RynthILT.csproj | 37 + .../RynthILTJsonContext.cs | 13 + .../RynthILTPlugin.cs | 207 ++++ .../HostSortWorld.cs | 155 +++ .../PluginExports.cs | 56 + .../RynthCore.Plugin.RynthSort.csproj | 49 + .../RynthSortPlugin.cs | 318 ++++++ .../RynthCore.Plugin.RynthSort/SortStore.cs | 260 +++++ .../Sorting/InventoryReader.cs | 191 ++++ .../Sorting/MoveTracker.cs | 84 ++ .../Sorting/SortController.cs | 236 +++++ .../Sorting/SortGate.cs | 124 +++ .../Sorting/SortInventory.cs | 34 + .../Sorting/SortPlanner.cs | 252 +++++ .../Sorting/SortRules.cs | 128 +++ .../RynthCore.Plugin.RynthSort/Ui/UiFormat.cs | 123 +++ .../RynthCore.Plugin.RynthSort/Ui/UiHost.cs | 202 ++++ .../RynthCore.Plugin.RynthSort/Ui/UiWindow.cs | 490 +++++++++ .../Views/SortPanel.cs | 197 ++++ Plugins/Shared/RynthAiActivityApi.cs | 63 ++ .../VTank/VTankLootParser.cs | 56 +- .../VTank/VTankLootProfile.cs | 7 + .../LootUnknownNodeTests.cs | 73 ++ Tools/RynthCore.LootSdkTests/Program.cs | 1 + Tools/RynthCore.PatrolProof/Program.cs | 2 + .../RynthCore.PatrolProof.csproj | 2 + Tools/RynthCore.PatrolProof/Waypoints.cs | 146 +++ Tools/RynthCore.RynthAiHostTests/Program.cs | 3 + .../Tests/ActivityInterfaceTests.cs | 73 ++ .../Tests/CorpseKillerTests.cs | 54 + .../Tests/HazardEscapeTests.cs | 6 +- .../Tests/LootSalvageTests.cs | 19 + .../Tests/ManaStoneChoiceTests.cs | 146 +++ .../Tests/PatrolDoorwayTests.cs | 28 + .../Tests/TargetingTests.cs | 286 +++++ .../Tests/VitalsTests.cs | 31 + Tools/RynthILT.Tests/BountyReviewTests.cs | 252 +++++ Tools/RynthILT.Tests/BountyTests.cs | 388 +++++++ Tools/RynthILT.Tests/Program.cs | 28 + Tools/RynthILT.Tests/RynthILT.Tests.csproj | 38 + Tools/RynthSort.Tests/Program.cs | 996 ++++++++++++++++++ Tools/RynthSort.Tests/RynthSort.Tests.csproj | 39 + 66 files changed, 7870 insertions(+), 315 deletions(-) create mode 100644 Plugins/RynthCore.Plugin.RynthAi/ActivityInterface.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/ConsumableLookup.cs create mode 100644 Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyParse.cs create mode 100644 Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyTracker.cs create mode 100644 Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs create mode 100644 Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj create mode 100644 Plugins/RynthCore.Plugin.RynthILT/RynthILTJsonContext.cs create mode 100644 Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/HostSortWorld.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/PluginExports.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/RynthCore.Plugin.RynthSort.csproj create mode 100644 Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/SortStore.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/Sorting/InventoryReader.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/Sorting/MoveTracker.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/Sorting/SortController.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/Sorting/SortGate.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/Sorting/SortInventory.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/Sorting/SortPlanner.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/Sorting/SortRules.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/Ui/UiFormat.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/Ui/UiHost.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/Ui/UiWindow.cs create mode 100644 Plugins/RynthCore.Plugin.RynthSort/Views/SortPanel.cs create mode 100644 Plugins/Shared/RynthAiActivityApi.cs create mode 100644 Tools/RynthCore.LootSdkTests/LootUnknownNodeTests.cs create mode 100644 Tools/RynthCore.PatrolProof/Waypoints.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/ActivityInterfaceTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/CorpseKillerTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs create mode 100644 Tools/RynthILT.Tests/BountyReviewTests.cs create mode 100644 Tools/RynthILT.Tests/BountyTests.cs create mode 100644 Tools/RynthILT.Tests/Program.cs create mode 100644 Tools/RynthILT.Tests/RynthILT.Tests.csproj create mode 100644 Tools/RynthSort.Tests/Program.cs create mode 100644 Tools/RynthSort.Tests/RynthSort.Tests.csproj diff --git a/Plugins/RynthCore.Plugin.RynthAi/ActivityInterface.cs b/Plugins/RynthCore.Plugin.RynthAi/ActivityInterface.cs new file mode 100644 index 0000000..3007964 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ActivityInterface.cs @@ -0,0 +1,98 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// 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. +/// +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; + } + + /// Frees the table (plugin shutdown). Callers resolve it every tick. + 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; + } + } + + /// The bits from RynthAi's state (pure, so the host tests check the mapping). + 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 +{ + /// What the bot is doing now (RynthAi.Activity); null before login. + 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); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 22300af..4e482ac 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -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); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index d23066a..1d9ad13 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -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; + /// The Targeting setting's choices (LegacyUiSettings.TargetSelection). + 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; - /// 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. + /// 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 + /// . private const double CastCommitmentWindowMs = 4000.0; - /// 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). + /// 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). private const double UndamagedCommitmentMaxMs = 15000.0; /// When the last offensive action was issued at - /// . Bounds the cast-issue commitment arm. + /// . Bounds the in-flight hold. 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; + /// Tests: the clock target selection reads (scan grace, in-flight hold). + internal Func TargetClock { get; set; } = () => DateTime.Now; + public struct ScannedTarget { public int Id; @@ -594,8 +589,14 @@ public partial class CombatManager : IDisposable } /// List of nearby, attackable, LOS-clear creatures. Re-scanned every tick (≤50 ms). - /// Sorted by distance — selection itself is score-based via HandleCombatTrigger. + /// Sorted by distance — HandleCombatTrigger picks from it by the Targeting setting. public IReadOnlyList ScannedTargets => _scannedTargets; + /// Tests: replace the scan list (distances and facing angles as given). + internal void SetScannedTargetsForTests(IEnumerable 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. /// + // ── 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. /// - 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 } } + /// + /// 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 (). 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). + /// 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) + /// + /// A candidate's rank under : 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. + /// + 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; + /// Ranks 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). + 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; + /// With Target Lock off, how much better (in units) another + /// candidate must be than the incumbent to take over. + 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"; + } + } + + /// + /// True while an attack at the locked target is still on its way: issued at it within + /// with no damage landed since. Capped by + /// 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. + /// + 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; } /// The Priority of the monster rule that applies to (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}"); diff --git a/Plugins/RynthCore.Plugin.RynthAi/ConsumableLookup.cs b/Plugins/RynthCore.Plugin.RynthAi/ConsumableLookup.cs new file mode 100644 index 0000000..a7be127 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ConsumableLookup.cs @@ -0,0 +1,25 @@ +using System; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// 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. +/// +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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index 3d9bd5d..f2049d8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -1122,7 +1122,13 @@ public sealed partial class RynthAiPlugin return trimmed.Trim(); } - private static string? ExtractCorpseKillerName(string longDesc) + /// + /// 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. + /// + 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. /// + private long _noUstLeftSaidAt = long.MinValue / 2; + + /// Says once every 5 minutes in chat that salvage items are being left for want of a UST. + 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 _); diff --git a/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs b/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs index 92facb2..c142b16 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs @@ -380,13 +380,16 @@ public sealed partial class RynthAiPlugin return "no-state"; } - private ConsumableRule? FindLockpickInConsumables() + /// The first listed lockpick still carried: its own stack, else one of the same name (ConsumableLookup). + 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; } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs index ce120fe..79a2b64 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs @@ -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 graph, DungeonRooms rooms, HashSet 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 /// private static void CrossRoom(List pts, Dictionary 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? 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. internal static Dictionary? KindLog; + /// Why one patrol point is where it is (diagnostics only; filled while + /// is set, never read by the route itself). + 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 + } + + /// Set (per thread) around a route build to record a + /// for every point laid: BuildDunPatrol's waypoint log, PatrolProof "waypoints". + [ThreadStatic] internal static Dictionary? PointLog; + + /// GetMainRouteNodes' sizes for the last build while was set. + [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 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; } + } + } + + /// The cell whose floor is under a point, else the nearest cell centre. + internal static uint CellAt(Dictionary 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)); + } + + /// + /// 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 ". + /// + internal static List DescribePatrol(NavRouteParser route, Dictionary graph, + DungeonGeometry? geo, IReadOnlySet? hazards, + Dictionary? log, int tinyMaxCells = 5) + { + var lines = new List(); + var rooms = geo != null ? BuildRooms(graph, geo, hazards) : null; + int tiny = 0, tinyEntered = 0, tinyLooked = 0; + var tinyRooms = new SortedDictionary(); + 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, diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs index 3cae505..ccf3678 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs @@ -464,6 +464,88 @@ internal static partial class DungeonPathfinder private static HashSet GetMainRouteNodes( Dictionary graph, uint startCell, IReadOnlySet? 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 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; + } + + /// Dead-end spurs this short (cells from the tip to the first junction) are left out + /// when the hazards collapsed the 2-core. + internal const int PatrolMaxSpurCells = 3; + + /// + /// without every dead-end spur of at most 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. + /// + internal static HashSet TrimShortSpurs(Dictionary graph, HashSet 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(); + foreach (uint tip in cells) + { + if (tip == keep || Degree(tip) != 1) continue; + var chain = new List { 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(cells); + result.ExceptWith(drop); + return result; + } + + /// The cells reachable from startCell (no drops, no hazards) and their 2-core. + private static (HashSet Reachable, HashSet Core) ReachableAndCore( + Dictionary graph, uint startCell, IReadOnlySet? 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(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); } /// diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index 5694b3a..0ffb9f2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -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(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 9709190..3f19a12 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -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; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index 9856c5d..4b9b66f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -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; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthRadarUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthRadarUi.cs index 34b5a80..6256364 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthRadarUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthRadarUi.cs @@ -582,13 +582,7 @@ internal sealed class RynthRadarUi /// "Killed by X." in a corpse's LongDesc: X, or "" (read as CorpseOpenController reads it). 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; /// Without GM sigils (+, @, #): the server leaves them out of "Killed by X". private static string NormalizeCharName(string name) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs index ae58016..3b6c076 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs @@ -173,6 +173,26 @@ public sealed class SalvageManager _cache = cache; } + private const long HasUstCacheMs = 3000; + private long _hasUstCheckedAt = long.MinValue / 2; + private bool _hasUst; + + /// + /// 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). + /// + public bool HasUst() + { + long now = NowMs; + if (now - _hasUstCheckedAt >= HasUstCacheMs) + { + _hasUstCheckedAt = now; + _hasUst = FindUst() != 0; + } + return _hasUst; + } + /// Returns true while a salvage operation is in flight. 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. diff --git a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs index 2f16781..7b8d886 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs @@ -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 _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 _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 _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; + /// Clock (ms); tests replace it. + internal static Func Clock { get; set; } = static () => Environment.TickCount64; + private static long NowMs => Clock(); /// /// 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; + + /// The server showed this stone empty since its read was taken (and no newer read came in). + 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); + } + /// /// 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; } + /// + /// 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. + /// + 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; + } + /// /// 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; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index 1621319..88995e7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -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; }), diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index 2487766..b19cdcc 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -14,7 +14,9 @@ public static unsafe class PluginExports internal static readonly RynthPluginRuntime 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) }) diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 3911895..9a66bc1 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -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 } } + /// + /// 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. + /// + 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(); + 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. /// + // 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 graph, DungeonGeometry? geometry, + IReadOnlySet? hazards, Dictionary 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(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. diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HazardEscape.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HazardEscape.cs index a435671..d8ad81a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HazardEscape.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HazardEscape.cs @@ -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. /// public sealed partial class RynthAiPlugin { @@ -59,6 +60,8 @@ public sealed partial class RynthAiPlugin private bool _hazardRunning; private long _hazardRunBeatAt; private string _hazardSource = ""; + /// Cells hurt in this session: the escape steers its target out of them. Not patrol hazards. + private readonly System.Collections.Generic.HashSet _hazardHurtCells = new(); /// True while the escape owns the character. 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; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs index 73a462c..c424a54 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs @@ -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)); + } + + /// + /// " | 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). + /// + 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 ""; + } } /// The live appraisal through the host (tick thread). diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 35e55db..948179e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -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), diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj index c805add..5c0a421 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj @@ -33,6 +33,8 @@ + + diff --git a/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyParse.cs b/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyParse.cs new file mode 100644 index 0000000..984839f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyParse.cs @@ -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; + +/// Where the player stands on one bounty reward. +internal enum BountyStatus +{ + /// Kills are counting: Kills of KillsRequired. + Counting = 0, + /// The cooldown after the last award runs; kills do not count until UnlockAtUtc. + Cooldown = 1, + /// The player's QB is below the reward's minimum; kills do not count. + NeedsQb = 2, +} + +/// One parsed status phrase. +internal readonly record struct BountyStatusInfo(BountyStatus Status, int Kills, int KillsRequired, + int WaitSeconds, long QbRequired, long QbHave); + +/// One "/bounty list" line. +internal readonly record struct BountyListLine(string Where, long Amount, string Item, int KillsRequired, + int CooldownSeconds, BountyStatusInfo Status); + +/// One "/bounty" (where you stand) line. Scope is "" (this dungeon/zone), "all zones" or a region name. +internal readonly record struct BountyHereLine(string Scope, long Amount, string Item, BountyStatusInfo Status); + +/// Kind of a bounty chat event. +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 = + @"(?" + Num + @" of " + Num + @" kills?|unlocks in .+?, then " + Num + @" kills? required|needs " + + Num + @" QB \(you have " + Num + @"\))"; + + /// "/bounty list" reward line (leading indentation already trimmed). + private static readonly Regex ListLine = new( + @"^(?.+?): (?" + Num + @") (?.+?) every (?" + Num + @") kills?" + + @"(?: \(at most every (?[^)]+)\))? - you: " + StatusPattern + @"\.$", Opt); + + /// "/bounty" reward line. + private static readonly Regex HereLine = new( + @"^Bounty(?: \((?[^)]+)\))?: (?" + Num + @") (?.+?) - " + StatusPattern + @"\.$", Opt); + + private static readonly Regex Counting = new(@"^(?" + Num + @") of (?" + Num + @") kills?$", Opt); + private static readonly Regex Cooldown = new(@"^unlocks in (?.+?), then (?" + Num + @") kills? required$", Opt); + private static readonly Regex Qb = new(@"^needs (?" + Num + @") QB \(you have (?" + Num + @")\)$", Opt); + private static readonly Regex WaitPart = new(@"(?\d+)\s*(?hr|min|sec)\b", Opt); + + private static readonly Regex EvUnlocked = new(@"^Bounty unlocked: (?.+) - (?" + Num + @") kills? required\.$", Opt); + private static readonly Regex EvComplete = new(@"^Bounty complete! \+(?" + Num + @") (?.+) gained\.$", Opt); + private static readonly Regex EvNextWait = new(@"^Next bounty unlocks in (?.+?) - (?" + Num + @") kills? required\.$", Opt); + private static readonly Regex EvNextReady = new(@"^Next bounty requires (?" + Num + @") kills?\.$", Opt); + + /// "/bounty list" header line. + public const string ListHeader = "Bounties:"; + + /// True for the line that ends a "/bounty list" reply (footer or "no bounties anywhere"). + public static bool IsListTerminator(string text) + => text.StartsWith("Bounty: type /bounty", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("Bounty: there are no bounties anywhere", StringComparison.OrdinalIgnoreCase); + + /// True when the terminator says no bounty is active anywhere. + public static bool IsNoBountiesAnywhere(string text) + => text.StartsWith("Bounty: there are no bounties anywhere", StringComparison.OrdinalIgnoreCase); + + /// ACE's reply to a command the server doesn't register. + public static bool IsUnknownCommand(string text) + => text.StartsWith("Unknown command: bounty", StringComparison.OrdinalIgnoreCase); + + /// Parses a "/bounty list" reward line. + 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; + } + + /// Parses a "/bounty" (where you stand) reward line. + 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; + } + + /// Parses one status phrase (without the trailing period). + 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; + } + + /// "2 min 30 sec" → 150, "1 hr 15 sec" → 3615. 0 when nothing parses. + 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); + } + + /// + /// 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". + /// + 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; + } + + /// Key that identifies one reward of one area across refreshes. + public static string Key(string where, long amount, string item, int killsRequired) + => $"{where}|{amount}|{item}|{killsRequired}".ToLowerInvariant(); + + /// "1 hr 5 min", "45 sec", "2 days 3 hr". Negative spans read as 0 sec. + 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"; + } + + /// Digits with "," grouping removed; 0 when nothing parses. + 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); +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyTracker.cs b/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyTracker.cs new file mode 100644 index 0000000..b980a45 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyTracker.cs @@ -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; + +/// Persisted per character (bounties.json): the window's options and the last list read. +internal sealed class BountyState +{ + public bool RefreshOnKills = true; + public int MinRefreshSeconds = 10; + public int PeriodicRefreshMinutes = 5; + public bool HideQbLocked; + public bool SortByProgress; + public List Entries = new(); + public DateTime ListedUtc; + public bool NoneAnywhere; + public string LastEvent = string.Empty; + public DateTime LastEventUtc; +} + +/// One reward of one bounty area and where this character stands on it. +internal sealed class BountyEntry +{ + public string Where = string.Empty; + public long Amount; + public string Item = string.Empty; + public int KillsRequired; + public int CooldownSeconds; + /// A value. + public int Status; + public int Kills; + public DateTime UnlockAtUtc; + public long QbRequired; + public long QbHave; + /// Last time the kills went up or an award reset them (row highlight). + public DateTime ChangedUtc; +} + +/// +/// RynthPluginGetBountiesJson payload. Mirrored by RynthCore.Engine UI/Data/BountiesSnapshotJson.cs; +/// either side may add fields (unknown ones are skipped, missing ones keep their defaults). +/// +internal sealed class BountyBridgePayload +{ + [JsonPropertyName("unsupported")] public bool Unsupported; + [JsonPropertyName("reading")] public bool Reading; + [JsonPropertyName("status")] public string Status = string.Empty; + /// Seconds since the last list read; -1 = never. + [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; + /// Rows not shown because of HideQbLocked. + [JsonPropertyName("hiddenCount")] public int HiddenCount; + [JsonPropertyName("rows")] public List Rows = new(); +} + +/// One row of , with the status as of the poll. +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; + /// A value; an ended cooldown is already Counting. + [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; + /// Kills went up (or an award reset them) in the last 15 seconds. + [JsonPropertyName("changed")] public bool Changed; +} + +internal sealed class BountyTracker +{ + /// The capture command; "/bounty all" is the same list. + public const string ListCommand = "/bounty list"; + /// Lowest allowed MinRefreshSeconds (the server is asked at most this often after kills). + public const int MinRefreshFloorSeconds = 5; + public const int MinRefreshCeilingSeconds = 300; + public const int PeriodicCeilingMinutes = 60; + public const string FileName = "bounties.json"; + + /// Wait after a kill so a burst of kills (and the server's own award lines) lands in one read. + private const long KillDebounceMs = 2000; + /// Wait after a bounty chat event before re-reading. + private const long EventDebounceMs = 1500; + /// The window counts as open while the engine polled the export this recently (it polls every second). + private const long WindowPollWindowMs = 3000; + /// A capture with no reply line by then is abandoned. + private const long FirstLineTimeoutMs = 10000; + /// A capture whose footer never came ends this long after its last line. + private const long IdleEndMs = 1500; + /// The engine may pass our own /bounty list back through the chat bar hook this soon after sending it. + private const long OwnEchoMs = 2000; + /// Longer chat lines are never parsed (no bounty line is near this; bounds the regex work). + private const int MaxLineLength = 512; + private const long SaveDebounceMs = 5000; + /// A list older than this is re-read when the window opens. + private static readonly TimeSpan OpenRefreshAge = TimeSpan.FromSeconds(30); + /// How long a row stays highlighted after its kills went up. + private static readonly TimeSpan ChangedHighlight = TimeSpan.FromSeconds(15); + + private readonly Action _send; + private readonly Action _chat; + private readonly Action _log; + private readonly string _filePath; + private readonly Func _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 _capLines = new(); + + private bool _unsupported; + private string _status = string.Empty; + private bool _dirty; + private long _lastSaveMs; + + /// Sends a chat command to the server (Host.InvokeChatParser). + /// Prints a line to the player's chat window. + /// Writes to the RynthCore log. + /// bounties.json in the character folder; empty = not persisted. + /// Milliseconds clock; Environment.TickCount64 unless a test supplies one. + public BountyTracker(Action send, Action chat, Action log, string filePath, Func? clock = null) + { + _send = send; + _chat = chat; + _log = log; + _filePath = filePath ?? string.Empty; + _clock = clock ?? (() => Environment.TickCount64); + _s = Load(); + } + + private long NowMs => _clock(); + + /// The persisted state (host tests). + internal BountyState State => _s; + + /// True once the server answered "Unknown command: bounty" (no bounty system on this server). + public bool Unsupported => _unsupported; + + /// True while a "/bounty list" reply is being captured. + public bool Reading => _capActive; + + /// True while the engine's Bounties window is polling the export. + public bool WindowOpen => _lastPollMs != 0 && NowMs - _lastPollMs < WindowPollWindowMs; + + // ── Scheduling ────────────────────────────────────────────────────────── + + /// + /// Schedules a "/bounty list" read; the earliest pending request wins. Every read waits for + /// MinRefreshSeconds since the last one; false (a manual + /// refresh) waits only for the MinRefreshFloorSeconds floor. + /// + 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; + } + + /// + /// 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. + /// + 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..."; + } + + /// One of this character's kills (RynthILTPlugin.OnKillNotification). + 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(); + } + + /// + /// 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. + /// + 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); + } + + /// "/bounty list" or "/bounty all" (or with ACE's '@' command prefix). + 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)); + } + + /// True for a chat-bar line that is a /bounty command (what the plugin passes to NoteTypedCommand). + 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 ──────────────────────────────────────────────────────────────── + + /// + /// 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. + /// + 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) ──────────────── + + /// + /// 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. + /// + internal void ApplyList(IReadOnlyList lines, bool complete, bool noneAnywhere, DateTime nowUtc) + { + var old = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var e in _s.Entries) + old[BountyParse.Key(e.Where, e.Amount, e.Item, e.KillsRequired)] = e; + + var fresh = new List(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; + } + + /// + /// 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. + /// + 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; + } + + /// Copies a parsed status onto and stamps ChangedUtc when kills went up or an award reset them. + 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; + } + + /// The status to show now: a cooldown that has ended is "0 of N kills". + 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); + } + + /// "Closest first" order: counting by fraction left, then cooldowns by time left, then QB-locked. + 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 ─────────────────────────────────────────────────────── + + /// RynthPluginGetBountiesJson. Each call also marks the window open for the read schedule. + 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 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); + + /// + /// RynthPluginBountyCommand: "refresh", or "set {option} {value}" with option one of + /// refreshonkills, minrefreshseconds, periodicminutes, hideqblocked, sortbyprogress. + /// + 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 ──────────────────────────────────────────────────────── + + /// "/ilt bounty [refresh|list]". + 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; + } + } + + /// One-line chat text for an entry. + 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}", + }; + } + + /// "/ilt bounty list": the tracked bounties in chat. + 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(); + 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; + } + + /// Writes bounties.json when something changed (also called at logout). + 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}"); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs new file mode 100644 index 0000000..f79a97a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs @@ -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 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; + + /// The tracked bounties as JSON (BountyBridgePayload); 0 before login. + [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; } + } + + /// "refresh" or "set {option} {value}" (BountyTracker.Command). + [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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj b/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj new file mode 100644 index 0000000..64e8661 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj @@ -0,0 +1,37 @@ + + + + + net10.0-windows + x86 + win-x86 + Library + true + enable + true + Shared + true + Size + false + RynthCore.Plugin.RynthILT + RynthCore.Plugin.RynthILT + x86 + + 66 + Infinite Leaftide (ACECustom) features: the Bounties window. + + + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthILTJsonContext.cs b/Plugins/RynthCore.Plugin.RynthILT/RynthILTJsonContext.cs new file mode 100644 index 0000000..81a0c77 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/RynthILTJsonContext.cs @@ -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 { } diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs b/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs new file mode 100644 index 0000000..34dff8e --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs @@ -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"); + + /// Wait this long after login for the character's name before tracking without a save file. + 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 _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 _typedBounty = new(); + + /// The Bounties window's tracker (PluginExports); null until login. + 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 ───────────────────────────────────────────────────────────── + + /// Starts the tracker once the character's name is known (its save file is per character). + 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}"); } + } + + /// The tracker's only way to the server: one chat command (Host.InvokeChatParser). + private void SendCommand(string command) + { + if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command)) + throw new InvalidOperationException("the engine's chat parser is not available"); + } + + /// + /// %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. + /// + 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); + } + + /// RynthILT's settings folder: %APPDATA%\RynthCore\RynthILT. + internal static string SettingsRoot => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "RynthILT"); + + /// A name safe as one folder: invalid characters become '_', no leading/trailing dots or spaces, at most 64 chars. + 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/HostSortWorld.cs b/Plugins/RynthCore.Plugin.RynthSort/HostSortWorld.cs new file mode 100644 index 0000000..3f4749c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/HostSortWorld.cs @@ -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; + +/// +/// 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. +/// +internal sealed unsafe class HostSortWorld : ISortWorld +{ + private readonly RynthCoreHost _host; + private readonly InventoryReader _reader; + private readonly LootWatch _loot; + private readonly Func _vendorOpenByEvent; + private uint[] _groundBuf = new uint[256]; + + public HostSortWorld(RynthCoreHost host, InventoryReader reader, LootWatch loot, Func 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 ───────────────────────────────────────────────────────────── + + /// + /// 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. + /// + 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; + } + + /// The bits an older RynthAi's status JSON ({macro, action, ...}) gives (no server-wait bit). + 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; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthSort/PluginExports.cs new file mode 100644 index 0000000..f25b43d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/PluginExports.cs @@ -0,0 +1,56 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthSort; + +/// +/// 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. +/// +public static unsafe class PluginExports +{ + private static readonly RynthPluginRuntime 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 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); +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/RynthCore.Plugin.RynthSort.csproj b/Plugins/RynthCore.Plugin.RynthSort/RynthCore.Plugin.RynthSort.csproj new file mode 100644 index 0000000..52d7036 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/RynthCore.Plugin.RynthSort.csproj @@ -0,0 +1,49 @@ + + + + + + net10.0-windows + x86 + win-x86 + Library + true + enable + true + Shared + true + Size + false + RynthCore.Plugin.RynthSort + RynthCore.Plugin.RynthSort + x86 + + 66 + Keeps your packs sorted: new loot goes to the pack its rule names. + + + + + + + + + + + + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.cs b/Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.cs new file mode 100644 index 0000000..f952b82 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.cs @@ -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; + +/// +/// 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. +/// +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 _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 _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}"); + } + + /// The RynthSort Lua script set to start too would sort beside the plugin: say so. + 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. + } + } + + /// True when RynthLua's settings start the "RynthSort" script for everyone or for this character. + 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); + } + + /// A pass when one is wanted, or on the refresh interval while visible (the status ticks on). + 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(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/SortStore.cs b/Plugins/RynthCore.Plugin.RynthSort/SortStore.cs new file mode 100644 index 0000000..db10345 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/SortStore.cs @@ -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; + +/// RynthSort's settings for one character (the Lua script's DEFAULTS, plus what the plugin adds). +internal sealed class SortSettings +{ + public const int SettleMin = 0, SettleMax = 30, GapMin = 100, GapMax = 3000; + + /// Auto-sort: new items in the main pack go to their pack after the settle time. + public bool Auto = true; + /// How long a new item sits in the main pack before it moves (seconds). + public int SettleSec = 5; + /// Auto-sort's pause between two moves (ms), to leave the bot room. + public int GapMs = 300; + /// Moves may go while RynthAi fights (never while it waits on the server or animates). + public bool SortInCombat; + /// The window was open when last seen. + public bool WindowOpen = true; + + public void Clamp() + { + SettleSec = Math.Clamp(SettleSec, SettleMin, SettleMax); + GapMs = Math.Clamp(GapMs, GapMin, GapMax); + } +} + +/// One character's rules and settings. +internal sealed class CharacterSortData +{ + public List Rules = SortRules.Defaults(); + public SortSettings Settings = new(); + /// Where these came from on first run ("" = defaults, else the Lua script's file). + public string ImportedFrom = string.Empty; +} + +/// +/// Per-character files: <SuiteDir>\RynthSort\characters\<server_character>.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 (<SuiteDir>\RynthLua\Data\RynthSort\characters\...) +/// is read the same way when a character has no RynthSort file yet. +/// +internal sealed class SortStore +{ + public const int MaxRules = 64; + public const int MaxPack = 32; + + /// RynthSort's folder (tests point it at a temp folder). + public string Root; + /// The Lua script's data folder for RynthSort (tests point it at a temp folder). + 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; + } + + /// "server_character" made safe as a file name, as the Lua script's storage names it. + 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"); + + /// + /// The character's rules and settings: RynthSort's own file; else the Lua script's (imported: + /// 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). + /// + 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; + } + } + + /// Rules and settings from the file's root object; anything missing or odd keeps its default. + 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(); + 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(); + } + } + + 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; + } + + /// Writes the character's file (temp file, then moved over the old one). Returns an error or null. + 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 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", + }; + + /// RynthLua's LibraryStorage.SafeFileName, so both name a character's file the same way. + 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/Sorting/InventoryReader.cs b/Plugins/RynthCore.Plugin.RynthSort/Sorting/InventoryReader.cs new file mode 100644 index 0000000..65013fe --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/Sorting/InventoryReader.cs @@ -0,0 +1,191 @@ +using System; +using System.Collections.Generic; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthSort.Sorting; + +/// +/// Reads the character's packs from the client into a . 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. +/// +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 _known = new(); + private uint[] _buf = new uint[512]; + + public void Reset() => _known.Clear(); + + /// The packs now, or null when the character or its inventory isn't readable yet. + 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(); + 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 }; + } + + /// + /// 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. + /// + 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); + } + + /// The classification from the raw data (pure). + 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/Sorting/MoveTracker.cs b/Plugins/RynthCore.Plugin.RynthSort/Sorting/MoveTracker.cs new file mode 100644 index 0000000..da5f694 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/Sorting/MoveTracker.cs @@ -0,0 +1,84 @@ +using System; + +namespace RynthCore.Plugin.RynthSort.Sorting; + +/// How a move in flight ended (or that it hasn't yet). +internal enum MoveOutcome +{ + Pending, + /// The item is in the destination, or merged into a stack there. + Done, + /// The server refused it (InventoryServerSaveFailed, or a refusal naming the item). + Refused, + /// The server said "You're too busy" (or too many actions): try again later. + TooBusy, + /// No answer in . + TimedOut, +} + +/// What the client says about the moved item and the server's last refusal, read each tick. +internal struct MoveObservation +{ + public bool Exists; + public uint Container; + public uint Wielder; + public int Stack; + /// The engine's refusal counter (TryGetLastWeenieError seq; 0 when unknown). + public int ErrorSeq; + public uint Error; + public uint ErrorEventType; + public uint ErrorObject; +} + +/// The one move RynthSort has out. +internal sealed class MoveInFlight +{ + public SortMove Move; + public long SentMs; + public int ErrorSeqAtSend; + public int StackAtSend; +} + +/// +/// 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. +/// +internal static class MoveTracker +{ + /// A move with no answer by then has failed (the Lua script's ObjectMove time limit). + public const long TimeoutMs = 5000; + /// An item that couldn't be moved is left alone this long. + public const long BlockMs = 60_000; + /// The longest hold after refusals in a row. + 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; + } + + /// + /// The hold before the next move after failures: 2 s, 4 s, + /// 8 s ... up to ; 0 after a success. + /// + public static long BackoffMs(int failuresInARow) + { + if (failuresInARow <= 0) return 0; + int shift = Math.Min(failuresInARow - 1, 10); + return Math.Min(2000L << shift, MaxBackoffMs); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortController.cs b/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortController.cs new file mode 100644 index 0000000..ec5d582 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortController.cs @@ -0,0 +1,236 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthSort.Sorting; + +/// What the controller needs from the game (the plugin's HostSortWorld; the tests' fake). +internal interface ISortWorld +{ + /// The packs now, or null when they can't be read yet. + SortInventory? ReadInventory(); + /// The "stay out of the way" inputs now. + GateInputs ReadGate(bool sortInCombat, long nowMs); + /// Sends the move to the client (merge or plain move). False = the engine refused it. + bool SendMove(in SortMove move); + /// The moved item and the server's last refusal. + MoveObservation Observe(uint itemId); + /// The engine's refusal counter now (0 when the engine can't say). + int ErrorSeqNow(); +} + +/// +/// 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 (). An item that fails is left alone for a minute, and +/// failures in a row hold every move off longer and longer (). +/// +internal sealed class SortController +{ + /// Between two moves of a job asked for (the server's answer came already). + public const long JobGapMs = 100; + /// How often the gate is checked while paused (and auto-sort off is looked at). + public const long PollMs = 250; + /// How often the packs are read while nothing moves (and for the window while paused). + public const long ViewMs = 1000; + public const int LogLines = 6; + + public CharacterSortData Data = new(); + public readonly SortPlanner Planner = new(); + public readonly SortGate Gate = new(); + + /// "watching", "off", "sorting", "unpacking", "paused: ..."; shown beside the auto-sort box. + public string Status { get; private set; } = "starting"; + public bool Paused => Status.StartsWith("paused", StringComparison.Ordinal); + /// A one-off job asked for, or null. + public SortScope? Job { get; private set; } + /// The side pack Unpack empties (null = all). + public int? UnpackWhich { get; private set; } + /// RynthAi's bits from the last gate read (null = RynthAi not there or not ready). + public RynthAiActivity? LastBot { get; private set; } + /// The last few moves and job results, newest first. + public readonly List Log = new(); + public int Moved { get; private set; } + public int Failed { get; private set; } + + /// Settings changed by a command (auto-sort off for Unpack): the plugin saves. + public Action? SettingsChanged; + + private MoveInFlight? _inFlight; + private long _nextStepMs; + private long _nextViewMs; + private int _failuresInARow; + + public bool HasMoveOut => _inFlight != null; + + /// Forget the character (logout, another character's data). + 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(); + } + + /// Sort now (Main), Tidy (All) or Clean, as soon as the way is clear. + public void StartJob(SortScope scope) + { + if (scope == SortScope.Unpack) { StartUnpack(null); return; } + Job = scope; + _nextStepMs = 0; + } + + /// Empty every side pack (or pack ) into the main pack; auto-sort goes off first so nothing moves straight back. + 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 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; + } + } + + /// Re-reads the packs for the window now and then while nothing moves. + 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); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortGate.cs b/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortGate.cs new file mode 100644 index 0000000..26f8546 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortGate.cs @@ -0,0 +1,124 @@ +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthSort.Sorting; + +/// Everything the "stay out of the way" check looks at, read once per pass. +internal struct GateInputs +{ + public bool InPortalSpace; + /// A corpse or chest is being looted (). + public bool Looting; + public bool VendorOpen; + public bool TradeOpen; + /// The client's busy count is above zero (a use, a cast, or anyone's item move in flight). + public bool ClientBusy; + /// The character's motion queue isn't empty (a gesture, a cast animation, a stance change). + public bool Animating; + /// RynthAi's activity bits (RynthAi.Activity), or null when RynthAi isn't loaded or not ready. + public RynthAiActivity? Bot; + /// The "Sort during fights" setting: moves may go while RynthAi fights (still never mid-action). + public bool SortInCombat; +} + +/// +/// 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 +/// more (the next corpse, cast or buff is often a moment away). +/// +internal sealed class SortGate +{ + /// How long the way must have been clear before the next move. + public const long QuietMs = 1500; + + private long _pausedAt = long.MinValue / 2; + private string _lastReason = string.Empty; + + /// The reason without the quiet time: pure, for the tests and the window. + 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; + } + + /// The reason, held for after it clears. + 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; + } +} + +/// +/// 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 ; and for after that (the next corpse is +/// often a moment away). The Lua script's rule, unchanged. +/// +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; + + /// The open ground container (0 = none). + /// How many items it holds now. + 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortInventory.cs b/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortInventory.cs new file mode 100644 index 0000000..1562084 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortInventory.cs @@ -0,0 +1,34 @@ +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthSort.Sorting; + +/// One loose item in a pack, as read this pass (InventoryReader). +internal sealed class SortItem +{ + public uint Id; + public string Name = string.Empty; + /// ObjectClass number (). + public int ObjectClass; + public uint Wcid; + public int Stack = 1; + public int MaxStack = 1; + /// Worn or wielded (the reader leaves these out; kept so the planner can refuse them too). + public bool Wielded { get; set; } +} + +/// The main pack or one side pack and its loose items (packs and foci are never items). +internal sealed class SortPack +{ + public uint Id; + public string Name = string.Empty; + /// How many items it holds (ItemsCapacity; 102 for the main pack and 24 for a side pack when unknown). + public int Capacity; + public readonly List Items = new(); +} + +/// The character's packs: the main pack and the side packs in order, top to bottom (pack 1 first). +internal sealed class SortInventory +{ + public SortPack Main = new(); + public readonly List Packs = new(); +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortPlanner.cs b/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortPlanner.cs new file mode 100644 index 0000000..17dfe05 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortPlanner.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthSort.Sorting; + +/// What a planning pass looks at. +internal enum SortScope +{ + /// Only the main pack; an item moves once it has sat there for the settle time (unless forced). + Main, + /// Every pack, no settling: items in the wrong side pack move to theirs too ("Tidy"). + All, + /// As , and side-pack items no rule wants go back to the main pack ("Clean"). + Clean, + /// Every side pack (or one) emptied into the main pack ("Unpack"). + Unpack, +} + +/// One move: into (pack , 0 = main pack). +internal readonly struct SortMove +{ + public readonly SortItem Item; + public readonly SortPack Dest; + public readonly int DestIndex; + /// A stack in the item joins (a merge), or 0 for a plain move. + 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; +} + +/// A side pack as the window lists it. +internal sealed class PackLine +{ + public string Name = string.Empty; + public int Used; + public int Capacity; +} + +/// What the window shows about the packs after a planning pass. +internal sealed class SortView +{ + public readonly List Packs = new(); + public int MainUsed; + public int MainCapacity; + /// Items a rule wants moved that can't go yet (settling, pack full, pack missing, main full). + public int Waiting; + /// Side packs (1-based) a rule wants to fill that are full. + public readonly SortedSet Full = new(); + /// Pack numbers rules use that the character doesn't have. + public readonly SortedSet Missing = new(); + /// Clean or Unpack found the main pack full. + public bool MainFull; +} + +/// +/// 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. +/// +internal sealed class SortPlanner +{ + public const int SideCapacityFallback = 24; + public const int MainCapacityFallback = 102; + + private readonly Dictionary _firstSeen = new(); + private readonly Dictionary _blocked = new(); + + public SortView View { get; private set; } = new(); + + /// Forget everything (logout, another character). + public void Reset() + { + _firstSeen.Clear(); + _blocked.Clear(); + View = new SortView(); + } + + /// Leave alone until (a move failed). + 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; + } + + /// Worn and wielded items, packs and foci never move. + 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; + + /// + /// A stack in that can join (the same kind, with room + /// left), or 0. That is what lets a full pack still take the item. + /// + 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; + + /// + /// The moves to make now for (not : see + /// ), first one first. Also refreshes and the main + /// pack's settle clock (an item's time starts when a pass first sees it in the main pack). + /// + public List Plan(SortInventory inv, IReadOnlyList rules, SortScope scope, bool force, long nowMs, int settleMs) + { + bool everyPack = scope != SortScope.Main; + bool evict = scope == SortScope.Clean; + var moves = new List(); + 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(); + 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(); + 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; + } + + /// + /// Emptying side packs into the main pack: every sortable item in side pack + /// (1-based; null = all of them), while the main pack has room or the item joins a stack there. + /// + public List PlanUnpack(SortInventory inv, int? which, long nowMs) + { + var moves = new List(); + 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), + }); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortRules.cs b/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortRules.cs new file mode 100644 index 0000000..0cf0a2b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortRules.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Plugin.RynthSort.Sorting; + +/// Which test a rule makes. +internal enum RuleKind +{ + /// The item's ObjectClass equals . + Class = 0, + /// The item's name contains (any case). + Name = 1, +} + +/// +/// One rule: items it matches go to side 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 }. +/// +internal sealed class SortRule +{ + public bool On = true; + public RuleKind Kind = RuleKind.Class; + /// An ObjectClass number (). + 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 }; +} + +/// +/// 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. +/// +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; + + /// The classes the rule editor offers, in the Lua script's order. + 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, + }; + + /// "Spell Component" for SpellComponent, as the Lua script showed them. + 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; + } + + /// A space before each capital that follows a small letter ("ManaStone" -> "Mana Stone"). + 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(); + } + + /// The index of in , or -1. + 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 +{ + /// The Lua script's defaults: components, salvage, then gems, stones and keys together. + public static List 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; + } + + /// The first rule that matches (rules are tried in order), or null. + public static SortRule? RuleFor(IReadOnlyList 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); +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/Ui/UiFormat.cs b/Plugins/RynthCore.Plugin.RynthSort/Ui/UiFormat.cs new file mode 100644 index 0000000..2bfb3c5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/Ui/UiFormat.cs @@ -0,0 +1,123 @@ +using System; + +namespace RynthCore.Plugin.RynthSort.Ui; + +/// +/// 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. +/// +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 bytes, uint hash = 2166136261) + { + foreach (byte b in bytes) + { + hash ^= b; + hash *= 16777619; + } + return hash; + } + + /// The length of cut to at most bytes without splitting a character. + public static int CutUtf8(ReadOnlySpan 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; + } + + /// An ImGui U32 colour (0xAABBGGRR) from RGB bytes. + public static uint Rgb(byte r, byte g, byte b, byte a = 255) => + ((uint)a << 24) | ((uint)b << 16) | ((uint)g << 8) | r; +} + +/// Colours RynthSort uses (0xAABBGGRR). +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); + /// Upstream's "destruction" highlight: deep pink brightened by half (255, 30, 220). + 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); + /// The Lua script's amber (paused, full packs): 1.0, 0.75, 0.25. + public static readonly uint Amber = UiFormat.Rgb(255, 191, 64); +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/Ui/UiHost.cs b/Plugins/RynthCore.Plugin.RynthSort/Ui/UiHost.cs new file mode 100644 index 0000000..131f148 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/Ui/UiHost.cs @@ -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; + +/// +/// 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. +/// +internal sealed class UiHost +{ + private readonly List _windows = new(); + private readonly Dictionary _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? Log; + + public IReadOnlyList Windows => _windows; + + public UiWindow Add(UiWindow w) + { + _windows.Add(w); + _byHash[w.Hash] = w; + return w; + } + + /// Drains the engine's queued events into the windows' handlers. + 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 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 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; + } + } + } + } + + /// Sends the window set when any window's list or header changed. + 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})."); + } + } + } + + /// Removes every window from the engine (logout, shutdown). Their placement is kept by the engine. + public void SubmitEmpty(RynthCoreHost host) + { + if (!host.HasUi || !_submittedSomething) return; + Span 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 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 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 b, int pos, ReadOnlySpan 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 b, int pos, float v) + { + BinaryPrimitives.WriteSingleLittleEndian(b[pos..], v); + return pos + 4; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/Ui/UiWindow.cs b/Plugins/RynthCore.Plugin.RynthSort/Ui/UiWindow.cs new file mode 100644 index 0000000..35d652b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/Ui/UiWindow.cs @@ -0,0 +1,490 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Plugin.RynthSort.Ui; + +/// One input from the engine for a widget (a click, a new value, an open state). +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; + } +} + +/// +/// 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. +/// +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; + + /// A pass is wanted at the next chance (input arrived, it was just shown, data changed). + 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(); + 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> _handlers = new(); + private Dictionary> _next = new(); + private readonly Dictionary _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 Body => _body.AsSpan(0, _len); + + // ── Pass ──────────────────────────────────────────────────────────────── + + public void Begin() + { + _len = 0; + _ops = 0; + _cut = false; + _blockDepth = 0; + _next.Clear(); + } + + /// Ends the pass: closes open blocks, writes End, and notes whether the list changed. + 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; + } + + /// The engine accepted the last submit: remember what it now has. + 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; + } + + /// The engine dropped every window (logout, empty submit): send everything again next time. + internal void ForgetSubmitted() + { + _sentLen = -1; + _sentTitle = null; + BodyDirty = _len > 0; + } + + internal void Dispatch(uint widgetKey, in UiEvent e) + { + if (_handlers.TryGetValue(widgetKey, out Action? 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)); + } + + /// Next item on the same line, logical units from the content start (0 = right after). + 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); + + /// A button drawn highlighted when (tabs, toggles). + 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 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); }; + } + + /// An integer slider from to (clamped by the engine). + public void SliderInt(string label, string id, int value, int min, int max, Action 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)); }; + } + + /// A text box; gets every edit (submitted = Enter was pressed). + public void InputText(string label, string id, string value, int maxLen, Action 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 items, Action 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); + } + + /// + /// An icon (op level 2): = a 0x06 + /// texture id, = a live object. Engines without op level + /// 2 skip it (the caller checks first so the layout doesn't shift). + /// + 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); + } + + /// Tooltip for the item just drawn. + 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); + } + + /// Pops are dropped when the list is cut short; the engine pops leftovers at the scope's end. + public void PopStyleColor(int count = 1) + { + if (!Room()) return; + int p = BeginOp(UiFormat.OpPopStyleColor); + U8((byte)Math.Clamp(count, 1, 255)); + EndOp(p); + } + + /// + /// 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. + /// + 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; + } + + /// A scrolling region; h 0 = fill the rest of the window. Must be closed with . + 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 ───────────────────────────────────────────────────────────── + + /// + /// 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). + /// + 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; + } + + /// str: u16 length + UTF-8, cut to on a character boundary. + private void Str(string s, int maxBytes = UiFormat.MaxString) + { + s ??= string.Empty; + ReadOnlySpan src = s.Length > maxBytes ? s.AsSpan(0, maxBytes) : s.AsSpan(); + Ensure(2 + Encoding.UTF8.GetMaxByteCount(src.Length)); + int at = _len + 2; + Span 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/Views/SortPanel.cs b/Plugins/RynthCore.Plugin.RynthSort/Views/SortPanel.cs new file mode 100644 index 0000000..be76635 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSort/Views/SortPanel.cs @@ -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; + +/// +/// 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. +/// +internal sealed class SortPanel +{ + private static readonly string[] Kinds = { "Class", "Name has" }; + + private readonly SortController _c; + private readonly Action _save; + private int _selected = -1; + + /// Extra warnings the plugin knows about (the Lua script set to start too). + public Func> Warnings = () => Array.Empty(); + /// The character (blank before login). + public Func 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 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 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(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"); + } + + /// "Pack 1: Name (used/cap)" for each side pack, then "(none)" up to at least 7. + internal static List PackChoices(SortView view, int atLeast) + { + int n = Math.Min(Math.Max(Math.Max(view.Packs.Count, 7), atLeast), SortStore.MaxPack); + var list = new List(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; + } +} diff --git a/Plugins/Shared/RynthAiActivityApi.cs b/Plugins/Shared/RynthAiActivityApi.cs new file mode 100644 index 0000000..fb3e585 --- /dev/null +++ b/Plugins/Shared/RynthAiActivityApi.cs @@ -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 + + /// + /// What RynthAi is doing now ( bits in *flags). + /// 1 = ok, 0 = not ready (not logged in yet; *flags is 0). + /// + public delegate* unmanaged[Cdecl] GetActivityFlags; +} + +/// The bits reports. +[Flags] +public enum RynthAiActivity : uint +{ + None = 0, + /// The macro is running. + MacroRunning = 1u << 0, + /// The bot's tick belongs to buffing: buffs, heals, mana or stamina (casts and kits). + Buffing = 1u << 1, + /// The bot's tick belongs to combat (attacks and casts at a monster). + Combat = 1u << 2, + /// Looting: the tick belongs to looting, or RynthAi has a corpse open or claimed. + Looting = 1u << 3, + /// Salvaging: the tick belongs to salvage, or the salvage manager has work queued or under way. + Salvaging = 1u << 4, + /// The tick belongs to navigation (a route or following). + Navigating = 1u << 5, + /// + /// 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). + /// + ServerAction = 1u << 6, + /// Missile ammunition is being made (it moves and combines items). + Crafting = 1u << 7, + /// The AutoCram setting is on: RynthAi itself moves loose items out of the main pack. + AutoCram = 1u << 8, +} diff --git a/Shared/RynthCore.LootSdk/VTank/VTankLootParser.cs b/Shared/RynthCore.LootSdk/VTank/VTankLootParser.cs index bc387d5..5df0260 100644 --- a/Shared/RynthCore.LootSdk/VTank/VTankLootParser.cs +++ b/Shared/RynthCore.LootSdk/VTank/VTankLootParser.cs @@ -52,10 +52,16 @@ public static class VTankLootParser idx = 1; } profile.FileVersion = fileVersion; + profile.DeclaredRuleCount = ruleCount; bool v1Plus = fileVersion >= 1; - while (idx < lines.Length && profile.Rules.Count < ruleCount) + // Past the header's count, keep going while the next lines still look like a + // rule: an undercounted header (T10locky.utl declared 134 of its 136 rules) + // would otherwise drop the last rules silently. The SalvageCombine block never + // matches, its third line having no ';'. + while (idx < lines.Length + && (profile.Rules.Count < ruleCount || IsStartOfNextRule(lines, idx, fileVersion))) { var rule = new VTankLootRule { @@ -101,11 +107,16 @@ public static class VTankLootParser var data = new List(); if (dataLineCount < 0) { - // Unknown type — slurp lines until we look like the start - // of the next rule. This mirrors the plugin's previous - // heuristic and at least keeps the bytes preserved. - while (idx < lines.Length && !IsStartOfNextRule(lines, idx, fileVersion)) - data.Add(lines[idx++]); + // Unknown type. The v1+ length code is the byte length of the data + // block (CRLF per line), so it bounds the block exactly; the old + // "slurp until something looks like a rule" fallback swallowed the + // rest of a multi-condition rule and the rules after it, and a + // trailing unknown node ate the SalvageCombine block. + if (!TryReadByLengthCode(lines, ref idx, lengthCode, data)) + { + while (idx < lines.Length && !IsStartOfNextRule(lines, idx, fileVersion)) + data.Add(lines[idx++]); + } } else { @@ -165,6 +176,39 @@ public static class VTankLootParser return cfg; } + /// + /// Reads an unknown node's data lines using its length code: each line counts its + /// length plus 2 for the CRLF the writer emits. Succeeds only when the lines add up + /// to a positive code exactly (as characters for ANSI files, or UTF-8 bytes); otherwise + /// and are left untouched so the + /// caller can fall back to the boundary heuristic. + /// + private static bool TryReadByLengthCode(string[] lines, ref int idx, string lengthCode, List data) + { + // 0 is what VTankLootWriter emits for a condition built in code, so it says + // nothing about the data's size. + if (!int.TryParse(lengthCode.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int target) + || target <= 0) + return false; + + int charTotal = 0, byteTotal = 0, i = idx; + // UTF-8 bytes >= chars, so the char total is the last one to reach the target. + while (i < lines.Length && charTotal < target) + { + charTotal += lines[i].Length + 2; + byteTotal += System.Text.Encoding.UTF8.GetByteCount(lines[i]) + 2; + i++; + if (charTotal == target || byteTotal == target) + { + for (int j = idx; j < i; j++) + data.Add(lines[j]); + idx = i; + return true; + } + } + return false; + } + /// /// Heuristic boundary detection for unknown node types — true if the lines /// starting at `index` could plausibly be a new rule (name + custom-expr + diff --git a/Shared/RynthCore.LootSdk/VTank/VTankLootProfile.cs b/Shared/RynthCore.LootSdk/VTank/VTankLootProfile.cs index f133ed2..672a853 100644 --- a/Shared/RynthCore.LootSdk/VTank/VTankLootProfile.cs +++ b/Shared/RynthCore.LootSdk/VTank/VTankLootProfile.cs @@ -113,6 +113,13 @@ public sealed class VTankLootProfile public List Rules { get; set; } = new(); + /// + /// The rule count in the file's header, or -1 when not loaded from a file. The parser + /// keeps reading rules that follow past this count, so it can be lower than + /// .Count for a file whose header was written wrong. + /// + public int DeclaredRuleCount { get; set; } = -1; + /// Optional SalvageCombine block at the end of the file. public SalvageCombineSettings? SalvageCombine { get; set; } } diff --git a/Tools/RynthCore.LootSdkTests/LootUnknownNodeTests.cs b/Tools/RynthCore.LootSdkTests/LootUnknownNodeTests.cs new file mode 100644 index 0000000..4c0b372 --- /dev/null +++ b/Tools/RynthCore.LootSdkTests/LootUnknownNodeTests.cs @@ -0,0 +1,73 @@ +using System; +using System.Linq; +using RynthCore.Loot.VTank; + +namespace RynthCore.LootSdkTests; + +// Condition types the parser has no arity for (2009/2011/2016 from a third-party editor): +// their data must be bounded by the length code, not by guessing where the next rule +// starts. The fixture mirrors T10locky.utl on 2026-10-06, where a leading unknown node +// swallowed two following rules and a trailing one ate the SalvageCombine block. +internal static partial class Program +{ + private const string UnknownNodeUtl = + "UTL\n1\n4\n" + + // Unknown node, a known LongValKeyGE, then another unknown node. + "Mixed\n\n0;1;2011;3;2011\n" + + "3\n0\n" + + "9\n15\n374\n" + + "3\n0\n" + + // Plain name rule right after it: was swallowed by the old heuristic. + "Coins\n\n0;1;1\n" + + "9\nCoin\n1\n" + + // Unknown node whose length code is not a number: heuristic fallback still applies. + "Bogus\n\n0;1;2010\n" + + "x\nabc\n" + + // Trailing unknown node directly before SalvageCombine. + "Spirit\n\n0;1;2016\n" + + "21\nEncapsulated Spirit\n" + + "SalvageCombine\n1\n1\n1-6, 7-8, 9, 10\n1\n25\n1-10\n"; + + private static void RunUnknownNodeTests() + { + Console.WriteLine("\n-- unknown VTank node types --"); + + VTankLootProfile p = VTankLootParser.LoadFromText(UnknownNodeUtl); + Eq(p.Rules.Count, 4, "unknown nodes: every rule parsed"); + Eq(string.Join("|", p.Rules.Select(r => r.Name)), "Mixed|Coins|Bogus|Spirit", "unknown nodes: rule names in order"); + + VTankLootRule mixed = p.Rules[0]; + Eq(mixed.Conditions.Count, 3, "unknown nodes: Mixed keeps three conditions"); + Eq(string.Join(",", mixed.Conditions[0].DataLines), "0", "unknown nodes: leading 2011 reads only its own line"); + Eq(mixed.Conditions[1].NodeType, VTankNodeTypes.LongValKeyGE, "unknown nodes: known node after an unknown one"); + Eq(string.Join(",", mixed.Conditions[1].DataLines), "15,374", "unknown nodes: known node data aligned"); + Eq(string.Join(",", mixed.Conditions[2].DataLines), "0", "unknown nodes: trailing 2011 reads only its own line"); + + Eq(string.Join(",", p.Rules[1].Conditions[0].DataLines), "Coin,1", "unknown nodes: following name rule intact"); + Eq(string.Join(",", p.Rules[2].Conditions[0].DataLines), "abc", "unknown nodes: non-numeric length code falls back"); + Eq(string.Join(",", p.Rules[3].Conditions[0].DataLines), "Encapsulated Spirit", "unknown nodes: 2016 reads one line"); + + Check(p.SalvageCombine != null, "unknown nodes: SalvageCombine block survives a trailing unknown node"); + if (p.SalvageCombine != null) + { + Check(p.SalvageCombine.Enabled, "unknown nodes: SalvageCombine enabled"); + Eq(p.SalvageCombine.PerMaterial.TryGetValue(25, out string? bands) ? bands : null, "1-10", + "unknown nodes: SalvageCombine per-material band"); + } + + // Unknown nodes keep their exact lines, so a re-save does not corrupt the profile. + VTankLootProfile back = VTankLootParser.LoadFromText(VTankLootWriter.Serialize(p)); + Eq(string.Join("|", back.Rules.Select(r => r.Name)), "Mixed|Coins|Bogus|Spirit", "unknown nodes: round-trip rule names"); + Eq(string.Join(",", back.Rules[0].Conditions[2].DataLines), "0", "unknown nodes: round-trip keeps unknown data"); + Eq(p.DeclaredRuleCount, 4, "unknown nodes: declared count recorded"); + + // A header that undercounts: every rule present is still read, SalvageCombine too, + // and a re-save writes the true count. + string undercounted = UnknownNodeUtl.Replace("UTL\n1\n4\n", "UTL\n1\n2\n"); + VTankLootProfile u = VTankLootParser.LoadFromText(undercounted); + Eq(u.DeclaredRuleCount, 2, "undercounted header: declared count"); + Eq(string.Join("|", u.Rules.Select(r => r.Name)), "Mixed|Coins|Bogus|Spirit", "undercounted header: all rules read"); + Check(u.SalvageCombine != null, "undercounted header: SalvageCombine still parsed"); + Eq(VTankLootParser.LoadFromText(VTankLootWriter.Serialize(u)).DeclaredRuleCount, 4, "undercounted header: re-save fixes the count"); + } +} diff --git a/Tools/RynthCore.LootSdkTests/Program.cs b/Tools/RynthCore.LootSdkTests/Program.cs index e12d48e..aa41afa 100644 --- a/Tools/RynthCore.LootSdkTests/Program.cs +++ b/Tools/RynthCore.LootSdkTests/Program.cs @@ -46,6 +46,7 @@ internal static partial class Program RunLootAddTests(args); RunT11Tests(); RunLootAddT11Tests(); + RunUnknownNodeTests(); Console.WriteLine($"\nGolden tests: {_asserts} assertions, {_fails} failed."); diff --git a/Tools/RynthCore.PatrolProof/Program.cs b/Tools/RynthCore.PatrolProof/Program.cs index c8078ea..d11d129 100644 --- a/Tools/RynthCore.PatrolProof/Program.cs +++ b/Tools/RynthCore.PatrolProof/Program.cs @@ -25,6 +25,7 @@ namespace RynthCore.PatrolProof; // // It also compares /ra dunnav paths between 40 random cell pairs. Extra words: // verbose list the off-floor legs trace log every room crossing +// waypoints one line per patrol waypoint and the rule that laid it (Waypoints.cs) // doors x y list the cells, openings and floor polygons within 20 m of world (x, y) // // Run: dotnet run -c Release [-- ] [-- ] [-- dump ] [-- verbose] @@ -33,6 +34,7 @@ internal static class Program private static int Main(string[] args) { if (args.Length > 0 && args[0] == "clear") return Clearance.Run(args.Skip(1).ToArray()); + if (args.Contains("waypoints")) return Waypoints.Run(args); uint lb = 0x6346; string acDir = @"C:\Turbine\Asheron's Call"; string dumpDir = null; diff --git a/Tools/RynthCore.PatrolProof/RynthCore.PatrolProof.csproj b/Tools/RynthCore.PatrolProof/RynthCore.PatrolProof.csproj index cdb69d9..c7c7c7b 100644 --- a/Tools/RynthCore.PatrolProof/RynthCore.PatrolProof.csproj +++ b/Tools/RynthCore.PatrolProof/RynthCore.PatrolProof.csproj @@ -29,6 +29,8 @@ + + diff --git a/Tools/RynthCore.PatrolProof/Waypoints.cs b/Tools/RynthCore.PatrolProof/Waypoints.cs new file mode 100644 index 0000000..52e376f --- /dev/null +++ b/Tools/RynthCore.PatrolProof/Waypoints.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Raycasting; + +namespace RynthCore.PatrolProof; + +// "waypoints": the patrol the plugin builds from given start cells, one line per waypoint with +// the rule that laid it (DungeonPathfinder.DescribePatrol, the same lines BuildDunPatrol logs as +// "[RynthAi] DunNav-Patrol wp ..."), and the hazard set the game would use: +// dotnet run -c Release -- 6146 waypoints 61460100 61460325 [surface] [hzfile ] [hz 012E,0131] [summary] [tiny] +// surface add the Detector C cells (floor textures in HazardTextures.txt, as the game seeds them) +// hzfile f add the cells listed in a DungeonHazards/.txt file +// hz a,b,... add cells (low 16 bits hex, or full ids) +// compare for each start, the summary with none / surface / file+hz / all hazards +// summary summary lines only tiny only waypoints in rooms of <= 5 cells +// The start cell is handled as BuildDunPatrol does: a start in a hazard moves to NearestSafeCell. +internal static class Waypoints +{ + public static int Run(string[] args) + { + uint lb = 0x6146; + string acDir = @"C:\Turbine\Asheron's Call"; + var starts = new List(); + bool surface = false, summaryOnly = false, tinyOnly = false, compare = false; + var extra = new HashSet(); + var fileCells = new HashSet(); + for (int i = 0; i < args.Length; i++) + { + string a = args[i]; + if (a == "waypoints") continue; + if (a == "surface") surface = true; + else if (a == "summary") summaryOnly = true; + else if (a == "tiny") tinyOnly = true; + else if (a == "compare") compare = true; + else if (a == "hzfile" && i + 1 < args.Length) + { + foreach (string raw in File.ReadAllLines(args[++i])) + { + string l = raw.Trim(); + if (l.Length == 0 || l[0] == '#') continue; + if (uint.TryParse(l.Replace("0x", ""), NumberStyles.HexNumber, null, out uint c)) fileCells.Add(c); + } + } + else if (a == "hz" && i + 1 < args.Length) + foreach (string t in args[++i].Split(',', StringSplitOptions.RemoveEmptyEntries)) + extra.Add(uint.Parse(t.Replace("0x", ""), NumberStyles.HexNumber)); + else if (a.Length <= 6 && uint.TryParse(a.Replace("0x", ""), NumberStyles.HexNumber, null, out uint v)) lb = v; + else if (a.Length == 8 && uint.TryParse(a, NumberStyles.HexNumber, null, out uint s)) starts.Add(s); + else acDir = a; + } + // Low-16 ids become full cell ids of this landblock. + extra = extra.Select(c => c <= 0xFFFF ? (lb << 16) | c : c).ToHashSet(); + + var loader = new GeometryLoader(); + if (!loader.Initialize(acDir)) { Console.WriteLine("Geometry loader failed: " + loader.StatusMessage); return 1; } + var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat); + var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS); + var surfaceCells = DungeonHazardSurfaces.ComputeHazardCells(lb, loader.CellDat, loader.PortalDat); + Console.WriteLine($"Landblock 0x{lb:X4}: {graph.Count} cells; hazard textures {DungeonHazardSurfaces.HazardTextureCount} -> {surfaceCells.Count} Detector C cells: {Ids(surfaceCells)}"); + if (fileCells.Count > 0) Console.WriteLine($" hzfile cells: {Ids(fileCells)}"); + if (extra.Count > 0) Console.WriteLine($" hz cells: {Ids(extra)}"); + if (starts.Count == 0) starts.Add(graph.Keys.Min()); + + var sets = new List<(string Name, HashSet Cells)>(); + var given = new HashSet(fileCells.Concat(extra)); + if (compare) + { + sets.Add(("none", new HashSet())); + sets.Add(("surface", new HashSet(surfaceCells))); + if (given.Count > 0) sets.Add(("file+hz", new HashSet(given))); + if (given.Count > 0) sets.Add(("all", new HashSet(surfaceCells.Concat(given)))); + } + else + { + var cells = new HashSet(given); + if (surface) cells.UnionWith(surfaceCells); + sets.Add((surface ? (given.Count > 0 ? "all" : "surface") : given.Count > 0 ? "file+hz" : "none", cells)); + } + + foreach (uint s0 in starts) + foreach (var (name, cells) in sets) + { + uint start = s0; + IReadOnlySet hazards = cells.Count > 0 ? cells : null; + if (hazards != null && hazards.Contains(start)) + { + uint safe = DungeonPathfinder.NearestSafeCell(graph, start, hazards); + if (safe != 0) start = safe; + } + var log = new Dictionary(ReferenceEqualityComparer.Instance); + DungeonPathfinder.PointLog = log; + NavRouteParser route; + try { route = DungeonPathfinder.BuildPatrolRoute(graph, start, hazards, geo); } + finally { DungeonPathfinder.PointLog = null; } + var lines = DungeonPathfinder.DescribePatrol(route, graph, geo, hazards, log); + Console.WriteLine(); + Console.WriteLine($"== start {s0:X8}{(start != s0 ? $" (moved to safe {start:X8})" : "")}, hazards {name} ({cells.Count})"); + Console.WriteLine(" " + EnteredRooms(route, graph, geo, hazards, log)); + foreach (string l in lines) + { + bool isSummary = l.StartsWith("wp summary", StringComparison.Ordinal) || l.StartsWith("wp main route", StringComparison.Ordinal); + if (summaryOnly && !isSummary) continue; + if (tinyOnly && !isSummary && !IsTiny(l)) continue; + Console.WriteLine(" " + l); + } + } + return 0; + } + + // "room N (k cells)" with k <= 5. + private static bool IsTiny(string line) + { + int at = line.IndexOf(" room ", StringComparison.Ordinal); + if (at < 0) return false; + int open = line.IndexOf('(', at), sp = line.IndexOf(" cells)", at, StringComparison.Ordinal); + return open > 0 && sp > open && int.TryParse(line.AsSpan(open + 1, sp - open - 1), out int n) && n > 0 && n <= 5; + } + + // Rooms with at least one waypoint not laid by a look-in, by size. + private static string EnteredRooms(NavRouteParser route, Dictionary graph, DungeonGeometry geo, + IReadOnlySet hazards, Dictionary log) + { + var rooms = DungeonPathfinder.BuildRooms(graph, geo, hazards); + var entered = new HashSet(); + var looked = new HashSet(); + foreach (var p in route.Points) + { + log.TryGetValue(p, out var info); + uint cell = info != null && info.Cell != 0 ? info.Cell : DungeonPathfinder.CellAt(graph, geo, p); + if (!rooms.RoomOf.TryGetValue(cell, out int r)) continue; + if (info != null && info.Why.StartsWith("look-in", StringComparison.Ordinal) && info.Room == r) looked.Add(r); + else entered.Add(r); + } + int tiny = entered.Count(r => rooms.Cells[r].Count <= 5); + var tinyList = entered.Where(r => rooms.Cells[r].Count <= 5).OrderBy(r => r) + .Select(r => $"{r}[{string.Join(",", rooms.Cells[r].Select(c => (c & 0xFFFF).ToString("X4")))}]"); + return $"rooms entered {entered.Count} (of {rooms.Cells.Count}), of them <= 5 cells: {tiny}: {string.Join(" ", tinyList)}; looked into {looked.Count}"; + } + + private static string Ids(IEnumerable cells) => string.Join(",", cells.OrderBy(c => c).Select(c => (c & 0xFFFF).ToString("X4"))); +} diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 3073038..f4ec4a9 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -63,6 +63,7 @@ internal static class Program LootCorpseTests.Register(runner); OwnCorpseTests.Register(runner); UseRefusalTests.Register(runner); + CorpseKillerTests.Register(runner); VitalsTests.Register(runner); MultiTargetTests.Register(runner); CastSafetyTests.Register(runner); @@ -73,6 +74,7 @@ internal static class Program UseAtLoginTests.Register(runner); LearnSpellsTests.Register(runner); AttackLatencyTests.Register(runner); + TargetingTests.Register(runner); LootAddItemTests.Register(runner); GiveTests.Register(runner); DungeonMapBakeTests.Register(runner); @@ -87,6 +89,7 @@ internal static class Program ManaStoneChoiceTests.Register(runner); CustomDebuffTests.Register(runner); ProfileLoadTests.Register(runner); + ActivityInterfaceTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ActivityInterfaceTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ActivityInterfaceTests.cs new file mode 100644 index 0000000..4cab120 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ActivityInterfaceTests.cs @@ -0,0 +1,73 @@ +using System; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// "RynthAi.Activity" v1 (2026-10-11): the read-only bits RynthSort reads so its pack moves stay +// out of RynthAi's way. The mapping from RynthAi's state is ActivityInterface.Compose; the table +// comes from ActivityInterface.Query (what the engine's GetPluginInterface hands other plugins). +internal static class ActivityInterfaceTests +{ + public static void Register(Runner r) + { + r.Add("activity: each arbiter decision maps to its own bit", ArbiterBits); + r.Add("activity: corpse, salvage queue, server wait, crafting and AutoCram add their bits", ExtraBits); + r.Add("activity: the table answers only its own name and versions", QueryTable); + } + + private static void ArbiterBits() + { + Check.Eq(ActivityInterface.Compose(BotActivity.Idle, false, false, false, false, false, false), RynthAiActivity.None, "idle, macro off"); + Check.Eq(ActivityInterface.Compose(BotActivity.Idle, true, false, false, false, false, false), RynthAiActivity.MacroRunning, "idle, macro on"); + Check.Eq(ActivityInterface.Compose(BotActivity.Buffing, true, false, false, false, false, false), + RynthAiActivity.MacroRunning | RynthAiActivity.Buffing, "buffing"); + Check.Eq(ActivityInterface.Compose(BotActivity.Combat, true, false, false, false, false, false), + RynthAiActivity.MacroRunning | RynthAiActivity.Combat, "combat"); + Check.Eq(ActivityInterface.Compose(BotActivity.Looting, true, false, false, false, false, false), + RynthAiActivity.MacroRunning | RynthAiActivity.Looting, "looting"); + Check.Eq(ActivityInterface.Compose(BotActivity.Salvaging, true, false, false, false, false, false), + RynthAiActivity.MacroRunning | RynthAiActivity.Salvaging, "salvaging"); + Check.Eq(ActivityInterface.Compose(BotActivity.Navigating, true, false, false, false, false, false), + RynthAiActivity.MacroRunning | RynthAiActivity.Navigating, "navigating"); + } + + private static void ExtraBits() + { + // A corpse RynthAi opened or claimed counts as looting whatever the tick's owner is. + RynthAiActivity f = ActivityInterface.Compose(BotActivity.Navigating, true, corpseInHand: true, false, false, false, false); + Check.True((f & RynthAiActivity.Looting) != 0 && (f & RynthAiActivity.Navigating) != 0, "corpse in hand while navigating -> looting too"); + f = ActivityInterface.Compose(BotActivity.Combat, true, false, salvageBusy: true, false, false, false); + Check.True((f & RynthAiActivity.Salvaging) != 0, "salvage queue while fighting -> salvaging"); + f = ActivityInterface.Compose(BotActivity.Idle, false, false, false, serverWait: true, false, false); + Check.Eq(f, RynthAiActivity.ServerAction, "a player's command waiting on the server, macro off"); + f = ActivityInterface.Compose(BotActivity.Idle, true, false, false, false, crafting: true, autoCram: true); + Check.Eq(f, RynthAiActivity.MacroRunning | RynthAiActivity.Crafting | RynthAiActivity.AutoCram, "crafting + AutoCram"); + } + + private static unsafe void QueryTable() + { + try + { + Check.True(ActivityInterface.Query("RynthAi.Status", 1) == IntPtr.Zero, "another interface's name"); + Check.True(ActivityInterface.Query(RynthAiActivityApiV1.InterfaceName, 0) == IntPtr.Zero, "version 0"); + Check.True(ActivityInterface.Query(RynthAiActivityApiV1.InterfaceName, 2) == IntPtr.Zero, "a newer version than RynthAi has"); + IntPtr p = ActivityInterface.Query(RynthAiActivityApiV1.InterfaceName, 1); + Check.True(p != IntPtr.Zero, "v1 answers"); + var t = (RynthAiActivityApiV1*)p; + Check.Eq(t->Version, 1u, "table version"); + Check.Eq(t->StructSize, (uint)sizeof(RynthAiActivityApiV1), "table size"); + Check.True(t->GetActivityFlags != null, "function filled in"); + Check.True(ActivityInterface.Query(RynthAiActivityApiV1.InterfaceName, 1) == p, "the same table on every call"); + // No plugin instance (not logged in): not ready, flags cleared. + uint flags = 0xFFFFFFFF; + Check.Eq(t->GetActivityFlags(&flags), 0, "not ready without a logged-in plugin"); + Check.Eq(flags, 0u, "flags cleared when not ready"); + } + finally + { + ActivityInterface.Release(); + } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CorpseKillerTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CorpseKillerTests.cs new file mode 100644 index 0000000..bc5f2c8 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/CorpseKillerTests.cs @@ -0,0 +1,54 @@ +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-10-06: Silentkelpie skipped its own kills unopened (Necrolytic Extract left behind). The +// corpse LongDesc had gained "Corpse will decay in 56s" under the "Killed by" line and the killer +// read as "Silentkelpie.\nCorpse will decay in 56s", which never matches the character name. +internal static class CorpseKillerTests +{ + public static void Register(Runner r) + { + r.Add("corpse killer: plain 'Killed by X.'", Plain); + r.Add("corpse killer: decay line after the killer is ignored", DecayLineIgnored); + r.Add("corpse killer: CRLF and multi-word names", CrLfMultiWord); + r.Add("corpse killer: no 'Killed by' line reads as unknown", Missing); + r.Add("corpse killer: radar column reads the same name", RadarMatches); + } + + private static void Plain() + { + Check.Eq(RynthAiPlugin.ExtractCorpseKillerName("Killed by Silentkelpie."), "Silentkelpie", "plain line"); + Check.Eq(RynthAiPlugin.ExtractCorpseKillerName("Killed by Silentkelpie"), "Silentkelpie", "no trailing period"); + } + + private static void DecayLineIgnored() + { + Check.Eq(RynthAiPlugin.ExtractCorpseKillerName("Killed by Silentkelpie.\nCorpse will decay in 56s"), + "Silentkelpie", "LF decay line"); + Check.Eq(RynthAiPlugin.ExtractCorpseKillerName("Killed by Silentkelpie.\n\nCorpse will decay in 4m 12s."), + "Silentkelpie", "blank line then decay line"); + } + + private static void CrLfMultiWord() + { + Check.Eq(RynthAiPlugin.ExtractCorpseKillerName("Killed by Moreck II.\r\nCorpse will decay in 3m 10s"), + "Moreck II", "CRLF and a roman-numeral suffix"); + } + + private static void Missing() + { + Check.Null(RynthAiPlugin.ExtractCorpseKillerName(""), "empty LongDesc"); + Check.Null(RynthAiPlugin.ExtractCorpseKillerName(null), "null LongDesc"); + Check.Null(RynthAiPlugin.ExtractCorpseKillerName("Corpse will decay in 56s"), "decay line only"); + Check.Null(RynthAiPlugin.ExtractCorpseKillerName("Killed by .\nCorpse will decay in 56s"), "empty killer"); + } + + private static void RadarMatches() + { + Check.Eq(RynthRadarUi.ExtractKiller("Killed by Silentkelpie.\nCorpse will decay in 56s"), "Silentkelpie", "radar decay line"); + Check.Eq(RynthRadarUi.ExtractKiller(null), "", "radar unknown is empty"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HazardEscapeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HazardEscapeTests.cs index 8bca30b..e7b888d 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/HazardEscapeTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/HazardEscapeTests.cs @@ -25,7 +25,7 @@ internal static class HazardEscapeTests r.Add("hazard: the hotspot damage line is read (amount, source); other lines are not", Parse); r.Add("hazard: a hit stops everything and walks back along the footsteps, then hands back", EscapeAlongFootsteps); r.Add("hazard: hurt again where it stopped - it goes further back", FurtherBack); - r.Add("hazard: macro off - the cell is still learned, nothing moves", MacroOff); + r.Add("hazard: macro off - nothing moves, nothing learned", MacroOff); r.Add("hazard: Escape Acid and Lava off - no escape and nothing learned (some walk through acid)", SettingOff); } @@ -85,7 +85,7 @@ internal static class HazardEscapeTests b.Hit(); Check.True(b.P.HazardEscaping, "the hit starts the escape"); - Check.True(b.Cache.IsHazardCell(CellB), "the cell it was hurt in is a hazard now"); + Check.False(b.Cache.IsHazardCell(CellB), "the cell it was hurt in is not a patrol hazard (patrol as before 10-07)"); Check.True(b.Hold(), "the escape owns the tick (nothing else runs)"); Check.True(FakeHost.AutoRun, "running"); @@ -134,7 +134,7 @@ internal static class HazardEscapeTests b.S.IsMacroRunning = false; for (int i = 0; i <= 6; i++) b.At(CellA, 60f, -185f + i); b.Hit(); - Check.True(b.Cache.IsHazardCell(CellA), "the cell is learned"); + Check.False(b.Cache.IsHazardCell(CellA), "the cell is not learned"); Check.False(b.P.HazardEscaping, "but nothing moves the character while you play it"); Check.False(b.Hold(), "and the tick is not held"); } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootSalvageTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootSalvageTests.cs index 98678a7..5429af4 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootSalvageTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootSalvageTests.cs @@ -40,6 +40,7 @@ internal static class LootSalvageTests r.Add("salvage: an item queued before it reaches the pack waits, then is salvaged", SalvageWaitsForArrival); r.Add("salvage: a pickup whose confirm was lost is still salvaged (tracked + sweep)", SalvageLostConfirm); r.Add("salvage: no UST keeps the items until one is in the pack", SalvageNoUstKeepsItems); + r.Add("salvage: no UST - HasUst false, no combine sweep; a UST in the pack turns both on", SalvageNoUstNoSweep); r.Add("salvage: skipped items are logged with their reason, once per batch", SalvageSkipReasonsLogged); r.Add("salvage: an item that keeps failing rests, retries, and is given up with a log line", SalvageGiveUpIsBounded); } @@ -287,6 +288,24 @@ internal static class LootSalvageTests Check.True(items.All(id => !w.InWorld(id)), "every item salvaged"); } + private static void SalvageNoUstNoSweep() + { + var w = new World(Items(0), withUst: false); + w.Settings.EnableCombineSalvage = true; + Check.False(w.Mgr.HasUst(), "no UST carried"); + w.Run(65_000, step: 500); + Check.False(w.SalvageLogs.Any(l => l.Contains("Combine sweep", StringComparison.Ordinal)), "no combine sweep without a UST"); + Check.Eq(FakeHost.Uses.Count, 0, "nothing used"); + + var ids = new List(); + World.AddUst(ids); + _ = w.Cache[unchecked((int)Ust)]; + w.Run(4_000, step: 500); + Check.True(w.Mgr.HasUst(), "a UST in the pack is seen (within the 3 s cache)"); + w.Run(31_000, step: 500); + Check.True(w.SalvageLogs.Any(l => l.Contains("Combine sweep", StringComparison.Ordinal)), "the combine sweep runs again"); + } + private static void SalvageSkipReasonsLogged() { uint good = ItemBase + 1, retained = ItemBase + 2, listed = ItemBase + 3; diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs index 3200b07..7f7c987 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs @@ -1,3 +1,6 @@ +using System; +using System.Collections.Generic; +using System.Linq; using RynthCore.Loot; using RynthCore.Plugin.RynthAi; using RynthCore.Plugin.RynthAi.LegacyUi; @@ -14,6 +17,149 @@ internal static class ManaStoneChoiceTests { r.Add("mana stones: only ordinary stones and charges are used; special stones only when a rule names them", OrdinaryOnly); r.Add("mana stones: with tapping off, charged stones and Mana Charges still refill worn gear", RefillWithoutTapping); + r.Add("mana stones: a stone the server called charged refills worn gear though its charge can't be read", KnownChargedRefills); + r.Add("mana stones: a stone just drained refills worn gear though its read still says empty", DrainedStoneRefills); + r.Add("mana stones: a stone that gave its mana is not used again; 'fully charged' holds refills", GaveManaNotReused); + r.Add("mana stones: tapping off, a stone whose charge can't be read is identified, then used", UnreadableStoneIdentified); + } + + // ── Refill rig (2026-10-11) ─────────────────────────────────────────── + // A stone's charge is read from its last appraisal; the server never sends a change to it. + // 2026-10-10: five charged stones whose charge couldn't be read were tried as empty stones + // ("The Ring is already full of mana."), marked known-charged, and then never used on a worn + // Khanda-handled Mace at 0% for over an hour. 2026-10-08: a stone that had just given its mana + // still read charged and was used again, cancelled by the server, timed out and parked. + + private const uint Player = 0x50000E01; + private const uint StoneA = 0x80400001, StoneB = 0x80400002, StoneC = 0x80400003; + private const uint Mace = 0x80400010, Ring = 0x80400020; + private const uint CurManaKey = 107, MaxManaKey = 108, WieldedSlotKey = 10; + + private sealed class Rig : IDisposable + { + public long Now = 1_000_000; + public readonly LegacyUiSettings S; + public readonly ManaStoneManager M; + + /// Stone id and its charge read (null = can't be read). + public Rig(bool tapping, (uint Id, int? Mana)[] stones, bool ringToDrain = false) + { + FakeHost.Reset(); + FakeHost.UseOnCalls = true; + FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData + FakeHost.Names[Player] = "Stone Tester"; + foreach (var (id, mana) in stones) + { + FakeHost.Names[id] = "Moderate Mana Stone"; + FakeHost.Containers[id] = Player; + SetMana(id, mana); + } + FakeHost.Names[Mace] = "Khanda-handled Mace"; + FakeHost.Wielders[Mace] = Player; + FakeHost.Ints[(Mace, WieldedSlotKey)] = 0x100000; + FakeHost.Ints[(Mace, MaxManaKey)] = 5000; + FakeHost.Ints[(Mace, CurManaKey)] = 0; // and it keeps reading 0: worn-item mana is an appraisal too + var ids = new List(); + foreach (var st in stones) ids.Add(st.Id); + ids.Add(Mace); + if (ringToDrain) + { + FakeHost.Names[Ring] = "Ring"; + FakeHost.Containers[Ring] = Player; + FakeHost.Ints[(Ring, MaxManaKey)] = 4000; + FakeHost.Ints[(Ring, CurManaKey)] = 4000; + ids.Add(Ring); + } + + var host = FakeHost.Create(Player); + var cache = FakeHost.MakeCache(host, Player, ids); + S = new LegacyUiSettings { EnableManaTapping = tapping, ManaTapMinMana = 100 }; + S.IsMacroRunning = true; + ManaStoneManager.Clock = () => Now; + M = new ManaStoneManager(host, S, cache); + if (ringToDrain) M.MarkLootedForTap(unchecked((int)Ring)); + } + + public static void SetMana(uint id, int? mana) + { + if (mana == null) FakeHost.Ints.Remove((id, CurManaKey)); + else FakeHost.Ints[(id, CurManaKey)] = mana.Value; + } + + public void Run(long ms) + { + for (long t = 0; t < ms; t += 100) + { + Now += 100; + M.OnHeartbeat(0); + } + } + + public void Chat(string line) => M.OnChatWindowText(line); + + public List OnPlayer => FakeHost.UsesOn.Where(u => u.Target == Player).Select(u => u.Source).ToList(); + public List OnRing => FakeHost.UsesOn.Where(u => u.Target == Ring).Select(u => u.Source).ToList(); + + public void Dispose() => ManaStoneManager.Clock = static () => Environment.TickCount64; + } + + private static void KnownChargedRefills() + { + using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null), (StoneB, null) }, ringToDrain: true); + rig.Run(1000); + Check.Eq(rig.OnRing.Count, 1, "an unreadable stone is tried as the empty stone for the looted ring"); + rig.Chat("The Ring is already full of mana."); + rig.Run(1000); + Check.Eq(rig.OnRing.Count, 2, "the next unreadable stone is tried"); + Check.True(rig.OnRing[0] != rig.OnRing[1], "a different stone"); + rig.Chat("The Ring is already full of mana."); + rig.Run(1000); + Check.Eq(rig.OnRing.Count, 2, "no stone left to drain into"); + Check.Eq(rig.OnPlayer.Count, 1, "a stone the server called charged refills the 0% mace"); + } + + private static void DrainedStoneRefills() + { + using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null) }, ringToDrain: true); + rig.Run(1000); + Check.Eq(rig.OnRing.Count, 1, "the empty stone drains the looted ring"); + rig.Chat("The Mana Stone drains 3,600 points of mana from the Ring.\nThe Ring is destroyed."); + rig.Run(1000); + Check.Eq(rig.OnPlayer.Count, 1, "the stone it just charged refills the 0% mace"); + Check.Eq(rig.OnPlayer.FirstOrDefault(), StoneA, "that stone"); + } + + private static void GaveManaNotReused() + { + using var rig = new Rig(tapping: false, new (uint, int?)[] { (StoneA, 3000), (StoneB, 2000), (StoneC, 1000) }); + rig.Run(1000); + Check.Eq(rig.OnPlayer.Count, 1, "the fullest stone refills the mace"); + Check.Eq(rig.OnPlayer[0], StoneA, "stone A (3000)"); + rig.Chat("The Mana Stone gives 3,000 points of mana to the following items: Khanda-handled Mace.\nYou need 2,000 more mana to fully charge your items."); + rig.Run(1000); + Check.Eq(rig.OnPlayer.Count, 2, "the gear still needs mana: the next stone"); + Check.Eq(rig.OnPlayer[1], StoneB, "stone B, not A again (A's read still says 3000)"); + rig.Chat("The Mana Stone gives 2,000 points of mana to the following items: Khanda-handled Mace.\nYour items are fully charged."); + rig.Run(60_000); + Check.Eq(rig.OnPlayer.Count, 2, "fully charged: no stone for a while though the mace still reads 0%"); + rig.Run(70_000); + Check.Eq(rig.OnPlayer.Count, 3, "after the hold the stale read is tried once more"); + Check.Eq(rig.OnPlayer[2], StoneC, "with stone C"); + rig.Chat("You have no items equipped that need mana."); + rig.Run(60_000); + Check.Eq(rig.OnPlayer.Count, 3, "the server says nothing needs mana: held again, C kept"); + } + + private static void UnreadableStoneIdentified() + { + using var rig = new Rig(tapping: false, new (uint, int?)[] { (StoneA, null) }); + rig.Run(1000); + Check.True(FakeHost.IdRequests.Contains(StoneA), "the stone whose charge can't be read is identified"); + Check.Eq(rig.OnPlayer.Count, 0, "not used before its charge is known"); + Rig.SetMana(StoneA, 3000); // the appraisal lands + rig.Run(6000); + Check.Eq(rig.OnPlayer.Count, 1, "then it refills the mace"); + Check.Eq(FakeHost.IdRequests.Count(i => i == StoneA), 1, "identified once"); } private static void OrdinaryOnly() diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PatrolDoorwayTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PatrolDoorwayTests.cs index a5bdf4f..eafaeef 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/PatrolDoorwayTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PatrolDoorwayTests.cs @@ -26,6 +26,33 @@ namespace RynthCore.RynthAiHostTests.Tests; // inside corner gets a corner. internal static class PatrolDoorwayTests { + // 2026-10-10, 0x6146: hazards cut the loops and the patrol fell back to every dead end. Now, + // in that case, only short spurs (closets) go: a junction J with a 1-cell closet, a 3-cell + // spur and a 5-cell branch hanging off a loop. + private static void TrimShortSpurs() + { + var g = new Dictionary(); + void Link(uint a, uint b) + { + foreach (uint c in new[] { a, b }) + if (!g.ContainsKey(c)) g[c] = new DungeonNavNode { CellId = c, NS = (c & 0xFF) * 0.01, EW = (c >> 8 & 0xFF) * 0.01 }; + g[a].Neighbors.Add(b); g[b].Neighbors.Add(a); + } + // Loop 1-2-3-4, J = 1. + Link(0x01, 0x02); Link(0x02, 0x03); Link(0x03, 0x04); Link(0x04, 0x01); + Link(0x01, 0x10); // closet + Link(0x01, 0x20); Link(0x20, 0x21); Link(0x21, 0x22); // 3-cell spur + Link(0x02, 0x30); Link(0x30, 0x31); Link(0x31, 0x32); Link(0x32, 0x33); Link(0x33, 0x34); // 5-cell branch + var all = new HashSet(g.Keys); + var kept = DungeonPathfinder.TrimShortSpurs(g, all, 0x03, DungeonPathfinder.PatrolMaxSpurCells); + Check.False(kept.Contains(0x10), "the 1-cell closet goes"); + Check.False(kept.Overlaps(new uint[] { 0x20, 0x21, 0x22 }), "the 3-cell spur goes"); + Check.True(kept.IsSupersetOf(new uint[] { 0x30, 0x31, 0x32, 0x33, 0x34 }), "the 5-cell branch stays whole"); + Check.True(kept.IsSupersetOf(new uint[] { 1, 2, 3, 4 }), "the loop stays"); + var keepStart = DungeonPathfinder.TrimShortSpurs(g, all, 0x10, DungeonPathfinder.PatrolMaxSpurCells); + Check.True(keepStart.Contains(0x10), "the start cell is never trimmed"); + } + public static void Register(Runner r) { r.Add("dungeon doorways: an opening's centre, facing and width come from its portal polygons", DoorwayFromPortals); @@ -38,6 +65,7 @@ internal static class PatrolDoorwayTests r.Add("dungeon patrol: a loop through a big room: no points inside it, every doorway taken", PatrolLoop); r.Add("dungeon patrol: a big dead-end room is looked into, not skirted", PatrolLooksIntoDeadEndRoom); r.Add("dungeon floors: a ceiling (facing down) is not a floor", CeilingIsNotFloor); + r.Add("dungeon patrol: spurs of up to 3 cells trimmed, a long branch kept whole", TrimShortSpurs); r.Add("dungeon clearance: walls, floor edges and slopes too steep to stand on bound it; a face high above doesn't", ClearanceMeasure); r.Add("dungeon clearance: a point next to a wall (or past the floor's edge) is pushed out to 1 m", PushedOffWall); r.Add("dungeon clearance: a point in a corridor narrower than 2 m ends on its middle line", NarrowCorridorCentred); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs new file mode 100644 index 0000000..8fd54be --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs @@ -0,0 +1,286 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Combat target selection (2026-10-10): the Targeting setting (lowest health, closest, farthest, +// least turning) and Target Lock. Combat used to switch targets mid-fight on a blended score; now +// a locked target is kept until it dies or goes, leaves Monster Range, or a higher-priority +// monster is in range, and with the lock off a switch needs a clear margin under the rule. +internal static class TargetingTests +{ + private const uint Player = 0x50000E01; + private const uint Lb = 0xA9B40000; + private const uint A = 0x80000401, B = 0x80000402, C = 0x80000403, Boss = 0x80000404; + + private const int LowestHealth = 0, Closest = 1, Farthest = 2, LeastTurning = 3; + + public static void Register(Runner r) + { + r.Add("targeting: each scheme picks its monster", SchemesPick); + r.Add("targeting: unknown health counts as full; ties go to the closest, then the lower id", UnknownHealthAndTies); + r.Add("targeting: Target Lock keeps the target when a better one of its tier appears", LockKeeps); + r.Add("targeting: Target Lock lets go when the target goes (after the scan grace)", LockReleasesWhenGone); + r.Add("targeting: Target Lock lets go when the target leaves Monster Range", LockReleasesOutOfRange); + r.Add("targeting: a higher-priority monster in range takes over, lock or not", HigherPriorityWins); + r.Add("targeting: lock off switches only past each scheme's margin", LockOffMargins); + r.Add("targeting: lock off never switches with an attack at the target in flight", NoSwitchInFlight); + r.Add("targeting: settings default to lowest health with the lock on", Defaults); + } + + // ── Schemes ─────────────────────────────────────────────────────────────── + + private static void SchemesPick() + { + // A: close, facing away, lightly wounded. B: mid, nearly ahead, badly wounded. + // C: far, health unknown. + var health = new Dictionary { [A] = 0.8f, [B] = 0.3f }; + (uint, double, double)[] scan = { (A, 2, 90), (B, 4, 10), (C, 6, 50) }; + + Check.Eq(new Rig(LowestHealth, true, health).Pick(scan), B, "lowest health: B at 30%"); + Check.Eq(new Rig(Closest, true, health).Pick(scan), A, "closest: A at 2 m"); + Check.Eq(new Rig(Farthest, true, health).Pick(scan), C, "farthest: C at 6 m"); + Check.Eq(new Rig(LeastTurning, true, health).Pick(scan), B, "least turning: B, 10 degrees off"); + + var t = new Rig(LeastTurning, true, health); + t.Pick((A, 2, 90), (B, 4, 60), (C, 6, 5)); + Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] lock 0x80000403") && l.Contains("least turning: turn 5 deg")), + "the lock line names the scheme and the deciding value"); + } + + private static void UnknownHealthAndTies() + { + // B is at 95%, A unknown: unknown counts as full, so B is the more wounded. + var t = new Rig(LowestHealth, true, new Dictionary { [B] = 0.95f }); + Check.Eq(t.Pick((A, 2, 0), (B, 5, 0)), B, "a known 95% beats an unknown (full) health"); + + // Every health unknown: all tie at full, so the closest. + t = new Rig(LowestHealth, true); + Check.Eq(t.Pick((A, 3, 0), (B, 1.5, 0), (C, 2, 0)), B, "all unknown: the closest"); + Check.True(FakeHost.Logs.Any(l => l.Contains("lowest health: health unknown (as full)")), "logged as unknown"); + + // Same distance: the lower id. + t = new Rig(Closest, true); + Check.Eq(t.Pick((B, 2, 0), (A, 2, 0)), A, "a tie in distance: the lower id"); + + // Lock off: an unknown-health monster never looks more wounded than the incumbent. + t = new Rig(LowestHealth, false, new Dictionary { [A] = 0.5f }); + Check.Eq(t.Pick((A, 3, 0), (B, 1, 0)), A, "A at 50% is picked over an unknown B"); + Check.Eq(t.Pick((A, 3, 0), (B, 1, 0), (C, 1, 0)), A, "unknown B and C don't take over"); + } + + // ── Target Lock ─────────────────────────────────────────────────────────── + + private static void LockKeeps() + { + var t = new Rig(Closest, true); + Check.Eq(t.Pick((A, 4, 0)), A, "A, alone, is locked"); + int before = FakeHost.Logs.Count(l => l.Contains("[CombatTarget]")); + Check.Eq(t.Pick((A, 4, 0), (B, 1, 0)), A, "B walks up to 1 m: the lock keeps A"); + Check.Eq(t.Pick((A, 4.5, 30), (B, 0.5, 0), (C, 0.8, 0)), A, "and keeps it with more around"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("[CombatTarget]")), before, "nothing new is logged while the lock holds"); + + t = new Rig(LowestHealth, true, new Dictionary { [A] = 0.7f, [B] = 0.9f }); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "lowest health: A at 70%"); + t.Health(B, 0.1f); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "B drops to 10%: the lock keeps A"); + } + + private static void LockReleasesWhenGone() + { + var t = new Rig(Closest, true); + Check.Eq(t.Pick((A, 2, 0), (B, 3, 0)), A, "A is locked"); + Check.Eq(t.Pick((B, 3, 0)), A, "A blinks out of the scan: kept within the scan grace"); + t.Advance(1000); + Check.Eq(t.Pick((B, 3, 0)), A, "still within the 1.5 s grace"); + t.Advance(1000); + Check.Eq(t.Pick((B, 3, 0)), B, "gone past the grace: B"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] switch 0x80000401") && l.Contains("(gone,")), + "the switch says why: gone"); + + // A kill drops the target outright (DropTarget), and the next pick is fresh. + t = new Rig(Closest, true); + t.Pick((A, 2, 0), (B, 3, 0)); + t.Combat.OnKillNotification("Mob A's perforated corpse falls before you!"); + Check.Eq(t.Combat.activeTargetId, 0, "the kill drops A"); + Check.Eq(t.Pick((B, 3, 0)), B, "and B is locked"); + } + + private static void LockReleasesOutOfRange() + { + var t = new Rig(Closest, true, monsterRange: 5); + Check.Eq(t.Pick((A, 4, 0), (B, 4.5, 0)), A, "A is locked at 4 m"); + Check.Eq(t.Pick((A, 5.5, 0)), A, "A steps past Monster Range, nothing else in range: kept"); + Check.Eq(t.Pick((A, 6.5, 0), (B, 4.8, 0)), B, "past Monster Range with B inside it: B"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] switch 0x80000401") && l.Contains("out of Monster Range, 6.5 m")), + "the switch says why: out of Monster Range"); + Check.Eq(t.Pick((A, 3, 0), (B, 4.8, 0)), B, "A coming back closer doesn't take it back (B is locked now)"); + } + + private static void HigherPriorityWins() + { + foreach (bool lockOn in new[] { true, false }) + { + string mode = lockOn ? "lock on" : "lock off"; + var t = new Rig(Closest, lockOn, monsterRange: 10); + t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 2 }); + Check.Eq(t.Pick((A, 2, 0), (B, 3, 0)), A, $"{mode}: A is locked"); + Check.Eq(t.Pick((A, 2, 0), (B, 3, 0), (Boss, 12, 0)), A, $"{mode}: a Boss outside Monster Range doesn't count"); + Check.Eq(t.Pick((A, 2, 0), (B, 3, 0), (Boss, 9, 0)), Boss, $"{mode}: the Boss inside Monster Range takes over at once, farther or not"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] switch 0x80000401") && l.Contains("priority 1 < 2")), + $"{mode}: the switch says why: priority"); + Check.Eq(t.Pick((A, 1, 0), (Boss, 9, 0)), Boss, $"{mode}: the Boss is kept over a closer, lower-priority A"); + } + } + + // ── Lock off ────────────────────────────────────────────────────────────── + + private static void LockOffMargins() + { + // Closest: 1.5 m. + var t = new Rig(Closest, false); + Check.Eq(t.Pick((A, 3, 0)), A, "closest: A at 3 m"); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "B 1 m closer: kept"); + Check.Eq(t.Pick((A, 3, 0), (B, 1.2, 0)), B, "B 1.8 m closer: switch"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] switch 0x80000401") && l.Contains("closest: 3.0 m, another is clearly better") + && l.Contains("-> 0x80000402") && l.Contains("closest: 1.2 m")), + "the switch names the scheme and both values"); + + // Farthest: 1.5 m. + t = new Rig(Farthest, false, monsterRange: 10); + Check.Eq(t.Pick((A, 8, 0)), A, "farthest: A at 8 m"); + Check.Eq(t.Pick((A, 8, 0), (B, 9, 0)), A, "B 1 m farther: kept"); + Check.Eq(t.Pick((A, 8, 0), (B, 9.8, 0)), B, "B 1.8 m farther: switch"); + + // Lowest health: 5 percentage points. + t = new Rig(LowestHealth, false, new Dictionary { [A] = 0.5f, [B] = 0.9f }); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "lowest health: A at 50%"); + t.Health(B, 0.47f); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "B at 47% (3 points lower): kept"); + t.Health(B, 0.40f); + Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), B, "B at 40% (10 points lower): switch"); + + // Least turning: 20 degrees. + t = new Rig(LeastTurning, false); + Check.Eq(t.Pick((A, 3, 30)), A, "least turning: A"); + Check.Eq(t.Pick((A, 3, 40), (B, 3, 25)), A, "B needs 15 degrees less: kept"); + Check.Eq(t.Pick((A, 3, 40), (B, 3, 15)), B, "B needs 25 degrees less: switch"); + } + + private static void NoSwitchInFlight() + { + // An attack at A with no damage since: held for the flight window. + var t = new Rig(Closest, false); + Check.Eq(t.Pick((A, 3, 0)), A, "A is locked"); + t.Combat.RecordOffensiveCast(unchecked((int)A)); + Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), A, "a cast at A in flight: B (2.5 m closer) waits"); + t.Advance(2000); + Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), A, "still in the 4 s window"); + t.Advance(2500); + Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), B, "the window passed with nothing landed: switch"); + + // Damage landing ends the hold. + t = new Rig(Closest, false); + t.Pick((A, 3, 0)); + t.Combat.RecordOffensiveCast(unchecked((int)A)); + Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), A, "cast in flight: kept"); + t.Combat.ReportDamageOnTarget(unchecked((int)A)); + Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), B, "the cast landed: switch"); + + // A target that never takes damage can't hold it forever under continuous fire. + t = new Rig(Closest, false); + t.Pick((A, 3, 0)); + t.Advance(16000); + t.Combat.RecordOffensiveCast(unchecked((int)A)); + Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), B, "16 s locked without damage: a fresh cast doesn't hold it"); + } + + private static void Defaults() + { + var s = new LegacyUiSettings(); + Check.Eq(s.TargetSelection, 0, "Targeting: lowest health"); + Check.True(s.TargetLock, "Target Lock: on"); + var loaded = System.Text.Json.JsonSerializer.Deserialize("{\"MonsterRange\":7}", RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(loaded != null && loaded.TargetLock, "a profile saved before the setting loads the lock as on"); + + // Profile switch/load copies them (CopySettings is the hand-written field list). + var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!; + var dst = new LegacyUiSettings(); + copy.Invoke(null, new object[] { new LegacyUiSettings { TargetSelection = 3, TargetLock = false }, dst }); + Check.Eq(dst.TargetSelection, 3, "a profile's Targeting is copied"); + Check.False(dst.TargetLock, "and its lock off"); + copy.Invoke(null, new object[] { loaded!, dst }); + Check.True(dst.TargetLock && dst.TargetSelection == 0, "an old profile loads the defaults"); + + // Engine Settings face: the payload carries them; an engine without the fields leaves them alone. + s = new LegacyUiSettings { TargetSelection = 2, TargetLock = false }; + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s); + typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)! + .SetValue(dash, new LegacyAdvancedSettingsUi(s)); // BuildSettingsJson reads its crafting state + var sent = System.Text.Json.JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(sent != null && sent.TargetSelection == 2 && sent.TargetLock == false, "sent to the engine face"); + dash.ApplySettingsJson("{\"PatrolOnLogin\":false}"); + Check.True(s.TargetSelection == 2 && !s.TargetLock, "a save without the fields leaves them alone"); + dash.ApplySettingsJson("{\"TargetSelection\":1,\"TargetLock\":true}"); + Check.True(s.TargetSelection == 1 && s.TargetLock, "a save with them sets them"); + dash.ApplySettingsJson("{\"TargetSelection\":9}"); + Check.Eq(s.TargetSelection, 3, "an out-of-range choice is clamped"); + } + + // ── Rig ─────────────────────────────────────────────────────────────────── + + private sealed class Rig + { + public readonly CombatManager Combat; + public readonly LegacyUiSettings S; + private readonly WorldObjectCache _cache; + private DateTime _now = DateTime.Now; + + public Rig(int scheme, bool targetLock, Dictionary? health = null, int monsterRange = 20) + { + FakeHost.Reset(); + Place(Player, "Me", 96, 96, creature: false); + FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f); + Place(A, "Mob A", 96, 98); + Place(B, "Mob B", 96, 99); + Place(C, "Mob C", 96, 100); + Place(Boss, "Boss", 96, 101); + S = new LegacyUiSettings { MonsterRange = monsterRange, TargetSelection = scheme, TargetLock = targetLock }; + var host = FakeHost.Create(); + _cache = FakeHost.MakeCache(host, Player, new[] { A, B, C, Boss }, health); + Combat = new CombatManager(host, S, _cache); + Combat.SetPlayerId(Player); + Combat.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore()); + Combat.TargetClock = () => _now; + } + + public void Health(uint id, float ratio) => _cache.OnUpdateHealth(id, ratio); + public void Advance(double ms) => _now = _now.AddMilliseconds(ms); + + /// One tick: the scan holds these (id, distance m, facing angle deg); returns the target. + public uint Pick(params (uint Id, double Dist, double Angle)[] scan) + { + Combat.SetScannedTargetsForTests(scan.Select(t => new CombatManager.ScannedTarget + { + Id = unchecked((int)t.Id), Distance = t.Dist, Angle = t.Angle, Bearing = double.NaN, Name = FakeHost.Names[t.Id], + })); + Combat.HandleCombatTrigger(); + return unchecked((uint)Combat.activeTargetId); + } + } + + private static void Place(uint id, string name, float x, float y, bool creature = true) + { + FakeHost.Names[id] = name; + FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f); + if (creature) FakeHost.ItemTypes[id] = 0x10; + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs index 8a54f9f..1b38277 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs @@ -24,6 +24,7 @@ internal static class VitalsTests r.Add("vitals: profiles without the Stamina to Health keys load today's 30 / 20", StaminaToHealthDefaults); r.Add("vitals: Re-stam To keeps a started recharge going to its line; off = one recharge as before", RestamTo); r.Add("vitals: out of Magic stance a listed stamina potion goes before Revitalize; a caster casts first", StaminaPotionFirst); + r.Add("vitals: a listed potion whose stack ran out is drunk from the next stack of that name", ListedPotionNextStack); r.Add("vitals: after a kit, nothing else heals until the kit's result line lands", KitResultWait); r.Add("vitals: Heal Self known only above the tier Life Magic allows (vitae) is still cast", HealAboveAllowedTier); r.Add("vitals: low health wins the arbiter even on a busy tick; backs off when nothing can heal", HealthWinsArbiter); @@ -290,6 +291,36 @@ internal static class VitalsTests } } + // Report 2026-10-10: 200+ Stamina Tinctures, and RynthAi stopped drinking them whenever the stack + // the rule was added from ran out, until the player added the next stack by hand. + private static void ListedPotionNextStack() + { + const uint Listed = 0x80001234, NextStack = 0x80005678; + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + FakeHost.Names[NextStack] = "Stamina Tincture"; // the listed stack (Listed) is gone + var host = FakeHost.Create(); + var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 0, TopOffMana = 0, RestamAt = 30, TopOffStam = 95, UsePotions = true, EnableBuffing = false }; + s.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Listed), Name = "Stamina Tincture", Type = "Stamina" }); + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 20, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, vitals); + b.SetCharacterSkills(skills); + b.SetWorldObjectCache(FakeHost.MakeCache(host, Player, new[] { NextStack })); + Check.True(b.CheckVitals(), "stamina 20% acts"); + Check.True(FakeHost.Uses.Contains(NextStack), "the next stack of Stamina Tinctures is drunk"); + Check.False(FakeHost.Uses.Contains(Listed), "not the stack that ran out"); + Check.Eq(FakeHost.Casts.Count, 0, "no Revitalize while a tincture is carried"); + } + // Tom, 2026-10-06: one Revitalize often doesn't recover enough stamina. private static void RestamTo() { diff --git a/Tools/RynthILT.Tests/BountyReviewTests.cs b/Tools/RynthILT.Tests/BountyReviewTests.cs new file mode 100644 index 0000000..2b434c8 --- /dev/null +++ b/Tools/RynthILT.Tests/BountyReviewTests.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthILT.Bounty; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The RynthILT review of SilentKelpie's tracker (2026-10-09). Two promises, checked here on a +// fake clock: +// * rate: at most one "/bounty list" per MinRefreshSeconds (5 s floor, whatever asks: kills, +// award lines every kill, Refresh spam, opening and closing the window), and none while the +// window is closed; +// * hidden chat: only the reply to the tracker's own read is eaten. A /bounty the player types +// is shown, also when it overlaps a read of ours, and our own command coming back through the +// engine's chat bar dispatcher is not mistaken for the player's. +internal static class BountyReviewTests +{ + public static void Register(Runner r) + { + r.Add("review: awards on every kill never read more than once per MinRefreshSeconds", AwardsEveryKill); + r.Add("review: Refresh spam and window open/close keep the 5 s floor", RefreshSpamAndToggling); + r.Add("review: a long mixed session: every read 5 s apart and only while the window is open", MixedSession); + r.Add("review: a /bounty list the player types is shown and stands in for the next read", TypedListShown); + r.Add("review: a /bounty the player types during our read: the rest of that read is shown", TypedDuringCapture); + r.Add("review: our own /bounty list coming back through the chat bar is not the player's", OwnEcho); + r.Add("review: command matching and long lines", Matching); + } + + private const string Header = "Bounties:"; + private const string Line = " Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills."; + private const string Footer = "Bounty: type /bounty to see the bounties where you stand."; + + private sealed class Rig + { + public long Ms = 1_000_000; + public readonly List SentAt = new(); + public readonly List SentWhileOpen = new(); + public BountyTracker T = null!; + public bool Open; + private long _lastPollMs; + + public void Step(long ms) + { + for (long e = 0; e < ms; e += 250) + { + Ms += 250; + if (Open && Ms - _lastPollMs >= 1000) { T.BuildJson(); _lastPollMs = Ms; } + T.Tick(); + } + } + + /// The server answers our read at once (header, a line, footer). + public void Reply() + { + T.OnChat(Header); + T.OnChat(Line); + T.OnChat(Footer); + } + } + + private static Rig New(int minRefreshSeconds = 5) + { + var rig = new Rig(); + rig.T = new BountyTracker(cmd => + { + if (cmd != BountyTracker.ListCommand) return; + rig.SentAt.Add(rig.Ms); + rig.SentWhileOpen.Add(rig.T.WindowOpen); + }, _ => { }, _ => { }, string.Empty, () => rig.Ms); + rig.T.Command($"set minrefreshseconds {minRefreshSeconds}"); + return rig; + } + + private static long MinGap(List at) + { + long min = long.MaxValue; + for (int i = 1; i < at.Count; i++) min = Math.Min(min, at[i] - at[i - 1]); + return min; + } + + private static void AwardsEveryKill() + { + var rig = New(minRefreshSeconds: 10); + rig.Open = true; + // A 1-kill bounty with no cooldown: every kill prints an award, for two minutes. + for (int s = 0; s < 120; s++) + { + rig.T.OnKill(); + rig.T.OnChat("Bounty complete! +1 Ascension Coin gained."); + rig.T.OnChat("Next bounty requires 1 kill."); + rig.Step(1000); + if (rig.T.Reading) rig.Reply(); + } + Check.True(rig.SentAt.Count >= 2, $"it still reads ({rig.SentAt.Count} reads)"); + Check.True(rig.SentAt.Count <= 13, $"at most one read per 10 s over 120 s ({rig.SentAt.Count} reads)"); + Check.True(MinGap(rig.SentAt) >= 10_000, $"reads at least MinRefreshSeconds apart (min gap {MinGap(rig.SentAt)} ms)"); + } + + private static void RefreshSpamAndToggling() + { + var rig = New(minRefreshSeconds: 30); + rig.Open = true; + rig.Step(500); + rig.Reply(); + Check.Eq(rig.SentAt.Count, 1, "opening reads once"); + + // Refresh clicked every half second for 20 s: manual reads keep the 5 s floor. + for (int i = 0; i < 40; i++) + { + rig.T.Command("refresh"); + rig.Step(500); + if (rig.T.Reading) rig.Reply(); + } + Check.True(rig.SentAt.Count <= 5, $"20 s of Refresh spam: at most 4 more reads ({rig.SentAt.Count} in all)"); + Check.True(MinGap(rig.SentAt) >= 5_000, $"manual reads at least 5 s apart (min gap {MinGap(rig.SentAt)} ms)"); + + // Kills while closed, then the window toggled open and shut every 4 s for a minute. + int before = rig.SentAt.Count; + for (int i = 0; i < 15; i++) + { + rig.Open = false; + rig.T.OnKill(); + rig.Step(4000); + rig.Open = true; + rig.Step(1000); + if (rig.T.Reading) rig.Reply(); + } + Check.True(rig.SentAt.Count - before <= 3, $"open/close every 5 s for 75 s with MinRefreshSeconds 30: at most 3 reads ({rig.SentAt.Count - before})"); + Check.True(MinGap(rig.SentAt) >= 5_000, "and never two within 5 s"); + Check.True(rig.SentWhileOpen.All(o => o), "every read went out with the window open"); + } + + private static void MixedSession() + { + var rig = New(minRefreshSeconds: 5); + var rnd = new Random(20261009); + for (int s = 0; s < 1800; s++) // 30 minutes + { + if (s % 120 == 0) rig.Open = !rig.Open; + int roll = rnd.Next(100); + if (roll < 30) rig.T.OnKill(); + else if (roll < 35) rig.T.OnChat("Bounty complete! +1 Ascension Coin gained."); + else if (roll < 37) rig.T.Command("refresh"); + else if (roll < 38) rig.T.OnChat("Bounty unlocked: Ascension Coin - 1 kill required."); + rig.Step(1000); + if (rig.T.Reading && rnd.Next(4) != 0) rig.Reply(); // now and then the server says nothing + } + Check.True(rig.SentAt.Count > 10, $"reads happened ({rig.SentAt.Count})"); + Check.True(MinGap(rig.SentAt) >= 5_000, $"every read at least 5 s after the last (min gap {MinGap(rig.SentAt)} ms)"); + Check.True(rig.SentWhileOpen.All(o => o), "every read went out with the window open"); + } + + private static void TypedListShown() + { + var rig = New(minRefreshSeconds: 5); + rig.Open = true; + rig.Step(500); + rig.Reply(); + Check.Eq(rig.SentAt.Count, 1, "first read"); + rig.Step(10_000); + + // The player types /bounty list: the reply is shown (nothing eaten) and still applied. + rig.T.NoteTypedCommand("/bounty list"); + Check.True(rig.T.Reading, "the typed list is captured (shown)"); + Check.False(rig.T.OnChat(Header), "typed reply: the header stays in chat"); + Check.False(rig.T.OnChat(" Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills."), "typed reply: the lines stay in chat"); + Check.False(rig.T.OnChat(Footer), "typed reply: the footer stays in chat"); + Check.False(rig.T.Reading, "and the footer ends it"); + Check.Eq(rig.T.State.Entries.Count, 1, "the typed reply fills the list"); + + // It counts as the latest read: a kill right after waits the full interval. + rig.T.OnKill(); + rig.Step(4000); + Check.Eq(rig.SentAt.Count, 1, "no read of ours on top of the player's"); + rig.Step(2000); + Check.Eq(rig.SentAt.Count, 2, "the kill's read comes MinRefreshSeconds after the typed one"); + Check.True(rig.T.OnChat(Header) && rig.T.OnChat(Line) && rig.T.OnChat(Footer), "our own read is eaten again"); + + // "/bounty" (where you stand) output is never eaten. + rig.T.NoteTypedCommand("/bounty"); + Check.False(rig.T.OnChat("Bounty: 1 Ascension Coin - 0 of 1 kills."), "a /bounty line stays in chat"); + Check.False(rig.T.OnChat("Bounty: there is no bounty here."), "'no bounty here' stays in chat"); + } + + private static void TypedDuringCapture() + { + var rig = New(minRefreshSeconds: 5); + rig.Open = true; + rig.Step(500); + Check.Eq(rig.SentAt.Count, 1, "our read went out"); + rig.T.NoteTypedCommand(BountyTracker.ListCommand); // our own echo first (consumed) + Check.True(rig.T.OnChat(Header), "our reply's header is eaten"); + + // The player types /bounty list while our reply is still coming in. + rig.Step(250); + rig.T.NoteTypedCommand("/bounty list"); + Check.False(rig.T.OnChat(Line), "after the player asked, reward lines are shown"); + Check.False(rig.T.OnChat(Footer), "and so is the footer"); + Check.False(rig.T.OnChat(Header), "the player's own reply: header shown"); + Check.False(rig.T.OnChat(Line), "the player's own reply: line shown"); + Check.False(rig.T.OnChat(Footer), "the player's own reply: footer shown"); + Check.False(rig.T.OnChat("Bounty complete! +1 Ascension Coin gained."), "award lines are never eaten"); + + // On a server without /bounty, the player's typed /bounty during our read: the refusal shows. + var rig2 = New(); + rig2.Open = true; + rig2.Step(500); + rig2.T.NoteTypedCommand("/bounty"); + Check.False(rig2.T.OnChat("Unknown command: bounty"), "the refusal of the player's own /bounty stays in chat"); + } + + private static void OwnEcho() + { + var rig = New(minRefreshSeconds: 5); + rig.Open = true; + rig.Step(500); + Check.Eq(rig.SentAt.Count, 1, "our read went out"); + rig.Step(250); + rig.T.NoteTypedCommand("/bounty list"); // the engine's dispatcher passing our own line back + Check.True(rig.T.OnChat(Header), "our echo is recognised: the reply is still eaten"); + Check.True(rig.T.OnChat(Line), "reward lines eaten"); + Check.True(rig.T.OnChat(Footer), "footer eaten"); + + // An echo that comes too late is taken for the player's: that read is shown, never eaten wrongly. + rig.Step(10_000); + Check.Eq(rig.SentAt.Count, 1, "no new read yet (nothing asked)"); + rig.T.Command("refresh"); + rig.Step(500); + Check.Eq(rig.SentAt.Count, 2, "refresh reads"); + rig.Step(3000); + rig.T.NoteTypedCommand("/bounty list"); + Check.False(rig.T.OnChat(Header), "a late echo errs on the shown side"); + } + + private static void Matching() + { + Check.True(BountyTracker.IsBountyCommand("/bounty"), "/bounty"); + Check.True(BountyTracker.IsBountyCommand("/bounty list"), "/bounty list"); + Check.True(BountyTracker.IsBountyCommand("@Bounty all"), "@bounty all"); + Check.False(BountyTracker.IsBountyCommand("/bountyhunter"), "a longer command is not /bounty"); + Check.False(BountyTracker.IsBountyCommand("/b hello"), "chat"); + Check.True(BountyTracker.IsListCommand("/bounty list") && BountyTracker.IsListCommand("/BOUNTY ALL"), "list commands"); + Check.False(BountyTracker.IsListCommand("/bounty") || BountyTracker.IsListCommand("/bounty list now"), "not list commands"); + + var rig = New(); + rig.Open = true; + rig.Step(500); + string longLine = " Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills." + new string(' ', 600) + "x"; + Check.False(rig.T.OnChat(longLine), "a line over 512 characters is never eaten or parsed"); + } +} diff --git a/Tools/RynthILT.Tests/BountyTests.cs b/Tools/RynthILT.Tests/BountyTests.cs new file mode 100644 index 0000000..1c00dc9 --- /dev/null +++ b/Tools/RynthILT.Tests/BountyTests.cs @@ -0,0 +1,388 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using RynthCore.Plugin.RynthILT.Bounty; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// ACECustom bounty tracker (2026-10-09). The server keeps the kill counts (BountyProgress is a +// server-only property), so the engine's Bounties window has RynthILT read "/bounty list" quietly +// and parse it. The line formats below are copied from ACECustom BountyManager (ShowAllBounties / +// ShowBounty / Award / NextBountyLine). The tracker runs on a fake clock; the engine's 1 s poll +// of RynthPluginGetBountiesJson is simulated by calling BuildJson. +internal static class BountyTests +{ + public static void Register(Runner r) + { + r.Add("bounty: /bounty list lines (counting, cooldown, QB, layers, commas)", ListLines); + r.Add("bounty: /bounty lines, waits and chat events", HereLinesAndEvents); + r.Add("bounty: a full read replaces the list, a partial one updates it", ApplyListRules); + r.Add("bounty: kills and awards stamp the row; an ended cooldown shows 0 kills; state survives a relog", ChangesAndCooldown); + r.Add("bounty: /bounty updates only the one reward it can mean", HereMatching); + r.Add("bounty: an open window reads the list quietly, kills and awards re-read it", WindowReadsAndKills); + r.Add("bounty: closed window sends nothing; unknown command stops reads; no reply times out", ClosedAndUnsupported); + r.Add("bounty: the window's JSON (options, QB filter, closest first) parses in the engine", BridgeJson); + } + + // ── Parsing ──────────────────────────────────────────────────────────────── + + private static void ListLines() + { + Check.True(BountyParse.TryParseListLine(" Lugian Mines: 1 Ascension Coin every 100 kills (at most every 5 min) - you: 34 of 100 kills.", out var a), + "counting line parses (leading indentation)"); + Check.Eq(a.Where, "Lugian Mines", "area"); + Check.Eq(a.Amount, 1L, "amount"); + Check.Eq(a.Item, "Ascension Coin", "item"); + Check.Eq(a.KillsRequired, 100, "kills per award"); + Check.Eq(a.CooldownSeconds, 300, "cooldown"); + Check.Eq(a.Status.Status, BountyStatus.Counting, "status"); + Check.Eq(a.Status.Kills, 34, "kills so far"); + + Check.True(BountyParse.TryParseListLine("All zones: 3 Pyreal Nugget every 1,000 kills (at most every 2 min 30 sec) - you: unlocks in 1 hr 15 sec, then 1,000 kills required.", out var b), + "cooldown line parses"); + Check.Eq(b.Where, "All zones", "all-zones area"); + Check.Eq(b.KillsRequired, 1000, "N0 kills"); + Check.Eq(b.CooldownSeconds, 150, "2 min 30 sec"); + Check.Eq(b.Status.Status, BountyStatus.Cooldown, "cooldown status"); + Check.Eq(b.Status.WaitSeconds, 3615, "1 hr 15 sec"); + Check.Eq(b.Status.KillsRequired, 1000, "kills after the cooldown"); + + Check.True(BountyParse.TryParseListLine("Valley of Death: 1,500 Trade Note - Large every 1 kill - you: needs 5,000 QB (you have 3,210).", out var c), + "QB line with no cooldown and a hyphenated item parses"); + Check.Eq(c.Amount, 1500L, "N0 amount"); + Check.Eq(c.Item, "Trade Note - Large", "item keeps its own ' - '"); + Check.Eq(c.KillsRequired, 1, "one kill"); + Check.Eq(c.CooldownSeconds, 0, "no cooldown"); + Check.Eq(c.Status.Status, BountyStatus.NeedsQb, "QB status"); + Check.Eq(c.Status.QbRequired, 5000L, "QB needed"); + Check.Eq(c.Status.QbHave, 3210L, "QB had"); + + Check.True(BountyParse.TryParseListLine("Halls of Metos: Lower (layer 2): 2 Ascension Coin every 50 kills - you: 0 of 50 kills.", out var d), + "an area with ': ' and a layer parses"); + Check.Eq(d.Where, "Halls of Metos: Lower (layer 2)", "area keeps its colon and layer"); + + Check.False(BountyParse.TryParseListLine("Bounties:", out _), "the header is not a reward"); + Check.False(BountyParse.TryParseListLine("Bounty: type /bounty to see the bounties where you stand.", out _), "the footer is not a reward"); + Check.False(BountyParse.TryParseListLine("Bob says, \"Lugian Mines: 1 coin every 100 kills\"", out _), "chat talk is not a reward"); + Check.True(BountyParse.IsListTerminator("Bounty: type /bounty to see the bounties where you stand."), "footer ends the reply"); + Check.True(BountyParse.IsListTerminator("Bounty: there are no bounties anywhere right now."), "'none anywhere' ends the reply"); + Check.True(BountyParse.IsNoBountiesAnywhere("Bounty: there are no bounties anywhere right now."), "'none anywhere' is recognised"); + Check.False(BountyParse.IsListTerminator("Bounty: there is no bounty here."), "/bounty's 'none here' is not the list's end"); + Check.True(BountyParse.IsUnknownCommand("Unknown command: bounty"), "ACE's unknown-command reply is recognised"); + Check.False(BountyParse.IsUnknownCommand("Unknown command: bank"), "another command's reply is not ours"); + } + + private static void HereLinesAndEvents() + { + Check.True(BountyParse.TryParseHereLine("Bounty: 1 Ascension Coin - 12 of 100 kills.", out var h1), "plain /bounty line"); + Check.Eq(h1.Scope, "", "no scope"); + Check.Eq(h1.Status.Kills, 12, "kills"); + Check.True(BountyParse.TryParseHereLine("Bounty (all zones): 3 Pyreal Nugget - unlocks in 45 sec, then 1 kill required.", out var h2), "all-zones /bounty line"); + Check.Eq(h2.Scope, "all zones", "all-zones scope"); + Check.Eq(h2.Status.WaitSeconds, 45, "45 sec"); + Check.True(BountyParse.TryParseHereLine("Bounty (Thaelaryn Island): 1 Ascension Coin - needs 500 QB (you have 20).", out var h3), "region /bounty line"); + Check.Eq(h3.Scope, "Thaelaryn Island", "region scope"); + Check.False(BountyParse.TryParseHereLine("Bounty: there is no bounty here.", out _), "'none here' is not a reward"); + Check.False(BountyParse.TryParseHereLine("Bounty: +1 Ascension Coin will follow in a moment.", out _), "held notice is not a reward"); + + Check.Eq(BountyParse.ParseWaitSeconds("5 min"), 300, "5 min"); + Check.Eq(BountyParse.ParseWaitSeconds("2 hr 3 min 4 sec"), 7384, "hr min sec"); + Check.Eq(BountyParse.ParseWaitSeconds("soon"), 0, "unparseable wait"); + + Check.True(BountyParse.TryParseEvent("Bounty unlocked: Ascension Coin - 100 kills required.", out var k1, out string item1, out int n1, out _) + && k1 == BountyEventKind.Unlocked && item1 == "Ascension Coin" && n1 == 100, "unlock event"); + Check.True(BountyParse.TryParseEvent("Bounty complete! +3 Pyreal Nuggets gained.", out var k2, out string item2, out _, out _) + && k2 == BountyEventKind.Complete && item2 == "Pyreal Nuggets", "award event"); + Check.True(BountyParse.TryParseEvent("Next bounty unlocks in 2 min 30 sec - 1 kill required.", out var k3, out _, out int n3, out int w3) + && k3 == BountyEventKind.NextCooldown && n3 == 1 && w3 == 150, "next-cooldown event"); + Check.True(BountyParse.TryParseEvent("Next bounty requires 1,000 kills.", out var k4, out _, out int n4, out _) + && k4 == BountyEventKind.NextReady && n4 == 1000, "next-ready event"); + Check.True(BountyParse.TryParseEvent("Bounty: Your inventory is full. +1 Ascension Coin gained (3 total). They're safe until you make room.", out var k5, out _, out _, out _) + && k5 == BountyEventKind.Held, "held event"); + Check.False(BountyParse.TryParseEvent("Bounty: there is no bounty here.", out _, out _, out _, out _), "'none here' is not an event"); + Check.False(BountyParse.TryParseEvent("Bounty: 1 Ascension Coin - 12 of 100 kills.", out _, out _, out _, out _), "a status line is not an event"); + Check.False(BountyParse.TryParseEvent("Bounty: type /bounty to see the bounties where you stand.", out _, out _, out _, out _), "the footer is not an event"); + } + + // ── Applying reads ───────────────────────────────────────────────────────── + + private static BountyListLine L(string line) + { + Check.True(BountyParse.TryParseListLine(line, out var l), "fixture parses: " + line); + return l; + } + + private static void ApplyListRules() + { + var t = New(out _, out _, out _); + var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc); + t.ApplyList(new[] + { + L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."), + L("All zones: 3 Pyreal Nugget every 50 kills - you: 0 of 50 kills."), + }, complete: true, noneAnywhere: false, t0); + Check.Eq(t.State.Entries.Count, 2, "full read: two rewards"); + Check.Eq(t.State.ListedUtc, t0, "read time stamped"); + + // A partial reply (no footer) only updates what it names; the other rows stay. + t.ApplyList(new[] { L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 11 of 100 kills.") }, + complete: false, noneAnywhere: false, t0.AddSeconds(5)); + Check.Eq(t.State.Entries.Count, 2, "partial read keeps the other row"); + Check.Eq(t.State.Entries[0].Kills, 11, "partial read updates the named row in place"); + + // A full read drops areas that are gone and keeps the server's order. + t.ApplyList(new[] + { + L("Thaelaryn Island: 1 Ascension Coin every 20 kills - you: 4 of 20 kills."), + L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 12 of 100 kills."), + }, complete: true, noneAnywhere: false, t0.AddSeconds(10)); + Check.Eq(string.Join(",", t.State.Entries.Select(e => e.Where)), "Thaelaryn Island,Lugian Mines", "server order, removed area gone"); + + t.ApplyList(Array.Empty(), complete: true, noneAnywhere: true, t0.AddSeconds(20)); + Check.Eq(t.State.Entries.Count, 0, "'none anywhere' empties the list"); + Check.True(t.State.NoneAnywhere, "and says so"); + } + + private static void ChangesAndCooldown() + { + string file = Path.Combine(Program.TempRoot, "bounty-changes", BountyTracker.FileName); + var t = New(out _, out _, out _, file); + var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc); + const string Head = "Lugian Mines: 1 Ascension Coin every 3 kills (at most every 5 min) - you: "; + t.ApplyList(new[] { L(Head + "1 of 3 kills.") }, true, false, t0); + Check.Eq(t.State.Entries[0].ChangedUtc, default(DateTime), "first sighting is not a change"); + + t.ApplyList(new[] { L(Head + "2 of 3 kills.") }, true, false, t0.AddSeconds(10)); + Check.Eq(t.State.Entries[0].ChangedUtc, t0.AddSeconds(10), "a new kill stamps the row"); + + t.ApplyList(new[] { L(Head + "unlocks in 5 min, then 3 kills required.") }, true, false, t0.AddSeconds(20)); + var e = t.State.Entries[0]; + Check.Eq(e.ChangedUtc, t0.AddSeconds(20), "the award stamps the row"); + Check.Eq(e.UnlockAtUtc, t0.AddSeconds(320), "unlock time = read time + wait"); + Check.Eq(BountyTracker.Effective(e, t0.AddSeconds(100)).Status, BountyStatus.Cooldown, "still cooling down"); + var after = BountyTracker.Effective(e, t0.AddSeconds(321)); + Check.True(after.Status == BountyStatus.Counting && after.Kills == 0, "after the cooldown: 0 of N kills"); + Check.True(BountyTracker.Describe(e, t0.AddSeconds(100)).Contains("unlocks in 3 min 40 sec"), "chat text counts the cooldown down"); + + // The state survives a relog (the window fills right after login). + t.Command("set hideqblocked 1"); + t.Save(); + var loaded = New(out _, out _, out _, file); + Check.Eq(loaded.State.Entries.Count, 1, "entries saved per character"); + Check.Eq(loaded.State.Entries[0].UnlockAtUtc, t0.AddSeconds(320), "unlock time saved"); + Check.True(loaded.State.HideQbLocked, "options saved"); + } + + private static void HereMatching() + { + var t = New(out _, out _, out _); + var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc); + t.ApplyList(new[] + { + L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."), + L("Halls of Metos: 1 Ascension Coin every 100 kills - you: 50 of 100 kills."), + L("Thaelaryn Island: 2 Ascension Coin every 20 kills - you: 4 of 20 kills."), + L("All zones: 1 Ascension Coin every 100 kills - you: 0 of 100 kills."), + }, true, false, t0); + + Check.True(BountyParse.TryParseHereLine("Bounty (Thaelaryn Island): 2 Ascension Coin - 5 of 20 kills.", out var region), "fixture"); + Check.True(t.ApplyHere(region, t0.AddSeconds(5)), "a region line names its area"); + Check.Eq(t.State.Entries[2].Kills, 5, "region row updated"); + + Check.True(BountyParse.TryParseHereLine("Bounty (all zones): 1 Ascension Coin - 1 of 100 kills.", out var zones), "fixture"); + Check.True(t.ApplyHere(zones, t0.AddSeconds(6)), "an all-zones line names its area"); + Check.Eq(t.State.Entries[3].Kills, 1, "all-zones row updated"); + + Check.True(BountyParse.TryParseHereLine("Bounty: 1 Ascension Coin - 11 of 100 kills.", out var plain), "fixture"); + Check.False(t.ApplyHere(plain, t0.AddSeconds(7)), "two dungeons pay the same reward: left alone"); + Check.Eq(t.State.Entries[0].Kills, 10, "first dungeon untouched"); + Check.Eq(t.State.Entries[1].Kills, 50, "second dungeon untouched"); + } + + // ── The read loop ────────────────────────────────────────────────────────── + + private const string ListReplyCounting = " Lugian Mines: 1 Ascension Coin every 100 kills - you: 34 of 100 kills."; + private const string Footer = "Bounty: type /bounty to see the bounties where you stand."; + + private static void WindowReadsAndKills() + { + var t = New(out var clock, out var sent, out _); + t.Command("set minrefreshseconds 5"); + Run(t, clock, 500, windowOpen: true); + Check.Eq(Reads(sent), 1, "opening the window reads /bounty list"); + Check.True(t.Reading, "a read is in progress"); + + Check.True(t.OnChat("Bounties:"), "the header is hidden from chat"); + Check.True(t.OnChat(ListReplyCounting), "reward lines are hidden from chat"); + Check.True(t.OnChat(Footer), "the footer is hidden and ends the read"); + Check.False(t.Reading, "the read is over"); + Check.Eq(t.State.Entries.Count, 1, "the read fills the list"); + Check.Eq(t.State.Entries[0].Kills, 34, "with the player's kills"); + + // A kill re-reads after the debounce, but not sooner than MinRefreshSeconds after the last read. + t.OnKill(); + Run(t, clock, 3000, windowOpen: true); + Check.Eq(Reads(sent), 1, "no re-read inside MinRefreshSeconds"); + Run(t, clock, 3000, windowOpen: true); + Check.Eq(Reads(sent), 2, "a kill re-reads the list"); + t.OnChat("Bounties:"); + t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills - you: 35 of 100 kills."); + t.OnChat(Footer); + Check.Eq(t.State.Entries[0].Kills, 35, "the kill shows up"); + Check.True(t.State.Entries[0].ChangedUtc != default, "and the row is highlighted"); + + // Award lines are shown to the player and also trigger a read, once MinRefreshSeconds + // have passed since the last one (review 2026-10-09: awards used to skip the interval). + Check.False(t.OnChat("Bounty complete! +1 Ascension Coin gained."), "award lines stay in chat"); + Check.Eq(t.State.LastEvent, "Bounty complete! +1 Ascension Coin gained.", "the window shows the last event"); + Run(t, clock, 2000, windowOpen: true); + Check.Eq(Reads(sent), 2, "the award's re-read waits for MinRefreshSeconds"); + Run(t, clock, 3000, windowOpen: true); + Check.Eq(Reads(sent), 3, "an award re-reads the list"); + + // A reply whose footer never comes ends after a quiet moment, as a partial update. + t.OnChat("Bounties:"); + t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills (at most every 5 min) - you: unlocks in 5 min, then 100 kills required."); + Run(t, clock, 2000, windowOpen: true); + Check.False(t.Reading, "a reply without its footer still ends"); + Check.Eq(t.State.Entries[0].Status, (int)BountyStatus.Cooldown, "and is applied"); + + // Lines the player asks for themselves are not hidden but still update the list. + Check.False(t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills - you: 0 of 100 kills."), "a typed /bounty list line stays in chat"); + Check.Eq(t.State.Entries[0].Status, (int)BountyStatus.Counting, "and updates the row"); + + // Closing the window (the engine stops polling; 3 s grace) stops the reads. + Run(t, clock, 5000, windowOpen: false); + int before = Reads(sent); + t.OnKill(); + Run(t, clock, 20000, windowOpen: false); + Check.Eq(Reads(sent), before, "no reads once the window is closed"); + } + + private static void ClosedAndUnsupported() + { + var t = New(out var clock, out var sent, out var chat); + t.Command("set minrefreshseconds 5"); + t.OnKill(); + Run(t, clock, 10000, windowOpen: false); + Check.Eq(Reads(sent), 0, "closed window: kills send nothing"); + + Run(t, clock, 500, windowOpen: true); + Check.Eq(Reads(sent), 1, "opening the window reads the list"); + Check.True(t.OnChat("Unknown command: bounty"), "the unknown-command reply to our read is hidden"); + Check.True(t.Unsupported, "'Unknown command: bounty' marks the server unsupported"); + + t.OnKill(); + Run(t, clock, 10 * 60_000, windowOpen: true); + Check.Eq(Reads(sent), 1, "no automatic reads on an unsupported server, periodic included"); + + t.HandleChatCommand(new[] { "/ilt", "bountys", "refresh" }); + Check.False(t.Unsupported, "a manual refresh tries again"); + Run(t, clock, 500, windowOpen: true); + Check.Eq(Reads(sent), 2, "and reads the list"); + Check.True(chat.Any(c => c.Contains("Reading /bounty list")), "the command answers in chat"); + + Run(t, clock, 11000, windowOpen: true); + Check.False(t.Reading, "no reply: the read is abandoned"); + Check.True(t.BuildJson().Contains("no reply to /bounty list"), "and the window says so"); + + // With the window closed a manual refresh sends nothing (review 2026-10-09: reads only + // while the window is open); the next open reads. + Run(t, clock, 5000, windowOpen: false); + Check.True(t.Command("refresh").Contains("window is open"), "a closed-window refresh says why it waits"); + Check.Eq(Reads(sent), 2, "a closed-window refresh sends nothing"); + Run(t, clock, 500, windowOpen: true); + Check.Eq(Reads(sent), 3, "the next open reads"); + + chat.Clear(); + t.HandleChatCommand(new[] { "/ilt", "bounty" }); + Check.True(chat.Any(c => c.Contains("/rc bounties")), "'/ilt bounty' points at the window"); + } + + private static void BridgeJson() + { + var t = New(out _, out _, out _); + var now = DateTime.UtcNow; + t.ApplyList(new[] + { + L("Valley of Death: 1,500 Trade Note - Large every 1 kill - you: needs 5,000 QB (you have 3,210)."), + L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."), + L("Thaelaryn Island: 2 Ascension Coin every 20 kills (at most every 5 min) - you: unlocks in 2 min, then 20 kills required."), + L("Halls of Metos: 1 Ascension Coin every 10 kills - you: 9 of 10 kills."), + }, true, false, now); + + Check.Eq(t.Command("set minrefreshseconds 1"), "", "option accepted"); + Check.Eq(t.State.MinRefreshSeconds, BountyTracker.MinRefreshFloorSeconds, "MinRefreshSeconds is clamped to the floor"); + t.Command("set periodicminutes 999"); + Check.Eq(t.State.PeriodicRefreshMinutes, BountyTracker.PeriodicCeilingMinutes, "PeriodicRefreshMinutes is clamped"); + Check.True(t.Command("set nonsense 1").Contains("unknown"), "unknown option is reported"); + + using (var doc = JsonDocument.Parse(t.BuildJson())) + { + var root = doc.RootElement; + Check.Eq(root.GetProperty("rows").GetArrayLength(), 4, "all rows by default"); + Check.Eq(root.GetProperty("rows")[0].GetProperty("where").GetString(), "Valley of Death", "server order by default"); + Check.Eq(root.GetProperty("minRefreshSeconds").GetInt32(), 5, "camelCase option names"); + } + + t.Command("set hideqblocked 1"); + t.Command("set sortbyprogress on"); + string json = t.BuildJson(); + using (var doc = JsonDocument.Parse(json)) + { + var rows = doc.RootElement.GetProperty("rows"); + Check.Eq(rows.GetArrayLength(), 3, "QB-locked row hidden"); + Check.Eq(doc.RootElement.GetProperty("hiddenCount").GetInt32(), 1, "and counted"); + Check.Eq(rows[0].GetProperty("where").GetString(), "Halls of Metos", "closest first: 9 of 10"); + Check.Eq(rows[2].GetProperty("where").GetString(), "Thaelaryn Island", "cooldowns after counting rows"); + } + +#if ENGINE_BOUNTIES + var snap = RynthCore.Engine.UI.Data.BountiesSnapshot.Parse(json); + Check.NotNull(snap, "the engine parses the plugin's JSON"); + Check.True(snap!.HideQbLocked && snap.SortByProgress, "engine sees the options"); + Check.Eq(snap.MinRefreshSeconds, 5, "engine sees MinRefreshSeconds"); + Check.Eq(snap.HiddenCount, 1, "engine sees the hidden count"); + Check.Eq(snap.Rows.Count, 3, "engine sees the rows"); + var cd = snap.Rows.Single(r => r.Where == "Thaelaryn Island"); + Check.Eq(cd.Status, (int)RynthCore.Engine.UI.Data.BountyRowStatus.Cooldown, "engine status enum matches the plugin's"); + Check.True(cd.UnlockInSec > 100 && cd.UnlockInSec <= 120, $"cooldown seconds left ({cd.UnlockInSec})"); + Check.Eq(cd.CooldownSeconds, 300, "cooldown length"); + var halls = snap.Rows[0]; + Check.True(halls.Kills == 9 && halls.KillsRequired == 10 && halls.Amount == 1 && halls.Item == "Ascension Coin", "row fields"); +#endif + } + + // ── Helpers ──────────────────────────────────────────────────────────────── + + private sealed class Clock { public long Ms = 1_000_000; } + + private static BountyTracker New(out Clock clock, out List sent, out List chat, string file = "") + { + var c = new Clock(); + var s = new List(); + var ch = new List(); + if (file.Length > 0) Directory.CreateDirectory(Path.GetDirectoryName(file)!); + var t = new BountyTracker(s.Add, ch.Add, _ => { }, file, () => c.Ms); + clock = c; + sent = s; + chat = ch; + return t; + } + + private static int Reads(List sent) => sent.Count(x => x == BountyTracker.ListCommand); + + /// Advances the clock in 250 ms steps, ticking; with the window open the engine polls every second. + private static void Run(BountyTracker t, Clock clock, long ms, bool windowOpen) + { + for (long elapsed = 0; elapsed < ms; elapsed += 250) + { + clock.Ms += 250; + if (windowOpen && elapsed % 1000 == 0) t.BuildJson(); + t.Tick(); + } + } +} diff --git a/Tools/RynthILT.Tests/Program.cs b/Tools/RynthILT.Tests/Program.cs new file mode 100644 index 0000000..c7ec3bf --- /dev/null +++ b/Tools/RynthILT.Tests/Program.cs @@ -0,0 +1,28 @@ +using System; +using System.IO; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// Offline tests for the RynthILT plugin: the ACECustom bounty tracker (parsing, merging, the +// quiet /bounty list read loop on a fake clock, persistence, the bridge JSON). Each test prints +// PASS / FAIL. +// +// Run: dotnet run -c Release (all tests) +// dotnet run -c Release -- window (tests whose name contains "window") +internal static class Program +{ + /// Scratch folder next to the exe for files tests write. Emptied at start. + public static string TempRoot { get; } = Path.Combine(AppContext.BaseDirectory, "scratch"); + + private static int Main(string[] args) + { + if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true); + Directory.CreateDirectory(TempRoot); + + var runner = new Runner(); + BountyTests.Register(runner); + BountyReviewTests.Register(runner); + return runner.Run("RynthILT tests", args.Length > 0 ? args[0] : null); + } +} diff --git a/Tools/RynthILT.Tests/RynthILT.Tests.csproj b/Tools/RynthILT.Tests/RynthILT.Tests.csproj new file mode 100644 index 0000000..2263da6 --- /dev/null +++ b/Tools/RynthILT.Tests/RynthILT.Tests.csproj @@ -0,0 +1,38 @@ + + + + + Exe + net10.0 + enable + true + RynthILT.Tests + + + + + + + + + + + + + + $(DefineConstants);ENGINE_BOUNTIES + + + + + + diff --git a/Tools/RynthSort.Tests/Program.cs b/Tools/RynthSort.Tests/Program.cs new file mode 100644 index 0000000..8a0246a --- /dev/null +++ b/Tools/RynthSort.Tests/Program.cs @@ -0,0 +1,996 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using RynthCore.Engine.UI.ScriptWindows; +using RynthCore.Plugin.RynthSort; +using RynthCore.Plugin.RynthSort.Sorting; +using RynthCore.Plugin.RynthSort.Ui; +using RynthCore.Plugin.RynthSort.Views; +using RynthCore.Plugin.Shared; + +// The engine parser's only outside dependency: the registry's limits (the engine's values). +namespace RynthCore.Engine.UI.ScriptWindows +{ + internal static class ScriptWindowRegistry + { + public const int MaxOpsPerWindow = 1500; + public const int MaxBytesPerWindow = 64 * 1024; + public const int MaxWindowsPerOwner = 32; + public const int MaxBytesPerSubmit = 256 * 1024; + } +} + +namespace RynthSort.Tests +{ + internal static partial class Program + { + private static int _pass, _fail; + private static string _temp = ""; + + [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "Write")] + private static extern int Write(UiHost h); + + [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_submit")] + private static extern ref byte[] SubmitBuffer(UiHost h); + + [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "Apply")] + private static extern void Apply(UiHost h, ReadOnlySpan data); + + private static int Main() + { + _temp = Path.Combine(Path.GetTempPath(), "RynthSort.Tests." + Environment.ProcessId); + Directory.CreateDirectory(_temp); + try + { + Run("rules: class and name matching, first match wins", RuleMatching); + Run("classify: item classes as RynthLua sees them", Classify); + Run("plan: settle time, force", PlanSettle); + Run("plan: pack choice (full pack, stacks, capacity)", PlanPackChoice); + Run("plan: worn, packs, foci and blocked items never move", PlanNeverMoves); + Run("plan: missing pack", PlanMissingPack); + Run("plan: tidy and clean", PlanTidyClean); + Run("plan: unpack", PlanUnpack); + Run("gate: stay out of the way", Gates); + Run("gate: RynthAi activity", GatesRynthAi); + Run("gate: quiet time after a pause", GateQuiet); + Run("gate: looting watch", LootWatching); + Run("gate: older RynthAi status JSON", StatusJsonFallback); + Run("moves: answers and back-off", MoveAnswers); + Run("loop: nothing is sent while paused", LoopPaused); + Run("loop: one move at a time, then the gap", LoopOneAtATime); + Run("loop: refusals block the item and back off", LoopRefusals); + Run("loop: too busy and no answer", LoopBusyAndTimeout); + Run("loop: jobs (sort now, tidy, clean, unpack)", LoopJobs); + Run("store: save and load", StoreRoundTrip); + Run("store: Lua script import", StoreLuaImport); + Run("store: odd files", StoreOddFiles); + Run("lua autostart warning", LuaAutostart); + Run("window: display lists parse in the engine", WindowParses); + Run("window: rule editing through events", WindowEvents); + } + finally + { + try { Directory.Delete(_temp, true); } catch { } + } + Console.WriteLine($"{_pass} passed, {_fail} failed"); + if (_pass == 0) { Console.WriteLine("ABORT: zero assertions ran."); return 1; } + return _fail == 0 ? 0 : 1; + } + + private static void Run(string name, Action test) + { + int before = _fail; + try { test(); } + catch (Exception ex) { _fail++; Console.WriteLine($"FAIL: {name} threw {ex}"); } + Console.WriteLine($" {(before == _fail ? "ok " : "FAIL")} {name}"); + } + + private static void Check(bool ok, string what) + { + if (ok) _pass++; + else { _fail++; Console.WriteLine("FAIL: " + what); } + } + + private static void Eq(T actual, T expected, string what) => + Check(EqualityComparer.Default.Equals(actual, expected), $"{what}: expected {expected}, got {actual}"); + + // ── Sample data ───────────────────────────────────────────────────── + + private const uint Me = 0x50000001; + + private static SortInventory Inv(int packs, int cap = 24, int mainCap = 102) + { + var inv = new SortInventory(); + inv.Main.Id = Me; + inv.Main.Name = "Main pack"; + inv.Main.Capacity = mainCap; + for (int i = 1; i <= packs; i++) + inv.Packs.Add(new SortPack { Id = 0x40000000u + (uint)i, Name = "Pack " + i, Capacity = cap }); + return inv; + } + + private static SortItem It(uint id, string name, int cls, uint wcid = 0, int stack = 1, int max = 1) => + new() { Id = id, Name = name, ObjectClass = cls, Wcid = wcid, Stack = stack, MaxStack = max }; + + private static void Fill(SortPack p, int count, uint firstId) + { + for (int i = 0; i < count; i++) p.Items.Add(It(firstId + (uint)i, "Junk " + i, ObjectClasses.Misc)); + } + + private static readonly List Defaults = SortRules.Defaults(); + + // ── Rules ─────────────────────────────────────────────────────────── + + private static void RuleMatching() + { + SortItem comp = It(1, "Prismatic Taper", ObjectClasses.SpellComponent); + SortItem salvage = It(2, "Salvaged Iron (100)", ObjectClasses.Salvage); + SortItem gem = It(3, "Black Opal", ObjectClasses.Gem); + SortItem misc = It(4, "Ashcoal", ObjectClasses.Misc); + + Check(SortRules.Matches(SortRule.ForClass(ObjectClasses.SpellComponent, 1), comp), "class rule matches its class"); + Check(!SortRules.Matches(SortRule.ForClass(ObjectClasses.SpellComponent, 1), salvage), "class rule ignores other classes"); + Check(SortRules.Matches(SortRule.ForName("taper", 4), comp), "name rule: part of the name, any case"); + Check(!SortRules.Matches(SortRule.ForName("", 4), comp), "an empty name rule matches nothing"); + var off = SortRule.ForClass(ObjectClasses.Gem, 3); + off.On = false; + Check(!SortRules.Matches(off, gem), "a rule that is off matches nothing"); + + var rules = new List { SortRule.ForName("taper", 5), SortRule.ForClass(ObjectClasses.SpellComponent, 1) }; + Eq(SortRules.RuleFor(rules, comp)?.Pack, 5, "first match wins (name rule above the class rule)"); + (rules[0], rules[1]) = (rules[1], rules[0]); + Eq(SortRules.RuleFor(rules, comp)?.Pack, 1, "reordered: the class rule wins"); + Check(SortRules.RuleFor(Defaults, misc) == null, "no rule wants misc"); + Eq(SortRules.RuleFor(Defaults, salvage)?.Pack, 2, "default: salvage to pack 2"); + Eq(SortRules.RuleFor(Defaults, gem)?.Pack, 3, "default: gems to pack 3"); + + Eq(ObjectClasses.Label(ObjectClasses.ManaStone), "Mana Stone", "class label"); + Eq(ObjectClasses.ChoiceLabels[ObjectClasses.ChoiceIndex(ObjectClasses.WandStaffOrb)], "Wand Staff Orb", "choice label"); + Eq(SortRules.Describe(SortRule.ForName("Pyreal", 2)), "name has \"Pyreal\"", "describe name rule"); + // The Lua script's numbers mean the same classes (saved rules stay right). + Eq(ObjectClasses.Names[12], "SpellComponent", "12 = SpellComponent"); + Eq(ObjectClasses.Names[39], "Salvage", "39 = Salvage"); + Eq(ObjectClasses.Names[29], "HealingKit", "29 = HealingKit"); + } + + private static void Classify() + { + Eq(InventoryReader.ClassifyFrom(0x40000000, 0, "Salvaged Iron", out bool c1), ObjectClasses.Salvage, "tinkering material = salvage"); + Check(c1, "certain with a type"); + Eq(InventoryReader.ClassifyFrom(0x00001000, 0, "Prismatic Taper", out _), ObjectClasses.SpellComponent, "spell component"); + Eq(InventoryReader.ClassifyFrom(0x00080000 | 0x00000080, 0, "Mana Stone", out _), ObjectClasses.ManaStone, "mana stone before misc"); + Eq(InventoryReader.ClassifyFrom(0x00000080, 0x10000, "Healing Kit", out _), ObjectClasses.HealingKit, "healer bit = healing kit"); + Eq(InventoryReader.ClassifyFrom(0x00000080, 0x20000, "Lockpick", out _), ObjectClasses.Lockpick, "lockpick bit"); + Eq(InventoryReader.ClassifyFrom(0x00002000, 0, "Scroll of Strength Self VII", out _), ObjectClasses.Scroll, "writable named Scroll = scroll"); + Eq(InventoryReader.ClassifyFrom(0x00000200, 0, "Foci of Enchantment", out _), ObjectClasses.Foci, "foci by name"); + Eq(InventoryReader.ClassifyFrom(0x00000080, 0x8000, "Apple", out _), ObjectClasses.Food, "misc with the food bit = food"); + Eq(InventoryReader.ClassifyFrom(0, 0, "", out bool c2), ObjectClasses.Unknown, "no data"); + Check(!c2, "not certain without data (read again later)"); + } + + // ── Planner ───────────────────────────────────────────────────────── + + private static void PlanSettle() + { + var p = new SortPlanner(); + SortInventory inv = Inv(3); + inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent)); + List m = p.Plan(inv, Defaults, SortScope.Main, false, 1000, 5000); + Eq(m.Count, 0, "a new item waits for the settle time"); + Eq(p.View.Waiting, 1, "it is counted as waiting"); + m = p.Plan(inv, Defaults, SortScope.Main, false, 5999, 5000); + Eq(m.Count, 0, "still settling just before"); + m = p.Plan(inv, Defaults, SortScope.Main, false, 6000, 5000); + Eq(m.Count, 1, "moves once settled"); + Eq(m[0].DestIndex, 1, "to pack 1"); + Eq(m[0].Dest.Id, inv.Packs[0].Id, "pack 1's id"); + + var q = new SortPlanner(); + m = q.Plan(inv, Defaults, SortScope.Main, true, 1000, 5000); + Eq(m.Count, 1, "Sort now (force) skips the settle time"); + + // An item that left the main pack and came back starts its settle time again. + var r = new SortPlanner(); + r.Plan(inv, Defaults, SortScope.Main, false, 0, 5000); + SortItem it = inv.Main.Items[0]; + inv.Main.Items.Clear(); + r.Plan(inv, Defaults, SortScope.Main, false, 3000, 5000); + inv.Main.Items.Add(it); + Eq(r.Plan(inv, Defaults, SortScope.Main, false, 6000, 5000).Count, 0, "re-seen item settles again"); + Eq(r.Plan(inv, Defaults, SortScope.Main, false, 11000, 5000).Count, 1, "then moves"); + + // Settle 0: moves at once. + Eq(new SortPlanner().Plan(inv, Defaults, SortScope.Main, false, 0, 0).Count, 1, "settle 0 moves at once"); + } + + private static void PlanPackChoice() + { + // A full pack refuses an item that can't stack there. + SortInventory inv = Inv(3); + Fill(inv.Packs[1], 24, 1000); + inv.Main.Items.Add(It(10, "Salvaged Iron", ObjectClasses.Salvage, wcid: 20981, stack: 1, max: 1)); + var p = new SortPlanner(); + List m = p.Plan(inv, Defaults, SortScope.Main, true, 0, 5000); + Eq(m.Count, 0, "full pack, no stack: refused"); + Check(p.View.Full.Contains(2), "pack 2 reported full"); + Eq(p.View.Waiting, 1, "waiting"); + + // A full pack takes a stackable item when a stack of the same kind has room there. + inv = Inv(3); + Fill(inv.Packs[0], 23, 1000); + inv.Packs[0].Items.Add(It(50, "Prismatic Taper", ObjectClasses.SpellComponent, wcid: 8897, stack: 40, max: 100)); + inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent, wcid: 8897, stack: 12, max: 100)); + p = new SortPlanner(); + m = p.Plan(inv, Defaults, SortScope.Main, true, 0, 5000); + Eq(m.Count, 1, "full pack, joins a stack: moves"); + Eq(m.Count > 0 ? m[0].MergeInto : 0u, 50u, "merges into the stack there"); + Check(p.View.Full.Count == 0, "not reported full"); + + // ... but not when that stack is itself full. + inv.Packs[0].Items[23].Stack = 100; + p = new SortPlanner(); + m = p.Plan(inv, Defaults, SortScope.Main, true, 0, 5000); + Eq(m.Count, 0, "full pack whose stack is full: refused"); + Check(p.View.Full.Contains(1), "pack 1 full"); + + // A different kind with the same name doesn't count when both have a class id (wcid). + inv.Packs[0].Items[23].Stack = 40; + inv.Packs[0].Items[23].Wcid = 9999; + Eq(new SortPlanner().Plan(inv, Defaults, SortScope.Main, true, 0, 5000).Count, 0, "same name, other wcid: no stack"); + // Without wcids the name decides (the Lua script's rule). + inv.Packs[0].Items[23].Wcid = 0; + inv.Main.Items[0].Wcid = 0; + Eq(new SortPlanner().Plan(inv, Defaults, SortScope.Main, true, 0, 5000).Count, 1, "no wcid: same name stacks"); + + // Room for one: two items, only the first goes; the second waits as "full". + inv = Inv(3); + Fill(inv.Packs[2], 23, 1000); + inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem)); + inv.Main.Items.Add(It(11, "Mana Stone", ObjectClasses.ManaStone)); + p = new SortPlanner(); + m = p.Plan(inv, Defaults, SortScope.Main, true, 0, 5000); + Eq(m.Count, 1, "one slot: one move planned"); + Check(p.View.Full.Contains(3), "then pack 3 counts as full"); + + // A non-full pack merges into a stack with room when there is one (keeps stacks tidy). + inv = Inv(1); + inv.Packs[0].Items.Add(It(50, "Prismatic Taper", ObjectClasses.SpellComponent, wcid: 8897, stack: 40, max: 100)); + inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent, wcid: 8897, stack: 12, max: 100)); + m = new SortPlanner().Plan(inv, Defaults, SortScope.Main, true, 0, 5000); + Eq(m.Count == 1 ? m[0].MergeInto : 0u, 50u, "merges into an existing stack"); + + // Capacity unknown (0): a side pack holds 24. + inv = Inv(1, cap: 0); + Fill(inv.Packs[0], 24, 1000); + inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent)); + Eq(new SortPlanner().Plan(inv, Defaults, SortScope.Main, true, 0, 5000).Count, 0, "unknown capacity = 24"); + } + + private static void PlanNeverMoves() + { + SortInventory inv = Inv(3); + var worn = It(10, "Prismatic Taper", ObjectClasses.SpellComponent); + worn.Wielded = true; + inv.Main.Items.Add(worn); + inv.Main.Items.Add(It(11, "Backpack", ObjectClasses.Container)); + inv.Main.Items.Add(It(12, "Foci of Enchantment", ObjectClasses.Foci)); + var rules = new List + { + SortRule.ForClass(ObjectClasses.SpellComponent, 1), + SortRule.ForClass(ObjectClasses.Container, 1), + SortRule.ForClass(ObjectClasses.Foci, 1), + }; + var p = new SortPlanner(); + Eq(p.Plan(inv, rules, SortScope.All, true, 0, 0).Count, 0, "worn item, pack and foci never move"); + + inv.Main.Items.Clear(); + inv.Main.Items.Add(It(20, "Prismatic Taper", ObjectClasses.SpellComponent)); + p.Block(20, 60_000); + Eq(p.Plan(inv, rules, SortScope.Main, true, 1000, 0).Count, 0, "a blocked item is left alone"); + Eq(p.BlockedCount(1000), 1, "counted as blocked"); + Eq(p.Plan(inv, rules, SortScope.Main, true, 60_000, 0).Count, 1, "after its minute it is tried again"); + } + + private static void PlanMissingPack() + { + SortInventory inv = Inv(2); + inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem)); + var p = new SortPlanner(); + Eq(p.Plan(inv, Defaults, SortScope.Main, true, 0, 0).Count, 0, "pack 3 doesn't exist: no move"); + Check(p.View.Missing.Contains(3), "pack 3 reported missing"); + Eq(p.View.Packs.Count, 2, "the view lists the two packs"); + } + + private static void PlanTidyClean() + { + SortInventory inv = Inv(3); + inv.Packs[0].Items.Add(It(10, "Salvaged Iron", ObjectClasses.Salvage)); // belongs in pack 2 + inv.Packs[1].Items.Add(It(11, "Salvaged Gold", ObjectClasses.Salvage)); // right where it is + inv.Packs[2].Items.Add(It(12, "Ashcoal", ObjectClasses.Misc)); // no rule wants it + var p = new SortPlanner(); + Eq(p.Plan(inv, Defaults, SortScope.Main, true, 0, 0).Count, 0, "Sort now leaves side packs alone"); + List m = p.Plan(inv, Defaults, SortScope.All, false, 0, 5000); + Eq(m.Count, 1, "Tidy: one misplaced item"); + Check(m.Count == 1 && m[0].Item.Id == 10 && m[0].DestIndex == 2, "Tidy moves it to pack 2 (no settle time)"); + + m = p.Plan(inv, Defaults, SortScope.Clean, false, 0, 5000); + Eq(m.Count, 2, "Clean: the misplaced one and the stray"); + Check(m.Any(x => x.Item.Id == 12 && x.DestIndex == 0 && x.Dest.Id == Me), "the stray goes to the main pack"); + + // Main pack full: the stray stays, and Clean says so. + inv = Inv(1, mainCap: 2); + Fill(inv.Main, 2, 2000); + inv.Packs[0].Items.Add(It(12, "Ashcoal", ObjectClasses.Misc)); + p = new SortPlanner(); + Eq(p.Plan(inv, Defaults, SortScope.Clean, false, 0, 0).Count, 0, "main pack full: stray stays"); + Check(p.View.MainFull, "main pack reported full"); + // ... unless it joins a stack in the main pack. + inv.Main.Items[0] = It(2000, "Pyreal", ObjectClasses.Money, wcid: 273, stack: 10, max: 25000); + inv.Packs[0].Items[0] = It(12, "Pyreal", ObjectClasses.Money, wcid: 273, stack: 5, max: 25000); + Eq(new SortPlanner().Plan(inv, Defaults, SortScope.Clean, false, 0, 0).Count, 1, "joins a main-pack stack"); + } + + private static void PlanUnpack() + { + SortInventory inv = Inv(3); + inv.Packs[0].Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent)); + inv.Packs[1].Items.Add(It(11, "Salvaged Iron", ObjectClasses.Salvage)); + inv.Packs[2].Items.Add(It(12, "Black Opal", ObjectClasses.Gem)); + var p = new SortPlanner(); + List m = p.PlanUnpack(inv, null, 0); + Eq(m.Count, 3, "unpack all: every side-pack item"); + Check(m.All(x => x.DestIndex == 0), "all to the main pack"); + m = p.PlanUnpack(inv, 2, 0); + Check(m.Count == 1 && m[0].Item.Id == 11, "unpack 2: only pack 2"); + inv = Inv(1, mainCap: 1); + Fill(inv.Main, 1, 2000); + inv.Packs[0].Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent)); + m = p.PlanUnpack(inv, null, 0); + Eq(m.Count, 0, "main pack full: nothing"); + Check(p.View.MainFull && p.View.Waiting == 1, "main full reported"); + } + + // ── Gates ─────────────────────────────────────────────────────────── + + private static void Gates() + { + Check(SortGate.Reason(new GateInputs()) == null, "nothing going on: fine"); + Eq(SortGate.Reason(new GateInputs { InPortalSpace = true }), "portal space", "portal space"); + Eq(SortGate.Reason(new GateInputs { Looting = true }), "looting", "looting a corpse or chest"); + Eq(SortGate.Reason(new GateInputs { VendorOpen = true }), "vendor open", "vendor"); + Eq(SortGate.Reason(new GateInputs { TradeOpen = true }), "trading", "trade window"); + Eq(SortGate.Reason(new GateInputs { ClientBusy = true }), "busy", "busy (a use or a cast)"); + Eq(SortGate.Reason(new GateInputs { Animating = true }), "busy", "animating"); + Eq(SortGate.Reason(new GateInputs { InPortalSpace = true, Looting = true }), "portal space", "portal space comes first"); + } + + private static void GatesRynthAi() + { + RynthAiActivity run = RynthAiActivity.MacroRunning; + Check(SortGate.Reason(new GateInputs { Bot = run }) == null, "RynthAi idle: fine"); + Check(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Navigating }) == null, "RynthAi walking a route: fine"); + Eq(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Looting }), "RynthAi is looting", "looting"); + Eq(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Salvaging }), "RynthAi is salvaging", "salvaging"); + Eq(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Buffing }), "RynthAi is buffing", "buffing / healing"); + Eq(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Crafting }), "RynthAi is making ammo", "crafting"); + Eq(SortGate.Reason(new GateInputs { Bot = RynthAiActivity.ServerAction }), "RynthAi is waiting on the server", "an unanswered use/cast, macro off too"); + Eq(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Combat }), "RynthAi is fighting", "fighting, Sort during fights off"); + Check(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Combat, SortInCombat = true }) == null, "fighting, Sort during fights on"); + Eq(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Combat | RynthAiActivity.ServerAction, SortInCombat = true }), + "RynthAi is waiting on the server", "fighting with a cast unanswered: still waits"); + Eq(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.Combat, SortInCombat = true, Animating = true }), "busy", + "fighting while animating: waits"); + Check(SortGate.Reason(new GateInputs { Bot = run | RynthAiActivity.AutoCram }) == null, "AutoCram alone doesn't pause (it's a warning)"); + Check(SortGate.Reason(new GateInputs { Bot = null }) == null, "no RynthAi: the client's own signals only"); + } + + private static void GateQuiet() + { + var g = new SortGate(); + Eq(g.Evaluate(new GateInputs { ClientBusy = true }, 10_000), "busy", "busy"); + Eq(g.Evaluate(new GateInputs(), 10_100), "busy", "just cleared: still held"); + Eq(g.Evaluate(new GateInputs(), 10_000 + SortGate.QuietMs - 1), "busy", "held until the quiet time ends"); + Check(g.Evaluate(new GateInputs(), 10_000 + SortGate.QuietMs) == null, "then clear"); + Check(new SortGate().Evaluate(new GateInputs(), 0) == null, "never paused: clear at once"); + } + + private static void LootWatching() + { + var w = new LootWatch(); + Check(!w.Update(0, 0, 0), "nothing open"); + Check(w.Update(0x7000_0001, 5, 1000), "a corpse just opened"); + Check(w.Update(0x7000_0001, 4, 3000), "its contents changing"); + Check(w.Update(0x7000_0001, 4, 6999), "within 4 s of the last change"); + // 6999 was the last "looting" read: 1.5 s more from there, then a finished corpse the client + // still shows open doesn't count. + Check(w.Update(0x7000_0001, 4, 6999 + LootWatch.AfterMs - 1), "the 1.5 s after the last looting"); + Check(!w.Update(0x7000_0001, 4, 6999 + LootWatch.AfterMs), "a finished corpse still shown open doesn't count"); + Check(w.Update(0x7000_0002, 7, 20_000), "the next corpse"); + Check(w.Update(0, 0, 20_500), "closed: 1.5 s more (the next corpse is a moment away)"); + Check(!w.Update(0, 0, 21_600), "then clear"); + } + + private static void StatusJsonFallback() + { + Eq(HostSortWorld.FromStatusJson("{\"macro\":true,\"action\":\"Looting\"}"), RynthAiActivity.MacroRunning | RynthAiActivity.Looting, "looting"); + Eq(HostSortWorld.FromStatusJson("{\"macro\":true,\"action\":\"Healing\"}"), RynthAiActivity.MacroRunning | RynthAiActivity.Buffing, "healing = buffing slot"); + Eq(HostSortWorld.FromStatusJson("{\"macro\":true,\"action\":\"Restoring mana\"}"), RynthAiActivity.MacroRunning | RynthAiActivity.Buffing, "restoring mana"); + Eq(HostSortWorld.FromStatusJson("{\"macro\":true,\"action\":\"Following\"}"), RynthAiActivity.MacroRunning | RynthAiActivity.Navigating, "following"); + Eq(HostSortWorld.FromStatusJson("{\"macro\":true,\"action\":\"Default\"}"), RynthAiActivity.MacroRunning, "default"); + Eq(HostSortWorld.FromStatusJson("{\"macro\":false,\"action\":\"Combat\"}"), RynthAiActivity.None, "macro off: nothing"); + Check(HostSortWorld.FromStatusJson("nope") == null && HostSortWorld.FromStatusJson(null) == null, "not JSON: null"); + } + + // ── Moves ─────────────────────────────────────────────────────────── + + private static MoveInFlight Flight(uint item, uint dest, uint merge = 0, int stack = 1, int seq = 7, long sent = 1000) + { + var it = It(item, "Thing", ObjectClasses.Misc, stack: stack); + var pack = new SortPack { Id = dest }; + return new MoveInFlight { Move = new SortMove(it, pack, 1, merge), SentMs = sent, ErrorSeqAtSend = seq, StackAtSend = stack }; + } + + private static void MoveAnswers() + { + MoveInFlight m = Flight(10, 0x40000001); + Eq(MoveTracker.Observe(m, new MoveObservation { Exists = true, Container = Me, ErrorSeq = 7 }, 1500), MoveOutcome.Pending, "still in the main pack"); + Eq(MoveTracker.Observe(m, new MoveObservation { Exists = true, Container = 0x40000001, ErrorSeq = 7 }, 1500), MoveOutcome.Done, "landed"); + Eq(MoveTracker.Observe(m, new MoveObservation { Exists = false }, 1500), MoveOutcome.Done, "gone: merged on arrival"); + Eq(MoveTracker.Observe(m, new MoveObservation { Exists = true, Container = Me, ErrorSeq = 8, ErrorEventType = 0xA0, ErrorObject = 10 }, 1500), + MoveOutcome.Refused, "InventoryServerSaveFailed for it"); + Eq(MoveTracker.Observe(m, new MoveObservation { Exists = true, Container = Me, ErrorSeq = 8, Error = 0x1D, ErrorEventType = 0x28A }, 1500), + MoveOutcome.TooBusy, "You're too busy"); + Eq(MoveTracker.Observe(m, new MoveObservation { Exists = true, Container = Me, ErrorSeq = 8, Error = 0x402, ErrorEventType = 0x28A, ErrorObject = 99 }, 1500), + MoveOutcome.Pending, "someone else's refusal (a fizzle) isn't ours"); + Eq(MoveTracker.Observe(m, new MoveObservation { Exists = true, Container = Me, ErrorSeq = 7 }, 1000 + MoveTracker.TimeoutMs), + MoveOutcome.TimedOut, "no answer in 5 s"); + MoveInFlight merge = Flight(10, 0x40000001, merge: 50, stack: 12); + Eq(MoveTracker.Observe(merge, new MoveObservation { Exists = true, Container = Me, Stack = 4, ErrorSeq = 7 }, 1500), + MoveOutcome.Done, "a merge that took part of the stack"); + + Eq(MoveTracker.BackoffMs(0), 0L, "no failures: no hold"); + Eq(MoveTracker.BackoffMs(1), 2000L, "one: 2 s"); + Eq(MoveTracker.BackoffMs(3), 8000L, "three: 8 s"); + Eq(MoveTracker.BackoffMs(30), MoveTracker.MaxBackoffMs, "capped at 30 s"); + } + + // ── The loop ──────────────────────────────────────────────────────── + + /// A pretend game for the controller: packs, gate inputs and how the server answers. + private sealed class FakeWorld : ISortWorld + { + public SortInventory Inv = Inv(3); + public GateInputs Gate; + public readonly List Sent = new(); + public bool EngineAccepts = true; + /// "land" moves the item at once; "refuse" answers with InventoryServerSaveFailed; "busy" with You're too busy; "silent" never answers. + public string Server = "land"; + public int ErrorSeq = 3; + private readonly Dictionary _where = new(); + + public SortInventory? ReadInventory() => Inv; + public GateInputs ReadGate(bool sortInCombat, long nowMs) { GateInputs g = Gate; g.SortInCombat = sortInCombat; return g; } + public int ErrorSeqNow() => ErrorSeq; + + public bool SendMove(in SortMove move) + { + Sent.Add(move); + if (!EngineAccepts) return false; + switch (Server) + { + case "land": + uint id = move.Item.Id; + foreach (SortPack p in Inv.Packs.Prepend(Inv.Main)) p.Items.RemoveAll(i => i.Id == id); + uint destId = move.Dest.Id; + SortPack dest = destId == Inv.Main.Id ? Inv.Main : Inv.Packs.First(p => p.Id == destId); + dest.Items.Add(move.Item); + _where[id] = dest.Id; + break; + case "refuse": + ErrorSeq++; + _refused = move.Item.Id; + break; + case "busy": + ErrorSeq++; + _busy = true; + break; + } + return true; + } + + private uint _refused; + private bool _busy; + + public MoveObservation Observe(uint itemId) + { + var o = new MoveObservation { Exists = true, Container = _where.TryGetValue(itemId, out uint c) ? c : Me, ErrorSeq = ErrorSeq }; + if (_refused == itemId) { o.ErrorEventType = 0xA0; o.ErrorObject = itemId; } + if (_busy) { o.Error = 0x1D; o.ErrorEventType = 0x28A; } + return o; + } + } + + private static SortController Controller(bool auto = true, int gapMs = 300, int settleSec = 0) + { + var c = new SortController(); + c.Data.Settings.Auto = auto; + c.Data.Settings.GapMs = gapMs; + c.Data.Settings.SettleSec = settleSec; + return c; + } + + /// Ticks every 16 ms from to . + private static void Ticks(SortController c, FakeWorld w, long from, long to) + { + for (long t = from; t <= to; t += 16) c.Tick(w, t); + } + + private static void LoopPaused() + { + foreach (var (name, gate) in new (string, GateInputs)[] + { + ("looting", new GateInputs { Looting = true }), + ("vendor", new GateInputs { VendorOpen = true }), + ("trade", new GateInputs { TradeOpen = true }), + ("busy", new GateInputs { ClientBusy = true }), + ("animating", new GateInputs { Animating = true }), + ("portal", new GateInputs { InPortalSpace = true }), + ("RynthAi looting", new GateInputs { Bot = RynthAiActivity.MacroRunning | RynthAiActivity.Looting }), + ("RynthAi salvaging", new GateInputs { Bot = RynthAiActivity.MacroRunning | RynthAiActivity.Salvaging }), + ("RynthAi buffing", new GateInputs { Bot = RynthAiActivity.MacroRunning | RynthAiActivity.Buffing }), + ("RynthAi waiting on the server", new GateInputs { Bot = RynthAiActivity.ServerAction }), + ("RynthAi fighting", new GateInputs { Bot = RynthAiActivity.MacroRunning | RynthAiActivity.Combat }), + }) + { + var w = new FakeWorld { Gate = gate }; + w.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent)); + SortController c = Controller(); + Ticks(c, w, 0, 10_000); + Eq(w.Sent.Count, 0, $"{name}: nothing sent"); + Check(c.Paused, $"{name}: status says paused ({c.Status})"); + c.StartJob(SortScope.All); + Ticks(c, w, 10_000, 12_000); + Eq(w.Sent.Count, 0, $"{name}: a job asked for waits too"); + // Clear: after the quiet time it goes (counted from the last paused read, which is at + // most one poll before the clear). + w.Gate = new GateInputs(); + long quietEnd = 12_000 + SortGate.QuietMs - SortController.PollMs - 50; + Ticks(c, w, 12_000, quietEnd); + Eq(w.Sent.Count, 0, $"{name}: not during the quiet time"); + Ticks(c, w, quietEnd + 16, 16_000); + Eq(w.Sent.Count, 1, $"{name}: moves once clear"); + } + } + + private static void LoopOneAtATime() + { + var w = new FakeWorld { Server = "silent" }; + for (uint i = 0; i < 3; i++) w.Inv.Main.Items.Add(It(10 + i, "Prismatic Taper " + i, ObjectClasses.SpellComponent)); + SortController c = Controller(gapMs: 300); + Ticks(c, w, 0, 2000); + Eq(w.Sent.Count, 1, "one move out, unanswered: no second one"); + Check(c.HasMoveOut, "the move is out"); + + // Answered: the next goes only after the gap. + w.Server = "land"; + var w2 = new FakeWorld(); + for (uint i = 0; i < 3; i++) w2.Inv.Main.Items.Add(It(10 + i, "Prismatic Taper " + i, ObjectClasses.SpellComponent)); + SortController c2 = Controller(gapMs: 300); + c2.Tick(w2, 0); + Eq(w2.Sent.Count, 1, "first move"); + c2.Tick(w2, 16); // answer seen (landed) + Check(!c2.HasMoveOut, "answered"); + c2.Tick(w2, 16 + 299); + Eq(w2.Sent.Count, 1, "the gap holds the next one"); + c2.Tick(w2, 16 + 300); + Eq(w2.Sent.Count, 2, "second move after the gap"); + Ticks(c2, w2, 400, 3000); + Eq(w2.Sent.Count, 3, "all three moved"); + Eq(w2.Inv.Packs[0].Items.Count, 3, "all in pack 1"); + Eq(c2.Moved, 3, "three moved"); + Eq(c2.Status, "watching", "then watching"); + Check(c2.Log.Count == 3 && c2.Log[0].Contains("-> pack 1"), "moves logged, newest first"); + + // Settle time: nothing before it. + var w3 = new FakeWorld(); + w3.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent)); + SortController c3 = Controller(settleSec: 5); + Ticks(c3, w3, 0, 4900); + Eq(w3.Sent.Count, 0, "settling"); + Ticks(c3, w3, 4900, 6000); + Eq(w3.Sent.Count, 1, "moved after the settle time"); + + // Auto-sort off: nothing, status off. + var w4 = new FakeWorld(); + w4.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent)); + SortController c4 = Controller(auto: false); + Ticks(c4, w4, 0, 3000); + Eq(w4.Sent.Count, 0, "auto-sort off: nothing moves"); + Eq(c4.Status, "off", "status off"); + } + + private static void LoopRefusals() + { + var w = new FakeWorld { Server = "refuse" }; + w.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent)); + w.Inv.Main.Items.Add(It(11, "Salvaged Iron", ObjectClasses.Salvage)); + SortController c = Controller(gapMs: 300); + c.Tick(w, 0); + Eq(w.Sent.Count, 1, "first move"); + c.Tick(w, 16); + Check(!c.HasMoveOut, "refusal seen"); + Check(c.Planner.IsBlocked(10, 17), "the refused item is left alone"); + Check(c.Log[0].Contains("not moved"), "logged as not moved"); + Ticks(c, w, 32, 16 + MoveTracker.BackoffMs(1) - 16); + Eq(w.Sent.Count, 1, "held for the back-off"); + w.Server = "land"; + Ticks(c, w, 16 + MoveTracker.BackoffMs(1), 6000); + Eq(w.Sent.Count, 2, "then the next item"); + Eq(w.Sent[1].Item.Id, 11u, "it is the other item, not the refused one"); + Ticks(c, w, 6000, 50_000); + Eq(w.Sent.Count, 2, "the refused one waits out its minute"); + Ticks(c, w, 50_000, 62_000); + Eq(w.Sent.Count, 3, "tried again after a minute"); + Eq(c.Failed, 1, "one failure counted"); + + // The engine refusing the call counts as a refusal too. + var w2 = new FakeWorld { EngineAccepts = false }; + w2.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent)); + SortController c2 = Controller(); + c2.Tick(w2, 0); + Check(c2.Planner.IsBlocked(10, 1) && c2.Log[0].Contains("engine refused"), "engine refusal blocks the item"); + + // Failures in a row hold longer each time. + var w3 = new FakeWorld { Server = "refuse" }; + for (uint i = 0; i < 4; i++) w3.Inv.Main.Items.Add(It(10 + i, "Taper " + i, ObjectClasses.SpellComponent)); + SortController c3 = Controller(); + var sentAt = new List(); + for (long t = 0; t < 40_000; t += 16) + { + int before = w3.Sent.Count; + c3.Tick(w3, t); + if (w3.Sent.Count > before) sentAt.Add(t); + } + Check(sentAt.Count == 4, $"four tries ({sentAt.Count})"); + if (sentAt.Count == 4) + Check(sentAt[2] - sentAt[1] > sentAt[1] - sentAt[0] && sentAt[3] - sentAt[2] > sentAt[2] - sentAt[1], "each hold longer than the last"); + } + + private static void LoopBusyAndTimeout() + { + var w = new FakeWorld { Server = "busy" }; + w.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent)); + SortController c = Controller(); + c.Tick(w, 0); + c.Tick(w, 16); + Check(!c.Planner.IsBlocked(10, 17), "too busy: the item isn't blocked"); + Check(c.Log[0].Contains("busy"), "logged"); + w.Server = "land"; + Ticks(c, w, 32, 1900); + Eq(w.Sent.Count, 1, "held for the back-off"); + Ticks(c, w, 1900, 3000); + Eq(w.Sent.Count, 2, "then tried again"); + + var w2 = new FakeWorld { Server = "silent" }; + w2.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent)); + SortController c2 = Controller(); + Ticks(c2, w2, 0, MoveTracker.TimeoutMs - 16); + Check(c2.HasMoveOut, "waiting for the answer"); + Ticks(c2, w2, MoveTracker.TimeoutMs, MoveTracker.TimeoutMs + 32); + Check(!c2.HasMoveOut && c2.Planner.IsBlocked(10, MoveTracker.TimeoutMs + 32), "no answer in 5 s: blocked"); + Check(c2.Log[0].Contains("no answer"), "logged"); + } + + private static void LoopJobs() + { + // Tidy: misplaced side-pack items, as fast as the server answers (no auto gap). + var w = new FakeWorld(); + w.Inv.Packs[0].Items.Add(It(10, "Salvaged Iron", ObjectClasses.Salvage)); + w.Inv.Packs[0].Items.Add(It(11, "Salvaged Gold", ObjectClasses.Salvage)); + SortController c = Controller(auto: false, gapMs: 3000); + c.StartJob(SortScope.All); + Ticks(c, w, 0, 600); + Eq(w.Sent.Count, 2, "tidy moved both quickly (job gap, not the 3 s auto gap)"); + Eq(w.Inv.Packs[1].Items.Count, 2, "both in pack 2"); + Check(c.Job == null && c.Log[0] == "Packs tidied", "job ends with a note"); + + // Unpack turns auto-sort off (and asks for a save) so nothing moves back. + var w2 = new FakeWorld(); + w2.Inv.Packs[0].Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent)); + w2.Inv.Packs[2].Items.Add(It(12, "Black Opal", ObjectClasses.Gem)); + SortController c2 = Controller(auto: true); + int saves = 0; + c2.SettingsChanged = () => saves++; + c2.StartUnpack(null); + Check(!c2.Data.Settings.Auto && saves == 1, "unpack: auto-sort off, saved"); + Ticks(c2, w2, 0, 1000); + Eq(w2.Inv.Main.Items.Count, 2, "both in the main pack"); + Eq(c2.Log[0], "Side packs emptied", "noted"); + Ticks(c2, w2, 1000, 20_000); + Eq(w2.Sent.Count, 2, "nothing moved back"); + + // Unpack one pack. + var w3 = new FakeWorld(); + w3.Inv.Packs[0].Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent)); + w3.Inv.Packs[2].Items.Add(It(12, "Black Opal", ObjectClasses.Gem)); + SortController c3 = Controller(); + c3.StartUnpack(3); + Ticks(c3, w3, 0, 1000); + Check(w3.Inv.Main.Items.Count == 1 && w3.Inv.Main.Items[0].Id == 12, "only pack 3 emptied"); + + // Clean: strays back to the main pack. + var w4 = new FakeWorld(); + w4.Inv.Packs[1].Items.Add(It(12, "Ashcoal", ObjectClasses.Misc)); + SortController c4 = Controller(auto: false); + c4.StartJob(SortScope.Clean); + Ticks(c4, w4, 0, 1000); + Check(w4.Inv.Main.Items.Count == 1 && c4.Log[0] == "Packs cleaned", "clean sent the stray home"); + + // Sort now ignores the settle time. + var w5 = new FakeWorld(); + w5.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent)); + SortController c5 = Controller(settleSec: 30); + c5.StartJob(SortScope.Main); + Ticks(c5, w5, 0, 200); + Eq(w5.Sent.Count, 1, "sort now: no settle time"); + } + + // ── Store ─────────────────────────────────────────────────────────── + + private static SortStore TempStore(string name) + { + string root = Path.Combine(_temp, name); + return new SortStore(Path.Combine(root, "RynthSort"), Path.Combine(root, "RynthLua", "Data", "RynthSort")); + } + + private static void StoreRoundTrip() + { + SortStore st = TempStore("roundtrip"); + CharacterSortData d = st.Load("DreamWeave", "Drakkon", out string? problem); + Check(problem == null && d.Rules.Count == 5 && d.ImportedFrom.Length == 0, "no file: the defaults"); + d.Rules.Add(SortRule.ForName("Pyreal \"Mote\"", 6)); + d.Rules[0].On = false; + d.Settings.Auto = false; + d.Settings.SettleSec = 12; + d.Settings.GapMs = 900; + d.Settings.SortInCombat = true; + d.Settings.WindowOpen = false; + Check(st.Save("DreamWeave", "Drakkon", d) == null, "saved"); + Check(File.Exists(Path.Combine(st.Root, "characters", "DreamWeave_Drakkon.json")), "file named server_character"); + CharacterSortData back = st.Load("DreamWeave", "Drakkon", out problem); + Check(problem == null, "read back"); + Eq(back.Rules.Count, 6, "rules"); + Check(!back.Rules[0].On && back.Rules[5].Kind == RuleKind.Name && back.Rules[5].Text == "Pyreal \"Mote\"" && back.Rules[5].Pack == 6, "rule fields"); + Check(!back.Settings.Auto && back.Settings.SettleSec == 12 && back.Settings.GapMs == 900 && back.Settings.SortInCombat && !back.Settings.WindowOpen, "settings"); + Eq(SortStore.FileStem("Dream:Weave", "Con"), "Dream_Weave_Con", "unsafe characters replaced like RynthLua"); + Eq(SortStore.SafeFileName("CON"), "_CON", "reserved names guarded"); + } + + // The Lua script's file for Drakkon, as it is on disk (2026-10-07). + private const string LuaFile = "{\n \"rules\": [{\"on\":true,\"kind\":\"class\",\"class\":12,\"text\":\"\",\"pack\":1},{\"on\":true,\"kind\":\"class\",\"class\":39,\"text\":\"\",\"pack\":2},{\"on\":true,\"kind\":\"class\",\"class\":11,\"text\":\"\",\"pack\":3},{\"on\":true,\"kind\":\"class\",\"class\":16,\"text\":\"\",\"pack\":3},{\"on\":true,\"kind\":\"class\",\"class\":13,\"text\":\"\",\"pack\":3},{\"on\":true,\"kind\":\"class\",\"class\":29,\"text\":\"\",\"pack\":4}],\n \"settings\": {\"auto\":false,\"settleSec\":5,\"gapMs\":600}\n}\n"; + + private static void StoreLuaImport() + { + SortStore st = TempStore("import"); + string lua = st.LuaPathFor("DreamWeave", "Drakkon"); + Directory.CreateDirectory(Path.GetDirectoryName(lua)!); + File.WriteAllText(lua, LuaFile); + CharacterSortData d = st.Load("DreamWeave", "Drakkon", out string? problem); + Check(problem == null, "Lua file read"); + Eq(d.ImportedFrom, lua, "marked as imported"); + Eq(d.Rules.Count, 6, "six rules"); + Check(d.Rules[5].Kind == RuleKind.Class && d.Rules[5].Class == ObjectClasses.HealingKit && d.Rules[5].Pack == 4, "healing kits to pack 4"); + Check(!d.Settings.Auto && d.Settings.SettleSec == 5 && d.Settings.GapMs == 600, "settings taken over"); + Check(d.Settings.WindowOpen && !d.Settings.SortInCombat, "plugin-only settings at their defaults"); + + // Once RynthSort has its own file, the Lua file is no longer read (and is left alone). + d.Rules.RemoveAt(0); + st.Save("DreamWeave", "Drakkon", d); + CharacterSortData again = st.Load("DreamWeave", "Drakkon", out _); + Eq(again.Rules.Count, 5, "own file wins over the Lua file"); + Check(File.Exists(lua) && File.ReadAllText(lua) == LuaFile, "the Lua file is untouched"); + + // Another character with no Lua file: defaults. + Eq(st.Load("DreamWeave", "Someone", out _).ImportedFrom, "", "nothing to import: defaults"); + } + + private static void StoreOddFiles() + { + SortStore st = TempStore("odd"); + string own = st.PathFor("S", "A"); + Directory.CreateDirectory(Path.GetDirectoryName(own)!); + File.WriteAllText(own, "{ not json"); + CharacterSortData d = st.Load("S", "A", out string? problem); + Check(problem != null && d.Rules.Count == 5, "broken file: defaults, problem reported"); + + // The Lua script saved an empty rule list as {}; numbers as doubles; out-of-range values clamped. + File.WriteAllText(own, "{\"rules\":{},\"settings\":{\"auto\":true,\"settleSec\":99.0,\"gapMs\":5,\"x\":1}}"); + d = st.Load("S", "A", out problem); + Check(problem == null && d.Rules.Count == 0, "{} = no rules"); + Check(d.Settings.SettleSec == SortSettings.SettleMax && d.Settings.GapMs == SortSettings.GapMin, "clamped"); + + File.WriteAllText(own, "{\"rules\":[{\"kind\":\"name\",\"text\":\"Key\",\"pack\":2.0},{\"class\":11,\"pack\":-4},7,{\"on\":false}]}"); + d = st.Load("S", "A", out _); + Eq(d.Rules.Count, 3, "a non-object entry is skipped"); + Check(d.Rules[0].Kind == RuleKind.Name && d.Rules[0].Pack == 2 && d.Rules[0].On, "missing 'on' = on; 2.0 = 2"); + Eq(d.Rules[1].Pack, 1, "pack clamped to 1"); + Check(!d.Rules[2].On && d.Rules[2].Class == ObjectClasses.SpellComponent, "defaults for missing fields"); + } + + private static void LuaAutostart() + { + static bool Starts(string json, string key) + { + using var doc = System.Text.Json.JsonDocument.Parse(json); + return RynthSortPlugin.LuaScriptStarts(doc.RootElement, key); + } + Check(!Starts("{\"GlobalScripts\":[],\"CharacterScripts\":{\"DreamWeave|Drakkon\":[\"item-counter\"]}}", "DreamWeave|Drakkon"), "today's settings: not set to start"); + Check(Starts("{\"GlobalScripts\":[\"RynthSort\"]}", "DreamWeave|Drakkon"), "global autostart"); + Check(Starts("{\"CharacterScripts\":{\"DreamWeave|Drakkon\":[\"rynthsort\"]}}", "DreamWeave|Drakkon"), "this character's autostart"); + Check(!Starts("{\"CharacterScripts\":{\"DreamWeave|Other\":[\"RynthSort\"]}}", "DreamWeave|Drakkon"), "another character's"); + } + + // ── Window ────────────────────────────────────────────────────────── + + private static (SortController, SortPanel, UiHost, UiWindow) Window() + { + var c = new SortController(); + var panel = new SortPanel(c, () => { }) { Character = () => "Drakkon" }; + var host = new UiHost(); + UiWindow w = host.Add(new UiWindow("RynthSort/Main", "RynthSort") { Visible = true }); + var inv = Inv(4); + Fill(inv.Packs[0], 24, 1000); + inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem)); + c.Planner.Plan(inv, c.Data.Rules, SortScope.Main, true, 0, 0); + return (c, panel, host, w); + } + + private static void Draw(UiWindow w, SortPanel panel) + { + w.Begin(); + panel.Draw(w); + w.End(); + } + + private static string BodyText(UiWindow w) => Encoding.UTF8.GetString(w.Body); + + private static unsafe void ParseAll(UiHost host, string what, out int maxOps) + { + int n = Write(host); + byte[] buf = SubmitBuffer(host); + int rc; + List windows; + string error; + fixed (byte* p = buf) rc = DisplayListParser.Parse(p, n, 4000f, out _, out windows, out error); + Check(rc == 0, $"{what}: engine parser refused the submit ({rc}): {error}"); + maxOps = windows.Where(x => x.List != null).Select(x => x.List!.OpCount).DefaultIfEmpty(0).Max(); + } + + private static byte[] Event(ushort type, uint seq, uint window, uint key, byte[] payload) + { + var e = new byte[16 + payload.Length]; + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(e, type); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(e.AsSpan(2), (ushort)e.Length); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(e.AsSpan(4), seq); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(e.AsSpan(8), window); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(e.AsSpan(12), key); + payload.CopyTo(e, 16); + return e; + } + + private static byte[] Click => new byte[] { 1, 0 }; + + private static void WindowParses() + { + var (c, panel, host, w) = Window(); + Draw(w, panel); + ParseAll(host, "default rules", out int ops); + Check(ops > 10 && ops < 1500, $"ops in range ({ops})"); + string body = BodyText(w); + Check(body.Contains("Auto-sort") && body.Contains("Sort main pack") && body.Contains("Tidy all packs") + && body.Contains("Empty side packs") && body.Contains("Clean packs"), "buttons and toggle"); + Check(body.Contains("Rules (first match wins)") && body.Contains("1. Spell Component -> pack 1 (Pack 1)"), "rule list"); + w.MarkSubmitted(true); + + // A selected rule's editor (class, then name), the settings open, warnings and a log. + Apply(host, Event(1, 1, w.Hash, w.KeyOf("row.0"), Click)); + Apply(host, Event(6, 2, w.Hash, w.KeyOf("settings"), new byte[] { 1 })); + c.Note("Prismatic Taper -> pack 1"); + panel.Warnings = () => new[] { "The RynthSort Lua script is set to start too" }; + Draw(w, panel); + ParseAll(host, "rule editor (class)", out _); + body = BodyText(w); + Check(body.Contains("Rule 1") && body.Contains("Mana Stone") && body.Contains("Pack 1: Pack 1 (24/24)") && body.Contains("Pack 7 (none)"), "editor with class and pack choices"); + Check(body.Contains("Settle (s)") && body.Contains("Gap (ms)") && body.Contains("Sort during fights"), "settings shown"); + Check(body.Contains("Lua script is set to start"), "warning shown"); + w.MarkSubmitted(true); + + c.Data.Rules[0].Kind = RuleKind.Name; + c.Data.Rules[0].Text = "Taper"; + c.Data.Rules[0].Class = 999; + Draw(w, panel); + ParseAll(host, "rule editor (name)", out _); + Check(BodyText(w).Contains("Name has"), "name editor"); + c.Data.Rules[0].Kind = RuleKind.Class; + Draw(w, panel); + ParseAll(host, "rule editor (class the editor doesn't offer)", out _); + Check(BodyText(w).Contains("class 999"), "an unknown class stays shown"); + + // Many rules still fit. + for (int i = 0; i < SortStore.MaxRules; i++) c.Data.Rules.Add(SortRule.ForName("x" + i, 1 + i % 8)); + Draw(w, panel); + ParseAll(host, "64+ rules", out int many); + Check(many < 1500, $"many rules fit ({many} ops)"); + + // Logged out. + panel.Character = () => ""; + Draw(w, panel); + ParseAll(host, "logged out", out _); + Check(BodyText(w).Contains("Log in"), "logged-out text"); + } + + private static void WindowEvents() + { + var (c, panel, host, w) = Window(); + Draw(w, panel); + int rules = c.Data.Rules.Count; + + Apply(host, Event(1, 1, w.Hash, w.KeyOf("rule.add"), Click)); + Eq(c.Data.Rules.Count, rules + 1, "Add rule"); + Eq(panel.Selected, rules, "the new rule is selected"); + Draw(w, panel); + + Apply(host, Event(1, 2, w.Hash, w.KeyOf("rule.up"), Click)); + Eq(panel.Selected, rules - 1, "Up moves the selection with the rule"); + Draw(w, panel); + + // The new rule: make it a name rule for "opal" to pack 4. + Apply(host, Event(3, 3, w.Hash, w.KeyOf("rule.kind"), BitConverter.GetBytes(1))); + Draw(w, panel); + byte[] text = Encoding.UTF8.GetBytes("opal"); + var payload = new byte[3 + text.Length]; + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(1), (ushort)text.Length); + text.CopyTo(payload, 3); + Apply(host, Event(5, 4, w.Hash, w.KeyOf("rule.text"), payload)); + Apply(host, Event(3, 5, w.Hash, w.KeyOf("rule.pack"), BitConverter.GetBytes(3))); + SortRule r = c.Data.Rules[rules - 1]; + Check(r.Kind == RuleKind.Name && r.Text == "opal" && r.Pack == 4, "edited through the combo, text box and pack combo"); + Draw(w, panel); + + // Its checkbox turns it off. + Apply(host, Event(2, 6, w.Hash, w.KeyOf("on." + (rules - 1)), new byte[] { 0 })); + Check(!r.On, "checkbox turns the rule off"); + Draw(w, panel); + + Apply(host, Event(1, 7, w.Hash, w.KeyOf("rule.down"), Click)); + Eq(c.Data.Rules.IndexOf(r), rules, "Down"); + Draw(w, panel); + Apply(host, Event(1, 8, w.Hash, w.KeyOf("rule.remove"), Click)); + Check(!c.Data.Rules.Contains(r) && c.Data.Rules.Count == rules, "Remove"); + Draw(w, panel); + + // Class combo on rule 1. + Apply(host, Event(1, 9, w.Hash, w.KeyOf("row.0"), Click)); + Draw(w, panel); + Apply(host, Event(3, 10, w.Hash, w.KeyOf("rule.class"), BitConverter.GetBytes(ObjectClasses.ChoiceIndex(ObjectClasses.HealingKit)))); + Eq(c.Data.Rules[0].Class, ObjectClasses.HealingKit, "class combo"); + + // Settings and buttons. + Apply(host, Event(6, 11, w.Hash, w.KeyOf("settings"), new byte[] { 1 })); + Draw(w, panel); + Apply(host, Event(3, 12, w.Hash, w.KeyOf("settle"), BitConverter.GetBytes(12))); + Apply(host, Event(3, 13, w.Hash, w.KeyOf("gap"), BitConverter.GetBytes(50_000))); + Apply(host, Event(2, 14, w.Hash, w.KeyOf("combat"), new byte[] { 1 })); + Check(c.Data.Settings.SettleSec == 12 && c.Data.Settings.GapMs == SortSettings.GapMax && c.Data.Settings.SortInCombat, "sliders (clamped) and the fights box"); + Apply(host, Event(2, 15, w.Hash, w.KeyOf("auto"), new byte[] { 0 })); + Check(!c.Data.Settings.Auto, "auto-sort box"); + Apply(host, Event(1, 16, w.Hash, w.KeyOf("job.all"), Click)); + Eq(c.Job, SortScope.All, "Tidy button"); + Apply(host, Event(1, 17, w.Hash, w.KeyOf("job.unpack"), Click)); + Check(c.Job == SortScope.Unpack && c.UnpackWhich == null, "Empty side packs button"); + } + } +} diff --git a/Tools/RynthSort.Tests/RynthSort.Tests.csproj b/Tools/RynthSort.Tests/RynthSort.Tests.csproj new file mode 100644 index 0000000..519ab6b --- /dev/null +++ b/Tools/RynthSort.Tests/RynthSort.Tests.csproj @@ -0,0 +1,39 @@ + + + + + Exe + net10.0-windows + enable + true + true + RynthSort.Tests + $(NoWarn);CS0649;CS0169;CS0414;CS8618 + + + + + + + + + + + + + + + + + +