From 5416e8066ab60bff1dd1f2849db10c519d552397 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Tue, 6 Oct 2026 08:47:11 -0400 Subject: [PATCH 1/6] Snapshot for release 2026.10.6.1 (internal bd2f068) --- .../Combat/BuffManager.cs | 112 +++- .../Combat/CastTracker.cs | 2 + .../Combat/CombatManager.cs | 91 ++- .../Combat/KillClock.cs | 126 ++++ .../Combat/MissileCraftingManager.cs | 2 +- .../Combat/PetManager.cs | 85 ++- .../Combat/SpellManager.cs | 20 + .../Combat/WorldObjectCache.cs | 126 +++- .../CorpseOpenController.cs | 277 +++++++- .../CreatureData/CreatureProfileStore.cs | 2 +- .../CreatureData/CreatureWeakness.cs | 2 +- .../DungeonHazardStore.cs | 3 +- .../DungeonHazardSurfaces.cs | 2 +- .../FlightRecorderSignal.cs | 28 + .../ItemInfo/ItemInfoText.cs | 308 +++++++++ .../ItemInfo/SelfSelect.cs | 27 + .../LegacyUi/LegacyAdvancedSettingsUi.cs | 13 +- .../LegacyUi/LegacyDashboardRenderer.cs | 72 +- .../LegacyUi/LegacyMetaUi.cs | 5 +- .../LegacyUi/LegacyUiSettings.cs | 22 +- .../Loot/LootEditorBridge.cs | 2 +- .../Loot/UseRefusalWatch.cs | 189 ++++++ .../MagToolsCommands.cs | 4 +- .../ManaStoneManager.cs | 19 +- .../Maps/DungeonMapBake.cs | 2 +- .../Meta/AfFileParser.cs | 2 + .../Meta/AfFileWriter.cs | 3 + .../Meta/ExpressionEngine.cs | 33 +- .../Meta/ExpressionReference.txt | 13 + .../Meta/MetaManager.cs | 24 +- .../Meta/MetaRuleEdits.cs | 52 ++ .../Meta/MetaSchema.cs | 2 + .../NavMarkerRenderer.cs | 70 ++ .../RynthCore.Plugin.RynthAi/NavOverlay.cs | 234 +++++++ .../NavigationEngine.cs | 112 +++- .../RadarWallRenderer.cs | 2 +- .../RynthAiCommands.cs | 13 +- .../RynthAiPlugin.ItemInfo.cs | 189 ++++++ .../RynthAiPlugin.Pacing.cs | 66 ++ .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 58 +- .../RynthCore.Plugin.RynthAi.csproj | 9 + .../Trade/AutoTradeManager.cs | 2 +- .../UtilityBeltExtraCommands.cs | 6 +- .../Vendor/AutoVendorManager.cs | 2 +- .../RynthCore.Plugin.RynthLua.csproj | 5 + .../RynthLuaPaths.cs | 6 +- .../NavRouteExport.cs | 203 ++++++ .../RynthCore.Plugin.RynthNav/PathMarkers.cs | 295 +++++++++ .../RynthCore.Plugin.RynthNav.csproj | 7 + .../RynthNavPlugin.Avoid.cs | 13 +- .../RynthNavPlugin.Markers.cs | 220 +++++++ .../RynthNavPlugin.Panel.cs | 8 + .../RynthNavPlugin.SaveRoute.cs | 100 +++ .../RynthNavPlugin.Travel.cs | 10 +- .../RynthNavPlugin.cs | 13 +- .../TilePathFinder.cs | 241 +++++++ Plugins/RynthCore.Plugin.RynthNav/TripPath.cs | 190 ++++++ Plugins/RynthCore.Plugin.RynthNav/TripPlan.cs | 215 ++++++ .../RynthCore.Plugin.RynthNet.csproj | 5 + .../RynthNetSettings.cs | 2 +- Plugins/Shared/ActionPacer.cs | 471 +++++++++++++ Plugins/Shared/MoveAudit.cs | 112 ++++ Plugins/Shared/Nav3DText.cs | 175 +++++ Plugins/Shared/RynthInstallPaths.cs | 186 ++++++ Plugins/Shared/UseAudit.cs | 107 ++- Tools/RynthCore.LootEditor/MainViewModel.cs | 4 +- .../RynthCore.LootEditor.csproj | 5 + Tools/RynthCore.MonsterEditor/JsonContext.cs | 3 +- .../RynthCore.MonsterEditor/MainWindow.axaml | 24 +- .../MainWindow.axaml.cs | 49 +- Tools/RynthCore.MonsterEditor/Models.cs | 19 + .../MonsterRulesFile.cs | 99 +++ .../Fakes/FakeHost.cs | 75 ++- Tools/RynthCore.RynthAiHostTests/Program.cs | 16 + .../RynthCore.RynthAiHostTests.csproj | 11 + .../Tests/ActionPacingTests.cs | 622 ++++++++++++++++++ .../Tests/InstallPathsTests.cs | 144 ++++ .../Tests/ItemInfoTests.cs | 349 ++++++++++ .../Tests/LootAddItemTests.cs | 11 +- .../Tests/MetaTests.cs | 121 ++++ .../Tests/MonsterEditorTests.cs | 200 ++++++ .../Tests/NavEngineTests.cs | 15 +- .../Tests/NavOverlayTests.cs | 263 ++++++++ .../Tests/NavReachTests.cs | 261 ++++++++ .../Tests/NoKillTests.cs | 368 +++++++++++ .../Tests/PetRefillTests.cs | 198 ++++++ .../Tests/UseRefusalTests.cs | 539 +++++++++++++++ .../Tests/VitalsTests.cs | 24 + .../Tests/WorldCacheTypedTests.cs | 241 +++++++ .../RynthCore.RynthAiTests.csproj | 5 + .../RynthLua.CompatTests.csproj | 7 + .../RynthLua.ScriptWindowsTests.csproj | 5 + Tools/RynthNav.GraphTests/Program.cs | 70 ++ .../RynthNav.GraphTests.csproj | 7 + Tools/RynthNav.RouteTests/Program.cs | 1 + .../RynthNav.RouteTests.csproj | 8 + Tools/RynthNav.RouteTests/TripExportTests.cs | 389 +++++++++++ 97 files changed, 8926 insertions(+), 244 deletions(-) create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/KillClock.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/FlightRecorderSignal.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/ItemInfo/ItemInfoText.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfSelect.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/MetaRuleEdits.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/NavOverlay.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/NavRouteExport.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/PathMarkers.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.SaveRoute.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/TilePathFinder.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/TripPath.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/TripPlan.cs create mode 100644 Plugins/Shared/ActionPacer.cs create mode 100644 Plugins/Shared/Nav3DText.cs create mode 100644 Plugins/Shared/RynthInstallPaths.cs create mode 100644 Tools/RynthCore.MonsterEditor/MonsterRulesFile.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/InstallPathsTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/NavOverlayTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/NavReachTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/NoKillTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/WorldCacheTypedTests.cs create mode 100644 Tools/RynthNav.RouteTests/TripExportTests.cs diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 2d2d7bd..f71a21a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -1117,6 +1117,18 @@ public class BuffManager : IDisposable return; } + // One server action at a time (2026-10-06, Plugins/Shared/ActionPacer.cs): no kit, potion, + // wand, stance change or cast while the server hasn't answered the last one (its UseDone; + // a buff's enchantment lands before that). Heals keep their priority (ActionPacer's heal + // rules). And not while RynthAi still has the character running: the arbiter's stop goes + // out this tick, the cast the next one (a stop mid-windup disturbs the cast). + if (!PacerAllows(out string paceWhy)) + { + LastBuffSkipReason = "server answering the last action: " + paceWhy; + Hold("server answering the last action", paceWhy); + return; + } + // Don't issue a cast while the previous cast GESTURE is still animating. // CanCastNow is the engine's CMotionInterp gesture gate (the REAL cast // gate). AC refuses a cast issued mid-gesture with a server-driven @@ -1135,6 +1147,7 @@ public class BuffManager : IDisposable // everything else still waits for the count to drop. bool gateOpen = CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s)); bool busyHolds = BusyCount > 0 + && !_pacerLetHealAhead // the pacing let this heal go ahead of an unanswered corpse use (its rules) && (ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out _, out _).Length == 0 || BusyHoldsHeal()); if (!gateOpen || busyHolds) { @@ -1157,6 +1170,14 @@ public class BuffManager : IDisposable return; } + // Health floor: no buff while health is under a heal line that nothing could heal + // (Drakkon, 2026-10-06 04:51: recasting Swift Killer at 19% health, dead 10 s later). + if (_vitals.MaxHealth > 0 && HealthUnderAnyLine(_vitals.HealthPct, _vitals.StaminaPct)) + { + Hold("health under a heal line"); + return; + } + // Mana floor: no buff while mana is under Get Mana At. CheckVitals above already tried // Stamina to Mana and a mana potion; when neither could run (stamina too low, none // carried) buffing used to carry on and run mana to 0. Wait for it instead. @@ -1409,6 +1430,16 @@ public class BuffManager : IDisposable if (!healed) { _vitalWhy = ""; healed = AttemptVitalCast("Heal Self"); } string spellWhy = _vitalWhy; if (!healed) { _vitalWhy = ""; healed = AttemptPotion("HealthPotion"); } + // Last resort: the kit Kit Min Success skipped. A low chance beats no heal at all + // (Drakkon, 2026-10-06: 29% kit skipped, no spell, no potion, dead 6 s later). + if (!healed && kitWhy.EndsWith("under Kit Min Success %", StringComparison.Ordinal)) + { + string potionWhy = _vitalWhy; + _vitalWhy = ""; + healed = AttemptHealthKitUse(ignoreMinSuccess: true); + if (healed) _host.Log("[RynthAi] Vitals: no spell or potion could heal; using the kit despite Kit Min Success %."); + else _vitalWhy = potionWhy; + } if (healed) { _isHealingSelf = true; @@ -1485,6 +1516,7 @@ public class BuffManager : IDisposable if ((DateTime.Now - _lastPendingEmergencyHealAt).TotalMilliseconds < 2500) return; if (IsAwaitingCastResolution() || BusyHoldsHeal() || KitPending()) return; if (!CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s))) return; + if (!ActionPacer.MayStart(_host, "Buff", HealNeed.Emergency, out _)) return; if (AttemptHealthKitUse() || AttemptPotion("HealthPotion")) { _lastPendingEmergencyHealAt = DateTime.Now; @@ -1541,6 +1573,18 @@ public class BuffManager : IDisposable return true; } int spellId = FindBestSpellId(baseName, AcSkillType.LifeMagic); + // A heal with nothing known at the allowed tiers: the lowest known tier above them. + // Vitae can drop Life Magic under a tier line while only higher tiers are known. + if (spellId == 0 && baseName is "Heal Self" or "Stamina to Health Self") + { + spellId = _spellManager.GetSelfSpellIdAboveAllowedTier(baseName, AcSkillType.LifeMagic); + if (spellId != 0 && (DateTime.Now - _lastAboveTierLog).TotalSeconds >= 30) + { + _lastAboveTierLog = DateTime.Now; + _host.Log($"[RynthAi] Vitals: no '{baseName}' at the tiers Life Magic allows now; " + + $"trying {SpellTableStub.GetById(spellId)?.Name ?? spellId.ToString()} (may fizzle)."); + } + } if (spellId == 0) return VitalNo($"no known '{baseName}' spell at the allowed tiers"); // Parked after a hard server refusal (see OnChatWindowText) — the same // per-family cooldown the buff selectors honour. @@ -1566,7 +1610,8 @@ public class BuffManager : IDisposable _pendingSpellId = spellId; _pendingVitalSpellId = spellId; // instant: confirmed by chat, never by the registry _pendingVitalLabel = VitalLabel(baseName); - bool castOk = _host.CastSpell((uint)_host.GetPlayerId(), spellId); + bool castOk = _host.CastSpellFor((uint)_host.GetPlayerId(), spellId, "Buff", + SpellTableStub.GetById(spellId)?.Name ?? baseName); _lastCastAttempt = DateTime.Now; if (!castOk) { @@ -1726,7 +1771,9 @@ public class BuffManager : IDisposable } private DateTime _lastPotionAt = DateTime.MinValue; - private bool AttemptHealthKitUse() + private DateTime _lastAboveTierLog = DateTime.MinValue; + + private bool AttemptHealthKitUse(bool ignoreMinSuccess = false) { if (_worldObjectCache == null) return false; // VTank's kit options: skip kits in magic mode unless allowed; optionally @@ -1745,10 +1792,10 @@ public class BuffManager : IDisposable if (KitRetryWait(out string kitWait)) return VitalNo(kitWait); // Too likely to fail on what's missing (KitMinSuccessPct): let the spell have it. uint missing = _vitals.MaxHealth > _vitals.CurrentHealth ? _vitals.MaxHealth - _vitals.CurrentHealth : 0; - if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return VitalNo($"{kit.Name} under Kit Min Success %"); + if (!ignoreMinSuccess && !KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return VitalNo($"{kit.Name} under Kit Min Success %"); if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode) { - _host.ChangeCombatMode(CombatMode.NonCombat); + _host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the healing kit"); _lastCastAttempt = DateTime.Now; _healWaitKind = "peace mode for the kit"; return true; // use the kit next tick, once in peace mode @@ -1781,7 +1828,7 @@ public class BuffManager : IDisposable if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return false; if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode) { - _host.ChangeCombatMode(CombatMode.NonCombat); + _host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the stamina kit"); _lastCastAttempt = DateTime.Now; return true; // use the kit next tick, once in peace mode } @@ -2102,7 +2149,7 @@ public class BuffManager : IDisposable // buffed when it wasn't and never retried the known tier. if (diagnose) _host.Log($"[FR] CAST '{buffBaseName}' resolvedSpellId={spellId} (pending now set)"); - bool castOk = _host.CastSpell((uint)_host.GetPlayerId(), spellId); + bool castOk = _host.CastSpellFor((uint)_host.GetPlayerId(), spellId, "Buff", spellInfo?.Name ?? buffBaseName); _lastCastAttempt = DateTime.Now; if (castOk) NoteCastIssued(spellId); if (castOk && buffFamily != 0 && spellInfo != null) @@ -3364,6 +3411,50 @@ public class BuffManager : IDisposable _onCastResolved?.Invoke($"cast '{spellName}'"); } + /// What a heal needs from the pacing now: none, a heal line, or Emergency Heal At. + internal HealNeed HealNeedNow() + { + if (_vitals.MaxHealth <= 0) return HealNeed.None; + int hp = _vitals.HealthPct; + int emergencyAt = _settings.EmergencyHealAt; + if (emergencyAt > 0 && hp <= emergencyAt) return HealNeed.Emergency; + return HealthUnderAnyLine(hp, _vitals.StaminaPct) ? HealNeed.Heal : HealNeed.None; + } + + /// Times the vitals/buff step waited for the server's answer (tests, status). + internal int PacerHolds { get; private set; } + + /// + /// The pacing gate of the vitals/buff step (see HeartbeatCore): false while the server is still + /// answering the last action (ActionPacer.MayStart, with the heal rules) or while RynthAi still + /// has the character running (the arbiter's stop goes out first). + /// + private bool _pacerLetHealAhead; + + private bool PacerAllows(out string why) + { + why = ""; + _pacerLetHealAhead = false; + if (!ActionPacer.Enabled) return true; + if (MoveAudit.OwnMovementActive) + { + why = "the character is still moving (the stop goes out first)"; + PacerHolds++; + return false; + } + HealNeed need = HealNeedNow(); + bool outstanding = ActionPacer.Current(_host) != null; + if (ActionPacer.MayStart(_host, "Buff", need, out why)) + { + // A heal let ahead of an unanswered action: the busy count still counts that action, + // so the busy gate below must not hold the heal again. + _pacerLetHealAhead = outstanding && need != HealNeed.None; + return true; + } + PacerHolds++; + return false; + } + /// Record that a cast just went out, so the next one waits for the /// server to report the action finished rather than a blind interval. private void NoteCastIssued(int spellId) @@ -3491,6 +3582,7 @@ public class BuffManager : IDisposable var held = _cast.Open; string name = held?.Name ?? "?"; double secs = _cast.HeldSeconds; + FlightRecorderSignal.Dump(_host, $"held cast nudge: '{name}' {secs:0.0} s"); if (!_host.HasSetAutoRun) { _host.Log($"[CastSafe] '{name}' held open {secs:0.0} s after its incantation, but this engine has no SetAutoRun: no nudge."); @@ -3740,9 +3832,9 @@ public class BuffManager : IDisposable // _lastBuffStanceAttempt), while buffing held the bot. int noWandShift = Math.Min(_buffStanceConsecutiveFails, 5); int noWandGateMs = Math.Min(1000 << noWandShift, 30000); - if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs) + if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs + && _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "no wand: Magic mode bare-handed")) { - _host.ChangeCombatMode(CombatMode.Magic); NoteStanceRequest(); _lastBuffStanceAttempt = DateTime.Now; _lastCastAttempt = DateTime.Now; @@ -3924,9 +4016,9 @@ public class BuffManager : IDisposable if (shift > 5) shift = 5; int gateMs = 1000 << shift; // 1s, 2s, 4s, 8s, 16s, 32s if (gateMs > 30000) gateMs = 30000; // cap at 30s - if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs) + if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs + && _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode")) { - _host.ChangeCombatMode(CombatMode.Magic); NoteStanceRequest(); _lastBuffStanceAttempt = DateTime.Now; _lastCastAttempt = DateTime.Now; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CastTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CastTracker.cs index bfc882e..7d64663 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CastTracker.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CastTracker.cs @@ -156,6 +156,8 @@ internal sealed class CastTracker private void Close(Cast c, string kind) { c.Done = true; + // The server is in the cast's recoil now: one heal may be queued behind it (ActionPacer). + RynthCore.Plugin.Shared.ActionPacer.NoteCastResult(); DateTime now = Now; string nudged = c.Nudged ? " (after the movement nudge)" : ""; if (c.HasIncantation) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index b9d250b..9131b2b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -221,6 +221,14 @@ public partial class CombatManager : IDisposable private WeaponSwapGate? _weaponSwapGate; public void SetWeaponSwapGate(WeaponSwapGate gate) => _weaponSwapGate = gate; + /// + /// True = hold the idle peace-mode swap (PeaceModeWhenIdle) for now. RynthAi answers true while + /// looting has work: on ACE a combat-mode change cancels the server's walk/turn to a corpse + /// being opened (2026-10-06). Null = never hold. + /// + public Func? HoldIdlePeace { get; set; } + private bool _idlePeaceHeldLogged; + /// Current combat mode — read live from AC client each access to avoid event-drop drift. public int CurrentCombatMode => _host.HasGetCurrentCombatMode ? _host.GetCurrentCombatMode() : CombatMode.NonCombat; @@ -305,7 +313,7 @@ public partial class CombatManager : IDisposable private DateTime _lastSwingEvidenceAt = DateTime.MinValue; private DateTime _lastHitAt = DateTime.MinValue; private DateTime _lastMissAt = DateTime.MinValue; - private DateTime _lastKillAt = DateTime.MinValue; + private DateTime _lastKillAt = DateTime.MinValue; // stall-watchdog evidence only; metas and the status feed read the plugin's KillClock private string _lastSwingEvidenceKind = "none"; private readonly CombatStallWatchdog _stallWatch = new(); @@ -2314,9 +2322,22 @@ public partial class CombatManager : IDisposable // prevents ChangeCombatMode spam while idling between spawns. if (CurrentCombatMode == CombatMode.NonCombat) _idlePeaceAttempts = 0; // reached peace — the next idle request starts fresh + bool peaceHeld = false; if (_settings.PeaceModeWhenIdle && CurrentCombatMode != CombatMode.NonCombat && _scannedTargets.Count == 0 && BusyCount == 0 && DateTime.Now >= _navMagicWantedUntil) // a nav recall wants Magic mode + { + try { peaceHeld = HoldIdlePeace?.Invoke() == true; } catch { peaceHeld = false; } + if (peaceHeld && !_idlePeaceHeldLogged) + { + _idlePeaceHeldLogged = true; + _host.Log($"[EquipDiag] idle peace-mode swap held: looting is working (a mode change would cancel the server's walk/turn to the corpse); it goes out once looting is done."); + } + } + if (!peaceHeld) _idlePeaceHeldLogged = false; + if (!peaceHeld && _settings.PeaceModeWhenIdle && CurrentCombatMode != CombatMode.NonCombat + && _scannedTargets.Count == 0 && BusyCount == 0 + && DateTime.Now >= _navMagicWantedUntil) // a nav recall wants Magic mode { // Defer idle peace-swap while a cast at the just-dropped target is still // resolving: ChangeCombatMode truncates the in-flight gesture → strands @@ -2325,9 +2346,9 @@ public partial class CombatManager : IDisposable // 4 after that up to 15 s. An unbounded ChangeCombatMode stream is the // 2026-05-25 stance-spam crash class; this used to retry every 500 ms forever. double peaceDelayMs = Math.Min(15_000, 500 * Math.Pow(2, Math.Min(5, _idlePeaceAttempts / 4))); - if ((DateTime.Now - _lastPeaceAttempt).TotalMilliseconds > peaceDelayMs && !IsCastInFlight()) + if ((DateTime.Now - _lastPeaceAttempt).TotalMilliseconds > peaceDelayMs && !IsCastInFlight() + && _host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", "idle: no target (Peace Mode When Idle)")) { - _host.ChangeCombatMode(CombatMode.NonCombat); _lastPeaceAttempt = DateTime.Now; _idlePeaceAttempts++; if (_idlePeaceAttempts == 16) @@ -2411,6 +2432,17 @@ public partial class CombatManager : IDisposable if (RunStallWatchdog(targetObj, currentDist)) return true; + // One server action at a time (2026-10-06, Plugins/Shared/ActionPacer.cs): no stance change, + // wield, attack or cast while the server is still answering the last action (a kit, a corpse + // use, a buff, the last stance change). On ACE a mode change cancels a pending use's walk + // and fails a cast in progress; that interleaving began every stuck-use stall on record. + if (!ActionPacer.MayStart(_host, "Combat", HealNeed.None, out _)) + { + LastCombatSkipReason = "server-answering"; // D4 record-only + _tickWait = CombatLatencyTracker.Wait.Busy; + return true; + } + // While a targeted combat cast is still resolving on the server, do NOT re-assert // stance/weapon here: EquipWeaponAndSetStance can emit ChangeCombatMode/UseObject, // motion-replacing actions that truncate the in-flight cast gesture → orphan the cast @@ -2648,7 +2680,9 @@ public partial class CombatManager : IDisposable _returnToPhysicalCombat = true; _host.UseFor((uint)wandId, "Combat", "wield the wand to cast"); _lastEquipTime = DateTime.Now; // gate AttackWithMagic until wand is wielded - _host.ChangeCombatMode(CombatMode.Magic); + // Held by the pacing until the wield is answered; the wielded branch of + // EquipWeaponAndSetStance sends it then (2026-10-06). + _host.ChangeCombatModeFor(CombatMode.Magic, "Combat", "debuff: Magic mode after the wand"); lastAttackCmd = DateTime.Now; _lastAttackCmdTargetId = activeTargetId; return true; @@ -2813,7 +2847,7 @@ public partial class CombatManager : IDisposable // Same effect on the server as the wand heal: a mode change runs // HandleActionCancelAttack. EquipWeaponAndSetStance flips back after its // stance retry delay (~1 s with the flip backoff reset). - _host.ChangeCombatMode(CombatMode.NonCombat); + _host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat/Stall", "stall watchdog: toggle the mode", force: true); _stallToggleAt = now; ResetStanceFlipBackoff(); lastStanceAttempt = now; @@ -3721,9 +3755,9 @@ public partial class CombatManager : IDisposable ResetStanceFlipBackoff(); return true; } - if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()) + if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs() + && _host.ChangeCombatModeFor(CombatMode.Melee, "Combat", "stance")) { - _host.ChangeCombatMode(CombatMode.Melee); lastStanceAttempt = DateTime.Now; NoteStanceFlipSent(); } @@ -3931,7 +3965,6 @@ public partial class CombatManager : IDisposable _lastStanceRecoverAt = DateTime.Now; _stanceReEquipAttempts++; _host.Log($"[EquipDiag] STANCE STUCK {stuckMs:0}ms mode={CurrentCombatMode}≠{desiredMode} (wielded reads true) — re-equip attempt {_stanceReEquipAttempts}/{StanceReEquipMaxAttempts} 0x{targetWeaponId:X8}"); - if (_host.HasForceResetBusyCount) _host.ForceResetBusyCount(); _host.UseFor((uint)targetWeaponId, "Combat", "stance stuck: equip again"); _lastEquipTime = DateTime.Now; lastStanceAttempt = DateTime.MinValue; // let ChangeCombatMode re-fire next tick @@ -3948,10 +3981,10 @@ public partial class CombatManager : IDisposable _host.WriteToChat($"[RynthAi] Stance wedged: wand wielded but AC won't enter {(desiredMode == CombatMode.Magic ? "Magic" : "combat")} mode after {stuckMs / 1000:0}s. Re-equip stopped (was jamming item actions). Try /ra clearbusy, or relog if it persists.", 2); } - if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()) + if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs() + && _host.ChangeCombatModeFor(desiredMode, "Combat", "stance")) { if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=true mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource}) — sending ChangeCombatMode"); } - _host.ChangeCombatMode(desiredMode); lastStanceAttempt = DateTime.Now; NoteStanceFlipSent(); } @@ -3998,9 +4031,9 @@ public partial class CombatManager : IDisposable // mode bare-handed (throttled) and send no wield. if (!allowWield) { - if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()) + if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs() + && _host.ChangeCombatModeFor(desiredMode, "Combat", "stance")) { - _host.ChangeCombatMode(desiredMode); lastStanceAttempt = DateTime.Now; NoteStanceFlipSent(); } @@ -4035,10 +4068,10 @@ public partial class CombatManager : IDisposable // nothing when the wand genuinely isn't wielded: ACE just denies it, and the // gated UseObject below still does the wielding. Mirrors the non-wand branch, // which has always sent both. - if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()) + if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs() + && _host.ChangeCombatModeFor(desiredMode, "Combat", "stance")) { if (diagNow) _host.Log($"[EquipDiag] hand clear — ChangeCombatMode({desiredMode}) alongside wand equip (mode={CurrentCombatMode})"); - _host.ChangeCombatMode(desiredMode); lastStanceAttempt = DateTime.Now; NoteStanceFlipSent(); } @@ -4092,13 +4125,10 @@ public partial class CombatManager : IDisposable // OnCombatModeChange). Request both a mode change and an equip — these go in the // main hand, which AC swaps in place (no held-slot collision). ChangeCombatMode // succeeds if already wielded (fixes hot-reload next tick); UseObject equips it if not. - if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()) - { - if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=FALSE mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource} class={weaponObj.ObjectClass}) — ChangeCombatMode"); } - _host.ChangeCombatMode(desiredMode); - lastStanceAttempt = DateTime.Now; - NoteStanceFlipSent(); - } + // The wield goes first (2026-10-06): both went out within 3 ms (07:13:16.446/.453), a + // mode change on top of an unanswered action. With the pacing on, the mode change waits + // for the wield's answer (and once the weapon reads wielded, the wielded branch above + // sends it); off, both still go in this tick, as before. if (allowWield && (DateTime.Now - _lastEquipTime).TotalMilliseconds > 2000 && ClearOffhandFor(targetWeaponId, _curOffhandMode) == OffPrep.Ready // a shield off before a two-hander / launcher && (desiredMode != CombatMode.Missile || PrepareAmmoFor(targetWeaponId) == AmmoPrep.Ready) @@ -4109,6 +4139,13 @@ public partial class CombatManager : IDisposable MarkWieldSent(targetWeaponId, inHand); _lastEquipTime = DateTime.Now; } + if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs() + && _host.ChangeCombatModeFor(desiredMode, "Combat", "stance")) + { + if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=FALSE mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource} class={weaponObj.ObjectClass}) — ChangeCombatMode"); } + lastStanceAttempt = DateTime.Now; + NoteStanceFlipSent(); + } return false; } @@ -4225,9 +4262,9 @@ public partial class CombatManager : IDisposable // for good, even in Magic mode, so a Recall waypoint never cast and sat // out the whole portal timeout. if (CurrentCombatMode == CombatMode.Magic) { ResetStanceFlipBackoff(); return true; } - if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()) + if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs() + && _host.ChangeCombatModeFor(CombatMode.Magic, "Combat", "stance")) { - _host.ChangeCombatMode(CombatMode.Magic); lastStanceAttempt = DateTime.Now; NoteStanceFlipSent(); } @@ -4244,9 +4281,9 @@ public partial class CombatManager : IDisposable if (alreadyWielded) { if (CurrentCombatMode == CombatMode.Magic) { ResetWandSwapState(); ResetStanceFlipBackoff(); return true; } - if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()) + if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs() + && _host.ChangeCombatModeFor(CombatMode.Magic, "Combat", "stance")) { - _host.ChangeCombatMode(CombatMode.Magic); lastStanceAttempt = DateTime.Now; NoteStanceFlipSent(); } @@ -4770,7 +4807,7 @@ public partial class CombatManager : IDisposable try { - _host.CastSpell((uint)activeTargetId, spellId); + _host.CastSpellFor((uint)activeTargetId, spellId, "Combat", SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}"); MarkCombatCastIssued(); _lastSpellCast = DateTime.Now; _lastCastWasRing = false; @@ -4823,7 +4860,7 @@ public partial class CombatManager : IDisposable $"shape={ShapeName(castShape)} ring={isRing} warTier={warTier} voidTier={voidTier} target='{target.Name}'"); try { - _host.CastSpell((uint)activeTargetId, offensiveSpellId); + _host.CastSpellFor((uint)activeTargetId, offensiveSpellId, "Combat", SpellTableStub.GetById(offensiveSpellId)?.Name ?? $"spell {offensiveSpellId}"); MarkCombatCastIssued(); SessionAttackCasts++; // D6: offensive attack-cast tally for the casts-per-kill signal CastsSinceLastKill++; // reset in OnKillNotification when a kill lands diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/KillClock.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/KillClock.cs new file mode 100644 index 0000000..754fdb2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/KillClock.cs @@ -0,0 +1,126 @@ +using System; +using System.Threading; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// The one "time since our last kill" clock (2026-10-06). Read by the meta expression +/// secondssincelastkill[], the "No Kills Within Minutes" meta condition and the status feed's +/// secsSinceLastKill. +/// +/// A kill is ACE's KillerNotification (GameEvent 0x01AD), which the server sends only to the +/// killer: RynthAiPlugin.OnKillNotification is the only caller of . +/// Death messages in chat ("X died", a fellow's kill) never count. +/// +/// Before the first kill this session the clock counts from the last macro start, or, if the +/// macro hasn't been started since login, from login (a plugin load or hot reload counts as a +/// login), so a meta can still act on "no kills at all". After that it counts from the later of +/// the last kill and the last macro start: restarting the macro starts the count again. +/// +/// Monotonic (Environment.TickCount64, not the wall clock). Writers are the plugin pump thread; +/// the status feed reads from its poll thread, so every field is read and written with Interlocked. +/// +internal sealed class KillClock +{ + private const long None = long.MinValue; + + private readonly Func _nowMs; + private long _sessionStartMs; + private long _macroStartMs = None; + private long _lastKillMs = None; + private int _macroWasRunning; + + /// Monotonic milliseconds; tests pass a fake clock. + public KillClock(Func? nowMs = null) + { + _nowMs = nowMs ?? (static () => Environment.TickCount64); + _sessionStartMs = _nowMs(); + } + + /// Asked on every read, so a macro start is seen before the first condition after it. + /// The plugin also calls every tick. + public Func? MacroRunning { get; set; } + + /// Login (and plugin load): no kill yet, the clock counts from now. A macro that is + /// already on (start macro on login) counts as started now. + public void SessionStarted() + { + Interlocked.Exchange(ref _sessionStartMs, _nowMs()); + Interlocked.Exchange(ref _macroStartMs, None); + Interlocked.Exchange(ref _lastKillMs, None); + Interlocked.Exchange(ref _macroWasRunning, 0); + Observe(); + } + + /// Notes a macro start (off to on). Safe to call any number of times. + public void ObserveMacro(bool running) + { + int prev = Interlocked.Exchange(ref _macroWasRunning, running ? 1 : 0); + if (running && prev == 0) + Interlocked.Exchange(ref _macroStartMs, _nowMs()); + } + + /// We killed something (KillerNotification only). + public void RecordKill() => Interlocked.Exchange(ref _lastKillMs, _nowMs()); + + /// True once we have a kill this session. + public bool HasKill => Interlocked.Read(ref _lastKillMs) != None; + + /// What the clock counts from: "kill", "macro start" or "login". + public string Since + { + get + { + Observe(); + long kill = Interlocked.Read(ref _lastKillMs), macro = Interlocked.Read(ref _macroStartMs); + if (kill != None && kill >= macro) return "kill"; + return macro != None ? "macro start" : "login"; + } + } + + /// Milliseconds since our last kill (before the first: since the macro start, or login). Never negative. + public long ElapsedMs() + { + Observe(); + // The later of the last kill and the last macro start: a restart after a long pause + // starts the count again (Tom, 2026-10-06), so "no kills in 10 min" doesn't fire at once. + long from = Math.Max(Interlocked.Read(ref _lastKillMs), Interlocked.Read(ref _macroStartMs)); + if (from == None) from = Interlocked.Read(ref _sessionStartMs); + return Math.Max(0, _nowMs() - from); + } + + /// Whole seconds for secondssincelastkill[]. + public long SecondsSinceLastKill() => ElapsedMs() / 1000; + + /// Whole seconds since an actual kill, or -1 before the first (the status feed's value). + public int SecondsSinceKillOnly() + { + long kill = Interlocked.Read(ref _lastKillMs); + if (kill == None) return -1; + return (int)Math.Clamp((_nowMs() - kill) / 1000, 0, int.MaxValue); + } + + /// "No Kills Within Minutes": true when nothing was killed for at least + /// minutes (decimals allowed: 0.5 = 30 s). + public bool NoKillsFor(double minutes) => ElapsedMs() >= minutes * 60_000.0; + + /// The condition's value as typed in the editor or the .af file: minutes, decimals + /// allowed ("5", "2.5"; a comma decimal is accepted too). False for empty, negative or not a number. + public static bool TryParseMinutes(string? text, out double minutes) + { + minutes = 0; + if (string.IsNullOrWhiteSpace(text)) return false; + string t = text.Trim().Replace(',', '.'); + if (!double.TryParse(t, System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out double m)) return false; + if (double.IsNaN(m) || double.IsInfinity(m) || m < 0) return false; + minutes = m; + return true; + } + + private void Observe() + { + Func? probe = MacroRunning; + if (probe != null) ObserveMacro(probe()); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs index 5615fff..aa06156 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs @@ -223,7 +223,7 @@ public class MissileCraftingManager _combinesCompleted = 0; _allCombinesDone = false; - try { _host.ChangeCombatMode(CombatMode.NonCombat); } catch { } + try { _host.ChangeCombatModeFor(CombatMode.NonCombat, "Crafting", "missile crafting needs peace mode"); } catch { } var headItems = inv.Where(i => recipe.IsHead(i.Name)).ToList(); var shaftItems = inv.Where(i => recipe.IsShaft(i.Name)).ToList(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs index b0fdbbe..5ad5396 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs @@ -60,6 +60,16 @@ internal sealed class PetManager // get parked so we advance to the next configured essence instead of looping. private readonly Dictionary _deviceCooldownUntil = new(); + // The server's word over a stale Structure read (2026-10-05). A read + // can say 0 while the server holds a full essence; the server then answers a refill with + // "already full" (or refills it and the read still lags), and deciding from the read alone + // re-issued the refill every think tick: peace mode and a clap each time, a spirit each time + // the refill was real. Essence -> until when its read of 0 is not believed; cleared when a + // summon reports "not enough charges". + private readonly Dictionary _serverSaidFullUntil = new(); + // Refills issued per essence: how many since the window opened, and when it opened. + private readonly Dictionary _refills = new(); + // Encapsulated Spirit — the fixed retail recharge item (WCID 49485). Detected // by name; it is never itself a summon device. private const string EncapsulatedSpiritName = "Encapsulated Spirit"; @@ -69,11 +79,17 @@ internal sealed class PetManager private const long AssumeActiveAfterSummonMs = 10_000; private const long DeviceFailCooldownMs = 30_000; private const long DeviceNoSpiritCooldownMs = 15_000; + private const long ServerSaidFullTrustMs = 30 * 60_000; + private const long RefillWindowMs = 120_000; // two refills inside this and the + private const int RefillsPerWindow = 2; // essence still reads empty: + private const long RefillLoopParkMs = 300_000; // park it this long private string _playerName = string.Empty; private long _playerNameAt; - 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(); public PetManager(RynthCoreHost host, LegacyUiSettings settings, WorldObjectCache objectCache, CombatManager? combat, @@ -159,6 +175,7 @@ internal sealed class PetManager if (text.Contains("enough charges", StringComparison.OrdinalIgnoreCase)) { _host.Log($"[RynthAi] Pet: essence 0x{(uint)_activeDeviceId:X8} reports empty; will refill."); + _serverSaidFullUntil.Remove(_activeDeviceId); // really empty: the read is right again GoIdle(); return; } @@ -168,10 +185,13 @@ internal sealed class PetManager if (_state == PetState.Refilling) { // "You add the spirit to the essence." (success) / "This essence is - // already full." (our Structure read was stale — also done). - if (text.Contains("add the spirit to the essence", StringComparison.OrdinalIgnoreCase) - || text.Contains("essence is already full", StringComparison.OrdinalIgnoreCase)) + // already full." (our Structure read was stale — also done). Either way the + // essence is full now, whatever its read says until the next update. + bool added = text.Contains("add the spirit to the essence", StringComparison.OrdinalIgnoreCase); + bool full = !added && text.Contains("essence is already full", StringComparison.OrdinalIgnoreCase); + if (added || full) { + OnServerSaidFull(_activeDeviceId, added); GoIdle(); } } @@ -203,6 +223,12 @@ internal sealed class PetManager int charges = ReadCharges(deviceId); // -1 = unreadable + // The server called this essence full after the read last changed: the 0 is stale. + // Summon as for an unreadable one (an empty essence is refused harmlessly, and that + // "not enough charges" ends the trust). + if (charges == 0 && ServerSaidFull(deviceId, now)) + charges = -1; + if (charges != 0) { // Has charges (or unreadable → attempt; an empty one is rejected @@ -215,11 +241,13 @@ internal sealed class PetManager if (_settings.PetAutoRefill) { int spiritId = FindEncapsulatedSpirit(); - if (spiritId != 0) + if (spiritId != 0 && !RefillLooping(deviceId, now)) { IssueRefill(deviceId, spiritId); return; } + if (spiritId != 0) + continue; // parked by RefillLooping; try the next essence } // Out of charges and no spirit (or refill off): park this essence @@ -251,10 +279,57 @@ internal sealed class PetManager _activeDeviceId = deviceId; _activeSpiritId = spiritId; _actionIssuedAt = NowMs; + CountRefill(deviceId, _actionIssuedAt); _host.Log($"[RynthAi] Pet: refilling essence 0x{(uint)deviceId:X8} with spirit 0x{(uint)spiritId:X8}."); _host.UseOnFor(unchecked((uint)spiritId), unchecked((uint)deviceId), "Pet", "refill the essence with a spirit"); } + /// + /// The server said the essence is full ("You add the spirit..." / "...already full"): its + /// read of 0 is not believed for a while, and it is re-identified so the read catches up. + /// + private void OnServerSaidFull(int deviceId, bool refilled) + { + if (deviceId == 0) return; + _serverSaidFullUntil[deviceId] = NowMs + ServerSaidFullTrustMs; + if (_host.HasRequestId) _host.RequestId(unchecked((uint)deviceId)); + _host.Log(refilled + ? $"[RynthAi] Pet: refill complete (essence 0x{(uint)deviceId:X8}, server confirmed)." + : $"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} is already full (its charge read was stale); summoning from it."); + } + + private bool ServerSaidFull(int deviceId, long now) + { + if (!_serverSaidFullUntil.TryGetValue(deviceId, out long until)) return false; + if (now < until) return true; + _serverSaidFullUntil.Remove(deviceId); + return false; + } + + private void CountRefill(int deviceId, long now) + { + if (_refills.TryGetValue(deviceId, out var r) && now - r.Since < RefillWindowMs) + _refills[deviceId] = (r.Count + 1, r.Since); + else + _refills[deviceId] = (1, now); + } + + /// + /// True, and the essence parked, when it was refilled times + /// inside and still reads empty: another refill would only cost + /// a spirit and force peace mode again. An essence holds dozens of summons, so two real + /// refills that close together don't happen. + /// + private bool RefillLooping(int deviceId, long now) + { + if (!_refills.TryGetValue(deviceId, out var r) || now - r.Since >= RefillWindowMs || r.Count < RefillsPerWindow) + return false; + _refills.Remove(deviceId); + _deviceCooldownUntil[deviceId] = now + RefillLoopParkMs; + _host.Log($"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} was refilled {r.Count}x in {(now - r.Since) / 1000}s and still reads empty; parking it for {RefillLoopParkMs / 60_000} min."); + return true; + } + private void GoIdle() { _state = PetState.Idle; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs index f3452a9..4c4d384 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs @@ -174,6 +174,26 @@ public class SpellManager _ => "I" }; + /// + /// The LOWEST known tier of above the buff tier the skill + /// allows, 0 when none. For heals when nothing at or under the allowed tier is known: vitae + /// can drop Life Magic under a tier line while the character only knows higher tiers, and a + /// heal that may fizzle beats none (Drakkon died twice, 2026-10-06). + /// + public int GetSelfSpellIdAboveAllowedTier(string baseSpellName, AcSkillType magicSkill) + { + RefreshKnownSpells(); + int maxTier = GetHighestBuffSpellTier(magicSkill); + string cleanBase = baseSpellName.Replace(" Self", "").Trim(); + BaseNameAliases.TryGetValue(cleanBase, out string? alias); + for (int tier = maxTier + 1; tier <= 8; tier++) + { + if (TryGetTierId(cleanBase, tier, out int id)) return id; + if (alias != null && TryGetTierId(alias, tier, out int idAlias)) return idAlias; + } + return 0; + } + public int GetDynamicSelfBuffId(string baseSpellName, AcSkillType magicSkill) { RefreshKnownSpells(); // keep the authoritative inventory current (throttled) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs index a54df62..e0fb827 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs @@ -601,17 +601,17 @@ public class WorldObjectCache return; } - // Non-creature with a position — could be equipped item on 0x8000 range - // or static world object; classify by type flags - if ((typeFlags & (ItemTypeMeleeWeapon | ItemTypeMissileWeapon | ItemTypeCaster | ItemTypeArmor | ItemTypeContainer)) != 0) - { - // Item with a world position = equipped or ground-dropped - cls = ClassifyItem(uid, typeFlags); - _inventory.Add(id); - _landscape.Remove(id); - _byId[id] = Make(id, name, cls); + // Non-creature with a position and a known item type: equipped gear, a ground + // drop, a chest. It gets the class its type gives and is filed by who has it + // (FileTypedObject). Only weapons, armor, casters and containers were taken + // here before, all into the inventory: keys, gems, comps, food and the like + // stayed Unknown landscape and were re-probed every 2 s for good, and other + // players' wielded gear and ground-dropped weapons counted as ours + // (2026-10-05). A static object that isn't a chest or a lifestone returns + // false and stays Unknown scenery below, hazard check included. + AcObjectClass typedCls = ClassifyItem(uid, typeFlags); + if (typedCls != AcObjectClass.Unknown && FileTypedObject(uid, id, name, typedCls, typeFlags)) return; - } } else if (uid >= 0x80000000u) { @@ -660,6 +660,77 @@ public class WorldObjectCache } } + private const uint ItemTypeGear = ItemTypeMeleeWeapon | ItemTypeMissileWeapon | ItemTypeCaster | ItemTypeArmor | ItemTypeContainer; + + private enum Holder { Unknown, Player, OtherWielder, OtherContainer, Nobody } + + /// + /// Who has the object: the player (wielded, in the main pack, or in a side pack), another + /// wielder (other players' and NPCs' gear), another container (a corpse, a chest), or + /// nobody (it lies on the ground). Unknown when the player isn't known yet or the engine + /// can't read the object's ownership. Caller holds _gate. + /// + private Holder WhoHas(int id) + { + if (_playerId == 0 || !TryGetOwnership(id, out int containerId, out int wielderId, out _)) + return Holder.Unknown; + uint container = unchecked((uint)containerId), wielder = unchecked((uint)wielderId); + if (wielder == _playerId || container == _playerId) return Holder.Player; + if (wielder != 0) return Holder.OtherWielder; + if (container == 0) return Holder.Nobody; + // Side packs sit in the main pack (AC has no deeper nesting). + return TryGetOwnership(containerId, out int outer, out _, out _) && unchecked((uint)outer) == _playerId + ? Holder.Player : Holder.OtherContainer; + } + + /// + /// Files a positioned non-creature whose item type gave it a real class. Caller holds _gate. + /// + /// A lifestone: landscape. + /// Another static object: a chest goes on the landscape; anything else returns false + /// and the caller keeps it Unknown scenery (doors, signs, static hotspots). + /// A dynamic object the player has: inventory. One another player or an NPC wields: + /// neither list (known by id only), so it is not ours, not a ground item on the radar and + /// not something a meta can pick up. In another container or loose on the ground: landscape. + /// Ownership unreadable: gear goes to the inventory as before, the rest to the landscape. + /// + /// A non-gear object that lands on the landscape gets the hazard check it had as Unknown + /// (a hotspot spawned with a dynamic id and a Misc type is still a hazard). + /// + private bool FileTypedObject(uint uid, int id, string name, AcObjectClass cls, uint typeFlags) + { + bool gear = (typeFlags & ItemTypeGear) != 0; + bool toInventory, toLandscape; + if (cls == AcObjectClass.Lifestone) + { + toInventory = false; + toLandscape = true; + } + else if (uid < 0x80000000u) + { + if ((typeFlags & ItemTypeContainer) == 0) return false; + toInventory = false; + toLandscape = true; + } + else + { + Holder holder = WhoHas(id); + toInventory = holder == Holder.Player || (holder == Holder.Unknown && gear); + toLandscape = !toInventory && holder != Holder.OtherWielder; + } + + _classifyRetry.Remove(uid); + _reclassifySkipState.Remove(uid); + if (toInventory) { if (_inventory.Add(id)) _inventoryDirty = true; } + else if (_inventory.Remove(id)) _inventoryDirty = true; + if (toLandscape) _landscape.Add(id); + else _landscape.Remove(id); + _byId[id] = Make(id, name, cls); + if (toLandscape && !gear) + MaybeRegisterHazard(uid, name); + return true; + } + // PublicWeenieDesc._bitfield BF_CORPSE (ObjectDescriptionFlag.Corpse). private const uint BfCorpse = 0x2000; @@ -725,6 +796,7 @@ public class WorldObjectCache List? toPromote = null; List? toCorpse = null; List<(int id, string name, AcObjectClass cls)>? statics = null; + List<(int Id, uint Flags)>? typed = null; // Unknowns whose item type now gives a class foreach (int id in _landscape) { uint uid = unchecked((uint)id); @@ -754,7 +826,11 @@ public class WorldObjectCache // Bounded to Monster/Unknown so we don't name-query every ground // item each pass; IsCorpseName is specific ("X corpse"/"Corpse of X") // so a live mob cannot be misread as a corpse. - if ((wo.ObjectClass == AcObjectClass.Monster || wo.ObjectClass == AcObjectClass.Unknown) + // Container too: a corpse typed before its name or flag was readable is filed as a + // landscape Container by FileTypedObject (it used to go to the inventory, which the + // inventory pass below re-checks). + if ((wo.ObjectClass == AcObjectClass.Monster || wo.ObjectClass == AcObjectClass.Unknown + || wo.ObjectClass == AcObjectClass.Container) && ((_host.TryGetObjectName(uid, out string maybeCorpse) && IsCorpseName(maybeCorpse)) || HasCorpseFlag(uid))) { @@ -771,14 +847,21 @@ public class WorldObjectCache // immediate signal that doesn't wait on qualities/appraisal). This // second path is what rescues a login mob within 2s if it slipped // to Unknown before its weenie/combat-state was readable. - bool isCreature = _host.TryGetItemType(uid, out uint typeFlags) - && (typeFlags & ItemTypeCreature) != 0; + bool gotType = _host.TryGetItemType(uid, out uint typeFlags); + bool isCreature = gotType && (typeFlags & ItemTypeCreature) != 0; if (!isCreature && _host.HasObjectIsAttackable && _host.ObjectIsAttackable(uid)) isCreature = true; if (!isCreature) { + // Its type arrived after it was classified: file it as the item it is instead + // of probing it again every pass. Done after the loop (filing edits _landscape). + if (gotType && typeFlags != 0 && ClassifyByItemType(typeFlags) != AcObjectClass.Unknown) + { + (typed ??= new()).Add((id, typeFlags)); + continue; + } DiagLogReclassifySkip(uid, wo.Name); continue; } @@ -832,10 +915,27 @@ public class WorldObjectCache _host.Log($"[RynthAi] ReclassifyUnknownDynamics: rescued {toCorpse.Count} stale corpse(s) → Corpse"); } + if (typed != null) + { + int filed = 0, intoInventory = 0; + foreach (var (id, flags) in typed) + { + if (!_byId.TryGetValue(id, out var wo)) continue; + uint uid = unchecked((uint)id); + AcObjectClass cls = ClassifyItem(uid, flags); + if (cls == AcObjectClass.Unknown || !FileTypedObject(uid, id, wo.Name ?? string.Empty, cls, flags)) continue; + filed++; + if (_inventory.Contains(id)) intoInventory++; + } + if (filed > 0) + _host.Log($"[RynthAi] ReclassifyUnknownDynamics: typed {filed} Unknown object(s) as items ({intoInventory} into the inventory)"); + } + // DIAG: heartbeat — Unknown landscape candidates checked but nothing promoted // this pass. Confirms ReclassifyUnknownDynamics is running and engine signals // keep failing for the stuck uids (vs. them never reaching _landscape at all). if (toPromote == null + && typed == null && _reclassifySkipState.Count > 0 && _reclassifyDiagSummaryCount < MaxReclassifyDiagSummaries) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index 0e7da6c..efab96a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -104,7 +104,9 @@ public sealed partial class RynthAiPlugin private long _corpseIdsRequestedAt; private bool _corpseApproachTurnsActive; - private static long CorpseNowMs => Environment.TickCount64; + /// The loot clock (ms); the host tests replace it to run minutes of looting at once. + internal static Func CorpseClock = static () => Environment.TickCount64; + private static long CorpseNowMs => CorpseClock(); private void LootDiag(string message) { Log(message); @@ -142,8 +144,49 @@ public sealed partial class RynthAiPlugin // busy-zero churn) paced the whole loot grind, and the 2026-06-12 09:33 // storm of them latched the variant-2 stance/item deadlock. private const long BUSY_TIMEOUT_COMBAT_URGENT_MS = 5_000; + // The engine's count is the one owner (2026-10-06; analysis by Silentkelpie, re-implemented + // here): this mirror is fed by the engine's busy events, and the engine now sends one for + // every UseDone and every reset it does, so the two agree except for events still on their + // way. A disagreement that lasts BusyMirrorFollowMs is settled the engine's way; the old + // 5/10 s mirror reset below is only for an engine without GetBusyState. + private const long BusyMirrorFollowMs = 1_500; + private long _busyMismatchSince; + private long _lastBusyFollowLogAt; + private int _busyFollowsSinceLog; + + private bool FollowEngineBusyCount() + { + if (!Host.HasGetBusyState) return false; + int engine; + try { engine = Host.GetBusyState(); } catch { return false; } + long now = CorpseNowMs; + if (engine == _busyCount) { _busyMismatchSince = 0; return true; } + if (_busyMismatchSince == 0) { _busyMismatchSince = now; return true; } + if (now - _busyMismatchSince < BusyMirrorFollowMs) return true; + int was = _busyCount; + _busyMismatchSince = 0; + _busyCount = Math.Max(0, engine); + _busyCountLastIncrementAt = 0; + _busyCountBecamePositiveAt = _busyCount > 0 ? now : 0; + if (_combatManager != null) _combatManager.BusyCount = _busyCount; + if (_buffManager != null) _buffManager.BusyCount = _busyCount; + _busyFollowsSinceLog++; + if (now - _lastBusyFollowLogAt >= 10_000) + { + Log($"[RynthAi] Busy mirror {was} -> {_busyCount}: following the engine's count ({_busyFollowsSinceLog} in the last {(now - _lastBusyFollowLogAt) / 1000.0:0} s; the client's count is never cleared by RynthAi)."); + _lastBusyFollowLogAt = now; + _busyFollowsSinceLog = 0; + } + return true; + } + private void CheckBusyTimeout() { + if (FollowEngineBusyCount()) + { + PruneCorpseCollections(); + return; + } if (_busyCount > 0 && _busyCountBecamePositiveAt != 0) { long elapsed = CorpseNowMs - _busyCountBecamePositiveAt; @@ -176,10 +219,17 @@ public sealed partial class RynthAiPlugin if (elapsed > threshold) { - Log($"[RynthAi] Busy count stuck at {_busyCount} for >{elapsed}ms (combatUrgent={combatUrgent} lootOpenUrgent={lootOpenUrgent} castGesture={castGestureInProgress}) — force-clearing."); - // Reset pending loot item BEFORE zeroing AC's m_cBusy. If we have an - // in-flight UseObject, ForceResetBusyCount zeros m_cBusy under it; the - // retry in TickPendingCorpsePickup would then hit a freed AC object and crash. + // Our mirror only (2026-10-06). AC's m_cBusy is +1 per action the client sends and + // -1 per server UseDone (ClientUISystem::Handle_Item::UseDone, inline - which is why + // this mirror, fed by the Increment/Decrement hooks, never saw the decrement and + // looked "stuck"). Force-clearing AC's count here zeroed the count of actions the + // server had not answered yet (each later UseDone then drove it negative: ~190 + // repairs an hour in the 10-05/10-06 logs) and let the next action out on top of + // them. The pacing waits on the server's answers now (ActionPacer); the client's + // own count is left to the client and the engine. + bool serverWaiting = RynthCore.Plugin.Shared.ActionPacer.Current(Host) != null; + Log($"[RynthAi] Busy mirror at {_busyCount} for >{elapsed}ms (combatUrgent={combatUrgent} lootOpenUrgent={lootOpenUrgent} castGesture={castGestureInProgress}" + + $"{(serverWaiting ? ", a server action is still unanswered" : "")}) — resetting the mirror only (the client's count is left alone)."); ResetCurrentLootItem(); _corpseIdsRequested = false; _lastLootActionAt = CorpseNowMs; @@ -188,7 +238,6 @@ public sealed partial class RynthAiPlugin _busyCountBecamePositiveAt = 0; if (_combatManager != null) _combatManager.BusyCount = 0; if (_buffManager != null) _buffManager.BusyCount = 0; - if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount(); } } @@ -350,6 +399,8 @@ public sealed partial class RynthAiPlugin } LootDiag($"[RynthAi] Corpse loot: opened container 0x{objectId:X8}."); _consecutiveLootTimeouts = 0; // a successful open proves AC is responsive again + _lootWedgeAnnounced = false; + ApplyUseRefusalVerdict(_useRefusals.OnOpened(CorpseNowMs), CorpseNowMs); if (switchedTarget) LootDiag($"[RynthAi] Corpse loot: switching active corpse target from 0x{(uint)_targetCorpseId:X8} to 0x{objectId:X8}."); @@ -476,7 +527,12 @@ public sealed partial class RynthAiPlugin // timeouts). Stop firing opens into a dead client until the halt window // elapses — hammering it can't recover a server-side lock, only a relog // can. Navigation/combat (non-item-action) still run elsewhere. - if (CorpseNowMs < _lootHaltUntil) + // The use-refusal watch first: it reads the server's answers to our opens, and while it + // has decided the server refuses every use (Stuck) no corpse is claimed or opened until + // its back-off ends. + long haltNow = CorpseNowMs; + TickUseRefusalWatch(haltNow); + if (haltNow < _lootHaltUntil || _useRefusals.HoldsOpens(haltNow)) return; // ── Buffing: halt loot work but retain target so looting resumes immediately ── @@ -613,6 +669,29 @@ public sealed partial class RynthAiPlugin return; } + // An open goes out only once the arbiter has given Looting the tick. A corpse claimed on + // the tick a fight ended (Combat still owned it) used to be opened at once, and the + // arbiter's nav stop (StopCompletely) and Combat's idle peace-mode swap followed 3-30 ms + // later. On ACE both cancel the server's walk/turn to the corpse - a mode change runs + // HandleActionCancelAttack -> cancel_moveto - so that open could only fail (2026-10-06 + // 06:18:44, the first failed open of the day's stall). One tick later the stop goes + // out first (PauseNavigationForCorpse) and the open after it. + if (_activity != BotActivity.Looting) + return; + + // One server action at a time (2026-10-06, ActionPacer): no open while the server is still + // answering another action - a kit, a cast, a stance change, or the last open itself (a + // re-sent open restarts the server's walk and fails the first one's callback). The claim's + // 12 s timeout keeps running (the longest wait here is the 5 s limit on an open). + if (!ActionPacer.MayStart(Host, "Loot", HealNeed.None, out _)) + return; + // The last corpse's close is not answered yet (CloseGroundContainer, ~40 ms): a use now makes + // the client send its own NoLongerViewingContents for that corpse too (flight recorder + // 2026-10-06 07:57:09.801: the engine's close, then the client's, beside the next use). + if (_closeSentFor != 0 && _closeSentFor != _targetCorpseId && now - _closeSentAt < CloseAnswerWaitMs + && Host.HasGetGroundContainerId && unchecked((int)Host.GetGroundContainerId()) == _closeSentFor) + return; + // Farther than reach: just use the corpse. The server walks the character to it and turns // it (as a player's double-click does); steering there ourselves looked awkward and // turned slowly (owner, 2026-10-04). Our own movement stays off so it can't cancel that @@ -625,8 +704,8 @@ public sealed partial class RynthAiPlugin if (_lastCorpseOpenAttemptAt == 0 || now - _lastCorpseOpenAttemptAt >= walkMs) { if (_busyCount > 0 && now - _lastCorpseOpenAttemptAt < OpenBusyWaitMaxMs) return; - AttemptOpenCorpse(_targetCorpseId); - _lastCorpseOpenAttemptAt = now; + if (AttemptOpenCorpse(_targetCorpseId)) + _lastCorpseOpenAttemptAt = now; } return; } @@ -651,8 +730,8 @@ public sealed partial class RynthAiPlugin return; // busy — hold the open briefly } _corpseOpenBusyWaitSince = 0; - AttemptOpenCorpse(_targetCorpseId); - _lastCorpseOpenAttemptAt = now; + if (AttemptOpenCorpse(_targetCorpseId)) + _lastCorpseOpenAttemptAt = now; } } @@ -1299,6 +1378,7 @@ public sealed partial class RynthAiPlugin ChatLine($"[RynthAi] Loot rule: {matchItemName} -> [{matchActionLabel}] {matchRuleLabel}"); _currentLootItemId = firstMatchId; + RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)firstMatchId)); Host.SelectItem(unchecked((uint)firstMatchId)); LootDiag($"[RynthAi] Corpse loot: picking up 0x{(uint)firstMatchId:X8} '{matchItemName}' from corpse 0x{(uint)corpseId:X8}."); @@ -1412,6 +1492,7 @@ public sealed partial class RynthAiPlugin if (_busyCount > 0) return; // Client is busy — don't queue retry + RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)_currentLootItemId)); Host.SelectItem(unchecked((uint)_currentLootItemId)); LootPickupResult retry = SendLootPickup(_currentLootItemId, _currentLootItemName, _openedContainerId); if (retry == LootPickupResult.NoRoom || retry == LootPickupResult.Refused) @@ -1546,6 +1627,11 @@ public sealed partial class RynthAiPlugin if (!settings.IsMacroRunning || !settings.EnableLooting) return false; + // The server refuses every use (UseRefusalWatch, Stuck): no loot work until the back-off + // ends, so the arbiter lets nav and combat run on instead of standing at the corpses. + if (_openedContainerId == 0 && _useRefusals.HoldsOpens(CorpseNowMs)) + return false; + // Already committed to a body, or mid-loot with the container open. if (_openedContainerId != 0 || _targetCorpseId != 0 || _corpseAutorunActive) { @@ -1993,10 +2079,6 @@ public sealed partial class RynthAiPlugin if (_manaStoneManager == null) return false; if (!Host.HasGetObjectIntProperty) return false; - // ACE won't drain a wand, staff or orb into a stone, so ManaStoneManager never taps - // one (and its pending-drain count skips them, so the quota never filled): every - // high-mana wand was looted and kept for good. Drakkon's "Piercing Sceptre", 2026-10-05. - if (ManaStoneManager.IsWandLike(item)) return false; int threshold = settings.ManaTapMinMana; if (threshold <= 0) return false; @@ -2297,13 +2379,142 @@ public sealed partial class RynthAiPlugin // or a corpse the bot never reached?). private int _lastOpenAttemptCorpseId; - private void AttemptOpenCorpse(int corpseId) + /// Sends one open. False when the use-refusal watch acted instead (nothing sent). + private bool AttemptOpenCorpse(int corpseId) { + long now = CorpseNowMs; + bool watch = Host.HasUseDoneSeq; + if (watch) + { + // The previous open, answered with nothing opened, is judged before this one goes out: + // a clean stop or a back-off must not land right after a fresh use (it would cancel it). + var verdict = _useRefusals.SettleBeforeOpen(now); + if (verdict != UseRefusalWatch.Verdict.None) + { + ApplyUseRefusalVerdict(verdict, now); + return false; + } + } + _lastOpenAttemptCorpseId = corpseId; StopCorpseMovement(); + int seqBefore = watch ? Host.GetUseDoneSeq() : 0; Host.SelectItem(unchecked((uint)corpseId)); - Host.UseFor(unchecked((uint)corpseId), "Loot", "open the claimed corpse"); + bool sent = Host.UseFor(unchecked((uint)corpseId), "Loot", "open the claimed corpse"); + if (watch && sent) + _useRefusals.OnOpenSent(corpseId, now, seqBefore); LootDiag($"[RynthAi] Corpse loot: attempting open for 0x{(uint)corpseId:X8}."); + return true; + } + + // ── Server refuses every use (2026-10-06; Loot/UseRefusalWatch.cs) ───────────────────── + private readonly UseRefusalWatch _useRefusals = new(); + private bool _useStuckAnnounced; + private bool _lootWedgeAnnounced; + + /// Every tick while looting runs: the server's answers to our opens. + private void TickUseRefusalWatch(long now) + { + if (!Host.HasUseDoneSeq) + return; + int seq = Host.GetUseDoneSeq(); + bool haveErr = Host.TryGetLastUseDone(out int lastSeq, out uint err) && lastSeq == seq; + ApplyUseRefusalVerdict(_useRefusals.OnTick(now, seq, err, haveErr), now); + } + + private void ApplyUseRefusalVerdict(UseRefusalWatch.Verdict verdict, long now) + { + switch (verdict) + { + case UseRefusalWatch.Verdict.CleanStopAndRetry: + { + FlightRecorderSignal.Dump(Host, "use check: corpse opens answered but not opened"); + Log($"[RynthAi] Use check: {_useRefusals.Refusals} corpse opens in a row were answered by the server but nothing opened ({RefusedList()}) - one clean stop, a {UseRefusalWatch.CleanStopPauseMs} ms pause, then one more try."); + Host.SetAutoRunBy("Loot/UseCheck", false); + if (Host.HasStopCompletely) + Host.StopCompletelyBy("Loot/UseCheck"); + _corpseAutorunActive = false; + _corpseApproachTurnsActive = false; + // Face the corpse for the retry. Since 2026-10-04 the bot leaves the turn to the + // server; if the server can't turn the character any more, a corpse already in + // front may still open (mid-stall, 06:28:19, a use by hand with the macro off + // opened one - the only open in those 13 minutes; whether it was faced isn't logged). + if (_targetCorpseId != 0 && Host.HasTurnToHeading + && TryGetHeadingToObject(_targetCorpseId, out double faceDeg, out double faceErr, out _) + && faceErr > 2.0) + { + Host.TurnToHeadingBy("Loot/UseCheck", (float)faceDeg); + Log($"[RynthAi] Use check: facing 0x{(uint)_targetCorpseId:X8} ({faceErr:0} deg off) for the retry."); + } + _lootHaltUntil = Math.Max(_lootHaltUntil, now + UseRefusalWatch.CleanStopPauseMs); + _lastCorpseOpenAttemptAt = 0; // the retry goes out as soon as the pause ends + if (_targetCorpseId != 0) + _corpseTargetSince = now; // and gets a full corpse timeout + break; + } + case UseRefusalWatch.Verdict.DropCorpse: + { + int id = _useRefusals.LastRefusedCorpse; + Log($"[RynthAi] Use check: corpse 0x{(uint)id:X8} is answered but never opens - giving up on it; the next corpse tells whether every use is refused."); + if (id != 0 && _targetCorpseId == id && _openedContainerId == 0) + AbandonCurrentCorpse(now, "refused"); + else if (id != 0) + _corpseCooldownUntil[id] = now + NeverOpenedAbandonRetryMs; + break; + } + case UseRefusalWatch.Verdict.Stuck: + { + FlightRecorderSignal.Dump(Host, "use check: server refuses every use"); + Log($"[RynthAi] Use check: the server answers every use but nothing opens ({_useRefusals.Refusals} refusals on {RefusedList()}), the clean stop and retry didn't help - looting paused {_useRefusals.BackoffMs / 60_000} min, then one corpse is tried again."); + if (!_useStuckAnnounced) + { + _useStuckAnnounced = true; + ChatLine($"[RynthAi] The server isn't letting this character use objects; a relog fixes it. Looting is paused and tried again every few minutes."); + } + ResetCorpseTarget(); + break; + } + case UseRefusalWatch.Verdict.StillStuck: + Log($"[RynthAi] Use check: still refused - next try in {_useRefusals.BackoffMs / 60_000} min."); + ResetCorpseTarget(); + break; + case UseRefusalWatch.Verdict.Recovered: + Log("[RynthAi] Use check: a corpse opened - uses work again, looting resumes."); + if (_useStuckAnnounced) + ChatLine("[RynthAi] Objects open again; looting is back on."); + _useStuckAnnounced = false; + break; + } + } + + private string RefusedList() => + string.Join(", ", _useRefusals.RefusedCorpses.Select(id => $"0x{(uint)id:X8}")); + + // The arbiter's wantLoot of the current tick (HasLootWork), for LootHoldsIdlePeace. + private bool _lastWantLoot; + + /// + /// CombatManager's idle peace-mode swap waits while looting has work: a corpse to claim, a + /// claimed or open corpse, or a door/corpse use the server is still answering. On ACE a + /// combat-mode change cancels the server's walk/turn to a used corpse (HandleActionCancelAttack + /// -> cancel_moveto), so the swap that went out 3 ms after the 06:18:44 open (2026-10-06) made + /// it fail; and between kills in a busy spawn it flipped peace/war every few seconds. Opening a + /// corpse needs no peace mode; the swap happens once looting is done. + /// + private bool LootHoldsIdlePeace() => + _targetCorpseId != 0 + || _openedContainerId != 0 + || _lastWantLoot + || RynthCore.Plugin.Shared.UseAudit.WorldUseInFlight(Host, out _); + + /// A fresh session (logout/login): a relog is what clears a server that refuses uses. + private void ResetUseRefusalState() + { + _useRefusals.Reset(); + _useStuckAnnounced = false; + _lootWedgeAnnounced = false; + _consecutiveLootTimeouts = 0; + _lootHaltUntil = 0; } private void SyncCorpseContainerState() @@ -2542,6 +2753,11 @@ public sealed partial class RynthAiPlugin /// which closes the window and brings OnStopViewingObjectContents. Older engines: nothing /// (the server closes the corpse when the next one is opened, as before). /// + // The last close sent, until the server's CloseGroundContainer answers it (see TickCorpseOpening). + private int _closeSentFor; + private long _closeSentAt; + private const long CloseAnswerWaitMs = 500; + private void CloseCorpseContainer(int corpseId, string why) { if (corpseId == 0 || !Host.HasCloseContainer) @@ -2553,7 +2769,11 @@ public sealed partial class RynthAiPlugin return; if (Host.CloseContainer(unchecked((uint)corpseId))) + { + _closeSentFor = corpseId; + _closeSentAt = CorpseNowMs; LootDiag($"[RynthAi] Corpse loot: closing 0x{(uint)corpseId:X8} ({why})."); + } else LootDiag($"[RynthAi] Corpse loot: close of 0x{(uint)corpseId:X8} not sent ({why})."); } @@ -2583,7 +2803,7 @@ public sealed partial class RynthAiPlugin long ageMs = _corpseTargetSince != 0 ? now - _corpseTargetSince : 0; LootDiag($"[RynthAi] Corpse loot: abandoning corpse 0x{(uint)corpseId:X8} after {ageMs}ms ({reason})."); - ChatLine($"[RynthAi] Corpse timeout: giving up on 0x{(uint)corpseId:X8} after {ageMs}ms."); + ChatLine($"[RynthAi] Corpse {(reason == "refused" ? "refuses to open" : "timeout")}: giving up on 0x{(uint)corpseId:X8} after {ageMs}ms."); // Only a corpse we actually OPENED earns the completed mark (30-min // do-not-touch — its loot is permanently skipped). A never-opened @@ -2655,13 +2875,19 @@ public sealed partial class RynthAiPlugin /// private void HandleLootWedge(long now) { + FlightRecorderSignal.Dump(Host, "loot wedge"); _lootHaltUntil = now + LootWedgeHaltMs; _consecutiveLootTimeouts = 0; // re-arm; if still wedged it trips again after the halt if (Host.HasCancelAttack) Host.CancelAttack(); - if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat); + // Peace only when not already in it (2026-10-06): an unneeded request went to the server as + // a raw 0x53 anyway, and on ACE a mode change cancels whatever walk/turn is pending. Not + // while a server action is unanswered either (ChangeCombatModeFor holds it then). + Host.ChangeCombatModeFor(CombatMode.NonCombat, "Loot/Wedge", "loot wedge reset"); if (Host.HasStopCompletely) Host.StopCompletelyBy("Loot/Wedge"); - if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount(); + // No ForceResetBusyCount (2026-10-06): AC's busy count is the count of actions the server + // has not answered; zeroing it fixed nothing here (the lock is the server's or the + // client's item-request gates below) and let the next action out on top of them. // The lock is client-side: AC's pending-item-request slot or attacking // flag (see the engine's ClientActionGates). Open both now. if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc unlockactions"); @@ -2671,7 +2897,12 @@ public sealed partial class RynthAiPlugin if (_combatManager != null) _combatManager.BusyCount = 0; if (_buffManager != null) _buffManager.BusyCount = 0; - ChatLine($"[RynthAi] WEDGE: {LootWedgeThreshold} corpse opens timed out — AC item-actions are locked. Halting looting {LootWedgeHaltMs / 1000}s and unlocking. If equip/loot stays stuck, /rc actionstate shows what the client is waiting on."); + // Once per stall (until a corpse opens): 2026-10-06 it fired 11 times in 13 minutes. + if (!_lootWedgeAnnounced) + { + _lootWedgeAnnounced = true; + ChatLine($"[RynthAi] WEDGE: {LootWedgeThreshold} corpse opens timed out — AC item-actions are locked. Halting looting {LootWedgeHaltMs / 1000}s and unlocking. If equip/loot stays stuck, /rc actionstate shows what the client is waiting on."); + } Log($"[RynthAi] LOOT WEDGE detected ({LootWedgeThreshold} consecutive open timeouts) — halt {LootWedgeHaltMs}ms + reset fired."); } @@ -2707,6 +2938,10 @@ public sealed partial class RynthAiPlugin ChatLine($"[RynthAi] Corpse ranges: max={ConvertMetersToYards(maxMeters):F1} yd / {maxMeters:F1} m, min={ConvertMetersToYards(minMeters):F1} yd / {minMeters:F1} m"); uint rawOpen = Host.HasGetGroundContainerId ? Host.GetGroundContainerId() : 0; ChatLine($"[RynthAi] Corpse state: target=0x{(uint)_targetCorpseId:X8}, corpse-open=0x{(uint)_openedContainerId:X8}, raw-open=0x{rawOpen:X8}, busy={_busyCount}, inv-update={(_openedContainerInventoryObservedAt != 0 ? 1 : 0)}, completed={_completedCorpses.Count}"); + long infoNow = CorpseNowMs; + ChatLine($"[RynthAi] Use check: {_useRefusals.State}, {_useRefusals.Refusals} refused open(s) since the last open" + + (_useRefusals.HoldsOpens(infoNow) ? $", looting paused {(_useRefusals.BackoffUntil - infoNow) / 1000}s more (the server refuses uses; a relog fixes it)" : "") + + (Host.HasUseDoneSeq ? "" : " (this engine can't report the server's answers: the check is off)")); if (TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out double distanceMeters)) ChatLine($"[RynthAi] Nearest corpse: {corpse!.Name} (0x{(uint)corpse.Id:X8}) at {ConvertMetersToYards(distanceMeters):F1} yd / {distanceMeters:F1} m"); diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfileStore.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfileStore.cs index 3426a0f..c867eba 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfileStore.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfileStore.cs @@ -28,7 +28,7 @@ namespace RynthCore.Plugin.RynthAi.CreatureData; /// internal sealed class CreatureProfileStore { - internal const string Folder = @"C:\Games\RynthSuite\RynthAi\CreatureData"; + internal static readonly string Folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "CreatureData"); private const string FileName = "creatures.json"; private readonly object _lock = new(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureWeakness.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureWeakness.cs index bf64950..53f3965 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureWeakness.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureWeakness.cs @@ -249,7 +249,7 @@ internal static class CreatureWeakness } /// The on-disk copy of the weakness table next to RynthAi (optional; the DLL has one built in). - internal const string WeaknessFile = @"C:\Games\RynthSuite\RynthAi\Data\creature_weakness.json"; + internal static readonly string WeaknessFile = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "Data", "creature_weakness.json"); // JSON keys → Elements index (the table spells Lightning "electric"). private static readonly (string Key, int Index)[] JsonKeys = diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardStore.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardStore.cs index 6261eee..2ad95ea 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardStore.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardStore.cs @@ -23,7 +23,8 @@ namespace RynthCore.Plugin.RynthAi; internal static class DungeonHazardStore { // Sibling of the existing NavProfiles folder (see LegacyDashboardRenderer._navFolder). - private static readonly string Folder = @"C:\Games\RynthSuite\RynthAi\DungeonHazards"; + // Settable so the host tests point it at their scratch folder. + internal static string Folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "DungeonHazards"); private static string PathFor(uint landblockKey) => System.IO.Path.Combine(Folder, $"{landblockKey:X4}.txt"); diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardSurfaces.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardSurfaces.cs index 6c207df..32d0cd6 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardSurfaces.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardSurfaces.cs @@ -36,7 +36,7 @@ namespace RynthCore.Plugin.RynthAi; internal static class DungeonHazardSurfaces { // Sibling of NavProfiles / DungeonHazards (LegacyDashboardRenderer._navFolder family). - private static readonly string Folder = @"C:\Games\RynthSuite\RynthAi"; + private static readonly string Folder = RynthCore.Install.RynthInstallPaths.RynthAiDir; private static readonly string SetPath = System.IO.Path.Combine(Folder, "HazardTextures.txt"); private static readonly object _gate = new(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/FlightRecorderSignal.cs b/Plugins/RynthCore.Plugin.RynthAi/FlightRecorderSignal.cs new file mode 100644 index 0000000..3b5268b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/FlightRecorderSignal.cs @@ -0,0 +1,28 @@ +using System; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Asks the engine's flight recorder (RynthCore Net/FlightRecorder.cs, 2026-10-06) to write its +/// buffer: the last minutes of client/server messages and engine markers. Called where RynthAi +/// notices a stall (LOOT WEDGE, the use-refusal check, a held-cast nudge), so the dump holds +/// the message sequence that led into it. The engine writes at most one automatic dump per +/// 10 minutes, so calling this often is harmless. Uses the plugin-command broker (API v64) +/// with a name the engine reserves; an engine without the recorder finds no such plugin and +/// nothing happens. Never throws. +/// +internal static class FlightRecorderSignal +{ + public const string Target = "RynthCore.FlightRecorder"; + + public static void Dump(RynthCoreHost host, string reason) + { + try + { + if (host.HasSendPluginCommand) + host.SendPluginCommand(Target, "dump", "RynthAi " + reason); + } + catch { } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/ItemInfoText.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/ItemInfoText.cs new file mode 100644 index 0000000..ae8c4f5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/ItemInfoText.cs @@ -0,0 +1,308 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using RynthCore.Loot.Editing; +using RynthCore.Plugin.RynthAi.CreatureData; + +namespace RynthCore.Plugin.RynthAi.ItemInfo; + +/// One item's appraisal values, as reads them. +internal interface IItemInfoSource +{ + /// The name the client shows ("" when unknown). + string Name { get; } + bool TryInt(uint key, out int value); + bool TryFloat(uint key, out double value); + /// The item's spells (empty when none or not appraised). + IReadOnlyList SpellIds { get; } +} + +/// +/// /ra iteminfo's text: one item on one chat line, in the spirit of Mag-Tools' item info +/// (name, type, set, armor, ratings, damage and mods, imbues, slayer, tinks, spells by name, +/// wield and activation requirements, craft, material, value and burden). A field the +/// appraisal doesn't carry is left out. Pure: no host calls, so the host tests feed it a +/// fake source. +/// +internal static class ItemInfoText +{ + // STypeInt (AC / ACE PropertyInt numbering; the names in Meta/PropertyNames.cs). + internal const uint IntItemType = 1, IntEncumbrance = 5, IntStackSize = 12, IntRareId = 17, IntValue = 19, + IntArmorLevel = 28, IntBonded = 33, IntDamage = 44, IntDamageType = 45, IntWeaponSkill = 48, + IntWeaponTime = 49, IntWorkmanship = 105, IntSpellcraft = 106, IntCurMana = 107, IntMaxMana = 108, + IntItemDifficulty = 109, IntAllegianceRankLimit = 110, IntAttuned = 114, IntSkillLevelLimit = 115, + IntMaterial = 131, IntWieldReq = 158, IntWieldSkill = 159, IntWieldDiff = 160, IntSlayerType = 166, + IntTinks = 171, IntImbued = 179, IntElementalBonus = 204, IntSetId = 265, IntWieldReq2 = 270, + IntWieldSkill2 = 271, IntWieldDiff2 = 272, IntItemMaxLevel = 319; + + // STypeFloat (ACE PropertyFloat numbering). + internal const uint FloatDamageVariance = 22, FloatMeleeDefense = 29, FloatWeaponOffense = 62, FloatDamageMod = 63, + FloatManaConversion = 144, FloatMissileDefense = 149, FloatMagicDefense = 150, FloatElementalDamage = 152; + + /// Gear ratings (STypeInt 370-389) and their short tags, in print order. + internal static readonly (uint Key, string Tag)[] Ratings = + { + (370, "D"), (371, "DR"), (372, "C"), (373, "CR"), (374, "CD"), (375, "CDR"), + (376, "HB"), (379, "Vit"), (377, "NR"), (378, "LR"), (388, "OP"), (389, "OPR"), + (383, "PvP D"), (384, "PvP DR"), + }; + + // ItemType flags (STypeInt 1), most specific first. + private static readonly (uint Flag, string Name)[] Types = + { + (0x00040000, "Promissory Note"), (0x00080000, "Mana Stone"), (0x00001000, "Spell Component"), + (0x00000800, "Gem"), (0x00004000, "Key"), (0x40000000, "Salvage"), (0x20000000, "Tinkering Tool"), + (0x00000200, "Container"), (0x00008000, "Caster"), (0x00000100, "Missile Weapon"), + (0x00000001, "Melee Weapon"), (0x00000002, "Armor"), (0x00000004, "Clothing"), (0x00000008, "Jewelry"), + (0x00000020, "Food"), (0x00000040, "Money"), (0x00002000, "Writable"), (0x00000080, "Misc"), + }; + + // ImbuedEffect flags (STypeInt 179). + private static readonly (uint Flag, string Name)[] Imbues = + { + (0x0001, "Critical Strike"), (0x0002, "Crippling Blow"), (0x0004, "Armor Rending"), + (0x0008, "Slash Rending"), (0x0010, "Pierce Rending"), (0x0020, "Bludgeon Rending"), + (0x0040, "Acid Rending"), (0x0080, "Cold Rending"), (0x0100, "Lightning Rending"), + (0x0200, "Fire Rending"), (0x0400, "Melee Defense"), (0x0800, "Missile Defense"), + (0x1000, "Magic Defense"), (0x4000, "Nether Rending"), + }; + + // Equipment sets (STypeInt 265) whose ids are certain: the loot armor sets and Aetheria. + private static readonly Dictionary Sets = new() + { + [13] = "Soldier's", [14] = "Adept's", [15] = "Archer's", [16] = "Defender's", [17] = "Tinker's", + [18] = "Crafter's", [19] = "Hearty", [20] = "Dexterous", [21] = "Wise", [22] = "Swift", + [23] = "Hardened", [24] = "Reinforced", [25] = "Interlocking", [26] = "Flame Proof", + [27] = "Acid Proof", [28] = "Cold Proof", [29] = "Lightning Proof", + [35] = "Aetheria: Defense", [36] = "Aetheria: Destruction", [37] = "Aetheria: Fury", + [38] = "Aetheria: Growth", [39] = "Aetheria: Vigor", + }; + + // Attributes and vitals for attribute/vital wield requirements (ACE PropertyAttribute / PropertyAttribute2nd). + private static readonly string[] Attributes = { "", "Strength", "Endurance", "Quickness", "Coordination", "Focus", "Self" }; + private static readonly string[] Vitals = { "", "Max Health", "Health", "Max Stamina", "Stamina", "Max Mana", "Mana" }; + + private static readonly CultureInfo Inv = CultureInfo.InvariantCulture; + + /// + /// The item on one line. names a spell id (the plugin's + /// spell table). false adds a note that the server never + /// answered the ID, so only what the client already knew is shown. + /// + public static string Describe(IItemInfoSource item, Func spellName, bool identified = true) + { + var parts = new List(24); + int type = Int(item, IntItemType); + + // Name, with the material in front the way the game names loot ("Gold Ring"). + string name = item.Name.Trim(); + int material = Int(item, IntMaterial); + string full = WeaponNames.Full(name, material); + if (full.Length == 0) full = "(unnamed item)"; + string typeName = TypeName(type); + int stack = Int(item, IntStackSize); + var head = new StringBuilder(full); + if (stack > 1) head.Append(" x").Append(stack.ToString("N0", Inv)); + if (typeName.Length > 0) head.Append(" (").Append(typeName).Append(')'); + parts.Add(head.ToString()); + + if (Int(item, IntSetId) is int set and > 0) + parts.Add((Sets.TryGetValue(set, out string? setName) ? setName : "Set " + set) + " Set"); + + if (item.TryInt(IntArmorLevel, out int al) && (al > 0 || (type & 0x2) != 0)) + parts.Add("AL " + al.ToString(Inv)); + + string ratings = RatingText(item); + if (ratings.Length > 0) parts.Add(ratings); + + AddWeapon(item, type, parts); + + string imbues = ImbueText(Int(item, IntImbued)); + if (imbues.Length > 0) parts.Add(imbues); + + if (Int(item, IntSlayerType) is int slayer and > 0) + parts.Add(CreatureTypeNames.Name(slayer) + " Slayer"); + + if (item.TryInt(IntTinks, out int tinks) && tinks > 0) + parts.Add("Tinks " + tinks.ToString(Inv)); + + string spells = SpellText(item.SpellIds, spellName); + if (spells.Length > 0) parts.Add(spells); + + string wield = WieldText(item, IntWieldReq, IntWieldSkill, IntWieldDiff); + if (wield.Length > 0) parts.Add(wield); + string wield2 = WieldText(item, IntWieldReq2, IntWieldSkill2, IntWieldDiff2); + if (wield2.Length > 0) parts.Add(wield2); + + if (Int(item, IntSkillLevelLimit) is int skillLimit and > 0) parts.Add("Skill " + skillLimit.ToString(Inv) + " to activate"); + if (Int(item, IntAllegianceRankLimit) is int rank and > 0) parts.Add("Rank " + rank.ToString(Inv)); + if (Int(item, IntItemDifficulty) is int diff and > 0) parts.Add("Diff " + diff.ToString(Inv)); + if (Int(item, IntSpellcraft) is int spellcraft and > 0) parts.Add("Spellcraft " + spellcraft.ToString(Inv)); + if (item.TryInt(IntMaxMana, out int maxMana) && maxMana > 0) + parts.Add("Mana " + (item.TryInt(IntCurMana, out int cur) ? cur.ToString(Inv) + "/" : "") + maxMana.ToString(Inv)); + if (Int(item, IntItemMaxLevel) is int maxLevel and > 0) parts.Add("Max Level " + maxLevel.ToString(Inv)); + + if (item.TryInt(IntWorkmanship, out int craft) && craft > 0) parts.Add("Craft " + craft.ToString(Inv)); + string matName = WeaponNames.Material(material); + if (matName.Length > 0) parts.Add("Mat " + matName); + + if (Int(item, IntBonded) == 1) parts.Add("Bonded"); + if (Int(item, IntAttuned) == 1) parts.Add("Attuned"); + if (Int(item, IntRareId) is int rare and > 0) parts.Add("Rare #" + rare.ToString(Inv)); + + if (item.TryInt(IntValue, out int value)) parts.Add("Value " + value.ToString("N0", Inv)); + if (item.TryInt(IntEncumbrance, out int burden)) parts.Add("BU " + burden.ToString("N0", Inv)); + + if (!identified) parts.Add("(not identified: no reply from the server)"); + return string.Join(", ", parts); + } + + private static int Int(IItemInfoSource item, uint key) => item.TryInt(key, out int v) ? v : 0; + + /// The item's kind from its ItemType flags ("" when none is set). + internal static string TypeName(int itemType) + { + uint t = unchecked((uint)itemType); + foreach (var (flag, n) in Types) + if ((t & flag) != 0) return n; + return ""; + } + + /// "[D3 CD2 CDR1]" for the gear ratings that are set; "" for none. + internal static string RatingText(IItemInfoSource item) + { + var sb = new StringBuilder(); + foreach (var (key, tag) in Ratings) + { + if (!item.TryInt(key, out int r) || r <= 0) continue; + sb.Append(sb.Length == 0 ? "[" : " ").Append(tag).Append(r.ToString(Inv)); + } + return sb.Length == 0 ? "" : sb.Append(']').ToString(); + } + + private static void AddWeapon(IItemInfoSource item, int type, List parts) + { + uint t = unchecked((uint)type); + bool melee = (t & 0x1) != 0, missile = (t & 0x100) != 0, caster = (t & 0x8000) != 0; + bool weapon = melee || missile || caster; + + if (Int(item, IntWeaponSkill) is int skill and > 0 && weapon) + parts.Add(SkillName(skill)); + + int dmgType = Int(item, IntDamageType); + if (item.TryInt(IntDamage, out int max) && max > 0) + { + string dmg = "Dmg " + max.ToString(Inv); + if (item.TryFloat(FloatDamageVariance, out double variance) && variance > 0 && variance < 1) + { + int min = (int)Math.Round(max * (1.0 - variance), MidpointRounding.AwayFromZero); + dmg = $"Dmg {min.ToString(Inv)}-{max.ToString(Inv)}"; + } + string element = DamageTypeName(dmgType); + if (element.Length > 0) dmg += " " + element; + parts.Add(dmg); + } + else if (weapon && dmgType > 0) + { + string element = DamageTypeName(dmgType); + if (element.Length > 0) parts.Add(element); + } + if (Int(item, IntElementalBonus) is int elemBonus and > 0) parts.Add("+" + elemBonus.ToString(Inv) + " elemental dmg"); + if (weapon && item.TryInt(IntWeaponTime, out int speed) && speed > 0) parts.Add("Speed " + speed.ToString(Inv)); + + // Modifiers: 1.18 = +18%. Missile launchers' damage mod and casters' elemental mod too. + var mods = new List(6); + AddPercent(item, FloatWeaponOffense, "atk", mods, weapon); + if (missile) AddPercent(item, FloatDamageMod, "dmg", mods, true); + if (caster) AddPercent(item, FloatElementalDamage, "vs monsters", mods, true); + AddPercent(item, FloatMeleeDefense, "md", mods, weapon); + AddPercent(item, FloatMissileDefense, "mid", mods, weapon); + AddPercent(item, FloatMagicDefense, "mgd", mods, weapon); + AddPercent(item, FloatManaConversion, "mana c", mods, true); + if (mods.Count > 0) parts.Add("(" + string.Join(", ", mods) + ")"); + } + + private static void AddPercent(IItemInfoSource item, uint key, string label, List mods, bool allowed) + { + if (!allowed || !item.TryFloat(key, out double v) || double.IsNaN(v)) return; + // Multipliers (attack, defense, damage) are stored as 1.xx; mana conversion as 0.xx. + double pct = key == FloatManaConversion ? v * 100.0 : (v - 1.0) * 100.0; + int rounded = (int)Math.Round(pct, MidpointRounding.AwayFromZero); + if (rounded == 0) return; + mods.Add((rounded > 0 ? "+" : "") + rounded.ToString(Inv) + "% " + label); + } + + /// "Crippling Blow, Fire Rending" for the imbue flags; "" for none. + internal static string ImbueText(int flags) + { + if (flags == 0) return ""; + uint f = unchecked((uint)flags); + var names = new List(2); + foreach (var (flag, n) in Imbues) + if ((f & flag) != 0) names.Add(n); + return string.Join(", ", names); + } + + /// "Spells: A, B, C" by name, in the item's order, each once; "" for none. + internal static string SpellText(IReadOnlyList spellIds, Func spellName) + { + if (spellIds.Count == 0) return ""; + var seen = new HashSet(); + var names = new List(spellIds.Count); + foreach (int id in spellIds) + { + if (id <= 0 || !seen.Add(id)) continue; + string n = spellName(id); + names.Add(string.IsNullOrWhiteSpace(n) ? "spell " + id.ToString(Inv) : n); + } + return names.Count == 0 ? "" : "Spells: " + string.Join(", ", names); + } + + /// One wield requirement ("Wield Lvl 180", "Heavy Weapons 375 to wield"); "" for none. + internal static string WieldText(IItemInfoSource item, uint reqKey, uint skillKey, uint diffKey) + { + int req = Int(item, reqKey); + if (req <= 0) return ""; + int skill = Int(item, skillKey); + int diff = Int(item, diffKey); + string d = diff.ToString(Inv); + return req switch + { + 1 => $"{SkillName(skill)} {d} to wield", + 2 => $"Base {SkillName(skill)} {d} to wield", + 3 => $"{Pick(Attributes, skill, "Attribute")} {d} to wield", + 4 => $"Base {Pick(Attributes, skill, "Attribute")} {d} to wield", + 5 => $"{Pick(Vitals, skill, "Vital")} {d} to wield", + 6 => $"Base {Pick(Vitals, skill, "Vital")} {d} to wield", + 7 => $"Wield Lvl {d}", + 8 => $"{(diff >= 3 ? "Specialized" : "Trained")} {SkillName(skill)} to wield", + 12 => $"Heritage {d} to wield", + _ => $"Wield requirement {req.ToString(Inv)} ({skill.ToString(Inv)}, {d})", + }; + } + + private static string Pick(string[] names, int i, string fallback) => + i > 0 && i < names.Length ? names[i] : $"{fallback} {i.ToString(Inv)}"; + + /// AC's skill name for a skill id ("skill N" when unknown). + internal static string SkillName(int id) + { + foreach (var (sid, n) in LootRuleText.Skills) + if (sid == id) return n; + return "skill " + id.ToString(Inv); + } + + /// The damage type's name ("Slashing/Piercing" etc.); "" for none. + internal static string DamageTypeName(int flags) + { + if (flags <= 0) return ""; + foreach (var (id, n) in LootRuleText.DamageTypes) + if (id == flags) return n; + // Other combinations: the single flags joined. + var names = new List(3); + foreach (var (id, n) in LootRuleText.DamageTypes) + if (id > 0 && (id & (id - 1)) == 0 && (flags & id) != 0) names.Add(n); + return string.Join("/", names); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfSelect.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfSelect.cs new file mode 100644 index 0000000..b2bbd6a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfSelect.cs @@ -0,0 +1,27 @@ +using System; + +namespace RynthCore.Plugin.RynthAi.ItemInfo; + +/// +/// Items RynthAi selects by itself (the looter picking an item up, a meta's selectitem), so the +/// selection-change handler can tell them from the player's own clicks: Item Info on select +/// prints only for the player's. goes right before Host.SelectItem. +/// +internal static class SelfSelect +{ + /// A selection change this soon after , for the same id, is ours. + internal const long WindowMs = 2000; + + internal static Func Clock = () => Environment.TickCount64; + + private static uint _id; + private static long _at; + + internal static void Mark(uint id) + { + _at = Clock(); + _id = id; + } + + internal static bool IsOurs(uint id) => id != 0 && id == _id && Clock() - _at <= WindowMs; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index 6b363d0..e5dd363 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -13,6 +13,7 @@ internal sealed class LegacyAdvancedSettingsUi private string _newBlacklistName = ""; private static readonly string[] AttackHeights = { "Low", "Medium", "High" }; + private static readonly string[] NavLabelModeNames = { "Off", "Numbers", "Numbers and names" }; private static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" }; public LegacyAdvancedSettingsUi(LegacyUiSettings settings) @@ -564,7 +565,7 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.InputFloat("Nav point reach (yd)", ref _settings.FollowNavMin, 0.1f, 1.0f, "%.1f"); _settings.FollowNavMin = LegacyUiSettings.ClampFollowNavMin(_settings.FollowNavMin); if (ImGui.IsItemHovered()) - ImGui.SetTooltip("How close to get to each nav point before moving on to the next (yards). VTank calls it Follow/Nav Min Distance. Follow stops this close to its leader; the nav marker ring shows it."); + ImGui.SetTooltip("How close to get to each nav point before moving on to the next (yards). VTank calls it Follow/Nav Min Distance. Up to 2 nav walks right up to each point before turning (tight dungeons); bigger values round corners. Follow stops this close to its leader; the nav marker ring shows it."); ImGui.Spacing(); ImGui.Text("Nav Marker Display"); @@ -584,6 +585,11 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Checkbox("Show Terrain Passability", ref _settings.ShowTerrainPassability); if (ImGui.IsItemHovered()) ImGui.SetTooltip("Highlight impassable terrain triangles in red."); + ImGui.SetNextItemWidth(160); + ImGui.Combo("Waypoint Labels", ref _settings.NavLabelMode, NavLabelModeNames, NavLabelModeNames.Length); + ImGui.Checkbox("Guide Line", ref _settings.NavGuideLine); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("A line from your character to the waypoint nav is heading for."); ImGui.Spacing(); ImGui.Separator(); @@ -654,7 +660,7 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.InputFloat("Lookahead (yd)", ref _settings.NavLookaheadYards, 0.5f, 1f, "%.1f"); if (_settings.NavLookaheadYards < 0f) _settings.NavLookaheadYards = 0f; if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off (aim straight at each waypoint)."); + ImGui.SetTooltip("Within this distance of a waypoint, blend the aim point toward the next one to round corners. The nav point reach limits it to 2 yd per yard of reach over 1 yd (no rounding up to a 2 yd reach), never more than this. 0 = off (aim straight at each waypoint)."); ImGui.SetNextItemWidth(80); ImGui.InputFloat("Turn Rate (deg/s)", ref _settings.NavTurnRateDegPerSec, 15f, 45f, "%.0f"); @@ -767,6 +773,9 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Checkbox("Recover My Corpse", ref _settings.LootOwnCorpse); if (ImGui.IsItemHovered()) ImGui.SetTooltip("When your own corpse (\"Corpse of \") is within loot range, open it and take\nevery item on it, whatever the loot profile and Loot From say."); + ImGui.Checkbox("Item Info On Select", ref _settings.ItemInfoOnSelect); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Selecting an item prints its details to chat (/ra iteminfo)."); ImGui.Checkbox("Travel Back To My Corpse", ref _settings.TravelToOwnCorpse); if (ImGui.IsItemHovered()) ImGui.SetTooltip("After a death, travel back to where you died with RynthNav (outdoors only),\nfighting on the way, recover the corpse, then carry on. Needs the macro running."); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 38dddac..5ff8404 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -60,16 +60,16 @@ internal sealed class LegacyDashboardRenderer // escaped the snapshot poll's reverse-P/Invoke boundary it fail-fasted the // NativeAOT runtime. Copy-under-lock on read; lock the Clear+AddRange swap. private readonly object _profileListsLock = new(); - private readonly string _navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles"; - private readonly string _lootFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles"; - private readonly string _metaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles"; + private readonly string _navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles"); + private readonly string _lootFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles"); + private readonly string _metaFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles"); // Profiles are kept per server: SettingsProfiles\\ and // MonsterProfiles\\.json, the server being the world name // the server sends at login. Before 2026-09-28 every server shared // SettingsProfiles\ACEmulator, so the same character name on two servers // shared one profile; that folder is still used when no name is known. - private const string ProfilesBase = @"C:\Games\RynthSuite\RynthAi\SettingsProfiles"; - private const string MonstersBase = @"C:\Games\RynthSuite\RynthAi\MonsterProfiles"; + private static readonly string ProfilesBase = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "SettingsProfiles"); + private static readonly string MonstersBase = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MonsterProfiles"); private const string LegacyServerFolder = "ACEmulator"; private string _serverFolder = LegacyServerFolder; private string _settingsRoot => Path.Combine(ProfilesBase, _serverFolder); @@ -113,7 +113,8 @@ internal sealed class LegacyDashboardRenderer private DateTime _sessionStartUtc = DateTime.UtcNow; private long _sessionKills; // Interlocked: incremented on the pump thread, read in the snapshot private double _killsPerHour; - private long _lastKillTicks; // DateTime.UtcNow.Ticks of the last kill (0 = none yet this session) + /// The plugin's kill clock (secsSinceLastKill); set once at plugin init. + internal KillClock? KillClock { get; set; } // volatile: written on the pump thread (SetFreeSlots/SetComponentCounts), read on the snapshot-poll // thread (BuildSnapshotJson). x86 int writes are atomic but give no visibility guarantee — without // volatile the reader can see a stale value indefinitely. (_sessionKills uses Interlocked for the same reason.) @@ -1009,6 +1010,8 @@ internal sealed class LegacyDashboardRenderer NavHeightOffset = s.NavHeightOffset, NavSlopeSink = s.NavSlopeSink, ShowTerrainPassability = s.ShowTerrainPassability, + NavLabelMode = NavLabelModes.Clamp(s.NavLabelMode), + NavGuideLine = s.NavGuideLine, OpenDoors = s.OpenDoors, OpenDoorRange = s.OpenDoorRange, AutoUnlockDoors = s.AutoUnlockDoors, @@ -1056,6 +1059,7 @@ internal sealed class LegacyDashboardRenderer LootOwnership = s.LootOwnership, LootOwnCorpse = s.LootOwnCorpse, TravelToOwnCorpse = s.TravelToOwnCorpse, + ItemInfoOnSelect = s.ItemInfoOnSelect, EnableAutostack = s.EnableAutostack, ReadUnknownScrolls = s.ReadUnknownScrolls, EnableCombineSalvage = s.EnableCombineSalvage, @@ -1212,6 +1216,8 @@ internal sealed class LegacyDashboardRenderer s.NavHeightOffset = p.NavHeightOffset; s.NavSlopeSink = p.NavSlopeSink; s.ShowTerrainPassability = p.ShowTerrainPassability; + if (p.NavLabelMode >= 0) s.NavLabelMode = NavLabelModes.Clamp(p.NavLabelMode); + if (p.NavGuideLine is bool guideLine) s.NavGuideLine = guideLine; s.OpenDoors = p.OpenDoors; s.OpenDoorRange = p.OpenDoorRange; s.AutoUnlockDoors = p.AutoUnlockDoors; @@ -1256,6 +1262,7 @@ internal sealed class LegacyDashboardRenderer s.LootOwnership = p.LootOwnership; if (p.LootOwnCorpse is bool lootOwn) s.LootOwnCorpse = lootOwn; // absent = unchanged if (p.TravelToOwnCorpse is bool travelOwn) s.TravelToOwnCorpse = travelOwn; // absent = unchanged + if (p.ItemInfoOnSelect is bool infoOnSelect) s.ItemInfoOnSelect = infoOnSelect; // absent = unchanged s.EnableAutostack = p.EnableAutostack; s.ReadUnknownScrolls = p.ReadUnknownScrolls; s.EnableCombineSalvage = p.EnableCombineSalvage; @@ -1657,6 +1664,7 @@ internal sealed class LegacyDashboardRenderer dst.LootOwnership = tmp.LootOwnership; dst.LootOwnCorpse = tmp.LootOwnCorpse; dst.TravelToOwnCorpse = tmp.TravelToOwnCorpse; + dst.ItemInfoOnSelect = tmp.ItemInfoOnSelect; dst.LootOnlyRareCorpses = tmp.LootOnlyRareCorpses; dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle; dst.RebuffWhenIdle = tmp.RebuffWhenIdle; @@ -1759,6 +1767,8 @@ internal sealed class LegacyDashboardRenderer dst.PatrolOnLogin = tmp.PatrolOnLogin; dst.YieldToVTank = tmp.YieldToVTank; dst.ShowTerrainPassability = tmp.ShowTerrainPassability; + dst.NavLabelMode = NavLabelModes.Clamp(tmp.NavLabelMode); + dst.NavGuideLine = tmp.NavGuideLine; dst.GiveQueueIntervalMs = tmp.GiveQueueIntervalMs; dst.SpellCastIntervalMs = tmp.SpellCastIntervalMs; dst.AttackSpellIntervalMs = tmp.AttackSpellIntervalMs; @@ -1891,15 +1901,13 @@ internal sealed class LegacyDashboardRenderer { _sessionStartUtc = DateTime.UtcNow; System.Threading.Interlocked.Exchange(ref _sessionKills, 0); - System.Threading.Interlocked.Exchange(ref _lastKillTicks, 0); } - /// Called from the plugin's OnKillNotification (pump thread) for each kill — feeds kills/hour - /// and the "time since last kill" liveness signal. + /// Called from the plugin's OnKillNotification (pump thread) for each kill — feeds kills/hour. + /// The "time since last kill" signal is the plugin's KillClock. public void RecordKill() { System.Threading.Interlocked.Increment(ref _sessionKills); - System.Threading.Interlocked.Exchange(ref _lastKillTicks, DateTime.UtcNow.Ticks); } /// Pushed from the plugin tick (it owns the inventory cache) — main-pack empty slots. -1 = unknown. @@ -2087,6 +2095,30 @@ internal sealed class LegacyDashboardRenderer _selectedNavIdx = sel; } + private DateTime _navFolderStamp; + private long _nextNavFolderCheckMs; + + /// + /// Lists NavProfiles again when the folder changed since the last look (a route saved there by + /// RynthNav's "save as nav route", or a file copied in), so the Nav picker shows it without a + /// relog. One folder time check every 3 s. Plugin tick. + /// + public void TickNavFolder() + { + long now = Environment.TickCount64; + if (now < _nextNavFolderCheckMs) return; + _nextNavFolderCheckMs = now + 3000; + try + { + DateTime stamp = Directory.Exists(_navFolder) ? Directory.GetLastWriteTimeUtc(_navFolder) : DateTime.MinValue; + if (stamp == _navFolderStamp) return; + bool first = _navFolderStamp == default; + _navFolderStamp = stamp; + if (!first) RefreshNavFiles(); + } + catch { } + } + /// Save button and /ra nav save [name]. Returns the chat line. public string SaveRoute(string? name) { @@ -2519,11 +2551,8 @@ internal sealed class LegacyDashboardRenderer // (kill counter + inventory cache); the rest of the player stats are engine top-level. AppendFloat(sb, "killsPerHour", (float)_killsPerHour); sb.Append(','); AppendInt(sb, "sessionKills", (int)System.Threading.Interlocked.Read(ref _sessionKills)); sb.Append(','); - long lastKillTicks = System.Threading.Interlocked.Read(ref _lastKillTicks); - int secsSinceLastKill = lastKillTicks == 0 - ? -1 - : (int)Math.Clamp((DateTime.UtcNow - new DateTime(lastKillTicks, DateTimeKind.Utc)).TotalSeconds, 0, int.MaxValue); - AppendInt(sb, "secsSinceLastKill", secsSinceLastKill); sb.Append(','); + // -1 before the first kill this session (the plugin's KillClock, reset at login). + AppendInt(sb, "secsSinceLastKill", KillClock?.SecondsSinceKillOnly() ?? -1); sb.Append(','); AppendInt(sb, "freeSlots", _freeSlots); sb.Append(','); // D2 three-tier target telemetry + D6 attack-cast/kill ratio (orphan early-warning). AppendInt(sb, "scanTotal", _scanTotal); sb.Append(','); @@ -2732,7 +2761,7 @@ internal sealed class LegacyDashboardRenderer // ── Meta bridge ─────────────────────────────────────────────────────────── - private static readonly string MetaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles"; + private static readonly string MetaFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles"); // Result of the last set_source, reported in BuildMetaJson (under MetaRulesLock). private long _metaApplySeq; @@ -2993,11 +3022,10 @@ internal sealed class LegacyDashboardRenderer break; case "update_rule": - if (cmd.Rule != null && cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count) - { - _settings.MetaRules[cmd.Index] = DtoToMetaRule(cmd.Rule); + // The engine's editor saves every change (2026-10-05): keep the running rule's + // latch (no re-fire) and the fields the panel can't send (MetaRuleEdits). + if (cmd.Rule != null && MetaRuleEdits.Replace(_settings.MetaRules, cmd.Index, DtoToMetaRule(cmd.Rule))) TryAutoSaveMetaCmd(); - } break; case "delete_rule": @@ -3028,7 +3056,9 @@ internal sealed class LegacyDashboardRenderer case "duplicate_rule": if (cmd.Rule != null && cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count) { - _settings.MetaRules.Insert(cmd.Index + 1, DtoToMetaRule(cmd.Rule)); + var copy = DtoToMetaRule(cmd.Rule); + MetaRuleEdits.KeepHidden(_settings.MetaRules[cmd.Index], copy); // CallState return / ChatCapture colours + _settings.MetaRules.Insert(cmd.Index + 1, copy); TryAutoSaveMetaCmd(); } break; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs index 8360a03..fdb2298 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs @@ -46,7 +46,7 @@ internal sealed class LegacyMetaUi private string _statusMessage = ""; private DateTime _statusTime = DateTime.MinValue; - private static readonly string MetaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles"; + private static readonly string MetaFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles"); /// Warnings from the most recent LoadMacroFile, so the Avalonia /// bridge can surface them too (it doesn't see the LoadedMeta). @@ -698,6 +698,9 @@ internal sealed class LegacyMetaUi case MetaConditionType.VitaePHE: condHint = "Vitae penalty % (e.g. 5)"; break; + case MetaConditionType.NoKillsWithinMinutes: + condHint = "Minutes without a kill (e.g. 5 or 2.5)"; + break; } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index 46da731..ce7760b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -43,7 +43,7 @@ public sealed class LegacyUiSettings public float NavResumeTurnAngle = 10f; public float NavDeadZone = 4f; public float NavSweepMult = 2.5f; - public float NavLookaheadYards = 4.0f; // distance to start blending the aim point toward the next waypoint (0 = off) + public float NavLookaheadYards = 4.0f; // most the aim point is blended toward the next waypoint (0 = off); the nav point reach scales it down (NavigationEngine.CornerLookaheadYards) public float NavShortcutYards = 1.0f; // on arrival, skip waypoints only while the straight run to a later one stays within this of every skipped point (0 = visit every point) public float NavTurnRateDegPerSec = 270f; // mode 0 (heading servo) max turn rate public float NavTier1TurnSpeed = 3.0f; // mode 1 (CM_Movement) DoMovement turn-command speed (magnitude of CMotionInterp turn_speed; 1.0 = native keyboard rate) @@ -167,6 +167,11 @@ public sealed class LegacyUiSettings public float NavHeightOffset = 0.05f; public float NavSlopeSink = 1.5f; public bool ShowTerrainPassability = true; + // Nav3D extras, both off by default: labels over the route's waypoints (NavLabelModes: + // 0 off, 1 numbers, 2 numbers and what happens there) and a line from the character to + // the waypoint nav is heading for. + public int NavLabelMode; + public bool NavGuideLine; public double MaxMonRange = 12.0; public bool SummonPets; public int CustomPetRange = 5; @@ -196,6 +201,11 @@ public sealed class LegacyUiSettings /// on the way as usual, recover the corpse, then carry on. Off by default. /// public bool TravelToOwnCorpse; + /// + /// Selecting an item prints its details to chat (/ra iteminfo, Mag-Tools style), + /// identifying it first when needed. Items RynthAi selects itself are skipped. On by default. + /// + public bool ItemInfoOnSelect = true; public bool LootOnlyRareCorpses; public bool PeaceModeWhenIdle = true; public bool RebuffWhenIdle; @@ -828,6 +838,9 @@ public sealed class SettingsBridgePayload public float NavHeightOffset { get; set; } public float NavSlopeSink { get; set; } public bool ShowTerrainPassability { get; set; } + // Absent from an older engine: -1 / null keep the plugin's value. + public int NavLabelMode { get; set; } = -1; + public bool? NavGuideLine { get; set; } public bool OpenDoors { get; set; } public float OpenDoorRange { get; set; } public bool AutoUnlockDoors { get; set; } @@ -882,6 +895,7 @@ public sealed class SettingsBridgePayload // and its save must leave them alone. public bool? LootOwnCorpse { get; set; } public bool? TravelToOwnCorpse { get; set; } + public bool? ItemInfoOnSelect { get; set; } public bool EnableAutostack { get; set; } public bool ReadUnknownScrolls { get; set; } = true; // absent from an older engine: keep the default public bool EnableCombineSalvage { get; set; } @@ -953,7 +967,11 @@ public enum MetaConditionType MainManaLE, MainManaPHE, MainStamLE, - VitaePHE + VitaePHE, + /// RynthAi only (2026-10-06): no kill for at least N minutes (ConditionData = minutes, + /// decimals allowed). Appended last: the value is the wire / JSON number, and an older RynthAi + /// that reads it treats the unknown number (and the .af keyword NoKillsInMins) as never true. + NoKillsWithinMinutes } public enum MetaActionType diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs index 8a17650..22ca87f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs @@ -20,7 +20,7 @@ namespace RynthCore.Plugin.RynthAi.Loot; /// internal sealed class LootEditorBridge { - public const string LootFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles"; + public static readonly string LootFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles"); private readonly object _sync = new(); private readonly LootEditSession _session = new(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs new file mode 100644 index 0000000..6614aa9 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs @@ -0,0 +1,189 @@ +// ============================================================================ +// RynthAi - Loot/UseRefusalWatch.cs +// Notices when the server answers every corpse open but nothing opens. +// +// Why (2026-10-06, Drakkon on DreamWeave): from 06:18:44 every use of a corpse +// or door got the server's "use done" (UseDone, no error) about one round trip +// after it was sent, and nothing opened. Fighting, healing kits and spells kept +// working. Macro off, walking, jumping and /rc unlockactions changed nothing; a +// relog fixed it at once, for the very same corpses. The bot hammered corpses +// for 13 minutes: 33 abandons, 11 "LOOT WEDGE" resets, a chat line each. +// +// What this does: each corpse open is remembered with the server's UseDone +// count at the time. A UseDone that arrives after it with no error, with no +// corpse opening within AnswerGraceMs, is a refusal. A successful open of any +// corpse clears everything. +// - RefusalsBeforeRetry refusals in a row: stop all movement once, pause a +// moment, try once more (CleanStopAndRetry). +// - The retry refused too, with refusals on two different corpses since the +// last open: the server refuses every use. Say so once and back off +// (Stuck), then try one corpse every BackoffMs (doubling, capped). Each +// probe that is refused again is StillStuck (log only); one that opens is +// Recovered. +// - The retry refused but only one corpse has ever refused: that corpse can't +// be opened (its loot rights, say). Give up on it (DropCorpse); the next +// corpse's first refusal decides. +// +// A UseDone with an error (0x1D "too busy", ...) says nothing either way, and +// an open the server never answers is left to the corpse timeout as before. +// No game calls here: the controller acts on the verdicts. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi.Loot; + +internal sealed class UseRefusalWatch +{ + /// After the server's answer, a corpse that opens does so within a few frames. + public const long AnswerGraceMs = 1500; + /// An open the server hasn't answered after this long is forgotten (the corpse timeout handles it). + public const long UnansweredForgetMs = 15_000; + public const int RefusalsBeforeRetry = 3; + /// The pause after the clean stop, before the one retry. + public const long CleanStopPauseMs = 1500; + public const long FirstBackoffMs = 5 * 60_000; + public const long MaxBackoffMs = 20 * 60_000; + + public enum Phase { Normal, Retrying, Stuck } + + public enum Verdict + { + None, + /// Several refusals in a row: stop all movement, pause CleanStopPauseMs, try once more. + CleanStopAndRetry, + /// The retry was refused but only this corpse ever refused: give up on it. + DropCorpse, + /// The server refuses every use: tell the player once, back off until BackoffUntil. + Stuck, + /// A probe after the back-off was refused too: back off again (longer), quietly. + StillStuck, + /// A corpse opened after Stuck: uses work again. + Recovered, + } + + public Phase State { get; private set; } = Phase.Normal; + public int Refusals { get; private set; } + public long BackoffUntil { get; private set; } + public long BackoffMs { get; private set; } + /// The corpses refused since the last successful open. + public IReadOnlyCollection RefusedCorpses => _refused; + /// The corpse of the last refusal (what a verdict is about). + public int LastRefusedCorpse { get; private set; } + + private readonly HashSet _refused = new(); + private bool _pending; + private int _pendingId; + private long _sentAt; + private int _seqAtSend; + private long _answeredAt; + + /// While Stuck: no opens until the back-off ends (then one probe). + public bool HoldsOpens(long now) => State == Phase.Stuck && now < BackoffUntil; + + /// Call before sending the next open: the previous one, answered with nothing opened, + /// counts as refused now (the next attempt came before its grace ran out). A verdict other than + /// None means: act on it and don't send this open. + public Verdict SettleBeforeOpen(long now) + { + if (!_pending || _answeredAt == 0) + return Verdict.None; + _pending = false; + return Refused(_pendingId, now); + } + + /// An open of went out; is the + /// server UseDone count read just before it was sent. + public void OnOpenSent(int corpseId, long now, int useDoneSeq) + { + _pending = true; + _pendingId = corpseId; + _sentAt = now; + _seqAtSend = useDoneSeq; + _answeredAt = 0; + } + + /// Every tick: is the server UseDone count now, + /// the error of the latest one when the engine can say + /// (). + public Verdict OnTick(long now, int useDoneSeq, uint lastError, bool haveLastError) + { + if (!_pending) + return Verdict.None; + + if (_answeredAt == 0) + { + if (useDoneSeq != _seqAtSend) + { + if (haveLastError && lastError != 0) + { + _pending = false; // "too busy" or another error: says nothing about refusals + return Verdict.None; + } + _answeredAt = now; + } + else if (now - _sentAt >= UnansweredForgetMs) + { + _pending = false; + } + return Verdict.None; + } + + if (now - _answeredAt < AnswerGraceMs) + return Verdict.None; + + _pending = false; + return Refused(_pendingId, now); + } + + /// A corpse opened (the server sent its contents): uses work. + public Verdict OnOpened(long now) + { + bool wasStuck = State == Phase.Stuck; + Reset(); + return wasStuck ? Verdict.Recovered : Verdict.None; + } + + /// Back to normal: a relog, a login, a successful open. + public void Reset() + { + State = Phase.Normal; + Refusals = 0; + BackoffUntil = 0; + BackoffMs = 0; + LastRefusedCorpse = 0; + _refused.Clear(); + _pending = false; + _answeredAt = 0; + } + + private Verdict Refused(int corpseId, long now) + { + _refused.Add(corpseId); + LastRefusedCorpse = corpseId; + Refusals++; + + switch (State) + { + case Phase.Normal: + if (Refusals < RefusalsBeforeRetry) + return Verdict.None; + State = Phase.Retrying; + return Verdict.CleanStopAndRetry; + + case Phase.Retrying: + if (_refused.Count < 2) + return Verdict.DropCorpse; // stay Retrying: the next corpse's refusal decides + State = Phase.Stuck; + BackoffMs = FirstBackoffMs; + BackoffUntil = now + BackoffMs; + return Verdict.Stuck; + + default: // Stuck: a probe after the back-off + BackoffMs = Math.Min(MaxBackoffMs, Math.Max(FirstBackoffMs, BackoffMs * 2)); + BackoffUntil = now + BackoffMs; + return Verdict.StillStuck; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs index aad7156..5419be0 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs @@ -289,7 +289,7 @@ public sealed partial class RynthAiPlugin if (cm == 0) { ChatLine($"[RynthAi] Unknown combat mode: {mode}"); return true; } - Host.ChangeCombatMode(cm); + Host.ChangeCombatModeFor(cm, "Command", "/mt combat", force: true); return true; } @@ -379,7 +379,7 @@ public sealed partial class RynthAiPlugin targetId = Host.GetPlayerId(); } - Host.CastSpell(targetId, spellId); + Host.CastSpellFor(targetId, spellId, "Command", $"spell {spellId} (/mt cast)", asked: true); return true; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs index 578070d..1125ac2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs @@ -418,7 +418,6 @@ internal sealed class ManaStoneManager if (item == null) continue; if (IsManaStone(item)) continue; if (!IsOwnedByPlayer(item, playerId)) continue; - if (IsWandLike(item)) continue; // wands are never tap targets — keep this in sync with FindTapTarget if (_tapTargetCooldownUntil.TryGetValue(item.Id, out long until) && now < until) continue; if (_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield) && wield != 0) continue; @@ -649,13 +648,9 @@ internal sealed class ManaStoneManager if (IsManaStone(item)) continue; if (!IsOwnedByPlayer(item, playerId)) continue; - // Never tap a casting implement (wand/staff/orb). ACE refuses to - // drain mana out of these into a stone, so the tap can never complete - // and the loop spins forever (each attempt cancels movement + bumps - // busy). This is most often the character's OWN casting wand mis-read - // as a loose item — WieldedSlot can read 0 from a stale cache, so the - // equipped-skip below misses it. Mirrors CombatManager.IsWandObject. - if (IsWandLike(item)) continue; + // Wands, staves and orbs drain like any other item (ACE's ManaStone only refuses + // retained items). Only items looted for Mana Tap are candidates, and the wielded / + // listed-item / loot-kept checks below protect the character's own casters. // Skip items that recently failed to drain. if (_tapTargetCooldownUntil.TryGetValue(item.Id, out long until) && now < until) @@ -682,11 +677,9 @@ internal sealed class ManaStoneManager } /// - /// True for casting implements (wand/staff/orb). ACE will not drain mana out - /// of these into a mana stone, so they must never be selected as a tap target - /// — otherwise the tap can never complete and loops forever. ObjectClass alone - /// is unreliable for unappraised items, so we fall back to the name, matching - /// CombatManager/BuffManager.IsWandObject. + /// True for casting implements (wand/staff/orb). They drain like any other item; + /// this is only a classifier. ObjectClass alone is unreliable for unappraised items, + /// so we fall back to the name, matching CombatManager/BuffManager.IsWandObject. /// internal static bool IsWandLike(WorldObject item) => item.ObjectClass == AcObjectClass.WandStaffOrb || IsWandName(item.Name); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Maps/DungeonMapBake.cs b/Plugins/RynthCore.Plugin.RynthAi/Maps/DungeonMapBake.cs index 627e03f..7dd650f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Maps/DungeonMapBake.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Maps/DungeonMapBake.cs @@ -33,7 +33,7 @@ internal static class DungeonMapBake private const int MaxDim = 8192; // the agent refuses bigger rasters /// Where plans go. A test points this at its own folder. - internal static string CacheDir { get; set; } = @"C:\Games\RynthSuite\RynthAi\Maps"; + internal static string CacheDir { get; set; } = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "Maps"); // Pixel colours, as the old DungeonMapTexture (and DungeonMapUi's former ImGui colours). private static uint Argb(float r, float g, float b, float a) => diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileParser.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileParser.cs index 1d0d3ae..43cf0fd 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileParser.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileParser.cs @@ -476,6 +476,8 @@ internal static class AfFileParser case MetaConditionType.MainManaPHE: case MetaConditionType.MainStamLE: case MetaConditionType.VitaePHE: + // RynthAi only: NoKillsInMins 5 (minutes, decimals allowed). + case MetaConditionType.NoKillsWithinMinutes: // These use bare numbers (no braces): e.g. MainSlotsLE 4, BlockE F6820033 rule.ConditionData = ExtractBareOrBrace(rest); break; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs index 888679f..a10fd2d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs @@ -139,6 +139,9 @@ internal static class AfFileWriter case MetaConditionType.MainManaPHE: case MetaConditionType.MainStamLE: case MetaConditionType.VitaePHE: + // RynthAi only (NoKillsInMins 5): metaf can't compile it to a .met, and an older + // RynthAi loads it as Never with an "unknown condition keyword" warning. + case MetaConditionType.NoKillsWithinMinutes: // Bare values (no braces): MainSlotsLE 4, MainHealthLE 50 writer.Write($"{keyword} {data}"); break; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index 2d70da8..a1ca0f3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -62,7 +62,7 @@ internal sealed class ExpressionEngine // The three data paths are settable only so offline tests can point them at a scratch // folder before anything reads or writes them; the plugin never changes them. internal static string ItemGiverDir { get; set; } - = Path.Combine(@"C:\Games\RynthSuite\RynthAi", "ItemGiver"); + = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "ItemGiver"); /// Millisecond tick for delayexec and the var-flush throttle. Tests swap it for a /// fake clock; the plugin never changes it. @@ -107,8 +107,8 @@ internal sealed class ExpressionEngine private long _lastVarFlushMs; private string? _pvarPathCached; private const long VarFlushIntervalMs = 2000; - internal static string PvarsDir { get; set; } = Path.Combine(@"C:\Games\RynthSuite\RynthAi", "pvars"); - internal static string GvarsPath { get; set; } = Path.Combine(@"C:\Games\RynthSuite\RynthAi", "gvars.txt"); + internal static string PvarsDir { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "pvars"); + internal static string GvarsPath { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "gvars.txt"); private Dictionary Get, Action Set)>? _settingsMap; public IReadOnlyDictionary Variables => _variables; @@ -156,6 +156,11 @@ internal sealed class ExpressionEngine private CreatureProfileStore? _creatureStore; public void SetCreatureStore(CreatureProfileStore? store) => _creatureStore = store; + // secondssincelastkill[]: the plugin's kill clock. Null (not wired) reads as 0, i.e. + // "just killed", so a "no kills for a while" test never holds by mistake. + private KillClock? _killClock; + public void SetKillClock(KillClock? clock) => _killClock = clock; + // ── Backward-compat shim ────────────────────────────────────────────────── /// Executes an expression for its side effects. Always returns true. @@ -327,6 +332,8 @@ internal sealed class ExpressionEngine "getdatetimelocal" => DateTime.Now.ToString(A(0)), "getdatetimeutc" => DateTime.UtcNow.ToString(A(0)), "getunixtime" => DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture), + // Whole seconds since our last kill; before the first, since the macro start (or login). + "secondssincelastkill" => (_killClock?.SecondsSinceLastKill() ?? 0).ToString(CultureInfo.InvariantCulture), // ── World object queries ────────────────────────────────────────── "wobjectfindnearestbytemplatetype" => EvalWobjectFindNearestByTemplateType(A(0)), @@ -2412,6 +2419,7 @@ internal sealed class ExpressionEngine { if (!TryParseWobjectHandle(arg, out uint uid, out _) || uid == 0) return "0"; if (!_host.HasSelectItem) return "0"; + RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(uid); _host.SelectItem(uid); return "0"; } @@ -2440,7 +2448,7 @@ internal sealed class ExpressionEngine if (!EnsureMagicModeForCast()) return "0"; - _host.CastSpell(targetId, spellId); + _host.CastSpellFor(targetId, spellId, "Meta", $"spell {spellId} (meta)", asked: true); return "1"; } @@ -2486,7 +2494,7 @@ internal sealed class ExpressionEngine if (!_host.HasGetCurrentCombatMode) { // Can't read mode — best-effort flip and bail. - if (_host.HasChangeCombatMode) _host.ChangeCombatMode(CombatMode.Magic); + if (_host.HasChangeCombatMode) _host.ChangeCombatModeFor(CombatMode.Magic, "Meta", "meta cast: Magic mode", force: true); return false; } @@ -2509,7 +2517,7 @@ internal sealed class ExpressionEngine if (wandId == 0 || !_host.HasUseObject) { // No wand (or no UseObject) — try bare-handed magic. - if (_host.HasChangeCombatMode) _host.ChangeCombatMode(CombatMode.Magic); + if (_host.HasChangeCombatMode) _host.ChangeCombatModeFor(CombatMode.Magic, "Meta", "meta cast: Magic mode", force: true); return false; } @@ -2613,7 +2621,7 @@ internal sealed class ExpressionEngine if (_host.HasChangeCombatMode && (now - _castStanceLastFlipAt).TotalMilliseconds > CastStanceFlipGateMs) { - _host.ChangeCombatMode(CombatMode.Magic); + _host.ChangeCombatModeFor(CombatMode.Magic, "Meta", "meta cast: Magic mode", force: true); _castStanceLastFlipAt = now; } return false; @@ -2717,7 +2725,7 @@ internal sealed class ExpressionEngine if (targetId == 0) targetId = _host.GetPlayerId(); if (targetId == 0) return "2"; - _host.CastSpell(targetId, spellId); + _host.CastSpellFor(targetId, spellId, "Meta", $"spell {spellId} (meta)", asked: true); return "1"; } @@ -2867,7 +2875,11 @@ internal sealed class ExpressionEngine _ => 0, }; if (mode == 0) return "0"; - return _host.ChangeCombatMode(mode) ? "1" : "0"; + if (!_host.HasChangeCombatMode) return "0"; + int seq = _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0; + bool ok = _host.ChangeCombatMode(mode); + if (ok) ActionPacer.Begin(_host, PacedKind.CombatMode, 0, ActionPacer.ModeName(mode), "RynthAi/Meta (asked)", seq, mode); + return ok ? "1" : "0"; } private string EvalGetBusyState() @@ -3307,6 +3319,7 @@ internal sealed class ExpressionEngine ["StopLootingWhenPackFull"] = (() => B(s.StopLootingWhenPackFull), v => s.StopLootingWhenPackFull = ToDouble(v) != 0), ["LootOwnCorpse"] = (() => B(s.LootOwnCorpse), v => s.LootOwnCorpse = ToDouble(v) != 0), ["TravelToOwnCorpse"] = (() => B(s.TravelToOwnCorpse), v => s.TravelToOwnCorpse = ToDouble(v) != 0), + ["ItemInfoOnSelect"] = (() => B(s.ItemInfoOnSelect), v => s.ItemInfoOnSelect = ToDouble(v) != 0), ["StopMacroWhenPackFull"] = (() => B(s.StopMacroWhenPackFull), v => s.StopMacroWhenPackFull = ToDouble(v) != 0), ["SummonPets"] = (() => B(s.SummonPets), v => s.SummonPets = ToDouble(v) != 0), ["MineOnly"] = (() => B(s.MineOnly), v => s.MineOnly = ToDouble(v) != 0), @@ -3371,6 +3384,8 @@ internal sealed class ExpressionEngine ["MaxMonRange"] = (() => D(s.MaxMonRange), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.MaxMonRange = d; }), ["NavRingThickness"] = (() => F(s.NavRingThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavRingThickness = f; }), ["NavLineThickness"] = (() => F(s.NavLineThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavLineThickness = f; }), + ["NavLabelMode"] = (() => I(s.NavLabelMode), v => { if (int.TryParse(v, out int i)) s.NavLabelMode = NavLabelModes.Clamp(i); }), + ["NavGuideLine"] = (() => B(s.NavGuideLine), v => s.NavGuideLine = ToDouble(v) != 0), ["CurrentNavPath"] = (() => s.CurrentNavPath, v => s.CurrentNavPath = v), ["CurrentLootPath"] = (() => s.CurrentLootPath, v => s.CurrentLootPath = v), ["CurrentMetaPath"] = (() => s.CurrentMetaPath, v => s.CurrentMetaPath = v), diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionReference.txt b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionReference.txt index 4c6a14e..d84ffe8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionReference.txt +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionReference.txt @@ -728,6 +728,19 @@ getunixtime[] Example: setvar[t, getunixtime[]] → snapshot a timestamp Example: getunixtime[] - getvar[t] > 60 → true if 60s have elapsed +secondssincelastkill[] + Returns the whole number of seconds since your character's last kill. + Only kills credited to you count (the server's "you killed it" notice); + deaths you only see in chat, and your fellows' kills, do not. + Before your first kill this session it counts from when the macro was last + started, or from login (or a RynthAi reload) if the macro hasn't been started + since, so a meta can still react when nothing has been killed at all. + After a kill it is always the time since that kill, also across a macro stop/start. + The meta condition "No Kills Within Minutes" (.af: NoKillsInMins 5) uses the same clock. + Test in chat: /ra mexec secondssincelastkill[] + Example: secondssincelastkill[] → e.g. "42" + Example: secondssincelastkill[] >= 300 → true after 5 minutes without a kill + getaccounthash[] Returns a lowercase MD5 hex string of the current account name. Returns "" (empty string) if the account name is not yet available. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs index 1d1d1a2..9f247de 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs @@ -144,6 +144,15 @@ internal sealed class MetaManager _expressions?.SetCreatureStore(store); } + // The plugin's kill clock (secondssincelastkill[], No Kills Within Minutes). Without one + // (never in the plugin) the condition is false and the function says 0: fail closed. + private KillClock? _killClock; + public void SetKillClock(KillClock? clock) + { + _killClock = clock; + _expressions?.SetKillClock(clock); + } + public void SetPlayerId(uint id) { _playerId = id; @@ -200,6 +209,7 @@ internal sealed class MetaManager engine.SetQuestTracker(_questTracker); engine.SetSettings(_settings); engine.SetCreatureStore(_creatureStore); + engine.SetKillClock(_killClock); return engine; } @@ -727,6 +737,14 @@ internal sealed class MetaManager case MetaConditionType.NeedToBuff: return _buffManager != null && _buffManager.NeedsAnyBuff(); + // ── No kills within N minutes (RynthAi only) ────────────────────── + // The secondssincelastkill[] clock: our last kill (KillerNotification), or before + // the first one the last macro start / login. Bad or missing minutes never hold. + case MetaConditionType.NoKillsWithinMinutes: + return _killClock != null + && KillClock.TryParseMinutes(rule.ConditionData, out double noKillMins) + && _killClock.NoKillsFor(noKillMins); + default: return false; } } @@ -892,7 +910,7 @@ internal sealed class MetaManager } // Fallback: a standalone .nav file in NavProfiles. - string navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles"; + string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles"); string fullPath = Path.Combine(navFolder, routeName + ".nav"); if (File.Exists(fullPath)) { @@ -1091,7 +1109,7 @@ internal sealed class MetaManager parts[2].Equals("load", StringComparison.OrdinalIgnoreCase)) { string name = string.Join(" ", parts, 3, parts.Length - 3); - string metaDir = @"C:\Games\RynthSuite\RynthAi\MetaFiles"; + string metaDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles"); string afPath = Path.Combine(metaDir, name + ".af"); string metPath = Path.Combine(metaDir, name + ".met"); @@ -1155,7 +1173,7 @@ internal sealed class MetaManager string path = name; if (!File.Exists(path)) { - string folder = @"C:\Games\RynthSuite\RynthAi\LootProfiles"; + string folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles"); string stem = name.EndsWith(".utl", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".json", StringComparison.OrdinalIgnoreCase) ? name : name + ".utl"; string candidate = Path.Combine(folder, stem); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaRuleEdits.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaRuleEdits.cs new file mode 100644 index 0000000..1fa2d37 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaRuleEdits.cs @@ -0,0 +1,52 @@ +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi.Meta; + +/// +/// How a rule edited in the Meta panel replaces the running one (update_rule / duplicate_rule). +/// +/// The engine's Meta editor saves every change on its own since 2026-10-05 (debounced), so an +/// update must not disturb a meta that is running: +/// - the rule keeps its runtime latch (HasFired) and LastFiredAt. A fresh MetaRule had +/// HasFired = false, so every save of a rule in the current state fired it again +/// (an IF Always DO EmbedNav rule restarted its route from point 0 on each save); +/// - the panel's DTO has no CallReturnState (CallState's return state) or ChatColors +/// (ChatCapture's chat types), so an update used to drop both from VTank-imported rules. +/// They are kept while the rule still has that action / condition. +/// Nothing here touches the current state, the state clocks, the watchdog or the call stack. +/// +internal static class MetaRuleEdits +{ + /// Puts at , keeping the old rule's + /// runtime latch and the fields the panel can't send. False when the index is out of range. + public static bool Replace(List rules, int index, MetaRule edited) + { + if (index < 0 || index >= rules.Count) return false; + MetaRule old = rules[index]; + KeepHidden(old, edited); + edited.HasFired = old.HasFired; + edited.LastFiredAt = old.LastFiredAt; + rules[index] = edited; + return true; + } + + /// Copies CallReturnState / ChatColors from into an edited copy + /// that still has the same action / condition and carries none of its own; children by position. + public static void KeepHidden(MetaRule from, MetaRule to) + { + if (to.Action == MetaActionType.CallMetaState && from.Action == MetaActionType.CallMetaState + && string.IsNullOrEmpty(to.CallReturnState)) + to.CallReturnState = from.CallReturnState; + if (to.Condition == MetaConditionType.ChatMessageCapture && from.Condition == MetaConditionType.ChatMessageCapture + && string.IsNullOrEmpty(to.ChatColors)) + to.ChatColors = from.ChatColors; + + if (from.Children != null && to.Children != null) + for (int i = 0; i < from.Children.Count && i < to.Children.Count; i++) + KeepHidden(from.Children[i], to.Children[i]); + if (from.ActionChildren != null && to.ActionChildren != null) + for (int i = 0; i < from.ActionChildren.Count && i < to.ActionChildren.Count; i++) + KeepHidden(from.ActionChildren[i], to.ActionChildren[i]); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaSchema.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaSchema.cs index dbb3161..83b60c9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaSchema.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaSchema.cs @@ -72,6 +72,8 @@ internal static class MetaSchema new(MetaConditionType.MainManaPHE, "MainManaPHE", "Main Mana % >="), new(MetaConditionType.MainStamLE, "MainStamLE", "Main Stam <="), new(MetaConditionType.VitaePHE, "VitaePHE", "Vitae % >="), + // RynthAi only: VTank and metaf have no such condition (see AfFileWriter). + new(MetaConditionType.NoKillsWithinMinutes, "NoKillsInMins", "No Kills Within Minutes"), }; // Index == (int)MetaActionType. diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavMarkerRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/NavMarkerRenderer.cs index 4f39261..ecc3b52 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavMarkerRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavMarkerRenderer.cs @@ -3,6 +3,7 @@ using System.Numerics; using ImGuiNET; using RynthCore.Plugin.RynthAi.LegacyUi; using RynthCore.PluginSdk; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi; @@ -249,6 +250,13 @@ internal sealed class NavMarkerRenderer int n = route.Points.Count; bool circular = route.RouteType == NavRouteType.Circular; + // ── Waypoint labels and guide line (both off by default) ───── + // Worked out from the route here, on the plugin tick, into an immutable frame; the + // emit steps read only that frame. The guide goes in first so the route's lines can't + // crowd it out of the engine's line buffer; the labels go in last (pass 4). + NavOverlayFrame overlay = BuildOverlay(route, px, py, pz, playerNS, playerEW, heightOffset); + NavOverlay.EmitGuide(overlay, _sink ??= new HostNav3DSink(_host), lineThick); + // ── Pass 1: Submit rings ───────────────────────────────────── // Arrays are indexed by window slot k (0..count), not absolute route // index — the absolute index can run far past count on a long route. @@ -339,6 +347,68 @@ internal sealed class NavMarkerRenderer _host.Nav3DAddRing(pwx, pwy, pwz, ringRadius, ringThick * 1.4f, ColorPortal3D); _host.Nav3DAddLine(px, pwy, py, pwx, pwy, pwz, lineThick, ColorPortal3D); } + + // ── Pass 4: waypoint labels (filled strokes, Nav3D triangles) ─ + if (overlay.Labels.Count > 0 && _host.HasNav3DTriangle) + NavOverlay.EmitLabels(overlay, _sink); + } + + // ── Labels and guide line ──────────────────────────────────────── + private NavOverlay.RouteText? _labelText; + private INav3DSink? _sink; + + /// + /// The tick's labels and guide line from the route and the two settings (Navigation ▸ + /// Waypoint Labels / Guide Line). Plugin tick only; returns an immutable frame. + /// + internal NavOverlayFrame BuildOverlay(NavRouteParser route, float px, float py, float pz, + double playerNS, double playerEW, float heightOffset) + { + int mode = NavLabelModes.Clamp(_settings.NavLabelMode); + bool guideOn = _settings.NavGuideLine; + if (mode == NavLabelModes.Off && !guideOn) + { + _labelText = null; + return NavOverlayFrame.Empty; + } + + var points = route.Points; + int n = points.Count; + NavOverlay.RouteText? text = null; + if (mode != NavLabelModes.Off) + { + // Rebuilt only when the route, its length or the mode change (an edit in place keeps + // the count: the Nav panel's edits replace the route or change its length). + text = _labelText; + if (text == null || !ReferenceEquals(text.Route, route) || text.Count != n || text.Mode != mode) + _labelText = text = NavOverlay.BuildText(route, points, mode, SpellDatabase.GetSpellNameOrId); + } + else _labelText = null; + + int active = _settings.ActiveNavIndex; + bool guide = guideOn && active >= 0 && active < n && HasGroundCoords(points[active].Type); + + (float X, float Y, float Z) WorldOf(int i) + { + var pt = points[i]; + return (px + (float)((pt.EW - playerEW) * 240.0), + ResolveMarkerWorldY(route, i, heightOffset), + py + (float)((pt.NS - playerNS) * 240.0)); + } + + // D3D frame: X = EW, Y = height, Z = NS; the player's height is pose z. + return NavOverlay.BuildFrame(text, guide, active, WorldOf, px, pz, py, heightOffset); + } + + /// The engine's Nav3D buffer. + private sealed class HostNav3DSink : INav3DSink + { + private readonly RynthCoreHost _host; + public HostNav3DSink(RynthCoreHost host) => _host = host; + public void Line(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb) + => _host.Nav3DAddLine(x1, y1, z1, x2, y2, z2, thickness, colorArgb); + public void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint colorArgb) + => _host.Nav3DAddTriangle(x1, y1, z1, x2, y2, z2, x3, y3, z3, colorArgb); } private void PrepareFloorCache(NavRouteParser route) diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavOverlay.cs b/Plugins/RynthCore.Plugin.RynthAi/NavOverlay.cs new file mode 100644 index 0000000..5607b81 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/NavOverlay.cs @@ -0,0 +1,234 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +/// Settings ▸ Navigation ▸ "Waypoint Labels" (LegacyUiSettings.NavLabelMode). +internal static class NavLabelModes +{ + public const int Off = 0, Numbers = 1, Names = 2; + public static int Clamp(int mode) => mode is >= Off and <= Names ? mode : Off; +} + +/// +/// One tick's waypoint labels and guide line, worked out from the route on the plugin tick and +/// then never changed: the emit step reads only this, never the route's lists. Positions are in +/// the Nav3D frame NavMarkerRenderer uses (X = east metres, Y = height, Z = north metres, in +/// the player's landblock). +/// +internal sealed class NavOverlayFrame +{ + public static readonly NavOverlayFrame Empty = new(Array.Empty(), null, 0f, 0f, 0f); + + public NavOverlayFrame(NavLabel[] labels, NavGuide? guide, float playerX, float playerY, float playerZ) + { + Labels = labels; + Guide = guide; + PlayerX = playerX; + PlayerY = playerY; + PlayerZ = playerZ; + } + + public IReadOnlyList Labels { get; } + public NavGuide? Guide { get; } + public float PlayerX { get; } + public float PlayerY { get; } + public float PlayerZ { get; } +} + +/// One text line over a waypoint. Row 0 sits just above the ring; higher rows stack above it. +internal sealed record NavLabel(float X, float Y, float Z, string Text, int Row, uint Color); + +/// The line from the character's feet to the waypoint nav is heading for. +internal sealed record NavGuide(float X1, float Y1, float Z1, float X2, float Y2, float Z2, uint Color); + +/// +/// Waypoint labels (numbers, or numbers and what happens there) and the guide line for the Nav3D +/// markers (Silentkelpie's rynth PR #1 idea, done on our pump-thread Nav3D path). Both are off by +/// default. Labels are drawn as filled strokes (Nav3D triangles) on an upright plane turned toward +/// the character, sized up with distance so far labels stay readable; the guide is one Nav3D line. +/// +internal static class NavOverlay +{ + /// Labels further than this from the character are left out (metres). + public const float LabelRange = 60f; + /// At most this many label lines a tick, nearest first (the active point's always first). + public const int MaxLabelLines = 24; + /// At most this many action lines stacked over one point. + public const int MaxActionLines = 3; + /// Triangle budget for all labels together (the engine keeps 8192 a tick for every plugin). + public const int MaxLabelTriangles = 1600; + public const int MaxLabelChars = 22; + + public const uint LabelColor = 0xFFE6FFFF; // near white, a cyan touch like the rings + public const uint ActiveLabelColor = 0xFFFF6A6A; + public const uint ActionLabelColor = 0xFFFFC040; + public const uint GuideColor = 0xFFFFD21E; + + private const float GuideLift = 0.05f; + private const float MaxGuideLength = 500f; + + // ── Text per route (rebuilt when the route or the mode changes) ────── + + /// + /// Label text for every route point, built once per route and mode: Own[i] for a point + /// with ground coordinates (null otherwise), and the action lines ("13 RECALL ...") hung on + /// the ground point before them (the point where nav does them). + /// + internal sealed class RouteText + { + public readonly object Route; + public readonly int Count, Mode; + public readonly string?[] Own; + public readonly string[]?[] Actions; + + public RouteText(object route, int count, int mode, string?[] own, string[]?[] actions) + { + Route = route; Count = count; Mode = mode; Own = own; Actions = actions; + } + } + + public static RouteText BuildText(object route, IReadOnlyList points, int mode, Func spellName) + { + int n = points.Count; + var own = new string?[n]; + var actions = new string[]?[n]; + var pending = new List(); + int lastGround = -1; + for (int i = 0; i < n; i++) + { + NavPoint p = points[i]; + if (HasGroundCoords(p.Type)) + { + own[i] = mode == NavLabelModes.Names ? Fit(GroundName(i, p)) : i.ToString(); + lastGround = i; + continue; + } + if (mode != NavLabelModes.Names || lastGround < 0) continue; + var list = actions[lastGround] ??= Array.Empty(); + if (list.Length < MaxActionLines) + actions[lastGround] = Append(list, Fit(ActionName(i, p, spellName))); + else if (list.Length == MaxActionLines) + actions[lastGround] = Append(list, "..."); + } + return new RouteText(route, n, mode, own, actions); + } + + private static string[] Append(string[] a, string s) + { + var b = new string[a.Length + 1]; + Array.Copy(a, b, a.Length); + b[a.Length] = s; + return b; + } + + private static bool HasGroundCoords(NavPointType t) => NavRouteParser.IsPlainWaypoint(t) || t == NavPointType.Jump; + + private static string GroundName(int i, NavPoint p) => p.Type switch + { + NavPointType.Checkpoint => $"{i} CHECKPOINT", + NavPointType.Jump => $"{i} JUMP", + _ => i.ToString(), + }; + + private static string ActionName(int i, NavPoint p, Func spellName) => p.Type switch + { + NavPointType.Recall => $"{i} {spellName(p.SpellId)}", + NavPointType.Pause => $"{i} PAUSE {Math.Max(0, p.PauseTimeMs) / 1000.0:0.#}S", + NavPointType.Chat => $"{i} CHAT {p.ChatCommand}", + NavPointType.OpenVendor => $"{i} VENDOR {p.TargetName}", + NavPointType.PortalNPC => $"{i} PORTAL {p.TargetName}", + NavPointType.Npc => $"{i} NPC {p.TargetName}", + _ => $"{i} {p.Type}", + }; + + private static string Fit(string s) + { + s = s.Trim().ToUpperInvariant(); + return s.Length > MaxLabelChars ? s[..(MaxLabelChars - 2)] + ".." : s; + } + + // ── The frame (plugin tick) ─────────────────────────────────────── + + /// + /// Builds the tick's overlay from (null: no labels) and the waypoints' + /// positions (, only asked for points that have ground coordinates). + /// is the point nav is heading for; draws the + /// line to it (the caller passes false when that point has no ground coordinates). Plugin tick only. + /// + public static NavOverlayFrame BuildFrame(RouteText? text, bool guide, int active, + Func worldOf, float playerX, float playerY, float playerZ, float lift) + { + NavGuide? g = null; + if (guide && active >= 0) + { + var (ax, ay, az) = worldOf(active); + float dx = ax - playerX, dz = az - playerZ; + if (dx * dx + dz * dz <= MaxGuideLength * MaxGuideLength) + g = new NavGuide(playerX, playerY + lift + GuideLift, playerZ, ax, ay, az, GuideColor); + } + + if (text == null || text.Mode == NavLabelModes.Off) + return g == null ? NavOverlayFrame.Empty : new NavOverlayFrame(Array.Empty(), g, playerX, playerY, playerZ); + + // Ground points in range, nearest first; the active point first of all. + var near = new List<(float D2, int I, float X, float Y, float Z)>(); + float range2 = LabelRange * LabelRange; + for (int i = 0; i < text.Count; i++) + { + if (text.Own[i] == null) continue; + var (x, y, z) = worldOf(i); + float dx = x - playerX, dz = z - playerZ; + float d2 = dx * dx + dz * dz; + if (d2 > range2) continue; + near.Add((i == active ? -1f : d2, i, x, y, z)); + } + near.Sort((a, b) => a.D2.CompareTo(b.D2)); + + var labels = new List(Math.Min(MaxLabelLines, near.Count * 2)); + foreach (var (_, i, x, y, z) in near) + { + if (labels.Count >= MaxLabelLines) break; + labels.Add(new NavLabel(x, y, z, text.Own[i]!, 0, i == active ? ActiveLabelColor : LabelColor)); + string[]? acts = text.Actions[i]; + if (acts == null) continue; + for (int k = 0; k < acts.Length && labels.Count < MaxLabelLines; k++) + labels.Add(new NavLabel(x, y, z, acts[k], k + 1, ActionLabelColor)); + } + return new NavOverlayFrame(labels.ToArray(), g, playerX, playerY, playerZ); + } + + // ── Emit (plugin tick, into the Nav3D buffer) ────────────────────── + + /// The guide line, if the frame has one: submitted before the route's lines so a full line buffer never drops it. + public static void EmitGuide(NavOverlayFrame frame, INav3DSink sink, float thickness) + { + NavGuide? g = frame.Guide; + if (g != null) + sink.Line(g.X1, g.Y1, g.Z1, g.X2, g.Y2, g.Z2, thickness, g.Color); + } + + /// + /// Each label as filled strokes (triangles). Returns the number of triangles used (at most + /// ). + /// + public static int EmitLabels(NavOverlayFrame frame, INav3DSink sink) + { + int tris = 0; + foreach (NavLabel l in frame.Labels) + { + if (!EmitLabel(l, frame.PlayerX, frame.PlayerZ, sink, ref tris)) break; + } + return tris; + } + + /// The line height (m) for a label this far from the character. + internal static float LineHeight(float distance) => Nav3DText.LineHeight(distance); + + // The text itself is drawn by the shared Nav3DText (Plugins/Shared/Nav3DText.cs), which + // RynthNav's path markers use too. + private static bool EmitLabel(NavLabel l, float playerX, float playerZ, INav3DSink sink, ref int tris) + => Nav3DText.Emit(l.X, l.Y, l.Z, l.Text, l.Row, l.Color, playerX, playerZ, sink, ref tris, MaxLabelTriangles); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs index 38f1c02..da7361d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs @@ -75,7 +75,16 @@ internal sealed class NavigationEngine private bool _inPause; private int _pauseIdx = -1; // the Pause waypoint _pauseUntil belongs to private long _pauseUntil; - private double _prevDist = double.MaxValue; + // Closest the character has come to the current waypoint since it became the target (or + // since a pause / escape / teleport reset it). It used to hold only the previous tick's + // distance, so a "sweep pass" needed the distance to grow 0.3 yd in ONE 33 ms tick (over + // 9 yd/s straight away from the point): just past a point the distance grows slowly, the + // pass was never seen, and nav turned round and walked back to the point (2026-10-05). + private double _closestDist = double.MaxValue; + // Where the character stood when it started on the current waypoint (NaN = take it on the + // next steering tick). With the waypoint it gives the way the route arrives at the point, + // for the pass-through rule (PassedThrough). + private double _legStartNs = double.NaN, _legStartEw = double.NaN; // ── Portal/Recall state machine ────────────────────────────────────────── private enum PortalState @@ -147,7 +156,7 @@ internal sealed class NavigationEngine public int Doorways; public long StartedAt; public long DeadlineAt; - public double PrevDist = double.MaxValue; + public double ClosestDist = double.MaxValue; // closest to the current detour point so far public bool Paused; // nav was stopped (combat, loot, buff, door) mid-detour public long PausedAt; public double PausedNs = double.NaN, PausedEw = double.NaN; @@ -244,10 +253,39 @@ internal sealed class NavigationEngine private double ReachFor(NavPoint p) => p.Doorway ? Math.Min(ArrivalYards, DoorwayReachYd) : ArrivalYards; private double SweepFor(NavPoint p) => ReachFor(p) * (p.Doorway ? Math.Min(SweepMult, DoorwaySweepMult) : SweepMult); - // Lookahead: within this distance of a waypoint, blend the aim point toward - // the next one so corners are cut smoothly. 0 = off (aim straight at each - // waypoint). Tunable in Advanced ▸ Navigation ▸ Steering. - private double LookaheadYards => Math.Max(0.0, _settings.NavLookaheadYards); + // Lookahead (corner rounding): within this distance of a waypoint, blend the aim point + // toward the next one so corners are rounded. It used to be the Lookahead setting alone + // (4 yd), whatever the nav point reach: at a 1 yd reach the aim was already 75% of the way + // down the next leg when the character got to 1 yd, so it cut the corner, never got within + // the reach, and ran into the wall at the corner (2026-10-05). Now the reach decides how + // much rounding there is: none at or under CornerRoundFreeReachYd, then CornerRoundPerReachYd + // per yard of reach above it, never more than the Lookahead setting (Advanced > Navigation > + // Steering; 0 = off). Blending only matters where it starts outside the reach, so there is + // none up to a 2 yd reach (the 1.5 yd default gives 1 yd, inside it); it reaches the 4 yd + // setting at a 3 yd reach, so 3-5 yd round corners as before. Doorway points never blend. + internal const double CornerRoundFreeReachYd = 1.0, CornerRoundPerReachYd = 2.0; + internal static double CornerLookaheadYards(double lookaheadSetting, double reachYd) + => Math.Clamp(CornerRoundPerReachYd * (reachYd - CornerRoundFreeReachYd), 0.0, Math.Max(0.0, lookaheadSetting)); + private double LookaheadYards => CornerLookaheadYards(_settings.NavLookaheadYards, ArrivalYards); + + // Pass-through: a plain waypoint the character has gone past (it is beyond the point along + // the way it came, and no farther to the side than the sweep radius) counts as reached, + // so nav doesn't turn round to walk back to it. "Beyond along the way it came" means the + // point is behind the character: a corner cut toward the next point never qualifies. + // Doorway points keep their own tight reach and sweep and never use it. + private const double PassMinLegYd = 1.0; // shorter approach: no reliable direction + private bool PassedThrough(NavPoint pt, double ns, double ew) + { + if (pt.Doorway || double.IsNaN(_legStartNs)) return false; + double ux = (pt.NS - _legStartNs) * 240.0, uy = (pt.EW - _legStartEw) * 240.0; + double len = Math.Sqrt(ux * ux + uy * uy); + if (len < PassMinLegYd) return false; + ux /= len; uy /= len; + double ax = (ns - pt.NS) * 240.0, ay = (ew - pt.EW) * 240.0; + double along = ax * ux + ay * uy; + double side = Math.Abs(ax * uy - ay * ux); + return along > 0.0 && side <= SweepFor(pt); + } // Mode 0 heading servo: cap the heading change we command per tick so the @@ -411,7 +449,7 @@ internal sealed class NavigationEngine { _lastRoute = route; _inPause = false; - _prevDist = double.MaxValue; + _closestDist = double.MaxValue; _linearDir = 1; _watchdogNs = double.NaN; _watchdogEw = double.NaN; @@ -462,7 +500,7 @@ internal sealed class NavigationEngine _watchdogNs = double.NaN; _watchdogEw = double.NaN; _watchdogNext = Now + (long)WatchdogMs; - _prevDist = double.MaxValue; + _closestDist = double.MaxValue; _globalSettling = false; ResetRecovery("teleported"); } @@ -582,7 +620,7 @@ internal sealed class NavigationEngine if (dist < ReachFor(pt)) { _host.Log($"Nav: arrived at [{idx}] dist={dist:F1}yd → advancing"); - _prevDist = double.MaxValue; + _closestDist = double.MaxValue; UpdateStatusLine(idx, dist, route, 0.0); // Advance before the jump: the Jumper pauses nav and later restores what it // saw, so jumping first turned a finished Once route back on (re-run from [0]). @@ -591,17 +629,33 @@ internal sealed class NavigationEngine return; } - // Closest-approach detection — prevents circling. - // Matches old NavigationManager exactly. - if (_prevDist < SweepFor(pt) && dist > _prevDist + 0.3) + // First tick on this waypoint (or after a pause / escape / teleport): remember where + // the approach starts, for the pass-through rule. + if (_closestDist == double.MaxValue) { _legStartNs = ns; _legStartEw = ew; } + + // Went past it: the point is behind, close enough to the side. Counts as reached + // instead of turning round to walk back to it. + if (PassedThrough(pt, ns, ew)) { - _host.Log($"Nav: sweep-pass [{idx}] prev={_prevDist:F1} now={dist:F1}yd → advancing"); - _prevDist = double.MaxValue; + _host.Log($"Nav: passed [{idx}] dist={dist:F1}yd → advancing"); + _closestDist = double.MaxValue; + UpdateStatusLine(idx, dist, route, 0.0); Advance(route); if (pt.Type == NavPointType.Jump) FireJump(pt, idx); return; } - _prevDist = dist; + + // Closest-approach detection — prevents circling: within the sweep radius, then + // 0.3 yd farther out than the closest it came. + if (_closestDist < SweepFor(pt) && dist > _closestDist + 0.3) + { + _host.Log($"Nav: sweep-pass [{idx}] closest={_closestDist:F1} now={dist:F1}yd → advancing"); + _closestDist = double.MaxValue; + Advance(route); + if (pt.Type == NavPointType.Jump) FireJump(pt, idx); + return; + } + _closestDist = Math.Min(_closestDist, dist); SteerToWaypoint(idx, pt, route, ns, ew, dist); } @@ -622,7 +676,7 @@ internal sealed class NavigationEngine // closest-approach reading from before the pause says nothing about where we // are now; kept, the first tick back reads the displacement as a sweep-pass // and advances past a waypoint that was never reached. - _prevDist = double.MaxValue; + _closestDist = double.MaxValue; _stopRequestedAt = long.MaxValue; // A detour survives the pause: it re-plans on the way back if the pause // moved us. Whatever moved us, being far off the route afterwards is not @@ -689,7 +743,7 @@ internal sealed class NavigationEngine _host.Log($"Nav: macro start — {how} waypoint [{best}] ({Math.Sqrt(Sq(route.Points[best].NS - ns) + Sq(route.Points[best].EW - ew)) * 240.0:F0}yd) instead of [{cur}]"); _settings.ActiveNavIndex = best; - _prevDist = double.MaxValue; + _closestDist = double.MaxValue; _stuckCount = 0; _watchdogNs = double.NaN; _watchdogEw = double.NaN; @@ -747,7 +801,7 @@ internal sealed class NavigationEngine _linearDir = 1; _stuckCount = 0; _recoveryKind = RecoveryKind.Jump; - _prevDist = double.MaxValue; + _closestDist = double.MaxValue; _watchdogNs = double.NaN; _watchdogEw = double.NaN; _hasGoodHeading = false; @@ -1146,7 +1200,7 @@ internal sealed class NavigationEngine private void Advance(NavRouteParser route) { int oldIdx = _settings.ActiveNavIndex; - _prevDist = double.MaxValue; + _closestDist = double.MaxValue; _portalState = PortalState.None; // Reaching a waypoint is progress: the next snag gets a fresh detour budget. _detourAttempts = 0; @@ -1238,7 +1292,7 @@ internal sealed class NavigationEngine /// current route's iteration direction. Used by the dense-waypoint /// skip loop in . Mirrors the single-step logic /// in the main switch; factored out so the skip loop can call it - /// without re-clearing _prevDist / _portalState. + /// without re-clearing _closestDist / _portalState. /// private void AdvanceOneIndex(NavRouteParser route) { @@ -1352,7 +1406,7 @@ internal sealed class NavigationEngine private void HoldAtCampRoute(int idx, double dist, NavRouteParser route) { if (_isMovingForward || _isTurning) StopMovement(); - _prevDist = double.MaxValue; + _closestDist = double.MaxValue; UpdateStatusLine(idx, dist, route, 0.0); if (!_campHoldAnnounced) { @@ -1448,7 +1502,7 @@ internal sealed class NavigationEngine _host.Log($"Nav: no player id — cannot fire recall {pt.SpellId}"); return; } - _host.CastSpell(target, pt.SpellId); + _host.CastSpellFor(target, pt.SpellId, "Nav", $"recall spell {pt.SpellId}"); _host.Log($"Nav: CastSpell(recall {pt.SpellId}) on player 0x{target:X8}"); } @@ -2229,7 +2283,7 @@ internal sealed class NavigationEngine // The escape moves us off the approach line, so the closest-approach // tracker's last reading is meaningless — reset it or the next steer // tick reads the retreat as a sweep-pass and advances the index. - _prevDist = double.MaxValue; + _closestDist = double.MaxValue; } // ══════════════════════════════════════════════════════════════════════════ @@ -2577,7 +2631,7 @@ internal sealed class NavigationEngine StopMovement(); _inRecovery = false; - _prevDist = double.MaxValue; + _closestDist = double.MaxValue; _settings.NavIsStuck = true; return true; } @@ -2604,7 +2658,7 @@ internal sealed class NavigationEngine + $"reached {Math.Min(d.Index, d.Points.Count)}/{d.Points.Count}, door requests {d.DoorRequestCount}, re-plans {d.Replans}, " + $"{(Now - d.StartedAt) / 1000.0:F1}s - result: {result}"); - _prevDist = double.MaxValue; + _closestDist = double.MaxValue; if (!_inRecovery) _settings.NavIsStuck = false; } @@ -2635,7 +2689,7 @@ internal sealed class NavigationEngine // against the deadline; if the pause moved us, plan again from here. d.Paused = false; d.DeadlineAt += Now - d.PausedAt; - d.PrevDist = double.MaxValue; + d.ClosestDist = double.MaxValue; double moved = double.IsNaN(d.PausedNs) ? 0.0 : NavYd(ns - d.PausedNs, ew - d.PausedEw); if (moved > DetourReplanMovedYd && !ReplanDetour(route, d, moved)) return; } @@ -2650,10 +2704,10 @@ internal sealed class NavigationEngine var p = d.Points[d.Index]; double dist = NavYd(p.NS - ns, p.EW - ew); - if (dist < ReachFor(p) || (d.PrevDist < SweepFor(p) && dist > d.PrevDist + 0.3)) + if (dist < ReachFor(p) || (d.ClosestDist < SweepFor(p) && dist > d.ClosestDist + 0.3)) { d.Index++; - d.PrevDist = double.MaxValue; + d.ClosestDist = double.MaxValue; if (d.Index >= d.Points.Count) { // Back on the route: resume at the rejoin waypoint; normal nav walks the last leg. @@ -2662,7 +2716,7 @@ internal sealed class NavigationEngine } return; } - d.PrevDist = dist; + d.ClosestDist = Math.Min(d.ClosestDist, dist); // Aim point: blend toward the following point near arrival, but less than the // route does (doorways are narrow). diff --git a/Plugins/RynthCore.Plugin.RynthAi/RadarWallRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/RadarWallRenderer.cs index f128203..448f37f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RadarWallRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RadarWallRenderer.cs @@ -49,7 +49,7 @@ internal sealed class RadarWallRenderer private readonly bool[] _inside = new bool[MaxPolyVerts]; private static readonly string ExploredDir = - @"C:\Games\RynthSuite\RynthAi\ExploredDungeons"; + System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "ExploredDungeons"); public RadarWallRenderer(RynthCoreHost host, LegacyUiSettings settings) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 5e25525..cee01bb 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -36,6 +36,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra attackable — check if target is attackable"); ChatLine("[RynthAi] /ra wielded — show wielded items"); ChatLine("[RynthAi] /ra dumpprops [0xId] — every property of the selection (else yourself)"); + ChatLine("[RynthAi] /ra iteminfo [name] — the selected (or named) item's details, Mag-Tools style"); ChatLine("[RynthAi] /ra mexec — evaluate meta expression"); ChatLine("[RynthAi] /ra listvars — show session variables"); ChatLine("[RynthAi] /ra listpvars — show persistent variables"); @@ -68,6 +69,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra hazard add|del|list|near — mark current cell as lava/acid so patrol avoids it"); ChatLine("[RynthAi] /ra jump[swzxc] [heading] [holdtime] — jump with optional face/direction (s=run w=fwd x=back z=strafeL c=strafeR)"); ChatLine("[RynthAi] /ra corpseinfo — show corpse range/open diagnostics"); + ChatLine("[RynthAi] /ra pace — what the server is still answering (one action at a time)"); ChatLine("[RynthAi] /ra owncorpse [go|stop] — where your corpse is; travel back to it, or stop"); ChatLine("[RynthAi] /ra corpsecheck — explain whether a corpse would be looted"); ChatLine("[RynthAi] /ra corpseopen — force the nearest corpse open flow"); @@ -240,7 +242,7 @@ public sealed partial class RynthAiPlugin return; } - bool ok = Host.CastSpell(_currentTargetId, spellId); + bool ok = Host.CastSpellFor(_currentTargetId, spellId, "Command", $"spell {spellId} (/ra cast)", asked: true); ChatLine($"[RynthAi] CastSpell(target=0x{_currentTargetId:X8}, spell={spellId}) => {ok}"); } @@ -2148,6 +2150,8 @@ public sealed partial class RynthAiPlugin private void HandleClearBusyCommand() { int before = Host.HasGetBusyState ? Host.GetBusyState() : -1; + // You asked for it: forget what the pacing waits on too (ActionPacer). + RynthCore.Plugin.Shared.ActionPacer.Forget("/ra clearbusy"); if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount(); if (Host.HasStopCompletely) @@ -2171,9 +2175,10 @@ public sealed partial class RynthAiPlugin { int before = Host.HasGetBusyState ? Host.GetBusyState() : -1; ChatLine("[RynthAi] PANIC — full AC state reset"); + RynthCore.Plugin.Shared.ActionPacer.Forget("/ra panic"); if (Host.HasCancelAttack) Host.CancelAttack(); - if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat); + if (Host.HasChangeCombatMode) Host.ChangeCombatModeFor(CombatMode.NonCombat, "Command", "/ra panic", force: true); if (Host.HasStopCompletely) Host.StopCompletelyBy("Command"); if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount(); // The item-action lock itself is not the busy count: AC refuses every use, @@ -2612,7 +2617,7 @@ public sealed partial class RynthAiPlugin string playerPart = argStr.Substring(toIdx + 4).Trim(); // Resolve profile path — bare name resolved from ItemGiver dir, .utl extension added if needed - const string itemGiverDir = @"C:\Games\RynthSuite\RynthAi\ItemGiver"; + string itemGiverDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "ItemGiver"); string profilePath = System.IO.Path.IsPathRooted(profileArg) ? profileArg : System.IO.Path.Combine(itemGiverDir, profileArg); @@ -2975,7 +2980,7 @@ public sealed partial class RynthAiPlugin sb.Append("\"routes\":["); try { - const string navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles"; + string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles"); if (System.IO.Directory.Exists(navFolder)) { var files = System.IO.Directory.GetFiles(navFolder, "*.nav"); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs new file mode 100644 index 0000000..9b6c5ef --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs @@ -0,0 +1,189 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.ItemInfo; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// /ra iteminfo [name]: a selected (or named) item's details on one chat line, Mag-Tools +/// style (ItemInfo/ItemInfoText). An item the client hasn't appraised is identified first +/// and printed when the appraisal arrives, or after with +/// what the client has. Partial class of RynthAiPlugin. +/// +/// Threads: the command only queues its argument; on the plugin +/// tick does every host read, the ID request and the print. Nothing is drawn. +/// +public sealed partial class RynthAiPlugin +{ + internal const long ItemInfoTimeoutMs = 5000; + + /// Test seam: the clock the ID timeout runs on. + internal static Func ItemInfoClock = () => Environment.TickCount64; + + private readonly ConcurrentQueue _itemInfoRequests = new(); + // One item waiting for its appraisal at a time (tick thread only); a newer request replaces it. + private uint _itemInfoPendingId; + private long _itemInfoDeadline; + + /// /ra iteminfo [item name]. Queued for the next tick. + private void HandleItemInfoCommand(string[] parts) + { + string arg = parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2).Trim() : string.Empty; + if (arg.Equals("help", StringComparison.OrdinalIgnoreCase) || arg == "?") + { + ChatLine("[RynthAi] /ra iteminfo - the selected item's details (identifies it first when needed)."); + ChatLine("[RynthAi] /ra iteminfo - the first item in your inventory with that name (else one whose name contains it)."); + return; + } + if (_itemInfoRequests.Count < 8) _itemInfoRequests.Enqueue(arg); + } + + /// Plugin tick: starts queued requests, prints an item once its ID lands or times out. + private void TickItemInfo() + { + while (_itemInfoRequests.TryDequeue(out string? arg)) + StartItemInfo(arg); + + uint selected = System.Threading.Interlocked.Exchange(ref _itemInfoSelectId, 0); + if (selected != 0) + StartItemInfoFor(selected, quiet: true); + + uint pending = _itemInfoPendingId; + if (pending == 0) return; + bool appraised = !Host.HasHasAppraisalData || Host.HasAppraisalData(pending); + if (appraised || ItemInfoClock() >= _itemInfoDeadline) + { + _itemInfoPendingId = 0; + PrintItemInfo(pending, identified: appraised); + } + } + + private void StartItemInfo(string arg) + { + uint id; + if (arg.Length == 0) + { + id = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0; + if (id == 0) + { + ChatLine("[RynthAi] Item info: nothing selected. Select an item, or /ra iteminfo ."); + return; + } + } + else + { + id = FindInventoryItemByName(arg); + if (id == 0) + { + ChatLine($"[RynthAi] Item info: no \"{arg}\" in your inventory."); + return; + } + } + StartItemInfoFor(id, quiet: false); + } + + /// + /// Prints now when it's appraised, else asks for its ID and prints when + /// it lands. (Item Info On Select): no "identifying" chatter. + /// + private void StartItemInfoFor(uint id, bool quiet) + { + if (!Host.HasHasAppraisalData || Host.HasAppraisalData(id)) + { + if (_itemInfoPendingId == id) _itemInfoPendingId = 0; + PrintItemInfo(id, identified: true); + return; + } + + if (!quiet && _itemInfoPendingId != 0 && _itemInfoPendingId != id) + ChatLine($"[RynthAi] Item info: stopped waiting for {ObjectNameOr(_itemInfoPendingId)}."); + if (Host.HasRequestId) Host.RequestId(id); + _itemInfoPendingId = id; + _itemInfoDeadline = ItemInfoClock() + ItemInfoTimeoutMs; + if (!quiet) ChatLine($"[RynthAi] Item info: identifying {ObjectNameOr(id)}..."); + } + + // Item Info On Select: the item the player just selected, for the next tick (0 = none). + private uint _itemInfoSelectId; + + /// + /// Selection change (OnSelectedTargetChange): queues Item Info for an item the player + /// selected. Skips non-items and RynthAi's own selections (the looter, metas). + /// + private void QueueItemInfoOnSelect(uint id, WorldObject? obj) + { + if (id == 0 || _dashboard?.Settings is not { ItemInfoOnSelect: true }) return; + if (obj == null || !IsLootableClass(obj.ObjectClass)) return; + if (SelfSelect.IsOurs(id)) return; + System.Threading.Interlocked.Exchange(ref _itemInfoSelectId, id); + } + + /// + /// An inventory item (carried or worn) whose name is , ignoring case; + /// else the first whose name contains it. 0 when none. + /// + private uint FindInventoryItemByName(string name) + { + if (_objectCache == null) return 0; + uint partial = 0; + foreach (WorldObject wo in _objectCache.GetInventory()) + { + if (wo.Name.Length == 0) continue; + if (wo.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) return unchecked((uint)wo.Id); + if (partial == 0 && wo.Name.Contains(name, StringComparison.OrdinalIgnoreCase)) partial = unchecked((uint)wo.Id); + } + return partial; + } + + private string ObjectNameOr(uint id) => + Host.TryGetObjectName(id, out string n) && n.Length > 0 ? n : $"0x{id:X8}"; + + private void PrintItemInfo(uint id, bool identified) + { + var source = new HostItemInfoSource(Host, id); + ChatLine("[RynthAi] " + ItemInfoText.Describe(source, SpellDatabase.GetSpellName, identified)); + } + + /// The live appraisal through the host (tick thread). + private sealed class HostItemInfoSource : IItemInfoSource + { + private readonly RynthCoreHost _host; + private readonly uint _id; + + public HostItemInfoSource(RynthCoreHost host, uint id) + { + _host = host; + _id = id; + Name = host.TryGetObjectName(id, out string n) ? n : string.Empty; + SpellIds = ReadSpells(host, id); + } + + public string Name { get; } + public IReadOnlyList SpellIds { get; } + + public bool TryInt(uint key, out int value) + { + value = 0; + return _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(_id, key, out value); + } + + public bool TryFloat(uint key, out double value) + { + value = 0; + return _host.TryGetObjectDoubleProperty(_id, key, out value); + } + + private static IReadOnlyList ReadSpells(RynthCoreHost host, uint id) + { + if (!host.HasGetObjectSpellIds) return Array.Empty(); + var buf = new uint[64]; + int n = host.GetObjectSpellIds(id, buf, buf.Length); + if (n <= 0) return Array.Empty(); + var list = new List(n); + for (int i = 0; i < n && i < buf.Length; i++) list.Add(unchecked((int)buf[i])); + return list; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs new file mode 100644 index 0000000..daf3f27 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs @@ -0,0 +1,66 @@ +using System; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +// ============================================================================ +// RynthAi's side of the action pacing (Plugins/Shared/ActionPacer.cs, 2026-10-06). +// Every use / use-on RynthAi sends is recorded as the server action it waits on; +// casts and mode changes record themselves (CastSpellFor / ChangeCombatModeFor). +// The managers that only see a busy count (inventory, salvage, mana stones, pets) +// get PacedBusy: the count, plus one while a server action is unanswered. +// ============================================================================ +public sealed partial class RynthAiPlugin +{ + /// UseAudit.AfterSend: a use or use-on went out - record it as the action the server is answering. + private static void RecordUseForPacing(RynthCoreHost host, UseAudit.SentUse use) + { + try + { + // The salvage panel (a UST use) opens on the client; the server answered only 7 of 18 + // of them with a UseDone in the 10-05/10-06 logs, so it is not waited on. + if (use.Subsystem == "Salvage" || use.What.Contains("'Ust'", StringComparison.OrdinalIgnoreCase)) + return; + PacedKind kind; + uint player = host.HasGetPlayerId ? host.GetPlayerId() : 0; + if (use.TargetId != 0) + { + // Something on a target: on yourself (kit, stone, food) it is an item use; on a + // door/corpse or anything else in the world the server walks there first. + kind = use.TargetId == player + ? PacedKind.ItemUse + : ActionPacer.ClassifyUse(host, use.TargetId, use.DoorOrCorpse); + } + else + { + kind = ActionPacer.ClassifyUse(host, use.ObjectId, use.DoorOrCorpse); + } + string who = "RynthAi/" + use.Subsystem + (use.Kind == UseKind.Asked ? " (asked)" : ""); + ActionPacer.Begin(host, kind, use.ObjectId, use.What, who, use.UseDoneSeqBefore); + } + catch { } + } + + /// + /// The busy count the item managers gate on (inventory, salvage, mana stones, pets): our mirror of + /// AC's count, plus one while a server action is unanswered so they don't start one on top of it. + /// + private int PacedBusy + { + get + { + int busy = _busyCount; + if (ActionPacer.Enabled && ActionPacer.Current(Host) != null) busy++; + return busy; + } + } + + /// /ra pace: what the pacing is waiting on, and its counters. + private void HandlePaceCommand() + { + foreach (string line in ActionPacer.DescribeLines(Host)) + ChatLine("[RynthAi] " + line); + ChatLine($"[RynthAi] Busy mirror {_busyCount} (shadow resets only; the client's count is never force-cleared by RynthAi now)"); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 6a37fb7..c107dfd 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -165,11 +165,21 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // and never reads Host.ImGuiContext.) ComponentDatabase.SetLog(msg => Log(msg)); _dashboard = new LegacyDashboardRenderer(Host); + _killClock.MacroRunning = () => _dashboard?.Settings.IsMacroRunning == true; + _dashboard.KillClock = _killClock; // Every use goes through Host.UseFor (Plugins/Shared/UseAudit.cs): one log line // each, and no automatic door/corpse use while the macro is off. RynthCore.Plugin.Shared.UseAudit.Reset("RynthAi", () => _dashboard?.Settings.IsMacroRunning == true); // Every movement call is logged with its subsystem (Plugins/Shared/MoveAudit.cs). RynthCore.Plugin.Shared.MoveAudit.Reset(); + // A door/corpse use the server is still answering holds RynthAi's own moves and turns + // (moving would cancel the server's walk/turn to it; 2026-10-06). + RynthCore.Plugin.Shared.UseAudit.TrackWorldUses = true; + // One server action at a time (Plugins/Shared/ActionPacer.cs, 2026-10-06): every use, + // use-on, cast and combat-mode change waits for the server's answer to the last one. + RynthCore.Plugin.Shared.ActionPacer.Reset(); + RynthCore.Plugin.Shared.ActionPacer.Enabled = true; + RynthCore.Plugin.Shared.UseAudit.AfterSend = RecordUseForPacing; _objectCache = new WorldObjectCache(Host); // must exist before CreateObject events fire during login // Items we use (or use something on) get re-identified before a meta reads them. // ObjectUsed is a static event and Shutdown never unsubscribes: when the engine @@ -217,6 +227,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _dashboard = null; // Don't let the static audit hold this instance once it's gone (a reused module). RynthCore.Plugin.Shared.UseAudit.MacroOn = static () => false; + RynthCore.Plugin.Shared.UseAudit.AfterSend = null; + RynthCore.Plugin.Shared.ActionPacer.Enabled = false; + RynthCore.Plugin.Shared.ActionPacer.Forget("shutdown"); // Give the heap back. When a changed RynthAi is deployed, the engine loads // it as a new copy and this one is abandoned for good (a NativeAOT DLL can't @@ -345,6 +358,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase private void TeardownSession() { ObjectChangeTracker.Clear(); + // The server drops whatever it was doing for this character at logout. + RynthCore.Plugin.Shared.ActionPacer.Forget("logout"); _navigationEngine?.Stop(); _navigationEngine = null; // The dungeon cell graph is a static single-landblock cache; nothing may outlive the session. @@ -365,6 +380,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase } _combatManager?.Dispose(); _combatManager = null; + // A relog is what clears a server that refuses every use: start the next session clean. + ResetUseRefusalState(); Log($"RynthAi: TeardownSession — RadarWallFlush={tFlushMs} ms, RaycastDispose={tRayMs} ms"); _fellowshipTracker?.Dispose(); _fellowshipTracker = null; @@ -452,6 +469,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _loginCompletedAt = DateTime.Now; _loginComplete = true; + _killClock.SessionStarted(); _dashboard.OnLoginComplete(); _dashboard.ChatSubmitHandler = HandleRynthChatSubmit; _navigationEngine = new NavigationEngine(Host, _dashboard.Settings) @@ -607,6 +625,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _combatManager = new CombatManager(Host, _dashboard.Settings, _objectCache!, _spellManager); _combatManager.SetWeaponSwapGate(_weaponSwapGate); + _combatManager.HoldIdlePeace = LootHoldsIdlePeace; _combatManager.SetStaleBusyCallback(OnCombatBusyStale); _buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count if (_buffManager != null) @@ -646,6 +665,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _metaManager.SetQuestTracker(_questTracker); if (_buffManager != null) _metaManager.SetBuffManager(_buffManager); _metaManager.SetCreatureStore(_creatureStore); + _metaManager.SetKillClock(_killClock); if (_dashboard != null) _dashboard.MetaSnapshotProvider = () => _metaManager?.GetStateSnapshot(); @@ -698,6 +718,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // decides whether nav runs at all. One edge-detect replaces the cascade. private BotActivity _activity = BotActivity.Idle; // last arbiter decision private bool _macroWasRunning; // edge: release held turns when the macro stops + + // Time since our last kill (KillerNotification only): secondssincelastkill[], the + // No Kills Within Minutes meta condition and the status feed. Counts from login / plugin + // load, then from each macro start, until the first kill. + private readonly KillClock _killClock = new(); + internal KillClock Kills => _killClock; private BotActivity _navStoppedFor = BotActivity.Idle; // activity we last issued a nav Stop() for private bool _navStopIssued; // Buffing-coma watchdog (see the Priority-1 block): how long BotAction has @@ -733,8 +759,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _navStopIssued = true; _navStoppedFor = owner; + bool ownMovement = RynthCore.Plugin.Shared.MoveAudit.OwnMovementActive; // before nav's own stops clear it _navigationEngine?.Stop(); - if (Host.HasStopCompletely) + // A StopCompletely only when RynthAi itself has the character moving (2026-10-06): with + // nothing of ours moving it is one more movement packet on the server's motion - 116 in 46 + // minutes on 10-06, on every change of activity - and it cut off movement another plugin + // (RynthNav, RynthLua) had just started (analysis by Silentkelpie). RynthNav's travel is + // stopped by its own command (TickOwnCorpseTravel). Without the pacing, as before. + if (Host.HasStopCompletely + && (!RynthCore.Plugin.Shared.ActionPacer.Enabled || ownMovement)) Host.StopCompletelyBy("Arbiter"); // Combat taking the tick invalidates any in-progress door interaction. @@ -846,7 +879,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase ["MonsterRange"] = (1, 200), ["MonsterDisengageRange"] = (0, 200), ["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), ["OpenDoorRange"] = (0.1, 70), ["MovementMode"] = (0, 0), + ["NavHeightOffset"] = (-5, 5), ["NavSlopeSink"] = (0, 8), ["NavLabelMode"] = (0, 2), ["OpenDoorRange"] = (0.1, 70), ["MovementMode"] = (0, 0), ["NavStopTurnAngle"] = (1, 90), ["NavResumeTurnAngle"] = (1, 45), ["NavDeadZone"] = (0.5, 20), ["NavSweepMult"] = (0.5, 10), ["NavLookaheadYards"] = (0, 30), ["NavShortcutYards"] = (0, 10), ["NavTurnRateDegPerSec"] = (30, 720), ["NavTier1TurnSpeed"] = (0.5, 15), ["PostPortalDelaySec"] = (0, 30), ["NavOffTrackYards"] = (160, 1000), ["NavMaxDetourAttempts"] = (1, 10), @@ -1358,10 +1391,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // to run only inside the legacy dashboard's Render(), which the engine no // longer calls, so edits waited for the next login. A flag check when idle. _dashboard?.TickMonsterReload(); + // A nav saved into NavProfiles from outside (RynthNav's "save as nav route"): list it. + _dashboard?.TickNavFolder(); _questTracker?.Tick(); if (diag) Host.Log("[RynthAi] OnTick: after quest tracker"); DrainGiveQueue(); if (diag) Host.Log("[RynthAi] OnTick: after drain give queue"); + if (_loginComplete) TickItemInfo(); _jumper?.Tick(); if (diag) Host.Log("[RynthAi] OnTick: after jumper tick"); @@ -1487,6 +1523,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (!_macroWasRunning && settings.IsMacroRunning) _navigationEngine?.ResumeFromNearestWaypoint(); _macroWasRunning = settings.IsMacroRunning; + _killClock.ObserveMacro(settings.IsMacroRunning); // a start counts even if nothing reads the clock meanwhile if (_patrolOnLoginPending && _raycast?.GeometryLoader?.CellDat?.IsLoaded == true) { @@ -1589,6 +1626,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _combatEndedAt = nowMs; bool wantLoot = HasLootWork(settings, nowMs); + _lastWantLoot = wantLoot; bool wantSalvage = _salvageManager != null && _salvageManager.IsBusy; bool routeLoaded = settings.CurrentRoute != null && settings.CurrentRoute.Points.Count > 0; @@ -1735,7 +1773,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase && _openedContainerId == 0 && _targetCorpseId == 0) { - _inventoryManager.OnHeartbeat(_busyCount); + _inventoryManager.OnHeartbeat(PacedBusy); } // Status feed: main-pack empty slots (cache-based, off-thread-safe). Throttled to @@ -1808,7 +1846,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // combine work while a threat is up so it doesn't contend with // combat over SelectItem; it resumes the moment the threat clears. if (inventorySettled && !combatThreat) - _salvageManager?.OnTick(_busyCount); + _salvageManager?.OnTick(PacedBusy); if (diag) Host.Log("[RynthAi] OnTick: before manaStoneManager"); // STEP 4: the salvage gap-fill that used to pin/release @@ -1821,8 +1859,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // decision from scratch every tick. // Mana stone tapping — runs after salvage, independent of looting state. - _manaStoneManager?.OnHeartbeat(_busyCount); - _petManager?.OnHeartbeat(_busyCount); + _manaStoneManager?.OnHeartbeat(PacedBusy); + _petManager?.OnHeartbeat(PacedBusy); if (diag) Host.Log("[RynthAi] OnTick: before combatManager"); // Missile crafting runs before combat — blocks everything while active. @@ -1960,13 +1998,14 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (Host.HasQueryHealth) Host.QueryHealth(currentTargetId); } - if (_lootInspectMode && currentTargetId != 0) + if (currentTargetId != 0) { int sid = unchecked((int)currentTargetId); WorldObject? obj = _objectCache?[sid]; // Skip non-items (monsters, players, NPCs, doors, corpses, portals, etc.) - if (obj != null && IsLootableClass(obj.ObjectClass)) + if (_lootInspectMode && obj != null && IsLootableClass(obj.ObjectClass)) InspectLootRuleForItem(sid, quiet: true); + QueueItemInfoOnSelect(currentTargetId, obj); } } @@ -2011,6 +2050,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase public override void OnKillNotification(string? deathMessage) { if (string.IsNullOrEmpty(deathMessage)) return; + _killClock.RecordKill(); // the only kill source: KillerNotification goes to the killer alone _combatManager?.OnKillNotification(deathMessage); _dashboard?.RecordKill(); // feeds the kills/hour session stat } @@ -3026,6 +3066,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "listpvars": HandleListPvarsCommand(); break; case "listgvars": HandleListGvarsCommand(); break; case "dumpprops": HandleDumpPropsCommand(parts); break; + case "iteminfo": HandleItemInfoCommand(parts); break; case "version": HandleVersionCommand(); break; case "wielded": HandleWieldedCommand(); break; case "scan": HandleScanCommand(); break; @@ -3052,6 +3093,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "lootcheck": HandleLootCheckSelectedCommand(parts); break; case "loot": HandleLootCommand(parts); break; case "corpseinfo": HandleCorpseInfoCommand(); break; + case "pace": HandlePaceCommand(); break; case "corpsecheck": HandleCorpseCheckCommand(parts); break; case "corpseopen": HandleCorpseOpenCommand(); break; case "owncorpse": diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj index e45f8d7..e3740c0 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj @@ -39,6 +39,10 @@ + + + + @@ -93,4 +97,9 @@ + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthAi/Trade/AutoTradeManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Trade/AutoTradeManager.cs index df5c622..ebc0f43 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Trade/AutoTradeManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Trade/AutoTradeManager.cs @@ -45,7 +45,7 @@ namespace RynthCore.Plugin.RynthAi.Trade; /// internal sealed class AutoTradeManager { - public const string MainProfileDir = @"C:\Games\RynthSuite\RynthAi\AutoTrade"; + public static readonly string MainProfileDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "AutoTrade"); public const string ProfileSubfolder = "AutoTrade"; public const string AutoAcceptListFileName = "autoAcceptList.json"; public const uint RequiredApiVersion = 72; diff --git a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltExtraCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltExtraCommands.cs index 430c3e5..32cc716 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltExtraCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltExtraCommands.cs @@ -170,7 +170,7 @@ public sealed partial class RynthAiPlugin { string n = name.Trim().Trim('"'); if (File.Exists(n)) return n; - const string folder = @"C:\Games\RynthSuite\RynthAi\LootProfiles"; + string folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles"); foreach (string cand in new[] { n, n + ".utl", n + ".json" }) { string p = Path.Combine(folder, cand); @@ -236,7 +236,7 @@ public sealed partial class RynthAiPlugin int sp = args.IndexOf(' '); if (sp > 0 && int.TryParse(args.AsSpan(0, sp), out _)) file = args.Substring(sp + 1).Trim(); file = file.Trim('"'); - if (!Path.IsPathRooted(file)) file = Path.Combine(@"C:\Games\RynthSuite\RynthAi", file); + if (!Path.IsPathRooted(file)) file = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, file); if (!File.Exists(file)) { ChatLine($"[RynthAi] Sound file not found: {file}"); return; } try { PlaySound(file, IntPtr.Zero, 0x00020000 /*SND_FILENAME*/ | 0x0001 /*SND_ASYNC*/); } catch (Exception ex) { ChatLine($"[RynthAi] playsound failed: {ex.Message}"); } @@ -352,7 +352,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] Usage: /ub translateroute [force]"); return; } - const string navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles"; + string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles"); string inPath = Path.IsPathRooted(w[1]) ? w[1] : Path.Combine(navFolder, w[1]); string outPath = Path.IsPathRooted(w[3]) ? w[3] : Path.Combine(navFolder, w[3]); if (!outPath.EndsWith(".nav", StringComparison.OrdinalIgnoreCase)) outPath += ".nav"; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs index 6404863..3862d9e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs @@ -34,7 +34,7 @@ namespace RynthCore.Plugin.RynthAi.Vendor; /// internal sealed class AutoVendorManager { - public const string MainProfileDir = @"C:\Games\RynthSuite\RynthAi\AutoVendor"; + public static readonly string MainProfileDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "AutoVendor"); public const string ProfileSubfolder = "AutoVendor"; private const long BailMs = 60_000; // UB bailTimer diff --git a/Plugins/RynthCore.Plugin.RynthLua/RynthCore.Plugin.RynthLua.csproj b/Plugins/RynthCore.Plugin.RynthLua/RynthCore.Plugin.RynthLua.csproj index 673c466..3d3962d 100644 --- a/Plugins/RynthCore.Plugin.RynthLua/RynthCore.Plugin.RynthLua.csproj +++ b/Plugins/RynthCore.Plugin.RynthLua/RynthCore.Plugin.RynthLua.csproj @@ -44,4 +44,9 @@ + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthLua/RynthLuaPaths.cs b/Plugins/RynthCore.Plugin.RynthLua/RynthLuaPaths.cs index d24d1fb..5fb8302 100644 --- a/Plugins/RynthCore.Plugin.RynthLua/RynthLuaPaths.cs +++ b/Plugins/RynthCore.Plugin.RynthLua/RynthLuaPaths.cs @@ -10,11 +10,11 @@ namespace RynthCore.Plugin.RynthLua; /// internal static class RynthLuaPaths { - /// RynthLua's folder: Scripts\, Data\, settings.json, editor.lua. - public static string Root { get; set; } = @"C:\Games\RynthSuite\RynthLua"; + /// RynthLua's folder: Scripts\, Data\, settings.json, editor.lua (<SuiteDir>\RynthLua, C:\Games\RynthSuite\RynthLua by default). + public static string Root { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.SuiteDir, "RynthLua"); /// Where scripts lived while Lua was part of RynthAi (copied over once, then left alone). - public static string LegacyScripts { get; set; } = @"C:\Games\RynthSuite\RynthAi\LuaScripts"; + public static string LegacyScripts { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LuaScripts"); public static string Scripts => Path.Combine(Root, "Scripts"); public static string Data => Path.Combine(Root, "Data"); diff --git a/Plugins/RynthCore.Plugin.RynthNav/NavRouteExport.cs b/Plugins/RynthCore.Plugin.RynthNav/NavRouteExport.cs new file mode 100644 index 0000000..39a6737 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/NavRouteExport.cs @@ -0,0 +1,203 @@ +using System; +using System.Collections.Generic; +using System.IO; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthNav.Routing; + +namespace RynthCore.Plugin.RynthNav; + +/// +/// "Save as nav route": a planned trip as a RynthAi nav route (uTank2 NAV 1.2, the VTank format +/// RynthAi reads and writes; RynthAi's own NavRouteParser, linked in, does the writing), so RynthAi +/// can load it from NavProfiles and run it. Route type Once. +/// +/// a walk step its path's waypoints (Point), thinned (TripPathBuilder.Thin): not every +/// navmesh corner, a point at least every 60 yd on straight ground +/// a portal step the walk up to PortalStopShort yd before the entrance, then a Portal step +/// (VTank "Portal", type 6) naming the portal object, at the entrance: RynthAi +/// uses it by name (the nearest one) and walks the last yards itself +/// a recall spell a Recall step (type 2) with the spell id, cast where the trip stands +/// a command recall (@lifestone, @house recall...): a Chat step with the command, then a Pause +/// of CommandRecallPauseMs (RynthAi doesn't wait for a chat command's teleport) +/// the Town Network the walk inside (townnet.json) as waypoints, then a Portal step for the exit +/// a dungeon goto ends with the Portal step into the dungeon's entrance portal +/// A step it can't write (a recall the plan doesn't know, a Town Network walk townnet.json doesn't +/// have) stops the route there: what comes before is kept, and the reason is given. +/// Host-free: the route tests convert made-up trips and read the file back with RynthAi's reader. +/// +internal static class NavRouteExport +{ + /// The walk to a portal stops this far short of its entrance (the Portal step walks the rest). + public const double PortalStopShort = 5.0; + /// Inside the Town Network the stored walk ends at the exit portal: stop this far short. + public const double HubStopShort = 2.0; + /// After a command recall's chat step: wait this long for its teleport (ms). + public const int CommandRecallPauseMs = 20000; + /// VTank's object class for a portal (the Portal step's second trailer line). + public const int PortalObjectClass = 14; + + public sealed class Result + { + public NavRouteParser Route = new() { RouteType = NavRouteType.Once }; + /// The step (0-based) the route stops at, short of the trip's end; -1 = the whole trip. + public int StoppedAt = -1; + public string StopReason = ""; + public int Waypoints, Portals, Recalls, Chats; + } + + /// The trip as nav points (see the class notes). must be this trip's. + public static Result Convert(PlannedTrip trip, TripPath path, TownNet? net) + { + var r = new Result(); + if (path.TripId != trip.Id) { r.StoppedAt = 0; r.StopReason = "the path was worked out for another trip"; return r; } + WorldPt here = trip.Start; // where action steps happen when nothing better is known + double lastH = double.IsNaN(trip.Start.H) ? 0 : trip.Start.H; + + void Stop(int i, string why) { r.StoppedAt = i; r.StopReason = $"step {i + 1}: {why}"; } + void AddPoint(WorldPt p) + { + if (!double.IsNaN(p.H)) lastH = p.H; + r.Route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = p.Ns, EW = p.Ew, Z = lastH / 240.0 }); + r.Waypoints++; + here = p; + } + void AddPortal(string name, WorldPt at) + { + if (!double.IsNaN(at.H)) lastH = at.H; + double ns = at.Ns, ew = at.Ew, z = lastH / 240.0; + r.Route.Points.Add(new NavPoint + { + Type = NavPointType.PortalNPC, NS = ns, EW = ew, Z = z, + TargetName = name, ObjectClass = PortalObjectClass, IsTie = true, + PortalExitNS = ns, PortalExitEW = ew, PortalExitZ = z, + }); + r.Portals++; + } + void Land(RouteStep s) + { + if (!double.IsNaN(s.LandNs)) here = WorldPt.FromMap(s.LandNs, s.LandEw, double.NaN); + } + + for (int i = 0; i < trip.Count; i++) + { + RouteStep s = trip.Steps[i]; + if (s.UseRecall) + { + TripRecall? rec = trip.RecallOf(i); + if (rec is not TripRecall o) { Stop(i, $"the recall {s.Label} isn't one the plan knows how to cast"); return r; } + WorldPt at = trip.Point[i] ?? here; + double z = (double.IsNaN(at.H) ? lastH : at.H) / 240.0; + if (o.SpellId != 0) + { + r.Route.Points.Add(new NavPoint { Type = NavPointType.Recall, NS = at.Ns, EW = at.Ew, Z = z, SpellId = o.SpellId }); + r.Recalls++; + } + else if (o.Command.Length > 0) + { + r.Route.Points.Add(new NavPoint { Type = NavPointType.Chat, NS = at.Ns, EW = at.Ew, Z = z, ChatCommand = o.Command }); + r.Route.Points.Add(new NavPoint { Type = NavPointType.Pause, NS = at.Ns, EW = at.Ew, Z = z, PauseTimeMs = CommandRecallPauseMs }); + r.Chats++; + } + else { Stop(i, $"{o.Name} has neither a spell nor a command"); return r; } + Land(s); + continue; + } + if (s.IsHub) + { + WorldPt[]? inside = path.Hub[i]; + WorldPt? exit = PlannedTrip.HubExitPoint(net, s); + if (inside == null || exit == null || net == null) + { + trip.HubWalk(i, net, out string why); + Stop(i, $"the walk inside the Town Network isn't known ({(why.Length > 0 ? why : "no townnet.json")})"); + return r; + } + List walk = TripPathBuilder.StopShort(inside, HubStopShort); + for (int k = 1; k < walk.Count; k++) AddPoint(walk[k]); + AddPortal(net.Exits[s.HubExit].Name, exit.Value); + Land(s); + continue; + } + WorldPt[]? pts = path.Walks[i]; + if (pts == null || pts.Length == 0) + { + if (trip.WalkFrom[i] == null) { Stop(i, "it starts where the plan has no map position (inside a dungeon)"); return r; } + Stop(i, "its walk wasn't worked out"); + return r; + } + if (s.UsePortal) + { + List walk = TripPathBuilder.StopShort(pts, PortalStopShort); + for (int k = 1; k < walk.Count; k++) AddPoint(walk[k]); + WorldPt at = trip.Point[i] is WorldPt p ? p with { H = pts[^1].H } : pts[^1]; + string name = trip.PortalName(i); + if (name.Length == 0) { Stop(i, "the portal has no name to look for"); return r; } + AddPortal(name, at); + Land(s); + continue; + } + for (int k = 1; k < pts.Length; k++) AddPoint(pts[k]); + } + return r; + } + + // ── The file ───────────────────────────────────────────────────────── + + /// + /// A nav file name from what was typed: trimmed, without ".nav". "" with + /// when it can't be one (empty, characters a file name can't have, a path). + /// + public static string FileName(string typed, out string error) + { + error = ""; + string n = (typed ?? "").Trim(); + if (n.EndsWith(".nav", StringComparison.OrdinalIgnoreCase)) n = n[..^4].TrimEnd(); + if (n.Length == 0) { error = "give the route a name"; return ""; } + if (n.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || n.Contains("..") || n.Length > 100) + { error = $"'{typed}' can't be used as a file name"; return ""; } + return n; + } + + /// A file name made from a place's name (characters a file can't have become spaces). + public static string SafeName(string text) + { + var chars = (text ?? "").ToCharArray(); + char[] bad = Path.GetInvalidFileNameChars(); + for (int i = 0; i < chars.Length; i++) if (Array.IndexOf(bad, chars[i]) >= 0) chars[i] = ' '; + string s = string.Join(" ", new string(chars).Split(' ', StringSplitOptions.RemoveEmptyEntries)); + return s.Length > 60 ? s[..60].TrimEnd() : s; + } + + /// + /// Writes to <folder>\<name>.nav. An existing file is only replaced + /// with ; otherwise nothing is written and false comes back with + /// set. Written to a temporary file first, then moved into place. + /// + public static bool Save(string folder, string name, NavRouteParser route, bool overwrite, out string path, out bool exists, out string error) + { + error = ""; + path = Path.Combine(folder, name + ".nav"); + exists = File.Exists(path); + if (exists && !overwrite) return false; + string tmp = path + ".tmp"; + try + { + Directory.CreateDirectory(folder); + File.WriteAllLines(tmp, route.ToLines()); + File.Move(tmp, path, overwrite); + return true; + } + catch (IOException) when (!overwrite && File.Exists(path)) + { + exists = true; // made by someone else in the meantime + try { File.Delete(tmp); } catch { } + return false; + } + catch (Exception ex) + { + error = ex.Message; + try { File.Delete(tmp); } catch { } + return false; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/PathMarkers.cs b/Plugins/RynthCore.Plugin.RynthNav/PathMarkers.cs new file mode 100644 index 0000000..9352950 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/PathMarkers.cs @@ -0,0 +1,295 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.Shared; +using RynthNav.Routing; + +namespace RynthCore.Plugin.RynthNav; + +internal enum MarkKind : byte { Waypoint, Portal, Recall, Town, Goal } + +/// One marker on the ground: a waypoint of a walk, or where a step happens. +internal readonly record struct Mark(WorldPt P, MarkKind Kind, string Label, int Step, bool LineToNext); + +/// +/// A trip's markers, built on the tick from the trip and its path and then never changed: the +/// Nav3D emit reads only this (never the plan, the route or the walker's state). +/// +internal sealed class MarkerSnapshot +{ + public static readonly MarkerSnapshot Empty = new(0, false, Array.Empty()); + + public readonly int TripId; + /// Built with the trip's path (waypoints and lines), not just the steps' points. + public readonly bool HasPath; + public readonly Mark[] Marks; + + public MarkerSnapshot(int tripId, bool hasPath, Mark[] marks) { TripId = tripId; HasPath = hasPath; Marks = marks; } + + /// The first marker of step , or -1. + public int FirstOfStep(int step) + { + for (int i = 0; i < Marks.Length; i++) if (Marks[i].Step == step) return i; + return -1; + } + + /// The last marker of step , or -1. + public int LastOfStep(int step) + { + for (int i = Marks.Length - 1; i >= 0; i--) if (Marks[i].Step == step) return i; + return -1; + } +} + +/// Where the markers go: the engine's Nav3D buffer in the game, a recorder in the tests. +internal interface IMarkerSink : INav3DSink +{ + void Ring(float x, float y, float z, float radius, float thickness, uint colorArgb); +} + +/// What the emit needs to know about this tick (all plain values, taken on the tick). +internal readonly record struct MarkerView( + double Px, double Py, double Pz, // the character: world east, north, height + int Next, // the marker the walk is heading for (-1: none, a plan only) + bool Labels, bool Guide); + +/// +/// RynthNav's path markers: the planned trip drawn on the ground the way RynthAi draws its nav +/// routes (rings at the waypoints, lines between them, on the engine's Nav3D buffer), with the +/// place each step happens (a portal, a recall, the Town Network, the goal) in its own colour and, +/// optionally, a label (Plugins/Shared/Nav3DText) and a guide line from your feet to the next +/// waypoint. Host-free: the route tests build and emit these into a recorder. +/// +internal static class PathMarkers +{ + public const double WaypointRange = 160.0; // waypoints this close (yards) are drawn + public const double StepRange = 400.0; // a step's own marker, this close + public const double LabelRange = 90.0; + public const double MaxGuideUnits = 500.0; + public const double NextReach = 4.0; // the next waypoint counts as reached this close + public const int MaxWaypointRings = 40; + public const int MaxStepRings = 8; + public const int MaxLines = 90; + public const int MaxLabelTriangles = 900; // the engine keeps 8192 a tick for every plugin + public const int MaxLabelChars = 22; + + public const uint WaypointColor = 0xFF40D973, LineColor = 0xFF2FB863, NextColor = 0xFFFF4444, + PortalColor = 0xFFBF4DFF, RecallColor = 0xFFFFC040, TownColor = 0xFF2EC4C4, GoalColor = 0xFFFFD24D, + GuideColor = 0xFFFFD21E; + + private const float WaypointRadius = 0.9f, StepRadius = 1.8f, RingThick = 0.12f, LineThick = 0.08f, Lift = 0.1f; + + // ── Build (tick) ───────────────────────────────────────────────────── + + /// + /// The markers for : with its (same trip), every + /// walk's waypoints joined by lines and each step's own marker; without it (still being worked + /// out, or none to be had), only the steps' markers. + /// + public static MarkerSnapshot Build(PlannedTrip trip, TripPath? path, TownNet? net) + { + if (path != null && path.TripId != trip.Id) path = null; + var marks = new List(); + int n = trip.Count; + for (int i = 0; i < n; i++) + { + RouteStep s = trip.Steps[i]; + bool last = i == n - 1; + if (s.UseRecall) + { + if (trip.Point[i] is WorldPt at) + marks.Add(new Mark(at, MarkKind.Recall, Fit("RECALL " + (trip.RecallOf(i)?.Name ?? s.Label)), i, false)); + continue; + } + if (s.IsHub) + { + WorldPt? exit = PlannedTrip.HubExitPoint(net, s); + WorldPt[]? inside = path?.Hub[i]; + if (inside != null) + foreach (WorldPt p in inside) + { + if (exit is WorldPt e && p.FlatDistance(e) < 2.0) continue; + Add(marks, new Mark(p, MarkKind.Waypoint, "", i, true)); + } + WorldPt? at = exit ?? (inside is { Length: > 0 } ? inside[^1] : null); + string where = net != null && s.HubExit >= 0 && s.HubExit < net.Exits.Count ? net.Exits[s.HubExit].Where : s.Label; + if (at is WorldPt a) marks.Add(new Mark(a, MarkKind.Town, Fit("PORTAL TO " + where), i, false)); + continue; + } + if (trip.Point[i] is not WorldPt to) continue; + WorldPt[]? walk = path?.Walks[i]; + if (walk != null) + for (int k = 0; k < walk.Length - 1; k++) + Add(marks, new Mark(walk[k], MarkKind.Waypoint, "", i, true)); + if (walk is { Length: > 0 }) to = to with { H = walk[^1].H }; + Mark end; + if (s.UsePortal) + { + bool intoHub = i + 1 < n && trip.Steps[i + 1].IsHub; + string label = intoHub ? "TOWN NETWORK" + : last && trip.EndsInEntrance ? "ENTER " + trip.EnterName + : "PORTAL " + s.Label; + end = new Mark(to, intoHub ? MarkKind.Town : MarkKind.Portal, Fit(label), i, false); + } + else if (last) end = new Mark(to, MarkKind.Goal, Fit(trip.Goal.Length > 0 ? trip.Goal : "ARRIVE"), i, false); + else end = new Mark(to, MarkKind.Waypoint, "", i, walk != null); + Add(marks, end); + } + return new MarkerSnapshot(trip.Id, path != null, marks.ToArray()); + } + + // A leg starts where the last one ended: the same point once. A step's own marker takes the + // place of a waypoint under it (the line before it then runs into the step's marker). + private static void Add(List marks, Mark m) + { + if (marks.Count > 0 && marks[^1].P.FlatDistance(m.P) < 1.0) + { + Mark prev = marks[^1]; + if (m.Kind == MarkKind.Waypoint) + { + if (m.LineToNext && !prev.LineToNext && prev.Kind == MarkKind.Waypoint) marks[^1] = prev with { LineToNext = true }; + return; + } + if (prev.Kind == MarkKind.Waypoint) marks.RemoveAt(marks.Count - 1); + } + marks.Add(m); + } + + private static string Fit(string s) + { + s = s.Trim().ToUpperInvariant(); + return s.Length > MaxLabelChars ? s[..(MaxLabelChars - 2)] + ".." : s; + } + + // ── The next waypoint (tick) ───────────────────────────────────────── + + /// + /// The marker the walk on step heads for next, carried on from + /// (last tick's): it moves on when the character is within + /// of it, or is already nearer the stretch after it than the one before + /// it (a re-plan or a cut corner). Never moves back within a step. -1 when the step has no markers. + /// + public static int Advance(MarkerSnapshot s, int idx, int step, double px, double py) + { + Mark[] m = s.Marks; + int first = s.FirstOfStep(step), lastOfStep = s.LastOfStep(step); + if (first < 0) return -1; + if (idx < first || idx > lastOfStep) idx = first; + var me = new WorldPt(px, py, 0); + while (idx < lastOfStep) + { + if (m[idx].P.FlatDistance(me) < NextReach) { idx++; continue; } + WorldPt before = idx > first ? m[idx - 1].P : m[idx].P; + double toBefore = idx > first ? PlannedTrip.SegmentDistance(me, before, m[idx].P) : double.MaxValue; + double toAfter = PlannedTrip.SegmentDistance(me, m[idx].P, m[idx + 1].P, out double t); + if (toAfter + 1.0 < toBefore && t > 0.05) { idx++; continue; } + break; + } + return idx; + } + + /// The marker nearest the character (a plan only: where the guide line points), or -1. + public static int Nearest(MarkerSnapshot s, double px, double py) + { + int best = -1; + double bestD = MaxGuideUnits; + var me = new WorldPt(px, py, 0); + for (int i = 0; i < s.Marks.Length; i++) + { + double d = s.Marks[i].P.FlatDistance(me); + if (d < bestD) { bestD = d; best = i; } + } + return best; + } + + // ── Emit (tick, into the Nav3D buffer) ─────────────────────────────── + + /// + /// Submits the markers near the character: rings (waypoints within , + /// at most nearest; steps' markers within ), + /// lines between neighbouring waypoints, the guide line first (so a full line buffer never drops + /// it) and the labels last. Positions go in the Nav3D frame: the character's landblock, X = east + /// metres, Y = height, Z = north metres. Returns the number of rings drawn. + /// + public static int Emit(MarkerSnapshot s, in MarkerView v, IMarkerSink sink) + { + Mark[] m = s.Marks; + if (m.Length == 0) return 0; + double baseX = Math.Floor(v.Px / 192.0) * 192.0, baseY = Math.Floor(v.Py / 192.0) * 192.0; + float px = (float)(v.Px - baseX), py = (float)(v.Py - baseY), pz = (float)v.Pz; + var me = new WorldPt(v.Px, v.Py, v.Pz); + + // Which markers: steps' own within StepRange, waypoints within WaypointRange (the nearest). + var dist = new double[m.Length]; + var drawn = new bool[m.Length]; + var waypoints = new List(); + int steps = 0; + for (int i = 0; i < m.Length; i++) + { + dist[i] = m[i].P.FlatDistance(me); + if (m[i].Kind == MarkKind.Waypoint) { if (dist[i] <= WaypointRange) waypoints.Add(i); } + else if (dist[i] <= StepRange && steps < MaxStepRings) { drawn[i] = true; steps++; } + } + if (waypoints.Count > MaxWaypointRings) waypoints.Sort((a, b) => dist[a].CompareTo(dist[b])); + for (int k = 0; k < waypoints.Count && k < MaxWaypointRings; k++) drawn[waypoints[k]] = true; + if (v.Next >= 0 && v.Next < m.Length && dist[v.Next] <= StepRange) drawn[v.Next] = true; + + (float X, float Y, float Z) Local(WorldPt p) => + ((float)(p.X - baseX), (double.IsNaN(p.H) ? pz : (float)p.H) + Lift, (float)(p.Y - baseY)); + + // Guide line: to the next waypoint (a walk), else the nearest marker (a plan). + if (v.Guide) + { + int g = v.Next >= 0 && v.Next < m.Length ? v.Next : Nearest(s, v.Px, v.Py); + if (g >= 0 && dist[g] <= MaxGuideUnits) + { + var (gx, gy, gz) = Local(m[g].P); + sink.Line(px, pz + Lift + 0.05f, py, gx, gy, gz, LineThick, GuideColor); + } + } + + int rings = 0; + for (int i = 0; i < m.Length; i++) + { + if (!drawn[i]) continue; + var (x, y, z) = Local(m[i].P); + bool next = i == v.Next; + bool step = m[i].Kind != MarkKind.Waypoint; + uint color = next ? NextColor : ColorOf(m[i].Kind); + sink.Ring(x, y, z, step ? StepRadius : next ? WaypointRadius * 1.2f : WaypointRadius, step || next ? RingThick * 1.4f : RingThick, color); + rings++; + } + + int lines = 0; + for (int i = 0; i + 1 < m.Length && lines < MaxLines; i++) + { + if (!m[i].LineToNext) continue; + // A line when either end is drawn and the other isn't far off. + if (!(drawn[i] || drawn[i + 1]) || Math.Min(dist[i], dist[i + 1]) > WaypointRange) continue; + var (ax, ay, az) = Local(m[i].P); + var (bx, by, bz) = Local(m[i + 1].P); + sink.Line(ax, ay, az, bx, by, bz, LineThick, LineColor); + lines++; + } + + if (v.Labels) + { + int tris = 0; + for (int i = 0; i < m.Length; i++) + { + if (!drawn[i] || m[i].Label.Length == 0 || dist[i] > LabelRange) continue; + var (x, y, z) = Local(m[i].P); + if (!Nav3DText.Emit(x, y, z, m[i].Label, 0, ColorOf(m[i].Kind), px, py, sink, ref tris, MaxLabelTriangles)) break; + } + } + return rings; + } + + public static uint ColorOf(MarkKind k) => k switch + { + MarkKind.Portal => PortalColor, + MarkKind.Recall => RecallColor, + MarkKind.Town => TownColor, + MarkKind.Goal => GoalColor, + _ => WaypointColor, + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthCore.Plugin.RynthNav.csproj b/Plugins/RynthCore.Plugin.RynthNav/RynthCore.Plugin.RynthNav.csproj index e152420..ccedab5 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthCore.Plugin.RynthNav.csproj +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthCore.Plugin.RynthNav.csproj @@ -42,6 +42,13 @@ + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Avoid.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Avoid.cs index 5b8c661..206073a 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Avoid.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Avoid.cs @@ -48,18 +48,9 @@ public sealed partial class RynthNavPlugin _nextAvoidMs = now + AvoidRefreshMs; if (!_avoidPortals) { _avoid.Clear(); return; } - Atlas atlas = _atlas; - if (!ReferenceEquals(atlas, _avoidAtlas)) - { - var list = new List(); - foreach (AtlasLocation l in atlas.Locations) - if (l.OnMap && l.Type.Equals("Portal", StringComparison.Ordinal)) - list.Add(new PortalAvoid.Spot(NavCoords.WorldX(l.Ew), NavCoords.WorldY(l.Ns), PortalAvoid.MapRadius, l.Name)); - _atlasPortals = list; - _avoidAtlas = atlas; - } + IReadOnlyList atlasPortals = AtlasPortalSpots(); var map = new List(); - foreach (PortalAvoid.Spot sp in _atlasPortals) + foreach (PortalAvoid.Spot sp in atlasPortals) if (Math.Abs(sp.X - _wx) < AvoidNearUnits && Math.Abs(sp.Y - _wy) < AvoidNearUnits) map.Add(sp); var live = new List(); diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs new file mode 100644 index 0000000..e9bc430 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs @@ -0,0 +1,220 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using RynthNav.Routing; + +namespace RynthCore.Plugin.RynthNav; + +// The planned trip on the ground: RynthNav's path markers (PathMarkers), drawn on the engine's +// Nav3D buffer the way RynthAi draws its nav routes. When Route or Go plans a trip, a worker works +// out the whole walk ahead of time (TilePathFinder: the route graph and the tiles, in its own +// navmesh), and the markers show it: rings at the waypoints near you, lines between them, the +// portal / recall / Town Network / goal markers in their own colours, and (switches) labels on +// those and a guide line from your feet to the next waypoint. The same path is what "save as nav +// route" writes (RynthNavPlugin.SaveRoute.cs). +// +// The markers go away when the trip ends (arrived, stopped), is cancelled (Stop, the d-pad), or you +// land in a landblock that isn't on it (a teleport elsewhere). Switches in rynthnav.json +// (markers, markerLabels, markerGuide); /rnav markers and the panel's Go tab change them. +// +// Threads: everything here runs on the tick, except the path worker, which reads only the frozen +// trip (PlannedTrip), the immutable route graph and Atlas portal list, and the tile files. The +// emit reads only the frozen MarkerSnapshot, never the trip, the route or the walker. +public sealed partial class RynthNavPlugin +{ + private volatile bool _markersOn = true, _markerLabels = true, _markerGuide; + + // The last trip planned (Route or Go): kept for "save as nav route" after it ends. + private volatile PlannedTrip? _trip; + private int _tripSeq; + private volatile bool _tripShown; // its markers are on the ground (not ended / cancelled / left) + private TripPath? _tripPath; // its path, once worked out + private Task<(TripPath Path, long Ms, int Tiles)>? _pathTask; + private PlannedTrip? _pathTaskTrip; + private string _nextEnterPortal = "", _enterPortal = ""; + + // Markers (tick thread). + private MarkerSnapshot _markerSnap = MarkerSnapshot.Empty; + private PlannedTrip? _snapTrip; + private TripPath? _snapPath; + private int _markNext = -1, _markStep = -2, _markTrip; + private uint _markLb; + private HostMarkerSink? _markerSink; + private volatile string _markerStatus = ""; + + private void LoadMarkerSettings() + { + _markersOn = NavDataConfig.ReadSwitch("markers", true); + _markerLabels = NavDataConfig.ReadSwitch("markerLabels", true); + _markerGuide = NavDataConfig.ReadSwitch("markerGuide", false); + } + + // ── The trip ───────────────────────────────────────────────────────── + + /// A new plan (Route) or goto (Go): its trip, shown, its path worked out. Tick thread. + private void SetTrip(List? steps, string goal, double goalNs, double goalEw, List? recalls, + string enterName, bool live) + { + var tr = new List(); + if (recalls != null) foreach (RecallOption o in recalls) tr.Add(new TripRecall(o.Name, o.SpellId, o.Command, o.CastSeconds)); + _trip = new PlannedTrip(++_tripSeq, steps ?? new List(), goal, goalNs, goalEw, + IsOnMap(_cellId), new WorldPt(_wx, _wy, _wz), _cellId, tr, + enterName.Length > 0 ? _enterPortal : "", enterName, live); + _tripPath = null; + _tripShown = true; + _markNext = -1; _markStep = -2; + _markLb = CurrentLandblock; + _saveConflict = ""; + _saveDefault = NavRouteExport.SafeName("To " + goal); + if (_markersOn) StartPathBuild(); + _markerStatus = "working out the path…"; + } + + /// Takes the markers off the ground (the trip stays for "save as nav route"). Tick thread. + private void HideMarkers(string why) + { + if (!_tripShown) return; + _tripShown = false; + _markNext = -1; + _markerStatus = why; + Host.Log($"[RynthNav] path markers: off ({why})"); + } + + private void StartPathBuild() + { + PlannedTrip? trip = _trip; + if (trip == null || (_tripPath != null && _tripPath.TripId == trip.Id)) return; + if (_pathTask != null && ReferenceEquals(_pathTaskTrip, trip)) return; + NavGraph? g = UsableGraph(); + IReadOnlyList portals = AtlasPortalSpots(); + TownNet? net = _townNet; + string dir = NavDataDir; + _pathTaskTrip = trip; + _pathTask = Task.Run(() => + { + long t0 = Environment.TickCount64; + var finder = new TilePathFinder(dir, g, portals); + TripPath p = TripPathBuilder.Build(trip, + (WorldPt a, WorldPt b, bool intoPortal, out string note) => finder.Walk(a, b, intoPortal, out note), net); + return (p, Environment.TickCount64 - t0, finder.TilesRead); + }); + } + + private void TakePathResult() + { + if (_pathTask is not { IsCompleted: true } task) return; + PlannedTrip? forTrip = _pathTaskTrip; + _pathTask = null; _pathTaskTrip = null; + if (task.IsFaulted) + { + Host.Log($"[RynthNav] trip path failed: {task.Exception?.GetBaseException().Message}"); + _markerStatus = "the path couldn't be worked out (see the log)"; + OnPathReady(forTrip, null); + return; + } + var (path, ms, tiles) = task.Result; + if (_trip == null || path.TripId != _trip.Id) { if (_markersOn || _pendingSave != null) StartPathBuild(); return; } // planned for an older trip + _tripPath = path; + int points = 0; + foreach (WorldPt[]? w in path.Walks) points += w?.Length ?? 0; + foreach (WorldPt[]? w in path.Hub) points += w?.Length ?? 0; + Host.Log($"[RynthNav] trip path to {_trip.Goal}: {points} waypoints over {_trip.Count} step(s), {tiles} tile(s) read, {ms} ms"); + foreach (string n in path.Notes) Host.Log($"[RynthNav] trip path: {n}"); + _markerStatus = path.Notes.Count == 0 ? $"{points} waypoints" : $"{points} waypoints; {path.Notes[0]}"; + OnPathReady(_trip, path); + } + + // ── Tick ───────────────────────────────────────────────────────────── + + private void TickMarkers() + { + TakePathResult(); + PlannedTrip? trip = _trip; + if (trip == null) return; + + // A landblock that isn't on the trip (a teleport somewhere else): the markers go. + if (_hasPose && _tripShown) + { + uint lb = CurrentLandblock; + if (lb != _markLb && lb != 0) + { + _markLb = lb; + TownNet? net = _townNet; + if (!trip.Covers(lb, _tripPath, net == null ? null : net.Contains)) + HideMarkers($"landblock 0x{lb:X4} isn't on the trip"); + } + } + if (!_markersOn || !_tripShown || !Host.HasNav3D || !_hasPose) return; + + if (!ReferenceEquals(trip, _snapTrip) || !ReferenceEquals(_tripPath, _snapPath)) + { + _snapTrip = trip; _snapPath = _tripPath; + _markerSnap = PathMarkers.Build(trip, _tripPath, _townNet); + _markNext = -1; _markStep = -2; + } + MarkerSnapshot snap = _markerSnap; + if (snap.Marks.Length == 0) return; + if ((_cellId >> 16) == 0 || (Host.HasIsPortaling && Host.IsPortaling())) return; + + // The marker the walk heads for: on the running goto's current step. + int next = -1; + if (_gotoActive && trip.Live && !_settling) + { + int step = _route != null ? _routeIdx : 0; + if (step != _markStep || snap.TripId != _markTrip) { _markStep = step; _markTrip = snap.TripId; _markNext = -1; } + _markNext = next = PathMarkers.Advance(snap, _markNext, step, _wx, _wy); + } + var view = new MarkerView(_wx, _wy, _wz, next, _markerLabels && Host.HasNav3DTriangle, _markerGuide); + try { PathMarkers.Emit(snap, view, _markerSink ??= new HostMarkerSink(Host)); } + catch (Exception ex) { Host.Log($"[RynthNav] path markers: {ex.Message}"); } + } + + // ── /rnav markers ──────────────────────────────────────────────────── + + /// /rnav markers [on|off | labels on|off | guide on|off] + private void CmdMarkers(string rest) + { + string[] a = rest.ToLowerInvariant().Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (a.Length == 1 && a[0] is "on" or "off") + { + _markersOn = a[0] == "on"; + NavDataConfig.WriteSwitch("markers", _markersOn); + if (_markersOn) StartPathBuild(); + } + else if (a.Length == 2 && a[0] == "labels" && a[1] is "on" or "off") + { _markerLabels = a[1] == "on"; NavDataConfig.WriteSwitch("markerLabels", _markerLabels); } + else if (a.Length == 2 && a[0] == "guide" && a[1] is "on" or "off") + { _markerGuide = a[1] == "on"; NavDataConfig.WriteSwitch("markerGuide", _markerGuide); } + else if (a.Length > 0) { Say("/rnav markers on|off, markers labels on|off, markers guide on|off"); return; } + Say($"path markers {(_markersOn ? "ON" : "OFF")}, labels {(_markerLabels ? "on" : "off")}, guide line {(_markerGuide ? "on" : "off")}" + + (_trip == null ? "" : _tripShown ? $" — showing the trip to {_trip.Goal}" : $" — the trip to {_trip.Goal} isn't shown ({_markerStatus})")); + } + + /// The Atlas's portals on the map (positions to 0.01 degree): the circles a walk keeps out of. Tick thread. + private IReadOnlyList AtlasPortalSpots() + { + Atlas atlas = _atlas; + if (!ReferenceEquals(atlas, _avoidAtlas)) + { + var list = new List(); + foreach (AtlasLocation l in atlas.Locations) + if (l.OnMap && l.Type.Equals("Portal", StringComparison.Ordinal)) + list.Add(new PortalAvoid.Spot(NavCoords.WorldX(l.Ew), NavCoords.WorldY(l.Ns), PortalAvoid.MapRadius, l.Name)); + _atlasPortals = list; + _avoidAtlas = atlas; + } + return _atlasPortals; + } + + /// The engine's Nav3D buffer (the engine clears it each tick; every plugin adds to it). + private sealed class HostMarkerSink : IMarkerSink + { + private readonly RynthCore.PluginSdk.RynthCoreHost _host; + public HostMarkerSink(RynthCore.PluginSdk.RynthCoreHost host) => _host = host; + public void Ring(float x, float y, float z, float radius, float thickness, uint colorArgb) => _host.Nav3DAddRing(x, y, z, radius, thickness, colorArgb); + public void Line(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb) + => _host.Nav3DAddLine(x1, y1, z1, x2, y2, z2, thickness, colorArgb); + public void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint colorArgb) + => _host.Nav3DAddTriangle(x1, y1, z1, x2, y2, z2, x3, y3, z3, colorArgb); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs index abbb3c6..a9315c5 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs @@ -152,6 +152,14 @@ public sealed partial class RynthNavPlugin .Append("\",\"tileHere\":").Append(_tileHere).Append(",\"indoors\":").Append(_hasPose && (cell & 0xFFFF) >= 0x100 ? 1 : 0) .Append(",\"onDisk\":").Append(_tilesOnDisk) .Append(",\"townNet\":").Append(_townNet != null ? 1 : 0).Append(",\"townNetStatus\":\"").Append(Esc(_townNetStatus)).Append("\"}"); + // Path markers (RynthNavPlugin.Markers.cs) and "save as nav route" (RynthNavPlugin.SaveRoute.cs), 0.6.6+. + PlannedTrip? trip = _trip; + sb.Append(",\"markers\":{\"on\":").Append(_markersOn ? 1 : 0).Append(",\"labels\":").Append(_markerLabels ? 1 : 0) + .Append(",\"guide\":").Append(_markerGuide ? 1 : 0).Append(",\"shown\":").Append(trip != null && _tripShown ? 1 : 0) + .Append(",\"status\":\"").Append(Esc(_markerStatus)).Append("\"}"); + sb.Append(",\"save\":{\"can\":").Append(trip != null ? 1 : 0).Append(",\"for\":\"").Append(Esc(trip?.Goal ?? "")) + .Append("\",\"name\":\"").Append(Esc(_saveDefault)).Append("\",\"conflict\":\"").Append(Esc(_saveConflict)) + .Append("\",\"busy\":").Append(_saveBusy ? 1 : 0).Append(",\"last\":\"").Append(Esc(_saveLast)).Append("\"}"); } // ── The character's own recall spots, for the Recalls section (travel JSON) ── diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.SaveRoute.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.SaveRoute.cs new file mode 100644 index 0000000..4b5f518 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.SaveRoute.cs @@ -0,0 +1,100 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using RynthCore.Install; + +namespace RynthCore.Plugin.RynthNav; + +// "Save as nav route": the last trip RynthNav planned (Route or Go) written as a RynthAi nav route +// (NavRouteExport) into RynthAi's NavProfiles folder, where RynthAi's route picker lists it +// (RynthAi re-reads the folder when it changes) and /ra nav load loads it. +// /rnav saveroute [name] [overwrite] (the panel: the name box and Save on the Go tab) +// No name: "To ". An existing file is never replaced without "overwrite" (the panel +// then offers Replace). The path is the one the markers show; if it isn't worked out yet, it is +// first, and the save follows when it's done. Tick thread, except the file write (a worker). +public sealed partial class RynthNavPlugin +{ + /// RynthAi's route folder (what its Nav picker lists): <RynthSuite>\RynthAi\NavProfiles. + private static string NavProfilesDir => Path.Combine(RynthInstallPaths.RynthAiDir, "NavProfiles"); + + private (int TripId, string Name, bool Overwrite)? _pendingSave; + // For the panel (any thread reads them). + private volatile string _saveDefault = "", _saveConflict = "", _saveLast = ""; + private volatile bool _saveBusy; + + /// /rnav saveroute [name] [overwrite] + private void CmdSaveRoute(string rest) + { + PlannedTrip? trip = _trip; + if (trip == null) { Note("saveroute: plan a trip first (Route or Go), then save it"); return; } + string text = rest.Trim(); + bool overwrite = false; + if (text.Equals("overwrite", StringComparison.OrdinalIgnoreCase)) { overwrite = true; text = ""; } + else if (text.EndsWith(" overwrite", StringComparison.OrdinalIgnoreCase)) { overwrite = true; text = text[..^10].TrimEnd(); } + if (text.Length == 0) text = _saveDefault.Length > 0 ? _saveDefault : NavRouteExport.SafeName("To " + trip.Goal); + string name = NavRouteExport.FileName(text, out string error); + if (name.Length == 0) { Note("saveroute: " + error); return; } + + if (!overwrite && File.Exists(Path.Combine(NavProfilesDir, name + ".nav"))) + { + _saveConflict = name; + Note($"saveroute: {name}.nav is already in RynthAi's NavProfiles; /rnav saveroute {name} overwrite replaces it"); + return; + } + _saveConflict = ""; + if (_tripPath != null && _tripPath.TripId == trip.Id) { WriteRoute(trip, _tripPath, name, overwrite); return; } + _pendingSave = (trip.Id, name, overwrite); + StartPathBuild(); + _saveBusy = true; + Note($"saveroute: working out the path to {trip.Goal} first…"); + } + + /// The trip's path is in (or failed: null): a save waiting for it goes ahead. Tick thread. + private void OnPathReady(PlannedTrip? trip, TripPath? path) + { + if (_pendingSave is not { } ps || trip == null || ps.TripId != trip.Id) return; + _pendingSave = null; + _saveBusy = false; + if (path == null) { Note("saveroute: the path couldn't be worked out, so nothing was saved (see the log)"); return; } + WriteRoute(trip, path, ps.Name, ps.Overwrite); + } + + private void WriteRoute(PlannedTrip trip, TripPath path, string name, bool overwrite) + { + NavRouteExport.Result r = NavRouteExport.Convert(trip, path, _townNet); + if (r.Route.Points.Count == 0) + { + Note($"saveroute: nothing to save: {(r.StopReason.Length > 0 ? r.StopReason : "the trip has no steps")}"); + return; + } + string folder = NavProfilesDir; + string goal = trip.Goal; + int notes = path.Notes.Count; + string firstNote = notes > 0 ? path.Notes[0] : ""; + _saveBusy = true; + Task.Run(() => + { + string line; + bool ok = NavRouteExport.Save(folder, name, r.Route, overwrite, out string file, out bool exists, out string error); + if (ok) + { + line = $"saveroute: saved {name}.nav to {folder}: {r.Route.Points.Count} steps ({r.Waypoints} waypoints" + + (r.Portals > 0 ? $", {r.Portals} portal(s)" : "") + (r.Recalls + r.Chats > 0 ? $", {r.Recalls + r.Chats} recall(s)" : "") + + $"). RynthAi: pick it in Nav, or /ra nav load {name}."; + if (r.StoppedAt >= 0) line += $" It stops short of {goal}: {r.StopReason}."; + if (notes > 0) line += $" Check it: {firstNote}{(notes > 1 ? $" (+{notes - 1} more in the log)" : "")}."; + _saveConflict = ""; + Host.Log($"[RynthNav] {line} ({file})"); + } + else if (exists) + { + _saveConflict = name; + line = $"saveroute: {name}.nav is already there; /rnav saveroute {name} overwrite replaces it"; + } + else line = $"saveroute: couldn't write {name}.nav: {error}"; + _saveLast = line; + _saveBusy = false; + Say(line); + }); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs index 7281bc6..2957e9e 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs @@ -821,7 +821,9 @@ public sealed partial class RynthNavPlugin "/rnav route — plan a route (portals and recalls), no walking\n" + "/rnav atlas — find places | fav [place] — favorite | recalls [on|off] | tie 1|2\n" + "/rnav goto | preview | portals on|off | stop | here | load | test | navdata\n" + - "/rnav avoid — show; avoid portals on|off| | walls on|off| | corners "; + "/rnav avoid — show; avoid portals on|off| | walls on|off| | corners \n" + + "/rnav markers on|off | markers labels on|off | markers guide on|off — the trip on the ground\n" + + "/rnav saveroute [name] [overwrite] — save the last trip as a RynthAi nav route (NavProfiles)"; /// One /rnav command. Tick thread. private void RunCommand(string raw, bool fromPanel) @@ -863,6 +865,8 @@ public sealed partial class RynthNavPlugin break; case "recalls": CmdRecalls(rest); break; case "tie": CmdTie(rest); break; + case "markers": CmdMarkers(rest); break; + case "saveroute": CmdSaveRoute(rest); break; case "arrive": if (double.TryParse(rest, NumberStyles.Float, CultureInfo.InvariantCulture, out double yd) && yd >= 2 && yd <= 200) { _arrow.ArriveUnits = yd; Say($"the arrow counts you as arrived within {yd:F0} yd"); } @@ -937,6 +941,7 @@ public sealed partial class RynthNavPlugin AtlasLocation? portal = Entrance.PortalFor(_atlas, place, hasPos, pns, pew, out string why); if (portal == null) { Note("goto: " + why); return; } ns = portal.Ns; ew = portal.Ew; enter = place.Name; enterType = place.Type; + _nextEnterPortal = portal.Name; // the portal object a saved nav route uses (RynthNavPlugin.SaveRoute.cs) } StartGoto(name, type, ns, ew, enter, enterType); // StartWalk says "walking to ..." (or why it can't) } @@ -1034,7 +1039,7 @@ public sealed partial class RynthNavPlugin /// Plans a route (portals and, unless off, recalls) and shows it in the panel. Tick thread. private List? PlanAndShow(string name, double ns, double ew, out int used, out double est, out string refusal) { - TravelPlan.Result plan = PlanRoute(name, ns, ew, out _); + TravelPlan.Result plan = PlanRoute(name, ns, ew, out List recalls); List? steps = plan.Steps; used = plan.Teleports; est = plan.Est; refusal = plan.Refusal; _shownRoute = steps ?? new List { new(ns, ew, false, false, "walk") }; @@ -1042,6 +1047,7 @@ public sealed partial class RynthNavPlugin _shownRouteEst = est; _shownRouteLive = false; _routeVersion++; + if (refusal.Length == 0) SetTrip(steps, name, ns, ew, recalls, "", live: false); return steps; } diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs index 2cb97c3..d5dc65d 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs @@ -25,7 +25,7 @@ namespace RynthCore.Plugin.RynthNav; public sealed partial class RynthNavPlugin : RynthPluginBase { internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthNav"); - internal const string PluginVersion = "0.6.5"; + internal const string PluginVersion = "0.6.6"; internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi(PluginVersion); // Where the tiles, portals.tsv, locations.json and the player's atlas.txt/recalls.txt live. @@ -140,6 +140,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase _portalsEnabled = NavDataConfig.ReadSwitch("portals", false); _recallsEnabled = NavDataConfig.ReadSwitch("recalls", true); LoadAvoidSettings(); + LoadMarkerSettings(); Host.Log($"[RynthNav] Initialized v{PluginVersion} (tiled streaming + long-range goto + portal/recall routing + arrow + atlas). Panel: RynthNav. Tiles: {NavDataDir} ({NavConfig.Source})"); InitTravel(); LoadGraph(); @@ -180,6 +181,8 @@ public sealed partial class RynthNavPlugin : RynthPluginBase _tileRegions.Clear(); _tilePrints.Clear(); ResetCoarse(); _chatOut.Clear(); _goNote = ""; + HideMarkers("logged out"); + _trip = null; _tripPath = null; OnLogoutTravel(); } @@ -199,6 +202,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase TickTravel(); ProcessRequests(); ApplyMovement(); + TickMarkers(); UpdateGoLine(); FlushChat(); } @@ -342,6 +346,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase if (_gotoActive) _goNote = "stopped"; // the panel's status line (the d-pad and Stop say nothing in chat) _gotoActive = false; _route = null; _portalWait = false; if (_recallWait) EndRecall(); ResetHub(); + HideMarkers("cancelled"); } if (load && _hasPose) RefreshTiles(CurrentLandblock); if (test) TestImpl(); @@ -427,9 +432,9 @@ public sealed partial class RynthNavPlugin : RynthPluginBase { if (!_hasPose) { lock (_gate) _status = "no pose"; Note("goto: no player position yet"); return; } // A new goto (not the re-plan after "no route over land") may re-plan once again. - if (!landReplan) _landReplanned = false; + if (!landReplan) { _landReplanned = false; _enterPortal = enter.Length > 0 ? _nextEnterPortal : ""; _nextEnterPortal = ""; } // Whatever was running stops first: a refused goto must not leave the old one half-changed. - if (_gotoActive) { _gotoActive = false; _route = null; _portalWait = false; ResetHub(); Host.SetAutoRun(false); Host.StopCompletely(); } + if (_gotoActive) { _gotoActive = false; _route = null; _portalWait = false; ResetHub(); Host.SetAutoRun(false); Host.StopCompletely(); HideMarkers("a new goto"); } double twx = NavCoords.WorldX(tew), twy = NavCoords.WorldY(tns); int gLbX = (int)Math.Floor(twx / 192.0), gLbY = (int)Math.Floor(twy / 192.0); if (double.IsNaN(twx) || double.IsNaN(twy) || gLbX < 0 || gLbX > 255 || gLbY < 0 || gLbY > 255) @@ -503,6 +508,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase if (_route == null && !File.Exists(Path.Combine(NavDataDir, $"nav_{goalLb:X4}.tile"))) Say($"goto: the target's landblock 0x{goalLb:X4} has no tile; walking as far as the navmesh goes"); + SetTrip(_route, name, tns, tew, recalls, enter, live: true); _gotoActive = true; _gotoName = name; _gotoType = type; _walkHaveLast = false; @@ -790,6 +796,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase Say(status == "arrived" && _gotoName.Length > 0 ? $"goto: arrived at {_gotoName}" : $"goto: {status}"); _goNote = status == "arrived" && _gotoName.Length > 0 ? $"arrived at {_gotoName}" : status; _enterName = ""; _enterType = ""; + HideMarkers(status == "arrived" ? "arrived" : "the goto ended"); } // At a portal entrance, waiting for the teleport. A portal ALWAYS changes the diff --git a/Plugins/RynthCore.Plugin.RynthNav/TilePathFinder.cs b/Plugins/RynthCore.Plugin.RynthNav/TilePathFinder.cs new file mode 100644 index 0000000..55c000e --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/TilePathFinder.cs @@ -0,0 +1,241 @@ +using System; +using System.Collections.Generic; +using System.IO; +using DotRecast.Core.Numerics; +using DotRecast.Detour; +using DotRecast.Detour.Io; +using RynthCore.Plugin.RynthNav; + +namespace RynthNav.Routing; + +/// +/// Whole walking legs on the navmesh, worked out ahead of time for a planned trip (the path +/// markers and "save as nav route"), the way the walker would go: the route graph's border +/// crossings from the start's region to the goal's (NavGraph A*), then the detailed Detour path +/// between each pair of crossings, kept out of the Atlas's portals (AvoidFilter, PortalAvoid.Bend) +/// except the leg's own. Its own navmesh, filled from the tile files a few tiles at a time, so it +/// runs on a worker and never touches the walker's (tick-thread) navmesh. One instance per worker. +/// Without a route graph only short legs (a few landblocks) are planned; longer ones get none. +/// +internal sealed class TilePathFinder +{ + private const int MaxTiles = 64; + private const int MaxDirectTiles = 16; // without a graph: a leg spanning at most this many tiles + private const float ProbeReach = 40f; + private const double OwnPortalUnits = 15.0; // the leg's own portal (its goal) isn't avoided + private const double AvoidNearUnits = 300.0; + + private readonly string _dir; + private readonly NavGraph? _graph; + private readonly IReadOnlyList _portals; + private readonly DtNavMesh _nav; + private DtNavMeshQuery _query; + private readonly HashSet _loaded = new(), _bad = new(); + private readonly PortalAvoid _avoid = new(); + private readonly AvoidFilter _filter; + private readonly DtQueryDefaultFilter _plain = new(); + + /// Tile files read so far (for the log). + public int TilesRead { get; private set; } + + public TilePathFinder(string navDataDir, NavGraph? graph, IReadOnlyList? portals) + { + _dir = navDataDir; + _graph = graph; + _portals = portals ?? Array.Empty(); + _nav = new DtNavMesh(); + var p = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = MaxTiles, maxPolys = 1 << 16 }; + _nav.Init(p, 6); + _query = new DtNavMeshQuery(_nav); + _filter = new AvoidFilter(_avoid); + } + + /// + /// The walk from to : corners, both ends included. + /// : the walk ends by stepping into a portal there (not avoided). + /// Null when the navmesh can't give one (no tiles, no way over land); says why. + /// + public List? Walk(WorldPt from, WorldPt to, bool ownPortal, out string note) + { + note = ""; + var anchors = new List { from }; + if (_graph != null) + { + NavCoarse.Probe? s = GroundProbe(from), g = GroundProbe(to); + if (s == null || g == null) { note = $"no navmesh at its {(s == null ? "start" : "end")}"; return null; } + List? route = _graph.FindRoute(s.Region, s.Pt.X, s.Pt.Z, g.Region, g.Pt.X, g.Pt.Z, out _, out _); + if (route == null) { note = "no way over land on the navmesh"; return null; } + // Plan from and to the ground found there (the trip's own ends are added back by the caller). + anchors[0] = new WorldPt(s.Pt.X, s.Pt.Z, s.Pt.Y); + from = anchors[0]; + to = new WorldPt(g.Pt.X, g.Pt.Z, g.Pt.Y); + foreach (int p in route) + { + var c = _graph.Portal(p); + anchors.Add(new WorldPt(c.Ew, c.Ns, c.Up)); + } + } + else if (TileSpan(from, to) > MaxDirectTiles) + { + note = "too far to plan without the route graph (navgraph.bin)"; + return null; + } + anchors.Add(to); + + var path = new List { from }; + int gaps = 0; + for (int k = 0; k + 1 < anchors.Count; k++) + { + bool last = k + 2 == anchors.Count; + List? piece = Piece(anchors[k], anchors[k + 1], last && ownPortal ? anchors[k + 1] : null); + if (piece == null) { gaps++; piece = new List { anchors[k], anchors[k + 1] }; } + for (int i = 1; i < piece.Count; i++) path.Add(piece[i]); + } + if (gaps > 0) note = $"{gaps} gap(s) in the navmesh, straight lines there"; + return path; + } + + /// + /// Walkable ground at for the route search. A point with no height (a + /// landing, a portal, a town's centre) can find a roof or a ledge first: a region of a tiny + /// landmass that leads nowhere (the real map: Lytelthorpe's centre is under a roof). Then the + /// ground a few yards round it (rings out to 36 yd) that's part of a real landmass is taken. + /// + private NavCoarse.Probe? GroundProbe(WorldPt p) + { + NavGraph g = _graph!; + NavCoarse.Probe? first = NavCoarse.ProbeFile(g, _dir, p.X, p.H, p.Y, ProbeReach); + if (first != null && !Tiny(first.Region)) return first; + for (double r = 6; r <= 36; r += 6) + for (int k = 0; k < 8; k++) + { + double a = k * Math.PI / 4; + NavCoarse.Probe? q = NavCoarse.ProbeFile(g, _dir, p.X + Math.Cos(a) * r, p.H, p.Y + Math.Sin(a) * r, 4f); + if (q != null && !Tiny(q.Region)) return q; + } + return first; + } + + /// A region of a landmass this small (a roof, a ledge); false when the graph has no landmasses worked out. + private bool Tiny(int region) + { + int c = _graph!.Component(region); + return c >= 0 && _graph.ComponentSize(c) < 8; + } + + private static int TileSpan(WorldPt a, WorldPt b) + { + int ax = (int)Math.Floor(a.X / 192.0), ay = (int)Math.Floor(a.Y / 192.0), bx = (int)Math.Floor(b.X / 192.0), by = (int)Math.Floor(b.Y / 192.0); + return (Math.Abs(ax - bx) + 1) * (Math.Abs(ay - by) + 1); + } + + /// The Detour path a→b (both ends' tiles and those between loaded); null when there's none. + private List? Piece(WorldPt a, WorldPt b, WorldPt? own) + { + if (!LoadBox(a, b)) return null; + var half = new RcVec3f(8, 600, 8); + var pa = new RcVec3f((float)a.X, double.IsNaN(a.H) ? 0f : (float)a.H, (float)a.Y); + var pb = new RcVec3f((float)b.X, double.IsNaN(b.H) ? 0f : (float)b.H, (float)b.Y); + _query.FindNearestPoly(pa, half, _plain, out long sRef, out RcVec3f sPt, out _); + _query.FindNearestPoly(pb, half, _plain, out long gRef, out RcVec3f gPt, out _); + if (sRef == 0 || gRef == 0) return null; + + // Portals near this piece, except the leg's own. + var near = new List(); + double minX = Math.Min(a.X, b.X) - AvoidNearUnits, maxX = Math.Max(a.X, b.X) + AvoidNearUnits; + double minY = Math.Min(a.Y, b.Y) - AvoidNearUnits, maxY = Math.Max(a.Y, b.Y) + AvoidNearUnits; + foreach (PortalAvoid.Spot sp in _portals) + if (sp.X >= minX && sp.X <= maxX && sp.Y >= minY && sp.Y <= maxY) near.Add(sp); + if (own is WorldPt ownAt) _avoid.Set(Array.Empty(), near, ownAt.X, ownAt.Y, OwnPortalUnits); + else _avoid.Set(Array.Empty(), near); + _filter.AllowA = sRef; _filter.AllowB = gRef; + + Span polys = new long[1024]; + _query.FindPath(sRef, gRef, sPt, gPt, _filter, polys, out int pc, 1024); + if ((pc == 0 || polys[pc - 1] != gRef) && _avoid.Count > 0) + _query.FindPath(sRef, gRef, sPt, gPt, _plain, polys, out pc, 1024); + if (pc == 0 || polys[pc - 1] != gRef) return null; + Span sp2 = new DtStraightPath[256]; + _query.FindStraightPath(sPt, gPt, polys[..pc], pc, sp2, out int spc, 256, 0); + if (spc < 2) return null; + + var corners = new List<(double X, double Y)>(spc); + List? heights = new List(spc); + for (int i = 0; i < spc; i++) { corners.Add((sp2[i].pos.X, sp2[i].pos.Z)); heights.Add(sp2[i].pos.Y); } + if (_avoid.Count > 0) + { + var q = _query; + bool OnMesh(double x, double y) + { + q.FindNearestPoly(new RcVec3f((float)x, pa.Y, (float)y), new RcVec3f(0.5f, 600, 0.5f), _plain, out long r, out RcVec3f np, out _); + return r != 0 && Math.Abs(np.X - x) < 0.05 && Math.Abs(np.Z - y) < 0.05; + } + bool LegOnMesh(double ax, double ay, double bx, double by) + { + double len = Math.Sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay)); + int n = Math.Max(1, (int)Math.Ceiling(len)); + for (int k = 1; k < n; k++) + if (!OnMesh(ax + (bx - ax) * k / n, ay + (by - ay) * k / n)) return false; + return true; + } + int before = corners.Count; + corners = _avoid.Bend(corners, OnMesh, 12, LegOnMesh); + if (corners.Count != before) heights = null; // bend corners: heights filled from the neighbours + } + var o = new List(corners.Count) { a with { H = heights != null ? heights[0] : (double.IsNaN(a.H) ? sPt.Y : a.H) } }; + for (int i = 1; i < corners.Count; i++) + o.Add(new WorldPt(corners[i].X, corners[i].Y, heights != null ? heights[i] : double.NaN)); + if (heights == null) o[^1] = o[^1] with { H = gPt.Y }; + return o; + } + + /// Loads the tiles of the box a..b (evicting others when full); false when it's too big or none loads. + private bool LoadBox(WorldPt a, WorldPt b) + { + int x0 = (int)Math.Floor(Math.Min(a.X, b.X) / 192.0), x1 = (int)Math.Floor(Math.Max(a.X, b.X) / 192.0); + int y0 = (int)Math.Floor(Math.Min(a.Y, b.Y) / 192.0), y1 = (int)Math.Floor(Math.Max(a.Y, b.Y) / 192.0); + // A crossing on a tile edge belongs to both tiles: take one more on each side then. + if (a.X - x0 * 192.0 < 1 || b.X - x0 * 192.0 < 1) x0--; + if ((x1 + 1) * 192.0 - Math.Max(a.X, b.X) < 1) x1++; + if (a.Y - y0 * 192.0 < 1 || b.Y - y0 * 192.0 < 1) y0--; + if ((y1 + 1) * 192.0 - Math.Max(a.Y, b.Y) < 1) y1++; + x0 = Math.Max(0, x0); y0 = Math.Max(0, y0); x1 = Math.Min(255, x1); y1 = Math.Min(255, y1); + int want = (x1 - x0 + 1) * (y1 - y0 + 1); + if (want > MaxTiles / 2) return false; + var needed = new HashSet(); + for (int x = x0; x <= x1; x++) + for (int y = y0; y <= y1; y++) needed.Add((uint)((x << 8) | y)); + bool changed = false; + if (_loaded.Count + want > MaxTiles - 1) + { + foreach (uint lb in new List(_loaded)) + { + if (needed.Contains(lb)) continue; + long r = _nav.GetTileRefAt((int)(lb >> 8), (int)(lb & 0xFF), 0); + if (r != 0) _nav.RemoveTile(r); + _loaded.Remove(lb); + changed = true; + } + } + bool any = false; + foreach (uint lb in needed) + { + if (_loaded.Contains(lb)) { any = true; continue; } + if (_bad.Contains(lb)) continue; + string path = Path.Combine(_dir, $"nav_{lb:X4}.tile"); + if (!File.Exists(path)) { _bad.Add(lb); continue; } + try + { + DtMeshData md; + using (var fr = File.OpenRead(path)) using (var br = new BinaryReader(fr)) md = new DtMeshDataReader().Read(br, 6); + TilesRead++; + if (_nav.AddTile(md, 0, 0, out _).Failed()) { _bad.Add(lb); continue; } + _loaded.Add(lb); + changed = any = true; + } + catch { _bad.Add(lb); } + } + if (changed) _query = new DtNavMeshQuery(_nav); + return any; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/TripPath.cs b/Plugins/RynthCore.Plugin.RynthNav/TripPath.cs new file mode 100644 index 0000000..be92d8a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/TripPath.cs @@ -0,0 +1,190 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthNav; + +/// +/// The ground a walks, worked out once for the whole trip (on a worker: +/// TilePathFinder reads the tiles and the route graph into its own navmesh): per walking step, the +/// path from where the step starts to its point, thinned to the corners that matter; per hub step, +/// the walk inside the Town Network. The path markers draw it and "save as nav route" writes it. +/// Never changed after it's built. Host-free: the route tests build these with a fake path finder. +/// +internal sealed class TripPath +{ + public readonly int TripId; + /// Per step: the walk, first point = where it starts, last = the step's point (null = no walk). + public readonly WorldPt[]?[] Walks; + /// Per hub step: the walk inside the Town Network to the exit portal (null otherwise). + public readonly WorldPt[]?[] Hub; + /// What couldn't be worked out ("step 2: no navmesh path, a straight line"), for chat. + public readonly IReadOnlyList Notes; + + public TripPath(int tripId, WorldPt[]?[] walks, WorldPt[]?[] hub, IReadOnlyList notes) + { + TripId = tripId; Walks = walks; Hub = hub; Notes = notes; + } +} + +internal static class TripPathBuilder +{ + /// A corner closer than this (yards) to the straight line past it is dropped. + public const double ThinTolerance = 0.75; + /// Straight stretches get a point at least this often (yards), so the markers and a nav follow the ground. + public const double MaxSpacing = 60.0; + /// Points closer together than this are one point. + public const double DuplicateUnits = 0.5; + + /// + /// A walkable path from to (corners, both ends + /// included), or null when there is none to be had; says why or what was + /// approximated. : the walk ends by stepping into a portal at + /// (so that one isn't kept out of). + /// + public delegate List? WalkFinder(WorldPt from, WorldPt to, bool intoPortal, out string note); + + /// + /// The trip's ground: each walking step through (a straight line where it + /// has nothing, with a note), each hub step from ; all thinned. + /// + public static TripPath Build(PlannedTrip trip, WalkFinder? walk, TownNet? net) + { + int n = trip.Count; + var walks = new WorldPt[]?[n]; + var hub = new WorldPt[]?[n]; + var notes = new List(); + for (int i = 0; i < n; i++) + { + if (trip.Steps[i].IsHub) + { + List? inside = trip.HubWalk(i, net, out string why); + if (inside == null) notes.Add($"step {i + 1}: {why}"); + else hub[i] = Thin(inside).ToArray(); + continue; + } + if (trip.WalkFrom[i] is not WorldPt from || trip.Point[i] is not WorldPt to) continue; + string note = ""; + List? raw = null; + try { raw = walk?.Invoke(from, to, trip.Steps[i].UsePortal, out note); } + catch (Exception ex) { note = "path finder failed: " + ex.Message; raw = null; } + if (raw == null || raw.Count < 2) + { + raw = new List { from, to }; + notes.Add($"step {i + 1}: {(note.Length > 0 ? note : "no navmesh path")}; a straight line there"); + } + else + { + if (note.Length > 0) notes.Add($"step {i + 1}: {note}"); + // The path ends on the navmesh beside the point; the point itself is where the step goes. + if (raw[0].FlatDistance(from) > 2.0) raw.Insert(0, from); + if (raw[^1].FlatDistance(to) > 2.0) raw.Add(new WorldPt(to.X, to.Y, raw[^1].H)); + } + walks[i] = Thin(raw).ToArray(); + } + return new TripPath(trip.Id, walks, hub, notes); + } + + /// + /// The path with near-duplicate points merged, corners within of the + /// line past them dropped (Ramer-Douglas-Peucker, ends kept), and straight stretches longer than + /// split evenly. Unknown heights are filled from the neighbours. + /// + public static List Thin(IReadOnlyList pts, double tolerance = ThinTolerance, double maxSpacing = MaxSpacing) + { + var dedup = new List(pts.Count); + foreach (WorldPt p in pts) + { + if (double.IsNaN(p.X) || double.IsNaN(p.Y)) continue; + if (dedup.Count > 0 && dedup[^1].FlatDistance(p) < DuplicateUnits) + { + if (double.IsNaN(dedup[^1].H) && !double.IsNaN(p.H)) dedup[^1] = dedup[^1] with { H = p.H }; + continue; + } + dedup.Add(p); + } + FillHeights(dedup); + if (dedup.Count <= 2) return Split(dedup, maxSpacing); + + var keep = new bool[dedup.Count]; + keep[0] = keep[^1] = true; + var stack = new Stack<(int A, int B)>(); + stack.Push((0, dedup.Count - 1)); + while (stack.Count > 0) + { + var (a, b) = stack.Pop(); + int best = -1; + double bestD = tolerance; + for (int i = a + 1; i < b; i++) + { + double d = PlannedTrip.SegmentDistance(dedup[i], dedup[a], dedup[b]); + if (d > bestD) { bestD = d; best = i; } + } + if (best < 0) continue; + keep[best] = true; + stack.Push((a, best)); + stack.Push((best, b)); + } + var kept = new List(); + for (int i = 0; i < dedup.Count; i++) if (keep[i]) kept.Add(dedup[i]); + return Split(kept, maxSpacing); + } + + private static List Split(List pts, double maxSpacing) + { + if (pts.Count < 2 || maxSpacing <= 0) return pts; + var o = new List(pts.Count) { pts[0] }; + for (int i = 1; i < pts.Count; i++) + { + WorldPt a = pts[i - 1], b = pts[i]; + int parts = (int)Math.Ceiling(a.FlatDistance(b) / maxSpacing); + for (int k = 1; k < parts; k++) + { + double t = (double)k / parts; + o.Add(new WorldPt(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t, a.H + (b.H - a.H) * t)); + } + o.Add(b); + } + return o; + } + + /// NaN heights take the nearest known one before them (else after them). + private static void FillHeights(List pts) + { + double last = double.NaN; + for (int i = 0; i < pts.Count; i++) + { + if (!double.IsNaN(pts[i].H)) last = pts[i].H; + else if (!double.IsNaN(last)) pts[i] = pts[i] with { H = last }; + } + double next = double.NaN; + for (int i = pts.Count - 1; i >= 0; i--) + { + if (!double.IsNaN(pts[i].H)) next = pts[i].H; + else if (!double.IsNaN(next)) pts[i] = pts[i] with { H = next }; + } + } + + /// + /// The path stopped short of its end, measured along it (a walk to a + /// portal stops before stepping in). Only the start is left when the path is shorter than that. + /// + public static List StopShort(IReadOnlyList pts, double units) + { + var o = new List(pts); + double left = units; + while (o.Count >= 2 && left > 0) + { + WorldPt a = o[^2], b = o[^1]; + double d = a.FlatDistance(b); + if (d > left) + { + double t = (d - left) / d; + o[^1] = new WorldPt(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t, a.H + (b.H - a.H) * t); + return o; + } + left -= d; + o.RemoveAt(o.Count - 1); + } + return o; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/TripPlan.cs b/Plugins/RynthCore.Plugin.RynthNav/TripPlan.cs new file mode 100644 index 0000000..78aafc8 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/TripPlan.cs @@ -0,0 +1,215 @@ +using System; +using System.Collections.Generic; +using RynthNav.Routing; + +namespace RynthCore.Plugin.RynthNav; + +/// +/// A point in RynthNav's world units: X = east, Y = north (landblock * 192 + local), H = height +/// (the pose z; NaN = not known). +/// +internal readonly record struct WorldPt(double X, double Y, double H) +{ + public static WorldPt FromMap(double ns, double ew, double h = double.NaN) => new(NavCoords.WorldX(ew), NavCoords.WorldY(ns), h); + public double Ns => NavCoords.NsFromWorld(Y); + public double Ew => NavCoords.EwFromWorld(X); + public double FlatDistance(WorldPt o) => Math.Sqrt((X - o.X) * (X - o.X) + (Y - o.Y) * (Y - o.Y)); + /// The landblock under the point (0xXXYY), or uint.MaxValue off the map. + public uint Landblock + { + get + { + int x = (int)Math.Floor(X / 192.0), y = (int)Math.Floor(Y / 192.0); + return x is >= 0 and <= 255 && y is >= 0 and <= 255 ? (uint)((x << 8) | y) : uint.MaxValue; + } + } +} + +/// A recall of the plan, as the plan was made (RouteStep.RecallIndex indexes these). +internal readonly record struct TripRecall(string Name, int SpellId, string Command, double CastSeconds); + +/// +/// One trip RynthNav planned (Route) or is walking (Go), frozen when it was planned: the steps, +/// where it started, the recalls it may cast and the portal a dungeon goto ends in. Never changed +/// after it's made, so the path builder (a worker), the markers and "save as nav route" all read +/// the same thing without locks. Host-free: the route tests build these. +/// +/// What each step walks ( to ): +/// a walk step from where the last step left you to its point; +/// a portal step the same, its point being the portal's entrance (then the teleport); +/// a recall step nothing: cast where you stand (its point is that spot); +/// a hub step nothing on the map: the walk inside the Town Network (TownNet's walks). +/// After a portal or recall you stand at its landing (LandNs/LandEw); after a portal into a +/// dungeon or the Town Network there's no map position until a hub step or a recall. +/// +internal sealed class PlannedTrip +{ + /// A landblock this close to a leg (its centre, world units) counts as on the plan. + public const double CoverUnits = 288.0; + + public readonly int Id; + public readonly IReadOnlyList Steps; + public readonly string Goal; + public readonly double GoalNs, GoalEw; + public readonly bool StartOnMap; + public readonly WorldPt Start; + public readonly uint StartCell; + public readonly IReadOnlyList Recalls; + /// The portal object the last step walks into (a dungeon goto); "" = none or not known. + public readonly string EnterPortal; + /// The dungeon (or portal) that last step goes into; "" = none. + public readonly string EnterName; + /// The running goto's plan (false: planned with Route, not walked). + public readonly bool Live; + + /// Per step: where its walk starts (null = no walk: a recall, a hub step, or no map position). + public readonly WorldPt?[] WalkFrom; + /// Per step: where it happens (a walk's end, a portal's entrance, a recall's cast spot); null for a hub step. + public readonly WorldPt?[] Point; + + public PlannedTrip(int id, IReadOnlyList steps, string goal, double goalNs, double goalEw, + bool startOnMap, WorldPt start, uint startCell, IReadOnlyList? recalls, + string enterPortal = "", string enterName = "", bool live = false) + { + Id = id; + Steps = steps.Count == 0 ? new[] { new RouteStep(goalNs, goalEw, false, false, "walk") } : new List(steps).ToArray(); + Goal = goal; GoalNs = goalNs; GoalEw = goalEw; + StartOnMap = startOnMap; Start = start; StartCell = startCell; + Recalls = recalls ?? Array.Empty(); + EnterPortal = enterPortal ?? ""; EnterName = enterName ?? ""; Live = live; + + int n = Steps.Count; + WalkFrom = new WorldPt?[n]; + Point = new WorldPt?[n]; + WorldPt? here = startOnMap ? start : null; + for (int i = 0; i < n; i++) + { + RouteStep s = Steps[i]; + if (s.UseRecall) + { + // Cast where you stand: the trip's start for a first step (in a dungeon too). + Point[i] = here ?? (i == 0 ? start : null); + here = double.IsNaN(s.LandNs) ? null : WorldPt.FromMap(s.LandNs, s.LandEw); + continue; + } + if (s.IsHub) + { + here = double.IsNaN(s.LandNs) ? null : WorldPt.FromMap(s.LandNs, s.LandEw); + continue; + } + WorldPt to = WorldPt.FromMap(s.Ns, s.Ew); + WalkFrom[i] = here; + Point[i] = to; + here = !s.UsePortal ? to : double.IsNaN(s.LandNs) ? null : WorldPt.FromMap(s.LandNs, s.LandEw); + } + } + + public int Count => Steps.Count; + public bool HasHub { get { foreach (RouteStep s in Steps) if (s.IsHub) return true; return false; } } + + /// The last step is a portal into the place the goto was for (a dungeon). + public bool EndsInEntrance => EnterName.Length > 0 && Steps.Count > 0 && Steps[^1].UsePortal; + + /// The portal object step walks into: its label, or for the dungeon entrance, the portal's own name. + public string PortalName(int i) + { + if (i == Steps.Count - 1 && EndsInEntrance && EnterPortal.Length > 0) return EnterPortal; + return Steps[i].Label ?? ""; + } + + /// The recall of step , or null when the plan doesn't know it. + public TripRecall? RecallOf(int i) + { + int r = Steps[i].RecallIndex; + return r >= 0 && r < Recalls.Count ? Recalls[r] : null; + } + + /// + /// Is on this trip: the start's own landblock, near one of its walks + /// (the straight leg, or the path built for it), its steps or landings, or inside the Town + /// Network on a trip that takes it? A teleport somewhere else isn't. + /// + public bool Covers(uint landblock, TripPath? path, Func? inHub) + { + if (landblock == 0 || landblock == ((StartCell >> 16) & 0xFFFF)) return true; + if (HasHub && inHub != null && inHub(landblock)) return true; + double cx = ((landblock >> 8) & 0xFF) * 192.0 + 96.0, cy = (landblock & 0xFF) * 192.0 + 96.0; + var c = new WorldPt(cx, cy, 0); + for (int i = 0; i < Steps.Count; i++) + { + if (Point[i] is WorldPt p && p.FlatDistance(c) <= CoverUnits) return true; + if (WalkFrom[i] is WorldPt f && Point[i] is WorldPt t && SegmentDistance(c, f, t) <= CoverUnits) return true; + RouteStep s = Steps[i]; + if (!double.IsNaN(s.LandNs) && WorldPt.FromMap(s.LandNs, s.LandEw).FlatDistance(c) <= CoverUnits) return true; + WorldPt[]? w = path?.TripId == Id && i < path.Walks.Length ? path.Walks[i] : null; + if (w != null) + for (int k = 1; k < w.Length; k++) + if (SegmentDistance(c, w[k - 1], w[k]) <= CoverUnits) return true; + } + return false; + } + + /// Flat distance from to the segment a→b. + public static double SegmentDistance(WorldPt p, WorldPt a, WorldPt b) => SegmentDistance(p, a, b, out _); + + /// Flat distance from to the segment a→b, and how far along it the nearest point is (0..1). + public static double SegmentDistance(WorldPt p, WorldPt a, WorldPt b, out double t) + { + double vx = b.X - a.X, vy = b.Y - a.Y, l2 = vx * vx + vy * vy; + t = l2 < 1e-9 ? 0 : Math.Clamp(((p.X - a.X) * vx + (p.Y - a.Y) * vy) / l2, 0, 1); + double x = a.X + vx * t, y = a.Y + vy * t; + return Math.Sqrt((p.X - x) * (p.X - x) + (p.Y - y) * (p.Y - y)); + } + + /// + /// The walk inside the Town Network for hub step , in world units (the + /// network's landblock): from the arrival the entry portal before it lands on (or, for a trip + /// that starts inside, from where it started) to the exit portal. Null, with a reason, when + /// townnet.json doesn't have it. + /// + public List? HubWalk(int i, TownNet? net, out string why) + { + why = ""; + if (net == null) { why = "the Town Network data (townnet.json) isn't loaded"; return null; } + RouteStep s = Steps[i]; + int exit = s.HubExit; + if (exit < 0 || exit >= net.Exits.Count) { why = "the Town Network exit isn't in townnet.json"; return null; } + IReadOnlyList? pts = null; + if (i > 0 && Steps[i - 1].UsePortal) + { + // The entry portal walked into: the townnet.json entry at that spot, and its arrival. + RouteStep e = Steps[i - 1]; + TownNetEntry? best = null; + double bestD = 2.0; // the plan's entry coordinates are the entry's own + foreach (TownNetEntry en in net.Entries) + { + if (!en.OnMap) continue; + double d = NavCoords.Distance(en.Ns, en.Ew, e.Ns, e.Ew); + if (d < bestD) { bestD = d; best = en; } + } + if (best == null || best.Arrival < 0) { why = $"the entry portal {e.Label} isn't in townnet.json"; return null; } + pts = net.Walk(best.Arrival, exit)?.Points; + if (pts == null) { why = $"townnet.json has no walk from {best.Name}'s arrival to the {net.Exits[exit].Name}"; return null; } + } + else if (i == 0 && !StartOnMap && net.Contains((StartCell >> 16) & 0xFFFF)) + { + double lx = Start.X - ((StartCell >> 24) & 0xFF) * 192.0, ly = Start.Y - ((StartCell >> 16) & 0xFF) * 192.0; + pts = net.WayTo(exit, lx, ly, HubWalker.OffRouteUnits, out _); + if (pts == null) { why = "no Town Network walk to that exit passes where the trip started"; return null; } + } + else { why = "the plan doesn't say how it gets into the Town Network"; return null; } + + var list = new List(pts.Count); + foreach (TownNetPoint p in pts) + list.Add(new WorldPt(((p.Cell >> 24) & 0xFF) * 192.0 + p.X, ((p.Cell >> 16) & 0xFF) * 192.0 + p.Y, p.Z)); + return list; + } + + /// Where the hub step's exit portal stands (world units), or null. + public static WorldPt? HubExitPoint(TownNet? net, RouteStep s) + { + if (net == null || s.HubExit < 0 || s.HubExit >= net.Exits.Count) return null; + TownNetExit x = net.Exits[s.HubExit]; + return new WorldPt(((x.Cell >> 24) & 0xFF) * 192.0 + x.X, ((x.Cell >> 16) & 0xFF) * 192.0 + x.Y, x.Z); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNet/RynthCore.Plugin.RynthNet.csproj b/Plugins/RynthCore.Plugin.RynthNet/RynthCore.Plugin.RynthNet.csproj index b8d525e..1ce02a2 100644 --- a/Plugins/RynthCore.Plugin.RynthNet/RynthCore.Plugin.RynthNet.csproj +++ b/Plugins/RynthCore.Plugin.RynthNet/RynthCore.Plugin.RynthNet.csproj @@ -38,4 +38,9 @@ + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthNet/RynthNetSettings.cs b/Plugins/RynthCore.Plugin.RynthNet/RynthNetSettings.cs index 1efb4ce..63fdd1e 100644 --- a/Plugins/RynthCore.Plugin.RynthNet/RynthNetSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthNet/RynthNetSettings.cs @@ -57,7 +57,7 @@ internal sealed class RynthNetCharacter internal sealed class RynthNetSettings { - public const string DefaultFolder = @"C:\Games\RynthSuite\RynthNet"; + public static readonly string DefaultFolder = Path.Combine(RynthCore.Install.RynthInstallPaths.SuiteDir, "RynthNet"); // C:\Games\RynthSuite\RynthNet by default /// The settings folder; RYNTHNET_DIR overrides it (tests, portable setups). public static string Folder => Environment.GetEnvironmentVariable("RYNTHNET_DIR") is { Length: > 0 } dir ? dir : DefaultFolder; public static string FilePath => Path.Combine(Folder, "settings.json"); diff --git a/Plugins/Shared/ActionPacer.cs b/Plugins/Shared/ActionPacer.cs new file mode 100644 index 0000000..aaa5a44 --- /dev/null +++ b/Plugins/Shared/ActionPacer.cs @@ -0,0 +1,471 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/ActionPacer.cs +// One server action at a time: RynthAi's pacing of uses, casts and combat-mode +// changes on the server's answers (2026-10-06). +// +// Why: Drakkon's "can't use anything" and "stuck in the cast animation" stalls on +// DreamWeave (ops/overnight/2026-10-06-action-pacing.md). Every stall began with a +// combat-mode change sent while a corpse use was still unanswered by the server +// (4 of 4 onsets; 0 stalls after ~920 uses with no such overlap). Once in that state +// the server finishes nothing that waits on an animation until a relog, and the bot +// made it worse by firing the next cast/use every 0.4-2.5 s because nothing waited +// for the server's answer: the client busy count it paced on was zeroed and repaired +// hundreds of times an hour, and "cast resolved" meant the enchantment, not the +// server's UseDone. +// +// The rule here: +// * A use, a use-on, a cast or a combat-mode change that RynthAi sends is the ONE +// outstanding server action until the server answers it: +// - use / use-on / cast: the next UseDone (GameEvent 0x01C7) after the send, +// whatever its error (a refusal is an answer too); a wield also counts as +// answered when the item reads wielded (a wield gets no UseDone); +// - combat mode: the client reads the new mode and ModeSettleMs has passed +// (the stance animation; the server sends no UseDone for it); +// or its time limit passes (logged; nothing is force-cleared). +// * While one is outstanding, RynthAi starts no other one (MayStart; mode changes +// are refused right at ChangeCombatModeFor) and moves or turns the character +// only to stop real movement (MoveAudit asks HoldsMovement). +// * Heals keep their priority: a heal may go ahead of a corpse/door use the server +// hasn't answered after HealAfterWorldUseMs (EmergencyAfterWorldUseMs at +// Emergency Heal At), and one heal may follow a cast whose result is already in +// (the server queues one cast behind the recoil). +// +// Opt-in (Enabled, RynthAi sets it at Init); off = every call goes through as before. +// Linked into RynthAi only. UseAudit reports its sends through UseAudit.AfterSend. +// ============================================================================ + +using System; +using System.Collections.Generic; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.Shared; + +internal enum PacedKind +{ + None, + /// A door, corpse, portal or NPC: the server walks/turns the character to it first. + WorldUse, + /// A kit, potion, stone, wand or weapon (wield), scroll... in the character's own packs. + ItemUse, + /// A spell cast. + Cast, + /// A combat-mode (stance) change. + CombatMode, +} + +internal enum HealNeed +{ + None, + /// Health under a heal line. + Heal, + /// Health at or under Emergency Heal At. + Emergency, +} + +/// The one server action RynthAi is waiting on. +internal sealed class PacedAction +{ + public PacedKind Kind; + public uint Id; + public string Label = ""; + public string Who = ""; + public long SentMs; + public int SeqAtSend; + public int ModeTarget; + public bool WieldedAtSend; + public bool ResultSeen; // a cast's result is in (enchantment / chat); the server is in its recoil + public bool HealQueued; // the one heal allowed behind that recoil went out + public long ModeSeenMs; // when the client first read the requested mode + public long WieldSeenMs; // when a wield first read done + public readonly HashSet LoggedWaits = new(); +} + +internal static class ActionPacer +{ + /// Off = nothing is paced (every call goes through as before). RynthAi turns it on. + public static volatile bool Enabled; + + /// Clock (ms); tests replace it. + public static Func NowMs = () => Environment.TickCount64; + + // Time limits: the longest the server took to answer in 3.7 h of healthy logs (10-05/10-06, + // p99 / max): corpse use 3.0 / 3.7 s, kit 2.5 s, buff cast 3.6 s, vital cast 4.7 / 5.0 s. + public const long WorldUseMaxMs = 5000; + public const long ItemUseMaxMs = 3500; + public const long CastMaxMs = 7000; + public const long ModeMaxMs = 2000; + /// The stance animation after the client reads the new mode: no action before it ends. + public const long ModeSettleMs = 800; + /// A wield that reads done: a short settle for the wield motion. + public const long WieldSettleMs = 150; + /// A heal may go ahead of a door/corpse use unanswered this long (the server cancels the walk cleanly). + public const long HealAfterWorldUseMs = 1000; + public const long EmergencyAfterWorldUseMs = 300; + /// A heal behind a stance change: once the client has read the new mode this long. + public const long HealAfterModeReadMs = 300; + /// An engine without UseDone: an action counts as answered after this (no real pacing). + public const long NoUseDoneFallbackMs = 600; + + private static readonly object Gate = new(); + private static PacedAction? _cur; + + // Counters for /ra pace and the periodic summary. + private static long _started, _answered, _timedOut, _sentOverOutstanding, _modeRefused, _modeSkipped; + private static long _heldStarts, _heldMoves, _healsAhead; + private static long _maxWaitMs; + private static string _maxWaitWhat = ""; + private static readonly Dictionary _holdsByWho = new(); + private static string _lastTimeout = ""; + + public static long Started => _started; + public static long Answered => _answered; + public static long TimedOut => _timedOut; + public static long SentOverOutstanding => _sentOverOutstanding; + public static long ModeChangesRefused => _modeRefused; + public static long ModeChangesSkipped => _modeSkipped; + public static long HeldStarts => _heldStarts; + public static long HeldMoves => _heldMoves; + public static long HealsAhead => _healsAhead; + + /// Back to a fresh load (Init, logout, tests). Enabled is left as it is. + public static void Reset() + { + lock (Gate) + { + _cur = null; + _started = _answered = _timedOut = _sentOverOutstanding = _modeRefused = _modeSkipped = 0; + _heldStarts = _heldMoves = _healsAhead = 0; + _maxWaitMs = 0; + _maxWaitWhat = ""; + _holdsByWho.Clear(); + _lastTimeout = ""; + } + } + + /// Forget the outstanding action (logout, death, portal): the server dropped it. + public static void Forget(string why) + { + lock (Gate) { _cur = null; } + } + + // ── Recording what went out ────────────────────────────────────────────── + + /// + /// Records an action that just went out. is the UseDone count read + /// BEFORE the send. Logs once when it went out over another unanswered action (a player command, + /// a meta, or a heal let ahead). + /// + public static void Begin(RynthCoreHost host, PacedKind kind, uint id, string label, string who, int seqAtSend, int modeTarget = 0) + { + if (!Enabled || kind == PacedKind.None) return; + PacedAction? prev = Current(host); + long now = NowMs(); + var a = new PacedAction + { + Kind = kind, Id = id, Label = label, Who = who, SentMs = now, SeqAtSend = seqAtSend, ModeTarget = modeTarget, + }; + if (kind == PacedKind.ItemUse) a.WieldedAtSend = IsWieldedByPlayer(host, id); + string? over = null; + lock (Gate) + { + _started++; + if (prev != null) + { + _sentOverOutstanding++; + over = $"[Pace] {who}: {Describe(kind, label)} went out while {Describe(prev.Kind, prev.Label)} ({prev.Who}) was unanswered for {now - prev.SentMs} ms"; + } + _cur = a; + } + if (over != null) Log(host, over); + } + + /// A cast's result (enchantment landed, "You cast ...") is in: the server is in its recoil. + public static void NoteCastResult() + { + lock (Gate) + { + if (_cur is { Kind: PacedKind.Cast }) _cur.ResultSeen = true; + } + } + + // ── The outstanding action ─────────────────────────────────────────────── + + /// + /// The action still waiting for the server's answer, or null. Each call settles answers and + /// time limits first, so it is always current. + /// + public static PacedAction? Current(RynthCoreHost host) + { + if (!Enabled) return null; + PacedAction? a; + lock (Gate) a = _cur; + if (a == null) return null; + + long now = NowMs(); + long age = now - a.SentMs; + string? answeredHow = null; + bool timedOut = false; + + switch (a.Kind) + { + case PacedKind.WorldUse: + case PacedKind.ItemUse: + case PacedKind.Cast: + { + bool hasSeq = false; + int seq = 0; + try { hasSeq = host.HasUseDoneSeq; if (hasSeq) seq = host.GetUseDoneSeq(); } catch { hasSeq = false; } + if (hasSeq && seq != a.SeqAtSend) + { + answeredHow = "UseDone"; + } + else if (a.Kind == PacedKind.ItemUse && IsWieldedByPlayer(host, a.Id) != a.WieldedAtSend) + { + if (a.WieldSeenMs == 0) a.WieldSeenMs = now; + if (now - a.WieldSeenMs >= WieldSettleMs) answeredHow = "wield"; + } + else if (!hasSeq && age >= NoUseDoneFallbackMs) + { + answeredHow = "time (no UseDone on this engine)"; + } + long max = a.Kind switch { PacedKind.WorldUse => WorldUseMaxMs, PacedKind.Cast => CastMaxMs, _ => ItemUseMaxMs }; + if (answeredHow == null && age >= max) timedOut = true; + break; + } + case PacedKind.CombatMode: + { + int mode = -1; + try { if (host.HasGetCurrentCombatMode) mode = host.GetCurrentCombatMode(); } catch { mode = -1; } + if (mode == a.ModeTarget || mode < 0) + { + if (a.ModeSeenMs == 0) a.ModeSeenMs = now; + if (age >= ModeSettleMs) answeredHow = "mode"; + } + if (answeredHow == null && age >= ModeMaxMs) timedOut = true; + break; + } + } + + if (answeredHow == null && !timedOut) return a; + + string? line = null; + lock (Gate) + { + if (!ReferenceEquals(_cur, a)) return _cur; // replaced meanwhile + _cur = null; + if (timedOut) + { + _timedOut++; + _lastTimeout = $"{Describe(a.Kind, a.Label)} ({a.Who}) after {age} ms"; + line = $"[Pace] no answer from the server to {Describe(a.Kind, a.Label)} ({a.Who}) in {age} ms - going on (nothing cleared)"; + } + else + { + _answered++; + } + } + if (line != null) Log(host, line); + return null; + } + + /// True while an action is waiting for the server (out: it). + public static bool Outstanding(RynthCoreHost host, out PacedAction? action) + { + action = Current(host); + return action != null; + } + + // ── Gates ─────────────────────────────────────────────────────────────── + + /// + /// May send a use, a cast or a mode change now? False (with why) while + /// another action waits for the server, except the heal rules in the file header. One log + /// line per outstanding action and subsystem. + /// + public static bool MayStart(RynthCoreHost host, string who, HealNeed heal, out string why) + { + why = ""; + PacedAction? a = Current(host); + if (a == null) return true; + long age = NowMs() - a.SentMs; + + if (heal != HealNeed.None) + { + if (a.Kind == PacedKind.WorldUse + && age >= (heal == HealNeed.Emergency ? EmergencyAfterWorldUseMs : HealAfterWorldUseMs)) + { + lock (Gate) _healsAhead++; + Log(host, $"[Pace] {who}: the heal goes ahead of {Describe(a.Kind, a.Label)} (unanswered for {age} ms)"); + return true; + } + // A stance change (most often the one this heal asked for: the wand swap, or peace for + // a kit): the heal goes once the client has read the new mode for HealAfterModeReadMs, + // like BuffManager's emergency settle, not the full ModeSettleMs. + if (a.Kind == PacedKind.CombatMode && a.ModeSeenMs != 0 && NowMs() - a.ModeSeenMs >= HealAfterModeReadMs) + return true; + if (a.Kind == PacedKind.Cast && a.ResultSeen && !a.HealQueued) + { + a.HealQueued = true; + lock (Gate) _healsAhead++; + return true; + } + } + + why = $"{Describe(a.Kind, a.Label)} sent {age} ms ago by {a.Who} has no answer yet"; + bool log; + lock (Gate) + { + _heldStarts++; + _holdsByWho[who] = _holdsByWho.TryGetValue(who, out int n) ? n + 1 : 1; + if (age > _maxWaitMs) { _maxWaitMs = age; _maxWaitWhat = Describe(a.Kind, a.Label); } + log = a.LoggedWaits.Add(who); + } + if (log) Log(host, $"[Pace] {who} waits: {why}"); + return false; + } + + /// + /// True while the outstanding action is one the server animates (all of them: the walk/turn + /// to a used object, a heal or wield motion, a cast, a stance change). MoveAudit holds + /// RynthAi's movement starts and turns meanwhile. + /// + public static bool HoldsMovement(RynthCoreHost host, out string what) + { + what = ""; + PacedAction? a = Current(host); + if (a == null) return false; + what = $"{Describe(a.Kind, a.Label)} ({a.Who}, {NowMs() - a.SentMs} ms)"; + lock (Gate) _heldMoves++; + return true; + } + + // ── Helpers ───────────────────────────────────────────────────────────── + + internal static string Describe(PacedKind kind, string label) => kind switch + { + PacedKind.WorldUse => $"the use of {label}", + PacedKind.ItemUse => $"the use of {label}", + PacedKind.Cast => $"the cast of {label}", + PacedKind.CombatMode => $"the change to {label} mode", + _ => label, + }; + + internal static string ModeName(int mode) => mode switch + { + 1 => "Peace", 2 => "Melee", 4 => "Missile", 8 => "Magic", _ => $"mode {mode}", + }; + + private static bool IsWieldedByPlayer(RynthCoreHost host, uint id) + { + try + { + if (id == 0 || !host.HasGetObjectWielderInfo || !host.HasGetPlayerId) return false; + uint player = host.GetPlayerId(); + return player != 0 && host.TryGetObjectWielderInfo(id, out uint wielder, out _) && wielder == player; + } + catch { return false; } + } + + /// World object (no container, no wielder) = the server walks to it; else an item of ours. + internal static PacedKind ClassifyUse(RynthCoreHost host, uint id, bool doorOrCorpse) + { + if (doorOrCorpse) return PacedKind.WorldUse; + try + { + if (host.HasGetObjectOwnershipInfo && host.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _)) + return container == 0 && wielder == 0 ? PacedKind.WorldUse : PacedKind.ItemUse; + } + catch { } + return PacedKind.ItemUse; + } + + internal static int UseDoneSeqNow(RynthCoreHost host) + { + try { return host.HasUseDoneSeq ? host.GetUseDoneSeq() : 0; } catch { return 0; } + } + + private static void Log(RynthCoreHost host, string line) + { + try { host.Log(line); } catch { } + } + + /// Lines for /ra pace. + public static string[] DescribeLines(RynthCoreHost host) + { + var lines = new List(); + PacedAction? a = Current(host); + lines.Add($"Action pacing: {(Enabled ? "on" : "off")} (one server action at a time; see ops note 2026-10-06-action-pacing)"); + lines.Add(a == null + ? " Waiting on: nothing" + : $" Waiting on: {Describe(a.Kind, a.Label)} from {a.Who}, sent {NowMs() - a.SentMs} ms ago{(a.ResultSeen ? " (result in, recoil)" : "")}"); + lock (Gate) + { + lines.Add($" Sent {_started}, answered {_answered}, no answer in time {_timedOut}{(_lastTimeout.Length > 0 ? $" (last: {_lastTimeout})" : "")}"); + lines.Add($" Starts held {_heldStarts}, moves held {_heldMoves}, heals let ahead {_healsAhead}, sent over an unanswered one {_sentOverOutstanding}"); + lines.Add($" Mode changes refused while waiting {_modeRefused}, skipped (already in that mode) {_modeSkipped}"); + if (_maxWaitMs > 0) lines.Add($" Longest wait seen: {_maxWaitMs} ms ({_maxWaitWhat})"); + if (_holdsByWho.Count > 0) + { + var parts = new List(); + foreach (var kv in _holdsByWho) parts.Add($"{kv.Key} {kv.Value}"); + lines.Add(" Holds by subsystem: " + string.Join(", ", parts)); + } + } + return lines.ToArray(); + } + + // ── The paced sends that are not uses ──────────────────────────────────── + + /// + /// CastSpell, recorded as the outstanding action. RynthAi's callers check MayStart first; + /// (a player command or meta) is never held, only recorded. + /// + public static bool CastSpellFor(this RynthCoreHost host, uint targetId, int spellId, string who, string label, bool asked = false) + { + int seq = UseDoneSeqNow(host); + bool ok = host.CastSpell(targetId, spellId); + if (ok) Begin(host, PacedKind.Cast, unchecked((uint)spellId), label, who, seq); + return ok; + } + + /// + /// ChangeCombatMode with the pacing rules: nothing is sent when the client already reads that + /// mode (the engine would push a raw 0x53 to the server anyway, and on ACE every mode change + /// cancels the walk/turn of a pending use and fails a cast in progress) unless + /// ; and nothing while another server action is unanswered unless + /// . Returns false only when the pacing held the request back (or the + /// client already reads that mode); otherwise the request was made, as a plain ChangeCombatMode + /// call was before (whose result the callers never read), so their retry timers run as before. + /// + public static bool ChangeCombatModeFor(this RynthCoreHost host, int mode, string who, string why, bool force = false) + { + if (!host.HasChangeCombatMode) return true; // nothing to send or pace (the callers went on before too) + if (Enabled && !force) + { + int current = -1; + try { if (host.HasGetCurrentCombatMode) current = host.GetCurrentCombatMode(); } catch { current = -1; } + if (current == mode) + { + lock (Gate) _modeSkipped++; + return false; + } + PacedAction? a = Current(host); + if (a != null) + { + bool log; + lock (Gate) + { + _modeRefused++; + log = a.LoggedWaits.Add("mode:" + who); + } + if (log) + Log(host, $"[Pace] {who}: change to {ModeName(mode)} mode held ({why}): {Describe(a.Kind, a.Label)} sent {NowMs() - a.SentMs} ms ago by {a.Who} has no answer yet (a mode change now would cancel it on the server)"); + return false; + } + } + int seq = UseDoneSeqNow(host); + if (host.ChangeCombatMode(mode)) + Begin(host, PacedKind.CombatMode, 0, ModeName(mode), who, seq, mode); + return true; + } +} diff --git a/Plugins/Shared/MoveAudit.cs b/Plugins/Shared/MoveAudit.cs index 2afbc4b..b5d30a1 100644 --- a/Plugins/Shared/MoveAudit.cs +++ b/Plugins/Shared/MoveAudit.cs @@ -50,37 +50,142 @@ internal static class MoveAudit public static bool SetAutoRunBy(this RynthCoreHost host, string who, bool on) { + if (on && HeldForUse(host, who, "SetAutoRun(True)")) return false; + if (HeldForAction(host, who, on ? "SetAutoRun(True)" : "SetAutoRun(False)", isStop: !on)) return false; Note(host, who, "SetAutoRun", on ? "True" : "False", collapseByKindOnly: false); + lock (Gate) { _autoRunOn = on; if (on) _lastStartMs = NowMs(); } return host.SetAutoRun(on); } public static bool StopCompletelyBy(this RynthCoreHost host, string who) { + if (HeldForAction(host, who, "StopCompletely()", isStop: true)) return false; Note(host, who, "StopCompletely", "", collapseByKindOnly: false); + lock (Gate) { _autoRunOn = false; _motionsOn.Clear(); } return host.StopCompletely(); } public static bool SetMotionBy(this RynthCoreHost host, string who, uint motion, bool on) { + if (on && HeldForUse(host, who, $"SetMotion(0x{motion:X8}, True)")) return false; + if (HeldForAction(host, who, $"SetMotion(0x{motion:X8}, {(on ? "True" : "False")})", isStop: !on, motion)) return false; Note(host, who, "SetMotion", $"0x{motion:X8}, {(on ? "True" : "False")}", collapseByKindOnly: false); + lock (Gate) { if (on) { _motionsOn.Add(motion); _lastStartMs = NowMs(); } else _motionsOn.Remove(motion); } return host.SetMotion(motion, on); } public static bool DoMovementBy(this RynthCoreHost host, string who, uint motion, float speed, int holdKey) { + if (HeldForUse(host, who, $"DoMovement(0x{motion:X8})")) return false; + if (HeldForAction(host, who, $"DoMovement(0x{motion:X8})", isStop: false)) return false; Note(host, who, "DoMovement", $"0x{motion:X8}, {speed:0.##}, {holdKey}", collapseByKindOnly: false); + lock (Gate) { _motionsOn.Add(motion); _lastStartMs = NowMs(); } return host.DoMovement(motion, speed, holdKey); } + // -- Hold while any paced server action is unanswered (2026-10-06, ActionPacer) ---------- + // A use, cast or stance change the server is still animating is what a movement packet + // disturbs: on ACE every client MoveToState is applied to the server's physics, a mode change + // or a stop cancels the walk/turn to a used object, and a cast's end waits for its gesture. + // While ActionPacer has one outstanding: + // * starting to move or turning is held (returns false, one log line per action and caller); + // * a stop goes through only when RynthAi itself has the character moving (autorun, or the + // motion it turned on); a stop with nothing of ours moving would only send a redundant + // movement packet in the middle of the action, so it is held as well; + // * the deliberate kick for a held cast (Buff/Nudge), a macro stop and typed commands pass. + // Off unless ActionPacer.Enabled (RynthAi only). + + private static bool _autoRunOn; + private static long _lastStartMs = long.MinValue / 2; + /// Our "moving" state counts only this long after the last start we sent: nav re-sends + /// autorun every second while it drives, and AC can stop on its own (arrival, a portal) without + /// RynthAi sending a stop, so an old "on" must not hold casts back forever. + internal const long OwnMovementFreshMs = 3000; + private static readonly System.Collections.Generic.HashSet _motionsOn = new(); + private static readonly System.Collections.Generic.HashSet _actionHoldLogged = new(); + private static long _actionHoldLoggedFor = long.MinValue; + + /// Callers whose movement is never held: the cast nudge, a macro stop, typed commands. + internal static bool IsExemptFromActionHold(string who) => + who == "Buff/Nudge" || who == "MacroStop" || who == "Command"; + + /// True when RynthAi itself has the character moving (autorun or a motion it turned on). + internal static bool OwnMovementActive + { + get { lock (Gate) return (_autoRunOn || _motionsOn.Count > 0) && NowMs() - _lastStartMs < OwnMovementFreshMs; } + } + + /// True when the call must wait for an unanswered paced action (internal for the tests). + internal static bool HeldForAction(RynthCoreHost host, string who, string call, bool isStop, uint motion = 0) + { + if (!ActionPacer.Enabled || IsExemptFromActionHold(who)) return false; + if (isStop) + { + bool moving; + lock (Gate) moving = (motion != 0 ? _motionsOn.Contains(motion) : (_autoRunOn || _motionsOn.Count > 0)) + && NowMs() - _lastStartMs < OwnMovementFreshMs; + if (moving) return false; // a real stop always goes through + } + var pending = ActionPacer.Current(host); + if (pending == null) return false; + if (!ActionPacer.HoldsMovement(host, out string what)) return false; + bool log; + lock (Gate) + { + if (_actionHoldLoggedFor != pending.SentMs) { _actionHoldLoggedFor = pending.SentMs; _actionHoldLogged.Clear(); } + log = Enabled && _actionHoldLogged.Add(who + (isStop ? "|stop" : "|move")); + } + if (log) + { + string kind = isStop ? "redundant stop, nothing of ours is moving" : "move/turn"; + try { host.Log($"[Move] {PluginName}/{who} {call} held ({kind}): the server is still answering {what}"); } + catch { } + } + return true; + } + + // ── Hold while a door/corpse use is in flight (2026-10-06) ───────────────────── + // A move or a turn sent while the server is still walking/turning the character to a used + // door or corpse cancels that use (ACE stops its move-to chain on a client MoveToState). + // UseAudit knows when one is in flight (opt-in, UseAudit.TrackWorldUses); until the server + // answers (UseDone) or UseAudit.WorldUseInFlightMaxMs passes, starting to move or turning + // is skipped and the call returns false. Stops always go through. One line per held use. + + private static uint _heldLoggedFor; + private static long _heldLoggedAt; + + /// True when the call must wait for an in-flight door/corpse use (internal for the tests). + internal static bool HeldForUse(RynthCoreHost host, string who, string call) + { + if (!UseAudit.WorldUseInFlight(host, out uint objectId)) return false; + bool log; + lock (Gate) + { + long now = NowMs(); + log = Enabled && (objectId != _heldLoggedFor || now - _heldLoggedAt > UseAudit.WorldUseInFlightMaxMs); + if (log) { _heldLoggedFor = objectId; _heldLoggedAt = now; } + } + if (log) + { + try { host.Log($"[Move] {PluginName}/{who} {call} held: the server is still answering the use of 0x{objectId:X8} (moving now would cancel it)"); } + catch { } + } + return true; + } + public static bool StopMovementBy(this RynthCoreHost host, string who, uint motion, int holdKey) { + if (HeldForAction(host, who, $"StopMovement(0x{motion:X8})", isStop: true, motion)) return false; Note(host, who, "StopMovement", $"0x{motion:X8}, {holdKey}", collapseByKindOnly: false); + lock (Gate) _motionsOn.Remove(motion); return host.StopMovement(motion, holdKey); } /// A heading snap. Successive turns from one subsystem collapse whatever the angle. public static bool TurnToHeadingBy(this RynthCoreHost host, string who, float headingDegrees) { + if (HeldForUse(host, who, "TurnToHeading")) return false; + if (HeldForAction(host, who, "TurnToHeading", isStop: false)) return false; Note(host, who, "TurnToHeading", headingDegrees.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture), collapseByKindOnly: true); return host.TurnToHeading(headingDegrees); } @@ -131,6 +236,13 @@ internal static class MoveAudit _lastWrittenMs = long.MinValue; _repeats = 0; _repeatLastArg = ""; + _heldLoggedFor = 0; + _heldLoggedAt = 0; + _autoRunOn = false; + _motionsOn.Clear(); + _lastStartMs = long.MinValue / 2; + _actionHoldLogged.Clear(); + _actionHoldLoggedFor = long.MinValue; } } } diff --git a/Plugins/Shared/Nav3DText.cs b/Plugins/Shared/Nav3DText.cs new file mode 100644 index 0000000..d2a6e6d --- /dev/null +++ b/Plugins/Shared/Nav3DText.cs @@ -0,0 +1,175 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/Nav3DText.cs +// Text in the world on the engine's Nav3D buffer: a small stroke font drawn as +// filled strokes (Nav3D triangles) on an upright plane turned toward the +// character. RynthAi's waypoint labels (NavOverlay) and RynthNav's path +// markers both draw with it. Compiled into each plugin (linked source); no +// host calls, so the offline tests compile it too. +// +// Frame: the Nav3D one (X = east metres, Y = height, Z = north metres, in the +// player's landblock). Call only from the plugin tick (the Nav3D submit side). +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.Shared; + +/// Where Nav3D geometry goes: the engine's buffer in the game, a recorder in the tests. +internal interface INav3DSink +{ + void Line(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb); + void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint colorArgb); +} + +/// +/// One line of text over a point in the world, as filled strokes facing the viewer, sized up with +/// distance so far text stays readable. Rows stack upward from just above the point. +/// +internal static class Nav3DText +{ + /// Row 0's baseline above the point (m). + public const float LabelLift = 1.1f; + public const float MinLineHeight = 0.30f, MaxLineHeight = 1.5f, HeightPerMetre = 0.015f; + + /// The line height (m) for text this far from the viewer. + public static float LineHeight(float distance) => + Math.Clamp(MinLineHeight + HeightPerMetre * distance, MinLineHeight, MaxLineHeight); + + /// + /// Emits over (x, y, z), row , facing the viewer at + /// (viewX, viewZ). Counts triangles in ; returns false (having drawn what + /// fitted) when the next stroke would go past . + /// + public static bool Emit(float x, float y, float z, string text, int row, uint color, + float viewX, float viewZ, INav3DSink sink, ref int tris, int maxTris) + { + float dx = x - viewX, dz = z - viewZ; + float d = MathF.Sqrt(dx * dx + dz * dz); + // Text faces the viewer: its right-hand direction is the view direction turned 90° clockwise. + float fx = 0f, fz = 1f; + if (d > 0.01f) { fx = dx / d; fz = dz / d; } + float rx = fz, rz = -fx; + + float h = LineHeight(d); + float s = h / NavStrokeFont.Height; + float width = NavStrokeFont.Width(text) * s; + float u0 = -width * 0.5f; + float v0 = y + LabelLift + row * h * 1.5f; + float half = NavStrokeFont.Stroke * 0.5f * s; + + for (int c = 0; c < text.Length; c++) + { + float[][]? strokes = NavStrokeFont.Glyph(text[c]); + if (strokes == null) continue; + float cu = u0 + c * NavStrokeFont.Advance * s; + foreach (float[] poly in strokes) + { + for (int k = 0; k + 3 < poly.Length; k += 2) + { + if (tris + 2 > maxTris) return false; + float au = cu + poly[k] * s, av = v0 + poly[k + 1] * s; + float bu = cu + poly[k + 2] * s, bv = v0 + poly[k + 3] * s; + Quad(sink, x, z, color, rx, rz, au, av, bu, bv, half); + tris += 2; + } + } + } + return true; + } + + // A stroke a→b in the text plane (u along the text, v up) as two triangles, its ends pushed + // out half a stroke so corners close. + private static void Quad(INav3DSink sink, float x, float z, uint color, float rx, float rz, + float au, float av, float bu, float bv, float half) + { + float eu = bu - au, ev = bv - av; + float len = MathF.Sqrt(eu * eu + ev * ev); + if (len < 1e-5f) { eu = 0f; ev = 1f; } + else { eu /= len; ev /= len; } + au -= eu * half; av -= ev * half; + bu += eu * half; bv += ev * half; + float nu = -ev * half, nv = eu * half; + + // (u, v) → world: u runs along the right-hand direction, v is height. + float a1x = x + rx * (au + nu), a1z = z + rz * (au + nu), a1y = av + nv; + float a2x = x + rx * (au - nu), a2z = z + rz * (au - nu), a2y = av - nv; + float b1x = x + rx * (bu + nu), b1z = z + rz * (bu + nu), b1y = bv + nv; + float b2x = x + rx * (bu - nu), b2z = z + rz * (bu - nu), b2y = bv - nv; + sink.Triangle(a1x, a1y, a1z, a2x, a2y, a2z, b1x, b1y, b1z, color); + sink.Triangle(a2x, a2y, a2z, b2x, b2y, b2z, b1x, b1y, b1z, color); + } +} + +/// +/// A small stroke font for labels in the world: digits, A-Z and a few marks, each a set of +/// polylines on a 4 x 6 grid (y up). Lower case draws as upper case; anything else is a gap. +/// +internal static class NavStrokeFont +{ + public const float Height = 6f, Advance = 5.5f, Stroke = 0.75f; + + /// The text's drawn width in grid units. + public static float Width(string text) => text.Length == 0 ? 0f : text.Length * Advance - (Advance - 4f); + + public static float[][]? Glyph(char c) + { + c = char.ToUpperInvariant(c); + return Glyphs.TryGetValue(c, out float[][]? g) ? g : null; + } + + private static float[] P(params float[] xy) => xy; + + private static readonly Dictionary Glyphs = new() + { + ['0'] = new[] { P(0, 0, 4, 0, 4, 6, 0, 6, 0, 0), P(0, 0, 4, 6) }, + ['1'] = new[] { P(1, 5, 2, 6, 2, 0), P(1, 0, 3, 0) }, + ['2'] = new[] { P(0, 6, 4, 6, 4, 3, 0, 3, 0, 0, 4, 0) }, + ['3'] = new[] { P(0, 6, 4, 6, 4, 0, 0, 0), P(1, 3, 4, 3) }, + ['4'] = new[] { P(0, 6, 0, 3, 4, 3), P(4, 6, 4, 0) }, + ['5'] = new[] { P(4, 6, 0, 6, 0, 4, 3, 4, 4, 3, 4, 1, 3, 0, 0, 0) }, + ['6'] = new[] { P(4, 6, 0, 6, 0, 0, 4, 0, 4, 3, 0, 3) }, + ['7'] = new[] { P(0, 6, 4, 6, 1, 0) }, + ['8'] = new[] { P(0, 0, 4, 0, 4, 6, 0, 6, 0, 0), P(0, 3, 4, 3) }, + ['9'] = new[] { P(4, 3, 0, 3, 0, 6, 4, 6, 4, 0, 0, 0) }, + ['A'] = new[] { P(0, 0, 0, 4, 2, 6, 4, 4, 4, 0), P(0, 3, 4, 3) }, + ['B'] = new[] { P(0, 0, 0, 6, 3, 6, 4, 5, 4, 4, 3, 3, 0, 3), P(3, 3, 4, 2, 4, 1, 3, 0, 0, 0) }, + ['C'] = new[] { P(4, 6, 0, 6, 0, 0, 4, 0) }, + ['D'] = new[] { P(0, 0, 0, 6, 2, 6, 4, 4, 4, 2, 2, 0, 0, 0) }, + ['E'] = new[] { P(4, 6, 0, 6, 0, 0, 4, 0), P(0, 3, 3, 3) }, + ['F'] = new[] { P(4, 6, 0, 6, 0, 0), P(0, 3, 3, 3) }, + ['G'] = new[] { P(4, 6, 0, 6, 0, 0, 4, 0, 4, 3, 2, 3) }, + ['H'] = new[] { P(0, 0, 0, 6), P(4, 0, 4, 6), P(0, 3, 4, 3) }, + ['I'] = new[] { P(1, 6, 3, 6), P(2, 6, 2, 0), P(1, 0, 3, 0) }, + ['J'] = new[] { P(4, 6, 4, 0, 0, 0, 0, 2) }, + ['K'] = new[] { P(0, 0, 0, 6), P(4, 6, 0, 3, 4, 0) }, + ['L'] = new[] { P(0, 6, 0, 0, 4, 0) }, + ['M'] = new[] { P(0, 0, 0, 6, 2, 3, 4, 6, 4, 0) }, + ['N'] = new[] { P(0, 0, 0, 6, 4, 0, 4, 6) }, + ['O'] = new[] { P(0, 0, 4, 0, 4, 6, 0, 6, 0, 0) }, + ['P'] = new[] { P(0, 0, 0, 6, 4, 6, 4, 3, 0, 3) }, + ['Q'] = new[] { P(0, 0, 4, 0, 4, 6, 0, 6, 0, 0), P(2, 2, 4, -1) }, + ['R'] = new[] { P(0, 0, 0, 6, 4, 6, 4, 3, 0, 3, 4, 0) }, + ['S'] = new[] { P(4, 6, 0, 6, 0, 3, 4, 3, 4, 0, 0, 0) }, + ['T'] = new[] { P(0, 6, 4, 6), P(2, 6, 2, 0) }, + ['U'] = new[] { P(0, 6, 0, 0, 4, 0, 4, 6) }, + ['V'] = new[] { P(0, 6, 2, 0, 4, 6) }, + ['W'] = new[] { P(0, 6, 1, 0, 2, 3, 3, 0, 4, 6) }, + ['X'] = new[] { P(0, 0, 4, 6), P(0, 6, 4, 0) }, + ['Y'] = new[] { P(0, 6, 2, 3, 4, 6), P(2, 3, 2, 0) }, + ['Z'] = new[] { P(0, 6, 4, 6, 0, 0, 4, 0) }, + ['-'] = new[] { P(1, 3, 3, 3) }, + ['+'] = new[] { P(1, 3, 3, 3), P(2, 2, 2, 4) }, + ['.'] = new[] { P(2, 0, 2, 0.4f) }, + [','] = new[] { P(2, 0.6f, 1.5f, -0.6f) }, + [':'] = new[] { P(2, 1, 2, 1.4f), P(2, 4, 2, 4.4f) }, + ['\''] = new[] { P(2, 6, 2, 4.6f) }, + ['/'] = new[] { P(0, 0, 4, 6) }, + ['#'] = new[] { P(1, 0, 1, 6), P(3, 0, 3, 6), P(0, 2, 4, 2), P(0, 4, 4, 4) }, + ['('] = new[] { P(3, 6, 2, 5, 2, 1, 3, 0) }, + [')'] = new[] { P(1, 6, 2, 5, 2, 1, 1, 0) }, + ['?'] = new[] { P(0, 5, 1, 6, 3, 6, 4, 5, 4, 4, 2, 3, 2, 2), P(2, 0, 2, 0.4f) }, + ['!'] = new[] { P(2, 6, 2, 2), P(2, 0, 2, 0.4f) }, + ['_'] = new[] { P(0, 0, 4, 0) }, + }; +} diff --git a/Plugins/Shared/RynthInstallPaths.cs b/Plugins/Shared/RynthInstallPaths.cs new file mode 100644 index 0000000..a28011d --- /dev/null +++ b/Plugins/Shared/RynthInstallPaths.cs @@ -0,0 +1,186 @@ +// ============================================================================ +// RynthInstallPaths.cs - where RynthCore and RynthSuite are installed. +// +// ONE FILE, TWO COPIES: RynthCore src\Shared\RynthInstallPaths.cs (engine, +// launcher, injector, loader, StatusAgent) and RynthSuite +// Plugins\Shared\RynthInstallPaths.cs (plugins, Loot Editor). Keep them +// byte-identical; RynthSuite's RynthAi host tests compare the two when the +// RynthCore sibling is checked out. +// +// READ ONLY. This only answers "which folder"; it never writes or deletes a +// setting, and nothing here may be used to pick a DLL or EXE to load or run. +// +// Order, per folder (first usable answer wins): +// 1. environment variable RYNTHCORE_DIR / RYNTHSUITE_DIR (dev setups) +// 2. HKCU\Software\Rynth CoreDir / SuiteDir (per-user install) +// 3. HKLM\Software\Rynth CoreDir / SuiteDir, 32-bit view (all-users install) +// 4. C:\Games\RynthCore / C:\Games\RynthSuite (today's layout) +// A value counts only if it is an absolute path; anything else is skipped. +// With nothing set the result is exactly the old hard-coded folder. +// +// Idea from Silentkelpie (rynth PR #1); re-implemented here. +// ============================================================================ + +using System; +using System.IO; +using System.Runtime.InteropServices; + +namespace RynthCore.Install; + +/// Where reads settings from. Tests pass a fake. +internal interface IInstallSettingSource +{ + /// The process environment variable, or null. + string? EnvironmentVariable(string name); + + /// A string value under HKCU\Software\Rynth, or null. + string? CurrentUser(string valueName); + + /// A string value under HKLM\Software\Rynth (32-bit registry view), or null. + string? LocalMachine(string valueName); +} + +internal static class RynthInstallPaths +{ + /// RynthCore folder when nothing is set (launcher, Runtime\, Logs\, NavData\, AcClient\). + public const string DefaultCoreDir = @"C:\Games\RynthCore"; + + /// RynthSuite folder when nothing is set (plugins and their data, e.g. RynthAi\). + public const string DefaultSuiteDir = @"C:\Games\RynthSuite"; + + public const string CoreEnvironmentVariable = "RYNTHCORE_DIR"; + public const string SuiteEnvironmentVariable = "RYNTHSUITE_DIR"; + + /// Key under HKCU / HKLM. + public const string RegistryKey = @"Software\Rynth"; + public const string CoreValueName = "CoreDir"; + public const string SuiteValueName = "SuiteDir"; + + private static string? _coreDir; + private static string? _suiteDir; + + /// The RynthCore install folder. Resolved once per process. + public static string CoreDir => + _coreDir ??= Resolve(CoreEnvironmentVariable, CoreValueName, DefaultCoreDir, SystemInstallSettings.Instance); + + /// The RynthSuite install folder. Resolved once per process. + public static string SuiteDir => + _suiteDir ??= Resolve(SuiteEnvironmentVariable, SuiteValueName, DefaultSuiteDir, SystemInstallSettings.Instance); + + /// <CoreDir>\Logs - the unified log folder. + public static string CoreLogsDir => Path.Combine(CoreDir, "Logs"); + + /// <SuiteDir>\RynthAi - RynthAi's home and data root. + public static string RynthAiDir => Path.Combine(SuiteDir, "RynthAi"); + + /// + /// The first usable folder from : environment, then HKCU, + /// then HKLM, else exactly as given. Never throws. + /// + internal static string Resolve(string environmentVariable, string valueName, string fallback, IInstallSettingSource source) + { + string? found = Normalize(Ask(() => source.EnvironmentVariable(environmentVariable))) + ?? Normalize(Ask(() => source.CurrentUser(valueName))) + ?? Normalize(Ask(() => source.LocalMachine(valueName))); + return found ?? fallback; + } + + private static readonly char[] BadNameChars = { '*', '?', '<', '>', '"', '|' }; + + private static string? Ask(Func read) + { + try { return read(); } + catch { return null; } + } + + /// + /// An absolute folder path, tidied (whitespace and surrounding quotes trimmed, + /// trailing separators dropped except on a drive root); null when the value is + /// empty, relative or not a valid path. + /// + internal static string? Normalize(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return null; + string path = value.Trim().Trim('"').Trim(); + if (path.Length == 0) return null; + // .NET accepts some names Windows folders can't have; refuse them here. + if (path.IndexOfAny(Path.GetInvalidPathChars()) >= 0 || path.IndexOfAny(BadNameChars) >= 0) return null; + if (path.Length > 2 && path.IndexOf(':', 2) >= 0) return null; // a colon only after the drive letter + try + { + if (!Path.IsPathFullyQualified(path)) return null; + string full = Path.GetFullPath(path); + string root = Path.GetPathRoot(full) ?? string.Empty; + string trimmed = full.TrimEnd('\\', '/'); + return trimmed.Length < root.Length ? root : trimmed; + } + catch + { + return null; + } + } +} + +/// The real environment and registry (read only, advapi32 directly: NativeAOT and trim safe). +internal sealed class SystemInstallSettings : IInstallSettingSource +{ + public static readonly SystemInstallSettings Instance = new(); + + private SystemInstallSettings() { } + + public string? EnvironmentVariable(string name) => Environment.GetEnvironmentVariable(name); + + public string? CurrentUser(string valueName) => ReadString(HKEY_CURRENT_USER, valueName, 0); + + public string? LocalMachine(string valueName) => ReadString(HKEY_LOCAL_MACHINE, valueName, RRF_SUBKEY_WOW6432KEY); + + private static readonly IntPtr HKEY_CURRENT_USER = new(unchecked((int)0x80000001)); + private static readonly IntPtr HKEY_LOCAL_MACHINE = new(unchecked((int)0x80000002)); + private const uint RRF_RT_REG_SZ = 0x00000002; + private const uint RRF_RT_REG_EXPAND_SZ = 0x00000004; + private const uint RRF_SUBKEY_WOW6432KEY = 0x00020000; + private const int ERROR_SUCCESS = 0; + private const int MaxValueBytes = 64 * 1024; + + // Every argument is a pointer or an integer, so no marshalling stub is needed. + [DllImport("advapi32.dll", ExactSpelling = true)] + private static extern int RegGetValueW(IntPtr hkey, IntPtr subKey, IntPtr valueName, uint flags, + IntPtr type, IntPtr data, IntPtr dataBytes); + + private static string? ReadString(IntPtr root, string valueName, uint viewFlag) + { + IntPtr subKey = IntPtr.Zero, name = IntPtr.Zero, size = IntPtr.Zero, data = IntPtr.Zero; + try + { + subKey = Marshal.StringToHGlobalUni(RynthInstallPaths.RegistryKey); + name = Marshal.StringToHGlobalUni(valueName); + size = Marshal.AllocHGlobal(sizeof(uint)); + uint flags = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | viewFlag; + + Marshal.WriteInt32(size, 0); + if (RegGetValueW(root, subKey, name, flags, IntPtr.Zero, IntPtr.Zero, size) != ERROR_SUCCESS) + return null; + int bytes = Marshal.ReadInt32(size); + if (bytes < 2 || bytes > MaxValueBytes) return null; + + data = Marshal.AllocHGlobal(bytes + 2); + Marshal.WriteInt32(size, bytes); + if (RegGetValueW(root, subKey, name, flags, IntPtr.Zero, data, size) != ERROR_SUCCESS) + return null; + int written = Math.Min(Marshal.ReadInt32(size), bytes); + Marshal.WriteInt16(data, written - (written % 2), 0); // terminate even if the value wasn't + return Marshal.PtrToStringUni(data); + } + catch + { + return null; // no advapi32, access denied, ... -> the next source / the default + } + finally + { + if (data != IntPtr.Zero) Marshal.FreeHGlobal(data); + if (size != IntPtr.Zero) Marshal.FreeHGlobal(size); + if (name != IntPtr.Zero) Marshal.FreeHGlobal(name); + if (subKey != IntPtr.Zero) Marshal.FreeHGlobal(subKey); + } + } +} diff --git a/Plugins/Shared/UseAudit.cs b/Plugins/Shared/UseAudit.cs index c6a8441..605bbd4 100644 --- a/Plugins/Shared/UseAudit.cs +++ b/Plugins/Shared/UseAudit.cs @@ -80,6 +80,10 @@ internal static class UseAudit _windowStart = long.MinValue; _windowLines = 0; _windowDropped = 0; + _worldUseId = 0; + _worldUseSentMs = 0; + _worldUseSeqAtSend = 0; + AfterSend = null; } } @@ -93,7 +97,95 @@ internal static class UseAudit return false; } Write(host, objectId, subsystem, $"0x{objectId:X8} {what} macro={MacroText} {KindText(kind)} - {why}", force: false); - return host.UseObject(objectId); + int seqBefore = 0; + bool track = TrackWorldUses && doorOrCorpse; + var after = AfterSend; + if (track || after != null) + { + try { seqBefore = host.HasUseDoneSeq ? host.GetUseDoneSeq() : 0; } catch { } + } + bool sent = host.UseObject(objectId); + if (track && sent) + MarkWorldUse(objectId, seqBefore); + if (sent && after != null) + { + try { after(host, new SentUse(objectId, 0, subsystem, what, doorOrCorpse, seqBefore, kind)); } catch { } + } + return sent; + } + + /// What went out (for ). + internal readonly record struct SentUse(uint ObjectId, uint TargetId, string Subsystem, string What, + bool DoorOrCorpse, int UseDoneSeqBefore, UseKind Kind); + + /// + /// Called after every use / use-on this plugin sent (RynthAi records it as the server action it + /// waits on, Plugins/Shared/ActionPacer.cs). Null in plugins that don't pace. Cleared by Reset. + /// + public static Action? AfterSend; + + // ── A door or corpse use the server hasn't answered yet (2026-10-06) ────────── + // The server walks/turns the character to a used door or corpse, and any movement packet + // from the client cancels that (ACE: a MoveToState stops the move-to chain, and a combat + // mode change cancels the move-to too). MoveAudit holds the plugin's own movement while + // one is in flight. Opt-in per plugin (TrackWorldUses); off = nothing changes. + + /// Opt-in: remember door/corpse uses so MoveAudit can hold movement until the server answers. + public static volatile bool TrackWorldUses; + + /// Longest a use counts as in flight when the server doesn't answer (a long walk to it). + public const long WorldUseInFlightMaxMs = 1500; + + private static uint _worldUseId; + private static long _worldUseSentMs; + private static int _worldUseSeqAtSend; + + /// Records a door/corpse use that went out (internal for the tests). + internal static void MarkWorldUse(uint objectId, int useDoneSeqBefore) + { + lock (Gate) + { + _worldUseId = objectId; + _worldUseSentMs = NowMs(); + _worldUseSeqAtSend = useDoneSeqBefore; + } + } + + /// + /// True while the last door/corpse use is waiting for the server: sent less than + /// WorldUseInFlightMaxMs ago and no UseDone has arrived since (when the engine counts them; + /// without the count, the time alone). Always false unless TrackWorldUses. + /// + public static bool WorldUseInFlight(RynthCoreHost host, out uint objectId) + { + objectId = 0; + if (!TrackWorldUses) return false; + long sentMs; int seqAtSend; uint id; + lock (Gate) + { + sentMs = _worldUseSentMs; + seqAtSend = _worldUseSeqAtSend; + id = _worldUseId; + } + if (sentMs == 0 || NowMs() - sentMs >= WorldUseInFlightMaxMs) return false; + try + { + if (host.HasUseDoneSeq && host.GetUseDoneSeq() != seqAtSend) return false; + } + catch { } + objectId = id; + return true; + } + + /// Forget the in-flight use (Reset, tests). + internal static void ClearWorldUse() + { + lock (Gate) + { + _worldUseId = 0; + _worldUseSentMs = 0; + _worldUseSeqAtSend = 0; + } } /// UseObjectOn (item on a target) with a log line and the same guard on the target. @@ -107,7 +199,18 @@ internal static class UseAudit return false; } Write(host, targetId, subsystem, $"0x{sourceId:X8} {src} on 0x{targetId:X8} {tgt} macro={MacroText} {KindText(kind)} - {why}", force: false); - return host.UseObjectOn(sourceId, targetId); + var after = AfterSend; + int seqBefore = 0; + if (after != null) + { + try { seqBefore = host.HasUseDoneSeq ? host.GetUseDoneSeq() : 0; } catch { } + } + bool sent = host.UseObjectOn(sourceId, targetId); + if (sent && after != null) + { + try { after(host, new SentUse(sourceId, targetId, subsystem, $"{src} on {tgt}", doorOrCorpse, seqBefore, kind)); } catch { } + } + return sent; } private static string MacroText => MacroRunning switch { true => "on", false => "off", null => "n/a" }; diff --git a/Tools/RynthCore.LootEditor/MainViewModel.cs b/Tools/RynthCore.LootEditor/MainViewModel.cs index 843b2ca..8a77adf 100644 --- a/Tools/RynthCore.LootEditor/MainViewModel.cs +++ b/Tools/RynthCore.LootEditor/MainViewModel.cs @@ -14,10 +14,10 @@ namespace RynthCore.LootEditor; public class MainViewModel : INotifyPropertyChanged { - private const string DefaultFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles"; + private static readonly string DefaultFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles"); // RynthAi's AutoVendor reads .utl / default.utl from here (and from // AutoVendor folders per server and per character, which IsAutoVendorPath also covers). - private const string AutoVendorFolder = @"C:\Games\RynthSuite\RynthAi\AutoVendor"; + private static readonly string AutoVendorFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "AutoVendor"); public event PropertyChangedEventHandler? PropertyChanged; private void Set(ref T field, T value, [CallerMemberName] string? name = null) diff --git a/Tools/RynthCore.LootEditor/RynthCore.LootEditor.csproj b/Tools/RynthCore.LootEditor/RynthCore.LootEditor.csproj index f6a0262..c789be5 100644 --- a/Tools/RynthCore.LootEditor/RynthCore.LootEditor.csproj +++ b/Tools/RynthCore.LootEditor/RynthCore.LootEditor.csproj @@ -22,4 +22,9 @@ + + + + + diff --git a/Tools/RynthCore.MonsterEditor/JsonContext.cs b/Tools/RynthCore.MonsterEditor/JsonContext.cs index 2aed3a6..9e58e2a 100644 --- a/Tools/RynthCore.MonsterEditor/JsonContext.cs +++ b/Tools/RynthCore.MonsterEditor/JsonContext.cs @@ -5,5 +5,6 @@ namespace RynthCore.MonsterEditor; [JsonSerializable(typeof(List))] [JsonSerializable(typeof(EditorSettings))] -[JsonSourceGenerationOptions(WriteIndented = true, IncludeFields = true)] +// Case-insensitive like the plugin's RynthAiJsonContext, which reads the same files. +[JsonSourceGenerationOptions(WriteIndented = true, IncludeFields = true, PropertyNameCaseInsensitive = true)] internal partial class EditorJsonContext : JsonSerializerContext { } diff --git a/Tools/RynthCore.MonsterEditor/MainWindow.axaml b/Tools/RynthCore.MonsterEditor/MainWindow.axaml index 5e49875..79b88a8 100644 --- a/Tools/RynthCore.MonsterEditor/MainWindow.axaml +++ b/Tools/RynthCore.MonsterEditor/MainWindow.axaml @@ -3,7 +3,7 @@ xmlns:local="clr-namespace:RynthCore.MonsterEditor" x:Class="RynthCore.MonsterEditor.MainWindow" Title="RynthAi — Monster Rules Editor" - Width="1060" Height="520" MinWidth="800" MinHeight="300"> + Width="1300" Height="520" MinWidth="800" MinHeight="300"> @@ -138,6 +138,28 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/Tools/RynthCore.MonsterEditor/MainWindow.axaml.cs b/Tools/RynthCore.MonsterEditor/MainWindow.axaml.cs index 7e53071..c7b6c49 100644 --- a/Tools/RynthCore.MonsterEditor/MainWindow.axaml.cs +++ b/Tools/RynthCore.MonsterEditor/MainWindow.axaml.cs @@ -33,6 +33,8 @@ public partial class MainWindow : Window private string _charFolder = string.Empty; private string _monstersPath = string.Empty; private bool _initialized; + // Set when the monsters file couldn't be read: saving would replace it with what's on screen. + private bool _loadFailed; public MainWindow() { @@ -51,7 +53,7 @@ public partial class MainWindow : Window string[] args = Environment.GetCommandLineArgs(); if (args.Length > 1) - OpenCharFolder(args[1].Trim('"')); + Open(args[1].Trim('"')); else await PromptOpenFileAsync(); } @@ -65,11 +67,11 @@ public partial class MainWindow : Window var pick = await sp.OpenFilePickerAsync(new FilePickerOpenOptions { - Title = "Open monsters.json", + Title = "Open a monster rules file (RynthAi > MonsterProfiles > character.json)", AllowMultiple = false, FileTypeFilter = new[] { - new FilePickerFileType("Monster Rules") { Patterns = new[] { "monsters.json" } }, + new FilePickerFileType("Monster Rules") { Patterns = new[] { "*.json" } }, new FilePickerFileType("All Files") { Patterns = new[] { "*" } }, } }); @@ -83,14 +85,21 @@ public partial class MainWindow : Window string? path = file.TryGetLocalPath(); if (!string.IsNullOrEmpty(path)) - OpenCharFolder(Path.GetDirectoryName(path)!); + Open(path); } - private void OpenCharFolder(string charFolder) + /// Opens a monsters file, or a character's settings folder (what the plugin passes): + /// the folder maps to the file the plugin reads, MonsterProfiles\(server)\(character).json + /// (MonsterRulesFile.ResolveRulesPath). Before 2026-10-05 the editor always used + /// monsters.json in that folder, which the plugin now moves to MonsterProfiles at load, so the + /// editor opened empty and its saves were never read once the plugin's own file existed. + private void Open(string pathOrFolder) { - _charFolder = charFolder; - _monstersPath = Path.Combine(charFolder, "monsters.json"); - Title = $"RynthAi — Monster Rules — {Path.GetFileName(charFolder)}"; + _monstersPath = MonsterRulesFile.ResolveRulesPath(pathOrFolder); + _charFolder = Directory.Exists(pathOrFolder) ? pathOrFolder : MonsterRulesFile.CharFolderForRulesPath(_monstersPath); + string who = Path.GetFileNameWithoutExtension(_monstersPath); + if (who.Equals("monsters", StringComparison.OrdinalIgnoreCase)) who = Path.GetFileName(_charFolder); + Title = $"RynthAi — Monster Rules — {who}"; LoadWeaponOptions(); LoadRules(); @@ -128,17 +137,17 @@ public partial class MainWindow : Window { foreach (var r in Rules) r.PropertyChanged -= Rule_Changed; Rules.Clear(); + _loadFailed = false; - if (File.Exists(_monstersPath)) + try { - try - { - string json = File.ReadAllText(_monstersPath); - var rules = JsonSerializer.Deserialize(json, EditorJsonContext.Default.ListMonsterRule); - if (rules != null) - foreach (var r in rules) AddRule(r); - } - catch (Exception ex) { SetStatus($"Load error: {ex.Message}", error: true); return; } + foreach (var r in MonsterRulesFile.Load(_monstersPath)) AddRule(r); + } + catch (Exception ex) + { + _loadFailed = true; + SetStatus($"Load error: {ex.Message} - not saving over {_monstersPath}; fix the file and reopen it.", error: true); + return; } EnsureDefault(); @@ -187,12 +196,10 @@ public partial class MainWindow : Window private void Save() { - if (string.IsNullOrEmpty(_monstersPath)) return; + if (string.IsNullOrEmpty(_monstersPath) || _loadFailed) return; try { - Directory.CreateDirectory(_charFolder); - string json = JsonSerializer.Serialize(new List(Rules), EditorJsonContext.Default.ListMonsterRule); - File.WriteAllText(_monstersPath, json); + MonsterRulesFile.Save(_monstersPath, Rules); SetStatus($"Saved {Rules.Count} rule(s) — {DateTime.Now:HH:mm:ss}"); } catch (Exception ex) { SetStatus($"Save error: {ex.Message}", error: true); } diff --git a/Tools/RynthCore.MonsterEditor/Models.cs b/Tools/RynthCore.MonsterEditor/Models.cs index 5e0666f..ec0d509 100644 --- a/Tools/RynthCore.MonsterEditor/Models.cs +++ b/Tools/RynthCore.MonsterEditor/Models.cs @@ -1,13 +1,19 @@ using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; +using System.Text.Json; using System.Text.Json.Serialization; namespace RynthCore.MonsterEditor; +/// The editor's copy of RynthAi's MonsterRule (Plugins/RynthCore.Plugin.RynthAi/LegacyUi/ +/// LegacyUiSettings.cs), read from and saved to the same monsters file. A field the plugin has and +/// this class doesn't still survives a save, through . public class MonsterRule : INotifyPropertyChanged { private string _name = "New Monster"; + private string _category = ""; + private string _matchExpression = ""; private int _priority = 1; private string _damageType = "Auto"; private int _weaponId; @@ -18,6 +24,14 @@ public class MonsterRule : INotifyPropertyChanged private string _petDamage = "PAuto"; public string Name { get => _name; set { _name = value; OnPropertyChanged(); } } + /// The plugin's rule group label. Kept and editable here (before 2026-10-05 an + /// editor save dropped it). + public string Category { get => _category; set { _category = value ?? ""; OnPropertyChanged(); } } + /// The plugin's match expression (CombatManager.GetRuleForTarget): when set, the + /// rule matches when the expression is true (and the name, if any, is in the target's). + /// Empty = match by name only. Kept and editable here (before 2026-10-05 an editor save + /// dropped it, so expression rules fell back to name-only). + public string MatchExpression { get => _matchExpression; set { _matchExpression = value ?? ""; OnPropertyChanged(); } } public int Priority { get => _priority; set { _priority = value; OnPropertyChanged(); } } public string DamageType { get => _damageType; set { _damageType = value; OnPropertyChanged(); } } public int WeaponId { get => _weaponId; set { _weaponId = value; OnPropertyChanged(); } } @@ -36,6 +50,11 @@ public class MonsterRule : INotifyPropertyChanged public int OffhandId { get => _offhandId; set { _offhandId = value; OnPropertyChanged(); } } public string PetDamage { get => _petDamage; set { _petDamage = value; OnPropertyChanged(); } } + /// Every field in the file this class doesn't know (e.g. the plugin's CustomDebuffs, + /// or one added later), written back unchanged. + [JsonExtensionData] + public Dictionary? ExtraFields { get; set; } + [JsonIgnore] public bool IsDefault => string.Equals(_name, "Default", System.StringComparison.OrdinalIgnoreCase); diff --git a/Tools/RynthCore.MonsterEditor/MonsterRulesFile.cs b/Tools/RynthCore.MonsterEditor/MonsterRulesFile.cs new file mode 100644 index 0000000..d1d2b59 --- /dev/null +++ b/Tools/RynthCore.MonsterEditor/MonsterRulesFile.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; + +namespace RynthCore.MonsterEditor; + +/// +/// Reading and writing a monsters file (a JSON array of MonsterRule, the format RynthAi's +/// LegacyDashboardRenderer reads and writes), and finding the file the plugin uses. No UI: +/// Tools/RynthCore.RynthAiHostTests compiles this file in and round-trips a file through it and +/// the plugin's own serializer. +/// +public static class MonsterRulesFile +{ + private const string SettingsProfilesDir = "SettingsProfiles"; + private const string MonsterProfilesDir = "MonsterProfiles"; + // RynthAi's LegacyServerFolder: its monsters live straight in MonsterProfiles\. + private const string LegacyServerFolder = "ACEmulator"; + private const string LegacyFileName = "monsters.json"; + + /// The rules in ; empty when the file doesn't exist. + /// Throws on a file that isn't a JSON array of rules (the caller shows the error and + /// doesn't save over it). + public static List Load(string path) + { + if (!File.Exists(path)) return new List(); + string json = File.ReadAllText(path); + return JsonSerializer.Deserialize(json, EditorJsonContext.Default.ListMonsterRule) ?? new List(); + } + + /// Writes in place (File.WriteAllText, as before: the + /// plugin's FileSystemWatcher reloads on a LastWrite change). + public static void Save(string path, IEnumerable rules) + { + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + File.WriteAllText(path, JsonSerializer.Serialize(new List(rules), EditorJsonContext.Default.ListMonsterRule)); + } + + /// + /// The monsters file for what the editor was given: a .json file is edited as is. A + /// character's settings folder (RynthAi\SettingsProfiles\<server>\<character>, what the + /// plugin passes) maps to the plugin's file, RynthAi\MonsterProfiles\<server>\<character>.json + /// (MonsterProfiles\<character>.json for the ACEmulator folder). The old + /// <folder>\monsters.json is used only when that file doesn't exist and the old one does + /// (the plugin moves it across at its next load). + /// + public static string ResolveRulesPath(string pathOrFolder) + { + string p = pathOrFolder.Trim().Trim('"').TrimEnd('\\', '/'); + if (File.Exists(p) || p.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) + return p; + + string legacy = Path.Combine(p, LegacyFileName); + string? current = PluginRulesPathForCharFolder(p); + if (current == null) return legacy; + if (File.Exists(current)) return current; + return File.Exists(legacy) ? legacy : current; + } + + /// RynthAi's MonsterProfiles file for a SettingsProfiles character folder; null when + /// the folder isn't laid out that way. + public static string? PluginRulesPathForCharFolder(string charFolder) + { + var character = new DirectoryInfo(charFolder.TrimEnd('\\', '/')); + DirectoryInfo? server = character.Parent; + DirectoryInfo? profiles = server?.Parent; + DirectoryInfo? root = profiles?.Parent; + if (server == null || profiles == null || root == null) return null; + if (!profiles.Name.Equals(SettingsProfilesDir, StringComparison.OrdinalIgnoreCase)) return null; + + string monsters = Path.Combine(root.FullName, MonsterProfilesDir); + return server.Name.Equals(LegacyServerFolder, StringComparison.OrdinalIgnoreCase) + ? Path.Combine(monsters, character.Name + ".json") + : Path.Combine(monsters, server.Name, character.Name + ".json"); + } + + /// The character's settings folder (where active_profile.txt and the profile with + /// the weapon list live) for a monsters file: the file's own folder for an old + /// monsters.json, the matching SettingsProfiles folder for a MonsterProfiles file, else the + /// file's own folder. + public static string CharFolderForRulesPath(string rulesPath) + { + var file = new FileInfo(rulesPath); + string folder = file.DirectoryName ?? ""; + if (file.Name.Equals(LegacyFileName, StringComparison.OrdinalIgnoreCase)) + return folder; + + string character = Path.GetFileNameWithoutExtension(file.Name); + DirectoryInfo? dir = file.Directory; + if (dir == null) return folder; + if (dir.Name.Equals(MonsterProfilesDir, StringComparison.OrdinalIgnoreCase) && dir.Parent != null) + return Path.Combine(dir.Parent.FullName, SettingsProfilesDir, LegacyServerFolder, character); + if (dir.Parent is { } monsters && monsters.Name.Equals(MonsterProfilesDir, StringComparison.OrdinalIgnoreCase) && monsters.Parent != null) + return Path.Combine(monsters.Parent.FullName, SettingsProfilesDir, dir.Name, character); + return folder; + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index 87cddaf..d1cec55 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -48,6 +48,9 @@ internal static unsafe class FakeHost /// Item id -> container id. When it has entries at Create() time the host also gets /// GetObjectOwnershipInfo (opt-in, so tests written without it see no ownership, as before). public static readonly Dictionary Containers = new(); + /// Item id -> the creature wielding it (GetObjectOwnershipInfo's wielder). Entries here + /// also install GetObjectOwnershipInfo; an id in neither map reads as unknown ownership. + public static readonly Dictionary Wielders = new(); /// Object id -> PublicWeenieDesc bitfield (0x2000 corpse, 0x8 player, ...). When it has /// entries at Create() time the host also gets GetObjectBitfield (opt-in, as Containers). public static readonly Dictionary Bitfields = new(); @@ -118,6 +121,9 @@ internal static unsafe class FakeHost public static int CastBusy; public static int VTankSeq; public static int CombatModeValue = 1; + /// Opt-in (set before Create): ChangeCombatMode, recorded in . + public static bool CombatModeCalls; + public static readonly List CombatModeRequests = new(); /// Opt-in (set before Create): WieldItem (a wield into a named slot, API v70+). The /// host then reports API version 73, so only tests that ask for it see the newer calls. public static bool WieldCalls; @@ -149,23 +155,40 @@ internal static unsafe class FakeHost public static uint GroundContainer; /// The item selected in the game (GetSelectedItemId); 0 = none. public static uint SelectedItem; + /// Opt-in (set before Create): UseObjectOn (an item used on another, e.g. a spirit on a + /// pet essence); every call lands in . + public static bool UseOnCalls; + /// Every UseObjectOn (source, target), in order (opt-in with ). + public static readonly List<(uint Source, uint Target)> UsesOn = new(); /// Opt-in: install SendPluginCommand (the engine's plugin-command broker, API v64). public static bool PluginCommandCalls; /// What SendPluginCommand answers: true = delivered (the target plugin is loaded). public static bool PluginCommandDelivered = true; /// Every SendPluginCommand (plugin, action, value), in order. public static readonly List<(string Plugin, string Action, string Value)> PluginCommands = new(); + /// Opt-in (set before Create): ForceResetBusyCount (counted in ) + /// and GetBusyState (answering ). + public static bool BusyCalls; + public static int ForceResets; + public static int BusyStateValue; // ANSI strings handed back to tested code stay alive for the whole run. private static readonly Dictionary _ansi = new(); + /// Opt-in: install the Nav3D calls (clear, ring, line, triangle) and record them. + public static bool Nav3DCalls; + public static readonly List<(float X, float Y, float Z, float Radius, uint Color)> Nav3DRings = new(); + public static readonly List<(float X1, float Y1, float Z1, float X2, float Y2, float Z2, float Thick, uint Color)> Nav3DLines = new(); + public static readonly List<(float X1, float Y1, float Z1, float X2, float Y2, float Z2, float X3, float Y3, float Z3, uint Color)> Nav3DTriangles = new(); + public static void Reset() { + Nav3DCalls = false; Nav3DRings.Clear(); Nav3DLines.Clear(); Nav3DTriangles.Clear(); Names.Clear(); Positions.Clear(); ItemTypes.Clear(); Ints.Clear(); Doubles.Clear(); Quads.Clear(); Bools.Clear(); Strings.Clear(); Skills.Clear(); SkillLevels.Clear(); Attributes.Clear(); SpellIds.Clear(); DataIds.Clear(); Palettes.Clear(); KnownSpells.Clear(); NotAttackable.Clear(); Enchantments.Clear(); - Containers.Clear(); Bitfields.Clear(); + Containers.Clear(); Wielders.Clear(); Bitfields.Clear(); ServerTime = 0; Vitae = 1.0f; Portaling = false; PlayerPose = default; HasPose = true; Vitals = default; BaseVitals = default; WorldName = ""; AccountName = ""; HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0; @@ -179,7 +202,10 @@ internal static unsafe class FakeHost RefuseSalvageAdd.Clear(); OnSalvageExecute = null; Wielded.Clear(); _panelItems.Clear(); CloseContainerCalls = false; Closes.Clear(); GroundContainer = 0; SelectedItem = 0; + UseOnCalls = false; UsesOn.Clear(); PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear(); + CombatModeCalls = false; CombatModeRequests.Clear(); + BusyCalls = false; ForceResets = 0; BusyStateValue = 0; } /// @@ -212,7 +238,7 @@ internal static unsafe class FakeHost PlayerIdValue = playerId; if (playerId != 0) api.GetPlayerIdFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetPlayerId; - if (Containers.Count > 0) + if (Containers.Count > 0 || Wielders.Count > 0) api.GetObjectOwnershipInfoFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectOwnershipInfo; if (Bitfields.Count > 0) api.GetObjectBitfieldFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectBitfield; @@ -222,6 +248,13 @@ internal static unsafe class FakeHost api.CastSpellFn = (IntPtr)(delegate* unmanaged[Cdecl])&CastSpell; if (StopCalls) api.StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl])&StopCompletely; + if (Nav3DCalls) + { + api.Nav3DClearFn = (IntPtr)(delegate* unmanaged[Cdecl])&Nav3DClear; + api.Nav3DAddRingFn = (IntPtr)(delegate* unmanaged[Cdecl])&Nav3DAddRing; + api.Nav3DAddLineFn = (IntPtr)(delegate* unmanaged[Cdecl])&Nav3DAddLine; + api.Nav3DAddTriangleFn = (IntPtr)(delegate* unmanaged[Cdecl])&Nav3DAddTriangle; + } if (GiveCalls) api.GiveObjectToFn = (IntPtr)(delegate* unmanaged[Cdecl])&GiveObjectTo; if (WeaponCalls) @@ -241,6 +274,15 @@ internal static unsafe class FakeHost api.SalvagePanelExecuteFn = (IntPtr)(delegate* unmanaged[Cdecl])&SalvagePanelExecute; api.GetObjectWielderInfoFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectWielderInfo; } + if (CombatModeCalls) + api.ChangeCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl])&ChangeCombatMode; + if (BusyCalls) + { + api.ForceResetBusyCountFn = (IntPtr)(delegate* unmanaged[Cdecl])&ForceResetBusyCount; + api.GetBusyStateFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetBusyState; + } + if (UseOnCalls) + api.UseObjectOnFn = (IntPtr)(delegate* unmanaged[Cdecl])&UseObjectOn; if (WieldCalls) { api.Version = 73; @@ -402,9 +444,11 @@ internal static unsafe class FakeHost [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectOwnershipInfo(uint id, uint* container, uint* wielder, uint* location) { - if (!Containers.TryGetValue(id, out uint c)) return 0; + bool inPack = Containers.TryGetValue(id, out uint c); + bool worn = Wielders.TryGetValue(id, out uint w); + if (!inPack && !worn) return 0; *container = c; - *wielder = 0; + *wielder = w; *location = 0; return 1; } @@ -543,6 +587,20 @@ internal static unsafe class FakeHost [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static uint GetPlayerId() => PlayerIdValue; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static void Nav3DClear() { Nav3DRings.Clear(); Nav3DLines.Clear(); Nav3DTriangles.Clear(); } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static void Nav3DAddRing(float x, float y, float z, float radius, float thick, uint color) => Nav3DRings.Add((x, y, z, radius, color)); + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static void Nav3DAddLine(float x1, float y1, float z1, float x2, float y2, float z2, float thick, uint color) + => Nav3DLines.Add((x1, y1, z1, x2, y2, z2, thick, color)); + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static void Nav3DAddTriangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint color) + => Nav3DTriangles.Add((x1, y1, z1, x2, y2, z2, x3, y3, z3, color)); + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static uint GetSelectedItemId() => SelectedItem; @@ -561,14 +619,23 @@ internal static unsafe class FakeHost [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int StopCompletely() { Stops++; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static void ForceResetBusyCount() { ForceResets++; BusyStateValue = 0; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetBusyState() => BusyStateValue; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GiveObjectTo(uint item, uint target, int amount) { Gives.Add((item, target, amount)); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetCurrentCombatMode() => CombatModeValue; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int ChangeCombatMode(int mode) { CombatModeRequests.Add(mode); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int UseObject(uint id) { Uses.Add(id); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int UseObjectOn(uint source, uint target) { UsesOn.Add((source, target)); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int WieldItem(uint id, uint mask) { Wields.Add((id, mask)); return 1; } diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index a1cef53..2af7c91 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -17,6 +17,9 @@ 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"); + /// DungeonHazardStore's folder before Main pointed it at the scratch folder. + public static string LiveHazardFolder { get; private set; } = ""; + private static int Main(string[] args) { if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true); @@ -30,6 +33,9 @@ internal static class Program ExpressionEngine.ItemGiverDir = Path.Combine(TempRoot, "ItemGiver"); // The dungeon map bake writes floor plans under C:\Games\RynthSuite\RynthAi\Maps. RynthCore.Plugin.RynthAi.Maps.DungeonMapBake.CacheDir = Path.Combine(TempRoot, "Maps"); + // A sighted lava/acid hotspot is persisted under C:\Games\RynthSuite\RynthAi\DungeonHazards. + LiveHazardFolder = RynthCore.Plugin.RynthAi.DungeonHazardStore.Folder; + RynthCore.Plugin.RynthAi.DungeonHazardStore.Folder = Path.Combine(TempRoot, "DungeonHazards"); // Spell names (item spells, spell expiry by name) come from the plugin's embedded table. SpellDatabase.Load(); @@ -39,8 +45,10 @@ internal static class Program VTankLootTests.Register(runner); ExpressionTests.Register(runner); MetaTests.Register(runner); + NoKillTests.Register(runner); MetaSchedulerTests.Register(runner); NavEngineTests.Register(runner); + NavReachTests.Register(runner); PatrolDoorwayTests.Register(runner); BuffTests.Register(runner); CombatMathTests.Register(runner); @@ -53,6 +61,7 @@ internal static class Program LootSalvageTests.Register(runner); LootCorpseTests.Register(runner); OwnCorpseTests.Register(runner); + UseRefusalTests.Register(runner); VitalsTests.Register(runner); CastSafetyTests.Register(runner); HealLatencyTests.Register(runner); @@ -64,6 +73,13 @@ internal static class Program LootAddItemTests.Register(runner); GiveTests.Register(runner); DungeonMapBakeTests.Register(runner); + MonsterEditorTests.Register(runner); + InstallPathsTests.Register(runner); + PetRefillTests.Register(runner); + WorldCacheTypedTests.Register(runner); + ItemInfoTests.Register(runner); + NavOverlayTests.Register(runner); + ActionPacingTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj b/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj index f11b6d2..fb2bb24 100644 --- a/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj +++ b/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj @@ -50,6 +50,17 @@ RynthAi's JSON against the engine's real reader. Same relative engine path the plugin itself references. --> + + + + + + + + + diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs new file mode 100644 index 0000000..05f1905 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs @@ -0,0 +1,622 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// One server action at a time (2026-10-06, ops\overnight\2026-10-06-action-pacing.md). +// Drakkon's stuck uses and stuck casts on DreamWeave: every stall began with a combat-mode change +// sent while a corpse use was still unanswered, and once the server held an action RynthAi fired +// the next cast or use every 0.4-2.5 s on top of it (it paced on a busy count it kept zeroing, and +// on the enchantment rather than the server's UseDone). These tests replay those sequences against +// Plugins/Shared/ActionPacer.cs and the RynthAi code wired to it: +// - the pacer itself: answers (UseDone, a refusal, a wield, a stance read), time limits, the heal +// rules, and that nothing is ever force-cleared; +// - the onset sequence (corpse use -> idle peace swap 3-677 ms later) and the movement hold; +// - BuffManager: a cast whose result is in but whose UseDone isn't waits (one cast, not a flood), +// heals still go first, and the emergency stance settle is unchanged; +// - looting: one open per answer; Drakkon's stall is still found and reported once; +// - CombatManager's idle peace swap waits for an unanswered kit; +// - the busy mirror is reset without touching the client's count. +internal static class ActionPacingTests +{ + private const uint Player = 0x50000E01; + private const uint Corpse = 0x80068ACE; + private const uint CorpseB = 0x80072023; + private const uint Kit = 0x8004BEF8; + private const uint Wand = 0x8007467A; + private const uint Pack = 0x50000E01; // the player's main pack is the player + private const uint ItemTypeContainer = 0x200; + private const uint LongDescKey = 16; + private const uint TooBusy = 0x1D; + private const string Me = "Drakkon"; + private static readonly (uint Cell, float X, float Y, float Z) Me0 = (0xA9B40019u, 100f, 100f, 0f); + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static; + + public static void Register(Runner r) + { + r.Add("pacing: a use is the server action until its UseDone; a refusal answers it too; a wield answers by wielding", UseAnswers); + r.Add("pacing: the stall onset replayed - the idle peace swap waits for the corpse use's answer, then goes; no swap to the mode you're in", OnsetModeChangeHeld); + r.Add("pacing: moves, turns and redundant stops wait while the server answers; a real stop and the cast nudge go through", MovesHeld); + r.Add("pacing: no answer - each kind's time limit lets the next action go, logged, and nothing is force-cleared", TimeLimits); + r.Add("pacing: heals keep their priority (1 s behind a corpse use, 300 ms at Emergency, one behind a cast's result, 300 ms after the stance reads)", HealRules); + r.Add("pacing (vitals): Drakkon 07:03 - a cast whose result is in waits for its UseDone: one cast, not a too-busy flood", CastWaitsForUseDone); + r.Add("pacing (vitals): a heal goes 1 s behind an unanswered corpse use; the emergency stance settle is unchanged", HealLatencyKept); + r.Add("pacing (looting): one open per server answer, never re-sent on top of an unanswered one", LootOneOpenPerAnswer); + r.Add("pacing (looting): Drakkon's stall is still found and said once with pacing on", LootStallStillDetected); + r.Add("pacing (combat): the idle peace swap waits while a kit is unanswered", CombatPeaceWaitsForKit); + r.Add("pacing (arbiter): the activity-change StopCompletely only when RynthAi itself has the character moving", ArbiterStopOnlyWhenMoving); + r.Add("busy mirror: follows the engine's count (1.5 s), never reset while the engine says busy; old engines: the mirror only; never a force-clear", MirrorResetOnly); + } + + // ── Pacer rig ─────────────────────────────────────────────────────────────── + + private static long _t; + + /// Turns the pacing on with RynthAi's use recorder and a hand-moved clock. + private static void PaceOn() + { + _t = 10_000_000; + ActionPacer.Reset(); + ActionPacer.Enabled = true; + ActionPacer.NowMs = () => _t; + UseAudit.Reset("RynthAi", () => true); + UseAudit.NowMs = () => _t; + MoveAudit.Reset(); + MoveAudit.NowMs = () => _t; + var rec = typeof(RynthAiPlugin).GetMethod("RecordUseForPacing", Any)!; + UseAudit.AfterSend = (h, u) => rec.Invoke(null, new object[] { h, u }); + } + + private static void PaceOff() + { + ActionPacer.Enabled = false; + ActionPacer.Reset(); + ActionPacer.NowMs = () => Environment.TickCount64; + UseAudit.Reset("?", null); + UseAudit.NowMs = () => Environment.TickCount64; + MoveAudit.Reset(); + MoveAudit.NowMs = () => Environment.TickCount64; + } + + private static void Paced(Action body) + { + PaceOn(); + try { body(); } + finally { PaceOff(); } + } + + private static RynthCoreHost World(int combatMode = 2) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; // UseObject, GetCurrentCombatMode + FakeHost.SalvageCalls = true; // GetObjectWielderInfo + FakeHost.ServerGates = true; // GetUseDoneSeq + FakeHost.LastUseDoneCalls = true; + FakeHost.UseOnCalls = true; + FakeHost.CombatModeCalls = true; + FakeHost.StopCalls = true; + FakeHost.BusyCalls = true; + FakeHost.CombatModeValue = combatMode; + FakeHost.Names[Player] = Me; + FakeHost.Names[Corpse] = "Corpse of Olthoi Swarm Worker"; + FakeHost.Names[Kit] = "Peerless Healing Kit"; + FakeHost.Names[Wand] = "Academy Wand"; + FakeHost.Bitfields[Corpse] = 0x2000; + FakeHost.Containers[Kit] = Pack; + FakeHost.Containers[Wand] = Pack; + return FakeHost.Create(Player); + } + + private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal)); + + // ── The pacer ─────────────────────────────────────────────────────────────── + + private static void UseAnswers() => Paced(() => + { + var host = World(); + Check.True(host.UseFor(Corpse, "Loot", "open the claimed corpse"), "the open goes out"); + var a = ActionPacer.Current(host); + Check.True(a != null && a.Kind == PacedKind.WorldUse, "a corpse is a world use the server walks to"); + Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out string why), "nothing else starts meanwhile"); + Check.True(why.Contains("Corpse of Olthoi Swarm Worker") && why.Contains("RynthAi/Loot"), "why names the corpse and the sender: " + why); + _t += 690; // the healthy median answer + Check.True(ActionPacer.Current(host) != null, "still unanswered at 690 ms"); + FakeHost.UseDone(0); + Check.True(ActionPacer.Current(host) == null, "its UseDone answers it"); + Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "the next action may go"); + + // A kit on yourself is an item use; "You're too busy" (0x1D) is an answer as well. + Check.True(host.UseOnFor(Kit, Player, "Buff", "vitals: healing kit on yourself"), "the kit goes out"); + Check.True(ActionPacer.Current(host)?.Kind == PacedKind.ItemUse, "a kit on yourself is an item use"); + FakeHost.UseDone(TooBusy); + Check.True(ActionPacer.Current(host) == null, "a refusal answers it (the server is busy with something else; the caller backs off)"); + + // A wield gets no UseDone at all (0 of 18 wand wields on 10-05/10-06): it answers by wielding. + Check.True(host.UseFor(Wand, "Buff", "buffing: wield the wand"), "the wield goes out"); + Check.True(ActionPacer.Current(host)?.Kind == PacedKind.ItemUse, "an item use"); + _t += 400; + Check.True(ActionPacer.Current(host) != null, "not wielded yet: waiting"); + FakeHost.Wielded[Wand] = 0x1000000; + Check.True(ActionPacer.Current(host) != null, "wielded: a short settle first"); + _t += ActionPacer.WieldSettleMs; + Check.True(ActionPacer.Current(host) == null, "wielded and settled: answered"); + Check.Eq(ActionPacer.TimedOut, 0L, "no time limit was needed"); + }); + + private static void OnsetModeChangeHeld() => Paced(() => + { + // 06:18:44.549 corpse use in melee stance, 06:18:44.552 RequestCombatMode(peace). + var host = World(combatMode: 2); + host.UseFor(Corpse, "Loot", "open the claimed corpse"); + _t += 3; + Check.False(host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", "idle: no target"), "3 ms later: the peace swap is held"); + _t += 674; + Check.False(host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", "idle: no target"), "677 ms later (10-05 13:18:31): still held"); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no mode change reached the server while the use was unanswered"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("change to Peace mode held")), 1, "logged once"); + + FakeHost.UseDone(0); + Check.True(host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", "idle: no target"), "answered: the swap goes out"); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "one request, to peace"); + Check.True(ActionPacer.Current(host)?.Kind == PacedKind.CombatMode, "the stance change is now the action the server is answering"); + + // The next corpse waits for the stance: the client reads peace, then the animation. + FakeHost.CombatModeValue = 1; + _t += 500; + Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "500 ms: the stance animation is still running"); + _t += ActionPacer.ModeSettleMs - 500; + Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "800 ms: settled, the next open may go"); + + // No request for the mode the client already reads (the engine pushed a raw 0x53 anyway). + FakeHost.CombatModeRequests.Clear(); + Check.False(host.ChangeCombatModeFor(CombatMode.NonCombat, "Loot/Wedge", "loot wedge reset"), "already in peace: nothing to send"); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "nothing sent"); + Check.True(host.ChangeCombatModeFor(CombatMode.NonCombat, "Command", "/ra panic", force: true), "a typed command forces it"); + Check.Eq(FakeHost.CombatModeRequests.Count, 1, "forced: sent"); + }); + + private static void MovesHeld() => Paced(() => + { + var host = World(); + host.UseFor(Corpse, "Loot", "open the claimed corpse"); + Check.False(host.SetAutoRunBy("Nav", true), "nav can't start running"); + Check.False(host.TurnToHeadingBy("Nav", 90f), "nor turn"); + Check.False(host.SetMotionBy("Combat", 0x6500000D, true), "nor start a turn motion"); + Check.False(host.StopCompletelyBy("Arbiter"), "a stop with nothing of ours moving is a redundant movement packet: held"); + Check.False(host.SetMotionBy("Combat", 0x6500000D, false), "Combat's turn-off with no turn on: held"); + Check.Eq(FakeHost.AutoRunCalls.Count, 0, "no autorun reached the client"); + Check.Eq(FakeHost.Stops, 0, "no stop either"); + Check.True(Logged("held (move/turn): the server is still answering the use of"), "the hold is logged"); + + Check.True(host.SetAutoRunBy("Buff/Nudge", true) && host.SetAutoRunBy("Buff/Nudge", false), "the held-cast nudge is deliberate: it goes through"); + Check.True(host.StopCompletelyBy("MacroStop"), "a macro stop goes through"); + + FakeHost.UseDone(0); + Check.True(host.SetAutoRunBy("Nav", true), "answered: nav runs again"); + host.UseFor(CorpseB, "Loot", "open the claimed corpse"); + FakeHost.Names[CorpseB] = "Corpse of Olthoi Swarm Drone"; + Check.True(host.StopCompletelyBy("Arbiter"), "while we really run, a stop always goes through"); + Check.False(MoveAudit.OwnMovementActive, "and we are not moving any more"); + }); + + private static void TimeLimits() => Paced(() => + { + var host = World(); + void Expect(PacedKind kind, long limit, Action send) + { + long before = ActionPacer.TimedOut; + send(); + Check.True(ActionPacer.Current(host)?.Kind == kind, $"{kind}: outstanding"); + _t += limit - 1; + Check.True(ActionPacer.Current(host) != null, $"{kind}: still waiting 1 ms before {limit} ms"); + _t += 1; + Check.True(ActionPacer.Current(host) == null, $"{kind}: the time limit lets the next action go"); + Check.Eq(ActionPacer.TimedOut, before + 1, $"{kind}: counted"); + } + Expect(PacedKind.WorldUse, ActionPacer.WorldUseMaxMs, () => host.UseFor(Corpse, "Loot", "open")); + Expect(PacedKind.ItemUse, ActionPacer.ItemUseMaxMs, () => host.UseOnFor(Kit, Player, "Buff", "kit")); + Expect(PacedKind.Cast, ActionPacer.CastMaxMs, () => host.CastSpellFor(Player, 1426, "Buff", "Focus Self VI")); + FakeHost.CombatModeValue = 2; + Expect(PacedKind.CombatMode, ActionPacer.ModeMaxMs, () => host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand")); + Check.True(Logged("no answer from the server to the cast of Focus Self VI") && Logged("nothing cleared"), "each is logged, and says nothing was cleared"); + Check.Eq(FakeHost.ForceResets, 0, "the client's busy count was never force-cleared"); + }); + + private static void HealRules() => Paced(() => + { + var host = World(); + host.UseFor(Corpse, "Loot", "open"); + _t += 900; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a heal 900 ms behind an unanswered corpse use waits"); + _t += 100; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "at 1 s it goes ahead (the server cancels the walk cleanly)"); + Check.True(Logged("the heal goes ahead of the use of"), "logged"); + + FakeHost.UseDone(0); + host.UseFor(Corpse, "Loot", "open"); + _t += 300; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "at Emergency Heal At: 300 ms"); + Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "anything else still waits"); + + FakeHost.UseDone(0); + host.CastSpellFor(Player, 1426, "Buff", "Focus Self VI"); + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a cast before its result: the heal waits (the server would refuse it)"); + ActionPacer.NoteCastResult(); + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "its result is in: one heal may queue behind the recoil"); + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "only one"); + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "a buff waits for the UseDone"); + + FakeHost.UseDone(0); + FakeHost.CombatModeValue = 2; + host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode"); + _t += 60; + FakeHost.CombatModeValue = 8; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "the client reads Magic: not yet"); + _t += 299; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "299 ms after the read: not yet"); + _t += 1; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "300 ms after the read: the heal goes"); + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "a buff waits for the full 800 ms settle"); + }); + + // ── BuffManager ────────────────────────────────────────────────────────────── + + private sealed class BuffRig + { + public DateTime T0 = new(2026, 10, 6, 7, 3, 23); + public DateTime NowAt; + public readonly BuffManager B; + public readonly LegacyUiSettings S; + public readonly PlayerVitalsCache V; + public RynthCoreHost Host; + + public BuffRig(int combatMode = CombatMode.Magic) + { + Host = World(combatMode); + FakeHost.Containers.Clear(); + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, 33)] = (400, 2); + Host = FakeHost.Create(Player); + S = new LegacyUiSettings + { + IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false, + EnableBuffing = false, SpellCastIntervalMs = 0, + }; + var skills = new CharacterSkills(Host); + skills.SetPlayerId(Player); + var sm = new SpellManager(Host, S); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + V = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 10 }; + B = new BuffManager(Host, S, sm, V); + B.SetCharacterSkills(skills); + NowAt = T0; + B.Clock = () => NowAt; + B.MarkLiveBuffsReadyForTests(); + _t = 10_000_000; + ActionPacer.NowMs = () => _t + (long)(NowAt - T0).TotalMilliseconds; + MoveAudit.NowMs = ActionPacer.NowMs; + } + + public void At(double seconds) => NowAt = T0.AddSeconds(seconds); + public void Chat(string text, int type = 0) => B.OnChatWindowText(text, type); + public string CastName => SpellTable.ById(FakeHost.Casts.Last().SpellId)?.Name ?? ""; + } + + private static void CastWaitsForUseDone() + { + // Without the pacing (as before): the result line ends the cast, and with mana still low the + // next Stamina to Mana goes straight out - on a server holding the first one, "too busy". + int Script(bool pacing) + { + PaceOn(); + ActionPacer.Enabled = pacing; + try + { + var r = new BuffRig(); + r.At(0); r.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 1, $"pacing={pacing}: Stamina to Mana goes out"); + string name = r.CastName; + r.At(0.1); r.Chat("You say, \"Puish Zharil\"", 17); + // 07:03:26.799: the result is in 3.3 s later; the server's UseDone never comes. + r.At(2.3); r.Chat($"You cast {name} on yourself and lose 35 points of stamina and also gain 47 points of mana"); + for (double s = 2.4; s < 4.0; s += 0.1) { r.At(s); r.B.OnHeartbeat(); } + int before = FakeHost.Casts.Count; + if (pacing) + { + Check.True(r.B.PacerHolds > 0, "the vitals step waited for the server's answer"); + FakeHost.UseDone(0); + r.At(4.0); r.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 2, "the UseDone arrives: the next cast goes at once"); + } + return before; + } + finally { PaceOff(); } + } + int unpaced = Script(pacing: false); + int paced = Script(pacing: true); + Check.True(unpaced >= 2, $"without pacing a second cast went out before the server answered ({unpaced} casts by 4 s)"); + Check.Eq(paced, 1, "with pacing: one cast until the server answers it"); + } + + private static void HealLatencyKept() + { + PaceOn(); + try + { + // A heal behind a corpse use the server walks to: it waits 1 s, not the whole walk. + var r = new BuffRig(); + r.S.HealAt = 60; r.S.TopOffHP = 60; r.S.GetManaAt = 0; r.S.TopOffMana = 0; + r.V.CurrentHealth = 50; r.V.CurrentMana = 100; + r.At(0); + r.Host.UseFor(Corpse, "Loot", "open the claimed corpse"); + r.B.BusyCount = 1; // the open's +1 on the client's count, as the engine reports it + for (double s = 0; s < 0.95; s += 0.1) { r.At(s); r.B.OnHeartbeat(); } + Check.Eq(FakeHost.Casts.Count, 0, "under 1 s behind the unanswered open: no heal yet"); + r.At(1.0); r.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 1, "at 1 s the heal goes (the open's busy count doesn't hold it again)"); + string healName = SpellTable.ById(FakeHost.Casts[0].SpellId)?.Name ?? ""; + Check.True(healName.StartsWith("Heal Self") || healName == "Adja's Intervention", "and it is the heal spell: " + healName); + + // Nothing outstanding: the heal goes on the first heartbeat, as before. + PaceOff(); PaceOn(); + var q = new BuffRig(); + q.S.HealAt = 60; q.S.TopOffHP = 60; q.S.GetManaAt = 0; q.S.TopOffMana = 0; + q.V.CurrentHealth = 50; q.V.CurrentMana = 100; + q.At(0); q.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 1, "nothing outstanding: Heal Self on the first heartbeat"); + + // The emergency settle after a stance change (CastSafetyTests.EmergencyStanceWait) with the + // pacing on: the stance change is the outstanding action, and the heal still goes 300 ms + // after the client reads Magic. + PaceOff(); PaceOn(); + var e = new BuffRig(CombatMode.NonCombat); + e.S.EmergencyHealAt = 30; e.S.HealAt = 60; e.S.TopOffHP = 60; e.S.GetManaAt = 0; e.S.TopOffMana = 0; + e.V.CurrentHealth = 20; e.V.CurrentMana = 100; + e.At(0); e.B.OnHeartbeat(); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", "out of Magic: the stance request goes out"); + Check.Eq(FakeHost.Casts.Count, 0, "no cast before the stance"); + FakeHost.CombatModeValue = CombatMode.Magic; + e.At(0.06); e.B.OnHeartbeat(); + e.At(0.30); e.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 0, "240 ms after Magic: still settling"); + e.At(0.37); e.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 1, "310 ms after Magic (370 ms after the request): Heal Self goes, as without pacing"); + } + finally { PaceOff(); } + } + + // ── Looting ────────────────────────────────────────────────────────────────── + + private static void LootWorld() + { + FakeHost.Reset(); + FakeHost.SalvageCalls = true; + FakeHost.WeaponCalls = true; + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.StopCalls = true; + FakeHost.BusyCalls = true; + FakeHost.Names[Player] = Me; + FakeHost.Positions[Player] = Me0; + FakeHost.PlayerPose = Me0; + foreach ((uint id, float dx) in new[] { (Corpse, 1.0f), (CorpseB, 1.5f) }) + { + FakeHost.Names[id] = "Corpse of Olthoi Swarm Worker"; + FakeHost.ItemTypes[id] = ItemTypeContainer; + FakeHost.Strings[(id, LongDescKey)] = $"Killed by {Me}."; + FakeHost.NotAttackable.Add(id); + FakeHost.Positions[id] = (Me0.Cell, Me0.X + dx, Me0.Y, Me0.Z); + } + } + + private sealed class Bot + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new() + { + IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0, + LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false, + }; + + public Bot(RynthCoreHost host) + { + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + Set("_dashboard", dash); + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + Set("_objectCache", cache); + Set("_playerId", Player); + cache.OnCreateObject(Corpse); + cache.OnCreateObject(CorpseB); + cache.Tick(); + string profile = Path.Combine(Program.TempRoot, "action-pacing-test.json"); + new LootProfile { Name = "nothing" }.Save(profile); + S.CurrentLootPath = profile; + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public T Get(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!; + public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a); + public void Tick() { Set("_activity", BotActivity.Looting); Call("TickCorpseOpening"); } + } + + /// The loot clock and the pacer clock on one fake time. + private static void WithClock(Action, Action> body) + { + long now = 50_000_000; + var saved = RynthAiPlugin.CorpseClock; + RynthAiPlugin.CorpseClock = () => now; + ActionPacer.NowMs = () => now; + UseAudit.NowMs = () => now; + MoveAudit.NowMs = () => now; + try { body(() => now, ms => now += ms); } + finally { RynthAiPlugin.CorpseClock = saved; } + } + + private static void LootOneOpenPerAnswer() + { + LootWorld(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + PaceOn(); + try + { + WithClock((now, advance) => + { + for (int i = 0; i < 10 && FakeHost.Uses.Count == 0; i++) { bot.Tick(); advance(100); } + Check.Eq(FakeHost.Uses.Count, 1, "the open goes out"); + // A long walk: no answer for 3 s. Before, the open was re-sent every LootOpenRetryMs, + // and each re-send restarted the server's walk and failed the first open's callback. + for (int i = 0; i < 30; i++) { bot.Tick(); advance(100); } + Check.Eq(FakeHost.Uses.Count, 1, "not re-sent while the server hasn't answered"); + Check.True(Logged("[Pace] Loot waits: the use of"), "the wait is logged once"); + FakeHost.UseDone(0); + bot.P.OnViewObjectContents(FakeHost.Uses.Last()); + Check.True(ActionPacer.Current(host) == null, "answered: nothing outstanding"); + // The empty corpse is done; the next one is opened - once, and only now. + for (int i = 0; i < 20; i++) { bot.Tick(); advance(100); } + Check.Eq(FakeHost.Uses.Count, 2, "the next corpse's open went out after the answer, once"); + Check.Eq(FakeHost.Uses.Last(), CorpseB, "it is the other corpse"); + Check.True(ActionPacer.Current(host)?.Id == CorpseB, "and it is the action the server is answering now"); + Check.Eq(FakeHost.ForceResets, 0, "no force-clear"); + }); + } + finally { PaceOff(); } + } + + private static void LootStallStillDetected() + { + LootWorld(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + PaceOn(); + try + { + WithClock((now, advance) => + { + long answerAt = 0; + int maxOutstanding = 0; + void Step() + { + int uses = FakeHost.Uses.Count; + bot.Tick(); + if (FakeHost.Uses.Count > uses) answerAt = now() + 60; + maxOutstanding = Math.Max(maxOutstanding, FakeHost.Uses.Count - FakeHost.UseDoneSeq); + advance(100); + if (answerAt != 0 && now() >= answerAt) { FakeHost.UseDone(0); answerAt = 0; } + } + int steps = 0; + while (FakeHost.Chat.Count(c => c.Contains("isn't letting this character use objects")) == 0 && steps++ < 900) Step(); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("isn't letting this character use objects")), 1, + $"the stall is found and said once ({steps / 10.0} s)"); + Check.True(steps <= 600, $"within a minute ({steps / 10.0} s)"); + Check.True(maxOutstanding <= 1, $"never more than one open unanswered (max {maxOutstanding})"); + }); + } + finally { PaceOff(); } + } + + // ── Combat ─────────────────────────────────────────────────────────────────── + + private static void CombatPeaceWaitsForKit() => Paced(() => + { + var host = World(combatMode: 2); + FakeHost.Positions[Player] = Me0; + FakeHost.PlayerPose = Me0; + var s = new LegacyUiSettings { IsMacroRunning = true, EnableCombat = true, PeaceModeWhenIdle = true, MonsterRange = 50 }; + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + var combat = new CombatManager(host, s, cache); + combat.SetPlayerId(Player); + + // 07:00:11.8: a kit on yourself in melee stance; the server answers 2.4 s later. + host.UseOnFor(Kit, Player, "Buff", "vitals: healing kit on yourself"); + for (int i = 0; i < 5; i++) { combat.Think(); _t += 400; } + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no peace swap while the kit is unanswered"); + FakeHost.UseDone(0); + combat.Think(); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "the kit answered: the idle swap goes out"); + }); + + private static void ArbiterStopOnlyWhenMoving() + { + LootWorld(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + PaceOn(); + try + { + WithClock((now, advance) => + { + bot.Call("StopNavFor", BotActivity.Looting); + Check.Eq(FakeHost.Stops, 0, "nothing of ours moving: no StopCompletely (another plugin's movement isn't cut off)"); + host.SetAutoRunBy("Nav", true); + bot.Call("StopNavFor", BotActivity.Buffing); + Check.Eq(FakeHost.Stops, 1, "our autorun on: the stop goes out"); + ActionPacer.Enabled = false; + bot.Call("StopNavFor", BotActivity.Combat); + Check.Eq(FakeHost.Stops, 2, "pacing off: as before, always"); + }); + } + finally { PaceOff(); } + } + + // ── Busy mirror ────────────────────────────────────────────────────────────── + + private static void MirrorResetOnly() + { + // The engine's count is the owner: a mirror left up follows it down after 1.5 s. + LootWorld(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + WithClock((now, advance) => + { + FakeHost.BusyStateValue = 0; // the engine has seen the UseDones + bot.Set("_busyCount", 2); + bot.Set("_busyCountBecamePositiveAt", now()); + bot.Call("CheckBusyTimeout"); + Check.Eq(bot.Get("_busyCount"), 2, "a fresh disagreement waits (events may be on their way)"); + advance(1_600); + bot.Call("CheckBusyTimeout"); + Check.Eq(bot.Get("_busyCount"), 0, "1.6 s later: the mirror follows the engine's 0"); + Check.True(Logged("following the engine's count"), "logged"); + + FakeHost.BusyStateValue = 1; // the server owes an answer: the mirror follows that too + bot.Call("CheckBusyTimeout"); advance(1_600); bot.Call("CheckBusyTimeout"); + Check.Eq(bot.Get("_busyCount"), 1, "and up, while the server still owes an answer"); + advance(30_000); bot.Call("CheckBusyTimeout"); + Check.Eq(bot.Get("_busyCount"), 1, "never reset on a timer while the engine says busy"); + Check.Eq(FakeHost.ForceResets, 0, "the client's busy count is left to the client"); + }); + + // An engine without GetBusyState: the old timer, resetting the mirror only. + LootWorld(); + FakeHost.BusyCalls = false; + host = FakeHost.Create(Player); + bot = new Bot(host); + WithClock((now, advance) => + { + bot.Set("_busyCount", 2); + bot.Set("_busyCountBecamePositiveAt", now()); + advance(10_500); + bot.Call("CheckBusyTimeout"); + Check.Eq(bot.Get("_busyCount"), 0, "old engine: our mirror is reset after 10 s"); + Check.True(Logged("resetting the mirror only"), "and the line says so"); + }); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/InstallPathsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/InstallPathsTests.cs new file mode 100644 index 0000000..274112f --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/InstallPathsTests.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Install; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// RynthInstallPaths (Plugins/Shared/RynthInstallPaths.cs, compiled into RynthAi): where RynthSuite +// lives. Order is environment, HKCU, HKLM, then C:\Games\RynthSuite. The environment and the +// registry are a fake here; the real registry is only READ, for a value that does not exist. +// Idea from Silentkelpie (rynth PR #1); re-implemented here. +internal static class InstallPathsTests +{ + public static void Register(Runner r) + { + r.Add("install paths: nothing set gives C:\\Games\\RynthSuite and C:\\Games\\RynthCore", NothingSet); + r.Add("install paths: environment beats HKCU beats HKLM beats the default", Order); + r.Add("install paths: empty, relative and broken values are skipped", Unusable); + r.Add("install paths: folders with spaces", Spaces); + r.Add("install paths: a source that throws falls through to the default", Throwing); + r.Add("install paths: real registry, missing value reads as null (read only)", RealRegistryRead); + r.Add("install paths: on a default install RynthAi's folders are exactly the old ones", DefaultInstallUnchanged); + r.Add("install paths: same file as RynthCore src\\Shared (when the sibling is checked out)", SameAsRynthCore); + } + + private sealed class Fake : IInstallSettingSource + { + public readonly Dictionary Env = new(); + public readonly Dictionary User = new(); + public readonly Dictionary Machine = new(); + public int Asked; + public bool Throw; + + public string? EnvironmentVariable(string name) { Asked++; if (Throw) throw new InvalidOperationException(); return Env.GetValueOrDefault(name); } + public string? CurrentUser(string valueName) { Asked++; if (Throw) throw new UnauthorizedAccessException(); return User.GetValueOrDefault(valueName); } + public string? LocalMachine(string valueName) { Asked++; if (Throw) throw new IOException(); return Machine.GetValueOrDefault(valueName); } + } + + private static string Suite(Fake f) => RynthInstallPaths.Resolve(RynthInstallPaths.SuiteEnvironmentVariable, + RynthInstallPaths.SuiteValueName, RynthInstallPaths.DefaultSuiteDir, f); + + private static string Core(Fake f) => RynthInstallPaths.Resolve(RynthInstallPaths.CoreEnvironmentVariable, + RynthInstallPaths.CoreValueName, RynthInstallPaths.DefaultCoreDir, f); + + private static void NothingSet() + { + var f = new Fake(); + Check.Eq(Suite(f), @"C:\Games\RynthSuite", "suite default"); + Check.Eq(Core(f), @"C:\Games\RynthCore", "core default"); + Check.Eq(f.Asked, 6, "env, HKCU and HKLM asked for each folder"); + } + + private static void Order() + { + var f = new Fake(); + f.Machine["SuiteDir"] = @"D:\Machine\RynthSuite"; + Check.Eq(Suite(f), @"D:\Machine\RynthSuite", "HKLM beats the default"); + f.User["SuiteDir"] = @"E:\User\RynthSuite"; + Check.Eq(Suite(f), @"E:\User\RynthSuite", "HKCU beats HKLM"); + f.Env["RYNTHSUITE_DIR"] = @"F:\Dev\RynthSuite"; + Check.Eq(Suite(f), @"F:\Dev\RynthSuite", "environment beats HKCU"); + Check.Eq(Core(f), @"C:\Games\RynthCore", "suite settings leave the core folder alone"); + } + + private static void Unusable() + { + foreach (string? bad in new[] { null, "", " ", "RynthSuite", @"..\RynthSuite", "C:", "D:\\a|b", "D:\\a*", "D:\\x:y" }) + { + var f = new Fake(); + f.Env["RYNTHSUITE_DIR"] = bad; + f.User["SuiteDir"] = bad; + f.Machine["SuiteDir"] = bad; + Check.Eq(Suite(f), @"C:\Games\RynthSuite", $"'{bad}' everywhere -> default"); + } + } + + private static void Spaces() + { + var f = new Fake(); + f.User["SuiteDir"] = @"C:\Program Files (x86)\Rynth Suite\"; + Check.Eq(Suite(f), @"C:\Program Files (x86)\Rynth Suite", "HKCU value with spaces, trailing separator dropped"); + Check.Eq(Path.Combine(Suite(f), "RynthAi", "LootProfiles"), @"C:\Program Files (x86)\Rynth Suite\RynthAi\LootProfiles", "joined"); + var g = new Fake(); + g.Env["RYNTHSUITE_DIR"] = " \"D:\\My Games\\Rynth Suite\" "; + Check.Eq(Suite(g), @"D:\My Games\Rynth Suite", "quoted, padded environment value with spaces"); + } + + private static void Throwing() + { + var f = new Fake { Throw = true }; + Check.Eq(Suite(f), @"C:\Games\RynthSuite", "every source throws -> default"); + Check.Eq(f.Asked, 3, "all three tried"); + } + + private static void RealRegistryRead() + { + string missing = "NoSuchValue-" + Guid.NewGuid().ToString("N"); + Check.Null(SystemInstallSettings.Instance.CurrentUser(missing), "HKCU missing value"); + Check.Null(SystemInstallSettings.Instance.LocalMachine(missing), "HKLM missing value"); + Check.True(Path.IsPathFullyQualified(RynthInstallPaths.SuiteDir), "live SuiteDir is absolute: " + RynthInstallPaths.SuiteDir); + } + + private static void DefaultInstallUnchanged() + { + if (RynthInstallPaths.SuiteDir != RynthInstallPaths.DefaultSuiteDir) + { + Console.WriteLine($" (this machine sets the RynthSuite folder to {RynthInstallPaths.SuiteDir}; default-install check skipped)"); + return; + } + Check.Eq(RynthInstallPaths.RynthAiDir, @"C:\Games\RynthSuite\RynthAi", "RynthAi folder"); + Check.Eq(RynthCore.Plugin.RynthAi.Loot.LootEditorBridge.LootFolder, @"C:\Games\RynthSuite\RynthAi\LootProfiles", "loot profiles"); + Check.Eq(RynthCore.Plugin.RynthAi.Vendor.AutoVendorManager.MainProfileDir, @"C:\Games\RynthSuite\RynthAi\AutoVendor", "AutoVendor"); + Check.Eq(RynthCore.Plugin.RynthAi.Trade.AutoTradeManager.MainProfileDir, @"C:\Games\RynthSuite\RynthAi\AutoTrade", "AutoTrade"); + Check.Eq(RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder, @"C:\Games\RynthSuite\RynthAi\CreatureData", "creature data"); + Check.Eq(RynthCore.Plugin.RynthAi.CreatureData.CreatureWeakness.WeaknessFile, @"C:\Games\RynthSuite\RynthAi\Data\creature_weakness.json", "weakness file"); + Check.Eq(PrivateStatic(typeof(RynthCore.Plugin.RynthAi.RadarWallRenderer), "ExploredDir"), @"C:\Games\RynthSuite\RynthAi\ExploredDungeons", "explored dungeons"); + // The tests point the store at their scratch folder (Program.Main); this is its value before that. + Check.Eq(Program.LiveHazardFolder, @"C:\Games\RynthSuite\RynthAi\DungeonHazards", "dungeon hazards"); + } + + private static string? PrivateStatic(Type type, string field) + => type.GetField(field, BindingFlags.NonPublic | BindingFlags.Static)?.GetValue(null) as string; + + private static void SameAsRynthCore() + { + string here = Path.GetFullPath(Path.Combine(ThisFile(), "..", "..", "..", "..", "Plugins", "Shared", "RynthInstallPaths.cs")); + string sibling = Path.GetFullPath(Path.Combine(ThisFile(), "..", "..", "..", "..", "..", "RynthCore", "src", "Shared", "RynthInstallPaths.cs")); + Check.True(File.Exists(here), "RynthSuite copy found at " + here); + if (!File.Exists(sibling)) + { + Console.WriteLine($" (no RynthCore sibling at {sibling}; comparison skipped)"); + return; + } + Check.True(Text(here) == Text(sibling), + "Plugins\\Shared\\RynthInstallPaths.cs matches RynthCore src\\Shared\\RynthInstallPaths.cs"); + } + + private static string Text(string path) => File.ReadAllText(path).Replace("\r\n", "\n"); + + private static string ThisFile([CallerFilePath] string path = "") => path; +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTests.cs new file mode 100644 index 0000000..427b42f --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTests.cs @@ -0,0 +1,349 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.ItemInfo; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginCore; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// /ra iteminfo (Silentkelpie's rynth PR #1 idea, re-implemented): a Mag-Tools style one-line +// description of the selected or named item, identified first when the client hasn't +// appraised it. The formatter is checked on fake appraisal data; the command end to end on +// FakeHost (selection, ID request, the print when the ID lands, the timeout, name lookup). +internal static class ItemInfoTests +{ + private const uint Player = 0x50000F21; + private const uint Sword = 0x80300001, Ring = 0x80300002, Scarab = 0x80300003, Scarab2 = 0x80300004; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static; + + public static void Register(Runner r) + { + r.Add("iteminfo: a weapon's damage, mods, imbue, slayer, spells and wield line", WeaponLine); + r.Add("iteminfo: armor's set, AL, ratings, tinks and wield level", ArmorLine); + r.Add("iteminfo: jewelry with mana, diff and craft; a bare item stays short", JewelryAndBareItem); + r.Add("iteminfo: a selected item already appraised prints at once, no ID", SelectedAppraised); + r.Add("iteminfo: an unappraised item is identified, then printed when the ID lands", IdentifiesThenPrints); + r.Add("iteminfo: no reply prints what the client has after the timeout", TimeoutPrints); + r.Add("iteminfo: a name picks the inventory item, exact before partial", NameLookup); + r.Add("iteminfo: nothing selected or no such item says so", NothingSelected); + r.Add("iteminfo on select: the player's pick prints quietly; the bot's own picks and the setting off do not", OnSelect); + } + + // ── Fake appraisal data ───────────────────────────────────────────── + + private sealed class Fake : IItemInfoSource + { + public string Name { get; init; } = ""; + public Dictionary Ints { get; } = new(); + public Dictionary Floats { get; } = new(); + public List Spells { get; } = new(); + public IReadOnlyList SpellIds => Spells; + public bool TryInt(uint key, out int value) => Ints.TryGetValue(key, out value); + public bool TryFloat(uint key, out double value) => Floats.TryGetValue(key, out value); + } + + private static string Spell(int id) => SpellDatabase.GetSpellName(id); + + /// Each part appears, in this order. + private static void InOrder(string text, string[] parts, string what) + { + int at = 0; + foreach (string p in parts) + { + int i = text.IndexOf(p, at, StringComparison.Ordinal); + Check.True(i >= 0, $"{what}: has \"{p}\" after position {at} in: {text}"); + if (i >= 0) at = i + p.Length; + } + } + + private static void WeaponLine() + { + var w = new Fake { Name = "Ornate Katar" }; + w.Ints[ItemInfoText.IntItemType] = 0x1; + w.Ints[ItemInfoText.IntMaterial] = 61; // Iron + w.Ints[ItemInfoText.IntWeaponSkill] = 44; // Heavy Weapons + w.Ints[ItemInfoText.IntDamage] = 77; + w.Floats[ItemInfoText.FloatDamageVariance] = 0.4; + w.Ints[ItemInfoText.IntDamageType] = 16; // Fire + w.Ints[ItemInfoText.IntWeaponTime] = 30; + w.Floats[ItemInfoText.FloatWeaponOffense] = 1.18; + w.Floats[ItemInfoText.FloatMeleeDefense] = 1.20; + w.Floats[ItemInfoText.FloatMagicDefense] = 1.0; // +0%: left out + w.Ints[ItemInfoText.IntImbued] = 0x2 | 0x200; // Crippling Blow, Fire Rending + w.Ints[ItemInfoText.IntSlayerType] = 14; // Undead + w.Ints[ItemInfoText.IntTinks] = 2; + w.Spells.AddRange(new[] { 2531, 6107, 2531 }); // a repeat is named once + w.Ints[ItemInfoText.IntWieldReq] = 1; + w.Ints[ItemInfoText.IntWieldSkill] = 44; + w.Ints[ItemInfoText.IntWieldDiff] = 375; + w.Ints[ItemInfoText.IntWieldReq2] = 7; + w.Ints[ItemInfoText.IntWieldDiff2] = 150; + w.Ints[ItemInfoText.IntItemDifficulty] = 300; + w.Ints[ItemInfoText.IntWorkmanship] = 9; + w.Ints[ItemInfoText.IntValue] = 12345; + w.Ints[ItemInfoText.IntEncumbrance] = 350; + w.Ints[ItemInfoText.Ratings[0].Key] = 2; // D2 + + string s = ItemInfoText.Describe(w, Spell); + InOrder(s, new[] + { + "Iron Ornate Katar (Melee Weapon)", "[D2]", "Heavy Weapons", "Dmg 46-77 Fire", "Speed 30", + "(+18% atk, +20% md)", "Crippling Blow, Fire Rending", "Undead Slayer", "Tinks 2", + "Spells: Major Heavy Weapon Aptitude, Legendary Strength", "Heavy Weapons 375 to wield", + "Wield Lvl 150", "Diff 300", "Craft 9", "Mat Iron", "Value 12,345", "BU 350", + }, "weapon"); + Check.False(s.Contains("mgd"), "a +0% mod is left out"); + Check.Eq(s.Split("Major Heavy Weapon Aptitude").Length, 2, "each spell named once"); + Check.False(s.Contains("not identified"), "identified: no note"); + } + + private static void ArmorLine() + { + var a = new Fake { Name = "Chainmail Tassets" }; + a.Ints[ItemInfoText.IntItemType] = 0x2; + a.Ints[ItemInfoText.IntSetId] = 16; // Defender's + a.Ints[ItemInfoText.IntArmorLevel] = 584; + a.Ints[371] = 1; // DR1 + a.Ints[375] = 2; // CDR2 + a.Ints[ItemInfoText.IntTinks] = 3; + a.Ints[ItemInfoText.IntWieldReq] = 7; + a.Ints[ItemInfoText.IntWieldDiff] = 180; + a.Ints[ItemInfoText.IntMaterial] = 64; // Steel + string s = ItemInfoText.Describe(a, Spell); + InOrder(s, new[] { "Steel Chainmail Tassets (Armor)", "Defender's Set", "AL 584", "[DR1 CDR2]", "Tinks 3", "Wield Lvl 180", "Mat Steel" }, "armor"); + Check.False(s.Contains("Dmg"), "armor shows no damage"); + Check.False(s.Contains("Speed"), "or speed"); + } + + private static void JewelryAndBareItem() + { + var j = new Fake { Name = "Gold Ring" }; + j.Ints[ItemInfoText.IntItemType] = 0x8; + j.Ints[ItemInfoText.IntMaterial] = 60; // Gold: already in the name + j.Ints[ItemInfoText.IntCurMana] = 1200; + j.Ints[ItemInfoText.IntMaxMana] = 1500; + j.Ints[ItemInfoText.IntItemDifficulty] = 285; + j.Ints[ItemInfoText.IntWorkmanship] = 7; + j.Ints[ItemInfoText.IntAttuned] = 1; + j.Spells.Add(3964); + string s = ItemInfoText.Describe(j, Spell); + InOrder(s, new[] { "Gold Ring (Jewelry)", "Spells: Epic Focus", "Diff 285", "Mana 1200/1500", "Craft 7", "Mat Gold", "Attuned" }, "jewelry"); + Check.False(s.Contains("Gold Gold"), "the material isn't doubled"); + Check.False(s.Contains("AL "), "jewelry with no armor shows no AL"); + + var bare = new Fake { Name = "Mana Scarab" }; + bare.Ints[ItemInfoText.IntStackSize] = 25; + string b = ItemInfoText.Describe(bare, Spell, identified: false); + Check.True(b.StartsWith("Mana Scarab x25", StringComparison.Ordinal), $"a stack shows its size: {b}"); + Check.True(b.EndsWith("(not identified: no reply from the server)", StringComparison.Ordinal), "unidentified note last"); + Check.Eq(b.Split(", ").Length, 2, "nothing else is made up"); + } + + // ── The command on FakeHost ───────────────────────────────────────── + + private sealed class World + { + public readonly RynthAiPlugin P = new(); + public readonly WorldObjectCache Cache; + public long Now = 1_000_000; + + public World() + { + FakeHost.Reset(); + FakeHost.Names[Player] = "Reader"; + FakeHost.PlayerIdValue = Player; + FakeHost.Positions[Player] = (0x1048002Au, 100f, 100f, 0f); + FakeHost.PlayerPose = (0x1048002Au, 100f, 100f, 0f); + Item(Sword, "Ornate Katar", 0x1); + Item(Ring, "Gold Ring", 0x8); + Item(Scarab, "Mana Scarab", 0x80); + Item(Scarab2, "Platinum Scarab", 0x80); + FakeHost.Ints[(Sword, ItemInfoText.IntDamage)] = 77; + FakeHost.Ints[(Sword, ItemInfoText.IntWorkmanship)] = 9; + FakeHost.Ints[(Ring, ItemInfoText.IntWorkmanship)] = 7; + FakeHost.SpellIds[Ring] = new uint[] { 3964 }; + FakeHost.WeaponCalls = true; // RequestId + HasAppraisalData + var host = FakeHost.Create(playerId: Player); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, new LegacyUiSettings()); + Set("_dashboard", dash); + Cache = new WorldObjectCache(host); + Cache.SetPlayerId(Player); + Set("_objectCache", Cache); + Set("_playerId", Player); + Set("_initialized", true); + Set("_loginComplete", true); + foreach (uint id in new[] { Sword, Ring, Scarab, Scarab2 }) Cache.OnCreateObject(id); + Cache.Tick(); + RynthAiPlugin.ItemInfoClock = () => Now; + } + + private static void Item(uint id, string name, uint type) + { + FakeHost.Names[id] = name; + FakeHost.Containers[id] = Player; + FakeHost.ItemTypes[id] = type; + FakeHost.Ints[(id, ItemInfoText.IntItemType)] = (int)type; + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + + public void Command(string text) + { + string[] parts = text.Split(' ', StringSplitOptions.RemoveEmptyEntries); + typeof(RynthAiPlugin).GetMethod("HandleItemInfoCommand", Any)!.Invoke(P, new object[] { parts }); + } + + public void Tick() => typeof(RynthAiPlugin).GetMethod("TickItemInfo", Any)!.Invoke(P, null); + + public string[] InfoLines => FakeHost.Chat.Where(c => c.StartsWith("[RynthAi] ", StringComparison.Ordinal)).ToArray(); + } + + private static void Done() => RynthAiPlugin.ItemInfoClock = () => Environment.TickCount64; + + private static void OnSelect() + { + var w = new World(); + try + { + void Select(uint id) => typeof(RynthAiPlugin).GetMethod("QueueItemInfoOnSelect", Any)! + .Invoke(w.P, new object?[] { id, w.Cache[unchecked((int)id)] }); + + FakeHost.Appraised.Add(Ring); + Select(Ring); + w.Tick(); + Check.Eq(w.InfoLines.Length, 1, "the player's pick prints once"); + Check.True(w.InfoLines[0].Contains("Gold Ring (Jewelry)"), $"the ring's line: {w.InfoLines.FirstOrDefault()}"); + + Select(Sword); + w.Tick(); + Check.Eq(w.InfoLines.Length, 1, "unappraised: no 'identifying' chatter on select"); + Check.True(FakeHost.IdRequests.Contains(Sword), "but the ID is asked for"); + FakeHost.Appraised.Add(Sword); + w.Tick(); + Check.Eq(w.InfoLines.Length, 2, "printed when the appraisal lands"); + + SelfSelect.Mark(Ring); + Select(Ring); + w.Tick(); + Check.Eq(w.InfoLines.Length, 2, "an item RynthAi selected itself (the looter, a meta) prints nothing"); + + var dash = (LegacyDashboardRenderer)typeof(RynthAiPlugin).GetField("_dashboard", Any)!.GetValue(w.P)!; + dash.Settings.ItemInfoOnSelect = false; + Select(Scarab); + w.Tick(); + Check.Eq(w.InfoLines.Length, 2, "setting off: nothing"); + } + finally { Done(); } + } + + private static void SelectedAppraised() + { + var w = new World(); + try + { + FakeHost.SelectedItem = Ring; + FakeHost.Appraised.Add(Ring); + w.Command("/ra iteminfo"); + Check.Eq(FakeHost.Chat.Count, 0, "the command only queues (the tick prints)"); + w.Tick(); + Check.Eq(FakeHost.IdRequests.Count, 0, "appraised: no ID request"); + Check.Eq(w.InfoLines.Length, 1, "one line"); + Check.True(w.InfoLines[0].Contains("Gold Ring (Jewelry)") && w.InfoLines[0].Contains("Spells: Epic Focus") && w.InfoLines[0].Contains("Craft 7"), + $"the ring's line: {w.InfoLines.FirstOrDefault()}"); + } + finally { Done(); } + } + + private static void IdentifiesThenPrints() + { + var w = new World(); + try + { + FakeHost.SelectedItem = Sword; + w.Command("/ra iteminfo"); + w.Tick(); + Check.True(FakeHost.IdRequests.SequenceEqual(new[] { Sword }), "one ID request for the sword"); + Check.Eq(w.InfoLines.Length, 1, "just the 'identifying' line so far"); + Check.True(w.InfoLines[0].Contains("identifying Ornate Katar"), "says it is identifying"); + w.Now += 1000; + w.Tick(); + Check.Eq(w.InfoLines.Length, 1, "still waiting a second later"); + FakeHost.Appraised.Add(Sword); + w.Tick(); + Check.Eq(w.InfoLines.Length, 2, "printed when the appraisal arrives"); + Check.True(w.InfoLines[1].Contains("Ornate Katar (Melee Weapon)") && w.InfoLines[1].Contains("Dmg 77") && !w.InfoLines[1].Contains("not identified"), + $"the sword's line: {w.InfoLines[1]}"); + w.Now += 10_000; + w.Tick(); + Check.Eq(w.InfoLines.Length, 2, "printed once"); + Check.Eq(FakeHost.IdRequests.Count, 1, "never asked twice"); + } + finally { Done(); } + } + + private static void TimeoutPrints() + { + var w = new World(); + try + { + FakeHost.SelectedItem = Sword; + w.Command("/ra iteminfo"); + w.Tick(); + w.Now += RynthAiPlugin.ItemInfoTimeoutMs - 1; + w.Tick(); + Check.Eq(w.InfoLines.Length, 1, "not before the timeout"); + w.Now += 1; + w.Tick(); + Check.Eq(w.InfoLines.Length, 2, "printed at the timeout"); + Check.True(w.InfoLines[1].Contains("Ornate Katar") && w.InfoLines[1].EndsWith("(not identified: no reply from the server)", StringComparison.Ordinal), + $"with what the client has and the note: {w.InfoLines[1]}"); + } + finally { Done(); } + } + + private static void NameLookup() + { + var w = new World(); + try + { + FakeHost.Appraised.Add(Scarab); + FakeHost.Appraised.Add(Scarab2); + FakeHost.Appraised.Add(Ring); + w.Command("/ra iteminfo mana scarab"); + w.Tick(); + Check.True(w.InfoLines.Last().StartsWith("[RynthAi] Mana Scarab", StringComparison.Ordinal), $"exact name, any case: {w.InfoLines.Last()}"); + w.Command("/ra iteminfo Scarab"); + w.Tick(); + Check.True(w.InfoLines.Last().Contains("Scarab") && !w.InfoLines.Last().Contains("not in your"), "a partial name finds a scarab"); + w.Command("/ra iteminfo ring"); + w.Tick(); + Check.True(w.InfoLines.Last().StartsWith("[RynthAi] Gold Ring", StringComparison.Ordinal), "partial: Gold Ring"); + Check.Eq(FakeHost.SelectedItem, 0u, "a named lookup doesn't need a selection"); + } + finally { Done(); } + } + + private static void NothingSelected() + { + var w = new World(); + try + { + w.Command("/ra iteminfo"); + w.Tick(); + Check.True(w.InfoLines.Length == 1 && w.InfoLines[0].Contains("nothing selected"), "nothing selected says so"); + w.Command("/ra iteminfo Shield of Nowhere"); + w.Tick(); + Check.True(w.InfoLines.Last().Contains("no \"Shield of Nowhere\" in your inventory"), $"unknown name says so: {w.InfoLines.Last()}"); + Check.Eq(FakeHost.IdRequests.Count, 0, "and nothing is identified"); + } + finally { Done(); } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootAddItemTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootAddItemTests.cs index a15fbc6..a574943 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootAddItemTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootAddItemTests.cs @@ -42,7 +42,7 @@ internal static class LootAddItemTests r.Add("loot add: the popup's item_preview / item_add / item_close through the editor bridge", BridgePopupFlow); r.Add("loot add: unsaved edits in the Loot Editor block the add (nothing saved behind them)", BridgeRefusesUnderEdits); r.Add("loot add: the popup says when RynthAi's built-in looting takes the item (Mana Tap, mana stones)", BuiltInReasons); - r.Add("loot: Mana Tap never loots a wand (ACE won't drain one, so it was kept for good)", ManaTapSkipsWands); + r.Add("loot: Mana Tap takes a high-mana wand like any other item (they drain)", ManaTapTakesWands); } // ── World and plugin ────────────────────────────────────────────────────── @@ -445,16 +445,13 @@ internal static class LootAddItemTests Check.Eq(File.ReadAllText(path), SellGems, "preview saves nothing"); } - private static void ManaTapSkipsWands() + private static void ManaTapTakesWands() { var bot = TapWorld(); bot.S.CurrentLootPath = Temp("wand.utl", SellGems); var wand = LootEval(bot, Sceptre); - Check.False(wand.Taken, $"a 3,001-mana sceptre is left: [{wand.Action}] {wand.Rule}"); - Check.Eq(bot.Get>("_pendingManaTapIds")?.Count, 0, "not counted against the tap quota"); + Check.True(wand.Taken && wand.Action == "ManaTap", $"a 3,001-mana sceptre is tapped: [{wand.Action}] {wand.Rule}"); var ring = LootEval(bot, Ring); - Check.True(ring.Taken && ring.Action == "ManaTap", "a ring with the same mana is still tapped: " + ring.Action); - Send(bot.P.LootEditor, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Sceptre, Seq = 1 } }); - Check.Eq(State(bot.P.LootEditor).ItemDraft?.BuiltInReason, "", "the popup has no built-in reason for the wand"); + Check.False(ring.Taken, "the one empty stone is now spoken for by the wand, so the ring waits: " + ring.Action); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs index d877754..5259fc1 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs @@ -59,6 +59,127 @@ internal static class MetaTests SecondsInStatePPersists); r.Add("meta: MainHealthPHE / MainManaPHE mean 'percent >='", PercentConditionsAreGE); // was a known failure; fixed by a7c4618 r.Add("meta: a negative vital threshold never holds", NegativeVitalThreshold); // was a known failure; fixed by 6f72b67 + r.Add("meta edit: saving a rule keeps the running meta's state, clocks and latch", EditKeepsRunningMeta); + r.Add("meta edit: a saved rule keeps CallState's return state and ChatCapture's colours", EditKeepsHiddenFields); + r.Add("meta edit: the editor's Set current text matches the landblock / landcell", SetCurrentMatches); + r.Add("meta edit: a new state's Never -> None rule keeps it through a save and reload", NewStateSurvivesReload); + } + + private static void SetCurrentMatches() + { + FakeHost.Reset(); + foreach (uint cell in new uint[] { 0xA9B4001Cu, 0x00070143u, 0x8B370105u, 0x0001FFFEu }) + { + FakeHost.PlayerPose = (cell, 10f, 10f, 0f); + var rig = new Rig(FakeHost.Create(), Player); + string block = RynthCore.Engine.UI.Data.MetaLocation.Text(RynthCore.Engine.UI.Data.MetaLocation.LandblockCondition, cell)!; + string here = RynthCore.Engine.UI.Data.MetaLocation.Text(RynthCore.Engine.UI.Data.MetaLocation.LandcellCondition, cell)!; + Check.True(rig.Holds(C.Landblock_EQ, block), $"Landblock == {block} holds at {cell:X8}"); + Check.True(rig.Holds(C.Landcell_EQ, here), $"Landcell == {here} holds at {cell:X8}"); + FakeHost.PlayerPose = (cell + 0x00010000u, 10f, 10f, 0f); + Check.False(rig.Holds(C.Landblock_EQ, block), $"not in the next landblock ({cell:X8})"); + FakeHost.PlayerPose = (cell + 1, 10f, 10f, 0f); + Check.False(rig.Holds(C.Landcell_EQ, here), $"not in the next cell ({cell:X8})"); + } + } + + private static void NewStateSurvivesReload() + { + // What "+ New state..." adds (engine MetaRuleEdit.Placeholder): Never -> None in the new state. + var rules = new List + { + Rule("Default", C.Always, "", A.SetMetaState, "Loot"), + new() { State = "Loot", Condition = C.Never, Action = A.None }, + }; + string text = AfFileWriter.SaveToString(rules, new Dictionary>()); + var back = AfFileParser.LoadFromText(text); + Check.Eq(back.Rules.Count, 2, "both rules back"); + var loot = back.Rules.FirstOrDefault(x => x.State == "Loot"); + Check.NotNull(loot, "the new state is still there"); + if (loot != null) + { + Check.Eq(loot.Condition, C.Never, "Never"); + Check.Eq(loot.Action, A.None, "None"); + } + + // It never fires, and SetState into it just sits there. + var rig = new Rig(rules: new[] { Rule("Default", C.Always, "", A.SetMetaState, "Loot"), Mark("Loot", C.Never, "", "x") }); + rig.Tick(); + rig.Tick(5); + Check.Eq(rig.S.CurrentState, "Loot", "moved into the new state"); + Check.False(rig.Has("x"), "its Never rule never fires"); + } + + // ── Panel edits on a running meta (MetaRuleEdits, update_rule; 2026-10-05 autosave) ───── + + private static void EditKeepsRunningMeta() + { + var rig = new Rig(rules: new[] + { + Mark("Default", C.Always, "", "a"), + Mark("Default", C.SecondsInState_GE, "10", "t"), + }); + rig.Tick(); + Check.Eq(rig.Var("a"), "1", "the Always rule fired on entry"); + rig.Tick(6); + + // What the editor's autosave sends: an edited copy of rule 0, then the structural bump + // TryAutoSaveMetaCmd makes. + MetaRule edited = Mark("Default", C.Always, "", "a"); + edited.ActionData = "setvar[a, getvar[a]+10]"; + Check.True(MetaRuleEdits.Replace(rig.S.MetaRules, 0, edited), "replaced"); + rig.S.MetaRulesStructuralVersion++; + rig.Tick(); + Check.Eq(rig.Var("a"), "1", "the edited rule did not fire again (latch kept)"); + Check.Eq(rig.S.CurrentState, "Default", "state unchanged"); + Check.Near(rig.M.GetStateSnapshot().SecondsInState, 6, 1e-9, "seconds in state not restarted"); + rig.Tick(4.5); + Check.Eq(rig.Var("t"), "1", "the 10 s rule fired on the original clock"); + + // A real state entry re-arms it, now with the edited action. + rig.S.ForceStateReset = true; + rig.Tick(); + Check.Eq(rig.Var("a"), "11", "re-armed by a state entry, runs the edited action"); + + // Out of range: nothing changes. + Check.False(MetaRuleEdits.Replace(rig.S.MetaRules, 5, Mark("Default", C.Never, "", "z")), "bad index refused"); + Check.Eq(rig.S.MetaRules.Count, 2, "rule count unchanged"); + + // Before the fix (a plain replace) the same edit fired the rule again. + var old = new Rig(rules: new[] { Mark("Default", C.Always, "", "a") }); + old.Tick(); + old.S.MetaRules[0] = Mark("Default", C.Always, "", "a"); + old.S.MetaRulesStructuralVersion++; + old.Tick(); + Check.Eq(old.Var("a"), "2", "a plain replace re-fires (what MetaRuleEdits prevents)"); + } + + private static void EditKeepsHiddenFields() + { + var call = new MetaRule + { + State = "Default", Condition = C.ChatMessageCapture, ConditionData = "x", ChatColors = "2;4", + Action = A.CallMetaState, ActionData = "Buff", CallReturnState = "Hunt", + }; + var rules = new List { call }; + // The panel's DTO carries neither field. + var edited = new MetaRule { State = "Default", Condition = C.ChatMessageCapture, ConditionData = "y", Action = A.CallMetaState, ActionData = "Buff2" }; + MetaRuleEdits.Replace(rules, 0, edited); + Check.Eq(rules[0].CallReturnState, "Hunt", "CallState return kept"); + Check.Eq(rules[0].ChatColors, "2;4", "ChatCapture colours kept"); + Check.Eq(rules[0].ActionData, "Buff2", "the edit applied"); + + // Changing the action / condition drops them. + var other = new MetaRule { State = "Default", Condition = C.Always, Action = A.SetMetaState, ActionData = "Buff" }; + MetaRuleEdits.Replace(rules, 0, other); + Check.Eq(rules[0].CallReturnState, "", "not a CallState any more"); + Check.Eq(rules[0].ChatColors, "", "not a ChatCapture any more"); + + // Nested: an All's ChatCapture child by position. + var parent = new MetaRule { Condition = C.All, Children = { new MetaRule { Condition = C.ChatMessageCapture, ChatColors = "7" } } }; + var parentEdit = new MetaRule { Condition = C.All, Children = { new MetaRule { Condition = C.ChatMessageCapture, ConditionData = "z" } } }; + MetaRuleEdits.KeepHidden(parent, parentEdit); + Check.Eq(parentEdit.Children[0].ChatColors, "7", "child colours kept"); } // ── Rig ─────────────────────────────────────────────────────────────────── diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs new file mode 100644 index 0000000..23dfedc --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text.Json; +using RynthCore.MonsterEditor; +using RynthCore.Plugin.RynthAi; +using RynthCore.RynthAiTests.Harness; +using EditorRule = RynthCore.MonsterEditor.MonsterRule; +using PluginRule = RynthCore.Plugin.RynthAi.LegacyUi.MonsterRule; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The standalone Monster Editor (Tools/RynthCore.MonsterEditor; Models.cs, JsonContext.cs and +// MonsterRulesFile.cs compiled in) reads and writes the plugin's monsters file. Before 2026-10-05 +// its MonsterRule had no Category or MatchExpression (or CustomDebuffs), so an editor save +// dropped them and an expression rule fell back to matching by name only. Spotted by +// Silentkelpie (rynth PR #1); re-implemented here. Every file goes through the plugin's own +// serializer (RynthAiJsonContext) on the way in and out. +internal static class MonsterEditorTests +{ + public static void Register(Runner r) + { + r.Add("monster editor: a plugin file round-trips through the editor (every field kept)", RoundTripKeepsEveryField); + r.Add("monster editor: Category and MatchExpression load, edit and save", CategoryAndMatchEditable); + r.Add("monster editor: unknown fields survive, files without the new fields still load", UnknownAndOldFields); + r.Add("monster editor: a character folder opens the plugin's MonsterProfiles file", FindsThePluginsFile); + } + + private static string Dir(string name) + { + string dir = Path.Combine(Program.TempRoot, "monster-editor", name); + Directory.CreateDirectory(dir); + return dir; + } + + private static List PluginRules() => new() + { + new PluginRule { Name = "Default", Priority = 1 }, + new PluginRule + { + Name = "Olthoi", Category = "Olthoi nest", MatchExpression = "getcharintprop[25]>=200", + Priority = 3, DamageType = "Acid", WeaponId = 0x50001234, Fester = true, Broadside = true, + GravityWell = true, Imperil = true, Yield = true, Vuln = true, UseArc = true, UseRing = true, + UseStreak = true, UseBolt = false, UseBlast = true, ExVuln = "Fire", OffhandId = 2, + PetDamage = "Cold", CustomDebuffs = "Corrosion Vulnerability Other, Fire Vulnerability Other VII", + }, + new PluginRule { Name = "", Category = "Expression only", MatchExpression = "wobjectfindnearestbytemplatetype[1]" }, + }; + + private static string WriteAsPlugin(string dir, List rules) + { + string path = Path.Combine(dir, "Toon.json"); + File.WriteAllText(path, JsonSerializer.Serialize(rules, RynthAiJsonContext.Default.MonsterRuleList)); + return path; + } + + private static List ReadAsPlugin(string path) => + JsonSerializer.Deserialize(File.ReadAllText(path), RynthAiJsonContext.Default.MonsterRuleList)!; + + /// Every public property of the plugin's rule, compared one by one. + private static void SameRules(List actual, List expected, string what) + { + Check.Eq(actual.Count, expected.Count, what + ": rule count"); + PropertyInfo[] props = typeof(PluginRule).GetProperties(BindingFlags.Public | BindingFlags.Instance); + Check.True(props.Any(p => p.Name == "MatchExpression") && props.Any(p => p.Name == "Category"), "the plugin's rule has both fields"); + for (int i = 0; i < Math.Min(actual.Count, expected.Count); i++) + foreach (PropertyInfo p in props) + Check.Eq(p.GetValue(actual[i])?.ToString(), p.GetValue(expected[i])?.ToString(), $"{what}: rule {i} {p.Name}"); + } + + private static void RoundTripKeepsEveryField() + { + List original = PluginRules(); + string path = WriteAsPlugin(Dir("roundtrip"), original); + + // Open in the editor, change one thing (as a grid edit does), save. + List rules = MonsterRulesFile.Load(path); + Check.Eq(rules.Count, 3, "editor loads every rule"); + rules[1].Priority = 4; + MonsterRulesFile.Save(path, rules); + + List back = ReadAsPlugin(path); + original[1].Priority = 4; + SameRules(back, original, "after an editor save"); + + // A second save with no edits changes nothing more. + MonsterRulesFile.Save(path, MonsterRulesFile.Load(path)); + SameRules(ReadAsPlugin(path), original, "after a second save"); + string json = File.ReadAllText(path); + Check.Eq(CountOf(json, "\"MatchExpression\""), 3, "MatchExpression written once per rule"); + Check.Eq(CountOf(json, "\"CustomDebuffs\""), 3, "CustomDebuffs written once per rule"); + } + + private static void CategoryAndMatchEditable() + { + string path = WriteAsPlugin(Dir("edit"), PluginRules()); + List rules = MonsterRulesFile.Load(path); + Check.Eq(rules[1].Category, "Olthoi nest", "Category read"); + Check.Eq(rules[1].MatchExpression, "getcharintprop[25]>=200", "MatchExpression read"); + + var changed = new List(); + rules[1].PropertyChanged += (_, e) => changed.Add(e.PropertyName ?? ""); + rules[1].MatchExpression = ""; // back to matching by name + rules[1].Category = null!; // a cleared grid cell + Check.True(changed.Contains("MatchExpression") && changed.Contains("Category"), "edits raise PropertyChanged (the editor saves on it)"); + rules[2].MatchExpression = "true"; + MonsterRulesFile.Save(path, rules); + + List back = ReadAsPlugin(path); + Check.Eq(back[1].MatchExpression, "", "cleared expression saved"); + Check.Eq(back[1].Category, "", "a null Category is saved as empty"); + Check.Eq(back[2].MatchExpression, "true", "edited expression saved"); + Check.Eq(back[2].Category, "Expression only", "untouched Category kept"); + + // A rule added in the editor carries the plugin's defaults for the new fields. + var added = new EditorRule { Name = "Drudge" }; + Check.Eq(added.Category, "", "new rule: empty Category"); + Check.Eq(added.MatchExpression, "", "new rule: empty MatchExpression (by name)"); + } + + private static void UnknownAndOldFields() + { + string dir = Dir("unknown"); + string path = Path.Combine(dir, "Toon.json"); + // A field neither side knows yet (a later plugin), a nested value, and a file from before + // Category/MatchExpression existed (no such keys at all). + File.WriteAllText(path, """ + [ + { "Name": "Default", "Priority": 1 }, + { "Name": "Mosswart", "Priority": 2, "FutureField": { "A": [1, 2], "B": null }, "Shout": "hi" } + ] + """); + List rules = MonsterRulesFile.Load(path); + Check.Eq(rules[1].Category, "", "old file: Category empty"); + Check.Eq(rules[1].MatchExpression, "", "old file: MatchExpression empty"); + MonsterRulesFile.Save(path, rules); + + using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path)); + JsonElement mosswart = doc.RootElement[1]; + Check.True(mosswart.TryGetProperty("FutureField", out JsonElement future), "unknown field kept"); + Check.Eq(future.GetRawText().Replace(" ", "").Replace("\r", "").Replace("\n", ""), """{"A":[1,2],"B":null}""", "unknown field value unchanged"); + Check.Eq(mosswart.GetProperty("Shout").GetString(), "hi", "unknown string kept"); + Check.Eq(ReadAsPlugin(path)[1].Priority, 2, "the plugin still reads the file"); + } + + // The plugin launches the editor with the character's settings folder + // (SettingsProfiles\\) but reads MonsterProfiles\\.json + // (LegacyDashboardRenderer.MonstersFilePath); the editor used to open \monsters.json. + private static void FindsThePluginsFile() + { + string root = Dir("paths"); + string Rel(params string[] parts) => Path.Combine(new[] { root }.Concat(parts).ToArray()); + string aelChar = Rel("SettingsProfiles", "Aelrynth", "Toon"); + string aceChar = Rel("SettingsProfiles", "ACEmulator", "Toon"); + Directory.CreateDirectory(aelChar); + Directory.CreateDirectory(aceChar); + string aelFile = Rel("MonsterProfiles", "Aelrynth", "Toon.json"); + string aceFile = Rel("MonsterProfiles", "Toon.json"); + + // Not there yet: the plugin's path (a save creates it where the plugin reads). + Check.Eq(MonsterRulesFile.ResolveRulesPath(aelChar), aelFile, "server folder -> MonsterProfiles\\\\.json"); + Check.Eq(MonsterRulesFile.ResolveRulesPath(aceChar + "\\"), aceFile, "ACEmulator -> MonsterProfiles\\.json (trailing slash ok)"); + Check.Eq(MonsterRulesFile.ResolveRulesPath("\"" + aelChar + "\""), aelFile, "quoted argument"); + + // Only the old file exists: that one (the plugin moves it across at its next load). + string legacy = Path.Combine(aelChar, "monsters.json"); + File.WriteAllText(legacy, "[]"); + Check.Eq(MonsterRulesFile.ResolveRulesPath(aelChar), legacy, "only the old monsters.json: use it"); + + // Both: the plugin's. + Directory.CreateDirectory(Path.GetDirectoryName(aelFile)!); + File.WriteAllText(aelFile, "[]"); + Check.Eq(MonsterRulesFile.ResolveRulesPath(aelChar), aelFile, "both exist: the plugin's file"); + + // A file is edited as given; a folder outside SettingsProfiles keeps the old behaviour. + Check.Eq(MonsterRulesFile.ResolveRulesPath(aelFile), aelFile, "a file opens as is"); + string loose = Rel("Elsewhere", "Toon"); + Check.Eq(MonsterRulesFile.ResolveRulesPath(loose), Path.Combine(loose, "monsters.json"), "unknown layout: \\monsters.json"); + + // And back: the settings folder for the weapon list. + Check.Eq(MonsterRulesFile.CharFolderForRulesPath(aelFile), aelChar, "MonsterProfiles\\ file -> its settings folder"); + Check.Eq(MonsterRulesFile.CharFolderForRulesPath(aceFile), aceChar, "MonsterProfiles file -> SettingsProfiles\\ACEmulator"); + Check.Eq(MonsterRulesFile.CharFolderForRulesPath(legacy), aelChar, "old monsters.json -> its own folder"); + Check.Eq(MonsterRulesFile.CharFolderForRulesPath(Rel("Elsewhere", "x.json")), Rel("Elsewhere"), "unknown layout -> the file's folder"); + + // The plugin's own path for this character agrees. + Check.Eq(MonsterRulesFile.PluginRulesPathForCharFolder(aelChar), aelFile, "PluginRulesPathForCharFolder"); + Check.Null(MonsterRulesFile.PluginRulesPathForCharFolder(loose), "not under SettingsProfiles: null"); + } + + private static int CountOf(string text, string what) + { + int n = 0; + for (int i = text.IndexOf(what, StringComparison.Ordinal); i >= 0; i = text.IndexOf(what, i + what.Length, StringComparison.Ordinal)) + n++; + return n; + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs index 7d2d6c8..b6ec94c 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs @@ -54,7 +54,7 @@ internal static class NavEngineTests r.Add("nav point reach: values under 1.5 yd work (it used to be floored at 1.5)", ReachBelowOneAndAHalf); r.Add("nav point reach: a doorway point is reached within 1 yd, its sweep pass within 1.5 yd", DoorwayPointTight); - r.Add("nav point reach: no lookahead corner cut at a doorway point", DoorwayNoLookahead); + r.Add("nav point reach: no lookahead corner cut at a doorway point (or at a small reach)", DoorwayNoLookahead); r.Add("nav point reach: Follow stops within it and moves again 3 yd farther out", FollowUsesReach); r.Add("nav point reach: metas set it as FollowNavMin (yd) or VTank's NavCloseStopRange (x240)", ReachFromMetas); @@ -746,18 +746,27 @@ internal static class NavEngineTests private static void DoorwayNoLookahead() { - // 3 yd short of a point, the next one due east: a plain point blends the aim east - // (4 yd lookahead), a doorway point keeps aiming straight at itself. + // 3 yd short of a point, the next one due east, with a 2.8 yd reach (big enough to round + // corners: 3.6 yd of lookahead): a plain point blends the aim east, a doorway point keeps + // aiming straight at itself. At the 1.5 yd default reach there is no rounding at all + // (the lookahead scales with the reach since 2026-10-05, see NavReachTests). foreach (bool doorway in new[] { false, true }) { FakeHost.Reset(); At(7, 0); Face(10, 0); var first = doorway ? Door(10, 0) : Pt(10, 0); var nav = new Nav(Route(RT.Circular, first, Pt(10, 10))); + nav.S.FollowNavMin = 2.8f; nav.Tick(); double h = FakeHost.HeadingDeg; if (doorway) Check.True(h < 1.0 || h > 359.0, $"doorway point: still heading north ({h:F1})"); else Check.True(h > 3.0 && h < 90.0, $"plain point: turning east early ({h:F1})"); } + + FakeHost.Reset(); At(8, 0); Face(10, 0); + var dflt = new Nav(Route(RT.Circular, Pt(10, 0), Pt(10, 10))); + dflt.Tick(); + double hd = FakeHost.HeadingDeg; + Check.True(hd < 1.0 || hd > 359.0, $"1.5 yd default reach, 2 yd short: a plain point is walked straight at too ({hd:F1})"); } private static void FollowUsesReach() diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NavOverlayTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NavOverlayTests.cs new file mode 100644 index 0000000..bf707c5 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NavOverlayTests.cs @@ -0,0 +1,263 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; +using RynthCore.Plugin.Shared; +using T = RynthCore.Plugin.RynthAi.LegacyUi.NavPointType; +using RT = RynthCore.Plugin.RynthAi.LegacyUi.NavRouteType; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Nav3D waypoint labels and guide line (Silentkelpie's rynth PR #1 idea, re-implemented on our +// pump-thread Nav3D markers). Both settings are off by default and then change nothing. Labels +// are filled strokes (Nav3D triangles) on an upright plane facing the character; the guide is +// one Nav3D line from the character's feet to the waypoint nav is heading for. The frame is +// built from the route on the plugin tick and the emit reads only the frame. +internal static class NavOverlayTests +{ + private const double NS0 = 42.0, EW0 = 33.0; + + public static void Register(Runner r) + { + r.Add("nav overlay: both settings off by default - markers draw exactly as before", OffByDefault); + r.Add("nav overlay: number labels over nearby waypoints, upright, facing the character, readable left to right", NumberLabels); + r.Add("nav overlay: names mode names jumps and checkpoints and hangs actions on the point before", NamesMode); + r.Add("nav overlay: labels only within range, active point first, nearest next, capped", LabelRangeAndCap); + r.Add("nav overlay: the guide line runs from the character's feet to the active waypoint, not to an action point", GuideLine); + r.Add("nav overlay: the frame is a snapshot - emptying the route afterwards changes nothing", FrameIsSnapshot); + r.Add("nav overlay: the label triangle budget holds for long names", TriangleBudget); + r.Add("nav overlay: settings round-trip; an older engine's payload leaves them alone", SettingsRoundTrip); + } + + // ── Rig ───────────────────────────────────────────────────────────── + + private static NavPoint Pt(double north, double east, T type = T.Point) + => new() { Type = type, NS = NS0 + north / 240.0, EW = EW0 + east / 240.0 }; + + private static NavRouteParser Route(params NavPoint[] pts) + { + var r = new NavRouteParser { RouteType = RT.Linear }; + r.Points.AddRange(pts); + return r; + } + + private sealed class Rig + { + public readonly LegacyUiSettings S; + public readonly NavMarkerRenderer R; + public readonly float Px, Py; // the player's landblock-local metres (east, north) + + public Rig(NavRouteParser route, int labels = 0, bool guide = false, int active = 0) + { + FakeHost.Reset(); + FakeHost.Nav3DCalls = true; + FakeHost.SetNavPosition(NS0, EW0); + Px = FakeHost.PlayerPose.X; + Py = FakeHost.PlayerPose.Y; + S = new LegacyUiSettings { CurrentRoute = route, ActiveNavIndex = active, NavHeightOffset = 0f, NavSlopeSink = 0f }; + if (labels != 0) S.NavLabelMode = labels; + if (guide) S.NavGuideLine = true; + R = new NavMarkerRenderer(FakeHost.Create(), S); + } + + public void Submit() + { + FakeHost.Nav3DRings.Clear(); FakeHost.Nav3DLines.Clear(); FakeHost.Nav3DTriangles.Clear(); + R.SubmitNav3D(); + } + + /// World position (Nav3D frame) of a point north/east of the player, in metres. + public (float X, float Z) At(double north, double east) => (Px + (float)east, Py + (float)north); + } + + private sealed class Recorder : INav3DSink + { + public readonly List Lines = new(); + public readonly List Tris = new(); + public void Line(float x1, float y1, float z1, float x2, float y2, float z2, float t, uint c) => Lines.Add(new[] { x1, y1, z1, x2, y2, z2 }); + public void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint c) + => Tris.Add(new[] { x1, y1, z1, x2, y2, z2, x3, y3, z3 }); + } + + private static IEnumerable<(float X, float Y, float Z)> Vertices(IEnumerable tris) + { + foreach (float[] t in tris) + for (int i = 0; i < 9; i += 3) yield return (t[i], t[i + 1], t[i + 2]); + } + + // ── Tests ─────────────────────────────────────────────────────────── + + private static void OffByDefault() + { + var d = new LegacyUiSettings(); + Check.Eq(d.NavLabelMode, NavLabelModes.Off, "labels default off"); + Check.False(d.NavGuideLine, "guide line default off"); + + var rig = new Rig(Route(Pt(5, 0), Pt(10, 0), Pt(10, 6))); + rig.Submit(); + Check.Eq(FakeHost.Nav3DRings.Count, 3, "three rings"); + Check.Eq(FakeHost.Nav3DLines.Count, 2, "two route lines, nothing more"); + Check.Eq(FakeHost.Nav3DTriangles.Count, 0, "no label triangles"); + Check.True(FakeHost.Nav3DLines.All(l => l.Color == 0xFF0088FF), "only route-coloured lines"); + } + + private static void NumberLabels() + { + // One waypoint 10 m north, one 10 m east. + var rig = new Rig(Route(Pt(10, 0), Pt(0, 10)), labels: NavLabelModes.Numbers); + rig.Submit(); + Check.True(FakeHost.Nav3DTriangles.Count > 0, "labels drawn as triangles"); + Check.Eq(FakeHost.Nav3DLines.Count, 1, "the route line only (labels use no lines)"); + + var (nx, nz) = rig.At(10, 0); + var (ex, ez) = rig.At(0, 10); + var north = FakeHost.Nav3DTriangles.Where(t => Math.Abs(t.Z1 - nz) < 2f && Math.Abs(t.X1 - nx) < 2f).ToList(); + var east = FakeHost.Nav3DTriangles.Where(t => Math.Abs(t.X1 - ex) < 2f && Math.Abs(t.Z1 - ez) < 2f).ToList(); + Check.Eq(north.Count + east.Count, FakeHost.Nav3DTriangles.Count, "every triangle belongs to one of the two labels"); + Check.True(north.Count > 0 && east.Count > 0, "both waypoints labelled"); + // Facing the character: the north label's plane is east-west (one Z), the east one's north-south (one X). + Check.True(north.All(t => Math.Abs(t.Z1 - nz) < 1e-3 && Math.Abs(t.Z2 - nz) < 1e-3 && Math.Abs(t.Z3 - nz) < 1e-3), "north label faces south, toward you"); + Check.True(east.All(t => Math.Abs(t.X1 - ex) < 1e-3 && Math.Abs(t.X2 - ex) < 1e-3 && Math.Abs(t.X3 - ex) < 1e-3), "east label faces west, toward you"); + // Upright and above the ring. + Check.True(north.All(t => t.Y1 >= 0.9f && t.Y2 >= 0.9f && t.Y3 >= 0.9f), "above the ring"); + float minY = north.Min(t => Math.Min(t.Y1, Math.Min(t.Y2, t.Y3))), maxY = north.Max(t => Math.Max(t.Y1, Math.Max(t.Y2, t.Y3))); + Check.True(maxY - minY > 0.3f, "has height (upright)"); + + // Readable from the character: "12" north of you runs west to east ('1' left of '2'). + var rec = new Recorder(); + var frame = new NavOverlayFrame(new[] { new NavLabel(0f, 0f, 10f, "12", 0, NavOverlay.LabelColor) }, null, 0f, 0f, 0f); + NavOverlay.EmitLabels(frame, rec); + int oneTris = NavStrokeFont.Glyph('1')!.Sum(p => p.Length / 2 - 1) * 2; + float oneX = Vertices(rec.Tris.Take(oneTris)).Average(v => v.X); + float twoX = Vertices(rec.Tris.Skip(oneTris)).Average(v => v.X); + Check.True(oneX < twoX, $"'1' is west of '2' seen from the south ({oneX:0.00} < {twoX:0.00})"); + // Seen looking east, left-to-right is north to south. + rec = new Recorder(); + NavOverlay.EmitLabels(new NavOverlayFrame(new[] { new NavLabel(10f, 0f, 0f, "12", 0, NavOverlay.LabelColor) }, null, 0f, 0f, 0f), rec); + float oneZ = Vertices(rec.Tris.Take(oneTris)).Average(v => v.Z), twoZ = Vertices(rec.Tris.Skip(oneTris)).Average(v => v.Z); + Check.True(oneZ > twoZ, "looking east, '1' is north of '2'"); + // Far labels are bigger. + Check.True(NavOverlay.LineHeight(50f) > NavOverlay.LineHeight(5f), "a far label is drawn taller"); + } + + private static void NamesMode() + { + var pts = new List + { + Pt(5, 0), // 0 + new() { Type = T.Chat, ChatCommand = "/vt stop" }, // 1 + new() { Type = T.Recall, SpellId = 2645 }, // 2 + Pt(10, 0, T.Checkpoint), // 3 + Pt(12, 0, T.Jump), // 4 + new() { Type = T.PortalNPC, TargetName = "Gateway" }, // 5 + new() { Type = T.Pause, PauseTimeMs = 2500 }, // 6 + new() { Type = T.Npc, TargetName = "Town Crier" }, // 7 + new() { Type = T.OpenVendor, TargetName = "Shopkeeper" }, // 8 + }; + var text = NavOverlay.BuildText(pts, pts, NavLabelModes.Names, id => id == 2645 ? "Portal Recall" : "?"); + Check.Eq(text.Own[0], "0", "plain point: its number"); + Check.True(text.Own[1] == null && text.Own[2] == null, "action points get no label of their own"); + Check.Eq(string.Join("|", text.Actions[0] ?? Array.Empty()), "1 CHAT /VT STOP|2 PORTAL RECALL", "actions hang on the point before"); + Check.Eq(text.Own[3], "3 CHECKPOINT", "checkpoint named"); + Check.Eq(text.Own[4], "4 JUMP", "jump named"); + Check.Eq(string.Join("|", text.Actions[4] ?? Array.Empty()), "5 PORTAL GATEWAY|6 PAUSE 2.5S|7 NPC TOWN CRIER|...", + "at most three action lines, then ..."); + + var numbers = NavOverlay.BuildText(pts, pts, NavLabelModes.Numbers, _ => ""); + Check.Eq(numbers.Own[4], "4", "numbers mode: just the number"); + Check.True(numbers.Actions.All(a => a == null), "numbers mode: no action lines"); + + // Drawn: the action lines stack above the point's own line. + var rig = new Rig(Route(pts.ToArray()), labels: NavLabelModes.Names); + var frame = rig.R.BuildOverlay(rig.S.CurrentRoute!, rig.Px, rig.Py, 0f, NS0, EW0, 0f); + var at0 = frame.Labels.Where(l => l.Text.StartsWith("0", StringComparison.Ordinal) || l.Text.StartsWith("1 ", StringComparison.Ordinal) || l.Text.StartsWith("2 ", StringComparison.Ordinal)).ToList(); + Check.Eq(string.Join("|", at0.Select(l => $"{l.Row}:{l.Text}")), "0:0|1:1 CHAT /VT STOP|2:2 PORTAL RECALL", "rows 0, 1, 2 over point 0"); + Check.True(at0.Skip(1).All(l => l.Color == NavOverlay.ActionLabelColor), "action lines in their own colour"); + } + + private static void LabelRangeAndCap() + { + // 40 points in a line northwards, 2 m apart (0..78 m): 31 of them within 60 m. + var pts = Enumerable.Range(0, 40).Select(i => Pt(2 * i, 0)).ToArray(); + var rig = new Rig(Route(pts), labels: NavLabelModes.Numbers, active: 5); + var frame = rig.R.BuildOverlay(rig.S.CurrentRoute!, rig.Px, rig.Py, 0f, NS0, EW0, 0f); + Check.Eq(frame.Labels.Count, NavOverlay.MaxLabelLines, "capped at the line budget"); + Check.Eq(frame.Labels[0].Text, "5", "the active point first"); + Check.Eq(frame.Labels[0].Color, NavOverlay.ActiveLabelColor, "in the active colour"); + Check.Eq(frame.Labels[1].Text, "0", "then the nearest"); + Check.True(frame.Labels.All(l => Math.Abs(l.Z - rig.Py) <= NavOverlay.LabelRange + 0.01f), "all within range"); + + var few = new Rig(Route(Pt(10, 0), Pt(100, 0)), labels: NavLabelModes.Numbers); + var f2 = few.R.BuildOverlay(few.S.CurrentRoute!, few.Px, few.Py, 0f, NS0, EW0, 0f); + Check.Eq(string.Join(",", f2.Labels.Select(l => l.Text)), "0", "a point 100 m away gets no label"); + } + + private static void GuideLine() + { + var rig = new Rig(Route(Pt(5, 0), Pt(10, 4)), guide: true, active: 1); + rig.Submit(); + Check.Eq(FakeHost.Nav3DLines.Count, 2, "the route line plus the guide"); + var g = FakeHost.Nav3DLines[0]; + Check.Eq(g.Color, NavOverlay.GuideColor, "the guide goes in first (never crowded out)"); + var (tx, tz) = rig.At(10, 4); + Check.True(Math.Abs(g.X1 - rig.Px) < 1e-3 && Math.Abs(g.Z1 - rig.Py) < 1e-3, "starts at the character"); + Check.True(Math.Abs(g.X2 - tx) < 1e-3 && Math.Abs(g.Z2 - tz) < 1e-3, "ends at the active waypoint"); + Check.True(g.Y1 > 0f && g.Y1 < 0.5f, "at the feet, lifted a little"); + Check.Eq(FakeHost.Nav3DTriangles.Count, 0, "labels stay off"); + + var chat = new Rig(Route(Pt(5, 0), new NavPoint { Type = T.Chat, ChatCommand = "hi" }, Pt(10, 0)), guide: true, active: 1); + chat.Submit(); + Check.False(FakeHost.Nav3DLines.Any(l => l.Color == NavOverlay.GuideColor), "no guide to an action point (placeholder coordinates)"); + } + + private static void FrameIsSnapshot() + { + var route = Route(Pt(5, 0), Pt(10, 0), Pt(15, 0)); + var rig = new Rig(route, labels: NavLabelModes.Numbers, guide: true, active: 2); + NavOverlayFrame frame = rig.R.BuildOverlay(route, rig.Px, rig.Py, 0f, NS0, EW0, 0f); + var before = new Recorder(); + NavOverlay.EmitGuide(frame, before, 0.06f); + NavOverlay.EmitLabels(frame, before); + + route.Points.Clear(); // what a reload or an edit on another thread would do + var after = new Recorder(); + NavOverlay.EmitGuide(frame, after, 0.06f); + NavOverlay.EmitLabels(frame, after); + Check.Eq(after.Tris.Count, before.Tris.Count, "same label triangles from the frame"); + Check.Eq(after.Lines.Count, 1, "same guide line"); + Check.True(before.Tris.Zip(after.Tris).All(p => p.First.SequenceEqual(p.Second)), "identical geometry"); + Check.False(frame.Labels is List, "labels are not a list anyone can grow"); + + rig.Submit(); + Check.Eq(FakeHost.Nav3DTriangles.Count + FakeHost.Nav3DLines.Count + FakeHost.Nav3DRings.Count, 0, "an empty route draws nothing next tick"); + } + + private static void TriangleBudget() + { + var labels = Enumerable.Range(0, NavOverlay.MaxLabelLines) + .Select(i => new NavLabel(0f, 0f, 5f + i, "WWWWWWWWWWWWWWWWWWWWWW", 0, NavOverlay.LabelColor)).ToArray(); + var rec = new Recorder(); + int used = NavOverlay.EmitLabels(new NavOverlayFrame(labels, null, 0f, 0f, 0f), rec); + Check.True(used <= NavOverlay.MaxLabelTriangles && rec.Tris.Count == used, $"at most {NavOverlay.MaxLabelTriangles} triangles ({used})"); + Check.True(used > NavOverlay.MaxLabelTriangles - 20, "and the budget is used, not cut short"); + } + + private static void SettingsRoundTrip() + { + var s = new LegacyUiSettings { NavLabelMode = NavLabelModes.Names, NavGuideLine = true }; + string json = JsonSerializer.Serialize(s, RynthAiJsonContext.Default.LegacyUiSettings); + var back = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!; + Check.Eq(back.NavLabelMode, NavLabelModes.Names, "label mode saved per character"); + Check.True(back.NavGuideLine, "guide line saved per character"); + + var old = JsonSerializer.Deserialize("{\"NavRingThickness\":6}", RynthAiJsonContext.Default.SettingsBridgePayload)!; + Check.Eq(old.NavLabelMode, -1, "an older engine's payload: label mode absent (-1, kept)"); + Check.Null(old.NavGuideLine, "an older engine's payload: guide line absent (null, kept)"); + + Check.Eq(NavLabelModes.Clamp(7), NavLabelModes.Off, "a bad mode reads as off"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NavReachTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NavReachTests.cs new file mode 100644 index 0000000..fd1ce9e --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NavReachTests.cs @@ -0,0 +1,261 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; +using T = RynthCore.Plugin.RynthAi.LegacyUi.NavPointType; +using RT = RynthCore.Plugin.RynthAi.LegacyUi.NavRouteType; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The nav point reach (FollowNavMin) really decides how close nav gets to each point before it +// turns for the next (Tom, 2026-10-05: "at 1.0 it should pretty much go directly to it. It gets +// to it, passes it and turns around to go back"; "it's turning too early and running into walls"). +// +// Unlike NavEngineTests, where the fake character only moves when a test puts it somewhere, these +// walk it: each nav tick (33 ms) the character runs forward along FakeHost.HeadingDeg while nav +// has autorun on (using the autorun state from the tick before, so a stop takes a tick to land, +// as in the game). Nav turns it with TurnToHeading, rate-limited to the turn-rate setting. +// +// The corner: a corridor 2 yd wide runs north from the origin to a point 20 yd north, then east. +// Its inside wall corner is at (19 N, 1 E): any step with north < 19 and east > 1 went through it. +internal static class NavReachTests +{ + private const double NS0 = 42.0, EW0 = 33.0; + private static long _now; + + public static void Register(Runner r) + { + r.Add("nav reach: 1 yd at a 90 degree corner by a wall - touches the point, then turns, no corner cut", CornerTightReach); + r.Add("nav reach: the corner rounding scales with the reach - none up to the 1.5 yd default, the Lookahead setting at 3 yd+", CornerRoundingScales); + r.Add("nav reach: 5 yd still rounds a corner (moves on 5 yd out and heads across)", CornerWideReach); + r.Add("nav reach: going past a point on the side counts as reached - no turning round", PassBySide); + r.Add("nav reach: a corner cut never counts as passing (the point must be behind)", CutIsNotAPass); + r.Add("nav reach: fast run at a low frame rate skips over a 0.5 yd reach - counted, no turning round", FastRunSkipsOver); + r.Add("nav reach: the sweep pass uses the closest approach, not the last tick", SweepUsesClosest); + r.Add("nav reach: doorway points unchanged - 1 yd reach, no pass-through, no rounding", DoorwayUnchanged); + } + + // ── Rig ─────────────────────────────────────────────────────────────────── + + private static NavPoint Pt(double north, double east, bool doorway = false) + => new() { Type = T.Point, NS = NS0 + north / 240.0, EW = EW0 + east / 240.0, Doorway = doorway }; + + private static NavRouteParser Route(RT type, params NavPoint[] pts) + { + var r = new NavRouteParser { RouteType = type }; + r.Points.AddRange(pts); + return r; + } + + private sealed class Walk + { + public readonly LegacyUiSettings S; + public readonly NavigationEngine E; + public double N, E_; + public double SpeedYdPerS = 11.0; // a good run skill + public int TickMs = 33; + public readonly List<(double N, double E, int Idx, bool Run)> Path = new(); + + public Walk(NavRouteParser route, float reach, double north, double east, double faceDeg) + { + FakeHost.Reset(); + _now = 1_000_000; + NavigationEngine.Clock = static () => _now; + N = north; E_ = east; + FakeHost.SetNavPosition(NS0 + N / 240.0, EW0 + E_ / 240.0); + FakeHost.HeadingDeg = faceDeg; + S = new LegacyUiSettings + { + IsMacroRunning = true, EnableNavigation = true, CurrentRoute = route, ActiveNavIndex = 0, + FollowNavMin = reach, + }; + E = new NavigationEngine(FakeHost.Create(), S); + } + + public int Idx => S.ActiveNavIndex; + + /// One nav tick, then the character moves for one tick if autorun is on. + public void Step() + { + _now += TickMs; + bool run = FakeHost.AutoRun; // what the client was doing going into this tick + E.Tick(); + if (run) + { + double h = FakeHost.HeadingDeg * Math.PI / 180.0, d = SpeedYdPerS * TickMs / 1000.0; + N += d * Math.Cos(h); + E_ += d * Math.Sin(h); + FakeHost.SetNavPosition(NS0 + N / 240.0, EW0 + E_ / 240.0); + } + Path.Add((N, E_, Idx, FakeHost.AutoRun)); + } + + public void RunUntil(Func done, double maxSeconds = 20) + { + int n = (int)(maxSeconds * 1000 / TickMs); + for (int i = 0; i < n && !done(); i++) Step(); + } + } + + private static double Dist(double n0, double e0, double n1, double e1) => Math.Sqrt((n1 - n0) * (n1 - n0) + (e1 - e0) * (e1 - e0)); + + private static int LogCount(string contains) => FakeHost.Logs.Count(l => l.Contains(contains)); + + /// Corridor north 20 yd then east 20 yd; returns the walk after it moved on from the corner. + private static Walk Corner(float reach, float lookahead = 4.0f) + { + var w = new Walk(Route(RT.Once, Pt(20, 0), Pt(20, 20), Pt(20, 40)), reach, 0, 0, 0); + w.S.NavLookaheadYards = lookahead; + w.RunUntil(() => w.Idx >= 1 && w.E_ > 6); + return w; + } + + private static double ClosestToCorner(Walk w) => w.Path.Min(p => Dist(p.N, p.E, 20, 0)); + + // ── Tests ───────────────────────────────────────────────────────────────── + + private static void CornerTightReach() + { + var w = Corner(1.0f); + Check.True(w.Idx >= 1, "moved on to the east leg"); + var onCorner = w.Path.Where(p => p.Idx == 0).ToList(); + var first = w.Path.FirstOrDefault(p => p.Idx >= 1); + double atAdvance = Dist(first.N, first.E, 20, 0); + Check.True(atAdvance <= 1.0, $"moved on within 1 yd of the corner point ({atAdvance:F2} yd)"); + double closest = ClosestToCorner(w); + Check.True(closest <= 0.5, $"touched the point: came within {closest:F2} yd of it"); + // While the corner is the target the character runs straight up the corridor centre: + // no turning east early. + double drift = onCorner.Max(p => Math.Abs(p.E)); + Check.True(drift < 0.05, $"no early turn toward the next point ({drift:F2} yd off the centre line before arriving)"); + Check.False(w.Path.Any(p => p.N < 19 && p.E > 1), "never inside the corridor's inside wall corner (19 N, 1 E)"); + double over = w.Path.Max(p => p.N); + Check.True(over < 21.0, $"no overshoot into the far wall at 21 N (got to {over:F2} N)"); + // No turning round: north never drops back more than a hair after its highest. + double maxN = 0, back = 0; + foreach (var p in w.Path) { maxN = Math.Max(maxN, p.N); back = Math.Max(back, maxN - p.N); } + Check.True(back < 0.1, $"never walked back south ({back:F2} yd)"); + Check.Eq(LogCount("sweep-pass"), 0, "reached properly, not by a sweep pass"); + } + + private static void CornerRoundingScales() + { + Check.Near(NavigationEngine.CornerLookaheadYards(4.0, 0.5), 0.0, 1e-9, "0.5 yd: no rounding"); + Check.Near(NavigationEngine.CornerLookaheadYards(4.0, 1.0), 0.0, 1e-9, "1 yd: no rounding"); + Check.True(NavigationEngine.CornerLookaheadYards(4.0, 1.5) <= 1.5, "1.5 yd default: rounding inside the reach, so none"); + Check.True(NavigationEngine.CornerLookaheadYards(4.0, 2.0) <= 2.0, "2 yd: still inside the reach, so none"); + Check.Near(NavigationEngine.CornerLookaheadYards(4.0, 3.0), 4.0, 1e-9, "3 yd: the 4 yd Lookahead setting"); + Check.Near(NavigationEngine.CornerLookaheadYards(4.0, 5.0), 4.0, 1e-9, "5 yd: the 4 yd Lookahead setting (as before)"); + Check.Near(NavigationEngine.CornerLookaheadYards(0.0, 5.0), 0.0, 1e-9, "Lookahead 0 is still off"); + Check.Near(NavigationEngine.CornerLookaheadYards(6.0, 5.0), 6.0, 1e-9, "a bigger Lookahead setting is used at a big reach"); + + // The default reach walks the corner like the 1 yd one: straight to the point. + var w = Corner(1.5f); + var onCorner = w.Path.Where(p => p.Idx == 0).ToList(); + Check.True(onCorner.Max(p => Math.Abs(p.E)) < 0.05, "1.5 yd: no early turn"); + var first = w.Path.First(p => p.Idx >= 1); + Check.True(Dist(first.N, first.E, 20, 0) <= 1.5, "1.5 yd: moved on within 1.5 yd"); + Check.False(w.Path.Any(p => p.N < 19 && p.E > 1), "1.5 yd: no corner cut"); + } + + private static void CornerWideReach() + { + // A 5 yd reach moves on 5 yd short of the corner and heads across it for the next point: + // the open-area corner rounding a big reach has always given. + var w = Corner(5.0f); + Check.True(w.Idx >= 1, "moved on"); + var first = w.Path.First(p => p.Idx >= 1); + double atAdvance = Dist(first.N, first.E, 20, 0); + Check.True(atAdvance > 4.0 && atAdvance <= 5.0, $"moved on 4-5 yd short of the corner ({atAdvance:F2})"); + Check.True(w.Path.Any(p => p.N < 19 && p.E > 1), "rounded the corner (inside the 2 yd corridor's corner: fine in the open)"); + double maxN = 0, back = 0; + foreach (var p in w.Path) { maxN = Math.Max(maxN, p.N); back = Math.Max(back, maxN - p.N); } + Check.True(back < 0.1, $"never walked back south ({back:F2} yd)"); + } + + private static void PassBySide() + { + // The character is carried past [0] 1.2 yd to its east (outside a 1 yd reach); the old + // code saw the distance shrink then grow by under 0.3 yd a tick, so it turned round. + var w = new Walk(Route(RT.Circular, Pt(10, 0), Pt(30, 0)), 1.0f, 0, 1.2, 0); + void At(double n, double e) { w.N = n; w.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); } + foreach (double n in new[] { 2.0, 5.0, 8.0, 9.5, 10.0 }) { At(n, 1.2); FakeHost.HeadingDeg = 0; w.Step(); } + Check.Eq(w.Idx, 0, "level with the point, 1.2 yd off: not yet"); + At(10.4, 1.2); FakeHost.HeadingDeg = 0; w.Step(); + Check.Eq(w.Idx, 1, "just past it: counted as reached"); + Check.Eq(LogCount("passed [0]"), 1, "logged as a pass"); + At(10.8, 1.2); w.Step(); + Check.True(FakeHost.AutoRun, "still running"); + double h = FakeHost.HeadingDeg; + Check.True(h < 20 || h > 340, $"heading on north to [1], not back to [0] ({h:F0})"); + + // Too far to the side is not a pass (2.5 yd sweep radius at a 1 yd reach). + var far = new Walk(Route(RT.Circular, Pt(10, 0), Pt(30, 0)), 1.0f, 0, 3.0, 0); + void AtF(double n, double e) { far.N = n; far.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); } + foreach (double n in new[] { 2.0, 6.0, 9.0, 10.5, 12.0 }) { AtF(n, 3.0); FakeHost.HeadingDeg = 0; far.Step(); } + Check.Eq(far.Idx, 0, "3 yd to the side: not passed"); + } + + private static void CutIsNotAPass() + { + // Heading for the corner (20 N, 0 E) from the south, the character drifts east toward the + // next point while still short of the corner: beyond the corner along the NEXT leg, but + // the corner is not behind it, so it is not a pass. + var w = new Walk(Route(RT.Once, Pt(20, 0), Pt(20, 20)), 1.0f, 0, 0, 0); + void At(double n, double e) { w.N = n; w.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); } + foreach (var (n, e) in new[] { (5.0, 0.0), (12.0, 0.5), (17.0, 1.5), (18.5, 2.0), (19.0, 2.2) }) + { + At(n, e); w.Step(); + } + Check.Eq(w.Idx, 0, "cutting toward the next point short of the corner never counts"); + Check.Eq(LogCount("passed [0]"), 0, "no pass logged"); + } + + private static void FastRunSkipsOver() + { + // 15 yd/s at 10 frames a second: 1.5 yd a tick, three times the 0.5 yd reach's width. + var w = new Walk(Route(RT.Once, Pt(20, 0.3), Pt(40, 0.3), Pt(60, 0.3)), 0.5f, 0, 0.3, 0); + w.SpeedYdPerS = 15.0; w.TickMs = 100; + w.RunUntil(() => w.Idx >= 1 && w.N > 25, 10); + Check.True(w.Idx >= 1, "moved on"); + double maxN = 0, back = 0; + foreach (var p in w.Path) { maxN = Math.Max(maxN, p.N); back = Math.Max(back, maxN - p.N); } + Check.True(back < 0.1, $"never turned round ({back:F2} yd back)"); + } + + private static void SweepUsesClosest() + { + // A slow pass by at about 2.3 yd (inside the 2.5 yd sweep radius of a 1 yd reach): the distance + // grows 0.1 yd a tick, never 0.3 in one tick. The old check never fired. + var w = new Walk(Route(RT.Circular, Pt(10, 0), Pt(10, 30)), 1.0f, 8, 2, 90); + void At(double n, double e) { w.N = n; w.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); } + // Coming from the south-east toward the point, then sliding away east (pushed along a wall). + At(8.2, 1.4); w.Step(); // first tick: the approach starts here (2.3 yd) + At(8.4, 1.6); w.Step(); + At(8.4, 1.8); w.Step(); + At(8.4, 2.0); w.Step(); + At(8.4, 2.2); w.Step(); + Check.Eq(w.Idx, 1, "0.3 yd beyond the closest approach (inside 2.5 yd): sweep pass"); + Check.Eq(LogCount("sweep-pass"), 1, "logged as a sweep pass"); + } + + private static void DoorwayUnchanged() + { + // Doorway reach 1 yd, sweep 1.5 yd; the pass-through rule does not apply. + var w = new Walk(Route(RT.Circular, Pt(10, 0, doorway: true), Pt(10, 10)), 1.5f, 0, 1.2, 0); + void At(double n, double e) { w.N = n; w.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); } + foreach (double n in new[] { 4.0, 8.0, 9.5, 10.4 }) { At(n, 1.2); FakeHost.HeadingDeg = 0; w.Step(); } + Check.Eq(w.Idx, 0, "1.2 yd beside a doorway point and past it: not reached (doorways line up properly)"); + + // With the 5 yd reach a plain point would round the corner; a doorway point is walked straight. + var d = new Walk(Route(RT.Once, Pt(20, 0, doorway: true), Pt(20, 20), Pt(20, 40)), 5.0f, 0, 0, 0); + d.RunUntil(() => d.Idx >= 1 && d.E_ > 6); + var onDoor = d.Path.Where(p => p.Idx == 0).ToList(); + Check.True(onDoor.Max(p => Math.Abs(p.E)) < 0.05, "doorway point: straight at it"); + var first = d.Path.First(p => p.Idx >= 1); + Check.True(Dist(first.N, first.E, 20, 0) <= 1.0, "doorway point reached within 1 yd at a 5 yd reach"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NoKillTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NoKillTests.cs new file mode 100644 index 0000000..4970429 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NoKillTests.cs @@ -0,0 +1,368 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text.Json; +using System.Text.RegularExpressions; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.RynthAiTests.Harness; +using C = RynthCore.Plugin.RynthAi.LegacyUi.MetaConditionType; +using A = RynthCore.Plugin.RynthAi.LegacyUi.MetaActionType; + +namespace RynthCore.RynthAiHostTests.Tests; + +// "No kills within X minutes" (2026-10-06): the plugin's KillClock, the expression +// secondssincelastkill[] and the meta condition No Kills Within Minutes (.af NoKillsInMins). +// The kill clock and MetaManager each run on a fake clock, moved together by Rig.Advance. +internal static class NoKillTests +{ + private static readonly DateTime T0 = new(2026, 10, 6, 2, 0, 0); + + public static void Register(Runner r) + { + r.Add("no-kill: secondssincelastkill[] counts from login, then the later of the last kill and the last macro start", FunctionClock); + r.Add("no-kill: only KillerNotification counts, not death messages in chat", OnlyOurKills); + r.Add("no-kill: the condition holds from N minutes without a kill", ConditionThreshold); + r.Add("no-kill: bad minutes or no clock never hold", ConditionFailsClosed); + r.Add("no-kill: NoKillsInMins survives an .af save and reload (also nested)", AfRoundTrip); + r.Add("no-kill: survives the settings JSON; an unknown condition number loads and never holds", JsonRoundTrip); + r.Add("no-kill: an unknown .af keyword loads as Never (how an older RynthAi reads NoKillsInMins)", UnknownKeywordFailsClosed); + r.Add("no-kill: an editor save on a running meta doesn't re-fire it or reset the clock", AutosaveKeepsIt); + r.Add("no-kill: the engine Meta editor's vocabulary matches MetaSchema", () => EngineVocabularyMatches()); + } + + private sealed class Rig + { + public readonly LegacyUiSettings S = new() { IsMacroRunning = true, EnableMeta = true, CurrentState = "Default" }; + public readonly MetaManager M; + public readonly KillClock K; + public DateTime Now = T0; + public long Ms; + + public Rig(bool withClock = true, params MetaRule[] rules) + { + S.MetaRules = rules.ToList(); + M = new MetaManager(S, default, new PlayerVitalsCache()) { Clock = () => Now }; + K = new KillClock(() => Ms) { MacroRunning = () => S.IsMacroRunning }; + if (withClock) M.SetKillClock(K); + } + + public void Advance(double seconds) + { + Now = Now.AddSeconds(seconds); + Ms += (long)Math.Round(seconds * 1000); + } + + public void Tick(double seconds = 0) + { + Advance(seconds); + M.Think(); + } + + public string Eval(string expr) => M.Expressions.Evaluate(expr); + public string Var(string name) => M.Expressions.Variables.TryGetValue(name, out string? v) ? v : "(unset)"; + + /// One freshly armed tick with only this condition; did it fire? Time does not move. + public bool Holds(MetaRule cond) + { + cond.State = S.CurrentState; + cond.Action = A.ExpressionAction; + cond.ActionData = "setvar[__hit, 1]"; + S.MetaRules = new List { cond }; + M.Expressions.Evaluate("clearvar[__hit]"); + S.ForceStateReset = true; + M.Think(); + return M.Expressions.Variables.ContainsKey("__hit"); + } + + public bool Holds(string minutes) => Holds(NoKills(minutes)); + } + + private static MetaRule NoKills(string minutes) => new() { Condition = C.NoKillsWithinMinutes, ConditionData = minutes }; + + private static MetaRule Mark(string state, C cond, string data, string v) => new() + { + State = state, Condition = cond, ConditionData = data, + Action = A.ExpressionAction, ActionData = $"setvar[{v}, getvar[{v}]+1]", + }; + + // ── secondssincelastkill[] ──────────────────────────────────────────── + + private static void FunctionClock() + { + var rig = new Rig(); + rig.S.IsMacroRunning = false; + rig.Advance(5); + Check.Eq(rig.Eval("secondssincelastkill[]"), "5", "macro never started: from login"); + Check.Eq(rig.K.Since, "login", "basis: login"); + Check.Eq(rig.K.SecondsSinceKillOnly(), -1, "status feed: no kill yet"); + + rig.S.IsMacroRunning = true; + rig.Advance(5); // started at 10 s; nothing read until now + Check.Eq(rig.Eval("secondssincelastkill[]"), "0", "macro just started: from the start"); + rig.Advance(2.5); + Check.Eq(rig.Eval("secondssincelastkill[]"), "2", "whole seconds (2.5 -> 2)"); + Check.Eq(rig.K.Since, "macro start", "basis: macro start"); + + // A start between reads is still seen: the plugin tick observes the macro every tick. + rig.S.IsMacroRunning = false; + rig.K.ObserveMacro(false); + rig.Advance(10); + rig.S.IsMacroRunning = true; + rig.K.ObserveMacro(true); // restarted at 22.5 s + rig.Advance(3); + Check.Eq(rig.Eval("secondssincelastkill[]"), "3", "a restart before any kill restarts the count"); + + rig.K.RecordKill(); // kill at 25.5 s + rig.Advance(1.999); + Check.Eq(rig.Eval("secondssincelastkill[]"), "1", "after a kill: since the kill"); + Check.Eq(rig.K.Since, "kill", "basis: kill"); + Check.Eq(rig.K.SecondsSinceKillOnly(), 1, "status feed: since the kill"); + + rig.S.IsMacroRunning = false; + rig.K.ObserveMacro(false); + rig.Advance(8); + rig.S.IsMacroRunning = true; + rig.Advance(1); + Check.Eq(rig.Eval("secondssincelastkill[]"), "0", "a macro restart after a kill starts the count again"); + Check.Eq(rig.K.Since, "macro start", "basis: macro start"); + rig.Advance(10); + Check.Eq(rig.Eval("secondssincelastkill[] >= 10"), "1", "usable in a comparison"); + Check.Eq(rig.Eval("SecondsSinceLastKill[]"), "10", "any case"); + + rig.K.SessionStarted(); // a new login + rig.Advance(4); + Check.Eq(rig.Eval("secondssincelastkill[]"), "4", "a new login forgets the old kill (macro already on: counts from login)"); + Check.False(rig.K.HasKill, "no kill this session"); + + var none = new Rig(withClock: false); + none.Advance(600); + Check.Eq(none.Eval("secondssincelastkill[]"), "0", "no clock wired: 0 (never 'a long time')"); + } + + // ── Only our kills ──────────────────────────────────────────────────── + + private static void OnlyOurKills() + { + var p = new RynthAiPlugin(); + KillClock k = p.Kills; + int eat = 0; + foreach (string line in new[] + { + "You killed the Drudge Skulker!", + "Drudge Skulker died.", + "Your fellow Bob killed the Mite Scion!", + "The Olthoi Soldier was killed by Bob.", + "You have been slain!", + }) + p.OnChatWindowText(line, 0, ref eat); + Check.False(k.HasKill, "death messages in chat don't count as our kill"); + + p.OnKillNotification(""); + p.OnKillNotification(null); + Check.False(k.HasKill, "an empty notification isn't a kill"); + + p.OnKillNotification("You killed the Drudge Skulker!"); + Check.True(k.HasKill, "KillerNotification (sent to the killer only) is our kill"); + Check.Eq(k.Since, "kill", "the clock counts from it"); + } + + // ── The condition ───────────────────────────────────────────────────── + + private static void ConditionThreshold() + { + var rig = new Rig(); + rig.Eval("secondssincelastkill[]"); // the macro start is seen at 0 + rig.Advance(59.999); + Check.False(rig.Holds("1"), "59.999 s: not 1 minute yet"); + rig.Advance(0.001); + Check.True(rig.Holds("1"), "60 s without a kill (from the macro start): holds"); + Check.True(rig.Holds("0.5"), "decimal minutes (0.5 = 30 s)"); + Check.True(rig.Holds("0,5"), "a comma decimal too"); + Check.True(rig.Holds(" 1 "), "spaces ignored"); + Check.False(rig.Holds("1.5"), "90 s: not yet"); + Check.True(rig.Holds("0"), "0 minutes: always"); + + rig.K.RecordKill(); + Check.False(rig.Holds("1"), "right after a kill: no"); + Check.False(rig.Holds("0.01"), "0.01 min, right after a kill: no"); + rig.Advance(119.999); + Check.False(rig.Holds("2"), "just under 2 minutes after the kill"); + rig.Advance(0.001); + Check.True(rig.Holds("2"), "2 minutes after the kill"); + Check.Eq(rig.Eval("secondssincelastkill[]"), "120", "same clock as the function"); + + // Nested like any other condition. + Check.True(rig.Holds(new MetaRule { Condition = C.All, Children = { NoKills("1"), new MetaRule { Condition = C.Always } } }), "inside All"); + Check.False(rig.Holds(new MetaRule { Condition = C.Not, Children = { NoKills("1") } }), "Not of it"); + + // A rule fires once per state entry, like every condition. + var latch = new Rig(true, Mark("Default", C.NoKillsWithinMinutes, "1", "n")); + latch.Tick(); + latch.Tick(30); + Check.Eq(latch.Var("n"), "(unset)", "not before a minute"); + latch.Tick(30); + latch.Tick(30); + Check.Eq(latch.Var("n"), "1", "fired once at a minute, latched after"); + } + + private static void ConditionFailsClosed() + { + var rig = new Rig(); + rig.Eval("secondssincelastkill[]"); + rig.Advance(3600); + foreach (string bad in new[] { "", " ", "abc", "-1", "5m", "NaN", "Infinity" }) + Check.False(rig.Holds(bad), $"'{bad}' never holds (an hour without a kill)"); + Check.True(rig.Holds("5"), "a real number does"); + + var none = new Rig(withClock: false); + none.Advance(3600); + Check.False(none.Holds("0"), "no kill clock wired: never holds"); + } + + // ── Files ───────────────────────────────────────────────────────────── + + private static void AfRoundTrip() + { + var rules = new List + { + new() { State = "Default", Condition = C.NoKillsWithinMinutes, ConditionData = "2.5", Action = A.SetMetaState, ActionData = "Move" }, + new() + { + State = "Default", Condition = C.All, Action = A.ChatCommand, ActionData = "/say quiet", + Children = { NoKills("5"), new MetaRule { Condition = C.NavrouteEmpty } }, + }, + new() { State = "Move", Condition = C.Not, Children = { NoKills("10") }, Action = A.SetMetaState, ActionData = "Default" }, + }; + string text = AfFileWriter.SaveToString(rules, new Dictionary>()); + Check.True(text.Contains("NoKillsInMins 2.5"), "written as 'NoKillsInMins 2.5'"); + Check.False(text.Contains("Expr"), "not written as an expression"); + + LoadedMeta back = AfFileParser.LoadFromText(text); + Check.Eq(back.Warnings.Count, 0, "loads without warnings"); + Check.Eq(back.Rules.Count, 3, "three rules back"); + MetaRule? top = back.Rules.FirstOrDefault(r => r.Condition == C.NoKillsWithinMinutes); + Check.NotNull(top, "the top-level condition is back"); + if (top != null) Check.Eq(top.ConditionData, "2.5", "with its minutes"); + MetaRule? all = back.Rules.FirstOrDefault(r => r.Condition == C.All); + Check.True(all != null && all.Children.Count == 2 && all.Children[0].Condition == C.NoKillsWithinMinutes + && all.Children[0].ConditionData == "5", "inside All"); + MetaRule? not = back.Rules.FirstOrDefault(r => r.Condition == C.Not); + Check.True(not != null && not.Children.Count == 1 && not.Children[0].Condition == C.NoKillsWithinMinutes + && not.Children[0].ConditionData == "10", "under Not (same-line operand)"); + + string again = AfFileWriter.SaveToString(back.Rules, new Dictionary>()); + Check.Eq(again, text, "a second save is identical"); + } + + private static void JsonRoundTrip() + { + var s = new LegacyUiSettings(); + s.MetaRules.Add(new MetaRule { State = "Default", Condition = C.NoKillsWithinMinutes, ConditionData = "3", Action = A.ChatCommand, ActionData = "/say hi" }); + string json = JsonSerializer.Serialize(s, RynthAiJsonContext.Default.LegacyUiSettings); + LegacyUiSettings? back = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(back != null && back.MetaRules.Count == 1 && back.MetaRules[0].Condition == C.NoKillsWithinMinutes + && back.MetaRules[0].ConditionData == "3", "the rule survives the settings JSON"); + Check.True(Regex.IsMatch(json, "\"Condition\":\\s*" + (int)C.NoKillsWithinMinutes), "stored as its number, like every condition"); + + // A condition number this build doesn't know (what an older RynthAi sees for 35): it loads + // (System.Text.Json doesn't range-check enums) and the rule never fires. + string future = Regex.Replace(json, "\"Condition\":\\s*" + (int)C.NoKillsWithinMinutes, "\"Condition\": 99"); + LegacyUiSettings? f = JsonSerializer.Deserialize(future, RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(f != null && f.MetaRules.Count == 1 && (int)f.MetaRules[0].Condition == 99, "an unknown number loads"); + var rig = new Rig(); + rig.Eval("secondssincelastkill[]"); + rig.Advance(3600); + Check.False(rig.Holds(new MetaRule { Condition = (C)99, ConditionData = "3" }), "and never holds"); + Check.Eq(MetaSchema.ConditionKeyword((C)99), "Never", "an .af save writes it as Never (never true)"); + } + + private static void UnknownKeywordFailsClosed() + { + // An older RynthAi's AfFileParser has no NoKillsInMins: unknown keywords load as Never with a + // warning (same code path, before 2026-10-06). Simulated with a keyword this build doesn't know. + var rules = new List + { + new() { State = "Default", Condition = C.NoKillsWithinMinutes, ConditionData = "1", Action = A.ExpressionAction, ActionData = "setvar[x, 1]" }, + }; + string text = AfFileWriter.SaveToString(rules, new Dictionary>()).Replace("NoKillsInMins", "NoKillsInMinsV2"); + LoadedMeta back = AfFileParser.LoadFromText(text); + Check.Eq(back.Rules.Count, 1, "the rule still loads"); + Check.Eq(back.Rules[0].Condition, C.Never, "as Never"); + Check.True(back.Warnings.Any(w => w.Contains("NoKillsInMinsV2")), "with a warning naming the keyword"); + + var rig = new Rig(true, back.Rules.ToArray()); + rig.Tick(); + rig.Tick(3600); + Check.Eq(rig.Var("x"), "(unset)", "and never fires"); + } + + // ── Editor autosave (MetaRuleEdits, update_rule) ───────────────────── + + private static void AutosaveKeepsIt() + { + var rig = new Rig(true, + Mark("Default", C.NoKillsWithinMinutes, "1", "nk"), + Mark("Default", C.NoKillsWithinMinutes, "5", "late")); + rig.Tick(); + rig.Tick(61); + Check.Eq(rig.Var("nk"), "1", "fired after a minute without a kill"); + long before = rig.K.ElapsedMs(); + + // The editor's autosave: an edited copy of rule 0 (new minutes), then the structural bump. + Check.True(MetaRuleEdits.Replace(rig.S.MetaRules, 0, Mark("Default", C.NoKillsWithinMinutes, "0.5", "nk")), "replaced"); + rig.S.MetaRulesStructuralVersion++; + rig.Tick(); + Check.Eq(rig.Var("nk"), "1", "the saved rule did not fire again (latch kept)"); + Check.Eq(rig.K.ElapsedMs(), before, "the kill clock didn't move"); + Check.Eq(rig.S.MetaRules[0].ConditionData, "0.5", "the new minutes are in"); + + // An unfired rule saved with a lower threshold fires on the same clock (nothing restarted). + Check.Eq(rig.Var("late"), "(unset)", "the 5-minute rule hasn't fired at 61 s"); + MetaRuleEdits.Replace(rig.S.MetaRules, 1, Mark("Default", C.NoKillsWithinMinutes, "1", "late")); + rig.S.MetaRulesStructuralVersion++; + rig.Tick(); + Check.Eq(rig.Var("late"), "1", "lowered to 1 minute: fires now, the 61 s weren't reset"); + Check.Eq(rig.S.CurrentState, "Default", "state unchanged"); + } + + // ── Engine vocabulary drift ─────────────────────────────────────────── + + private static void EngineVocabularyMatches([CallerFilePath] string here = "") + { + // The engine's MetaVocabulary (RynthCore UI/Data/MetaData.cs) is indexed by the enum number + // and can't reference the plugin; read its arrays from the side-by-side engine source. + string path = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(here)!, "..", "..", "..", "..", "RynthCore", + "src", "RynthCore.Engine", "UI", "Data", "MetaData.cs")); + if (!File.Exists(path)) + { + Check.True(false, $"engine source not found at {path} (RynthCore must sit beside RynthSuite)"); + return; + } + string src = File.ReadAllText(path); + string[] keywords = ArrayIn(src, "ConditionKeywords"); + string[] names = ArrayIn(src, "ConditionNames"); + string[] hints = ArrayIn(src, "ConditionHints"); + Check.Eq(keywords.Length, MetaSchema.Conditions.Length, "as many engine keywords as conditions"); + Check.Eq(names.Length, MetaSchema.Conditions.Length, "as many engine names as conditions"); + Check.Eq(hints.Length, MetaSchema.Conditions.Length, "as many engine hints as conditions"); + for (int i = 0; i < Math.Min(keywords.Length, MetaSchema.Conditions.Length); i++) + Check.Eq(keywords[i], MetaSchema.Conditions[i].Keyword, $"keyword {i}"); + int nk = (int)C.NoKillsWithinMinutes; + Check.Eq(nk, 35, "No Kills Within Minutes is 35 (engine MetaRuleEdit.NoKillsWithinMinutes)"); + if (names.Length > nk) Check.Eq(names[nk], MetaSchema.Conditions[nk].Label, "same label in the editor"); + } + + private static string[] ArrayIn(string src, string name) + { + int i = src.IndexOf("string[] " + name, StringComparison.Ordinal); + if (i < 0) return Array.Empty(); + int j = src.IndexOf("};", i, StringComparison.Ordinal); + string body = Regex.Replace(src.Substring(i, j - i), "//[^\n]*", ""); + int open = body.IndexOf('{'); + return Regex.Matches(body.Substring(open), "\"([^\"]*)\"").Select(m => m.Groups[1].Value).ToArray(); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs new file mode 100644 index 0000000..5e76e37 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs @@ -0,0 +1,198 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Pet essence refill loop (2026-10-05; spotted by Silentkelpie, rynth PR #1). PetManager decides +// "empty, refill it" from the essence's Structure read alone. When that read is stale (0 while the +// server holds a full essence), the server answers "This essence is already full." and PetManager +// went idle, read 0 again a second later and refilled again: a refill every couple of seconds, +// each one forcing peace mode and a clap (ACE PetDevice refill), for as long as the read stayed +// stale. A confirmed refill ("You add the spirit to the essence.") with a read that stays 0 burned +// a spirit every time. Now the server's reply wins over the read until a summon says the essence +// really is empty, the essence is re-identified after a refill, and an essence refilled twice in +// 2 minutes that still reads empty is parked for 5 minutes. +internal static class PetRefillTests +{ + private const uint Player = 0x50000D01; + private const uint Mob = 0x80300010; + private const uint Essence = 0x80300001; + private const uint Spirit = 0x80300002; + private const uint StructureKey = 92; // AcIntProperty.Structure + private const uint Lb = 0xA9B40000; + + private const string AlreadyFull = "This essence is already full."; + private const string Added = "You add the spirit to the essence."; + private const string NoCharges = "Your summoning device does not have enough charges to function!"; + + public static void Register(Runner r) + { + r.Add("pets: a charged essence summons; an empty one is refilled once, then summons", NormalPath); + r.Add("pets: stale empty read + 'already full' -> summon, not another refill (the loop)", AlreadyFullLoop); + r.Add("pets: confirmed refill with a read that stays empty does not burn more spirits", AddedButStale); + r.Add("pets: 'not enough charges' after a confirmed refill ends the trust; refill again", TrustEndsOnEmptySummon); + r.Add("pets: refilled twice in 2 min and still empty (no reply) -> parked 5 min", SilentRefillsParked); + r.Add("pets: the server's 'full' trust expires after 30 min", TrustExpires); + } + + // ── Rig ─────────────────────────────────────────────────────────────── + + private sealed class Rig : IDisposable + { + public long Now = 1_000_000; + public readonly LegacyUiSettings S = new() { SummonPets = true, MonsterRange = 20, CustomPetRange = 5, PetAutoRefill = true }; + public readonly PetManager Pets; + + public Rig(int charges) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; // UseObject (summon), RequestId (re-identify) + FakeHost.UseOnCalls = true; // UseObjectOn (spirit on essence) + Place(Player, "Pet Tester", 96, 96, creature: false); + FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f); + Place(Mob, "Drudge Skulker", 96, 99, creature: true); // 3 m north + FakeHost.Names[Essence] = "Fire Moar Essence (50)"; + FakeHost.Containers[Essence] = Player; + FakeHost.Names[Spirit] = "Encapsulated Spirit"; + FakeHost.Containers[Spirit] = Player; + SetCharges(charges); + + var host = FakeHost.Create(Player); + var cache = FakeHost.MakeCache(host, Player, new[] { Mob, Essence, Spirit }); + S.IsMacroRunning = true; + S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Essence), Name = "Fire Moar Essence (50)", Type = "Pet" }); + var combat = new CombatManager(host, S, cache); + combat.SetPlayerId(Player); + combat.ScanNearbyTargets(); + Check.True(combat.ScannedTargets.Count == 1, "rig: the monster is scanned"); + PetManager.Clock = () => Now; + Pets = new PetManager(host, S, cache, combat, null); + } + + private static void Place(uint id, string name, float x, float y, bool creature) + { + FakeHost.Names[id] = name; + FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f); + if (creature) FakeHost.ItemTypes[id] = 0x10; + } + + public static void SetCharges(int charges) + { + if (charges < 0) FakeHost.Ints.Remove((Essence, StructureKey)); + else FakeHost.Ints[(Essence, StructureKey)] = charges; + } + + /// Runs the heartbeat for of fake time in 100 ms steps. + public void Run(long ms) + { + for (long t = 0; t < ms; t += 100) + { + Now += 100; + Pets.OnHeartbeat(0); + } + } + + public void Chat(string line) => Pets.OnChatWindowText(line); + + public int Refills => FakeHost.UsesOn.Count(u => u.Source == Spirit && u.Target == Essence); + public int Summons => FakeHost.Uses.Count(u => u == Essence); + + public void Dispose() => PetManager.Clock = static () => Environment.TickCount64; + } + + // ── Tests ───────────────────────────────────────────────────────────── + + private static void NormalPath() + { + using (var rig = new Rig(charges: 50)) + { + rig.Run(1500); + Check.Eq(rig.Summons, 1, "a charged essence: one summon"); + Check.Eq(rig.Refills, 0, "a charged essence: no refill"); + } + + using (var rig = new Rig(charges: 0)) + { + rig.Run(1500); + Check.Eq(rig.Refills, 1, "an empty essence: one refill"); + Check.Eq(rig.Summons, 0, "an empty essence: no summon yet"); + Rig.SetCharges(50); // the server's Structure update lands + rig.Chat(Added); + rig.Run(1500); + Check.Eq(rig.Refills, 1, "after the refill: still one refill"); + Check.Eq(rig.Summons, 1, "after the refill: it summons"); + Check.True(FakeHost.IdRequests.Contains(Essence), "the essence is re-identified after a refill"); + } + } + + private static void AlreadyFullLoop() + { + using var rig = new Rig(charges: 0); // the read says empty and never changes + rig.Run(1500); + Check.Eq(rig.Refills, 1, "the empty read starts one refill"); + for (int i = 0; i < 10; i++) + { + rig.Chat(AlreadyFull); // the server: it was full all along + rig.Run(2000); + } + Check.Eq(rig.Refills, 1, "the server said full: no further refills over 20 s"); + Check.True(rig.Summons >= 1, "it summons from the essence the server called full"); + Check.True(FakeHost.IdRequests.Contains(Essence), "the stale essence is re-identified"); + Check.True(FakeHost.Logs.Any(l => l.Contains("already full", StringComparison.OrdinalIgnoreCase)), "the stale read is logged"); + } + + private static void AddedButStale() + { + using var rig = new Rig(charges: 0); + rig.Run(1500); + for (int i = 0; i < 5; i++) + { + rig.Chat(Added); // each reply would be a spirit spent + rig.Run(2000); + } + Check.Eq(rig.Refills, 1, "one spirit spent, not one per think tick"); + Check.True(rig.Summons >= 1, "it summons after the confirmed refill"); + } + + private static void TrustEndsOnEmptySummon() + { + using var rig = new Rig(charges: 0); + rig.Run(1500); + rig.Chat(AlreadyFull); + rig.Run(1500); + Check.Eq(rig.Summons, 1, "trusting the server, it summons"); + rig.Chat(NoCharges); // the summon says it really is empty + rig.Run(1500); + Check.Eq(rig.Refills, 2, "really empty: refilled again"); + } + + private static void SilentRefillsParked() + { + using var rig = new Rig(charges: 0); // no reply ever arrives, the read stays 0 + rig.Run(10 * 60_000); + // Before: a refill every ~38 s (8 s timeout + 30 s park) = about 16 in 10 minutes. + // Now: two refills, a 5 minute park, two refills, a park. + Check.True(rig.Refills <= 4, $"at most 4 refills in 10 minutes (got {rig.Refills})"); + Check.True(rig.Refills >= 2, $"it still tries to refill (got {rig.Refills})"); + Check.True(FakeHost.Logs.Any(l => l.Contains("parking", StringComparison.OrdinalIgnoreCase)), "the park is logged"); + } + + private static void TrustExpires() + { + using var rig = new Rig(charges: 0); + rig.Run(1500); + rig.Chat(AlreadyFull); + rig.Run(1500); + int refills = rig.Refills; + Check.Eq(refills, 1, "trusted: no second refill"); + // No summon lands (no pet appears, the read never moves): each summon times out and + // parks the essence for 30 s. After 30 minutes the trust is gone and the read rules. + rig.Run(31 * 60_000); + Check.True(rig.Refills > refills, "after 30 minutes the empty read is believed again"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs new file mode 100644 index 0000000..d73ea3c --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs @@ -0,0 +1,539 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Loot; +using RynthCore.Plugin.Shared; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-10-06, Drakkon on DreamWeave: from 06:18:44 every corpse/door use got the server's UseDone +// (no error) about one round trip later and nothing opened; a relog fixed it. The bot kept +// hammering corpses for 13 minutes. These tests cover: +// - UseRefusalWatch: answered-but-nothing-opened opens -> one clean stop and retry -> "the server +// isn't letting this character use objects" once, then a back-off with quiet probes; +// - the same through RynthAi's corpse looting (fake clock, fake server); +// - the trigger side: a corpse open waits for the arbiter's Looting tick, RynthAi's moves and +// turns wait while a door/corpse use is in flight, and Combat's idle peace swap waits while +// looting has work (on ACE a move or a mode change cancels the server's walk/turn to the corpse). +internal static class UseRefusalTests +{ + private const uint Player = 0x50000D01; + private const uint CorpseA = 0x80068ACE; + private const uint CorpseB = 0x80072023; + private const uint ItemTypeContainer = 0x200; + private const uint LongDescKey = 16; + private const string Me = "Drakkon"; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + private const string StuckLine = "isn't letting this character use objects"; + + public static void Register(Runner r) + { + r.Add("use check: three answered opens with nothing opened -> clean stop; a second corpse refused too -> stuck; probes back off; an open recovers", WatchEscalates); + r.Add("use check: one corpse that never opens is dropped, not reported as a stuck server", WatchDropsSingleCorpse); + r.Add("use check: a UseDone with an error, or no UseDone at all, counts as no refusal", WatchIgnoresErrorsAndSilence); + r.Add("use check: the next open settles an answered one that opened nothing; an open resets", WatchSettlesOnNextOpen); + r.Add("use check (looting): Drakkon's stall - stop once, retry, say it once in chat, stop opening corpses, probe, recover", LootingStall); + r.Add("use check (looting): normal opens never trip it", LootingNormalOpens); + r.Add("flight recorder: the use check asks the engine for a dump (clean stop, stuck); normal opens never do", FlightDumpRequests); + r.Add("corpse open: a corpse claimed while Combat owns the tick is opened only on the Looting tick", OpenWaitsForLootingTick); + r.Add("move hold: while a corpse use is in flight RynthAi's moves and turns wait, stops go through, UseDone or 1.5 s releases", MoveHoldWhileUseInFlight); + r.Add("move hold: off unless the plugin opts in (RynthNav, RynthLua unchanged)", MoveHoldOptIn); + r.Add("idle peace: Combat's idle peace swap waits while looting has work", IdlePeaceHeldWhileLooting); + r.Add("idle peace: looting has work = a corpse claimed, a corpse open, a corpse in range, or a use in flight", LootHoldsIdlePeaceInputs); + } + + // ── UseRefusalWatch alone ───────────────────────────────────────────────── + + private sealed class Rig + { + public readonly UseRefusalWatch W = new(); + public long T = 1_000_000; + public int Seq; + + /// One open of : answered (UseDone err 0) after 60 ms, nothing opens. + /// Returns the verdict of the tick after the grace. + public UseRefusalWatch.Verdict RefusedOpen(int id) + { + var settle = W.SettleBeforeOpen(T); + if (settle != UseRefusalWatch.Verdict.None) return settle; + W.OnOpenSent(id, T, Seq); + T += 60; Seq++; + Check.Eq(W.OnTick(T, Seq, 0, true), UseRefusalWatch.Verdict.None, "answered: no verdict yet"); + T += UseRefusalWatch.AnswerGraceMs; + var v = W.OnTick(T, Seq, 0, true); + T += 500; + return v; + } + } + + private static void WatchEscalates() + { + var r = new Rig(); + int a = unchecked((int)CorpseA), b = unchecked((int)CorpseB); + Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.None, "refusal 1"); + Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.None, "refusal 2"); + Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.CleanStopAndRetry, "refusal 3: clean stop and retry"); + Check.Eq(r.W.State, UseRefusalWatch.Phase.Retrying, "retrying"); + Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.DropCorpse, "the retry refused on the same corpse: drop that corpse"); + Check.Eq(r.RefusedOpen(b), UseRefusalWatch.Verdict.Stuck, "a second corpse refused: the server refuses every use"); + Check.Eq(r.W.State, UseRefusalWatch.Phase.Stuck, "stuck"); + Check.Eq(r.W.BackoffMs, UseRefusalWatch.FirstBackoffMs, "first back-off"); + Check.True(r.W.HoldsOpens(r.T), "no opens during the back-off"); + Check.False(r.W.HoldsOpens(r.W.BackoffUntil), "the back-off ends"); + + r.T = r.W.BackoffUntil; + Check.Eq(r.RefusedOpen(b), UseRefusalWatch.Verdict.StillStuck, "the probe refused: still stuck"); + Check.Eq(r.W.BackoffMs, UseRefusalWatch.FirstBackoffMs * 2, "the back-off doubles"); + for (int i = 0; i < 5; i++) { r.T = r.W.BackoffUntil; r.RefusedOpen(a); } + Check.Eq(r.W.BackoffMs, UseRefusalWatch.MaxBackoffMs, "capped"); + + Check.Eq(r.W.OnOpened(r.T), UseRefusalWatch.Verdict.Recovered, "a corpse opened: recovered"); + Check.Eq(r.W.State, UseRefusalWatch.Phase.Normal, "back to normal"); + Check.Eq(r.W.Refusals, 0, "count cleared"); + Check.Eq(r.W.OnOpened(r.T), UseRefusalWatch.Verdict.None, "an open while normal says nothing"); + } + + private static void WatchDropsSingleCorpse() + { + var r = new Rig(); + int a = unchecked((int)CorpseA); + r.RefusedOpen(a); r.RefusedOpen(a); + Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.CleanStopAndRetry, "three refusals"); + Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.DropCorpse, "same corpse: dropped"); + Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.DropCorpse, "still only that corpse: dropped again, never stuck"); + Check.Eq(r.W.OnOpened(r.T), UseRefusalWatch.Verdict.None, "another corpse opens: nothing to announce"); + Check.Eq(r.W.State, UseRefusalWatch.Phase.Normal, "normal"); + Check.Eq(r.W.RefusedCorpses.Count, 0, "the refused list is cleared by an open"); + } + + private static void WatchIgnoresErrorsAndSilence() + { + var w = new UseRefusalWatch(); + long t = 5_000; int seq = 7; + for (int i = 0; i < 5; i++) + { + w.OnOpenSent(1, t, seq); + seq++; t += 60; + w.OnTick(t, seq, 0x1D, true); // "you're too busy" + t += 3000; + Check.Eq(w.OnTick(t, seq, 0x1D, true), UseRefusalWatch.Verdict.None, "a too-busy answer is no refusal"); + Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.None, "and settles nothing"); + } + Check.Eq(w.Refusals, 0, "no refusals from errors"); + + for (int i = 0; i < 5; i++) + { + w.OnOpenSent(1, t, seq); // the server never answers (a long walk, a lag) + t += 2000; + Check.Eq(w.OnTick(t, seq, 0, true), UseRefusalWatch.Verdict.None, "unanswered: no verdict"); + Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.None, "an unanswered open is not settled as refused"); + } + w.OnOpenSent(1, t, seq); + t += UseRefusalWatch.UnansweredForgetMs + 1; + w.OnTick(t, seq, 0, true); + seq++; t += 60; + w.OnTick(t, seq, 0, true); // a late UseDone for something else + t += 5000; + Check.Eq(w.OnTick(t, seq, 0, true), UseRefusalWatch.Verdict.None, "a forgotten open is not judged by a later UseDone"); + Check.Eq(w.Refusals, 0, "no refusals from silence"); + } + + private static void WatchSettlesOnNextOpen() + { + var w = new UseRefusalWatch(); + long t = 10_000; int seq = 0; + for (int i = 0; i < 2; i++) + { + Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.None, "below the threshold the open goes ahead"); + w.OnOpenSent(1, t, seq); + seq++; t += 60; + w.OnTick(t, seq, 0, true); + t += 400; // the next attempt comes before the grace + } + Check.Eq(w.Refusals, 1, "the first answered open was settled as refused by the second"); + Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.None, "the second one now"); + Check.Eq(w.Refusals, 2, "two"); + w.OnOpenSent(1, t, seq); seq++; t += 60; w.OnTick(t, seq, 0, true); t += 400; + Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.CleanStopAndRetry, "the third: hold this open, clean stop first"); + w.OnOpened(t); + Check.Eq(w.Refusals, 0, "an open resets"); + Check.Eq(w.State, UseRefusalWatch.Phase.Normal, "normal"); + } + + // ── Through RynthAi's corpse looting ────────────────────────────────────── + + private static (uint Cell, float X, float Y, float Z) Me0 => (0x6347028Au, 100f, 100f, 0f); + + private static void World() + { + FakeHost.Reset(); + FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal + FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData, GetCurrentCombatMode + FakeHost.ServerGates = true; // GetUseDoneSeq + FakeHost.LastUseDoneCalls = true; + FakeHost.StopCalls = true; + FakeHost.Names[Player] = Me; + FakeHost.Positions[Player] = Me0; + FakeHost.PlayerPose = Me0; + foreach ((uint id, float dx) in new[] { (CorpseA, 1.0f), (CorpseB, 1.5f) }) + { + FakeHost.Names[id] = "Corpse of Olthoi Swarm Worker"; + FakeHost.ItemTypes[id] = ItemTypeContainer; + FakeHost.Strings[(id, LongDescKey)] = $"Killed by {Me}."; + FakeHost.NotAttackable.Add(id); + FakeHost.Positions[id] = (Me0.Cell, Me0.X + dx, Me0.Y, Me0.Z); + } + } + + private sealed class Bot + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new() + { + IsMacroRunning = true, + EnableLooting = true, + EnableCombat = false, + LootOwnership = 0, // My Kills Only + LootContentSettleMs = 0, + LootEmptyCorpseMs = 0, + StopLootingWhenPackFull = false, + }; + public readonly WorldObjectCache Cache; + + public Bot(RynthCoreHost host) + { + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + Set("_dashboard", dash); + Cache = new WorldObjectCache(host); + Cache.SetPlayerId(Player); + Set("_objectCache", Cache); + Set("_playerId", Player); + Cache.OnCreateObject(CorpseA); + Cache.OnCreateObject(CorpseB); + Cache.Tick(); + + string profile = Path.Combine(Program.TempRoot, "use-refusal-test.json"); + var p = new LootProfile { Name = "nothing" }; + p.Save(profile); + S.CurrentLootPath = profile; + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public T Get(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!; + public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a); + public void Tick(BotActivity act) + { + Set("_activity", act); + Call("TickCorpseOpening"); + } + } + + /// Runs the fake clock with RynthAiPlugin.CorpseClock pointed at it. + private static void WithClock(Action, Action> body) + { + long now = 50_000_000; + var saved = RynthAiPlugin.CorpseClock; + RynthAiPlugin.CorpseClock = () => now; + try { body(() => now, ms => now += ms); } + finally { RynthAiPlugin.CorpseClock = saved; } + } + + private static int ChatCount(string text) => FakeHost.Chat.Count(c => c.Contains(text)); + + private static void LootingStall() + { + World(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + WithClock((now, advance) => + { + // The server of 06:18:44 on: every open is answered (UseDone, no error) 60 ms later, nothing opens. + long answerAt = 0; + void Step() + { + int uses = FakeHost.Uses.Count; + bot.Tick(BotActivity.Looting); + if (FakeHost.Uses.Count > uses) answerAt = now() + 60; + advance(100); + if (answerAt != 0 && now() >= answerAt) { FakeHost.UseDone(0); answerAt = 0; } + } + + int steps = 0; + while (ChatCount(StuckLine) == 0 && steps++ < 600) Step(); + Check.Eq(ChatCount(StuckLine), 1, "the player is told, once (after " + steps / 10.0 + " s of looting)"); + Check.True(steps <= 400, "within 40 s of the first refused open (took " + steps / 10.0 + " s)"); + Check.True(FakeHost.Logs.Any(l => l.Contains("one clean stop")), "the clean stop and retry came first"); + Check.True(FakeHost.Logs.Any(l => l.Contains("/Loot/UseCheck StopCompletely()")), "one StopCompletely from the use check"); + Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: facing 0x80068ACE")), "and the corpse is faced for the retry"); + Check.Near(FakeHost.HeadingDeg, 90.0, 0.5, "facing east, where the corpse lies"); + Check.True(FakeHost.Logs.Any(l => l.Contains("giving up on it")), "the first corpse, retried alone, was dropped before the verdict"); + Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: the server answers every use but nothing opens")), "the verdict is logged"); + Check.Eq(bot.Get("_targetCorpseId"), 0, "no corpse held"); + + int usesAtStuck = FakeHost.Uses.Count; + Check.False((bool)bot.Call("HasLootWork", bot.S, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())!, + "no loot work during the back-off: nav and combat run on"); + for (int i = 0; i < 2400; i++) Step(); // 4 minutes + Check.Eq(FakeHost.Uses.Count, usesAtStuck, "no corpse is opened during the back-off"); + Check.Eq(ChatCount(StuckLine), 1, "and nothing more is said"); + + for (int i = 0; i < 700 && FakeHost.Uses.Count == usesAtStuck; i++) Step(); + Check.Eq(FakeHost.Uses.Count, usesAtStuck + 1, "one probe after the back-off"); + for (int i = 0; i < 40; i++) Step(); + Check.True(FakeHost.Logs.Any(l => l.Contains("still refused")), "the probe refused: logged"); + Check.Eq(ChatCount(StuckLine), 1, "not said again"); + Check.Eq(FakeHost.Uses.Count, usesAtStuck + 1, "and backed off again"); + + // A relog, or the server recovers: the next probe opens. + int probeUses = FakeHost.Uses.Count; + for (int i = 0; i < 6100 && FakeHost.Uses.Count == probeUses; i++) + { + bot.Tick(BotActivity.Looting); + advance(100); + } + Check.Eq(FakeHost.Uses.Count, probeUses + 1, "the next probe after the longer back-off"); + uint probed = FakeHost.Uses.Last(); + bot.P.OnViewObjectContents(probed); + Check.Eq(ChatCount("Objects open again"), 1, "the player is told uses work again"); + Check.False(bot.Get("_useRefusals").HoldsOpens(now()), "looting is back on"); + }); + } + + private static void LootingNormalOpens() + { + World(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + WithClock((now, advance) => + { + for (int round = 0; round < 6; round++) + { + uint id = round % 2 == 0 ? CorpseA : CorpseB; + // Not completed yet: a fresh claim each round. + bot.Get>("_completedCorpses").Clear(); + int uses = FakeHost.Uses.Count; + for (int i = 0; i < 30 && FakeHost.Uses.Count == uses; i++) { bot.Tick(BotActivity.Looting); advance(100); } + Check.True(FakeHost.Uses.Count > uses, $"round {round}: an open went out"); + advance(200); + FakeHost.UseDone(0); + bot.P.OnViewObjectContents(FakeHost.Uses.Last()); + for (int i = 0; i < 30; i++) { bot.Tick(BotActivity.Looting); advance(100); } + } + var w = bot.Get("_useRefusals"); + Check.Eq(w.Refusals, 0, "no refusals"); + Check.Eq(w.State, UseRefusalWatch.Phase.Normal, "normal"); + Check.Eq(ChatCount(StuckLine), 0, "nothing said"); + Check.False(FakeHost.Logs.Any(l => l.Contains("Use check:")), "nothing logged by the use check"); + }); + } + + /// The engine's flight recorder answers SendPluginCommand("RynthCore.FlightRecorder", "dump", reason). + private static void FlightDumpRequests() + { + World(); + FakeHost.PluginCommandCalls = true; + var host = FakeHost.Create(Player); + var bot = new Bot(host); + WithClock((now, advance) => + { + long answerAt = 0; + int steps = 0; + while (ChatCount(StuckLine) == 0 && steps++ < 600) + { + int uses = FakeHost.Uses.Count; + bot.Tick(BotActivity.Looting); + if (FakeHost.Uses.Count > uses) answerAt = now() + 60; + advance(100); + if (answerAt != 0 && now() >= answerAt) { FakeHost.UseDone(0); answerAt = 0; } + } + var dumps = FakeHost.PluginCommands.Where(c => c.Plugin == "RynthCore.FlightRecorder").ToList(); + Check.True(dumps.Count >= 2, $"a dump asked at the clean stop and at the verdict ({dumps.Count})"); + Check.True(dumps.All(d => d.Action == "dump"), "all are dump requests"); + Check.True(dumps.Any(d => d.Value.StartsWith("RynthAi use check: corpse opens answered")), "the clean stop's reason"); + Check.True(dumps.Any(d => d.Value.StartsWith("RynthAi use check: server refuses every use")), "the verdict's reason"); + }); + + // Normal opens: nothing asked. + World(); + FakeHost.PluginCommandCalls = true; + var host2 = FakeHost.Create(Player); + var bot2 = new Bot(host2); + WithClock((now, advance) => + { + for (int round = 0; round < 4; round++) + { + bot2.Get>("_completedCorpses").Clear(); + int uses = FakeHost.Uses.Count; + for (int i = 0; i < 30 && FakeHost.Uses.Count == uses; i++) { bot2.Tick(BotActivity.Looting); advance(100); } + advance(200); + FakeHost.UseDone(0); + bot2.P.OnViewObjectContents(FakeHost.Uses.Last()); + for (int i = 0; i < 30; i++) { bot2.Tick(BotActivity.Looting); advance(100); } + } + Check.False(FakeHost.PluginCommands.Any(c => c.Plugin == "RynthCore.FlightRecorder"), "no dump asked"); + }); + } + + private static void OpenWaitsForLootingTick() + { + World(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + WithClock((now, advance) => + { + bot.Tick(BotActivity.Combat); // the kill tick: Combat still owns it + Check.Eq(bot.Get("_targetCorpseId"), unchecked((int)CorpseA), "the corpse is claimed"); + Check.Eq(FakeHost.Uses.Count, 0, "but not opened while Combat owns the tick"); + advance(30); + bot.Tick(BotActivity.Looting); // the arbiter hands the tick to Looting (its nav stop goes first) + Check.Eq(FakeHost.Uses.Count, 1, "opened on the Looting tick"); + Check.Eq(FakeHost.Uses[0], CorpseA, "the claimed corpse"); + }); + } + + // ── MoveAudit hold ──────────────────────────────────────────────────────── + + private static void WithAuditClock(Action> body) + { + long now = 7_000_000; + var savedUse = UseAudit.NowMs; + var savedMove = MoveAudit.NowMs; + UseAudit.NowMs = () => now; + MoveAudit.NowMs = () => now; + try { body(ms => now += ms); } + finally + { + UseAudit.NowMs = savedUse; + MoveAudit.NowMs = savedMove; + UseAudit.TrackWorldUses = false; + UseAudit.ClearWorldUse(); + MoveAudit.Reset(); + UseAudit.Reset("?", null); + } + } + + private static void MoveHoldWhileUseInFlight() + { + World(); + var host = FakeHost.Create(Player); + WithAuditClock(advance => + { + UseAudit.Reset("RynthAi", () => true); + MoveAudit.Reset(); + UseAudit.TrackWorldUses = true; + + Check.True(host.UseFor(CorpseA, "Loot", "test open"), "the corpse use goes out"); + advance(10); + Check.False(host.SetAutoRunBy("Nav", true), "autorun on is held"); + Check.False(host.TurnToHeadingBy("Nav", 90f), "a heading snap is held"); + Check.Eq(FakeHost.AutoRunCalls.Count, 0, "no autorun reached the client"); + Check.Eq(FakeHost.Turns, 0, "no turn reached the client"); + Check.True(host.StopCompletelyBy("Arbiter"), "a stop goes through"); + Check.Eq(FakeHost.Stops, 1, "one stop"); + host.SetAutoRunBy("Nav", false); + Check.Eq(string.Join(",", FakeHost.AutoRunCalls), "False", "autorun off goes through"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains(" held: the server is still answering the use of 0x80068ACE")), 1, "one 'held' line for the use"); + + FakeHost.UseDone(0); // the server answered + Check.True(host.SetAutoRunBy("Nav", true), "after the UseDone autorun goes out"); + Check.True(host.TurnToHeadingBy("Nav", 45f), "and turns"); + + Check.True(host.UseFor(CorpseB, "Loot", "test open 2"), "a second use"); + Check.False(host.TurnToHeadingBy("Nav", 50f), "held again"); + advance(UseAudit.WorldUseInFlightMaxMs); // no answer: the cap releases it + Check.True(host.TurnToHeadingBy("Nav", 55f), "released after the cap"); + + FakeHost.Uses.Clear(); + Check.True(host.UseFor(0x80001234, "Loot", "a non-world use (an item)"), "an item use"); + Check.True(host.TurnToHeadingBy("Nav", 60f), "an item use holds nothing"); + }); + } + + private static void MoveHoldOptIn() + { + World(); + var host = FakeHost.Create(Player); + WithAuditClock(advance => + { + UseAudit.Reset("RynthNav", null); + MoveAudit.Reset(); + Check.False(UseAudit.TrackWorldUses, "off by default"); + host.UseFor(CorpseA, "Nav", "test open"); + Check.True(host.SetAutoRunBy("Nav", true), "nothing held without the opt-in"); + Check.True(host.TurnToHeadingBy("Nav", 90f), "turns too"); + Check.False(UseAudit.WorldUseInFlight(host, out _), "no use is tracked"); + }); + } + + // ── Combat's idle peace swap ────────────────────────────────────────────── + + private static void IdlePeaceHeldWhileLooting() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeCalls = true; + FakeHost.CombatModeValue = 2; // melee stance, no target: the idle swap would go to peace + FakeHost.Names[Player] = Me; + FakeHost.Positions[Player] = Me0; + FakeHost.PlayerPose = Me0; + var host = FakeHost.Create(Player); + var s = new LegacyUiSettings { IsMacroRunning = true, EnableCombat = true, PeaceModeWhenIdle = true, MonsterRange = 50 }; + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + var combat = new CombatManager(host, s, cache); + combat.SetPlayerId(Player); + bool looting = true; + combat.HoldIdlePeace = () => looting; + + for (int i = 0; i < 5; i++) combat.Think(); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no peace swap while looting has work"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("idle peace-mode swap held")), 1, "said once in the log"); + + looting = false; + combat.Think(); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "looting done: the idle swap to peace goes out"); + + combat.HoldIdlePeace = null; + FakeHost.CombatModeRequests.Clear(); + typeof(CombatManager).GetField("_lastPeaceAttempt", Any)!.SetValue(combat, DateTime.MinValue); + combat.Think(); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "no hold set: as before"); + } + + private static void LootHoldsIdlePeaceInputs() + { + World(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bool Holds() => (bool)bot.Call("LootHoldsIdlePeace")!; + Check.False(Holds(), "nothing to loot: no hold"); + bot.Set("_targetCorpseId", unchecked((int)CorpseA)); + Check.True(Holds(), "a claimed corpse"); + bot.Set("_targetCorpseId", 0); + bot.Set("_openedContainerId", unchecked((int)CorpseA)); + Check.True(Holds(), "an open corpse"); + bot.Set("_openedContainerId", 0); + bot.Set("_lastWantLoot", true); + Check.True(Holds(), "a corpse waiting in range (the arbiter's wantLoot)"); + bot.Set("_lastWantLoot", false); + WithAuditClock(_ => + { + UseAudit.Reset("RynthAi", () => true); + UseAudit.TrackWorldUses = true; + host.UseFor(CorpseB, "Loot", "test open"); + Check.True(Holds(), "a corpse use in flight"); + }); + Check.False(Holds(), "all clear: no hold"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs index 8a81edb..c9d9d44 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs @@ -23,6 +23,7 @@ internal static class VitalsTests r.Add("vitals: Stamina to Health follows its own health line and stamina floor", StaminaToHealthThresholds); r.Add("vitals: profiles without the Stamina to Health keys load today's 30 / 20", StaminaToHealthDefaults); 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); r.Add("vitals: 'You're too busy!' paces vital casts, and a long streak stops the character once", TooBusyVitals); // Drakkon's death, 2026-10-05 13:43:20 (ops\overnight\2026-10-05-death-fixes.md). @@ -147,6 +148,29 @@ internal static class VitalsTests Check.False(BuffManager.IsKitResultLine("bob heals you for 40 health points."), "someone else's kit doesn't"); } + private static void HealAboveAllowedTier() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + int heal6 = SpellTable.Rows.First(r => r.Name == "Heal Self VI").Id; + FakeHost.Spellbook.Add((uint)heal6); // the only Heal Self known + FakeHost.Skills[(Player, STypeLife)] = (120, 2); // vitae: Life Magic under the tier 6 line + var host = FakeHost.Create(); + var s = new LegacyUiSettings { HealAt = 60, TopOffHP = 60, RestamAt = 0, TopOffStam = 0, GetManaAt = 0, TopOffMana = 0, UsePotions = false }; + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + Check.True(sm.GetHighestBuffSpellTier(AcSkillType.LifeMagic) < 6, "the rig: Life Magic 120 allows less than tier 6"); + var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 30, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, vitals); + b.SetCharacterSkills(skills); + Check.True(b.CheckVitals(), "health 30% under Heal At 60%: the vitals step acts"); + Check.True(FakeHost.Casts.Any(c => c.SpellId == heal6), "Heal Self VI is cast: " + string.Join(",", FakeHost.Casts.Select(c => c.SpellId))); + } + /// One CheckVitals on a fresh BuffManager; true when it cast a Stamina to Health spell. private static bool CastsStamToHealth(int healthPct, int staminaPct, System.Action? tweak = null) { diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/WorldCacheTypedTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/WorldCacheTypedTests.cs new file mode 100644 index 0000000..69db529 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/WorldCacheTypedTests.cs @@ -0,0 +1,241 @@ +using System; +using System.Linq; +using System.Reflection; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Typed world-cache placement (2026-10-05; spotted by Silentkelpie, rynth PR #1). A positioned, +// non-creature object with a known item type used to be filed only when it was a weapon, armor, +// caster or container, and then always into OUR inventory: other players' wielded gear and +// ground-dropped weapons counted as ours, and keys, gems, comps and food on the ground stayed +// Unknown and were re-probed every 2 s for good. Now they get the class their type gives and are +// filed by who has them. Pinned here: what goes where, that hazards (dynamic or static, typed or +// not) still register, that corpses are still found, and the loot classes (scrolls, slot-typed +// weapons) on objects that come this way. +internal static class WorldCacheTypedTests +{ + private const uint Player = 0x50000E01; + private const uint OtherPlayer = 0x50000E99; + private const uint Lb = 0xA9B40000; + private const uint Here = Lb | 0x1C; + private const uint Dungeon = 0x01D90105; + + private const uint TMelee = 0x1, TArmor = 0x2, TFood = 0x20, TMisc = 0x80, TContainer = 0x200, TGem = 0x800, + TComps = 0x1000, TWritable = 0x2000, TKey = 0x4000, TManaStone = 0x80000, TLifeStone = 0x10000000; + + public static void Register(Runner r) + { + r.Add("world cache: typed ground items get their class and stay on the landscape", GroundItems); + r.Add("world cache: another player's wielded gear is neither ours nor a ground item", OtherPlayersGear); + r.Add("world cache: our wielded gear and positioned pack / side-pack items are inventory", OwnGear); + r.Add("world cache: ground gear is landscape; unreadable ownership keeps the old filing", GroundGearAndUnknownOwnership); + r.Add("world cache: hazards still register (dynamic Misc, static, untyped); lava-named gear does not", Hazards); + r.Add("world cache: corpses: named at once, and a Container-typed one named late is rescued", Corpses); + r.Add("world cache: an Unknown whose type arrives late is filed as the item it is", LateType); + r.Add("world cache: scrolls, slot-typed weapons, chests, lifestones; signs stay scenery", LootClasses); + } + + // ── Rig ─────────────────────────────────────────────────────────────── + + private static uint _next; + + private static void World() + { + FakeHost.Reset(); + _next = 0x80310001; + FakeHost.Names[Player] = "Cache Tester"; + FakeHost.Positions[Player] = (Here, 96f, 96f, 0f); + FakeHost.PlayerPose = (Here, 96f, 96f, 0f); + FakeHost.Containers[Player] = 0; // installs GetObjectOwnershipInfo for every test + } + + /// A positioned non-creature: on the ground (owner null = ownership unreadable). + private static uint Obj(string name, uint type, uint? container = 0, uint? wielder = null, uint cell = Here, uint id = 0) + { + if (id == 0) id = _next++; + if (name.Length > 0) FakeHost.Names[id] = name; + FakeHost.Positions[id] = (cell, 97f, 97f, 0f); + if (type != 0) FakeHost.ItemTypes[id] = type; + if (container != null) FakeHost.Containers[id] = container.Value; + if (wielder != null) FakeHost.Wielders[id] = wielder.Value; + FakeHost.NotAttackable.Add(id); + return id; + } + + /// Classifies the way the game does: CreateObject, then ticks. + private static WorldObjectCache Classify(params uint[] ids) + { + var host = FakeHost.Create(Player); + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + foreach (uint id in ids) cache.OnCreateObject(id); + for (int i = 0; i < 12; i++) cache.Tick(); // past the 8 same-tick retries + return cache; + } + + private static void Reclassify(WorldObjectCache cache) + => typeof(WorldObjectCache).GetMethod("ReclassifyUnknownDynamics", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(cache, null); + + private static AcObjectClass ClassOf(WorldObjectCache c, uint id) + => c.AllKnownObjects().FirstOrDefault(w => w.Id == unchecked((int)id))?.ObjectClass ?? (AcObjectClass)(-1); + private static bool InInventory(WorldObjectCache c, uint id) => c.GetInventory().Any(w => w.Id == unchecked((int)id)); + private static bool OnLandscape(WorldObjectCache c, uint id) => c.GetLandscapeObjects().Any(w => w.Id == unchecked((int)id)); + + private static void Where(WorldObjectCache c, uint id, AcObjectClass cls, bool inv, bool land, string what) + { + Check.Eq(ClassOf(c, id), cls, what + ": class"); + Check.Eq(InInventory(c, id), inv, what + ": in the inventory"); + Check.Eq(OnLandscape(c, id), land, what + ": on the landscape"); + } + + // ── Tests ───────────────────────────────────────────────────────────── + + private static void GroundItems() + { + World(); + uint key = Obj("Key to the Black Gate", TKey); + uint gem = Obj("Black Opal", TGem); + uint comp = Obj("Prismatic Taper", TComps); + uint food = Obj("Apple", TFood); + uint stone = Obj("Mana Stone", TManaStone); + var c = Classify(key, gem, comp, food, stone); + Where(c, key, AcObjectClass.Key, false, true, "ground key"); + Where(c, gem, AcObjectClass.Gem, false, true, "ground gem"); + Where(c, comp, AcObjectClass.SpellComponent, false, true, "ground comps"); + Where(c, food, AcObjectClass.Food, false, true, "ground food"); + Where(c, stone, AcObjectClass.ManaStone, false, true, "ground mana stone"); + Reclassify(c); + Check.False(FakeHost.Logs.Any(l => l.Contains("stuck Unknown", StringComparison.Ordinal)), "nothing left for the Unknown re-probe"); + } + + private static void OtherPlayersGear() + { + World(); + uint sword = Obj("Fire Tachi", TMelee, container: 0, wielder: OtherPlayer); + uint armor = Obj("Amuli Shadow Coat", TArmor, container: 0, wielder: OtherPlayer); + var c = Classify(sword, armor); + Where(c, sword, AcObjectClass.MeleeWeapon, false, false, "another player's sword"); + Where(c, armor, AcObjectClass.Armor, false, false, "another player's coat"); + Check.False(c.GetContainedItems(unchecked((int)Player)).Any(w => w.Id == unchecked((int)sword)), "not one of our items"); + } + + private static void OwnGear() + { + World(); + uint sword = Obj("Fire Tachi", TMelee, container: 0, wielder: Player); + uint shield = Obj("Kite Shield", TArmor, container: Player); + uint pack = 0x80310F00; + FakeHost.Names[pack] = "Pack"; + FakeHost.ItemTypes[pack] = TContainer; + FakeHost.Containers[pack] = Player; + uint gem = Obj("Black Opal", TGem, container: pack); + var c = Classify(sword, shield, gem); + Where(c, sword, AcObjectClass.MeleeWeapon, true, false, "our wielded sword"); + Where(c, shield, AcObjectClass.Armor, true, false, "our shield"); + Where(c, gem, AcObjectClass.Gem, true, false, "a gem in our side pack"); + } + + private static void GroundGearAndUnknownOwnership() + { + World(); + uint dropped = Obj("Fire Tachi", TMelee, container: 0); + uint unknownSword = Obj("Frost Tachi", TMelee, container: null); + uint unknownGem = Obj("Black Opal", TGem, container: null); + var c = Classify(dropped, unknownSword, unknownGem); + Where(c, dropped, AcObjectClass.MeleeWeapon, false, true, "a sword on the ground"); + Where(c, unknownSword, AcObjectClass.MeleeWeapon, true, false, "a sword whose owner can't be read (as before)"); + Where(c, unknownGem, AcObjectClass.Gem, false, true, "a gem whose owner can't be read"); + } + + private static void Hazards() + { + World(); + uint lava = Obj("Lava", TMisc, container: 0, cell: Dungeon); + uint lavaUnknownOwner = Obj("Pool of Acid", TMisc, container: null, cell: Dungeon + 1); + uint staticAcid = Obj("Pool of Acid", TMisc, container: null, cell: Dungeon + 2, id: 0x71D90002); + uint untyped = Obj("Magma", 0, container: null, cell: Dungeon + 3); + uint gear = Obj("Lava Gauntlets", TArmor, container: 0, cell: Dungeon + 4); + var c = Classify(lava, lavaUnknownOwner, staticAcid, untyped, gear); + Check.True(c.IsHazardCell(Dungeon), "a dynamic Misc lava hotspot registers its cell"); + Where(c, lava, AcObjectClass.Misc, false, true, "the lava hotspot"); + Check.True(c.IsHazardCell(Dungeon + 1), "a hotspot whose owner can't be read registers"); + Check.True(c.IsHazardCell(Dungeon + 2), "a static hotspot registers"); + Where(c, staticAcid, AcObjectClass.Unknown, false, true, "the static hotspot stays scenery"); + Check.True(c.IsHazardCell(Dungeon + 3), "an untyped hotspot registers"); + Check.False(c.IsHazardCell(Dungeon + 4), "gauntlets named Lava on the floor are not a hazard (as before)"); + Check.True(System.IO.Directory.Exists(System.IO.Path.Combine(Program.TempRoot, "DungeonHazards")), "hazards persist to the scratch folder, not C:\\Games"); + } + + private static void Corpses() + { + World(); + uint named = Obj("Corpse of Drudge Skulker", TContainer, container: 0); + uint late = Obj("", TContainer, container: 0); + var c = Classify(named, late); + Where(c, named, AcObjectClass.Corpse, false, true, "a named corpse"); + Where(c, late, AcObjectClass.Container, false, true, "a nameless container (before its name)"); + FakeHost.Names[late] = "Corpse of Drudge Ravener"; + Reclassify(c); + Where(c, late, AcObjectClass.Corpse, false, true, "named late: rescued as a corpse"); + + // The corpse flag alone, name never matching. + World(); + uint flagged = Obj("Drudge Remains", TContainer, container: 0); + FakeHost.Bitfields[flagged] = 0x2000; + var c2 = Classify(flagged); + Where(c2, flagged, AcObjectClass.Corpse, false, true, "a corpse by its weenie flag"); + } + + private static void LateType() + { + World(); + uint gem = Obj("Black Opal", 0, container: 0); + var c = Classify(gem); + Where(c, gem, AcObjectClass.Unknown, false, true, "no type yet: Unknown landscape"); + FakeHost.ItemTypes[gem] = TGem; + FakeHost.Logs.Clear(); + Reclassify(c); + Where(c, gem, AcObjectClass.Gem, false, true, "type arrived: a ground gem"); + Check.True(FakeHost.Logs.Any(l => l.Contains("typed 1 Unknown object", StringComparison.Ordinal)), "logged once"); + + // Our own item whose type arrives late goes to the inventory. + World(); + uint mine = Obj("Fire Tachi", 0, container: 0, wielder: Player); + var c2 = Classify(mine); + FakeHost.ItemTypes[mine] = TMelee; + Reclassify(c2); + Where(c2, mine, AcObjectClass.MeleeWeapon, true, false, "our sword typed late"); + + // A creature still wins: a late Creature type promotes, it is not filed as an item. + World(); + uint mob = Obj("Drudge Skulker", 0, container: 0); + var c3 = Classify(mob); + FakeHost.ItemTypes[mob] = 0x10; + Reclassify(c3); + Check.Eq(ClassOf(c3, mob), AcObjectClass.Monster, "a late creature type: Monster"); + } + + private static void LootClasses() + { + World(); + uint scroll = Obj("Scroll of Gift of Essence", TWritable, container: 0); + FakeHost.DataIds[(scroll, 28)] = 2001; + uint book = Obj("Tattered Journal", TWritable, container: 0); // no "Scroll" name, no spell + uint slayer = Obj("Driftwarden Greataxe", TMisc, container: 0); + FakeHost.Ints[(slayer, 9)] = 0x00100000; // ValidLocations: melee weapon slot + uint chest = Obj("Chest", TContainer, container: null, id: 0x71D90010); + uint stone = Obj("Life Stone", TLifeStone, container: null, id: 0x71D90011); + uint sign = Obj("Sign", TMisc, container: null, id: 0x71D90012); + var c = Classify(scroll, book, slayer, chest, stone, sign); + Where(c, scroll, AcObjectClass.Scroll, false, true, "a spell scroll on the ground"); + Where(c, book, AcObjectClass.Book, false, true, "a journal on the ground"); + Where(c, slayer, AcObjectClass.MeleeWeapon, false, true, "a Misc-typed weapon with a weapon slot"); + Where(c, chest, AcObjectClass.Container, false, true, "a static chest"); + Where(c, stone, AcObjectClass.Lifestone, false, true, "a lifestone"); + Where(c, sign, AcObjectClass.Unknown, false, true, "a static sign stays scenery"); + } +} diff --git a/Tools/RynthCore.RynthAiTests/RynthCore.RynthAiTests.csproj b/Tools/RynthCore.RynthAiTests/RynthCore.RynthAiTests.csproj index c8b5957..1ef3c51 100644 --- a/Tools/RynthCore.RynthAiTests/RynthCore.RynthAiTests.csproj +++ b/Tools/RynthCore.RynthAiTests/RynthCore.RynthAiTests.csproj @@ -41,4 +41,9 @@ + + + + + diff --git a/Tools/RynthLua.CompatTests/RynthLua.CompatTests.csproj b/Tools/RynthLua.CompatTests/RynthLua.CompatTests.csproj index 64d8e15..a9e04f9 100644 --- a/Tools/RynthLua.CompatTests/RynthLua.CompatTests.csproj +++ b/Tools/RynthLua.CompatTests/RynthLua.CompatTests.csproj @@ -30,6 +30,8 @@ + + @@ -37,4 +39,9 @@ + + + + + diff --git a/Tools/RynthLua.ScriptWindowsTests/RynthLua.ScriptWindowsTests.csproj b/Tools/RynthLua.ScriptWindowsTests/RynthLua.ScriptWindowsTests.csproj index bab5c1b..502dec1 100644 --- a/Tools/RynthLua.ScriptWindowsTests/RynthLua.ScriptWindowsTests.csproj +++ b/Tools/RynthLua.ScriptWindowsTests/RynthLua.ScriptWindowsTests.csproj @@ -38,4 +38,9 @@ + + + + + diff --git a/Tools/RynthNav.GraphTests/Program.cs b/Tools/RynthNav.GraphTests/Program.cs index 545376a..61147b6 100644 --- a/Tools/RynthNav.GraphTests/Program.cs +++ b/Tools/RynthNav.GraphTests/Program.cs @@ -37,6 +37,8 @@ internal static class Program Run(nameof(EndToEndAroundAWall), EndToEndAroundAWall); Run(nameof(LandmassesAndSameLand), LandmassesAndSameLand); Run(nameof(PathGoesRoundAPortal), PathGoesRoundAPortal); + Run(nameof(TripWalkFromTileFiles), TripWalkFromTileFiles); + Run(nameof(RealTripWalk), RealTripWalk); } finally { try { Directory.Delete(_root, true); } catch { } } Console.WriteLine(); @@ -385,4 +387,72 @@ internal static class Program double d = Math.Sqrt((nearPt.X - 95) * (nearPt.X - 95) + (nearPt.Z - 96) * (nearPt.Z - 96)); Check(nearRef != 0 && d >= PortalAvoid.LiveRadius - 0.01, $"a goal beside the portal snaps to ground outside its circle ({d:F2} u away)"); } + + // ── A planned trip's walk, from the tile files (TilePathFinder, on a worker in the plugin) ── + + private static void TripWalkFromTileFiles() + { + // The wall: from the south of tile 0 to the south of tile 2, the only way is round the north. + string dir = Bake("tripwall", (0, 0, 192, 192), (192, 150, 384, 192), (384, 0, 576, 192)); + BuildGraph(dir, out NavGraph g); + var from = new RynthCore.Plugin.RynthNav.WorldPt(100, 20, 0); + var to = new RynthCore.Plugin.RynthNav.WorldPt(480, 20, double.NaN); + var finder = new TilePathFinder(dir, g, null); + var path = finder.Walk(from, to, false, out string note); + Check(path != null && path.Count >= 4, $"a path round the wall ({path?.Count} corners; {note})"); + Check(note == "", "no gaps: " + note); + Check(path != null && path.Exists(p => p.Y > 150), "it goes north through the passage"); + Check(path != null && Math.Abs(path[^1].X - 480) < 3 && Math.Abs(path[^1].Y - 20) < 3, "and ends at the goal"); + Check(path != null && path.TrueForAll(p => !double.IsNaN(p.H) && Math.Abs(p.H) < 2), "heights from the navmesh"); + Check(finder.TilesRead >= 3, $"read the tiles it needed ({finder.TilesRead})"); + var thin = RynthCore.Plugin.RynthNav.TripPathBuilder.Thin(path!); + Check(thin.Exists(p => p.Y > 150), "thinned, it still goes round"); + + // Without the route graph, a short leg is planned on the tiles alone. + var direct = new TilePathFinder(dir, null, null).Walk(from, to, false, out string note2); + Check(direct != null && direct.Exists(p => p.Y > 150), "without the graph: the same way round (" + note2 + ")"); + // No navmesh at the far end: none, and why. + var nowhere = new TilePathFinder(dir, g, null).Walk(from, new RynthCore.Plugin.RynthNav.WorldPt(2000, 2000, 0), false, out string why); + Check(nowhere == null && why.Length > 0, "no tile at the end: no path (" + why + ")"); + + // An Atlas portal on the straight line over open ground: kept out of, unless it's the leg's own. + string open = Bake("tripportal", (0, 0, 192, 192)); + var spot = new[] { new PortalAvoid.Spot(95, 96, PortalAvoid.MapRadius, "Unwanted Portal") }; + var round = new TilePathFinder(open, null, spot).Walk(new(30, 96, 0), new(160, 96, 0), false, out _); + double gap = double.MaxValue; + for (int i = 1; round != null && i < round.Count; i++) gap = Math.Min(gap, PortalAvoid.SegmentDistance(95, 96, round[i - 1].X, round[i - 1].Y, round[i].X, round[i].Y)); + Check(round != null && gap >= PortalAvoid.MapRadius - 0.01, $"the walk keeps out of the portal's circle ({gap:F2} u)"); + var own = new TilePathFinder(open, null, spot).Walk(new(30, 96, 0), new(95, 96, 0), true, out _); + Check(own != null && Math.Abs(own[^1].X - 95) < 3, "walking into that portal: it's the goal, not avoided"); + } + + /// + /// The real map (read only, when it's installed): Holtburg to Lytelthorpe, about 11k yd over + /// land, as the path markers and "save as nav route" would work it out. Prints the size and time. + /// + private static void RealTripWalk() + { + string dir = Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData"; + string graphFile = Path.Combine(dir, NavGraph.FileName); + if (!File.Exists(graphFile)) { Console.WriteLine(" (no real NavData here: skipped)"); return; } + NavGraph g = NavGraph.Load(graphFile); + var from = RynthCore.Plugin.RynthNav.WorldPt.FromMap(42.08, 33.6, double.NaN); + var to = RynthCore.Plugin.RynthNav.WorldPt.FromMap(-0.8, 51.2, double.NaN); + // Landmasses, as the plugin has them (LoadGraph): Lytelthorpe's centre probes onto a roof, + // a landmass of one region; the ground beside it is found instead. + g.BuildComponents(); + var sw = System.Diagnostics.Stopwatch.StartNew(); + var finder = new TilePathFinder(dir, g, null); + var path = finder.Walk(from, to, false, out string note); + long ms = sw.ElapsedMilliseconds; + Check(path != null, "Holtburg to Lytelthorpe on the real navmesh: " + note); + if (path == null) return; + var thin = RynthCore.Plugin.RynthNav.TripPathBuilder.Thin(path); + int corners = RynthCore.Plugin.RynthNav.TripPathBuilder.Thin(path, maxSpacing: 0).Count; + double len = 0; + for (int i = 1; i < thin.Count; i++) len += thin[i - 1].FlatDistance(thin[i]); + Console.WriteLine($" Holtburg -> Lytelthorpe: {path.Count} corners, {corners} kept by thinning, {thin.Count} with a point every {RynthCore.Plugin.RynthNav.TripPathBuilder.MaxSpacing} yd, {len:F0} yd, {finder.TilesRead} tiles read, {ms} ms{(note.Length > 0 ? "; " + note : "")}"); + Check(len > from.FlatDistance(to) * 0.98 && len < from.FlatDistance(to) * 2.5, $"a sensible length ({len:F0} vs {from.FlatDistance(to):F0} straight)"); + Check(ms < 30000, $"worked out in reasonable time ({ms} ms)"); + } } diff --git a/Tools/RynthNav.GraphTests/RynthNav.GraphTests.csproj b/Tools/RynthNav.GraphTests/RynthNav.GraphTests.csproj index 58ab199..7dca34a 100644 --- a/Tools/RynthNav.GraphTests/RynthNav.GraphTests.csproj +++ b/Tools/RynthNav.GraphTests/RynthNav.GraphTests.csproj @@ -22,6 +22,13 @@ + + + + + + + diff --git a/Tools/RynthNav.RouteTests/Program.cs b/Tools/RynthNav.RouteTests/Program.cs index 6617d3d..048fe16 100644 --- a/Tools/RynthNav.RouteTests/Program.cs +++ b/Tools/RynthNav.RouteTests/Program.cs @@ -53,6 +53,7 @@ internal static partial class Program RunTownNet(); RunAvoid(); RunTravelPlan(); + RunTripExport(); Console.WriteLine(); Console.WriteLine(_fails == 0 && _asserts > 0 diff --git a/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj b/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj index 5b33ba9..cf9ea22 100644 --- a/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj +++ b/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj @@ -28,6 +28,14 @@ + + + + + + + + diff --git a/Tools/RynthNav.RouteTests/TripExportTests.cs b/Tools/RynthNav.RouteTests/TripExportTests.cs new file mode 100644 index 0000000..8f6943d --- /dev/null +++ b/Tools/RynthNav.RouteTests/TripExportTests.cs @@ -0,0 +1,389 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthNav; +using RynthCore.Plugin.Shared; +using RynthNav.Routing; + +namespace RynthNav.RouteTests; + +// A planned trip on the ground and as a RynthAi nav route: the trip's legs (PlannedTrip), the +// walking path thinned (TripPathBuilder), the path markers (PathMarkers: what's built, what's drawn, +// the next waypoint, when the markers go) and "save as nav route" (NavRouteExport: walks, recalls, +// portals and the Town Network as nav steps, read back with RynthAi's own reader; a file that's +// there isn't replaced without being asked). +internal static partial class Program +{ + private static void RunTripExport() + { + Run(nameof(ThinKeepsCornersAndSplitsStraights), ThinKeepsCornersAndSplitsStraights); + Run(nameof(StopShortAlongThePath), StopShortAlongThePath); + Run(nameof(TripLegsWalkRecallPortal), TripLegsWalkRecallPortal); + Run(nameof(TripPathStraightLineWhenNoMesh), TripPathStraightLineWhenNoMesh); + Run(nameof(ExportWalkRecallPortalRoundTrip), ExportWalkRecallPortalRoundTrip); + Run(nameof(ExportCommandRecallAndDungeonEntrance), ExportCommandRecallAndDungeonEntrance); + Run(nameof(ExportTownNetwork), ExportTownNetwork); + Run(nameof(ExportStopsAtAStepWithNoNavEquivalent), ExportStopsAtAStepWithNoNavEquivalent); + Run(nameof(SaveRefusesToOverwrite), SaveRefusesToOverwrite); + Run(nameof(MarkersBuiltFromTheTrip), MarkersBuiltFromTheTrip); + Run(nameof(MarkersEmitNearTheCharacter), MarkersEmitNearTheCharacter); + Run(nameof(MarkersNextWaypointAdvances), MarkersNextWaypointAdvances); + Run(nameof(MarkersClearOffTheTrip), MarkersClearOffTheTrip); + } + + // ── Helpers ────────────────────────────────────────────────────────── + + /// A navmesh-like path a→b: a point every 2 yd, swinging 10 yd out round an obstacle halfway. + private static List? FakeWalk(WorldPt a, WorldPt b, bool intoPortal, out string note) + { + note = ""; + var pts = new List(); + double len = a.FlatDistance(b); + int n = Math.Max(2, (int)(len / 2)); + double nx = -(b.Y - a.Y) / len, ny = (b.X - a.X) / len; // left of the way + for (int i = 0; i <= n; i++) + { + double t = (double)i / n; + double off = 10.0 * Math.Max(0, 1 - Math.Abs(t - 0.5) * 8); // a tent 10 yd high from t=0.375 to 0.625 + pts.Add(new WorldPt(a.X + (b.X - a.X) * t + nx * off, a.Y + (b.Y - a.Y) * t + ny * off, 5.0)); + } + return pts; + } + + private static PlannedTrip Trip(List steps, double startNs, double startEw, string goal, double goalNs, double goalEw, + List? recalls = null, string enterPortal = "", string enterName = "", bool startOnMap = true, int id = 1) + { + WorldPt start = WorldPt.FromMap(startNs, startEw, 5.0); + uint lb = start.Landblock; + uint cell = (lb << 16) | 0x0001; + return new PlannedTrip(id, steps, goal, goalNs, goalEw, startOnMap, start, cell, recalls, enterPortal, enterName); + } + + private sealed class Recorder : IMarkerSink + { + public readonly List<(float X, float Y, float Z, float R, uint C)> Rings = new(); + public readonly List<(float X1, float Y1, float Z1, float X2, float Y2, float Z2, uint C)> Lines = new(); + public int Tris; + public void Ring(float x, float y, float z, float radius, float thickness, uint colorArgb) => Rings.Add((x, y, z, radius, colorArgb)); + public void Line(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb) => Lines.Add((x1, y1, z1, x2, y2, z2, colorArgb)); + public void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint colorArgb) => Tris++; + } + + // ── Thinning ───────────────────────────────────────────────────────── + + private static void ThinKeepsCornersAndSplitsStraights() + { + // 100 yd east in 1 yd steps with 0.2 yd wobble, then 50 yd north; heights unknown at first. + var raw = new List(); + for (int i = 0; i <= 100; i++) raw.Add(new WorldPt(1000 + i, 1000 + (i % 2 == 0 ? 0.2 : -0.2), i < 3 ? double.NaN : 7)); + for (int i = 1; i <= 50; i++) raw.Add(new WorldPt(1100, 1000 + i, 7)); + raw.Add(new WorldPt(1100, 1050.1, 7)); // a near duplicate + List thin = TripPathBuilder.Thin(raw); + Check(thin.Count < 12, $"151 navmesh points thin to a few ({thin.Count})"); + Check(thin[0].FlatDistance(raw[0]) < 0.01 && thin[^1].FlatDistance(raw[^1]) < 0.6, "the ends are kept"); + Check(thin.Any(p => Math.Abs(p.X - 1100) < 0.6 && Math.Abs(p.Y - 1000) < 0.6), "the corner is kept"); + for (int i = 1; i < thin.Count; i++) + Check(thin[i - 1].FlatDistance(thin[i]) <= TripPathBuilder.MaxSpacing + 0.01, $"no stretch longer than {TripPathBuilder.MaxSpacing} yd ({i})"); + Check(thin.All(p => !double.IsNaN(p.H)), "unknown heights filled from the neighbours"); + foreach (WorldPt p in raw) + { + double best = double.MaxValue; + for (int i = 1; i < thin.Count; i++) best = Math.Min(best, PlannedTrip.SegmentDistance(p, thin[i - 1], thin[i])); + if (best > TripPathBuilder.ThinTolerance + 0.01) { Check(false, $"a dropped point is {best:F2} yd off the thinned path"); break; } + } + Check(TripPathBuilder.Thin(new List { new(0, 0, 1), new(0, 100, 1) }).Count == 3, "a 100 yd straight gets a point every 60 yd at most (2 stretches)"); + } + + private static void StopShortAlongThePath() + { + var path = new List { new(0, 0, 1), new(10, 0, 1), new(10, 3, 1) }; + List s = TripPathBuilder.StopShort(path, 5); + Check(s.Count == 2 && Math.Abs(s[^1].X - 8) < 1e-9 && Math.Abs(s[^1].Y) < 1e-9, "5 yd short, back round the corner"); + Check(TripPathBuilder.StopShort(path, 20).Count == 1, "shorter than that: only the start"); + Check(TripPathBuilder.StopShort(path, 0).Count == 3, "0: unchanged"); + } + + // ── The trip's legs ────────────────────────────────────────────────── + + private static void TripLegsWalkRecallPortal() + { + var steps = new List + { + new(10, 10, false, true, "Lifestone Recall", 0, 20, 20), // cast here, land at 20,20 + new(20.5, 20, true, false, "Portal to Far", -1, 50, 50), // walk to a portal, land at 50,50 + new(50.4, 50.3, false, false, "walk"), // walk to the goal + }; + var trip = Trip(steps, 10, 10, "Far Goal", 50.4, 50.3, new List { new("Lifestone Recall", 1635, "", 13) }); + Check(trip.WalkFrom[0] == null && trip.Point[0] is WorldPt c && c.FlatDistance(trip.Start) < 0.01, "a recall walks nowhere; it's cast at the start"); + Check(trip.WalkFrom[1] is WorldPt f1 && Math.Abs(f1.Ns - 20) < 1e-9 && Math.Abs(f1.Ew - 20) < 1e-9, "the next walk starts at the recall's landing"); + Check(trip.Point[1] is WorldPt p1 && Math.Abs(p1.Ns - 20.5) < 1e-9, "...and ends at the portal"); + Check(trip.WalkFrom[2] is WorldPt f2 && Math.Abs(f2.Ns - 50) < 1e-9, "the last walk starts at the portal's landing"); + Check(trip.RecallOf(0)?.SpellId == 1635 && trip.RecallOf(1) == null, "the recall by index"); + + // A portal into a dungeon (no landing on the map) and nothing after it: the dungeon goto. + var into = Trip(new List { new(10.2, 10.2, true, false, "Matron Hive") }, 10, 10, "Matron Hive", 10.2, 10.2, + enterPortal: "Portal to Matron Hive", enterName: "Matron Hive"); + Check(into.EndsInEntrance && into.PortalName(0) == "Portal to Matron Hive", "a dungeon goto's portal is the portal object, not the dungeon's name"); + // No steps: a plain walk to the goal. + var plain = Trip(new List(), 10, 10, "Near", 10.3, 10.1); + Check(plain.Count == 1 && plain.WalkFrom[0] != null && !plain.Steps[0].UsePortal, "no steps = one walk"); + } + + private static void TripPathStraightLineWhenNoMesh() + { + var trip = Trip(new List { new(10.5, 10, false, false, "walk") }, 10, 10, "G", 10.5, 10); + TripPath p = TripPathBuilder.Build(trip, (WorldPt a, WorldPt b, bool ip, out string note) => { note = "no navmesh at its start"; return null; }, null); + Check(p.Walks[0] != null && p.Walks[0]!.Length == 3, $"a straight line, split every 60 yd (120 yd: {p.Walks[0]?.Length})"); + Check(p.Notes.Count == 1 && p.Notes[0].Contains("step 1") && p.Notes[0].Contains("straight"), "...with a note: " + string.Join("; ", p.Notes)); + TripPath q = TripPathBuilder.Build(trip, FakeWalk, null); + Check(q.Notes.Count == 0 && q.Walks[0]!.Length < 20, $"the navmesh path, thinned ({q.Walks[0]!.Length} points)"); + Check(q.Walks[0]!.Any(w => PlannedTrip.SegmentDistance(w, trip.Start, trip.Point[0]!.Value) > 9), "it keeps the swing round the obstacle"); + } + + // ── Save as nav route ──────────────────────────────────────────────── + + private static void ExportWalkRecallPortalRoundTrip() + { + var steps = new List + { + new(10, 10, false, true, "Lifestone Recall", 0, 20, 20), + new(20.5, 20, true, false, "Portal to Far", -1, 50, 50), + new(50.4, 50.3, false, false, "walk"), + }; + var trip = Trip(steps, 10, 10, "Far Goal", 50.4, 50.3, new List { new("Lifestone Recall", 1635, "", 13) }); + TripPath path = TripPathBuilder.Build(trip, FakeWalk, null); + NavRouteExport.Result r = NavRouteExport.Convert(trip, path, null); + Check(r.StoppedAt == -1 && r.StopReason == "", "the whole trip converts: " + r.StopReason); + List pts = r.Route.Points; + Check(r.Route.RouteType == NavRouteType.Once, "a Once route"); + Check(pts[0].Type == NavPointType.Recall && pts[0].SpellId == 1635, "first: the recall spell"); + int portal = pts.FindIndex(p => p.Type == NavPointType.PortalNPC); + Check(portal > 1, "then walking points, then the portal step"); + Check(pts.Skip(1).Take(portal - 1).All(p => p.Type == NavPointType.Point), "walking legs are Points"); + Check(portal - 1 < 15, $"thinned: not every navmesh corner ({portal - 1} points for 120 yd with an obstacle)"); + NavPoint pn = pts[portal]; + Check(pn.TargetName == "Portal to Far" && pn.ObjectClass == NavRouteExport.PortalObjectClass && pn.IsTie, "the portal by name, VTank's portal class"); + Check(Math.Abs(pn.PortalExitNS - 20.5) < 1e-6 && Math.Abs(pn.PortalExitEW - 20) < 1e-6, "at the portal's entrance"); + NavPoint before = pts[portal - 1]; + double toPortal = NavCoords.Distance(before.NS, before.EW, 20.5, 20); + Check(toPortal > NavRouteExport.PortalStopShort - 0.5 && toPortal < 12, $"the walk stops short of the entrance ({toPortal:F1} yd)"); + Check(pts[^1].Type == NavPointType.Point && NavCoords.Distance(pts[^1].NS, pts[^1].EW, 50.4, 50.3) < 0.5, "the last point is the goal"); + Check(NavCoords.Distance(pts[portal + 1].NS, pts[portal + 1].EW, 50, 50) < TripPathBuilder.MaxSpacing, "after the portal the walk starts near its landing"); + Check(pts.Where(p => p.Type == NavPointType.Point).All(p => Math.Abs(p.Z - 5.0 / 240.0) < 1e-9), "heights in nav units (metres / 240)"); + + // Read back with RynthAi's own reader. + var back = NavRouteParser.LoadFromLines(r.Route.ToLines()); + Check(back.LoadWarning == null && back.Points.Count == pts.Count && back.RouteType == NavRouteType.Once, "RynthAi reads it back whole"); + bool same = true; + for (int i = 0; i < pts.Count && same; i++) + same = back.Points[i].Type == pts[i].Type && Math.Abs(back.Points[i].NS - pts[i].NS) < 1e-9 && Math.Abs(back.Points[i].EW - pts[i].EW) < 1e-9 + && back.Points[i].SpellId == pts[i].SpellId && back.Points[i].TargetName == pts[i].TargetName && back.Points[i].ObjectClass == pts[i].ObjectClass; + Check(same, "every step the same after the round trip"); + Check(r.Waypoints + r.Portals + r.Recalls == pts.Count, "the counts add up"); + } + + private static void ExportCommandRecallAndDungeonEntrance() + { + var steps = new List + { + new(10, 10, false, true, "@lifestone", 0, 20, 20), + new(20.3, 20.2, true, false, "Matron Hive"), // Entrance.EndingInPortal labels it with the dungeon + }; + var trip = Trip(steps, 10, 10, "Matron Hive", 20.3, 20.2, new List { new("@lifestone", 0, "@lifestone", 15) }, + enterPortal: "Portal to Matron Hive", enterName: "Matron Hive"); + NavRouteExport.Result r = NavRouteExport.Convert(trip, TripPathBuilder.Build(trip, FakeWalk, null), null); + List pts = r.Route.Points; + Check(pts[0].Type == NavPointType.Chat && pts[0].ChatCommand == "@lifestone", "a command recall is a chat step"); + Check(pts[1].Type == NavPointType.Pause && pts[1].PauseTimeMs == NavRouteExport.CommandRecallPauseMs, "...and a pause for its teleport"); + Check(pts[^1].Type == NavPointType.PortalNPC && pts[^1].TargetName == "Portal to Matron Hive", "it ends with the dungeon's entrance portal, by the portal's name"); + Check(r.StoppedAt == -1, "nothing left out"); + var back = NavRouteParser.LoadFromLines(r.Route.ToLines()); + Check(back.Points.Count == pts.Count && back.Points[0].ChatCommand == "@lifestone" && back.Points[1].PauseTimeMs == NavRouteExport.CommandRecallPauseMs, + "read back by RynthAi"); + } + + private static void ExportTownNetwork() + { + TownNet net = TownNet.Parse(SmallTownNet(), out _)!; + var steps = PortalRoute.Plan(NoPortals, null, net.Links(90, false, null), 0, 0, 40, 40, out _, out int used); + Check(used == 2 && steps.Count == 3 && steps[1].IsHub, "the plan: walk to the entry, the network, walk on"); + var trip = Trip(steps, 0, 0, "Eastwatch", 40, 40); + TripPath path = TripPathBuilder.Build(trip, FakeWalk, net); + Check(path.Hub[1] != null && path.Hub[1]!.Length >= 2, "the walk inside comes from townnet.json"); + NavRouteExport.Result r = NavRouteExport.Convert(trip, path, net); + List pts = r.Route.Points; + var portals = pts.Where(p => p.Type == NavPointType.PortalNPC).ToList(); + Check(r.StoppedAt == -1 && portals.Count == 2, "two portal steps: " + r.StopReason); + Check(portals[0].TargetName == "Portal to Town Network" && portals[1].TargetName == "Portal to Eastwatch", "into the network, then the exit by name"); + int exit = pts.IndexOf(portals[1]), entry = pts.IndexOf(portals[0]); + Check(exit - entry >= 2, "waypoints inside the network between them"); + // Inside: the network's landblock 0x0007 (coordinates the way RynthAi reads a dungeon pose). + // The stored walk (60,-70) to (70,-70) to (86.5,-70) is one straight line: thinned to its end, + // stopped 2 yd short of the exit portal. + NavCoordinateHelper(0x0007016Bu, 84.5, -70, out double ins, out double iew); + Check(pts.Skip(entry + 1).Take(exit - entry - 1).Any(p => Math.Abs(p.NS - ins) < 0.001 && Math.Abs(p.EW - iew) < 0.001), "inside points in dungeon coordinates"); + NavCoordinateHelper(0x0007016Bu, 86.5, -70, out double xns, out double xew); + Check(Math.Abs(portals[1].PortalExitNS - xns) < 1e-6 && Math.Abs(portals[1].PortalExitEW - xew) < 1e-6, "the exit portal where it stands"); + + // Without townnet.json: stop before the network, say why. + NavRouteExport.Result none = NavRouteExport.Convert(trip, TripPathBuilder.Build(trip, FakeWalk, null), null); + Check(none.StoppedAt == 1 && none.StopReason.Contains("Town Network"), "no network data: stops at it: " + none.StopReason); + Check(none.Route.Points.Count > 0 && none.Route.Points[^1].Type == NavPointType.PortalNPC, "...keeping the walk to the entry portal"); + } + + private static void NavCoordinateHelper(uint cell, double x, double y, out double ns, out double ew) => NavCoords.FromCell(cell, x, y, out ns, out ew); + + private static void ExportStopsAtAStepWithNoNavEquivalent() + { + var steps = new List + { + new(10.2, 10, false, false, "walk"), + new(10.2, 10, false, true, "Some Recall", 3, 20, 20), // index 3: not in the trip's recalls + new(20.1, 20, false, false, "walk"), + }; + var trip = Trip(steps, 10, 10, "G", 20.1, 20, new List()); + NavRouteExport.Result r = NavRouteExport.Convert(trip, TripPathBuilder.Build(trip, FakeWalk, null), null); + Check(r.StoppedAt == 1 && r.StopReason.StartsWith("step 2:") && r.StopReason.Contains("Some Recall"), "stops at the recall it can't cast: " + r.StopReason); + Check(r.Route.Points.Count > 0 && r.Route.Points.All(p => p.Type == NavPointType.Point), "the walk before it is kept"); + + var other = Trip(steps, 10, 10, "G", 20.1, 20, new List(), id: 2); + NavRouteExport.Result wrong = NavRouteExport.Convert(other, TripPathBuilder.Build(trip, FakeWalk, null), null); + Check(wrong.StoppedAt == 0 && wrong.Route.Points.Count == 0, "a path from another trip isn't used"); + } + + private static void SaveRefusesToOverwrite() + { + string dir = Path.Combine(Path.GetTempPath(), "rnav-save-" + Guid.NewGuid().ToString("N")); + try + { + var trip = Trip(new List { new(10.2, 10, false, false, "walk") }, 10, 10, "G", 10.2, 10); + NavRouteParser route = NavRouteExport.Convert(trip, TripPathBuilder.Build(trip, FakeWalk, null), null).Route; + Check(NavRouteExport.Save(dir, "To G", route, false, out string path, out bool exists, out string err) && !exists && err == "", + "a new file is written (the folder made): " + err); + string first = File.ReadAllText(path); + Check(NavRouteParser.Load(path).Points.Count == route.Points.Count, "RynthAi loads the file"); + + var other = new NavRouteParser { RouteType = NavRouteType.Once }; + other.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 1, EW = 2 }); + Check(!NavRouteExport.Save(dir, "To G", other, false, out _, out exists, out _) && exists, "the same name again: refused"); + Check(File.ReadAllText(path) == first, "...and the file is untouched"); + Check(!File.Exists(path + ".tmp"), "no temporary file left"); + Check(NavRouteExport.Save(dir, "To G", other, true, out _, out _, out _) && NavRouteParser.Load(path).Points.Count == 1, "overwrite: replaced"); + + Check(NavRouteExport.FileName(" To Holtburg.nav ", out _) == "To Holtburg", "a typed name: trimmed, without .nav"); + Check(NavRouteExport.FileName("a/b", out string e1) == "" && e1.Length > 0, "a path isn't a name"); + Check(NavRouteExport.FileName("..", out _) == "" && NavRouteExport.FileName("", out _) == "", "nor .. or nothing"); + Check(NavRouteExport.SafeName("To Lin: \"Town\"?") == "To Lin Town", "a place's name made safe for a file"); + } + finally { try { Directory.Delete(dir, true); } catch { } } + } + + // ── Markers ────────────────────────────────────────────────────────── + + private static (PlannedTrip Trip, TripPath Path) MarkerTrip() + { + var steps = new List + { + new(10, 10, false, true, "Lifestone Recall", 0, 20, 20), + new(20.5, 20, true, false, "Portal to Far", -1, 50, 50), + new(50.4, 50.3, false, false, "walk"), + }; + var trip = Trip(steps, 10, 10, "Far Goal", 50.4, 50.3, new List { new("Lifestone Recall", 1635, "", 13) }); + return (trip, TripPathBuilder.Build(trip, FakeWalk, null)); + } + + private static void MarkersBuiltFromTheTrip() + { + var (trip, path) = MarkerTrip(); + MarkerSnapshot bare = PathMarkers.Build(trip, null, null); + Check(!bare.HasPath && bare.Marks.Length == 3, $"without the path: the steps' markers only ({bare.Marks.Length})"); + Check(bare.Marks[0].Kind == MarkKind.Recall && bare.Marks[0].Label.StartsWith("RECALL LIFESTONE") && bare.Marks[0].Label.Length <= PathMarkers.MaxLabelChars, + "the recall, where it's cast: " + bare.Marks[0].Label); + Check(bare.Marks[1].Kind == MarkKind.Portal && bare.Marks[1].Label.StartsWith("PORTAL"), "the portal at its entrance"); + Check(bare.Marks[2].Kind == MarkKind.Goal && bare.Marks[2].Label == "FAR GOAL", "the goal"); + Check(bare.Marks.All(m => !m.LineToNext), "no lines over ground not worked out yet"); + + MarkerSnapshot s = PathMarkers.Build(trip, path, null); + Check(s.HasPath && s.Marks.Length > 6, $"with the path: the waypoints too ({s.Marks.Length})"); + int portal = Array.FindIndex(s.Marks, m => m.Kind == MarkKind.Portal); + Check(!s.Marks[portal].LineToNext && !s.Marks[0].LineToNext, "no line across a teleport (after the portal, after the recall)"); + Check(s.Marks[portal - 1].LineToNext && s.Marks[portal - 1].Kind == MarkKind.Waypoint, "a line into the portal"); + Check(s.Marks.Count(m => m.Kind == MarkKind.Goal) == 1 && s.Marks[^1].Kind == MarkKind.Goal, "the goal last"); + for (int i = 1; i < s.Marks.Length; i++) + if (s.Marks[i].P.FlatDistance(s.Marks[i - 1].P) < 0.99) { Check(false, $"two markers on one spot ({i})"); break; } + Check(PathMarkers.Build(trip, TripPathBuilder.Build(Trip(trip.Steps.ToList(), 10, 10, "x", 1, 1, id: 9), FakeWalk, null), null).HasPath == false, + "another trip's path isn't drawn"); + } + + private static void MarkersEmitNearTheCharacter() + { + var (trip, path) = MarkerTrip(); + MarkerSnapshot s = PathMarkers.Build(trip, path, null); + WorldPt landing = WorldPt.FromMap(20.3, 20); // on the walk from the recall's landing to the portal, 48 yd short of it + var rec = new Recorder(); + int rings = PathMarkers.Emit(s, new MarkerView(landing.X, landing.Y, 5.0, -1, true, true), rec); + Check(rings > 3 && rec.Rings.Count == rings, $"rings near the character ({rings})"); + Check(rec.Lines.Count > 2, "lines between them"); + Check(rec.Lines[0].C == PathMarkers.GuideColor, "the guide line goes in first"); + float lx = (float)(landing.X - Math.Floor(landing.X / 192) * 192), lz = (float)(landing.Y - Math.Floor(landing.Y / 192) * 192); + Check(Math.Abs(rec.Lines[0].X1 - lx) < 0.01 && Math.Abs(rec.Lines[0].Z1 - lz) < 0.01, "...from the character's feet, in the landblock's frame"); + Check(rec.Rings.Any(r => r.C == PathMarkers.PortalColor), "the portal in its own colour"); + Check(rec.Rings.All(r => r.X > -200 && r.X < 400 && r.Z > -200 && r.Z < 400 && Math.Abs(r.Y - 5.1f) < 0.01), "landblock-local, at path height"); + Check(rec.Tris > 0, "the portal's label drawn (triangles)"); + Check(!rec.Rings.Any(r => r.C == PathMarkers.GoalColor), "the goal, far away, isn't drawn"); + + var off = new Recorder(); + PathMarkers.Emit(s, new MarkerView(landing.X, landing.Y, 5.0, -1, false, false), off); + Check(off.Tris == 0 && off.Lines.All(l => l.C != PathMarkers.GuideColor), "labels and guide off: neither"); + + WorldPt far = WorldPt.FromMap(80, 80); + var none = new Recorder(); + Check(PathMarkers.Emit(s, new MarkerView(far.X, far.Y, 0, -1, true, true), none) == 0 && none.Lines.Count == 0, "nothing far from the trip"); + + // A long dense walk: at most MaxWaypointRings rings. + var many = new List(); + for (int i = 0; i < 200; i++) many.Add(new Mark(new WorldPt(1000 + i, 1000, 1), MarkKind.Waypoint, "", 0, true)); + var dense = new MarkerSnapshot(5, true, many.ToArray()); + var cap = new Recorder(); + PathMarkers.Emit(dense, new MarkerView(1100, 1000, 1, 100, false, false), cap); + Check(cap.Rings.Count <= PathMarkers.MaxWaypointRings + 1 && cap.Lines.Count <= PathMarkers.MaxLines, $"capped ({cap.Rings.Count} rings, {cap.Lines.Count} lines)"); + Check(cap.Rings.Count(r => r.C == PathMarkers.NextColor) == 1, "the next waypoint in red"); + } + + private static void MarkersNextWaypointAdvances() + { + var marks = new List(); + for (int i = 0; i <= 10; i++) marks.Add(new Mark(new WorldPt(1000 + i * 10, 1000, 1), MarkKind.Waypoint, "", 0, true)); + marks.Add(new Mark(new WorldPt(1100, 1010, 1), MarkKind.Portal, "PORTAL X", 0, false)); + marks.Add(new Mark(new WorldPt(3000, 3000, 1), MarkKind.Goal, "G", 1, false)); + var s = new MarkerSnapshot(1, true, marks.ToArray()); + int next = PathMarkers.Advance(s, -1, 0, 1000, 1000); + Check(next == 1, $"standing on the first: the next is the second ({next})"); + next = PathMarkers.Advance(s, next, 0, 1033, 1001); + Check(next == 4, $"part way along: the one ahead ({next})"); + Check(PathMarkers.Advance(s, next, 0, 1005, 1000) == 4, "never back"); + Check(PathMarkers.Advance(s, next, 0, 1100, 1009) == 11, "at the end: the portal (the step's own marker)"); + Check(PathMarkers.Advance(s, 11, 1, 2900, 2900) == 12, "next step: its first marker"); + Check(PathMarkers.Advance(s, 0, 7, 0, 0) == -1, "a step with no markers: none"); + } + + private static void MarkersClearOffTheTrip() + { + var (trip, path) = MarkerTrip(); + uint startLb = (trip.StartCell >> 16) & 0xFFFF; + Check(trip.Covers(startLb, path, null), "where it starts"); + Check(trip.Covers(WorldPt.FromMap(20, 20).Landblock, path, null), "the recall's landing"); + Check(trip.Covers(WorldPt.FromMap(35, 35).Landblock, path, null) == false, "between the portal and its landing (a teleport) isn't on it"); + Check(trip.Covers(WorldPt.FromMap(50.2, 50.1).Landblock, path, null), "the last walk"); + Check(!trip.Covers(WorldPt.FromMap(-60, -60).Landblock, path, null), "a teleport elsewhere isn't"); + Check(trip.Covers(0, path, null), "portal space (landblock 0) doesn't count against it"); + + TownNet net = TownNet.Parse(SmallTownNet(), out _)!; + var steps = PortalRoute.Plan(NoPortals, null, net.Links(90, false, null), 0, 0, 40, 40, out _, out _); + var hubTrip = Trip(steps, 0, 0, "Eastwatch", 40, 40); + Check(hubTrip.Covers(0x0007, null, net.Contains), "inside the Town Network on a trip that takes it"); + Check(!trip.Covers(0x0007, path, net.Contains), "...but not on one that doesn't"); + } +} From dafd6084a75a8c8e372342c4afa2f4f6a7881eec Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Tue, 6 Oct 2026 11:21:16 -0400 Subject: [PATCH 2/6] Snapshot for release 2026.10.6.2 (internal e3a94cf) Faster weapon switches; T11 loot support (by SilentKelpie, rynth/RynthSuite PR #3). --- .../Combat/AcStubs.cs | 20 +- .../Combat/BuffManager.cs | 21 +- .../Combat/CombatManager.Ammo.cs | 1 + .../Combat/CombatManager.Offhand.cs | 2 + .../Combat/CombatManager.cs | 25 +- .../Combat/WeaponSwapGate.cs | 68 +++- .../LegacyUi/LegacyDashboardRenderer.cs | 3 + .../LegacyUi/LegacyUiSettings.cs | 8 + .../Loot/T11ItemSupport.cs | 116 ++++++ .../RynthAiCommands.cs | 1 + .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 10 + .../RynthAiT11Command.cs | 124 +++++++ Plugins/Shared/ActionPacer.cs | 2 +- .../RynthCore.LootSdk/Editing/LootRuleText.cs | 41 ++- Shared/RynthCore.LootSdk/T11/T11Catalog.cs | 197 ++++++++++ Shared/RynthCore.LootSdk/T11/T11ItemInfo.cs | 348 ++++++++++++++++++ Shared/RynthCore.LootSdk/T11/T11Keys.cs | 161 ++++++++ Shared/RynthCore.LootSdk/T11/T11PlayerAugs.cs | 138 +++++++ Tools/RynthCore.LootSdkTests/LootT11Tests.cs | 210 +++++++++++ .../LootValueNameTests.cs | 2 +- Tools/RynthCore.LootSdkTests/Program.cs | 1 + Tools/RynthCore.RynthAiHostTests/Program.cs | 1 + .../Tests/OffhandTests.cs | 52 +++ .../Tests/T11LootTests.cs | 127 +++++++ 24 files changed, 1645 insertions(+), 34 deletions(-) create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Loot/T11ItemSupport.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiT11Command.cs create mode 100644 Shared/RynthCore.LootSdk/T11/T11Catalog.cs create mode 100644 Shared/RynthCore.LootSdk/T11/T11ItemInfo.cs create mode 100644 Shared/RynthCore.LootSdk/T11/T11Keys.cs create mode 100644 Shared/RynthCore.LootSdk/T11/T11PlayerAugs.cs create mode 100644 Tools/RynthCore.LootSdkTests/LootT11Tests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/T11LootTests.cs diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs index 03f889c..c9ff602 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs @@ -39,6 +39,8 @@ public enum LongValueKey public enum StringValueKey { Name = 1, + // ACECustom puts the T11 "Modifiers:" block of armor, clothing and jewelry here. + Use = 14, ShortDesc = 15, LongDesc = 16, PluralName = 20, @@ -117,13 +119,27 @@ public class WorldObject public int Values(int key, int defaultValue) { + // T11 virtual keys are computed from the item's text, never stored on the object. + if (RynthCore.Loot.T11.T11Keys.IsVirtual(key)) + return Loot.T11ItemSupport.VirtualValue(this, key, defaultValue); + var o = Overlay; if (o != null) { if (o.Ints.TryGetValue(unchecked((uint)key), out int v)) return v; - if (!o.LiveFallback) return defaultValue; + if (!o.LiveFallback) return Loot.T11ItemSupport.StrippedValue(this, key, defaultValue); } - return Cache?.GetIntProperty(Id, (uint)key, defaultValue) ?? defaultValue; + if (Cache == null) return Loot.T11ItemSupport.StrippedValue(this, key, defaultValue); + + // T11 appraisals omit the item-aug wield gate (158-160) and modifier-carried ratings + // (370-379); an absent or zero value there falls back to what the item's text says. + if (RynthCore.Loot.T11.T11Keys.IsStrippedKey(key)) + { + int live = Cache.GetIntProperty(Id, (uint)key, int.MinValue); + if (live != int.MinValue && live != 0) return live; + return Loot.T11ItemSupport.StrippedValue(this, key, live == int.MinValue ? defaultValue : 0); + } + return Cache.GetIntProperty(Id, (uint)key, defaultValue); } public string Values(StringValueKey key, string defaultValue) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index f71a21a..72fd7f8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -328,6 +328,13 @@ public class BuffManager : IDisposable // stow the bow into a capacity-verified open pack FIRST (AutoCram pattern), then wield // the wand. All paths are bounded so a stale/no-op dequip or unwieldable wand can never // loop forever; on exhaustion the buff family is parked and the bot fights unbuffed. + // Switch like a player (2026-10-06): a use of the wand goes through ClientUISystem::UseObject, + // the client's double-click, which puts the weapon in hand away by itself (ACE's + // DoHandleActionGetAndWieldItem: "the client handles dequipping a lot of conflicting items + // automatically"). Drakkon's axe -> wand took 4.2 s with the pack move first (1.2 s for it, + // then the swap gate's flat 3 s). The pack move stays as the fallback: once a use hasn't + // got the wand into the hand in WieldResolveTimeoutMs, this session moves the weapon first. + private bool _directWandSwapFailed; private int _bowDequipPendingId; private DateTime _bowDequipAt = DateTime.MinValue; private int _bowDequipAttempts; @@ -3893,6 +3900,15 @@ public class BuffManager : IDisposable if ((now - _pendingWieldAt).TotalMilliseconds < WieldResolveTimeoutMs) return false; + int stillInHand = _directWandSwapFailed ? 0 : FindWieldedNonWandWeapon(wandId); + if (stillInHand != 0 && IsWieldedLive(stillInHand)) + { + _directWandSwapFailed = true; + _pendingWieldId = 0; + _host.Log($"[WieldGate] using the wand didn't put 0x{(uint)stillInHand:X8} away in {WieldResolveTimeoutMs:0} ms; " + + "from now on the weapon goes into a pack first"); + return false; + } _host.Log($"[WieldGate] UseObject(0x{(uint)_pendingWieldId:X8}) not confirmed in " + $"{WieldResolveTimeoutMs:0}ms — cooling down {WieldCooldownMs:0}ms"); _pendingWieldId = 0; @@ -3930,7 +3946,7 @@ public class BuffManager : IDisposable // non-wand weapon into a capacity-verified open pack FIRST (AutoCram pattern, // AV-safe), then UseObject(wand) once the hand is free. Fully bounded. int bowId = FindWieldedNonWandWeapon(wandId); - if (bowId != 0) + if (bowId != 0 && (_directWandSwapFailed || !IsWieldedLive(bowId))) // else the use swaps (see _directWandSwapFailed) { if (_bowDequipPendingId == bowId && (now - _bowDequipAt).TotalMilliseconds < WieldResolveTimeoutMs @@ -3953,6 +3969,7 @@ public class BuffManager : IDisposable if (_worldObjectCache?[bowId] is WorldObject blocker && IsInOffhandSlot(blocker)) OffhandStowed?.Invoke(bowId); // a shield: combat puts it back after _host.MoveItemInternal((uint)bowId, (uint)openPack, 0, 1); // amount>=1 (engine rejects 0) + _weaponSwapGate?.NoteMove(bowId, wieldedNow: true); _bowDequipPendingId = bowId; _bowDequipAt = now; _lastCastAttempt = now; @@ -3962,7 +3979,7 @@ public class BuffManager : IDisposable _bowDequipPendingId = 0; // bow confirmed unwielded — fall through to wield the wand } - _host.UseFor((uint)wandId, "Buff", "buffing: wield the wand"); + _host.UseFor((uint)wandId, "Buff", bowId != 0 && !_directWandSwapFailed ? "buffing: switch to the wand" : "buffing: wield the wand"); NoteStanceRequest(); _pendingWieldId = wandId; _pendingWieldAt = now; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs index 752de5f..3599cfd 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs @@ -220,6 +220,7 @@ public partial class CombatManager var wo = _worldFilter[wielded.Id]; int amount = Math.Max(1, wo?.Values(LongValueKey.StackCount, 1) ?? 1); // the whole stack, not one arrow _host.MoveItemInternal(unchecked((uint)wielded.Id), unchecked((uint)packId), 0, amount); + _weaponSwapGate?.NoteMove(wielded.Id, wieldedNow: true); _ammoDequipPendingId = wielded.Id; _ammoDequipAt = now; _ammoDequipTries++; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs index 95e0371..e163141 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs @@ -285,6 +285,7 @@ public partial class CombatManager if (!gateHeld && _weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("combat-offhand-dequip")) return OffPrep.Busy; _host.MoveItemInternal(unchecked((uint)offId), unchecked((uint)packId), 0, 1); + _weaponSwapGate?.NoteMove(offId, wieldedNow: true); _offDequipPendingId = offId; _offDequipAt = now; _offDequipTries++; @@ -379,6 +380,7 @@ public partial class CombatManager if (_host.HasGetLastUseDone && _host.TryGetLastUseDone(out int uSeq, out _)) _swapUseDoneSeq = uSeq; if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int wSeq, out _, out _, out _)) _swapWeenieSeq = wSeq; OffhandTracker.Sent(plan.Id, _offSwapFrom, now); + _weaponSwapGate?.NoteMove(plan.Id, wieldedNow: false); _offSwapFrom = 0; _lastEquipTime = now; if (plan.Id != _stowedOffhandId) _stowedOffhandId = 0; // a listed one replaces what was taken off diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index 9131b2b..9e23a11 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -113,6 +113,12 @@ public partial class CombatManager : IDisposable // Combat must stow the bow into an open pack FIRST, then UseObject(wand), and // only request Magic once the wand is actually wielded (handled by the // alreadyWielded branch). Mirrors the proven BuffManager.EnsureMagicMode path. + // Switch like a player (2026-10-06, see BuffManager._directWandSwapFailed): the wand's use + // puts the weapon in hand away by itself; the pack move first is the fallback once a use + // hasn't done it in DirectWandSwapFallbackMs. + private bool _combatDirectWandSwapFailed; + private DateTime _combatDirectSwapSince = DateTime.MinValue; + private const double DirectWandSwapFallbackMs = 2000; // SwapTracker retries at 2500: that retry is the pack move private int _combatBowDequipPendingId; private int _combatBowDequipAttempts; private DateTime _combatBowDequipAt = DateTime.MinValue; @@ -146,6 +152,7 @@ public partial class CombatManager : IDisposable _combatBowDequipPendingId = 0; _combatBowDequipAttempts = 0; _combatSwapTeardownDone = false; + _combatDirectSwapSince = DateTime.MinValue; } // ── Face-before-attack state ───────────────────────────────────────── @@ -4068,7 +4075,9 @@ public partial class CombatManager : IDisposable // nothing when the wand genuinely isn't wielded: ACE just denies it, and the // gated UseObject below still does the wielding. Mirrors the non-wand branch, // which has always sent both. - if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs() + // A weapon still in hand: the wand's use swaps it and the server then puts us in Magic. + if (FindWieldedNonWandWeapon(targetWeaponId) == 0 + && (DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs() && _host.ChangeCombatModeFor(desiredMode, "Combat", "stance")) { if (diagNow) _host.Log($"[EquipDiag] hand clear — ChangeCombatMode({desiredMode}) alongside wand equip (mode={CurrentCombatMode})"); @@ -4156,6 +4165,16 @@ public partial class CombatManager : IDisposable private bool EnsureHandClearForWand(int wandId, bool diagNow) { int bowId = FindWieldedNonWandWeapon(wandId); + DateTime now = DateTime.Now; + if (bowId != 0 && !_combatDirectWandSwapFailed && IsWieldedLive(bowId)) + { + if (_combatDirectSwapSince == DateTime.MinValue) _combatDirectSwapSince = now; + if ((now - _combatDirectSwapSince).TotalMilliseconds <= DirectWandSwapFallbackMs) + return true; // the wand's use swaps + _combatDirectWandSwapFailed = true; + _host.Log($"[EquipDiag] using the wand didn't put 0x{(uint)bowId:X8} away in {DirectWandSwapFallbackMs:0} ms; from now on the weapon goes into a pack first"); + } + _combatDirectSwapSince = DateTime.MinValue; if (bowId == 0) { _combatBowDequipPendingId = 0; _combatBowDequipAttempts = 0; @@ -4165,7 +4184,6 @@ public partial class CombatManager : IDisposable return ClearOffhandFor(wandId, _curOffhandMode, gateHeld: true) == OffPrep.Ready; } - DateTime now = DateTime.Now; if (_combatBowDequipPendingId == bowId && (now - _combatBowDequipAt).TotalMilliseconds < WandSwapWieldResolveMs && IsWieldedLive(bowId)) @@ -4173,7 +4191,7 @@ public partial class CombatManager : IDisposable if (IsWieldedLive(bowId)) { - int openPack = WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1); + int openPack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1); if (openPack == 0 || _combatBowDequipAttempts >= CombatBowDequipMaxAttempts) { // No verified-open pack to receive the bow, or repeated failures — the swap @@ -4192,6 +4210,7 @@ public partial class CombatManager : IDisposable } _combatBowDequipAttempts++; _host.MoveItemInternal((uint)bowId, (uint)openPack, 0, 1); // amount>=1 (engine rejects 0) + _weaponSwapGate?.NoteMove(bowId, wieldedNow: true); _combatBowDequipPendingId = bowId; _combatBowDequipAt = now; _host.Log($"[EquipDiag] dequip bow 0x{(uint)bowId:X8} -> pack 0x{(uint)openPack:X8} (attempt {_combatBowDequipAttempts}/{CombatBowDequipMaxAttempts}) before wand equip"); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs index cc10f50..0f5a7b2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs @@ -15,8 +15,8 @@ namespace RynthCore.Plugin.RynthAi; /// they didn't know about each other, so cross-subsystem swaps still raced. /// /// This gate is a single shared instance both managers consult: a swap is only -/// allowed if no other swap has been issued within MinIntervalMs. The loser -/// yields and retries on a later tick. Spell casts and non-weapon item actions +/// allowed once the last one is done on the server (or MinIntervalMs has passed). +/// The loser yields and retries on a later tick. Spell casts and non-weapon item actions /// (loot moves, corpse opens) do NOT go through here. /// public sealed class WeaponSwapGate @@ -24,37 +24,83 @@ public sealed class WeaponSwapGate private readonly object _lock = new(); private long _lastSwapTickMs = long.MinValue / 4; private string _lastSwapBy = ""; + private int _movingId; + private bool _movingWasWielded; /// - /// Minimum milliseconds between two weapon swaps. ~3s comfortably covers - /// AC's equip + stance-change settle (matches the existing 3000ms cast - /// equip-gate in CombatManager) so a swap fully resolves before the next. + /// The longest one swap holds the next: a swap the server's answer can't be seen for (or + /// with no ) waits this long, as before 2026-10-06. /// public int MinIntervalMs { get; set; } = 3000; /// - /// Atomically claim the swap slot. Returns true (recording the swap) when - /// no swap has occurred within MinIntervalMs; false when the caller must - /// wait. Only mutates state when it returns true, so a denied caller never + /// Swap speed (2026-10-06): the next swap may go once the last one is done on the server, + /// after at least this long. A weapon change takes up to three steps (a shield or arrows + /// into the pack, the weapon, the off hand); at a flat 3 s per step it took 6-9 s. + /// + public int FloorMs { get; set; } = 400; + + /// True when no use or cast is waiting for the server's answer (ActionPacer). + public Func? ServerIdle { get; set; } + + /// Reads whether the character wields an item (for a noted move, ). + public Func? IsWielded { get; set; } + + public Func NowMs { get; set; } = () => Environment.TickCount64; + + /// + /// Atomically claim the swap slot. Returns true (recording the swap) when the last swap is + /// done on the server (see ) or MinIntervalMs has passed; false when + /// the caller must wait. Only mutates state when it returns true, so a denied caller never /// "wastes" the slot. /// public bool TryBeginSwap(string requestedBy) { - long now = Environment.TickCount64; + long now = NowMs(); lock (_lock) { - if (now - _lastSwapTickMs < MinIntervalMs) + long since = now - _lastSwapTickMs; + if (since < MinIntervalMs && !LastSwapDone(since)) return false; _lastSwapTickMs = now; _lastSwapBy = requestedBy ?? ""; + _movingId = 0; return true; } } + /// + /// The claimed swap moved into or out of a hand without a use (a + /// pack move or a slot wield, which the server answers with no UseDone): the swap is done + /// once the item's wielded state is no longer . + /// + public void NoteMove(int itemId, bool wieldedNow) + { + lock (_lock) + { + _movingId = itemId; + _movingWasWielded = wieldedNow; + } + } + + private bool LastSwapDone(long since) + { + if (since < FloorMs || ServerIdle == null || IsWielded == null) return false; + try + { + if (!ServerIdle()) return false; + return _movingId == 0 || IsWielded(_movingId) != _movingWasWielded; + } + catch + { + return false; + } + } + /// Milliseconds since the last successful swap (diagnostics). public long MsSinceLastSwap { - get { lock (_lock) { return Environment.TickCount64 - _lastSwapTickMs; } } + get { lock (_lock) { return NowMs() - _lastSwapTickMs; } } } /// Who last claimed a swap (diagnostics). diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 5ff8404..5f71cfd 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -948,6 +948,7 @@ internal sealed class LegacyDashboardRenderer BlacklistCastSettleMs = s.BlacklistCastSettleMs, TargetNoProgressTimeoutSec = s.TargetNoProgressTimeoutSec, GiveQueueIntervalMs = s.GiveQueueIntervalMs, + T11ItemAugsOverride = s.T11ItemAugsOverride, // Recharge HealAt = s.HealAt, UsePotions = s.UsePotions, @@ -1154,6 +1155,7 @@ internal sealed class LegacyDashboardRenderer if (p.BlacklistCastSettleMs > 0) s.BlacklistCastSettleMs = p.BlacklistCastSettleMs; s.TargetNoProgressTimeoutSec = p.TargetNoProgressTimeoutSec; s.GiveQueueIntervalMs = p.GiveQueueIntervalMs; + s.T11ItemAugsOverride = p.T11ItemAugsOverride ?? -1; // Recharge s.HealAt = p.HealAt; s.UsePotions = p.UsePotions; @@ -1770,6 +1772,7 @@ internal sealed class LegacyDashboardRenderer dst.NavLabelMode = NavLabelModes.Clamp(tmp.NavLabelMode); dst.NavGuideLine = tmp.NavGuideLine; dst.GiveQueueIntervalMs = tmp.GiveQueueIntervalMs; + dst.T11ItemAugsOverride = tmp.T11ItemAugsOverride; dst.SpellCastIntervalMs = tmp.SpellCastIntervalMs; dst.AttackSpellIntervalMs = tmp.AttackSpellIntervalMs; dst.EmbeddedNavs = tmp.EmbeddedNavs; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index ce7760b..bc0cf78 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -267,6 +267,13 @@ public sealed class LegacyUiSettings public int GiveQueueIntervalMs = 150; + /// + /// Item augmentation count used for T11 wield gates in loot rules ("T11: Can Wield"). + /// -1 = automatic (read from the server's "/aug" reply). ACECustom doesn't send the count + /// at login, so this is the fallback when "/aug" is unavailable. Set with /ra t11 augs. + /// + public int T11ItemAugsOverride = -1; + public int SpellCastIntervalMs = 400; /// @@ -771,6 +778,7 @@ public sealed class SettingsBridgePayload public int BlacklistCastSettleMs { get; set; } = -1; public int TargetNoProgressTimeoutSec { get; set; } public int GiveQueueIntervalMs { get; set; } + public int? T11ItemAugsOverride { get; set; } // Recharge public int HealAt { get; set; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/T11ItemSupport.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/T11ItemSupport.cs new file mode 100644 index 0000000..db348fb --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/T11ItemSupport.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using RynthCore.Loot.T11; + +namespace RynthCore.Plugin.RynthAi.Loot; + +/// +/// T11 (tier 11+ ACECustom) loot support for : +/// answers the virtual T11 keys () and puts back the wield-requirement and +/// rating properties the server strips from T11 appraisals. Parsed item text is cached per +/// object and re-parsed only when the text changes. Holds the player's "/aug" counters for +/// the "Can Wield" key. One character per process, so the state is static. +/// +internal static class T11ItemSupport +{ + /// The logged-in character's T11 wield counters. + public static T11PlayerAugs Player { get; } = new(); + + private static readonly T11AugReportParser AugParser = new(); + private static readonly object Gate = new(); + private static readonly Dictionary Parsed = new(); + + // Bound so a long session's corpse items can't grow the cache without limit; a full + // clear is fine because re-parsing is cheap and only happens for items still in use. + private const int MaxEntries = 4096; + + private sealed class Entry + { + public string Name = string.Empty; + public string LongDesc = string.Empty; + public string Use = string.Empty; + public T11ItemInfo Info = T11ItemInfo.None; + } + + /// True when carries the server's T11 drop prefix. + public static bool HasT11Name(string? name) + => !string.IsNullOrEmpty(name) && name.StartsWith(T11Catalog.NamePrefix, StringComparison.Ordinal); + + /// The parsed T11 view of ( for other items). + public static T11ItemInfo Get(WorldObject item) + { + string name = item.Name.Length > 0 ? item.Name : item.Values(StringValueKey.Name, string.Empty); + string longDesc = item.Values(StringValueKey.LongDesc, string.Empty); + string use = item.Values(StringValueKey.Use, string.Empty); + + lock (Gate) + { + if (Parsed.TryGetValue(item.Id, out Entry? e) + && string.Equals(e.Name, name, StringComparison.Ordinal) + && string.Equals(e.LongDesc, longDesc, StringComparison.Ordinal) + && string.Equals(e.Use, use, StringComparison.Ordinal)) + return e.Info; + } + + T11ItemInfo info = T11ItemInfo.Parse(name, longDesc, use); + lock (Gate) + { + if (Parsed.Count >= MaxEntries) Parsed.Clear(); + Parsed[item.Id] = new Entry { Name = name, LongDesc = longDesc, Use = use, Info = info }; + } + return info; + } + + /// A virtual T11 key's value, or for an unused id. + public static int VirtualValue(WorldObject item, int key, int defaultValue) + { + try + { + return T11Keys.TryGetValue(Get(item), key, Player, out int value) ? value : defaultValue; + } + catch + { + return defaultValue; + } + } + + /// + /// The value a T11 appraisal stripped for a retail key (158/159/160, 370-379), else + /// . Only T11-named items are parsed, so other items pay a + /// string compare. + /// + public static int StrippedValue(WorldObject item, int key, int fallback) + { + if (!T11Keys.IsStrippedKey(key)) return fallback; + try + { + string name = item.Name.Length > 0 ? item.Name : item.Values(StringValueKey.Name, string.Empty); + if (!HasT11Name(name)) return fallback; + return T11Keys.TryGetStrippedValue(Get(item), key, out int value) ? value : fallback; + } + catch + { + return fallback; + } + } + + /// Feeds a chat line to the "/aug" reader. Returns true when a counter changed. + public static bool OnChat(string? text) => AugParser.Feed(text, Environment.TickCount64, Player); + + /// Applies the saved item-aug override (-1 = automatic). Cheap; called every tick. + public static void SyncOverride(int itemAugsOverride) + => Player.ItemAugOverride = itemAugsOverride >= 0 ? itemAugsOverride : null; + + /// Drops the cached parse of a deleted object. + public static void Forget(int objectId) + { + lock (Gate) Parsed.Remove(objectId); + } + + /// Forgets the character's counters and every cached item (logout). + public static void Reset() + { + Player.Clear(); + lock (Gate) Parsed.Clear(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index cee01bb..485a9e9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -36,6 +36,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra attackable — check if target is attackable"); ChatLine("[RynthAi] /ra wielded — show wielded items"); ChatLine("[RynthAi] /ra dumpprops [0xId] — every property of the selection (else yourself)"); + ChatLine("[RynthAi] /ra t11 [augs |refresh|item] — T11 loot: wield counters, aug override, parsed item"); ChatLine("[RynthAi] /ra iteminfo [name] — the selected (or named) item's details, Mag-Tools style"); ChatLine("[RynthAi] /ra mexec — evaluate meta expression"); ChatLine("[RynthAi] /ra listvars — show session variables"); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index c107dfd..ad0768c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -258,6 +258,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { Log("RynthAi: logout — tearing down session."); try { _dashboard?.SaveSettings(); } catch { } + Loot.T11ItemSupport.Reset(); // A real logout: the next OnLoginComplete is a fresh login, not a hot reload. ClearInGameMarker(); TeardownSession(); @@ -585,6 +586,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // other (the collision behind "you can only move or use one item at a // time" and the object-teardown AV). _weaponSwapGate ??= new WeaponSwapGate(); + // The next swap goes once the server is done with the last one (not a flat 3 s). + _weaponSwapGate.ServerIdle = () => RynthCore.Plugin.Shared.ActionPacer.Enabled && RynthCore.Plugin.Shared.ActionPacer.Current(Host) == null; + _weaponSwapGate.IsWielded = id => RynthCore.Plugin.Shared.ActionPacer.IsWieldedByPlayer(Host, unchecked((uint)id)); _buffManager = new BuffManager(Host, _dashboard.Settings, _spellManager, _vitals); _inGameMarkerSet = false; @@ -1398,6 +1402,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase DrainGiveQueue(); if (diag) Host.Log("[RynthAi] OnTick: after drain give queue"); if (_loginComplete) TickItemInfo(); + Loot.T11ItemSupport.SyncOverride(_dashboard?.Settings.T11ItemAugsOverride ?? -1); _jumper?.Tick(); if (diag) Host.Log("[RynthAi] OnTick: after jumper tick"); @@ -2039,6 +2044,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _scrollLearner?.OnChat(text); _metaManager?.HandleChat(text, chatType); _questTracker?.OnChatLine(text); + // The "/aug" reply carries the T11 wield counters. + try { Loot.T11ItemSupport.OnChat(text); } + catch (Exception ex) { Log("RynthAi: T11 /aug parse failed: " + ex.Message); } CheckChatForSafetyStops(text); try { OnOwnCorpseChat(text); } catch { } } @@ -2071,6 +2079,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _objectCache?.OnDeleteObject(objectId); _combatManager?.OnObjectDeleted(objectId); // D7/D8: free per-id maps + clear cast-wait if it was our target _scrollLearner?.OnObjectDeleted(objectId); // a read scroll is consumed + Loot.T11ItemSupport.Forget(unchecked((int)objectId)); HandleCorpseObjectDeleted(objectId); } catch (Exception ex) @@ -3068,6 +3077,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "dumpprops": HandleDumpPropsCommand(parts); break; case "iteminfo": HandleItemInfoCommand(parts); break; case "version": HandleVersionCommand(); break; + case "t11": HandleT11Command(parts); break; case "wielded": HandleWieldedCommand(); break; case "scan": HandleScanCommand(); break; case "buildinfo": HandleBuildInfoCommand(); break; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiT11Command.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiT11Command.cs new file mode 100644 index 0000000..c070bfc --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiT11Command.cs @@ -0,0 +1,124 @@ +using System; +using System.Globalization; +using System.Linq; +using RynthCore.Loot.T11; +using RynthCore.Plugin.RynthAi.Loot; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + /// + /// /ra t11 [augs <n|auto> | refresh | item [0xId]]: T11 loot support. + /// No argument shows the wield counters the loot rules use; "augs" sets or clears the + /// item-aug override; "refresh" asks the server for "/aug"; "item" shows how the selected + /// item's T11 text was read and the values its virtual loot keys return. + /// + private void HandleT11Command(string[] parts) + { + string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty; + switch (sub) + { + case "": + case "status": + PrintT11Status(); + break; + case "augs": + SetT11ItemAugOverride(parts.Length >= 4 ? parts[3] : string.Empty); + break; + case "refresh": + if (!Host.HasInvokeChatParser) { ChatLine("[RynthAi] This engine can't send chat commands."); break; } + Host.InvokeChatParser("/aug"); + ChatLine("[RynthAi] T11: sent /aug - the counters update from its reply."); + break; + case "item": + PrintT11Item(parts.Length >= 4 ? parts[3] : null); + break; + default: + ChatLine("[RynthAi] Usage: /ra t11 [augs | refresh | item [0xId]]"); + break; + } + } + + /// The counters the "T11: Can Wield" loot key compares wield gates against. + private void PrintT11Status() + { + T11PlayerAugs p = T11ItemSupport.Player; + int saved = _dashboard?.Settings.T11ItemAugsOverride ?? -1; + string updated = p.UpdatedUtc is DateTime t ? t.ToLocalTime().ToString("t", CultureInfo.CurrentCulture) : "never"; + ChatLine($"[RynthAi] === T11 loot (last /aug read: {updated}) ==="); + foreach ((T11Counter counter, string name) in T11Catalog.CounterNames) + { + long? v = p.Get(counter); + string source = counter == T11Counter.ItemAugmentations && saved >= 0 ? " (override)" : string.Empty; + ChatLine($"[RynthAi] {name}: {(v.HasValue ? v.Value.ToString("N0", CultureInfo.CurrentCulture) : "unknown")}{source}"); + } + if (p.UpdatedUtc == null && saved < 0) + ChatLine("[RynthAi] Unknown counters make \"T11: Can Wield\" -1. Use /ra t11 refresh, or /ra t11 augs ."); + } + + /// /ra t11 augs <n|auto>: saves the item-aug override (-1 = read from /aug). + private void SetT11ItemAugOverride(string arg) + { + if (_dashboard == null) { ChatLine("[RynthAi] Settings aren't loaded yet."); return; } + int value; + if (arg.Equals("auto", StringComparison.OrdinalIgnoreCase) || arg == "-1") + value = -1; + else if (!int.TryParse(arg.Replace(",", string.Empty), NumberStyles.Integer, CultureInfo.InvariantCulture, out value) || value < 0) + { + ChatLine("[RynthAi] Usage: /ra t11 augs (n = your item augmentation count)"); + return; + } + _dashboard.Settings.T11ItemAugsOverride = value; + _dashboard.SaveSettings(); + T11ItemSupport.SyncOverride(value); + ChatLine(value < 0 + ? "[RynthAi] T11: item augmentations now come from /aug." + : $"[RynthAi] T11: item augmentations fixed at {value:N0} for loot rules."); + } + + /// /ra t11 item [0xId]: the parsed T11 text of an item (selected item by default). + private void PrintT11Item(string? idArg) + { + uint id = 0; + if (!string.IsNullOrEmpty(idArg)) + uint.TryParse(idArg.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? idArg[2..] : idArg, + NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id); + if (id == 0 && Host.HasGetSelectedItemId) id = Host.GetSelectedItemId(); + if (id == 0) { ChatLine("[RynthAi] T11: select an item first (or pass 0xId)."); return; } + + int iid = unchecked((int)id); + WorldObject item = _objectCache?[iid] + ?? new WorldObject(iid, Host.TryGetObjectName(id, out string n) ? n : string.Empty) { Cache = _objectCache }; + T11ItemInfo info = T11ItemSupport.Get(item); + if (!info.IsT11) + { + bool appraised = !Host.HasHasAppraisalData || Host.HasAppraisalData(id); + ChatLine(appraised + ? $"[RynthAi] T11: {item.Name} is not a T11 item." + : $"[RynthAi] T11: {item.Name} isn't appraised yet - ID it and try again."); + return; + } + + ChatLine($"[RynthAi] === T11: {item.Name} (0x{id:X8}) ==="); + ChatLine($"[RynthAi] Tier ~{info.EstimatedTier}" + (info.Grade != null ? $", grade {info.Grade} ({info.DamagePercent}% of max damage)" : string.Empty) + + (info.ZoneLocked ? ", zone locked" : string.Empty)); + foreach (T11WieldGate g in info.WieldGates) + ChatLine($"[RynthAi] Wield requires {g.Amount:N0} {T11Catalog.CounterName(g.Counter)}"); + foreach (T11Modifier m in info.Modifiers) + { + string band = m.Min.HasValue && m.Max.HasValue ? $" [{m.Min}-{m.Max}] roll {m.RollPercent}%" : string.Empty; + ChatLine($"[RynthAi] Mod {m.Name} {(m.IsSlotSpecial ? "(special)" : "+" + m.Value)}{band}"); + } + foreach ((string name, double chance) in info.Procs) + ChatLine($"[RynthAi] Cast on strike: {name} ({chance.ToString("0.#", CultureInfo.CurrentCulture)}%)"); + + int canWield = item.Values(T11Keys.CanWield, -1); + ChatLine($"[RynthAi] Can wield: {(canWield == 1 ? "yes" : canWield == 0 ? "no" : "unknown (no /aug read, or not appraised)")}" + + $", modifier ratings {info.ModifierRatingTotal}, average roll {info.AverageRollPercent}%"); + string keys = string.Join(", ", T11Keys.Names() + .Where(k => k.Id < T11Keys.ModifierBase) + .Select(k => $"{k.Name.Replace("T11: ", string.Empty)}={item.Values(k.Id, 0)}")); + ChatLine($"[RynthAi] Loot keys: {keys}"); + } +} diff --git a/Plugins/Shared/ActionPacer.cs b/Plugins/Shared/ActionPacer.cs index aaa5a44..725b3e5 100644 --- a/Plugins/Shared/ActionPacer.cs +++ b/Plugins/Shared/ActionPacer.cs @@ -355,7 +355,7 @@ internal static class ActionPacer 1 => "Peace", 2 => "Melee", 4 => "Missile", 8 => "Magic", _ => $"mode {mode}", }; - private static bool IsWieldedByPlayer(RynthCoreHost host, uint id) + internal static bool IsWieldedByPlayer(RynthCoreHost host, uint id) { try { diff --git a/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs b/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs index 6190985..24fb2ce 100644 --- a/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs +++ b/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs @@ -38,17 +38,25 @@ public static class LootRuleText // ── Key tables (the common ones; unknown ids show as "key N") ────────── - public static readonly (int Id, string Name)[] LongKeys = + /// Retail / Decal long keys, then RynthAi's virtual T11 keys (T11Keys; RynthAi-only). + public static readonly (int Id, string Name)[] LongKeys = BuildLongKeys(); + + private static (int Id, string Name)[] BuildLongKeys() { - (5, "EncumbVal"), (9, "Locations"), (19, "Value"), (25, "Level"), (28, "ArmorLevel"), (44, "Damage"), (45, "DamageType"), - (48, "WeaponSkill"), (54, "MaxDamage"), - (87, "MaxStructure"), (88, "Structure"), (105, "ItemWorkmanship"), (107, "ItemMaxMana"), - (131, "MaterialType"), (158, "WieldRequirements"), (159, "WieldSkilltype"), (160, "WieldDifficulty"), - (218, "EquippedSlots"), (353, "ImbuedEffect"), (370, "DamageRating"), (371, "DamageResistRating"), - (372, "CritRating"), (373, "CritResistRating"), (374, "CritDamageRating"), - (375, "CritDamageResistRating"), (376, "HealBoostRating"), (379, "VitalityRating"), - (0x0D000000, "Type (WCID)"), // Decal's synthetic key: the weenie class id - }; + var keys = new List<(int, string)> + { + (5, "EncumbVal"), (9, "Locations"), (19, "Value"), (25, "Level"), (28, "ArmorLevel"), (44, "Damage"), (45, "DamageType"), + (48, "WeaponSkill"), (54, "MaxDamage"), + (87, "MaxStructure"), (88, "Structure"), (105, "ItemWorkmanship"), (107, "ItemMaxMana"), + (131, "MaterialType"), (158, "WieldRequirements"), (159, "WieldSkilltype"), (160, "WieldDifficulty"), + (218, "EquippedSlots"), (353, "ImbuedEffect"), (370, "DamageRating"), (371, "DamageResistRating"), + (372, "CritRating"), (373, "CritResistRating"), (374, "CritDamageRating"), + (375, "CritDamageResistRating"), (376, "HealBoostRating"), (377, "NetherResistRating"), (379, "VitalityRating"), + (0x0D000000, "Type (WCID)"), // Decal's synthetic key: the weenie class id + }; + keys.AddRange(T11.T11Keys.Names()); + return keys.ToArray(); + } public static readonly (int Id, string Name)[] DoubleKeys = { @@ -56,9 +64,10 @@ public static class LootRuleText (63, "WeaponOffense"), (152, "ElementalDamageVsMonsters"), (167, "ManaRate"), }; + /// String keys. Use (14) and LongDesc (16) hold the T11 "Modifiers:" / "Property Details:" text. public static readonly (int Id, string Name)[] StringKeys = { - (1, "Name"), (5, "Inscription"), (7, "Title"), + (1, "Name"), (5, "Inscription"), (7, "Title"), (14, "Use"), (16, "LongDesc"), }; /// @@ -85,12 +94,15 @@ public static class LootRuleText // ── Value tables (what a long key's number means) ────────────────────── - /// WieldRequirements (158): what WieldDifficulty is checked against (ACE's WieldRequirement enum). + /// + /// WieldRequirements (158): what WieldDifficulty is checked against (ACE's WieldRequirement + /// enum). 13 is ACECustom's Int64Stat, the T11 item-aug gate (RynthAi restores it on T11 items). + /// public static readonly (int Id, string Name)[] WieldRequirements = { (0, "Invalid"), (1, "Skill"), (2, "Base Skill"), (3, "Attribute"), (4, "Base Attribute"), (5, "Vital"), (6, "Base Vital"), (7, "Level"), (8, "Training"), (9, "Int Property"), - (10, "Bool Property"), (11, "Creature Type"), (12, "Heritage"), + (10, "Bool Property"), (11, "Creature Type"), (12, "Heritage"), (13, "Int64 Property"), }; /// MaterialType (131): ACE's MaterialType enum, in id order (grouped cloth, gems, hides, metals, stone, wood). @@ -134,6 +146,7 @@ public static class LootRuleText 131 => Materials, 158 => WieldRequirements, 159 => Skills, + T11.T11Keys.WeaponGrade => T11.T11Catalog.Grades, _ => null, }; @@ -141,7 +154,7 @@ public static class LootRuleText public static bool ValueTableIsFlags(int longKey) => longKey == 45; /// The long keys that have a value table, for the vocabulary. - public static readonly int[] KeysWithValueTables = { 45, 48, 131, 158, 159 }; + public static readonly int[] KeysWithValueTables = { 45, 48, 131, 158, 159, T11.T11Keys.WeaponGrade }; /// /// True for the conditions whose value is picked by name when the key has a diff --git a/Shared/RynthCore.LootSdk/T11/T11Catalog.cs b/Shared/RynthCore.LootSdk/T11/T11Catalog.cs new file mode 100644 index 0000000..233cb72 --- /dev/null +++ b/Shared/RynthCore.LootSdk/T11/T11Catalog.cs @@ -0,0 +1,197 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Loot.T11; + +/// +/// The player counter a T11 wield gate is checked against. On the server these are +/// PropertyInt64 values (WieldRequirement.Int64Stat); the client never receives the +/// gate as properties, only as a "Wield requires: N <counter>" description line. +/// +public enum T11Counter +{ + /// LumAugItemCount (PropertyInt64 9008). The server checks the raw count, without Triune Weave. + ItemAugmentations = 9008, + /// TriuneWeaveCount (PropertyInt64 50000), the T16+ armor gate. + TriuneWeave = 50000, + /// BattlemagesWrathCharmCount (PropertyInt64 50001). + BattlemagesWrath = 50001, + /// NetherVeilCharmCount (PropertyInt64 50002). + NetherVeil = 50002, + /// CrashingSteelCharmCount (PropertyInt64 50003). + CrashingSteel = 50003, + /// TrueShotCharmCount (PropertyInt64 50004). + TrueShot = 50004, +} + +/// One Zone Control modifier the server can stamp on T11 gear. +/// The server's catalog key (ZoneModifiers.Catalog). +/// The name printed at the start of the appraisal line. +/// The retail Gear* rating property the modifier sets, or 0. +/// True for the one-per-slot specials, whose line has no roll band. +public sealed record T11ModifierDef(int Key, string Name, int RatingKey, bool SlotSpecial); + +/// +/// Static T11 tables mirrored from ACECustom: weapon sub-grades, the Zone Control +/// modifier catalog, the wield-gate counter names and the tier-from-gate estimate. +/// Pure data, shared by the RynthAi evaluator, the loot editor and the tests. +/// +public static class T11Catalog +{ + /// The name prefix the server gives every tier 11+ drop (ApplyT11NamePrefix). + public const string NamePrefix = "T11 - "; + + /// Retail rating keys counted by the TotalRatings condition (VTank's set). + public static readonly int[] TotalRatingKeys = { 370, 371, 372, 373, 374, 375, 376, 379 }; + + /// + /// Weapon sub-grades best to worst with their rank (S = 16 ... F- = 1, 0 = no grade). + /// Order and labels follow WeaponScalingManager.SubGradeBands. + /// + public static readonly (int Id, string Name)[] Grades = + { + (16, "S"), (15, "A+"), (14, "A"), (13, "A-"), (12, "B+"), (11, "B"), (10, "B-"), + (9, "C+"), (8, "C"), (7, "C-"), (6, "D+"), (5, "D"), (4, "D-"), (3, "F+"), (2, "F"), (1, "F-"), + }; + + /// + /// ZoneModifiers.Catalog (ACECustom). Rating keys: 370 Damage, 371 Damage Resist, 372 Crit, + /// 373 Crit Resist, 374 Crit Damage, 375 Crit Damage Resist, 376 Healing Boost, + /// 377 Nether Resist, 379 Max Health. + /// + public static readonly T11ModifierDef[] Modifiers = + { + new(19, "Max Health", 379, false), + new(25, "Armor Level", 0, false), + new(28, "Damage Rating", 370, false), + new(29, "Crit Damage Rating", 374, false), + new(31, "Healing Boost", 376, false), + new(32, "Spell Duration", 0, false), + new(33, "Crit Chance", 372, false), + new(41, "Fortify Vitals", 0, true), + new(42, "Battle Mending", 0, true), + new(43, "All Attributes", 0, false), + new(44, "Pct HP Damage", 0, true), + new(45, "Cheat Death", 0, true), + new(46, "Regeneration", 0, true), + new(47, "Max Health Pct", 0, false), + new(48, "Life on Hit", 0, false), + new(49, "Reinforced", 0, false), + new(50, "Damage Resist", 371, false), + new(51, "Crit Damage Resist", 375, false), + new(52, "Crit Resist", 373, false), + new(53, "Nether Resist", 377, false), + }; + + // Longest names first, so "Max Health Pct" is tried before "Max Health". + private static readonly T11ModifierDef[] ModifiersByNameLength = SortByNameLength(Modifiers); + + private static T11ModifierDef[] SortByNameLength(T11ModifierDef[] defs) + { + var copy = (T11ModifierDef[])defs.Clone(); + Array.Sort(copy, (a, b) => b.Name.Length.CompareTo(a.Name.Length)); + return copy; + } + + /// + /// The catalog entry whose name starts as a whole word + /// ("Max Health Pct +2%" is Max Health Pct, not Max Health), or null. + /// + public static T11ModifierDef? MatchModifier(string text) + { + foreach (var def in ModifiersByNameLength) + { + if (!text.StartsWith(def.Name, StringComparison.OrdinalIgnoreCase)) continue; + if (text.Length == def.Name.Length || text[def.Name.Length] == ' ') return def; + } + return null; + } + + /// The catalog entry for a server key, or null. + public static T11ModifierDef? ModifierByKey(int key) + { + foreach (var def in Modifiers) + if (def.Key == key) return def; + return null; + } + + /// Rank of a sub-grade label ("B+" = 12), or 0 when it isn't one. + public static int GradeRank(string? label) + { + if (string.IsNullOrEmpty(label)) return 0; + foreach (var (id, name) in Grades) + if (string.Equals(name, label, StringComparison.OrdinalIgnoreCase)) return id; + return 0; + } + + /// The words a "Wield requires:" line uses for each counter. + public static readonly (T11Counter Counter, string Name)[] CounterNames = + { + (T11Counter.ItemAugmentations, "Item Augmentations"), + (T11Counter.TriuneWeave, "Triune Weave"), + (T11Counter.BattlemagesWrath, "Battlemage's Wrath"), + (T11Counter.NetherVeil, "Nether Veil"), + (T11Counter.CrashingSteel, "Crashing Steel"), + (T11Counter.TrueShot, "True Shot"), + }; + + /// The counter named by a "Wield requires:" line, or null. + public static T11Counter? CounterByName(string name) + { + foreach (var (counter, n) in CounterNames) + if (string.Equals(n, name.Trim(), StringComparison.OrdinalIgnoreCase)) return counter; + return null; + } + + /// Display name of a counter. + public static string CounterName(T11Counter counter) + { + foreach (var (c, n) in CounterNames) + if (c == counter) return n; + return counter.ToString(); + } + + /// Highest loot tier on the server's default weapon-scaling ladder (T11-T25). + public const int MaxTier = 25; + + /// + /// Triune Weave required per tier above 15 on the default ladder: 500 at T16 up to 5,000 + /// at T25. Weapons and armor carry the same Triune gate; weapons add a family-charm gate + /// of the same size, which isn't needed for the estimate. + /// + public const int TriunePerTier = 500; + + /// + /// The loot tier implied by an item-augmentation wield gate, using the server's default + /// weapon-scaling table: T11 = 2,000, T12 = 2,500, then +500 per tier, capped at 4,000. + /// Without a Triune Weave gate the cap makes T15 and above read as 15 (see the + /// three-argument overload). Returns 11 for a T11-named item with no gate read yet, and 0 + /// for anything else. The server owner can retune the table, so this is an estimate. + /// + public static int EstimateTier(int itemAugGate, bool isT11) + { + if (itemAugGate <= 0) return isT11 ? 11 : 0; + if (itemAugGate < 2500) return 11; + return Math.Min(15, 12 + (itemAugGate - 2500) / 500); + } + + /// + /// The loot tier implied by both T11 wield gates. The item-aug gate stops rising at T15, + /// so from T16 the Triune Weave gate ( x (tier - 15)) carries + /// the tier: 500 = T16 ... 5,000 = T25. Any Triune gate means T16 or higher (the server + /// only stamps it from T16) and the result is capped at . Without a + /// Triune gate this is . + /// + public static int EstimateTier(int itemAugGate, int triuneGate, bool isT11) + { + if (triuneGate > 0) return Math.Clamp(15 + triuneGate / TriunePerTier, 16, MaxTier); + return EstimateTier(itemAugGate, isT11); + } + + /// Modifier keys with a rating, for callers that map Gear* keys back to modifiers. + public static IEnumerable RatingModifiers() + { + foreach (var def in Modifiers) + if (def.RatingKey != 0) yield return def; + } +} diff --git a/Shared/RynthCore.LootSdk/T11/T11ItemInfo.cs b/Shared/RynthCore.LootSdk/T11/T11ItemInfo.cs new file mode 100644 index 0000000..6181ab0 --- /dev/null +++ b/Shared/RynthCore.LootSdk/T11/T11ItemInfo.cs @@ -0,0 +1,348 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace RynthCore.Loot.T11; + +/// One "Wield requires: N <counter>" gate. +public readonly record struct T11WieldGate(T11Counter Counter, int Amount); + +/// One line of the appraisal's "Modifiers:" section. +public sealed class T11Modifier +{ + /// Catalog key (T11Catalog.Modifiers), or 0 for a name the catalog doesn't know. + public int Key { get; init; } + /// The modifier name as printed. + public string Name { get; init; } = string.Empty; + /// The rolled value (the first number after the name; 0 for value-less specials). + public int Value { get; init; } + /// Low end of the "[min-max]" roll band, or null when the line has none. + public int? Min { get; init; } + /// High end of the "[min-max]" roll band, or null when the line has none. + public int? Max { get; init; } + /// Where the value landed in its band, 0-100, or -1 without a usable band. + public int RollPercent { get; init; } = -1; + /// The retail Gear* rating key the modifier sets, or 0. + public int RatingKey { get; init; } + /// True for a one-per-slot special (Fortify Vitals, Battle Mending, ...). + public bool IsSlotSpecial { get; init; } +} + +/// +/// What the client can learn about a T11 (tier 11+) ACECustom drop. The server keeps the +/// T11 properties (weapon quality, loot tier, the Zone Control record, the item-aug wield +/// gate) out of the appraisal and prints them as description text instead, so this is +/// parsed from the name, LongDesc (key 16) and Use (key 14). See ACECustom AppraiseInfo +/// (BuildProperties, BuildWeapon, PromoteZoneModifierLines) for the formats. +/// +public sealed class T11ItemInfo +{ + /// A non-T11 item: every field at its default. + public static readonly T11ItemInfo None = new(); + + /// True when the item is T11 gear (name prefix, or T11-only text in its description). + public bool IsT11 { get; private set; } + /// True when the name starts with "T11 - ". + public bool HasNamePrefix { get; private set; } + /// Weapon sub-grade label ("B+"), or null. + public string? Grade { get; private set; } + /// Sub-grade rank, S = 16 ... F- = 1, 0 = no grade. + public int GradeRank { get; private set; } + /// "N% of max damage" from the grade line, or -1. + public int DamagePercent { get; private set; } = -1; + /// Every wield gate, at most one per counter. + public IReadOnlyList WieldGates => _gates; + /// The Zone Control modifier lines, in appraisal order. + public IReadOnlyList Modifiers => _modifiers; + /// "Cast on Strike" lines: spell name and proc chance percent. + public IReadOnlyList<(string Name, double ChancePercent)> Procs => _procs; + /// True when the appraisal said "Zone Locked (Power Reduced)" (depends on where the examiner stood). + public bool ZoneLocked { get; private set; } + /// True when the item had appraisal text (false for a T11 name seen before its ID). + public bool HasText { get; private set; } + + private readonly List _gates = new(); + private readonly List _modifiers = new(); + private readonly List<(string, double)> _procs = new(); + + /// The item-augmentation gate, or 0 when there is none. + public int WieldItemAugs => GateAmount(T11Counter.ItemAugmentations); + + /// The amount required of , or 0 when it isn't gated. + public int GateAmount(T11Counter counter) + { + foreach (var g in _gates) + if (g.Counter == counter) return g.Amount; + return 0; + } + + /// + /// The estimated loot tier (11-25), or 0 for non-T11 items. T16 and up come from the + /// Triune Weave gate; an item without one reads at most 15. + /// + public int EstimatedTier => T11Catalog.EstimateTier(WieldItemAugs, GateAmount(T11Counter.TriuneWeave), IsT11); + + /// Sum of modifier values that land on the TotalRatings keys. + public int ModifierRatingTotal + { + get + { + int total = 0; + foreach (var m in _modifiers) + if (Array.IndexOf(T11Catalog.TotalRatingKeys, m.RatingKey) >= 0) total += m.Value; + return total; + } + } + + /// Sum of modifier values that set , or 0. + public int RatingFromModifiers(int ratingKey) + { + int total = 0; + foreach (var m in _modifiers) + if (m.RatingKey == ratingKey) total += m.Value; + return total; + } + + /// The value of the modifier with catalog key , or 0 when absent. + public int ModifierValue(int key) + { + foreach (var m in _modifiers) + if (m.Key == key) return m.Value; + return 0; + } + + /// Average roll position (0-100) of the banded modifiers, or 0 without any. + public int AverageRollPercent + { + get + { + int sum = 0, n = 0; + foreach (var m in _modifiers) + if (m.RollPercent >= 0) { sum += m.RollPercent; n++; } + return n == 0 ? 0 : (int)Math.Round(sum / (double)n, MidpointRounding.AwayFromZero); + } + } + + /// Best roll position (0-100) of the banded modifiers, or 0 without any. + public int BestRollPercent + { + get + { + int best = 0; + foreach (var m in _modifiers) + if (m.RollPercent > best) best = m.RollPercent; + return best; + } + } + + /// True when any modifier is a slot special. + public bool HasSlotSpecial + { + get + { + foreach (var m in _modifiers) + if (m.IsSlotSpecial) return true; + return false; + } + } + + // ── Parsing ───────────────────────────────────────────────────────────── + + private const RegexOptions Opt = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase; + + // "- Weapon Grade: B+ (86% of max damage)" / "- Weapon Grade: S" + private static readonly Regex GradeLine = new( + @"^-?\s*Weapon Grade:\s*(?S|[A-DF][+-]?)(?=\s|\(|$)(?:\s*\((?\d+)% of max damage\))?", Opt); + + // "- Wield requires: 2,000 Item Augmentations" (weapons) / "Wield requires: 2,000 Item Augmentations" (armor). + // ACE prints N0, so the group separator follows the server's culture: keep digits only. + private static readonly Regex WieldLine = new( + @"^-?\s*Wield requires:\s*(?\d[\d,.\s']*?)\s+(?[A-Za-z' ]+?)\s*$", Opt); + + // "- Cast on Strike: Force Arc (13% proc chance)" + private static readonly Regex ProcLine = new( + @"^-\s*Cast on Strike:\s*(?.+?)\s*\((?\d+(?:\.\d+)?)% proc chance\)\s*$", Opt); + + // A modifier's value: the first signed whole number after the name. + private static readonly Regex FirstNumber = new(@"[+-]?\d+", RegexOptions.CultureInvariant); + + // The roll band at the end of a modifier line: "[14-69]". + private static readonly Regex Band = new(@"\[(?\d+)\s*-\s*(?\d+)\]\s*$", RegexOptions.CultureInvariant); + + // An uncatalogued modifier from a newer server: "Some Name +12 [5-20]" or "Modifier 60 +3 [1-5]". + private static readonly Regex GenericModifier = new(@"^(?.+?)\s+(?[+-]?\d+)", RegexOptions.CultureInvariant); + // Checked before GenericModifier, whose lazy name would stop at "Modifier" and read the key as the value. + private static readonly Regex UnknownKeyName = new(@"^(?Modifier (?\d+))(?=\s|$)", RegexOptions.CultureInvariant); + + private const string ModifiersHeader = "Modifiers:"; + private const string ZoneLockedText = "Zone Locked (Power Reduced)"; + + /// + /// Parses an item. , and + /// may be null or empty (an item not yet appraised has no text; + /// the name prefix alone still marks it T11). Never throws. + /// + public static T11ItemInfo Parse(string? name, string? longDesc, string? use) + { + bool prefix = !string.IsNullOrEmpty(name) && name.StartsWith(T11Catalog.NamePrefix, StringComparison.Ordinal); + if (!prefix && string.IsNullOrEmpty(longDesc) && string.IsNullOrEmpty(use)) return None; + + var info = new T11ItemInfo + { + HasNamePrefix = prefix, + HasText = !string.IsNullOrEmpty(longDesc) || !string.IsNullOrEmpty(use), + }; + try + { + info.ParseText(longDesc); + info.ParseText(use); + } + catch + { + // Malformed text never breaks loot evaluation; whatever parsed so far stands. + } + + // Grade, gates and banded modifiers only appear on T11 gear; Cast on Strike and the + // zone-lock line alone do not mark an item. + info.IsT11 = prefix || info.GradeRank > 0 || info._gates.Count > 0 || info._modifiers.Count > 0; + return info.IsT11 ? info : None; + } + + private void ParseText(string? text) + { + if (string.IsNullOrEmpty(text)) return; + string[] lines = text.Replace("\r\n", "\n").Split('\n'); + for (int i = 0; i < lines.Length; i++) + { + string line = lines[i].Trim(); + if (line.Length == 0) continue; + + if (line.Contains(ZoneLockedText, StringComparison.OrdinalIgnoreCase)) { ZoneLocked = true; continue; } + + if (string.Equals(line, ModifiersHeader, StringComparison.OrdinalIgnoreCase)) + { + i = ParseModifierBlock(lines, i + 1) - 1; + continue; + } + + Match m = GradeLine.Match(line); + if (m.Success && GradeRank == 0) + { + Grade = m.Groups["g"].Value.ToUpperInvariant(); + GradeRank = T11Catalog.GradeRank(Grade); + if (m.Groups["pct"].Success && int.TryParse(m.Groups["pct"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int pct)) + DamagePercent = pct; + continue; + } + + m = WieldLine.Match(line); + if (m.Success && T11Catalog.CounterByName(m.Groups["what"].Value) is T11Counter counter) + { + int amount = DigitsOnly(m.Groups["n"].Value); + if (amount > 0) AddGate(counter, amount); + continue; + } + + m = ProcLine.Match(line); + if (m.Success && double.TryParse(m.Groups["pct"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out double chance)) + _procs.Add((m.Groups["name"].Value, chance)); + } + } + + /// Reads "- ..." lines after a "Modifiers:" header; returns the index of the first line not consumed. + private int ParseModifierBlock(string[] lines, int start) + { + int i = start; + for (; i < lines.Length; i++) + { + string line = lines[i].Trim(); + if (line.Length == 0 || !line.StartsWith("-", StringComparison.Ordinal)) break; + string body = line.Substring(1).Trim(); + if (body.Length == 0) continue; + if (body.Contains(ZoneLockedText, StringComparison.OrdinalIgnoreCase)) { ZoneLocked = true; continue; } + _modifiers.Add(ParseModifier(body)); + } + return i; + } + + private static T11Modifier ParseModifier(string body) + { + T11ModifierDef? def = T11Catalog.MatchModifier(body); + string name; + string rest; + int key = 0; + if (def != null) + { + name = def.Name; + key = def.Key; + rest = body.Substring(def.Name.Length); + } + else if (UnknownKeyName.Match(body) is { Success: true } k + && int.TryParse(k.Groups["key"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsedKey)) + { + key = parsedKey; + name = k.Groups["name"].Value; + rest = body.Substring(name.Length); + def = T11Catalog.ModifierByKey(parsedKey); + if (def != null) name = def.Name; + } + else + { + Match g = GenericModifier.Match(body); + name = g.Success ? g.Groups["name"].Value.Trim() : body; + rest = g.Success ? body.Substring(g.Groups["name"].Length) : string.Empty; + } + + int value = 0; + Match num = FirstNumber.Match(rest); + if (num.Success) int.TryParse(num.Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out value); + + int? min = null, max = null; + int roll = -1; + Match band = Band.Match(rest); + if (band.Success + && int.TryParse(band.Groups["min"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int lo) + && int.TryParse(band.Groups["max"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int hi)) + { + min = lo; + max = hi; + if (hi > lo) roll = Math.Clamp((int)Math.Round((value - lo) * 100.0 / (hi - lo), MidpointRounding.AwayFromZero), 0, 100); + } + + return new T11Modifier + { + Key = key, + Name = name, + Value = value, + Min = min, + Max = max, + RollPercent = roll, + RatingKey = def?.RatingKey ?? 0, + IsSlotSpecial = def?.SlotSpecial ?? false, + }; + } + + private void AddGate(T11Counter counter, int amount) + { + for (int i = 0; i < _gates.Count; i++) + { + if (_gates[i].Counter != counter) continue; + if (amount > _gates[i].Amount) _gates[i] = new T11WieldGate(counter, amount); + return; + } + _gates.Add(new T11WieldGate(counter, amount)); + } + + private static int DigitsOnly(string s) + { + long v = 0; + foreach (char c in s) + { + if (c < '0' || c > '9') continue; + v = v * 10 + (c - '0'); + if (v > int.MaxValue) return int.MaxValue; + } + return (int)v; + } +} diff --git a/Shared/RynthCore.LootSdk/T11/T11Keys.cs b/Shared/RynthCore.LootSdk/T11/T11Keys.cs new file mode 100644 index 0000000..f64397f --- /dev/null +++ b/Shared/RynthCore.LootSdk/T11/T11Keys.cs @@ -0,0 +1,161 @@ +using System.Collections.Generic; + +namespace RynthCore.Loot.T11; + +/// +/// Virtual long-value keys for T11 loot rules. A loot rule uses them like any long key +/// (LongValKeyGE / LE / E / NE), so VTank-format profiles need no new node types. RynthAi +/// answers them from ; other loot engines (VTank, Mag) don't know +/// them and read them as 0. +/// +public static class T11Keys +{ + /// + /// First id of the reserved block ("RY" in the high bytes). Far above retail STypeInt ids, + /// ACECustom's custom ids (9000-50999) and Decal's 0x0D000000 WCID key. + /// + public const int Base = 0x52590000; + + /// 1 when the item is T11 gear, else 0. + public const int IsT11 = Base + 1; + /// Estimated loot tier from the wield gates (11-25; T16+ from the Triune Weave gate), 0 for non-T11. + public const int EstimatedTier = Base + 2; + /// Weapon sub-grade rank: S = 16, A+ = 15 ... F- = 1, 0 = no grade. + public const int WeaponGrade = Base + 3; + /// The weapon's damage as a percent of a perfect roll, 0 when not shown. + public const int DamagePercent = Base + 4; + /// Item augmentations required to wield, 0 for none. + public const int WieldItemAugs = Base + 5; + /// 1 = this character meets every wield gate, 0 = it doesn't, -1 = a needed counter is unknown. + public const int CanWield = Base + 6; + /// Number of Zone Control modifier lines. + public const int ModifierCount = Base + 7; + /// Sum of modifier values that count toward TotalRatings. + public const int ModifierRatingTotal = Base + 8; + /// Average roll position of the banded modifiers, 0-100. + public const int AverageRollPercent = Base + 9; + /// Best roll position of the banded modifiers, 0-100. + public const int BestRollPercent = Base + 10; + /// 1 when the item has a slot special (Fortify Vitals, Battle Mending, ...). + public const int HasSlotSpecial = Base + 11; + /// Number of "Cast on Strike" procs. + public const int CastOnStrikeCount = Base + 12; + /// 1 when the appraisal said "Zone Locked (Power Reduced)". Depends on where you stood when it was appraised. + public const int ZoneLocked = Base + 13; + /// Triune Weave required to wield (T16+ armor), 0 for none. + public const int WieldTriuneWeave = Base + 14; + + /// + /// Base of the per-modifier keys: ModifierBase + catalog key is that modifier's value + /// on the item, 0 when absent (ModifierBase + 28 = Damage Rating). + /// + public const int ModifierBase = Base + 0x100; + + /// One past the last id in the block. + public const int End = Base + 0x200; + + /// True for any id in the T11 block. + public static bool IsVirtual(int key) => key > Base && key < End; + + /// The per-modifier key for a catalog key. + public static int ForModifier(int catalogKey) => ModifierBase + catalogKey; + + /// Editor names for every T11 key, summary keys first. + public static IEnumerable<(int Id, string Name)> Names() + { + yield return (IsT11, "T11: Is T11"); + yield return (EstimatedTier, "T11: Tier (est.)"); + yield return (WeaponGrade, "T11: Weapon Grade"); + yield return (DamagePercent, "T11: Damage % of Max"); + yield return (WieldItemAugs, "T11: Wield Item Augs"); + yield return (WieldTriuneWeave, "T11: Wield Triune Weave"); + yield return (CanWield, "T11: Can Wield"); + yield return (ModifierCount, "T11: Modifier Count"); + yield return (ModifierRatingTotal, "T11: Modifier Ratings"); + yield return (AverageRollPercent, "T11: Avg Roll %"); + yield return (BestRollPercent, "T11: Best Roll %"); + yield return (HasSlotSpecial, "T11: Has Slot Special"); + yield return (CastOnStrikeCount, "T11: Cast on Strike Count"); + yield return (ZoneLocked, "T11: Zone Locked"); + foreach (var def in T11Catalog.Modifiers) + yield return (ForModifier(def.Key), "T11 Mod: " + def.Name); + } + + /// + /// The value of T11 key for . CanWield needs + /// ; without it CanWield reads -1 (unknown) for gated items. + /// Returns false for an id outside the block or an unused id in it. + /// + public static bool TryGetValue(T11ItemInfo item, int key, T11PlayerAugs? player, out int value) + { + value = 0; + if (!IsVirtual(key)) return false; + if (key >= ModifierBase) + { + int catalogKey = key - ModifierBase; + if (T11Catalog.ModifierByKey(catalogKey) == null) return false; + value = item.ModifierValue(catalogKey); + return true; + } + switch (key) + { + case IsT11: value = item.IsT11 ? 1 : 0; return true; + case EstimatedTier: value = item.EstimatedTier; return true; + case WeaponGrade: value = item.GradeRank; return true; + case DamagePercent: value = item.DamagePercent < 0 ? 0 : item.DamagePercent; return true; + case WieldItemAugs: value = item.WieldItemAugs; return true; + case WieldTriuneWeave: value = item.GateAmount(T11Counter.TriuneWeave); return true; + case CanWield: + // Before its ID a T11 item's gates are unknown, so it can't count as wieldable yet. + if (item.WieldGates.Count == 0) value = item.IsT11 && !item.HasText ? -1 : 1; + else value = player?.CanWield(item) ?? -1; + return true; + case ModifierCount: value = item.Modifiers.Count; return true; + case ModifierRatingTotal: value = item.ModifierRatingTotal; return true; + case AverageRollPercent: value = item.AverageRollPercent; return true; + case BestRollPercent: value = item.BestRollPercent; return true; + case HasSlotSpecial: value = item.HasSlotSpecial ? 1 : 0; return true; + case CastOnStrikeCount: value = item.Procs.Count; return true; + case ZoneLocked: value = item.ZoneLocked ? 1 : 0; return true; + default: return false; + } + } + + /// + /// The value the server stripped from a T11 item's appraisal, for the retail keys loot rules + /// already use: wield requirement slot 1 (158 = 13 Int64 Property, 159 = 9008, 160 = the + /// item-aug gate) and the Gear* ratings a modifier line carries (370-379). Only call this + /// when the live property is absent. Returns false when the item supplies no value. + /// + public static bool TryGetStrippedValue(T11ItemInfo item, int key, out int value) + { + value = 0; + if (!item.IsT11) return false; + switch (key) + { + case 158: + if (item.WieldItemAugs <= 0) return false; + value = WieldRequirementInt64Stat; + return true; + case 159: + if (item.WieldItemAugs <= 0) return false; + value = (int)T11Counter.ItemAugmentations; + return true; + case 160: + if (item.WieldItemAugs <= 0) return false; + value = item.WieldItemAugs; + return true; + } + if (key < 370 || key > 379) return false; + int fromMods = item.RatingFromModifiers(key); + if (fromMods == 0) return false; + value = fromMods; + return true; + } + + /// ACECustom's WieldRequirement.Int64Stat (the value after HeritageType = 12). + public const int WieldRequirementInt64Stat = 13; + + /// True for the retail keys can answer. + public static bool IsStrippedKey(int key) => key is 158 or 159 or 160 || (key >= 370 && key <= 379); +} diff --git a/Shared/RynthCore.LootSdk/T11/T11PlayerAugs.cs b/Shared/RynthCore.LootSdk/T11/T11PlayerAugs.cs new file mode 100644 index 0000000..bb1a6d4 --- /dev/null +++ b/Shared/RynthCore.LootSdk/T11/T11PlayerAugs.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace RynthCore.Loot.T11; + +/// +/// The player counters T11 wield gates are checked against. ACECustom doesn't send these at +/// login (they aren't [SendOnLogin]), so they come from the "/aug" reply, or from a manual +/// item-aug override. Thread-safe: chat writes it, loot evaluation reads it. +/// +public sealed class T11PlayerAugs +{ + private readonly object _gate = new(); + private readonly Dictionary _counts = new(); + private long? _itemAugOverride; + + /// When the counters were last updated from "/aug" (UTC), or null. + public DateTime? UpdatedUtc { get; private set; } + + /// The manual item-aug count that replaces the "/aug" value, or null for automatic. + public long? ItemAugOverride + { + get { lock (_gate) return _itemAugOverride; } + set { lock (_gate) _itemAugOverride = value is < 0 ? null : value; } + } + + /// Records one counter read from "/aug". + public void Set(T11Counter counter, long value) + { + lock (_gate) + { + _counts[counter] = Math.Max(0, value); + UpdatedUtc = DateTime.UtcNow; + } + } + + /// + /// The player's count for , or null when unknown. Item + /// augmentations honour the manual override. + /// + public long? Get(T11Counter counter) + { + lock (_gate) + { + if (counter == T11Counter.ItemAugmentations && _itemAugOverride.HasValue) return _itemAugOverride; + return _counts.TryGetValue(counter, out long v) ? v : null; + } + } + + /// Forgets the "/aug" counts (logout). The manual override is kept. + public void Clear() + { + lock (_gate) + { + _counts.Clear(); + UpdatedUtc = null; + } + } + + /// + /// Whether the player meets every wield gate of : 1 = yes (or the + /// item has no gate), 0 = a gate is not met, -1 = a needed counter is unknown. Mirrors the + /// server's check (Player_Inventory, WieldRequirement.Int64Stat): raw counter >= amount. + /// + public int CanWield(T11ItemInfo item) + { + bool unknown = false; + foreach (var gate in item.WieldGates) + { + long? have = Get(gate.Counter); + if (have == null) { unknown = true; continue; } + if (have.Value < gate.Amount) return 0; + } + return unknown ? -1 : 1; + } +} + +/// +/// Reads ACECustom's "/aug" reply into . The reply is one chat line +/// per counter ("Item:1,234", "Triune Weave: 5 (adds ...)"), so a bare "Item:" line is only +/// trusted shortly after the "Advanced Augmentation Levels:" header. +/// +public sealed class T11AugReportParser +{ + /// How long after the header (or the last accepted line) reply lines are trusted. + public const long WindowMs = 5000; + + private const RegexOptions Opt = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase; + private static readonly Regex Header = new(@"^Advanced Augmentation Levels:\s*$", Opt); + private static readonly Regex Line = new(@"^(?[A-Za-z' ]+?)\s*:\s*(?\d[\d,.\s']*)", Opt); + + private long _openUntil = long.MinValue; + + /// + /// Feeds one chat line. Returns true when it updated a counter. + /// is any monotonic millisecond clock. + /// + public bool Feed(string? text, long nowMs, T11PlayerAugs into) + { + if (string.IsNullOrEmpty(text)) return false; + string line = text.Trim(); + if (Header.IsMatch(line)) + { + _openUntil = nowMs + WindowMs; + return false; + } + if (nowMs > _openUntil) return false; + + Match m = Line.Match(line); + if (!m.Success) return false; + T11Counter? counter = CounterFor(m.Groups["what"].Value.Trim()); + if (counter == null) return false; + + long value = 0; + foreach (char c in m.Groups["n"].Value) + { + if (c < '0' || c > '9') { if (c == ' ' || c == ',' || c == '.' || c == '\'') continue; break; } + value = value * 10 + (c - '0'); + } + into.Set(counter.Value, value); + _openUntil = nowMs + WindowMs; + return true; + } + + /// The counter a "/aug" line label stands for, or null for the ones T11 gates don't use. + private static T11Counter? CounterFor(string label) => label.ToLowerInvariant() switch + { + "item" => T11Counter.ItemAugmentations, + "triune weave" => T11Counter.TriuneWeave, + "battlemage's wrath charm" => T11Counter.BattlemagesWrath, + "nether veil charm" => T11Counter.NetherVeil, + "crashing steel charm" => T11Counter.CrashingSteel, + "true shot charm" => T11Counter.TrueShot, + _ => null, + }; +} diff --git a/Tools/RynthCore.LootSdkTests/LootT11Tests.cs b/Tools/RynthCore.LootSdkTests/LootT11Tests.cs new file mode 100644 index 0000000..a47e696 --- /dev/null +++ b/Tools/RynthCore.LootSdkTests/LootT11Tests.cs @@ -0,0 +1,210 @@ +using System; +using System.Linq; +using RynthCore.Loot.Editing; +using RynthCore.Loot.T11; + +namespace RynthCore.LootSdkTests; + +// T11 (ACECustom tier 11+) loot support: the item-text parser against the server's exact +// strings, tier estimates, the "/aug" reply reader, wield checks, virtual keys, the stripped +// wield/rating fallbacks, and the editor's key names and grade table. +internal static partial class Program +{ + // A T13 weapon as ACECustom appraises it: Property Details then Modifiers in LongDesc. + private const string T11WeaponLongDesc = + "A finely made sword.\n\n" + + "Property Details:\n" + + "- Weapon Grade: B+ (86% of max damage)\n" + + "- Wield requires: 3,000 Item Augmentations\n" + + "- Wield requires: 25 Crashing Steel\n" + + "- Cast on Strike: Force Arc (13% proc chance)\n" + + "\n" + + "Modifiers:\n" + + "- Damage Rating +41 [14-69]\n" + + "- Crit Damage Rating +10 [5-15]\n" + + "- Pct HP Damage 2%\n" + + "- Zone Locked (Power Reduced)\n"; + + // T16 armor: gates in LongDesc without a dash, Modifiers in the Use string. + private const string T11ArmorLongDesc = + "Sturdy plate.\n" + + "Wield requires: 4.000 Item Augmentations\n" + + "Wield requires: 500 Triune Weave\n"; + + private const string T11ArmorUse = + "Modifiers:\n" + + "- Damage Resist +8 [2-12]\n" + + "- Max Health +120 [40-200]\n" + + "- Max Health Pct +2% [1-4]\n" + + "- Modifier 60 +3 [1-5]\n"; + + private static void RunT11Tests() + { + Console.WriteLine("\n-- T11 loot --"); + TestT11WeaponParse(); + TestT11ArmorParse(); + TestT11NonT11(); + TestT11Tier(); + TestT11AugReport(); + TestT11Keys(); + TestT11Editor(); + } + + private static void TestT11WeaponParse() + { + T11ItemInfo w = T11ItemInfo.Parse("T11 - Tachi", T11WeaponLongDesc, null); + Check(w.IsT11 && w.HasNamePrefix, "weapon: T11 by prefix"); + Eq(w.Grade, "B+", "weapon: grade label"); + Eq(w.GradeRank, 12, "weapon: grade rank B+ = 12"); + Eq(w.DamagePercent, 86, "weapon: damage % of max"); + Eq(w.WieldItemAugs, 3000, "weapon: item-aug gate with group separator"); + Eq(w.GateAmount(T11Counter.CrashingSteel), 25, "weapon: charm gate"); + Eq(w.Procs.Count, 1, "weapon: one cast on strike"); + Eq(w.Procs.Count > 0 ? w.Procs[0].Name : "", "Force Arc", "weapon: proc name"); + Eq(w.Procs.Count > 0 ? w.Procs[0].ChancePercent : 0, 13.0, "weapon: proc chance"); + Check(w.ZoneLocked, "weapon: zone locked line inside Modifiers"); + Eq(w.Modifiers.Count, 3, "weapon: zone lock line is not a modifier"); + T11Modifier dr = w.Modifiers.First(m => m.Key == 28); + Eq(dr.Value, 41, "weapon: Damage Rating value"); + Eq((dr.Min, dr.Max), ((int?)14, (int?)69), "weapon: Damage Rating band"); + Eq(dr.RollPercent, 49, "weapon: Damage Rating roll (41-14)/(69-14)"); + Check(w.Modifiers.Any(m => m.Key == 44 && m.IsSlotSpecial), "weapon: slot special without a band"); + Check(w.HasSlotSpecial, "weapon: HasSlotSpecial"); + Eq(w.RatingFromModifiers(370), 41, "weapon: 370 from Damage Rating"); + Eq(w.RatingFromModifiers(374), 10, "weapon: 374 from Crit Damage Rating"); + Eq(w.ModifierRatingTotal, 51, "weapon: modifier rating total"); + Eq(w.EstimatedTier, 13, "weapon: 3,000 gate = T13"); + Eq(w.BestRollPercent, 50, "weapon: best roll (Crit Damage 10 in 5-15)"); + } + + private static void TestT11ArmorParse() + { + T11ItemInfo a = T11ItemInfo.Parse("T11 - Celdon Breastplate", T11ArmorLongDesc, T11ArmorUse); + Check(a.IsT11, "armor: T11"); + Eq(a.Grade, null, "armor: no weapon grade"); + Eq(a.WieldItemAugs, 4000, "armor: dot group separator, no dash"); + Eq(a.GateAmount(T11Counter.TriuneWeave), 500, "armor: Triune Weave gate"); + Eq(a.EstimatedTier, 16, "armor: 500 Triune Weave = T16"); + Eq(T11Keys.TryGetValue(a, T11Keys.EstimatedTier, null, out int at) ? at : 0, 16, "armor: tier key reads T16"); + Eq(a.Modifiers.Count, 4, "armor: modifiers from Use"); + Check(a.Modifiers.Any(m => m.Key == 47 && m.Value == 2), "armor: Max Health Pct is not Max Health"); + Check(a.Modifiers.Any(m => m.Key == 19 && m.Value == 120), "armor: Max Health"); + Check(a.Modifiers.Any(m => m.Key == 60 && m.Name == "Modifier 60" && m.Value == 3), "armor: unknown server key kept"); + Eq(a.RatingFromModifiers(371), 8, "armor: 371 from Damage Resist"); + Eq(a.RatingFromModifiers(379), 120, "armor: 379 from Max Health"); + Eq(a.ModifierRatingTotal, 128, "armor: rating total 371 + 379"); + } + + private static void TestT11NonT11() + { + Check(!T11ItemInfo.Parse("Tachi", "A finely made sword.", "").IsT11, "plain item is not T11"); + Check(!T11ItemInfo.Parse(null, null, null).IsT11, "no text is not T11"); + Check(!T11ItemInfo.Parse("Wand", "- Cast on Strike: Bolt (5% proc chance)", null).IsT11, "a proc alone doesn't mark T11"); + Check(T11ItemInfo.Parse("T11 - Robe", null, null).IsT11, "unappraised T11 name still T11"); + Eq(T11ItemInfo.Parse("T11 - Robe", null, null).EstimatedTier, 11, "unappraised T11 = tier 11"); + Check(!T11ItemInfo.Parse("T11 - Robe", null, null).HasText, "unappraised T11 has no text"); + Eq(T11Keys.TryGetValue(T11ItemInfo.Parse("T11 - Robe", null, null), T11Keys.CanWield, new T11PlayerAugs(), out int cw) ? cw : 99, -1, + "unappraised T11: Can Wield unknown"); + Eq(T11Keys.TryGetValue(T11ItemInfo.Parse("T11 - Robe", "A robe.", null), T11Keys.CanWield, null, out int cw2) ? cw2 : 99, 1, + "appraised T11 without a gate: wieldable"); + Check(!T11ItemInfo.Parse("x", "Modifiers:\n- ", "\n\n- [").IsT11, "malformed text doesn't throw or mark"); + } + + private static void TestT11Tier() + { + Eq(T11Catalog.EstimateTier(0, false), 0, "tier: nothing"); + Eq(T11Catalog.EstimateTier(2000, true), 11, "tier: 2,000 = T11"); + Eq(T11Catalog.EstimateTier(2500, true), 12, "tier: 2,500 = T12"); + Eq(T11Catalog.EstimateTier(3500, true), 14, "tier: 3,500 = T14"); + Eq(T11Catalog.EstimateTier(9000, true), 15, "tier: capped at 15"); + + // T16-T25: the item-aug gate is frozen at 4,000, the Triune Weave gate carries the tier. + Eq(T11Catalog.EstimateTier(4000, 0, true), 15, "tier: 4,000 without Triune = T15"); + Eq(T11Catalog.EstimateTier(3000, 0, true), 13, "tier: no Triune falls back to the item-aug gate"); + Eq(T11Catalog.EstimateTier(4000, 500, true), 16, "tier: 500 Triune = T16"); + Eq(T11Catalog.EstimateTier(4000, 1500, true), 18, "tier: 1,500 Triune = T18"); + Eq(T11Catalog.EstimateTier(4000, 5000, true), 25, "tier: 5,000 Triune = T25"); + Eq(T11Catalog.EstimateTier(4000, 9000, true), T11Catalog.MaxTier, "tier: capped at T25"); + Eq(T11Catalog.EstimateTier(4000, 250, true), 16, "tier: any Triune gate is at least T16"); + Eq(T11Catalog.EstimateTier(0, 0, false), 0, "tier: nothing (three-argument)"); + + // A T25 weapon as appraised: item augs frozen at 4,000, Triune and family charm 5,000 each. + T11ItemInfo t25 = T11ItemInfo.Parse("T11 - Tachi", + "Property Details:\n" + + "- Weapon Grade: A (95% of max damage)\n" + + "- Wield requires: 4,000 Item Augmentations\n" + + "- Wield requires: 5,000 Triune Weave\n" + + "- Wield requires: 5,000 Crashing Steel\n", null); + Eq(t25.EstimatedTier, 25, "tier: T25 weapon from its Triune gate"); + Eq(t25.GateAmount(T11Counter.CrashingSteel), 5000, "tier: T25 weapon charm gate"); + } + + private static void TestT11AugReport() + { + var p = new T11PlayerAugs(); + var r = new T11AugReportParser(); + Check(!r.Feed("Item:2,500", 0, p), "aug: Item line before the header ignored"); + Check(!r.Feed("Advanced Augmentation Levels:", 1000, p), "aug: header opens the window"); + Check(r.Feed("Item:2,500", 1100, p), "aug: Item line read"); + Check(r.Feed("Triune Weave: 3 (adds 3% damage)", 1200, p), "aug: Triune Weave read"); + Check(r.Feed("Crashing Steel Charm: 20", 1300, p), "aug: charm read"); + Check(!r.Feed("Item:9999", 1300 + T11AugReportParser.WindowMs + 1, p), "aug: window closes"); + Eq(p.Get(T11Counter.ItemAugmentations), (long?)2500, "aug: item count"); + Eq(p.Get(T11Counter.TriuneWeave), (long?)3, "aug: triune count"); + Eq(p.Get(T11Counter.NetherVeil), null, "aug: unreported counter unknown"); + + T11ItemInfo weapon = T11ItemInfo.Parse("T11 - Tachi", T11WeaponLongDesc, null); + Eq(p.CanWield(weapon), 0, "wield: 2,500 < 3,000"); + p.ItemAugOverride = 3000; + Eq(p.CanWield(weapon), 0, "wield: crashing steel 20 < 25"); + p.Set(T11Counter.CrashingSteel, 25); + Eq(p.CanWield(weapon), 1, "wield: override + charm met"); + p.Clear(); + Eq(p.Get(T11Counter.ItemAugmentations), (long?)3000, "aug: Clear keeps the override"); + Eq(p.CanWield(weapon), -1, "wield: charm unknown after Clear"); + } + + private static void TestT11Keys() + { + T11ItemInfo w = T11ItemInfo.Parse("T11 - Tachi", T11WeaponLongDesc, null); + int V(int key, T11PlayerAugs? pl = null) => T11Keys.TryGetValue(w, key, pl, out int v) ? v : int.MinValue; + Eq(V(T11Keys.IsT11), 1, "key: IsT11"); + Eq(V(T11Keys.EstimatedTier), 13, "key: tier"); + Eq(V(T11Keys.WeaponGrade), 12, "key: grade"); + Eq(V(T11Keys.DamagePercent), 86, "key: damage %"); + Eq(V(T11Keys.WieldItemAugs), 3000, "key: wield item augs"); + Eq(V(T11Keys.CanWield), -1, "key: can wield unknown without player"); + Eq(V(T11Keys.ModifierCount), 3, "key: modifier count"); + Eq(V(T11Keys.ModifierRatingTotal), 51, "key: modifier ratings"); + Eq(V(T11Keys.CastOnStrikeCount), 1, "key: procs"); + Eq(V(T11Keys.ZoneLocked), 1, "key: zone locked"); + Eq(V(T11Keys.ForModifier(28)), 41, "key: per-modifier Damage Rating"); + Eq(V(T11Keys.ForModifier(50)), 0, "key: absent modifier = 0"); + Eq(V(T11Keys.ModifierBase + 999), int.MinValue, "key: unknown modifier id unused"); + Eq(V(370), int.MinValue, "key: retail key isn't virtual"); + Check(T11Keys.IsVirtual(T11Keys.IsT11) && !T11Keys.IsVirtual(T11Keys.Base) && !T11Keys.IsVirtual(T11Keys.End), "key: block bounds"); + + int S(T11ItemInfo item, int key) => T11Keys.TryGetStrippedValue(item, key, out int v) ? v : int.MinValue; + Eq(S(w, 158), 13, "stripped: 158 = Int64 Property"); + Eq(S(w, 159), 9008, "stripped: 159 = item augs stat"); + Eq(S(w, 160), 3000, "stripped: 160 = gate"); + Eq(S(w, 370), 41, "stripped: 370 from modifier"); + Eq(S(w, 371), int.MinValue, "stripped: no modifier for 371"); + Eq(S(T11ItemInfo.None, 158), int.MinValue, "stripped: non-T11 gives nothing"); + Eq(S(T11ItemInfo.Parse("T11 - Robe", null, null), 160), int.MinValue, "stripped: no gate read yet"); + Check(T11Keys.IsStrippedKey(158) && T11Keys.IsStrippedKey(379) && !T11Keys.IsStrippedKey(161), "stripped: key set"); + } + + private static void TestT11Editor() + { + Check(LootRuleText.LongKeys.Any(k => k.Id == T11Keys.CanWield && k.Name == "T11: Can Wield"), "editor: Can Wield key named"); + Check(LootRuleText.LongKeys.Any(k => k.Id == T11Keys.ForModifier(28) && k.Name == "T11 Mod: Damage Rating"), "editor: per-modifier key named"); + Check(LootRuleText.LongKeys.Any(k => k.Id == 377), "editor: NetherResistRating listed"); + Eq(LootRuleText.LongKeys.Select(k => k.Id).Distinct().Count(), LootRuleText.LongKeys.Length, "editor: long key ids unique"); + Check(ReferenceEquals(LootRuleText.ValueTableFor(T11Keys.WeaponGrade), T11Catalog.Grades), "editor: grade value table"); + Eq(LootRuleText.ValueName(T11Keys.WeaponGrade, "12"), "B+", "editor: grade 12 named B+"); + Eq(LootRuleText.WieldRequirements.First(w => w.Id == 13).Name, "Int64 Property", "editor: wield requirement 13"); + Check(LootRuleText.StringKeys.Any(k => k.Id == 14) && LootRuleText.StringKeys.Any(k => k.Id == 16), "editor: Use and LongDesc string keys"); + Eq(T11Catalog.Grades.Select(g => g.Name).Distinct().Count(), T11Catalog.Grades.Length, "editor: grade names unique"); + } +} diff --git a/Tools/RynthCore.LootSdkTests/LootValueNameTests.cs b/Tools/RynthCore.LootSdkTests/LootValueNameTests.cs index 03b6bd3..f65f912 100644 --- a/Tools/RynthCore.LootSdkTests/LootValueNameTests.cs +++ b/Tools/RynthCore.LootSdkTests/LootValueNameTests.cs @@ -67,7 +67,7 @@ internal static partial class Program Eq(LootRuleText.Materials.First(m => m.Id == 15).Name, "Black Garnet", "material 15"); Eq(LootRuleText.Materials.Length, 78, "materials 0..77"); Eq(LootRuleText.WieldRequirements.First(w => w.Id == 2).Name, "Base Skill", "wield requirement 2 (RawSkill)"); - Eq(LootRuleText.WieldRequirements.Length, 13, "wield requirements 0..12"); + Eq(LootRuleText.WieldRequirements.Length, 14, "wield requirements 0..13 (13 = ACECustom Int64 Property)"); Eq(LootRuleText.DamageTypes.First(d => d.Id == 64).Name, "Electric", "damage type 64"); // Lookup and labels; unknown and odd values stay expressible. diff --git a/Tools/RynthCore.LootSdkTests/Program.cs b/Tools/RynthCore.LootSdkTests/Program.cs index 7eb1fd1..c0069ca 100644 --- a/Tools/RynthCore.LootSdkTests/Program.cs +++ b/Tools/RynthCore.LootSdkTests/Program.cs @@ -44,6 +44,7 @@ internal static partial class Program TestMalformedInputs(); RunLootEditTests(args); RunLootAddTests(args); + RunT11Tests(); Console.WriteLine($"\nGolden tests: {_asserts} assertions, {_fails} failed."); diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 2af7c91..313385a 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -43,6 +43,7 @@ internal static class Program var runner = new Runner(); NativeLootTests.Register(runner); VTankLootTests.Register(runner); + T11LootTests.Register(runner); ExpressionTests.Register(runner); MetaTests.Register(runner); NoKillTests.Register(runner); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs index 90e56fc..3e23d86 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs @@ -34,6 +34,8 @@ internal static class OffhandTests r.Add("offhand: two-hander -> the shield comes off first, back on with a one-hander", TwoHanderShieldOff); r.Add("offhand: bow -> the shield comes off, then the arrows still go on", BowShieldOffThenAmmo); r.Add("offhand: a caster -> the shield comes off first (swap gate held)", CasterShieldOff); + r.Add("swap speed: a weapon in hand -> one use of the wand (the client swaps); the pack move only as the fallback", CasterDirectSwap); + r.Add("swap speed: the gate lets the next step go once the server is done, else after 3 s", SwapGateSettles); r.Add("offhand: dual wield with the Dual Wield skill", DualWield); r.Add("offhand: no Dual Wield skill -> the shield", NoSkillShield); r.Add("offhand: None -> hands off (a worn shield is never taken off)", NoneHandsOff); @@ -331,6 +333,56 @@ internal static class OffhandTests Check.Eq(FakeHost.Wields.Count, 0, "no shield with a caster"); } + // 2026-10-06: Drakkon's axe -> wand took 4.2 s: the axe into the pack (1.2 s), then the swap + // gate's flat 3 s before the wand. A use of the wand (the client's double-click) swaps by itself. + private static void CasterDirectSwap() + { + var rig = new Rig(); // the sword in hand + rig.List(Wand); + rig.C.CanCastOverride = _ => true; + Check.False(rig.Tick(), "not ready"); + Check.True(FakeHost.Uses.Contains(Wand), "UseObject(wand) with the sword still in hand"); + Check.Eq(FakeHost.Moves.Count, 0, "no pack move first"); + + // The use didn't swap in 2 s (SwapTracker retries at 2.5 s): the sword goes into the pack first from now on. + var since = typeof(CombatManager).GetField("_combatDirectSwapSince", BindingFlags.Instance | BindingFlags.NonPublic)!; + since.SetValue(rig.C, DateTime.Now.AddSeconds(-3)); + rig.C.SwapTracker.Reset(); // its 2.5 s resolve time is up + rig.Tick(); + Check.True(FakeHost.Moves.Any(m => m.Id == Sword), "fallback: the sword into the pack"); + Check.True(FakeHost.Logs.Any(l => l.Contains("from now on the weapon goes into a pack first")), "logged once"); + } + + private static void SwapGateSettles() + { + long t = 0; + bool idle = true; + var wielded = new Dictionary { [7] = true }; + var g = new WeaponSwapGate { NowMs = () => t, ServerIdle = () => idle, IsWielded = id => wielded[id] }; + Check.True(g.TryBeginSwap("shield off"), "first swap"); + g.NoteMove(7, wieldedNow: true); + t = 500; + Check.False(g.TryBeginSwap("weapon"), "the shield is still in hand"); + wielded[7] = false; + Check.True(g.TryBeginSwap("weapon"), "the shield is off: the weapon goes at once (not at 3 s)"); + t = 700; + Check.False(g.TryBeginSwap("off hand"), "under the 400 ms floor"); + t = 1000; + idle = false; + Check.False(g.TryBeginSwap("off hand"), "the weapon's use is still unanswered"); + idle = true; + Check.True(g.TryBeginSwap("off hand"), "answered: the off hand goes"); + + // No pacing (ServerIdle unset): the flat 3 s, as before. + t = 0; + var flat = new WeaponSwapGate { NowMs = () => t }; + Check.True(flat.TryBeginSwap("a"), "first"); + t = 2999; + Check.False(flat.TryBeginSwap("b"), "inside 3 s"); + t = 3000; + Check.True(flat.TryBeginSwap("b"), "after 3 s"); + } + private static void DualWield() { var rig = new Rig(dualWieldSkill: true); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/T11LootTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/T11LootTests.cs new file mode 100644 index 0000000..f0e9af3 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/T11LootTests.cs @@ -0,0 +1,127 @@ +using RynthCore.Loot; +using RynthCore.Loot.T11; +using RynthCore.Loot.VTank; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.Loot; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; +using N = RynthCore.Loot.VTank.VTankNodeTypes; + +namespace RynthCore.RynthAiHostTests.Tests; + +// T11 (ACECustom tier 11+) items through the real evaluator: the virtual T11 keys answered by +// WorldObject.Values, the wield requirement and ratings the server strips put back from the +// item text, and "Can Wield" fed by the "/aug" reply. +internal static class T11LootTests +{ + private const string WeaponLongDesc = + "Property Details:\n" + + "- Weapon Grade: A- (91% of max damage)\n" + + "- Wield requires: 2,500 Item Augmentations\n" + + "\n" + + "Modifiers:\n" + + "- Damage Rating +30 [14-69]\n" + + "- Crit Chance +4 [1-8]\n"; + + private const string ArmorUse = + "Modifiers:\n" + + "- Damage Resist +6 [2-12]\n" + + "- Max Health +100 [40-200]\n"; + + public static void Register(Runner r) + { + r.Add("loot t11: virtual keys read the item text", VirtualKeys); + r.Add("loot t11: stripped wield requirement 158/159/160 restored", StrippedWield); + r.Add("loot t11: modifier ratings feed Gear* keys and TotalRatings", ModifierRatings); + r.Add("loot t11: a live rating wins over the modifier text", LiveRatingWins); + r.Add("loot t11: retail items are untouched", RetailUntouched); + r.Add("loot t11: Can Wield from the /aug reply and the override", CanWield); + } + + private static VTankLootCondition C(int node, params string[] data) => new(node, "0", data); + + private static bool M(WorldObject item, params VTankLootCondition[] conds) + { + var rule = new VTankLootRule { Name = "r", Action = VTankLootAction.Keep }; + rule.Conditions.AddRange(conds); + return VTankLootEvaluator.Match(rule, item); + } + + private static string K(int key) => key.ToString(System.Globalization.CultureInfo.InvariantCulture); + + private static Item Weapon() => new Item("T11 - Tachi", AcObjectClass.MeleeWeapon).Str(16, WeaponLongDesc); + + private static void VirtualKeys() + { + T11ItemSupport.Reset(); + WorldObject w = Weapon(); + Check.Eq(w.Values(T11Keys.IsT11, -5), 1, "IsT11"); + Check.Eq(w.Values(T11Keys.EstimatedTier, -5), 12, "2,500 gate = T12"); + Check.Eq(w.Values(T11Keys.WeaponGrade, -5), 13, "A- = 13"); + Check.True(M(w, C(N.LongValKeyGE, "12", K(T11Keys.WeaponGrade))), "rule: grade B+ or better"); + Check.False(M(w, C(N.LongValKeyGE, "14", K(T11Keys.WeaponGrade))), "rule: grade A or better"); + Check.True(M(w, C(N.LongValKeyGE, "25", K(T11Keys.ForModifier(28)))), "rule: Damage Rating mod >= 25"); + Check.True(M(w, C(N.LongValKeyE, "0", K(T11Keys.ZoneLocked))), "rule: not zone locked"); + Check.Eq(w.Values(T11Keys.Base + 0x1FF, -5), -5, "unused virtual id = default"); + Check.Eq(new Item("Tachi").Wo.Values(T11Keys.IsT11, -5), 0, "retail item: IsT11 = 0"); + } + + private static void StrippedWield() + { + T11ItemSupport.Reset(); + WorldObject w = Weapon(); + Check.Eq(w.Values(158, 0), T11Keys.WieldRequirementInt64Stat, "158 = Int64 Property"); + Check.Eq(w.Values(159, 0), 9008, "159 = item augs"); + Check.Eq(w.Values(160, 0), 2500, "160 = gate"); + Check.True(M(w, C(N.LongValKeyLE, "2500", "160")), "rule: wield difficulty <= 2500"); + Check.False(M(w, C(N.LongValKeyLE, "2000", "160")), "rule: wield difficulty <= 2000"); + Check.Eq(w.Values(161, -1), -1, "other keys keep the default"); + } + + private static void ModifierRatings() + { + T11ItemSupport.Reset(); + WorldObject w = Weapon(); + Check.Eq(w.Values(370, 0), 30, "370 Damage Rating from text"); + Check.Eq(w.Values(372, 0), 4, "372 Crit from text"); + Check.True(M(w, C(N.TotalRatingsGE, "34")), "TotalRatings counts modifier ratings"); + Check.False(M(w, C(N.TotalRatingsGE, "35")), "TotalRatings exact"); + + WorldObject armor = new Item("T11 - Celdon Breastplate", AcObjectClass.Armor).Str(14, ArmorUse); + Check.Eq(armor.Values(371, 0), 6, "371 from the Use string"); + Check.True(M(armor, C(N.TotalRatingsGE, "106")), "armor TotalRatings 371 + 379"); + } + + private static void LiveRatingWins() + { + T11ItemSupport.Reset(); + WorldObject w = Weapon().Int(370, 7); + Check.Eq(w.Values(370, 0), 7, "a property the item has is never replaced"); + } + + private static void RetailUntouched() + { + T11ItemSupport.Reset(); + WorldObject retail = new Item("Tachi", AcObjectClass.MeleeWeapon).Str(16, WeaponLongDesc); + Check.Eq(retail.Values(160, 0), 0, "no T11 prefix: no stripped-key fallback"); + Check.Eq(retail.Values(370, -1), -1, "no T11 prefix: rating default kept"); + } + + private static void CanWield() + { + T11ItemSupport.Reset(); + WorldObject w = Weapon(); + Check.Eq(w.Values(T11Keys.CanWield, -5), -1, "unknown before /aug"); + T11ItemSupport.OnChat("Advanced Augmentation Levels:"); + T11ItemSupport.OnChat("Item:2,400"); + Check.Eq(w.Values(T11Keys.CanWield, -5), 0, "2,400 < 2,500"); + Check.False(M(w, C(N.LongValKeyE, "1", K(T11Keys.CanWield))), "rule: wieldable fails"); + T11ItemSupport.SyncOverride(2500); + Check.Eq(w.Values(T11Keys.CanWield, -5), 1, "override 2,500 meets the gate"); + T11ItemSupport.SyncOverride(-1); + Check.Eq(w.Values(T11Keys.CanWield, -5), 0, "back to the /aug count"); + Check.Eq(new Item("T11 - Robe").Wo.Values(T11Keys.CanWield, -5), -1, "not appraised yet: unknown"); + Check.Eq(new Item("T11 - Robe").Str(16, "A robe.").Wo.Values(T11Keys.CanWield, -5), 1, "appraised, no gate: wieldable"); + T11ItemSupport.Reset(); + } +} From bf702ebc67bd241e7e1cfdb00538cd639af2f405 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Tue, 6 Oct 2026 15:03:24 -0400 Subject: [PATCH 3/6] Snapshot for release 2026.10.6.3 (internal f2255d0) --- .../Combat/BuffManager.cs | 9 ++++++++ .../Combat/WeaponSwapGate.cs | 21 ++++++++++--------- .../Tests/OffhandTests.cs | 13 ++++++++---- 3 files changed, 29 insertions(+), 14 deletions(-) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 72fd7f8..a0bc785 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -335,6 +335,9 @@ public class BuffManager : IDisposable // then the swap gate's flat 3 s). The pack move stays as the fallback: once a use hasn't // got the wand into the hand in WieldResolveTimeoutMs, this session moves the weapon first. private bool _directWandSwapFailed; + // The swap gate's claim count when the wand's use went out: a later claim means another swap + // (combat putting the axe back, 12:39 on 10-06) changed the hands, so the result says nothing. + private long _pendingWieldClaim; private int _bowDequipPendingId; private DateTime _bowDequipAt = DateTime.MinValue; private int _bowDequipAttempts; @@ -3900,6 +3903,11 @@ public class BuffManager : IDisposable if ((now - _pendingWieldAt).TotalMilliseconds < WieldResolveTimeoutMs) return false; + if (_weaponSwapGate != null && _weaponSwapGate.Claims != _pendingWieldClaim) + { + _pendingWieldId = 0; // another swap since ours: not a failed wield + return false; + } int stillInHand = _directWandSwapFailed ? 0 : FindWieldedNonWandWeapon(wandId); if (stillInHand != 0 && IsWieldedLive(stillInHand)) { @@ -3981,6 +3989,7 @@ public class BuffManager : IDisposable _host.UseFor((uint)wandId, "Buff", bowId != 0 && !_directWandSwapFailed ? "buffing: switch to the wand" : "buffing: wield the wand"); NoteStanceRequest(); + _pendingWieldClaim = _weaponSwapGate?.Claims ?? 0; _pendingWieldId = wandId; _pendingWieldAt = now; _lastCastAttempt = now; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs index 0f5a7b2..31703ea 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs @@ -25,7 +25,10 @@ public sealed class WeaponSwapGate private long _lastSwapTickMs = long.MinValue / 4; private string _lastSwapBy = ""; private int _movingId; - private bool _movingWasWielded; + private long _claims; + + /// Swaps claimed so far: a caller can tell whether another swap went out after its own. + public long Claims { get { lock (_lock) { return _claims; } } } /// /// The longest one swap holds the next: a swap the server's answer can't be seen for (or @@ -65,22 +68,21 @@ public sealed class WeaponSwapGate _lastSwapTickMs = now; _lastSwapBy = requestedBy ?? ""; _movingId = 0; + _claims++; return true; } } /// /// The claimed swap moved into or out of a hand without a use (a - /// pack move or a slot wield, which the server answers with no UseDone): the swap is done - /// once the item's wielded state is no longer . + /// pack move or a slot wield): the next swap waits the full MinIntervalMs, as before. + /// Drakkon 2026-10-06 13:58: the wand went out 1.3 s after the axe's pack move (the axe read + /// out of hand) and the server then held the first cast open until a relog. The server's + /// unwield motion outlasts the item move, and nothing tells us when it ends. /// public void NoteMove(int itemId, bool wieldedNow) { - lock (_lock) - { - _movingId = itemId; - _movingWasWielded = wieldedNow; - } + lock (_lock) _movingId = itemId; } private bool LastSwapDone(long since) @@ -88,8 +90,7 @@ public sealed class WeaponSwapGate if (since < FloorMs || ServerIdle == null || IsWielded == null) return false; try { - if (!ServerIdle()) return false; - return _movingId == 0 || IsWielded(_movingId) != _movingWasWielded; + return _movingId == 0 && ServerIdle(); } catch { diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs index 3e23d86..afdeb78 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs @@ -364,10 +364,15 @@ internal static class OffhandTests t = 500; Check.False(g.TryBeginSwap("weapon"), "the shield is still in hand"); wielded[7] = false; - Check.True(g.TryBeginSwap("weapon"), "the shield is off: the weapon goes at once (not at 3 s)"); - t = 700; - Check.False(g.TryBeginSwap("off hand"), "under the 400 ms floor"); - t = 1000; + t = 2999; + Check.False(g.TryBeginSwap("weapon"), "a pack move: the full 3 s even once it reads done (the server's unwield motion, 13:58 wedge)"); + t = 3000; + Check.True(g.TryBeginSwap("weapon"), "after 3 s"); + long claims = g.Claims; + t = 3300; + Check.False(g.TryBeginSwap("off hand"), "a use (the weapon): under the 400 ms floor"); + Check.Eq(g.Claims, claims, "a refused claim doesn't count"); + t = 3600; idle = false; Check.False(g.TryBeginSwap("off hand"), "the weapon's use is still unanswered"); idle = true; From 26907e6ab1ae31dc7ff17453b0680e7b64d1bf46 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Wed, 7 Oct 2026 12:54:26 -0400 Subject: [PATCH 4/6] Snapshot for release 2026.10.7.1 (internal 2a9c773) --- .../Combat/BuffManager.cs | 65 ++++- .../Combat/CombatManager.cs | 272 +++++++++++++----- .../Combat/WorldObjectCache.cs | 39 +++ .../CorpseOpenController.cs | 109 ++++++- .../LegacyUi/LegacyAdvancedSettingsUi.cs | 3 + .../LegacyUi/LegacyDashboardRenderer.cs | 3 + .../LegacyUi/LegacyUiSettings.cs | 6 + .../Loot/UseRefusalWatch.cs | 24 ++ .../Meta/ExpressionEngine.cs | 1 + .../RynthAiPlugin.Pacing.cs | 4 +- .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 2 +- .../RynthCore.Plugin.RynthAi.csproj | 2 + .../KillCounter.cs | 188 ++++++++++++ .../PluginExports.cs | 4 + .../RynthCore.Plugin.RynthTracker.csproj | 5 + .../RynthTrackerPlugin.cs | 100 ++++++- Plugins/Shared/ActionPacer.cs | 184 +++++++++++- Plugins/Shared/CombatText.cs | 127 ++++++++ .../Fakes/FakeHost.cs | 10 +- Tools/RynthCore.RynthAiHostTests/Program.cs | 1 + .../Tests/ActionPacingTests.cs | 234 ++++++++++++++- .../Tests/CombatMathTests.cs | 4 +- .../Tests/LootCorpseTests.cs | 55 ++++ .../Tests/MultiTargetTests.cs | 207 +++++++++++++ .../Tests/UseRefusalTests.cs | 154 ++++++++++ .../Tests/VitalsTests.cs | 71 +++++ .../KillCounterTests.cs | 131 +++++++++ .../RynthCore.TrackerSessionTests/Program.cs | 3 +- .../RynthCore.TrackerSessionTests.csproj | 2 + 29 files changed, 1900 insertions(+), 110 deletions(-) create mode 100644 Plugins/RynthCore.Plugin.RynthTracker/KillCounter.cs create mode 100644 Plugins/Shared/CombatText.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/MultiTargetTests.cs create mode 100644 Tools/RynthCore.TrackerSessionTests/KillCounterTests.cs diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index a0bc785..8d10537 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -1423,7 +1423,7 @@ public class BuffManager : IDisposable bool inCombat = _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true; int hpThreshold = inCombat ? _settings.HealAt : _settings.TopOffHP; int manaThreshold = inCombat ? _settings.GetManaAt : _settings.TopOffMana; - int stamThreshold = inCombat ? _settings.RestamAt : _settings.TopOffStam; + int stamThreshold = StaminaLine(inCombat, curStamPct, _settings, ref _restamRun, ref _restamRunCasts); // A flag is set only when something was actually done about the vital. // WantsVitalRecharge holds the arbiter on Buffing, above combat and nav, so @@ -1479,16 +1479,54 @@ public class BuffManager : IDisposable } // Stamina kits first, like healing kits for health: Lucy carried Greater Stamina Kits // and cast Revitalize/Robustification instead, because stamina never looked for a kit. - if (curStamPct < stamThreshold && (AttemptStaminaKitUse() || AttemptVitalCast("Revitalize Self") - || AttemptPotion("StaminaPotion", "Stamina"))) + // Melee first (Tom, 2026-10-06): out of Magic stance, Revitalize means switching the weapon + // for the wand and back (slow, and the 10-06 stalls began at those switches), so a stamina + // potion listed in Consumables goes before it. A potion drunk under 2.5 s ago: no Revitalize + // on top of it. In Magic stance (a caster) Revitalize stays first. + bool potionFirst = CurrentCombatMode != CombatMode.Magic; + if (curStamPct < stamThreshold) { - _isRechargingStamina = true; - return true; + bool potionJustDrunk = potionFirst && _settings.UsePotions + && (DateTime.Now - _lastPotionAt).TotalMilliseconds < 2500 + && HasListedPotion("StaminaPotion", "Stamina"); + if (!potionJustDrunk + && (AttemptStaminaKitUse() + || (potionFirst && AttemptPotion(true, "StaminaPotion", "Stamina")) + || AttemptVitalCast("Revitalize Self") + || AttemptPotion("StaminaPotion", "Stamina"))) + { + _isRechargingStamina = true; + if (_restamRun) _restamRunCasts++; + return true; + } } return false; } + // Re-stam To (2026-10-06): a recharge started under Re-stam At carries on until stamina + // reaches Re-stam To; one Revitalize often doesn't get far. Capped so a recharge that + // never gains can't loop: it ends after RestamRunMaxCasts. + private bool _restamRun; + private int _restamRunCasts; + internal const int RestamRunMaxCasts = 4; + + /// The stamina % to recharge under now (see the fields above). + internal static int StaminaLine(bool inCombat, int stamPct, LegacyUiSettings s, ref bool run, ref int casts) + { + if (!inCombat) { run = false; return s.TopOffStam; } + if (s.RestamTo <= s.RestamAt) { run = false; return s.RestamAt; } + if (stamPct < s.RestamAt) + { + if (!run) { run = true; casts = 0; } + } + else if (stamPct >= s.RestamTo || casts >= RestamRunMaxCasts) + { + run = false; + } + return run ? s.RestamTo : s.RestamAt; + } + /// True when Stamina To Health At / Min Stamina allow Stamina to Health Self now. internal static bool StaminaToHealthAllowed(LegacyUiSettings s, int healthPct, int staminaPct) => s.StaminaToHealthAt > 0 && healthPct <= s.StaminaToHealthAt && staminaPct > s.StaminaToHealthMinStamina; @@ -1644,7 +1682,21 @@ public class BuffManager : IDisposable /// Drinks the first potion of from the Items panel. /// "Stamina" is the older name for stamina potions. Off with UsePotions. /// - private bool AttemptPotion(params string[] types) + private bool AttemptPotion(params string[] types) => AttemptPotion(false, types); + + /// A potion of one of listed in Consumables and in the pack. + private bool HasListedPotion(params string[] types) + { + 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) + return true; + return false; + } + + /// : only the Consumables list, not any potion in the pack. + private bool AttemptPotion(bool listedOnly, params string[] types) { if (!_settings.UsePotions || _worldObjectCache == null) return VitalNo("Use Potions is off"); if ((DateTime.Now - _lastPotionAt).TotalMilliseconds < 2500) return VitalNo("one drunk under 2.5 s ago"); @@ -1660,6 +1712,7 @@ public class BuffManager : IDisposable if (IsHealthPotionType(types)) _healLatency.HealSent(Now, rule.Name); return true; } + if (listedOnly) return VitalNo("none listed in Consumables"); // Nothing on the Items panel: anything in the pack of that kind (Field Rations // weren't used unless someone added them by hand, 2026-09-29). foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: false)) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index 9e23a11..8d17476 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -922,6 +922,7 @@ public partial class CombatManager : IDisposable { int id = (int)objectId; _recentlyKilled.Remove(id); + _hitAt.Remove(id); _blacklistManager.ForgetTarget(id); if (id == activeTargetId || id == _lockedTargetId || id == _lastAttackedTargetId) @@ -1201,21 +1202,37 @@ public partial class CombatManager : IDisposable bool critLine = text.IndexOf("critical", StringComparison.OrdinalIgnoreCase) >= 0; if (critLine) _lastCritChatAt = now; - if (!TryParseOutgoingDamage(text, out int amount)) return; + if (!CombatText.TryParseOutgoingHit(text, out string victim, out int amount)) return; bool crit = critLine || (now - _lastCritChatAt).TotalMilliseconds <= CRIT_WINDOW_MS; - // Attribute to the current fight; if it's already cleared (we one-shot and - // moved on before the damage line landed), fall back to the last-fight - // snapshot — same wcid as the bolt, so the crit/non-crit average is right. - bool cur = _fightTargetWcid != 0; - uint wcid = cur ? _fightTargetWcid : _lastFightWcid; + // Which monster the line is about. One spell can hurt several (rings, walls, blasts, + // chain spells): each sends its own line naming its victim, and only the selected target + // gets health from the server. A line naming the fight target is the fight's; any other + // goes to the monster it names (CreditHitToOther), never to the fight target. + int victimId = ResolveHitVictim(victim, now); + bool cur = _fightTargetWcid != 0; + bool onFight = cur && (victimId != 0 + ? victimId == _fightTargetId + : victim.Equals(_fightTargetName, StringComparison.OrdinalIgnoreCase)); + // Fight already cleared (we one-shot and moved on before the line landed): the line + // belongs to the last fight when it names it. + bool onLastFight = !onFight && !cur && _lastFightWcid != 0 + && victim.Equals(_lastFightName, StringComparison.OrdinalIgnoreCase); if (_dmgDbgCount < 15) { _dmgDbgCount++; - _host.Log($"[DmgDbg] amt={amount} crit={crit} wcid={wcid} mode={CurrentCombatMode} text='{text}'"); + _host.Log($"[DmgDbg] amt={amount} crit={crit} victim='{victim}' id=0x{(uint)victimId:X8} fight={(onFight ? 1 : onLastFight ? 2 : 0)} mode={CurrentCombatMode} text='{text}'"); } + if (!onFight && !onLastFight) + { + CreditHitToOther(victimId, victim, amount, crit); + return; + } + + uint wcid = onFight ? _fightTargetWcid : _lastFightWcid; + // MAGIC-ONLY: melee/missile get the structured 0x01B1 event (OnCombatDamage), // so parsing chat for them too would double-count. if (CurrentCombatMode != CombatMode.Magic || wcid == 0) return; @@ -1224,16 +1241,147 @@ public partial class CombatManager : IDisposable // line is the ONLY damage signal for casters — without accumulating it, // _fightDamage stayed 0: EvaluateKillShot path B always saw a full-HP // target and RecordKill(totalDamage:0) never learned HP pools. - if (cur) + if (onFight) _fightDamage += amount; - uint weapon = cur ? _lastCastWeaponId : _lastFightWeaponId; - string nm = cur ? _fightTargetName : _lastFightName; - string elem = cur ? _lastCastElement : _lastFightElement; - int tier = cur ? _lastCastTier : _lastFightTier; + uint weapon = onFight ? _lastCastWeaponId : _lastFightWeaponId; + string nm = onFight ? _fightTargetName : _lastFightName; + string elem = onFight ? _lastCastElement : _lastFightElement; + int tier = onFight ? _lastCastTier : _lastFightTier; _damageStore.RecordHit(weapon, wcid, nm, elem, tier, amount, crit); } + // ── Hits on monsters other than the fight target ───────────────────────── + // A ring, wall, blast or chain spell hurts several monsters with one cast; each gets a + // damage line naming it. Same-named monsters (a swarm) are told apart by order: within one + // volley (lines no more than VolleyWindowMs apart) a monster is hit once, so the fight + // target takes the first line with its name and every further one goes to the nearest + // other monster of that name not yet hit in the volley. + private readonly Dictionary _hitAt = new(); // last line credited to each id + private const double VolleyWindowMs = 800; + private const double HitMemoryMs = 15000; // hits older than this are forgotten + private const double KillMatchRecentHitMs = 5000; // a kill notice is matched to hits this recent + + /// + /// The object a damage line naming is about, or 0 when no live monster + /// of that name is known. Stamps the hit so the next same-named line of the volley goes elsewhere. + /// + internal int ResolveHitVictim(string name, DateTime now) + { + if (string.IsNullOrEmpty(name)) return 0; + PruneHits(now); + int fight = _fightTargetId; + if (fight != 0 && !HitInVolley(fight, now) + && string.Equals(_worldFilter[fight]?.Name, name, StringComparison.OrdinalIgnoreCase)) + { + _hitAt[fight] = now; + return fight; + } + + int anchor = fight != 0 ? fight : unchecked((int)_playerId); + int best = 0, any = 0; + double bestD = double.MaxValue, anyD = double.MaxValue; + foreach (var wo in _worldFilter.GetLandscape()) + { + if (wo.ObjectClass != AcObjectClass.Monster) continue; + if (!string.Equals(wo.Name, name, StringComparison.OrdinalIgnoreCase)) continue; + if (_worldFilter.GetHealthRatio(wo.Id) == 0f) continue; // the server said dead + double d = anchor != 0 ? _worldFilter.Distance(anchor, wo.Id) : 0.0; + if (any == 0 || d < anyD) { any = wo.Id; anyD = d; } + if (wo.Id == fight || HitInVolley(wo.Id, now)) continue; + if (best == 0 || d < bestD) { best = wo.Id; bestD = d; } + } + int id = best != 0 ? best : any; + if (id != 0) _hitAt[id] = now; + return id; + } + + private bool HitInVolley(int id, DateTime now) + => _hitAt.TryGetValue(id, out DateTime t) && (now - t).TotalMilliseconds <= VolleyWindowMs; + + private readonly List _hitPruneScratch = new(); + private void PruneHits(DateTime now) + { + if (_hitAt.Count < 64) return; + _hitPruneScratch.Clear(); + foreach (var kv in _hitAt) + if ((now - kv.Value).TotalMilliseconds > HitMemoryMs) _hitPruneScratch.Add(kv.Key); + foreach (int id in _hitPruneScratch) _hitAt.Remove(id); + } + + /// + /// A hit on a monster that isn't the fight target (another target of a ring, wall or chain + /// spell): lower its health estimate (the server sends it none), count it as damage for the + /// blacklist, and learn the hit against its own monster type. + /// + private void CreditHitToOther(int victimId, string victim, int amount, bool crit) + { + uint wcid = 0; + if (victimId != 0) + { + if (_host.HasGetObjectWcid) _host.TryGetObjectWcid(unchecked((uint)victimId), out wcid); + double maxHp = ResolveMaxHpFor(victimId, wcid, victim); + _worldFilter.ApplyDamageEstimate(victimId, maxHp > 0 ? amount / maxHp : 0.0); + ReportDamageOnTarget(victimId); + } + if (wcid == 0) wcid = WcidForName(victim); + if (_damageStore != null && wcid != 0 && CurrentCombatMode == CombatMode.Magic) + _damageStore.RecordHit(_lastCastWeaponId, wcid, victim, _lastCastElement, _lastCastTier, amount, crit); + } + + /// A monster's max health from what we know: the manual override, the engine's vitals, + /// the shared creature profiles, the learned damage-to-kill. 0 when none says. + private double ResolveMaxHpFor(int id, uint wcid, string name) + { + if (_damageStore != null && wcid != 0) + { + double manual = _damageStore.GetManualHp(wcid); + if (manual > 0) return manual; + } + if (_host.HasGetTargetVitals + && _host.TryGetTargetVitals(unchecked((uint)id), out _, out uint maxHealth, out _, out _, out _, out _) + && maxHealth > 0) + return maxHealth; + if (_creatureStore != null && !string.IsNullOrEmpty(name)) + { + CreatureProfile? prof = null; + bool found = wcid != 0 ? _creatureStore.TryGet(name, wcid, out prof) : _creatureStore.TryGetByName(name, out prof); + if (found && prof != null && prof.MaxHealth > 0) return prof.MaxHealth; + } + if (_damageStore != null && wcid != 0) + { + double hp = _damageStore.GetLearnedHp(wcid); + if (hp > 0) return hp; + } + return 0; + } + + /// + /// The monster a kill notice is about, among those we hit in the last few seconds (other than + /// ): the longest name the message contains, then the most hurt, + /// then the most recently hit. 0 when none fits. + /// + private int FindRecentlyHitVictim(string deathMessage, int exclude, DateTime now) + { + int best = 0, bestLen = 0; + float bestHp = 2f; + DateTime bestAt = DateTime.MinValue; + foreach (var kv in _hitAt) + { + if (kv.Key == exclude || (now - kv.Value).TotalMilliseconds > KillMatchRecentHitMs) continue; + if (_recentlyKilled.ContainsKey(kv.Key)) continue; + string n = _worldFilter[kv.Key]?.Name ?? ""; + if (n.Length == 0 || deathMessage.IndexOf(n, StringComparison.OrdinalIgnoreCase) < 0) continue; + float hp = _worldFilter.GetHealthRatio(kv.Key); + if (hp < 0f) hp = 1f; + bool better = n.Length > bestLen + || (n.Length == bestLen && (hp < bestHp || (hp == bestHp && kv.Value > bestAt))); + if (!better) continue; + best = kv.Key; bestLen = n.Length; bestHp = hp; bestAt = kv.Value; + } + return best; + } + /// /// Extract our outgoing damage amount from a combat-log line. Two wordings reach us: /// • Retail combat log: "You blast X for 153 points of fire damage!" @@ -1241,56 +1389,13 @@ public partial class CombatManager : IDisposable /// (ACEmulator's SpellProjectile.DamageTarget emits "for {amount} points with /// {Spell.Name}" — NOT "points of damage" — so the old retail-only /// parser matched nothing on ACE and the Crit/NonCrit columns stayed empty.) - /// Returns false for incoming ("... you for N points ...") and non-damage - /// "points of <vital>" lines (heals / mana / stamina drains). Allocation-free (hot path). + /// Returns false for incoming lines ("... you for N points ...", "... your lower leg for ..."): + /// the sentence must start with "You" after any "Critical hit!"-style prefix. Also false for + /// non-damage "points of <vital>" lines (heals / mana / stamina drains). + /// Shared with RynthTracker (Plugins/Shared/CombatText.cs), which also reads the victim's name. /// internal static bool TryParseOutgoingDamage(string text, out int amount) - { - amount = 0; - - // Anchor on the word "points" (shared by both wordings). The number is the run - // of digits immediately before it; the word right AFTER it disambiguates: - // "points with ..." → ACE damage cast (only the projectile msg uses this) - // "points of ... damage" → retail damage - // "points of mana/stamina/..." → vital drain/heal (no "damage") → reject - int pts = text.IndexOf("points", StringComparison.OrdinalIgnoreCase); - if (pts < 0) return false; - - int w = pts + 6; // first char after "points" - while (w < text.Length && text[w] == ' ') w++; - bool nextWith = WordAt(text, w, "with"); - bool nextOf = WordAt(text, w, "of"); - bool isDamage = nextWith - || (nextOf && text.IndexOf("damage", w, StringComparison.OrdinalIgnoreCase) >= 0); - if (!isDamage) return false; - - // Incoming (we got hit) lines read "... you for N points ..." — not our damage. - if (text.IndexOf("you for", StringComparison.OrdinalIgnoreCase) >= 0) return false; - - int i = pts - 1; - while (i >= 0 && text[i] == ' ') i--; - long val = 0, mult = 1; bool any = false; - while (i >= 0 && (char.IsDigit(text[i]) || text[i] == ',')) - { - if (text[i] != ',') { val += (text[i] - '0') * mult; mult *= 10; any = true; } - i--; - } - if (!any || val <= 0 || val > 1_000_000) return false; - amount = (int)val; - return true; - } - - /// Case-insensitive whole-word match of (passed lowercase) - /// at in , bounded by end-of-string or a - /// non-letter. Allocation-free. - private static bool WordAt(string text, int pos, string word) - { - if (pos < 0 || pos + word.Length > text.Length) return false; - for (int k = 0; k < word.Length; k++) - if (char.ToLowerInvariant(text[pos + k]) != word[k]) return false; - int end = pos + word.Length; - return end >= text.Length || !char.IsLetter(text[end]); - } + => CombatText.TryParseOutgoingHit(text, out _, out amount); public void HandleChatForDebuffs(string text) { @@ -1882,12 +1987,26 @@ public partial class CombatManager : IDisposable // a late death notice killed a neighbour. Dropping it also hid it from the scan for // 4 s, and with no other mob in range the bot went to peace mid-fight. bool noticeForSwappedMob = pendingKillId != 0 && pendingKillId != tid; - bool curAttacked = _fightTargetId != tid || _fightCastCount > 0 || _pendingOffensiveTargetId == tid; - if (tid != 0 && curMatches && (noticeForSwappedMob || !curAttacked)) + // A damage line naming the target (ResolveHitVictim stamped it) is an attack too. + bool curAttacked = _fightTargetId != tid || _fightCastCount > 0 || _pendingOffensiveTargetId == tid + || (tid != 0 && _hitAt.ContainsKey(tid)); + // A ring, wall or chain spell kills neighbours too. The server's health for the fight + // target lands before its kill notice (ACE sends the 0 with the lethal hit), so a fight + // target the server still says is alive didn't die: the notice is a same-named + // neighbour's we hit in the last few seconds. + int otherVictim = (!curMatches || noticeForSwappedMob) ? 0 : FindRecentlyHitVictim(deathMessage, tid, nowKill); + float curHp = tid != 0 ? _worldFilter.GetHealthRatio(tid) : -1f; + bool curServerAlive = curHp > 0f && !_worldFilter.IsHealthEstimated(tid); + bool noticeForNeighbour = otherVictim != 0 && curServerAlive; + if (tid != 0 && curMatches && (noticeForSwappedMob || !curAttacked || noticeForNeighbour)) { _host.Log($"[RynthAi] Kill notice names 0x{tid:X8} '{curName}' but " + - (noticeForSwappedMob ? $"belongs to predicted kill 0x{pendingKillId:X8}" : "it hasn't been attacked yet") + + (noticeForSwappedMob ? $"belongs to predicted kill 0x{pendingKillId:X8}" + : noticeForNeighbour ? $"it is alive ({curHp:0.00}); a neighbour we hit died (0x{otherVictim:X8})" + : "it hasn't been attacked yet") + " — keeping the target"); + if (noticeForNeighbour) + _recentlyKilled[otherVictim] = nowKill.AddMilliseconds(RECENTLY_KILLED_SUPPRESS_MS); } else if (tid != 0 && curMatches) { @@ -1895,8 +2014,27 @@ public partial class CombatManager : IDisposable ForgetScanned(tid); DropTarget("killed (KillerNotification)"); } + else if (pendingKillId == 0) + { + // Another monster died, not the fight target: one we hit with a ring, wall or chain. + // Keep the scan off it while its corpse forms. + int victim = FindRecentlyHitVictim(deathMessage, tid, nowKill); + if (victim != 0) + _recentlyKilled[victim] = nowKill.AddMilliseconds(RECENTLY_KILLED_SUPPRESS_MS); + } } + /// Test seam: engage as the fight target, as a target lock does. + internal void EngageForTest(int targetId) + { + activeTargetId = targetId; + _lockedTargetId = targetId; + BeginFight(targetId); + } + + /// Test seam: true while the scan is kept off after a kill. + internal bool IsKillSuppressed(int id) => _recentlyKilled.ContainsKey(id); + /// Record the just-stamped _lastFight* context into the recent-fights ring, /// keyed by the live object id (refreshed per hit, capped, TTL-pruned). Lets a kill that /// lands after we've advanced past the dying mob still be credited by name (tier 4). @@ -2443,7 +2581,12 @@ public partial class CombatManager : IDisposable // wield, attack or cast while the server is still answering the last action (a kit, a corpse // use, a buff, the last stance change). On ACE a mode change cancels a pending use's walk // and fails a cast in progress; that interleaving began every stuck-use stall on record. - if (!ActionPacer.MayStart(_host, "Combat", HealNeed.None, out _)) + // Melee/missile attack repeats skip the animation gate (gestureGate false): the server swings + // on its own timers, a swing can't land inside a use's server turn because the use above holds + // every attack until it is answered, and waiting for each swing animation would cost DPS. A + // stance change still waits (ChangeCombatModeFor), and so does everything in peace/magic. + bool attackRepeat = CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile; + if (!ActionPacer.MayStart(_host, "Combat", HealNeed.None, out _, gestureGate: !attackRepeat)) { LastCombatSkipReason = "server-answering"; // D4 record-only _tickWait = CombatLatencyTracker.Wait.Busy; @@ -4698,6 +4841,7 @@ public partial class CombatManager : IDisposable else _host.MeleeAttack(targetId, acHeight, power); + RynthCore.Plugin.Shared.ActionPacer.NoteAttackSent(); // nothing else starts before this swing plays _serverAttackTargetId = activeTargetId; LastCombatSkipReason = "attack"; // D4 record-only: physical attack sent this tick return true; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs index e0fb827..115b6d3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs @@ -43,6 +43,12 @@ public class WorldObjectCache private readonly HashSet _landscape = new(); // has physics position private readonly HashSet _inventory = new(); // no physics position private readonly Dictionary _healthRatios = new(); // last known health ratio per object (0-1) + // Ids whose ratio is an estimate from our own damage lines (a ring, wall or chain spell's other + // targets: the server sends health only for the selected target). A real health update replaces + // the estimate and takes the id out of this set. + private readonly HashSet _estimatedHealth = new(); + /// The lowest an estimate goes: 0 means dead to every reader, and only the server says that. + internal const float EstimatedHealthFloor = 0.01f; // OnCreateObject IDs pending classification private readonly Queue _pending = new(); @@ -199,6 +205,7 @@ public class WorldObjectCache _creatures.Remove(sid); _landscape.Remove(sid); _healthRatios.Remove(sid); + _estimatedHealth.Remove(sid); _classifyRetry.Remove(id); _slowRetry.Remove(id); _reclassifySkipState.Remove(id); @@ -234,6 +241,37 @@ public class WorldObjectCache return _healthRatios.TryGetValue(id, out float v) ? v : -1f; } + /// + /// Lowers a creature's health by our own hit when the server sends it no health of its own: the + /// other targets of a ring, wall or chain spell (ACE pushes health only for the selected target). + /// is damage / max health, or 0 when the max is unknown, which only + /// marks the creature as hurt (0.99). Never goes to 0 (dead is the server's call: the kill + /// notice, a health update or the corpse) and never raises a known value. A real health update + /// overwrites the estimate. + /// + public void ApplyDamageEstimate(int id, double fraction) + { + lock (_gate) + { + if (_playerId != 0 && unchecked((uint)id) == _playerId) return; + float cur = _healthRatios.TryGetValue(id, out float v) ? v : 1f; + if (cur <= 0f) return; + float next = fraction > 0 + ? (float)Math.Max(EstimatedHealthFloor, cur - fraction) + : Math.Min(cur, 0.99f); + if (next >= cur && _healthRatios.ContainsKey(id)) return; + _healthRatios[id] = next; + _estimatedHealth.Add(id); + } + } + + /// True when 's health ratio is our estimate rather than the server's. + public bool IsHealthEstimated(int id) + { + lock (_gate) + return _estimatedHealth.Contains(id); + } + public void OnUpdateHealth(uint id, float healthRatio) { lock (_gate) @@ -243,6 +281,7 @@ public class WorldObjectCache int sid = (int)id; _healthRatios[sid] = Math.Clamp(healthRatio, 0f, 1f); + _estimatedHealth.Remove(sid); // the server's number replaces any estimate if (!_creatures.Add(sid)) return; // creature already known — ratio updated above, nothing more to do diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index efab96a..9678880 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -97,6 +97,8 @@ public sealed partial class RynthAiPlugin private bool _currentLootItemMovePending; private bool _corpseAutorunActive; private int _currentLootItemMoveAttempts; + private long _currentLootItemStillSince; + private long _pickupAnimSince; private string _currentLootItemActionLabel = string.Empty; private string _currentLootItemName = string.Empty; private bool _currentLootItemIsSalvage; @@ -400,6 +402,11 @@ public sealed partial class RynthAiPlugin LootDiag($"[RynthAi] Corpse loot: opened container 0x{objectId:X8}."); _consecutiveLootTimeouts = 0; // a successful open proves AC is responsive again _lootWedgeAnnounced = false; + if (_useCheckJumpAt != 0) + { + Log($"[RynthAi] Use check: 0x{objectId:X8} opened {CorpseNowMs - _useCheckJumpAt} ms after the use check's jump - the jump cleared the server's stuck turn."); + _useCheckJumpAt = 0; + } ApplyUseRefusalVerdict(_useRefusals.OnOpened(CorpseNowMs), CorpseNowMs); if (switchedTarget) LootDiag($"[RynthAi] Corpse loot: switching active corpse target from 0x{(uint)_targetCorpseId:X8} to 0x{objectId:X8}."); @@ -1376,6 +1383,11 @@ public sealed partial class RynthAiPlugin return; } + // The last pickup's bend-down still plays: the engine holds a move sent now until + // it ends, so wait and send it then. + if (PickupAnimating(CorpseNowMs)) + return; + ChatLine($"[RynthAi] Loot rule: {matchItemName} -> [{matchActionLabel}] {matchRuleLabel}"); _currentLootItemId = firstMatchId; RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)firstMatchId)); @@ -1448,6 +1460,28 @@ public sealed partial class RynthAiPlugin } } + /// Longest a pickup waits on the motion queue (the engine's own hold is 2.5 s). + internal const long PickupAnimMaxMs = 3000; + + /// + /// The character still has motions queued (the engine's cast gate, GetCastBusyState): + /// the bend-down of the last pickup is playing. False after PickupAnimMaxMs of it, so a + /// stuck queue can't stop looting, and on an engine without the gate. + /// + private bool PickupAnimating(long now) + { + bool busy; + try { busy = Host.HasGetCastBusyState && Host.GetCastBusyState() != 0; } catch { busy = false; } + if (!busy) + { + _pickupAnimSince = 0; + return false; + } + if (_pickupAnimSince == 0) + _pickupAnimSince = now; + return now - _pickupAnimSince < PickupAnimMaxMs; + } + private void TickPendingCorpsePickup(LegacyUiSettings settings) { if (_objectCache == null || _openedContainerId == 0 || _currentLootItemId == 0) @@ -1475,9 +1509,20 @@ public sealed partial class RynthAiPlugin return; } - // Item still on corpse — wait before retrying the UseObject. + // Item still on corpse — wait before retrying the UseObject. The window counts from + // when the character is still: while a pickup animation plays the engine holds the + // move, and a retry timed from the send gave up on items whose move had not gone + // out yet (2026-10-07: moves ran ~2.2 s late, 3 tries at 0.5 s skipped the item). + if (PickupAnimating(now)) + { + _currentLootItemStillSince = 0; + return; + } + if (_currentLootItemStillSince == 0) + _currentLootItemStillSince = now; long verifyWindowMs = Math.Max(150, settings.LootRetryTimeoutMs); - if (now - _currentLootItemMoveRequestedAt < verifyWindowMs) + long windowStart = Math.Max(_currentLootItemMoveRequestedAt, _currentLootItemStillSince); + if (now - windowStart < verifyWindowMs) return; if (_currentLootItemMoveAttempts >= 3) @@ -2293,6 +2338,7 @@ public sealed partial class RynthAiPlugin _currentLootItemMovePending = false; _currentLootItemMoveRequestedAt = 0; _currentLootItemMoveAttempts = 0; + _currentLootItemStillSince = 0; _currentLootItemActionLabel = string.Empty; _currentLootItemName = string.Empty; _currentLootItemIsSalvage = false; @@ -2394,6 +2440,16 @@ public sealed partial class RynthAiPlugin ApplyUseRefusalVerdict(verdict, now); return false; } + + // The back-off is over and this is the probe: jump first (clears the server's stuck + // animation queue, see UseRefusalWatch), send the probe after the pause. + if (_useRefusals.TakeProbeJump(now) && TryUseCheckJump(now, "before the probe")) + { + _lootHaltUntil = Math.Max(_lootHaltUntil, now + UseRefusalWatch.CleanStopPauseMs); + _lastCorpseOpenAttemptAt = 0; + _corpseTargetSince = now; + return false; + } } _lastOpenAttemptCorpseId = corpseId; @@ -2429,17 +2485,20 @@ public sealed partial class RynthAiPlugin case UseRefusalWatch.Verdict.CleanStopAndRetry: { FlightRecorderSignal.Dump(Host, "use check: corpse opens answered but not opened"); - Log($"[RynthAi] Use check: {_useRefusals.Refusals} corpse opens in a row were answered by the server but nothing opened ({RefusedList()}) - one clean stop, a {UseRefusalWatch.CleanStopPauseMs} ms pause, then one more try."); + Log($"[RynthAi] Use check: {_useRefusals.Refusals} corpse opens in a row were answered by the server but nothing opened ({RefusedList()}) - one clean stop, a jump, a {UseRefusalWatch.CleanStopPauseMs} ms pause, then one more try."); Host.SetAutoRunBy("Loot/UseCheck", false); if (Host.HasStopCompletely) Host.StopCompletelyBy("Loot/UseCheck"); _corpseAutorunActive = false; _corpseApproachTurnsActive = false; - // Face the corpse for the retry. Since 2026-10-04 the bot leaves the turn to the - // server; if the server can't turn the character any more, a corpse already in - // front may still open (mid-stall, 06:28:19, a use by hand with the macro off + // The jump is the fix (see UseRefusalWatch): it empties the server's animation + // queues and cancels the stuck turn; the retry then gets a fresh server turn. + bool jumped = TryUseCheckJump(now, "for the retry"); + // Without a jump: face the corpse for the retry. Since 2026-10-04 the bot leaves the + // turn to the server; if the server can't turn the character any more, a corpse already + // in front may still open (mid-stall, 06:28:19, a use by hand with the macro off // opened one - the only open in those 13 minutes; whether it was faced isn't logged). - if (_targetCorpseId != 0 && Host.HasTurnToHeading + if (!jumped && _targetCorpseId != 0 && Host.HasTurnToHeading && TryGetHeadingToObject(_targetCorpseId, out double faceDeg, out double faceErr, out _) && faceErr > 2.0) { @@ -2465,7 +2524,8 @@ public sealed partial class RynthAiPlugin case UseRefusalWatch.Verdict.Stuck: { FlightRecorderSignal.Dump(Host, "use check: server refuses every use"); - Log($"[RynthAi] Use check: the server answers every use but nothing opens ({_useRefusals.Refusals} refusals on {RefusedList()}), the clean stop and retry didn't help - looting paused {_useRefusals.BackoffMs / 60_000} min, then one corpse is tried again."); + Log($"[RynthAi] Use check: the server answers every use but nothing opens ({_useRefusals.Refusals} refusals on {RefusedList()}), the clean stop{(_useCheckJumpAt != 0 ? ", the jump" : "")} and retry didn't help - looting paused {_useRefusals.BackoffMs / 60_000} min, then one corpse is tried again{(Host.HasTapJump ? " after a jump" : "")}."); + _useCheckJumpAt = 0; if (!_useStuckAnnounced) { _useStuckAnnounced = true; @@ -2475,7 +2535,8 @@ public sealed partial class RynthAiPlugin break; } case UseRefusalWatch.Verdict.StillStuck: - Log($"[RynthAi] Use check: still refused - next try in {_useRefusals.BackoffMs / 60_000} min."); + Log($"[RynthAi] Use check: still refused{(_useCheckJumpAt != 0 ? " after the jump" : "")} - next try in {_useRefusals.BackoffMs / 60_000} min."); + _useCheckJumpAt = 0; ResetCorpseTarget(); break; case UseRefusalWatch.Verdict.Recovered: @@ -2487,6 +2548,35 @@ public sealed partial class RynthAiPlugin } } + /// When the use check last jumped (0 = not since the last open). + private long _useCheckJumpAt; + + /// + /// One jump in place for the use check. On ACE the jump (0xF61B, the keyboard path: TapJump) + /// is the only in-world action that empties the server's animation queues for the character + /// (Player.HandleActionJump: RemoveLinkAnimations drains MotionTableManager.PendingAnimations, + /// MotionInterp.PendingMotions.Clear(), IsAnimating = false) and it cancels the stuck walk/turn + /// (GameActionJump -> StopExistingMoveToChains2). JumpNonAutonomous (0xF7C9) is not used: ACE + /// has no handler for it. Not while the pacer has an action out (a jump in Magic stance fails a + /// cast on the server). + /// + private bool TryUseCheckJump(long now, string why) + { + if (!Host.HasTapJump) + return false; + if (ActionPacer.Outstanding(Host, out var pending) && pending != null) + { + Log($"[RynthAi] Use check: no jump {why} - the server still owes an answer to {ActionPacer.Describe(pending.Kind, pending.Label)}."); + return false; + } + Host.SetAutoRunBy("Loot/UseCheck", false); + bool ok = Host.TapJump(); + if (ok) + _useCheckJumpAt = now; + Log($"[RynthAi] Use check: jump {why} (clears the server's stuck animation queue; a relog was the only other fix) ok={ok}."); + return ok; + } + private string RefusedList() => string.Join(", ", _useRefusals.RefusedCorpses.Select(id => $"0x{(uint)id:X8}")); @@ -2511,6 +2601,7 @@ public sealed partial class RynthAiPlugin private void ResetUseRefusalState() { _useRefusals.Reset(); + _useCheckJumpAt = 0; _useStuckAnnounced = false; _lootWedgeAnnounced = false; _consecutiveLootTimeouts = 0; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index e5dd363..0da3631 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -396,6 +396,9 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.SetNextItemWidth(120); ImGui.SliderInt("Re-stam At", ref _settings.RestamAt, 0, 100); ImGui.SetNextItemWidth(120); + ImGui.SliderInt("Re-stam To", ref _settings.RestamTo, 0, 100); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Once a recharge starts under Re-stam At, keep recharging until stamina reaches this %.\n0 = one recharge, as before."); + ImGui.SetNextItemWidth(120); ImGui.SliderInt("Get Mana At", ref _settings.GetManaAt, 0, 100); ImGui.Spacing(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 5f71cfd..f023612 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -965,6 +965,7 @@ internal sealed class LegacyDashboardRenderer StopLootingWhenPackFull = s.StopLootingWhenPackFull, StopMacroWhenPackFull = s.StopMacroWhenPackFull, RestamAt = s.RestamAt, + RestamTo = s.RestamTo, GetManaAt = s.GetManaAt, TopOffHP = s.TopOffHP, TopOffStam = s.TopOffStam, @@ -1172,6 +1173,7 @@ internal sealed class LegacyDashboardRenderer s.StopLootingWhenPackFull = p.StopLootingWhenPackFull; s.StopMacroWhenPackFull = p.StopMacroWhenPackFull; s.RestamAt = p.RestamAt; + s.RestamTo = p.RestamTo ?? 0; s.GetManaAt = p.GetManaAt; s.TopOffHP = p.TopOffHP; s.TopOffStam = p.TopOffStam; @@ -1630,6 +1632,7 @@ internal sealed class LegacyDashboardRenderer dst.StopLootingWhenPackFull = tmp.StopLootingWhenPackFull; dst.StopMacroWhenPackFull = tmp.StopMacroWhenPackFull; dst.RestamAt = tmp.RestamAt; + dst.RestamTo = tmp.RestamTo; dst.GetManaAt = tmp.GetManaAt; dst.TopOffHP = tmp.TopOffHP; dst.TopOffStam = tmp.TopOffStam; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index bc0cf78..110d5f1 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -131,6 +131,11 @@ public sealed class LegacyUiSettings public bool StopLootingWhenPackFull = true; public bool StopMacroWhenPackFull = false; public int RestamAt = 30; + /// + /// In combat, once stamina drops under Re-stam At, keep recharging until it reaches this % + /// (one Revitalize often doesn't get far). 0, or not above Re-stam At = one recharge, as before. + /// + public int RestamTo = 0; public int GetManaAt = 40; public int TopOffHP = 95; public int TopOffStam = 95; @@ -796,6 +801,7 @@ public sealed class SettingsBridgePayload public bool StopLootingWhenPackFull { get; set; } public bool StopMacroWhenPackFull { get; set; } public int RestamAt { get; set; } + public int? RestamTo { get; set; } public int GetManaAt { get; set; } public int TopOffHP { get; set; } public int TopOffStam { get; set; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs index 6614aa9..1f84f44 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs @@ -27,6 +27,16 @@ // A UseDone with an error (0x1D "too busy", ...) says nothing either way, and // an open the server never answers is left to the corpse timeout as before. // No game calls here: the controller acts on the verdicts. +// +// The jump (2026-10-06 afternoon): the stuck state is the server's animation +// bookkeeping for the character (ACE: MotionInterp.PendingMotions/IsAnimating +// and the MotionTableManager queue never drain, so the server's turn to the +// corpse never starts and the use's callback never runs). Besides leaving the +// world, the only thing on ACE that empties those queues is the player's jump +// (Player.HandleActionJump: RemoveLinkAnimations drains the motion table queue, +// PendingMotions.Clear, IsAnimating = false; the jump also cancels the pending +// walk/turn). So the controller jumps at the clean stop, and once more before +// each probe after a back-off (TakeProbeJump). // ============================================================================ using System; @@ -73,6 +83,7 @@ internal sealed class UseRefusalWatch public int LastRefusedCorpse { get; private set; } private readonly HashSet _refused = new(); + private bool _probeJumpTaken; private bool _pending; private int _pendingId; private long _sentAt; @@ -82,6 +93,16 @@ internal sealed class UseRefusalWatch /// While Stuck: no opens until the back-off ends (then one probe). public bool HoldsOpens(long now) => State == Phase.Stuck && now < BackoffUntil; + /// The back-off is over and the probe is next: true once per back-off, meaning + /// "jump first, then send the probe after the pause". + public bool TakeProbeJump(long now) + { + if (State != Phase.Stuck || now < BackoffUntil || _probeJumpTaken) + return false; + _probeJumpTaken = true; + return true; + } + /// Call before sending the next open: the previous one, answered with nothing opened, /// counts as refused now (the next attempt came before its grace ran out). A verdict other than /// None means: act on it and don't send this open. @@ -154,6 +175,7 @@ internal sealed class UseRefusalWatch BackoffMs = 0; LastRefusedCorpse = 0; _refused.Clear(); + _probeJumpTaken = false; _pending = false; _answeredAt = 0; } @@ -178,11 +200,13 @@ internal sealed class UseRefusalWatch State = Phase.Stuck; BackoffMs = FirstBackoffMs; BackoffUntil = now + BackoffMs; + _probeJumpTaken = false; return Verdict.Stuck; default: // Stuck: a probe after the back-off BackoffMs = Math.Min(MaxBackoffMs, Math.Max(FirstBackoffMs, BackoffMs * 2)); BackoffUntil = now + BackoffMs; + _probeJumpTaken = false; return Verdict.StillStuck; } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index a1ca0f3..e6157a2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -3340,6 +3340,7 @@ internal sealed class ExpressionEngine ["MinBlastTargets"] = (() => I(s.MinBlastTargets), v => { if (int.TryParse(v, out int i)) s.MinBlastTargets = i; }), ["HealAt"] = (() => I(s.HealAt), v => { if (int.TryParse(v, out int i)) s.HealAt = i; }), ["RestamAt"] = (() => I(s.RestamAt), v => { if (int.TryParse(v, out int i)) s.RestamAt = i; }), + ["RestamTo"] = (() => I(s.RestamTo), v => { if (int.TryParse(v, out int i)) s.RestamTo = i; }), ["GetManaAt"] = (() => I(s.GetManaAt), v => { if (int.TryParse(v, out int i)) s.GetManaAt = i; }), ["TopOffHP"] = (() => I(s.TopOffHP), v => { if (int.TryParse(v, out int i)) s.TopOffHP = i; }), ["TopOffStam"] = (() => I(s.TopOffStam), v => { if (int.TryParse(v, out int i)) s.TopOffStam = i; }), diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs index daf3f27..fd7c8bf 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs @@ -51,7 +51,9 @@ public sealed partial class RynthAiPlugin get { int busy = _busyCount; - if (ActionPacer.Enabled && ActionPacer.Current(Host) != null) busy++; + if (ActionPacer.Enabled + && (ActionPacer.Current(Host) != null || ActionPacer.GestureHolds(Host, "Items", HealNeed.None, out _))) + busy++; // an unanswered server action, or the character still animating (a pack move of a wielded item, a stone, a summon would start on top) return busy; } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index ad0768c..7b556ad 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -871,7 +871,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase ["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (50, 2000), ["BowArcVelocity"] = (10, 60), ["CrossbowArcVelocity"] = (10, 80), ["AtlatlArcVelocity"] = (10, 60), ["MagicArcVelocity"] = (10, 60), ["MissileArcClearance"] = (0, 3), ["HealAt"] = (0, 100), ["EmergencyHealAt"] = (0, 100), - ["StaminaToHealthAt"] = (0, 100), ["StaminaToHealthMinStamina"] = (0, 100), ["RestamAt"] = (0, 100), ["GetManaAt"] = (0, 100), + ["StaminaToHealthAt"] = (0, 100), ["StaminaToHealthMinStamina"] = (0, 100), ["RestamAt"] = (0, 100), ["RestamTo"] = (0, 100), ["GetManaAt"] = (0, 100), ["TopOffHP"] = (0, 100), ["TopOffStam"] = (0, 100), ["TopOffMana"] = (0, 100), ["HealOthersAt"] = (0, 100), ["RestamOthersAt"] = (0, 100), ["InfuseOthersAt"] = (0, 100), ["MeleeAttackPower"] = (-1, 100), ["MissileAttackPower"] = (-1, 100), diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj index e3740c0..c805add 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj @@ -35,6 +35,8 @@ + + diff --git a/Plugins/RynthCore.Plugin.RynthTracker/KillCounter.cs b/Plugins/RynthCore.Plugin.RynthTracker/KillCounter.cs new file mode 100644 index 0000000..0e0c496 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthTracker/KillCounter.cs @@ -0,0 +1,188 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthTracker; + +/// +/// Counts your kills, including the extra monsters a ring, wall, blast or chain spell kills. +/// +/// Two ways a kill is counted: +/// 1. The server's killer notification (it goes only to whoever landed the killing blow). +/// One notification is one kill, as before. +/// 2. A corpse ("Corpse of X") with no notification for it, when you hit an X with a +/// multi-target spell in the last . Some servers send no +/// notification for the extra monsters a spell kills (chain spells on Conquest), and on +/// ACE a killing blow sends no damage line either, so the corpse is the one sign left. +/// +/// "Multi-target" is read from the combat log: one cast's damage lines (and kill notices) +/// arrive together, so lines no more than apart are one volley, and +/// a volley with two or more of them hit several monsters. Each name hit in such a volley may +/// be counted from its corpse as many times as that volley hit it (tokens). A single-target +/// hit never makes a corpse count: a monster you hit once that someone else then finished +/// isn't yours, the same as before. +/// +/// A notification is matched to its corpse later (the corpse forms after the death animation), +/// so a kill counted by its notification isn't counted again by its corpse. +/// +/// Pure logic, no host: the plugin passes every event with its time, so tests can drive it. +/// +internal sealed class KillCounter +{ + /// Damage lines and kill notices this close together belong to one cast. + public const double VolleyGapMs = 800; + /// How long after a multi-target hit a monster's corpse still counts as your kill. + public const double TokenLifeMs = 15000; + /// How long a kill notice waits for its corpse. + public const double NoticeLifeMs = 20000; + /// How long a single-target hit is remembered (only to explain an uncounted corpse in the log). + public const double HitMemoryMs = 15000; + + public int Kills { get; private set; } + public int NoticeKills { get; private set; } + public int CorpseKills { get; private set; } + + private readonly List<(string Message, DateTime At)> _notices = new(); + private readonly Dictionary _tokens = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _lastHit = new(StringComparer.OrdinalIgnoreCase); + + // The volley in progress: hits per name, and how many members (lines + notices) it has. + private readonly Dictionary _volley = new(StringComparer.OrdinalIgnoreCase); + private int _volleyMembers; + private DateTime _volleyLast = DateTime.MinValue; + + /// The server's killer notification: always one kill. + public void OnKillNotice(string? message, DateTime now) + { + Kills++; + NoticeKills++; + Prune(now); + _notices.Add((message ?? "", now)); + JoinVolley(now); + // A notice is one of the volley's monsters too (the killing blow sends no damage line), + // under the name of a monster we hit that the message contains. + string? name = LongestRecentHitIn(message ?? "", now); + if (name != null) _volley[name] = _volley.TryGetValue(name, out int n) ? n + 1 : 1; + GrantTokens(now); + } + + private string? LongestRecentHitIn(string message, DateTime now) + { + string? best = null; + foreach (var kv in _lastHit) + { + if ((now - kv.Value).TotalMilliseconds > HitMemoryMs) continue; + if (message.IndexOf(kv.Key, StringComparison.OrdinalIgnoreCase) < 0) continue; + if (best == null || kv.Key.Length > best.Length) best = kv.Key; + } + return best; + } + + /// One of your damage lines, naming the monster it hurt. + public void OnHit(string victim, DateTime now) + { + if (string.IsNullOrEmpty(victim)) return; + JoinVolley(now); + _volley[victim] = _volley.TryGetValue(victim, out int n) ? n + 1 : 1; + _lastHit[victim] = now; + GrantTokens(now); + } + + /// What a corpse turned out to be. + public enum CorpseResult + { + /// Its kill notice already counted it. + Notified, + /// No notice, but you hit it with a multi-target spell: counted now. + Counted, + /// You hit a monster of that name, but only single-target: not counted (someone else's kill?). + HitNotCounted, + /// Nothing of yours. + NotOurs, + } + + /// A corpse appeared; is the X of "Corpse of X". + public CorpseResult OnCorpse(string monsterName, DateTime now) + { + if (string.IsNullOrEmpty(monsterName)) return CorpseResult.NotOurs; + Prune(now); + + // The oldest notice that names this monster. + int match = -1; + for (int i = 0; i < _notices.Count; i++) + if (_notices[i].Message.IndexOf(monsterName, StringComparison.OrdinalIgnoreCase) >= 0) { match = i; break; } + if (match >= 0) + { + _notices.RemoveAt(match); + // It was one of the monsters a multi-target volley hit: it no longer vouches for another. + if (_tokens.TryGetValue(monsterName, out var used) && used.Count > 0) + _tokens[monsterName] = (used.Count - 1, used.Until); + return CorpseResult.Notified; + } + + if (_tokens.TryGetValue(monsterName, out var t) && t.Count > 0 && t.Until >= now) + { + _tokens[monsterName] = (t.Count - 1, t.Until); + Kills++; + CorpseKills++; + return CorpseResult.Counted; + } + + return _lastHit.TryGetValue(monsterName, out DateTime h) && (now - h).TotalMilliseconds <= HitMemoryMs + ? CorpseResult.HitNotCounted + : CorpseResult.NotOurs; + } + + public void Reset() + { + Kills = NoticeKills = CorpseKills = 0; + _notices.Clear(); + _tokens.Clear(); + _lastHit.Clear(); + _volley.Clear(); + _volleyMembers = 0; + _volleyLast = DateTime.MinValue; + } + + private void JoinVolley(DateTime now) + { + if ((now - _volleyLast).TotalMilliseconds > VolleyGapMs) + { + _volley.Clear(); + _volleyMembers = 0; + } + _volleyMembers++; + _volleyLast = now; + } + + // A volley that hit several monsters makes each name it hit countable from its corpse, as + // many times as the volley hit that name. Max, not sum: the next cast hits the same monsters + // again, and two casts at two monsters are still two monsters. + private void GrantTokens(DateTime now) + { + if (_volleyMembers < 2) return; + DateTime until = now.AddMilliseconds(TokenLifeMs); + foreach (var kv in _volley) + { + int have = _tokens.TryGetValue(kv.Key, out var t) && t.Until >= now ? t.Count : 0; + _tokens[kv.Key] = (Math.Max(have, kv.Value), until); + } + } + + private readonly List _pruneScratch = new(); + private void Prune(DateTime now) + { + _notices.RemoveAll(n => (now - n.At).TotalMilliseconds > NoticeLifeMs); + if (_tokens.Count > 32) + { + _pruneScratch.Clear(); + foreach (var kv in _tokens) if (kv.Value.Until < now) _pruneScratch.Add(kv.Key); + foreach (string k in _pruneScratch) _tokens.Remove(k); + } + if (_lastHit.Count > 64) + { + _pruneScratch.Clear(); + foreach (var kv in _lastHit) if ((now - kv.Value).TotalMilliseconds > HitMemoryMs) _pruneScratch.Add(kv.Key); + foreach (string k in _pruneScratch) _lastHit.Remove(k); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthTracker/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthTracker/PluginExports.cs index 62a6e8e..98a8b7a 100644 --- a/Plugins/RynthCore.Plugin.RynthTracker/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthTracker/PluginExports.cs @@ -40,6 +40,10 @@ public static unsafe class PluginExports public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) => Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth); + // Corpses (0.3.0): a kill a ring, wall or chain spell made without a kill notice is found by its corpse. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId); + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })] public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId); diff --git a/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj b/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj index 87e9c13..4fc8d89 100644 --- a/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj +++ b/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj @@ -21,6 +21,11 @@ Kills, experience and luminance per hour for each session. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthTracker/RynthTrackerPlugin.cs b/Plugins/RynthCore.Plugin.RynthTracker/RynthTrackerPlugin.cs index b1bba92..7ef7775 100644 --- a/Plugins/RynthCore.Plugin.RynthTracker/RynthTrackerPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthTracker/RynthTrackerPlugin.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Runtime.InteropServices; +using RynthCore.Plugin.Shared; using RynthCore.PluginCore; namespace RynthCore.Plugin.RynthTracker; @@ -8,7 +9,7 @@ namespace RynthCore.Plugin.RynthTracker; public sealed class RynthTrackerPlugin : RynthPluginBase { internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthTracker"); - internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.2.1"); + internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.0"); private uint _playerId; private bool _loginComplete; @@ -24,12 +25,28 @@ public sealed class RynthTrackerPlugin : RynthPluginBase // blow: a fellow's kill, a summon's kill or a mob someone else finished never counts, // and neither does the XP they bring (damage share, fellowship share, quests). That XP // still counts toward the totals and XP/hour. + // + // 0.3.0: plus the extra monsters a ring, wall, blast or chain spell kills when the + // server sends no notification for them (chain spells on Conquest): their corpse counts + // when you hit that monster with a multi-target spell just before (KillCounter.cs). private long _killXp; private int _xpKills; // kills that closed their window (the per-kill divisor) private int _openKills; // kills whose window is still open private DateTime _killWindowUntil; // XP rises seen until then belong to those kills private const double KillWindowSec = 2.5; + // Kill notices, our damage lines and corpses, for the kills a notice doesn't cover. + private readonly KillCounter _killCounter = new(); + // Corpses waiting for their name (the client may not have it on the create tick). + private readonly List<(uint Id, DateTime Seen)> _pendingCorpses = new(); + private const double CorpseNameWaitSec = 3.0; + private const int MaxPendingCorpses = 256; + // XP that landed outside any kill window: a kill found by its corpse (seconds after the + // death animation) takes the XP of the few seconds before it. + private readonly List<(DateTime At, long Xp)> _unattributedXp = new(); + private const double CorpseXpLookbackSec = 8.0; + private int _corpseLogCount; + private int _tickCounter; // Everything comes from the player's own properties, never from chat text: @@ -126,6 +143,76 @@ public sealed class RynthTrackerPlugin : RynthPluginBase _killsTotal++; _openKills++; _killWindowUntil = DateTime.UtcNow.AddSeconds(KillWindowSec); + _killCounter.OnKillNotice(deathMessage, DateTime.UtcNow); + } + + // Our damage lines name each monster a spell hurt (one line per monster for rings, walls, + // blasts and chain spells): that is how a multi-target hit is recognised. + public override void OnChatWindowText(string? text, int chatType, ref int eat) + { + if (!_loginComplete) return; + if (CombatText.TryParseOutgoingHit(text, out string victim, out _)) + _killCounter.OnHit(victim, DateTime.UtcNow); + } + + // Corpses are read on the tick (their name may not be readable yet on the create). + public override void OnCreateObject(uint objectId) + { + if (!_loginComplete || objectId == 0) return; + if (_pendingCorpses.Count >= MaxPendingCorpses) _pendingCorpses.RemoveAt(0); + _pendingCorpses.Add((objectId, DateTime.UtcNow)); + } + + public override void OnDeleteObject(uint objectId) + { + for (int i = _pendingCorpses.Count - 1; i >= 0; i--) + if (_pendingCorpses[i].Id == objectId) _pendingCorpses.RemoveAt(i); + } + + /// Reads the names of newly created objects; a "Corpse of X" goes to the kill counter. + private void CheckPendingCorpses() + { + if (_pendingCorpses.Count == 0) return; + if (!Host.HasGetObjectName) { _pendingCorpses.Clear(); return; } + DateTime now = DateTime.UtcNow; + for (int i = _pendingCorpses.Count - 1; i >= 0; i--) + { + var (id, seen) = _pendingCorpses[i]; + if (!Host.TryGetObjectName(id, out string name) || string.IsNullOrEmpty(name)) + { + if ((now - seen).TotalSeconds > CorpseNameWaitSec) _pendingCorpses.RemoveAt(i); + continue; + } + _pendingCorpses.RemoveAt(i); + string? monster = CombatText.CorpseOwnerName(name); + if (monster == null) continue; + var result = _killCounter.OnCorpse(monster, now); + if (result == KillCounter.CorpseResult.Counted) + CountCorpseKill(now); + if ((result == KillCounter.CorpseResult.Counted || result == KillCounter.CorpseResult.HitNotCounted) + && _corpseLogCount < 40) + { + _corpseLogCount++; + Host.Log(result == KillCounter.CorpseResult.Counted + ? $"[RynthTracker] Kill counted from its corpse (no kill notice): '{name}' 0x{id:X8}, hit by a multi-target spell. Kills {_killsTotal}." + : $"[RynthTracker] Not counted: '{name}' 0x{id:X8} - you hit it, single-target, and got no kill notice (someone else's kill?)."); + } + } + } + + /// A kill found by its corpse: one more kill, and the XP of the seconds before it. + private void CountCorpseKill(DateTime now) + { + _killsTotal++; + bool inKillWindow = _openKills > 0 && now <= _killWindowUntil; + if (inKillWindow) _openKills++; // closes with the window, its XP already in it + else _xpKills++; + for (int i = _unattributedXp.Count - 1; i >= 0; i--) + { + if ((now - _unattributedXp[i].At).TotalSeconds > CorpseXpLookbackSec) continue; + _killXp += _unattributedXp[i].Xp; + _unattributedXp.RemoveAt(i); + } } public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) @@ -148,6 +235,8 @@ public sealed class RynthTrackerPlugin : RynthPluginBase Host.Log("[RynthTracker] Session reset."); } + if (_loginComplete) CheckPendingCorpses(); + if (++_tickCounter < 30) return; // rebuild every ~0.5s at 60Hz _tickCounter = 0; if (_loginComplete) PollExperience(); @@ -171,6 +260,12 @@ public sealed class RynthTrackerPlugin : RynthPluginBase long gained = _xpRise.Take(xp); _xpTotal += gained; if (inKillWindow) _killXp += gained; + else if (gained > 0) + { + DateTime now = DateTime.UtcNow; + _unattributedXp.RemoveAll(e => (now - e.At).TotalSeconds > CorpseXpLookbackSec); + _unattributedXp.Add((now, gained)); + } // Capped only when past retail's 275 total AND kills keep bringing nothing: an // awakened character's cap is higher (Aelrynth), so the total alone can't say. _maxLevel = xp >= MaxLevelXp && _xpKills >= 3 && _xpTotal == 0; @@ -213,6 +308,9 @@ public sealed class RynthTrackerPlugin : RynthPluginBase _xpKills = 0; _openKills = 0; _radTotal = 0; + _killCounter.Reset(); + _pendingCorpses.Clear(); + _unattributedXp.Clear(); // The next read of each is the new baseline. _xpRise.Clear(); _lumRise.Clear(); _radRise.Clear(); _bankedRise.Clear(); _drawnRise.Clear(); _snapshot = EmptySnapshot; diff --git a/Plugins/Shared/ActionPacer.cs b/Plugins/Shared/ActionPacer.cs index 725b3e5..8fd513e 100644 --- a/Plugins/Shared/ActionPacer.cs +++ b/Plugins/Shared/ActionPacer.cs @@ -25,10 +25,30 @@ // * While one is outstanding, RynthAi starts no other one (MayStart; mode changes // are refused right at ChangeCombatModeFor) and moves or turns the character // only to stop real movement (MoveAudit asks HoldsMovement). -// * Heals keep their priority: a heal may go ahead of a corpse/door use the server -// hasn't answered after HealAfterWorldUseMs (EmergencyAfterWorldUseMs at -// Emergency Heal At), and one heal may follow a cast whose result is already in -// (the server queues one cast behind the recoil). +// * Heals keep some priority: at Emergency Heal At a heal may go ahead of a corpse/door +// use the server hasn't answered after EmergencyAfterWorldUseMs, and one heal may +// follow a cast whose result is already in (the server queues one cast behind the +// recoil). A heal under the plain Heal line waits for the use's answer (2026-10-06, +// below: an action during the use's server turn stops that turn for good). +// * And nothing starts while the character is still animating: the client's own motion +// queue (CMotionInterp pending motions, the engine's cast gate: GetCastBusyState) must +// be empty, for uses, kits, potions, casts, stance changes, wields and the item +// managers' moves (GestureHolds). Melee/missile attack repeats are exempt (MayStart +// with gestureGate false). Time limit GestureHoldMaxMs (GestureEmergencyMaxMs for an +// emergency heal), logged, like Combat/CastGateWatchdog for casts. +// +// Why the animation gate (2026-10-06 afternoon, ops/overnight/2026-10-06-turnto-stall.md, +// replayed through ACE's own physics code): on ACE a use in reach is finished by the +// server's MoveToManager turning the character (TurnRight on the server's copy of the +// motion state). Every server motion for the character (a swing, a kit, a cast gesture, +// a stance) is applied with MotionInterp.apply_raw_movement, which rewrites the +// interpreted TurnCommand from the raw state (none) and so stops that TurnRight; the +// MoveToManager is never told (its FailProgressCount is counted but never acted on) and +// stays Initialized, which keeps the player "moving or animating", so Player_Tick never +// runs the use's callback either. The use is answered only when the next use fails it: +// "UseDone with no error, nothing opens", the stall's signature. Starting nothing while +// the character animates, and nothing while a use's turn is unanswered, keeps every +// server motion out of every server turn. // // Opt-in (Enabled, RynthAi sets it at Init); off = every call goes through as before. // Linked into RynthAi only. UseAudit reports its sends through UseAudit.AfterSend. @@ -98,9 +118,14 @@ internal static class ActionPacer public const long ModeSettleMs = 800; /// A wield that reads done: a short settle for the wield motion. public const long WieldSettleMs = 150; - /// A heal may go ahead of a door/corpse use unanswered this long (the server cancels the walk cleanly). - public const long HealAfterWorldUseMs = 1000; + /// At Emergency Heal At a heal may go ahead of a door/corpse use unanswered this long. It stops + /// the server's walk/turn to that object (the use is then answered by the next one); a plain heal waits. public const long EmergencyAfterWorldUseMs = 300; + /// The client's motion queue reading busy this long is taken as stuck: the action goes (logged). + /// Same backstop as Combat/CastGateWatchdog (no real gesture, stance or swing lasts this long). + public const long GestureHoldMaxMs = 4000; + /// An emergency heal waits for the character's animation at most this long. + public const long GestureEmergencyMaxMs = 1500; /// A heal behind a stance change: once the client has read the new mode this long. public const long HealAfterModeReadMs = 300; /// An engine without UseDone: an action counts as answered after this (no real pacing). @@ -112,6 +137,10 @@ internal static class ActionPacer // Counters for /ra pace and the periodic summary. private static long _started, _answered, _timedOut, _sentOverOutstanding, _modeRefused, _modeSkipped; private static long _heldStarts, _heldMoves, _healsAhead; + private static long _gestureHolds, _gestureLimits; + private static long _gestureBusySince; // when the client's motion queue was first seen busy (0 = clear) + private static bool _gestureOverride; // the hold limit passed: open until the queue reads clear + private static readonly HashSet _gestureLogged = new(); private static long _maxWaitMs; private static string _maxWaitWhat = ""; private static readonly Dictionary _holdsByWho = new(); @@ -126,6 +155,8 @@ internal static class ActionPacer public static long HeldStarts => _heldStarts; public static long HeldMoves => _heldMoves; public static long HealsAhead => _healsAhead; + public static long GestureHoldCount => _gestureHolds; + public static long GestureLimits => _gestureLimits; /// Back to a fresh load (Init, logout, tests). Enabled is left as it is. public static void Reset() @@ -135,6 +166,11 @@ internal static class ActionPacer _cur = null; _started = _answered = _timedOut = _sentOverOutstanding = _modeRefused = _modeSkipped = 0; _heldStarts = _heldMoves = _healsAhead = 0; + _gestureHolds = _gestureLimits = 0; + _swingSentMs = 0; _swingSeenBusy = false; _swingHolds = 0; _swingLogged.Clear(); + _gestureBusySince = 0; + _gestureOverride = false; + _gestureLogged.Clear(); _maxWaitMs = 0; _maxWaitWhat = ""; _holdsByWho.Clear(); @@ -279,10 +315,20 @@ internal static class ActionPacer /// /// May send a use, a cast or a mode change now? False (with why) while - /// another action waits for the server, except the heal rules in the file header. One log - /// line per outstanding action and subsystem. + /// another action waits for the server, except the heal rules in the file header, and while + /// the character is still animating (; skipped with + /// false: melee/missile attack repeats). One log line per + /// outstanding action (or animation) and subsystem. /// - public static bool MayStart(RynthCoreHost host, string who, HealNeed heal, out string why) + public static bool MayStart(RynthCoreHost host, string who, HealNeed heal, out string why, bool gestureGate = true) + { + if (!Enabled) { why = ""; return true; } + if (!OutstandingAllows(host, who, heal, out why)) return false; + if (gestureGate && GestureHolds(host, who, heal, out why)) return false; + return true; + } + + private static bool OutstandingAllows(RynthCoreHost host, string who, HealNeed heal, out string why) { why = ""; PacedAction? a = Current(host); @@ -291,8 +337,7 @@ internal static class ActionPacer if (heal != HealNeed.None) { - if (a.Kind == PacedKind.WorldUse - && age >= (heal == HealNeed.Emergency ? EmergencyAfterWorldUseMs : HealAfterWorldUseMs)) + if (a.Kind == PacedKind.WorldUse && heal == HealNeed.Emergency && age >= EmergencyAfterWorldUseMs) { lock (Gate) _healsAhead++; Log(host, $"[Pace] {who}: the heal goes ahead of {Describe(a.Kind, a.Label)} (unanswered for {age} ms)"); @@ -324,6 +369,117 @@ internal static class ActionPacer return false; } + /// + /// True (with why) while the character is still animating: the client's own motion queue + /// (CMotionInterp pending motions, read by the engine as GetCastBusyState) is not empty. + /// The client animates exactly the motions the server sends for the character, a moment + /// after the server applies them, so an empty queue means the server's copy is done too. + /// Past GestureHoldMaxMs (GestureEmergencyMaxMs for an emergency heal) the action goes, + /// logged once per busy spell. No opinion (false) on an engine without the gate. + /// + public static bool GestureHolds(RynthCoreHost host, string who, HealNeed heal, out string why) + { + why = ""; + if (!Enabled) return false; + bool busy; + try { busy = host.HasGetCastBusyState && host.GetCastBusyState() != 0; } catch { busy = false; } + long now = NowMs(); + if (SwingHolds(host, who, heal, busy, now, out why)) return true; + string? line = null; + lock (Gate) + { + if (!busy) + { + if (_gestureOverride) + line = "[Pace] the character's animation queue reads clear again"; + _gestureBusySince = 0; + _gestureOverride = false; + _gestureLogged.Clear(); + } + else + { + if (_gestureBusySince == 0) _gestureBusySince = now; + long age = now - _gestureBusySince; + if (!_gestureOverride && age >= GestureHoldMaxMs) + { + _gestureOverride = true; + _gestureLimits++; + line = $"[Pace] {who}: the character's animation queue has read busy for {age} ms - taken as stuck, going on"; + } + if (_gestureOverride) + { + busy = false; + } + else if (heal == HealNeed.Emergency && age >= GestureEmergencyMaxMs) + { + _gestureLimits++; + line = $"[Pace] {who}: emergency heal after {age} ms of animation - going on"; + busy = false; + } + else + { + _gestureHolds++; + _holdsByWho[who] = _holdsByWho.TryGetValue(who, out int n) ? n + 1 : 1; + why = $"the character is still animating ({age} ms)"; + if (_gestureLogged.Add(who)) + line = $"[Pace] {who} waits: {why}"; + } + } + } + if (line != null) Log(host, line); + return busy; + } + + // A swing sent but not animating yet (Drakkon 2026-10-06 16:45:37): the wand's use went 110 ms + // after a MeleeAttack, before the swing showed in the client's motion queue, so the motion gate + // let it through; the switch landed on the swing the server was starting and the next cast was + // held open. After CombatManager sends an attack, nothing else starts until the client's motion + // queue has read busy and then clear (the swing played), or SwingStartMaxMs passes. + public const long SwingStartMaxMs = 1500; + public const long SwingEmergencyMaxMs = 500; + private static long _swingSentMs; + private static bool _swingSeenBusy; + private static long _swingHolds; + private static readonly HashSet _swingLogged = new(); + public static long SwingHoldCount => _swingHolds; + + /// CombatManager sent a melee or missile attack. + public static void NoteAttackSent() + { + lock (Gate) + { + _swingSentMs = NowMs(); + _swingSeenBusy = false; + _swingLogged.Clear(); + } + } + + private static bool SwingHolds(RynthCoreHost host, string who, HealNeed heal, bool busy, long now, out string why) + { + why = ""; + string? line = null; + bool hold = false; + lock (Gate) + { + if (_swingSentMs == 0) return false; + long age = now - _swingSentMs; + if (busy) _swingSeenBusy = true; + if ((_swingSeenBusy && !busy) || age >= SwingStartMaxMs) + { + _swingSentMs = 0; + } + else if (!_swingSeenBusy && !(heal == HealNeed.Emergency && age >= SwingEmergencyMaxMs)) + { + hold = true; + _swingHolds++; + why = $"a swing sent {age} ms ago hasn't started animating yet"; + if (_swingLogged.Add(who)) line = $"[Pace] {who} waits: {why}"; + } + } + if (line != null) Log(host, line); + return hold; + } + /// /// True while the outstanding action is one the server animates (all of them: the walk/turn /// to a used object, a heal or wield motion, a cast, a stance change). MoveAudit holds @@ -403,6 +559,7 @@ internal static class ActionPacer lines.Add($" Sent {_started}, answered {_answered}, no answer in time {_timedOut}{(_lastTimeout.Length > 0 ? $" (last: {_lastTimeout})" : "")}"); lines.Add($" Starts held {_heldStarts}, moves held {_heldMoves}, heals let ahead {_healsAhead}, sent over an unanswered one {_sentOverOutstanding}"); lines.Add($" Mode changes refused while waiting {_modeRefused}, skipped (already in that mode) {_modeSkipped}"); + lines.Add($" Held while the character was animating {_gestureHolds}, animation time limits {_gestureLimits}"); if (_maxWaitMs > 0) lines.Add($" Longest wait seen: {_maxWaitMs} ms ({_maxWaitWhat})"); if (_holdsByWho.Count > 0) { @@ -462,6 +619,11 @@ internal static class ActionPacer Log(host, $"[Pace] {who}: change to {ModeName(mode)} mode held ({why}): {Describe(a.Kind, a.Label)} sent {NowMs() - a.SentMs} ms ago by {a.Who} has no answer yet (a mode change now would cancel it on the server)"); return false; } + if (GestureHolds(host, "mode:" + who, HealNeed.None, out _)) + { + lock (Gate) _modeRefused++; + return false; + } } int seq = UseDoneSeqNow(host); if (host.ChangeCombatMode(mode)) diff --git a/Plugins/Shared/CombatText.cs b/Plugins/Shared/CombatText.cs new file mode 100644 index 0000000..63a883f --- /dev/null +++ b/Plugins/Shared/CombatText.cs @@ -0,0 +1,127 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/CombatText.cs +// Reading YOUR hits out of the combat log: who was hit and for how much. +// Compiled into RynthAi and RynthTracker (linked source), so both read the +// same lines the same way. +// +// A spell that hits several monsters (a ring, a wall, a blast, or a chain +// spell on servers that have them) sends one line per monster it hurt, each +// naming that monster: +// ACE: "You blast Drudge Skulker for 153 points with Whirling Blade VII." +// retail: "You scorch Mosswart Worshipper for 1,234 points of fire damage!" +// with optional prefixes ("Critical hit! ", "Sneak Attack! ", "Overpower! "). +// The victim's name is what tells the lines apart; nothing else in them does. +// +// Note (ACE SpellProjectile.DamageTarget): the line is sent only while the +// target is still alive. The killing blow sends the killer notification +// instead, so a monster killed by its first hit has no damage line at all. +// ============================================================================ +using System; + +namespace RynthCore.Plugin.Shared; + +internal static class CombatText +{ + /// + /// Reads one of OUR damage lines. True with the victim's name (no leading "the") and the + /// amount; false for anything else: a monster hitting us (or our body part), drains and + /// heals ("points of mana"), experience, evades. Allocation-light: one Substring for the name. + /// + public static bool TryParseOutgoingHit(string? text, out string victim, out int amount) + { + victim = ""; + amount = 0; + if (string.IsNullOrEmpty(text)) return false; + + int start = SkipPrefixes(text); + if (!StartsWithWord(text, start, "You")) return false; + int verbStart = start + 3; + while (verbStart < text.Length && text[verbStart] == ' ') verbStart++; + // The verb is one word ("blast", "gore", "scorch", "slash"...). + int verbEnd = verbStart; + while (verbEnd < text.Length && char.IsLetter(text[verbEnd])) verbEnd++; + if (verbEnd == verbStart || verbEnd >= text.Length || text[verbEnd] != ' ') return false; + + int pts = text.IndexOf(" points", verbEnd, StringComparison.OrdinalIgnoreCase); + if (pts < 0) return false; + + // What follows "points" decides whether it is damage. + int w = pts + 7; + while (w < text.Length && text[w] == ' ') w++; + bool nextWith = WordAt(text, w, "with"); + bool nextOf = WordAt(text, w, "of"); + bool isDamage = nextWith || (nextOf && text.IndexOf("damage", w, StringComparison.OrdinalIgnoreCase) >= 0); + if (!isDamage) return false; + + // The number right before " points". + int i = pts - 1; + long val = 0, mult = 1; + bool any = false; + while (i >= 0 && (char.IsDigit(text[i]) || text[i] == ',')) + { + if (text[i] != ',') { val += (text[i] - '0') * mult; mult *= 10; any = true; } + i--; + } + if (!any || val <= 0 || val > 1_000_000) return false; + + // "... for ": the victim runs from after the verb to " for ". + const string forWord = " for "; + int forAt = i - forWord.Length + 1; + if (forAt <= verbEnd || string.CompareOrdinal(text, forAt, forWord, 0, forWord.Length) != 0) return false; + int nameStart = verbEnd + 1; + if (StartsWithWord(text, nameStart, "the")) nameStart += 4; + if (forAt <= nameStart) return false; + string name = text.Substring(nameStart, forAt - nameStart).Trim(); + // "You ... yourself", "your ..." are not monsters. + if (name.Length == 0 || name.Equals("yourself", StringComparison.OrdinalIgnoreCase) + || name.StartsWith("your ", StringComparison.OrdinalIgnoreCase)) + return false; + + victim = name; + amount = (int)val; + return true; + } + + /// The monster's name out of a corpse's name ("Corpse of Drudge Skulker"), else null. + public static string? CorpseOwnerName(string? corpseName) + { + const string prefix = "Corpse of "; + if (string.IsNullOrEmpty(corpseName) || !corpseName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + return null; + string n = corpseName.Substring(prefix.Length).Trim(); + return n.Length == 0 ? null : n; + } + + // "Critical hit! ", "Sneak Attack! ", "Overpower! " (any order, any number): a short run + // of words ending in '!' before the sentence proper. + private static int SkipPrefixes(string text) + { + int p = 0; + for (int guard = 0; guard < 4; guard++) + { + while (p < text.Length && text[p] == ' ') p++; + int bang = text.IndexOf('!', p); + if (bang < 0 || bang - p > 24) break; + bool words = true; + for (int k = p; k < bang; k++) + if (!(char.IsLetter(text[k]) || text[k] == ' ')) { words = false; break; } + if (!words || bang == p) break; + // A sentence that itself ends in '!' ("You scorch X for 5 points of fire damage!") is + // not a prefix: prefixes never contain "You ". + if (StartsWithWord(text, p, "You")) break; + p = bang + 1; + } + while (p < text.Length && text[p] == ' ') p++; + return p; + } + + private static bool StartsWithWord(string text, int pos, string word) + { + if (pos < 0 || pos + word.Length > text.Length) return false; + if (string.Compare(text, pos, word, 0, word.Length, StringComparison.OrdinalIgnoreCase) != 0) return false; + int end = pos + word.Length; + return end >= text.Length || !char.IsLetter(text[end]); + } + + private static bool WordAt(string text, int pos, string word) => StartsWithWord(text, pos, word); +} diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index d1cec55..b12bc04 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -82,6 +82,9 @@ internal static unsafe class FakeHost public static readonly List AutoRunCalls = new(); public static bool AutoRun; public static int Jumps; + /// Opt-in: wires TapJump (the keyboard jump, 0xF61B); calls land in . + public static bool TapJumpCalls; + public static int TapJumps; public static int Turns; public static readonly List<(uint Target, int SpellId)> Casts = new(); /// Opt-in: wires GiveObjectTo (AC's give action); every call lands in . @@ -193,7 +196,7 @@ internal static unsafe class FakeHost Vitals = default; BaseVitals = default; WorldName = ""; AccountName = ""; HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0; Logs.Clear(); Chat.Clear(); ChatCommands.Clear(); - AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear(); + AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear(); Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1; VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0; ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false; @@ -245,6 +248,8 @@ internal static unsafe class FakeHost api.SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl])&SetAutoRun; api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl])&TurnToHeading; api.JumpNonAutonomousFn = (IntPtr)(delegate* unmanaged[Cdecl])&JumpNonAutonomous; + if (TapJumpCalls) + api.TapJumpFn = (IntPtr)(delegate* unmanaged[Cdecl])&TapJump; api.CastSpellFn = (IntPtr)(delegate* unmanaged[Cdecl])&CastSpell; if (StopCalls) api.StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl])&StopCompletely; @@ -614,6 +619,9 @@ internal static unsafe class FakeHost [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int JumpNonAutonomous(float extent) { Jumps++; return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int TapJump() { TapJumps++; return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 313385a..320a21b 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -64,6 +64,7 @@ internal static class Program OwnCorpseTests.Register(runner); UseRefusalTests.Register(runner); VitalsTests.Register(runner); + MultiTargetTests.Register(runner); CastSafetyTests.Register(runner); HealLatencyTests.Register(runner); BlastTests.Register(runner); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs index 05f1905..8a2cc81 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs @@ -49,14 +49,22 @@ internal static class ActionPacingTests r.Add("pacing: the stall onset replayed - the idle peace swap waits for the corpse use's answer, then goes; no swap to the mode you're in", OnsetModeChangeHeld); r.Add("pacing: moves, turns and redundant stops wait while the server answers; a real stop and the cast nudge go through", MovesHeld); r.Add("pacing: no answer - each kind's time limit lets the next action go, logged, and nothing is force-cleared", TimeLimits); - r.Add("pacing: heals keep their priority (1 s behind a corpse use, 300 ms at Emergency, one behind a cast's result, 300 ms after the stance reads)", HealRules); + r.Add("pacing: heals (a plain heal waits for a corpse use's answer, 300 ms at Emergency, one behind a cast's result, 300 ms after the stance reads)", HealRules); r.Add("pacing (vitals): Drakkon 07:03 - a cast whose result is in waits for its UseDone: one cast, not a too-busy flood", CastWaitsForUseDone); - r.Add("pacing (vitals): a heal goes 1 s behind an unanswered corpse use; the emergency stance settle is unchanged", HealLatencyKept); + r.Add("pacing (vitals): a heal waits for an unanswered corpse use's answer, then goes at once; the emergency stance settle is unchanged", HealLatencyKept); r.Add("pacing (looting): one open per server answer, never re-sent on top of an unanswered one", LootOneOpenPerAnswer); r.Add("pacing (looting): Drakkon's stall is still found and said once with pacing on", LootStallStillDetected); r.Add("pacing (combat): the idle peace swap waits while a kit is unanswered", CombatPeaceWaitsForKit); r.Add("pacing (arbiter): the activity-change StopCompletely only when RynthAi itself has the character moving", ArbiterStopOnlyWhenMoving); r.Add("busy mirror: follows the engine's count (1.5 s), never reset while the engine says busy; old engines: the mirror only; never a force-clear", MirrorResetOnly); + r.Add("motion gate (14:29): a kit waits for the swing's animation; the corpse open waits for the kit's answer and then its animation", MotionGate1429); + r.Add("pacing (motion): after a swing is sent, nothing else starts until it has played (16:45 wand on a swing)", SwingNotStarted); + r.Add("motion gate (13:58): wand wield -> the cast and the Magic stance wait until the wield's animation is over", MotionGate1358); + r.Add("motion gate (morning): corpse use -> the idle peace swap waits for the UseDone and then the turn's animation", MotionGateMorning); + r.Add("motion gate: 4 s of 'animating' is taken as stuck (logged once, open until it reads clear); an emergency heal waits 1.5 s at most", MotionGateLimits); + r.Add("motion gate: melee/missile attack repeats are not held by the animation, peace/magic combat starts are; off with the pacing", MotionGateAttackExempt); + r.Add("motion gate (looting): a corpse open waits while the character animates, then goes", MotionGateLooting); + r.Add("motion gate (items): the item managers' busy count includes the animation", MotionGateItems); } // ── Pacer rig ─────────────────────────────────────────────────────────────── @@ -239,14 +247,18 @@ internal static class ActionPacingTests host.UseFor(Corpse, "Loot", "open"); _t += 900; Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a heal 900 ms behind an unanswered corpse use waits"); - _t += 100; - Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "at 1 s it goes ahead (the server cancels the walk cleanly)"); - Check.True(Logged("the heal goes ahead of the use of"), "logged"); - + _t += 3000; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), + "a plain heal still waits at 3.9 s: on ACE any motion during the server's turn to the corpse stops that turn for good"); FakeHost.UseDone(0); + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "the use is answered: the heal goes"); + host.UseFor(Corpse, "Loot", "open"); - _t += 300; + _t += 299; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "at Emergency Heal At: not before 300 ms"); + _t += 1; Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "at Emergency Heal At: 300 ms"); + Check.True(Logged("the heal goes ahead of the use of"), "logged"); Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "anything else still waits"); FakeHost.UseDone(0); @@ -356,17 +368,20 @@ internal static class ActionPacingTests PaceOn(); try { - // A heal behind a corpse use the server walks to: it waits 1 s, not the whole walk. + // A heal behind a corpse use the server walks/turns to: it waits for the use's answer (a cast + // during the server's turn stops the turn for good on ACE), then goes at once. var r = new BuffRig(); r.S.HealAt = 60; r.S.TopOffHP = 60; r.S.GetManaAt = 0; r.S.TopOffMana = 0; r.V.CurrentHealth = 50; r.V.CurrentMana = 100; r.At(0); r.Host.UseFor(Corpse, "Loot", "open the claimed corpse"); r.B.BusyCount = 1; // the open's +1 on the client's count, as the engine reports it - for (double s = 0; s < 0.95; s += 0.1) { r.At(s); r.B.OnHeartbeat(); } - Check.Eq(FakeHost.Casts.Count, 0, "under 1 s behind the unanswered open: no heal yet"); - r.At(1.0); r.B.OnHeartbeat(); - Check.Eq(FakeHost.Casts.Count, 1, "at 1 s the heal goes (the open's busy count doesn't hold it again)"); + for (double s = 0; s < 1.45; s += 0.1) { r.At(s); r.B.OnHeartbeat(); } + Check.Eq(FakeHost.Casts.Count, 0, "behind the unanswered open: no heal"); + FakeHost.UseDone(0); + r.B.BusyCount = 0; // the engine's UseDone decrement + r.At(1.5); r.B.OnHeartbeat(); + Check.Eq(FakeHost.Casts.Count, 1, "the open is answered: the heal goes on the next heartbeat"); string healName = SpellTable.ById(FakeHost.Casts[0].SpellId)?.Name ?? ""; Check.True(healName.StartsWith("Heal Self") || healName == "Adja's Intervention", "and it is the heal spell: " + healName); @@ -619,4 +634,199 @@ internal static class ActionPacingTests Check.True(Logged("resetting the mirror only"), "and the line says so"); }); } + + // ── The motion gate (2026-10-06 afternoon, ops\overnight\2026-10-06-turnto-stall.md) ────────── + // Nothing starts while the character is still animating (the client's motion queue, the engine's + // GetCastBusyState); FakeHost.CastBusy = 1 stands for "animating". + + // 16:45:37: the wand's use went 110 ms after a MeleeAttack, before the swing animated. + private static void SwingNotStarted() => Paced(() => + { + var host = World(); + FakeHost.CastBusy = 0; + ActionPacer.NoteAttackSent(); + _t += 110; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out string why), "the wand waits: the swing hasn't animated yet"); + Check.True(why.Contains("swing"), "why: " + why); + Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "the next attack isn't held"); + _t += 200; + FakeHost.CastBusy = 1; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "swinging: still waits"); + _t += 700; + FakeHost.CastBusy = 0; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "the swing played: the wand goes"); + + ActionPacer.NoteAttackSent(); + _t += 600; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "an emergency heal waits at most 500 ms"); + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "anything else still waits"); + _t += 1000; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "a swing that never animates holds at most 1.5 s"); + Check.True(ActionPacer.SwingHoldCount >= 2, "holds counted"); + }); + + private static void MotionGate1429() => Paced(() => + { + var host = World(); + // 14:29:21.435 the swing; 22.380 AttackDone (the attack sequence is over, the swing still plays). + FakeHost.CastBusy = 1; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out string why), "22.41: the kit waits for the swing's animation"); + Check.True(why.Contains("still animating"), "why says so: " + why); + Check.True(Logged("[Pace] Buff waits: the character is still animating"), "logged once"); + _t += 300; + FakeHost.CastBusy = 0; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "the swing is over: the kit goes"); + host.UseOnFor(Kit, Player, "Buff", "vitals: healing kit on yourself"); + FakeHost.CastBusy = 1; // the kit's SkillHealSelf + _t += 2400; + Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "the corpse open waits for the kit's answer"); + FakeHost.UseDone(0); // 24.794 the kit's UseDone; the client still plays the kit's last frames + Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out why), "answered, but still animating: the open waits"); + Check.True(why.Contains("still animating"), "why: " + why); + _t += 120; + FakeHost.CastBusy = 0; + Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "at rest: the corpse open goes"); + Check.True(ActionPacer.GestureHoldCount >= 2, "holds counted"); + }); + + private static void MotionGate1358() => Paced(() => + { + var host = World(combatMode: 2); + // 13:58:54.210 the wand is wielded in melee stance (its use is an item use, answered by wielding). + host.UseFor(Wand, "Buff", "buffing: switch to the wand"); + FakeHost.CastBusy = 1; // the unwield/wield and stance motion + FakeHost.Wielded[Wand] = 0x01000000; + _t += 50; + ActionPacer.Current(host); // the wield is first seen done + _t += 200; + Check.True(ActionPacer.Current(host) == null, "the wield reads done: answered"); + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "the cast waits: still animating"); + Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode"), "the Magic stance waits too"); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no mode request sent"); + Check.True(Logged("[Pace] mode:Buff waits: the character is still animating"), "logged"); + _t += 900; + FakeHost.CastBusy = 0; + Check.True(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode"), "at rest: Magic mode"); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", "sent"); + FakeHost.CombatModeValue = 8; + FakeHost.CastBusy = 1; // the stance animation + _t += ActionPacer.ModeSettleMs; + Check.True(ActionPacer.Current(host) == null, "the stance is read and settled"); + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "but the client still animates it: the cast waits"); + FakeHost.CastBusy = 0; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "at rest: the cast goes"); + }); + + private static void MotionGateMorning() => Paced(() => + { + var host = World(combatMode: 2); + FakeHost.Positions[Player] = Me0; + FakeHost.PlayerPose = Me0; + var s = new LegacyUiSettings { IsMacroRunning = true, EnableCombat = true, PeaceModeWhenIdle = true, MonsterRange = 50 }; + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + var combat = new CombatManager(host, s, cache); + combat.SetPlayerId(Player); + + // 06:18:44.549 the corpse use in melee stance; the idle peace swap came 3 ms later. + host.UseFor(Corpse, "Loot", "open the claimed corpse"); + _t += 3; + combat.Think(); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "3 ms later: no peace swap (the use is unanswered)"); + FakeHost.CastBusy = 1; // the turn to the corpse + _t += 400; + FakeHost.UseDone(0); + typeof(CombatManager).GetField("_lastPeaceAttempt", Any)!.SetValue(combat, DateTime.MinValue); + combat.Think(); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "answered, but the character still animates: no peace swap"); + _t += 200; + FakeHost.CastBusy = 0; + typeof(CombatManager).GetField("_lastPeaceAttempt", Any)!.SetValue(combat, DateTime.MinValue); + combat.Think(); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "at rest: the idle swap goes out"); + }); + + private static void MotionGateLimits() => Paced(() => + { + var host = World(); + FakeHost.CastBusy = 1; + Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "animating: held"); + _t += 1499; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "an emergency heal waits up to 1.5 s"); + _t += 1; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "at 1.5 s the emergency heal goes"); + Check.True(Logged("emergency heal after 1500 ms of animation - going on"), "logged"); + Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "anything else still waits"); + _t += ActionPacer.GestureHoldMaxMs - 1500; + Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "4 s: taken as stuck, the action goes"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("taken as stuck, going on")), 1, "logged once"); + _t += 5000; + Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "still open while it reads busy"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("taken as stuck, going on")), 1, "not logged again"); + Check.Eq(ActionPacer.GestureLimits, 2L, "two limits counted"); + FakeHost.CastBusy = 0; + Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "clear"); + Check.True(Logged("animation queue reads clear again"), "the recovery is logged"); + FakeHost.CastBusy = 1; + Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "a new animation: held again (a fresh 4 s)"); + }); + + private static void MotionGateAttackExempt() => Paced(() => + { + var host = World(combatMode: 2); + FakeHost.CastBusy = 1; // the last swing still plays + Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "a melee attack repeat is not held by the animation"); + Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "anything gated is"); + host.UseFor(Corpse, "Loot", "open"); + Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "but an attack still waits for an unanswered corpse use (the server's turn)"); + FakeHost.UseDone(0); + Check.True(ActionPacer.Current(host) == null, "the use is answered"); + ActionPacer.Enabled = false; + Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "pacing off: no gate"); + Check.False(ActionPacer.GestureHolds(host, "Loot", HealNeed.None, out _), "pacing off: no animation hold"); + ActionPacer.Enabled = true; + FakeHost.ServerGates = false; + var old = FakeHost.Create(Player); + Check.True(ActionPacer.MayStart(old, "Loot", HealNeed.None, out _), "an engine without the gate: no opinion"); + }); + + private static void MotionGateLooting() + { + LootWorld(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + PaceOn(); + try + { + WithClock((now, advance) => + { + FakeHost.CastBusy = 1; + for (int i = 0; i < 20; i++) { bot.Tick(); advance(100); } + Check.Eq(FakeHost.Uses.Count, 0, "no open while the character animates"); + Check.True(Logged("[Pace] Loot waits: the character is still animating"), "logged"); + FakeHost.CastBusy = 0; + for (int i = 0; i < 10 && FakeHost.Uses.Count == 0; i++) { bot.Tick(); advance(100); } + Check.Eq(FakeHost.Uses.Count, 1, "at rest: the open goes"); + }); + } + finally { PaceOff(); } + } + + private static void MotionGateItems() + { + LootWorld(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + PaceOn(); + try + { + int Busy() => (int)typeof(RynthAiPlugin).GetProperty("PacedBusy", Any)!.GetValue(bot.P)!; + Check.Eq(Busy(), 0, "at rest, nothing outstanding: 0"); + FakeHost.CastBusy = 1; + Check.Eq(Busy(), 1, "animating: +1 (a pack move of a wielded item, a stone, a summon waits)"); + FakeHost.CastBusy = 0; + Check.Eq(Busy(), 0, "at rest again: 0"); + } + finally { PaceOff(); } + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CombatMathTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CombatMathTests.cs index 8e441de..82bf1b7 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/CombatMathTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/CombatMathTests.cs @@ -35,9 +35,7 @@ internal static class CombatMathTests r.Add("target range: closest first, then the one in front", ScanOrder); r.Add("target range: dead, unattackable, never-attack and spell projectiles are skipped", ScanFilters); - r.KnownFailure("damage text: a monster hitting our body part isn't our damage", - "TryParseOutgoingDamage only rejects \"you for\"; a hit like 'Olthoi Swarm Harvester blisters your lower leg for 12 points of acid damage!' is counted as a hit by us while casting, which skews the Damage tab averages and the kill-shot prediction (not fixed on any branch)", - BodyPartHitIsNotOurs); + r.Add("damage text: a monster hitting our body part isn't our damage", BodyPartHitIsNotOurs); // was a known failure; fixed by feature/warchain-fix (the line must start with "You") r.Add("weapon choice: a weapon the character no longer has is skipped", WeaponMissingSkipped); // was a known failure; fixed by 996b2a5 } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs index c58f90f..87f2a00 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs @@ -50,6 +50,7 @@ internal static class LootCorpseTests r.Add("corpse close: an engine without CloseContainer leaves it to the next open (no close)", FinishedCorpseNotClosedOnOldEngine); r.Add("corpse close: an abandoned open corpse is closed once", AbandonedCorpseClosed); r.Add("corpse close: stopping the macro mid-loot closes the open corpse, not marked completed", MacroStopClosesCorpse); + r.Add("loot pacing: a pickup waits for the last bend-down, and no retry is timed while it plays", PickupWaitsForAnimation); } // ── World set-up ────────────────────────────────────────────────────────── @@ -440,4 +441,58 @@ internal static class LootCorpseTests bot.Call("CloseOpenCorpseOnMacroStop"); Check.Eq(FakeHost.Closes.Count, 1, "a stop with no corpse open closes nothing"); } + + // 2026-10-07, Drakkon: picking up an item plays a bend-down, and the engine holds queued + // moves until it ends (about 2.2 s). RynthAi retried every 0.5 s from the send and gave up + // after 3 tries, so items were skipped while their first move had not even gone out. + private static void PickupWaitsForAnimation() + { + BaseWorld(corpsePositioned: true); + FakeHost.ServerGates = true; // GetCastBusyState + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.Cache.OnCreateObject(Corpse); + bot.Cache.Tick(); + bot.Tick(BotActivity.Looting); + Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened"); + + // The last pickup is still animating when the corpse's contents arrive. + FakeHost.CastBusy = 1; + bot.Cache.OnCreateObject(Gem); + bot.Cache.Tick(); + bot.P.OnViewObjectContents(Corpse); + TickFor(bot, 500); + Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "no pickup sent while the character animates"); + + FakeHost.CastBusy = 0; + for (int i = 0; i < 100 && !FakeHost.ExternalMoves.Any(m => m.Id == Gem); i++) + { + bot.Tick(BotActivity.Looting); + Thread.Sleep(10); + } + Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "the pickup goes out once the character is still"); + + // Its own bend-down plays for longer than 3 retry windows: no retry, no give-up. + FakeHost.CastBusy = 1; + TickFor(bot, 1800); + Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "no retry while the pickup animates"); + Check.False(FakeHost.Logs.Any(l => l.Contains("pickup failed")), "the item is not given up on"); + + // Still again and the item still on the corpse: the retry window starts now. + FakeHost.CastBusy = 0; + TickFor(bot, 250); + Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "the retry window counts from when the character is still"); + TickFor(bot, 500); + Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 2, "then one retry"); + } + + private static void TickFor(Bot bot, int ms) + { + long end = Environment.TickCount64 + ms; + while (Environment.TickCount64 < end) + { + bot.Tick(BotActivity.Looting); + Thread.Sleep(10); + } + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MultiTargetTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MultiTargetTests.cs new file mode 100644 index 0000000..4a1e263 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MultiTargetTests.cs @@ -0,0 +1,207 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.CreatureData; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// One spell, several monsters: rings, walls, blasts and chain spells (Conquest). Each monster the +// spell hurts gets its own damage line naming it, the server sends health only for the selected +// target, and a kill notice names the monster that died. These tests drive CombatManager with +// those lines on the fake host: every line goes to the monster it names (never to the fight +// target), the other monsters get a health estimate, and kill notices from one cast keep the scan +// off each monster that died without dropping a fight target that is still alive. +internal static class MultiTargetTests +{ + private const uint Player = 0x50000C01; + private const uint Lb = 0xA9B40000; + private const uint SkulkerWcid = 1001, MosswartWcid = 1002; + + public static void Register(Runner r) + { + r.Add("damage text: the victim's name comes with the amount", VictimNames); + r.Add("multi-target: each damage line goes to the monster it names", LinesGoToTheirMonsters); + r.Add("multi-target: same-named monsters in one volley are told apart", SameNameVolley); + r.Add("multi-target: other targets get a health estimate, the server's number wins", HealthEstimates); + r.Add("multi-target: several kills from one cast keep the live fight target", KillsFromOneCast); + r.Add("multi-target: the fight target's own kill notice still drops it", FightTargetKill); + } + + // ── The parser ─────────────────────────────────────────────────────────── + + private static string? Victim(string text) => CombatText.TryParseOutgoingHit(text, out string v, out _) ? v : null; + + private static void VictimNames() + { + Check.Eq(Victim("You blast Drudge Skulker for 153 points with Whirling Blade VII."), "Drudge Skulker", "ACE war magic"); + Check.Eq(Victim("You scorch the Mosswart Worshipper for 1,234 points of fire damage!"), "Mosswart Worshipper", "retail, 'the' dropped"); + Check.Eq(Victim("Critical hit! Sneak Attack! You gore Olthoi Slasher for 1638 points with Force Arc VII."), "Olthoi Slasher", "two prefixes"); + Check.Eq(Victim("Overpower! You frost Tusker Guard for 40 points with Frost Bolt VI."), "Tusker Guard", "Overpower prefix"); + Check.Eq(Victim("You slash Banderling Scout for 12 points of slashing damage!"), "Banderling Scout", "melee"); + Check.Eq(Victim("Olthoi Swarm Harvester blisters your lower leg for 12 points of acid damage!"), null, "a monster's hit on us"); + Check.Eq(Victim("You drain 45 points of mana from Drudge Skulker."), null, "a drain"); + Check.Eq(Victim("You heal yourself for 64 points."), null, "a heal"); + Check.Eq(CombatText.CorpseOwnerName("Corpse of Drudge Skulker"), "Drudge Skulker", "corpse name"); + Check.Eq(CombatText.CorpseOwnerName("Drudge Skulker"), null, "not a corpse"); + } + + // ── The rig ────────────────────────────────────────────────────────────── + + private sealed class Rig + { + public readonly LegacyUiSettings S = new() { MonsterRange = 30 }; + public readonly MonsterDamageStore Store = new(); + public CombatManager C = null!; + public RynthCore.Plugin.RynthAi.WorldObjectCache Cache = null!; + private readonly List _ids = new(); + private uint _next = 0x80000301; + + public Rig() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; // installs GetCurrentCombatMode + FakeHost.CombatModeValue = CombatMode.Magic; + FakeHost.Names[Player] = "Me"; + FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f); + FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f); + } + + public uint Mob(string name, uint wcid, float north, float east) + { + uint id = _next++; + FakeHost.Names[id] = name; + FakeHost.Positions[id] = (Lb | 0x1C, 96f + east, 96f + north, 0f); + FakeHost.ItemTypes[id] = 0x10; + FakeHost.Wcids[id] = wcid; + _ids.Add(id); + return id; + } + + public void Build(uint fightTarget, IReadOnlyDictionary? health = null) + { + var host = FakeHost.Create(); + Cache = FakeHost.MakeCache(host, Player, _ids, health); + C = new CombatManager(host, S, Cache); + C.SetPlayerId(Player); + C.SetDamageStores(null, Store); + C.EngageForTest(unchecked((int)fightTarget)); + } + + public float Hp(uint id) => Cache.GetHealthRatio(unchecked((int)id)); + + /// Learned non-crit average damage per monster type (the Damage tab's rows). + public Dictionary Learned() + => Store.Snapshot().GroupBy(r => r.Wcid) + .ToDictionary(g => g.Key, g => (g.First().AvgDamage, g.Sum(r => r.DmgSamples))); + } + + // ── The tests ──────────────────────────────────────────────────────────── + + private static void LinesGoToTheirMonsters() + { + var rig = new Rig(); + uint skulker = rig.Mob("Drudge Skulker", SkulkerWcid, 5, 0); + uint moss = rig.Mob("Mosswart Worshipper", MosswartWcid, 6, 2); + rig.Build(skulker); + + rig.C.HandleChatForDamage("You blast Drudge Skulker for 100 points with Lightning Chain VI."); + rig.C.HandleChatForDamage("You blast Mosswart Worshipper for 40 points with Lightning Chain VI."); + + var learned = rig.Learned(); + Check.True(learned.ContainsKey(MosswartWcid), "the Mosswart's hit is learned against the Mosswart"); + Check.Near(learned.GetValueOrDefault(MosswartWcid).Avg, 40, 1e-6, "the Mosswart's damage is its own 40"); + Check.Near(learned.GetValueOrDefault(SkulkerWcid).Avg, 100, 1e-6, "the Skulker keeps only its own 100 (not 140, not 70)"); + Check.Eq(learned.GetValueOrDefault(SkulkerWcid).Samples, 1, "one hit learned for the Skulker"); + Check.True(rig.Hp(moss) > 0f && rig.Hp(moss) < 1f, $"the Mosswart is marked hurt ({rig.Hp(moss):0.00})"); + Check.True(rig.Cache.IsHealthEstimated(unchecked((int)moss)), "and its health is our estimate"); + Check.True(!rig.Cache.IsHealthEstimated(unchecked((int)skulker)), "the fight target gets no estimate (the server sends its health)"); + } + + private static void SameNameVolley() + { + var rig = new Rig(); + uint target = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 5, 0); + uint near = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 7, 0); + uint far = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 20, 0); + rig.Build(target); + rig.Store.SetManualHp(SkulkerWcid, 200); + + // One chain: the target, then the nearest other soldier, then the next. + rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Lightning Chain VI."); + rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 50 points with Lightning Chain VI."); + rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 20 points with Lightning Chain VI."); + + Check.Near(rig.Hp(near), 0.75, 1e-4, "second line -> the nearest other soldier (200 hp, -50)"); + Check.Near(rig.Hp(far), 0.90, 1e-4, "third line -> the next one (-20)"); + Check.True(!rig.Cache.IsHealthEstimated(unchecked((int)target)), "the first line was the fight target's"); + } + + private static void HealthEstimates() + { + var rig = new Rig(); + uint target = rig.Mob("Drudge Skulker", SkulkerWcid, 5, 0); + uint moss = rig.Mob("Mosswart Worshipper", MosswartWcid, 6, 2); + rig.Build(target); + rig.Store.SetManualHp(MosswartWcid, 100); + int m = unchecked((int)moss); + + Check.Near(rig.Hp(moss), -1, 1e-6, "no health known before the hit"); + rig.C.HandleChatForDamage("You blast Mosswart Worshipper for 30 points with Flame Ring VI."); + Check.Near(rig.Hp(moss), 0.70, 1e-4, "100 hp, hit for 30 -> 0.70"); + System.Threading.Thread.Sleep(900); // next volley + rig.C.HandleChatForDamage("You blast Mosswart Worshipper for 500 points with Flame Ring VI."); + Check.Near(rig.Hp(moss), RynthCore.Plugin.RynthAi.WorldObjectCache.EstimatedHealthFloor, 1e-6, + "an estimate never reads dead (0): only the server says dead"); + rig.Cache.OnUpdateHealth(moss, 0.40f); + Check.Near(rig.Hp(moss), 0.40, 1e-6, "the server's number replaces the estimate"); + Check.True(!rig.Cache.IsHealthEstimated(m), "and it is no longer an estimate"); + rig.Cache.ApplyDamageEstimate(m, 0.0); + Check.Near(rig.Hp(moss), 0.40, 1e-6, "an unknown-max hit never raises a known value"); + } + + private static void KillsFromOneCast() + { + var rig = new Rig(); + uint target = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 5, 0); + uint twin = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 7, 0); + uint moss = rig.Mob("Mosswart Worshipper", MosswartWcid, 6, 2); + rig.Build(target); + + // A cast hits all three; the server has the fight target at 60%. + rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Flame Ring VI."); + rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Flame Ring VI."); + rig.C.HandleChatForDamage("You blast Mosswart Worshipper for 100 points with Flame Ring VI."); + rig.Cache.OnUpdateHealth(target, 0.60f); + + // The next cast kills the twin and the Mosswart (one notice each), not the target. + rig.C.OnKillNotification("Olthoi Swarm Soldier's death is preceded by a sharp, stabbing pain!"); + rig.C.OnKillNotification("You slay Mosswart Worshipper viciously enough to impart death several times over!"); + + Check.True(rig.C.IsKillSuppressed(unchecked((int)twin)), "the same-named twin is the one that died"); + Check.True(rig.C.IsKillSuppressed(unchecked((int)moss)), "the Mosswart died"); + Check.True(!rig.C.IsKillSuppressed(unchecked((int)target)), "the live fight target is not suppressed"); + Check.Eq(rig.C.activeTargetId, unchecked((int)target), "and is still the target"); + } + + private static void FightTargetKill() + { + var rig = new Rig(); + uint target = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 5, 0); + uint twin = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 7, 0); + rig.Build(target); + + rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Flame Ring VI."); + rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Flame Ring VI."); + rig.Cache.OnUpdateHealth(target, 0f); // ACE: the 0 comes with the lethal hit, before the notice + rig.C.OnKillNotification("Olthoi Swarm Soldier's death is preceded by a sharp, stabbing pain!"); + + Check.True(rig.C.IsKillSuppressed(unchecked((int)target)), "the fight target died and is suppressed"); + Check.Eq(rig.C.activeTargetId, 0, "and dropped"); + Check.True(!rig.C.IsKillSuppressed(unchecked((int)twin)), "the twin is untouched"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs index d73ea3c..bbbae57 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs @@ -49,6 +49,10 @@ internal static class UseRefusalTests r.Add("move hold: off unless the plugin opts in (RynthNav, RynthLua unchanged)", MoveHoldOptIn); r.Add("idle peace: Combat's idle peace swap waits while looting has work", IdlePeaceHeldWhileLooting); r.Add("idle peace: looting has work = a corpse claimed, a corpse open, a corpse in range, or a use in flight", LootHoldsIdlePeaceInputs); + r.Add("use check jump: one jump per back-off, before the probe; none while normal or during the back-off", WatchProbeJump); + r.Add("use check jump (looting): the clean stop jumps (TapJump, not JumpNonAutonomous), the retry waits the pause, an open after it is logged as cleared", LootingStallJumpClears); + r.Add("use check jump (looting): still stuck after the jump -> back-off; the probe goes out only after a jump and the pause", LootingStallJumpBeforeProbe); + r.Add("use check jump: no jump while the server still owes an answer to a cast (a jump would fail it)", NoJumpWhilePacerOutstanding); } // ── UseRefusalWatch alone ───────────────────────────────────────────────── @@ -536,4 +540,154 @@ internal static class UseRefusalTests }); Check.False(Holds(), "all clear: no hold"); } + + // ── The jump (2026-10-06 afternoon) ─────────────────────────────────────── + // On ACE the player's jump (Player.HandleActionJump) is the one in-world action that empties the + // server's animation queues (the stuck state); the use check jumps at the clean stop and before + // each probe. + + private static void WatchProbeJump() + { + var r = new Rig(); + int a = unchecked((int)CorpseA), b = unchecked((int)CorpseB); + Check.False(r.W.TakeProbeJump(r.T), "normal: no jump"); + r.RefusedOpen(a); r.RefusedOpen(a); r.RefusedOpen(a); + Check.False(r.W.TakeProbeJump(r.T), "retrying: no probe jump (the clean stop jumps itself)"); + r.RefusedOpen(a); + Check.Eq(r.RefusedOpen(b), UseRefusalWatch.Verdict.Stuck, "stuck"); + Check.False(r.W.TakeProbeJump(r.T), "during the back-off: no jump"); + r.T = r.W.BackoffUntil; + Check.True(r.W.TakeProbeJump(r.T), "the back-off is over: jump before the probe"); + Check.False(r.W.TakeProbeJump(r.T + 100), "once"); + Check.Eq(r.RefusedOpen(b), UseRefusalWatch.Verdict.StillStuck, "the probe refused"); + Check.False(r.W.TakeProbeJump(r.T), "a new back-off: no jump yet"); + r.T = r.W.BackoffUntil; + Check.True(r.W.TakeProbeJump(r.T), "again once the longer back-off is over"); + r.W.OnOpened(r.T); + Check.False(r.W.TakeProbeJump(r.T + UseRefusalWatch.MaxBackoffMs), "after an open: never"); + } + + /// The 14:29 server: every open is answered 60 ms later and nothing opens, until the + /// first open after a jump (when ). + private static void StallServer(Bot bot, Func now, Action advance, bool jumpClears, int maxSteps, Func until) + { + long answerAt = 0; uint answerFor = 0; + for (int steps = 0; steps < maxSteps && !until(); steps++) + { + int uses = FakeHost.Uses.Count; + bot.Tick(BotActivity.Looting); + if (FakeHost.Uses.Count > uses) { answerAt = now() + 60; answerFor = FakeHost.Uses.Last(); } + advance(100); + if (answerAt != 0 && now() >= answerAt) + { + FakeHost.UseDone(0); + if (jumpClears && FakeHost.TapJumps > 0) + bot.P.OnViewObjectContents(answerFor); + answerAt = 0; + } + } + } + + private static void LootingStallJumpClears() + { + World(); + FakeHost.TapJumpCalls = true; + var host = FakeHost.Create(Player); + var bot = new Bot(host); + WithClock((now, advance) => + { + int usesAtJump = -1; long jumpAt = 0; + StallServer(bot, now, advance, jumpClears: false, maxSteps: 400, until: () => + { + if (FakeHost.TapJumps > 0 && usesAtJump < 0) { usesAtJump = FakeHost.Uses.Count; jumpAt = now(); } + return usesAtJump >= 0; + }); + Check.Eq(FakeHost.TapJumps, 1, "the clean stop jumps once"); + Check.Eq(FakeHost.Jumps, 0, "with the keyboard jump, not JumpNonAutonomous (ACE ignores 0xF7C9)"); + Check.True(FakeHost.Logs.Any(l => l.Contains("one clean stop, a jump")), "logged"); + Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: jump for the retry")), "the jump is logged"); + Check.False(FakeHost.Logs.Any(l => l.Contains("Use check: facing")), "no facing turn when it jumps"); + + // The retry waits for the pause, then the server (cleared by the jump) opens it. + long retryAt = 0; + StallServer(bot, now, advance, jumpClears: true, maxSteps: 100, until: () => + { + if (retryAt == 0 && FakeHost.Uses.Count > usesAtJump) retryAt = now(); + return bot.Get("_openedContainerId") != 0; + }); + Check.True(retryAt != 0, "a retry went out"); + Check.True(retryAt - jumpAt >= UseRefusalWatch.CleanStopPauseMs, $"after the pause ({retryAt - jumpAt} ms)"); + Check.True(FakeHost.Logs.Any(l => l.Contains("after the use check's jump - the jump cleared")), "the open after the jump is logged as the fix"); + Check.Eq(ChatCount(StuckLine), 0, "the player is never told to relog"); + Check.Eq(bot.Get("_useRefusals").State, UseRefusalWatch.Phase.Normal, "back to normal"); + }); + } + + private static void LootingStallJumpBeforeProbe() + { + World(); + FakeHost.TapJumpCalls = true; + var host = FakeHost.Create(Player); + var bot = new Bot(host); + WithClock((now, advance) => + { + StallServer(bot, now, advance, jumpClears: false, maxSteps: 600, until: () => ChatCount(StuckLine) > 0); + Check.Eq(ChatCount(StuckLine), 1, "the jump didn't help here: the player is told once"); + Check.Eq(FakeHost.TapJumps, 1, "one jump so far (the clean stop)"); + Check.True(FakeHost.Logs.Any(l => l.Contains("the clean stop, the jump and retry didn't help")), "the verdict says the jump was tried"); + + var w = bot.Get("_useRefusals"); + int usesAtStuck = FakeHost.Uses.Count; + for (int i = 0; i < 2400; i++) { bot.Tick(BotActivity.Looting); advance(100); } // 4 minutes + Check.Eq(FakeHost.TapJumps, 1, "no jump during the back-off"); + Check.Eq(FakeHost.Uses.Count, usesAtStuck, "no opens during the back-off"); + + long probeJumpAt = 0; + for (int i = 0; i < 700 && FakeHost.Uses.Count == usesAtStuck; i++) + { + bot.Tick(BotActivity.Looting); + if (probeJumpAt == 0 && FakeHost.TapJumps == 2) probeJumpAt = now(); + advance(100); + } + Check.Eq(FakeHost.TapJumps, 2, "a jump before the probe"); + Check.Eq(FakeHost.Uses.Count, usesAtStuck + 1, "then the probe"); + Check.True(now() - 100 - probeJumpAt >= UseRefusalWatch.CleanStopPauseMs, "the probe waits the pause after the jump"); + Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: jump before the probe")), "logged"); + + // The jump cleared it: the probe opens. + bot.P.OnViewObjectContents(FakeHost.Uses.Last()); + Check.Eq(ChatCount("Objects open again"), 1, "the player is told uses work again"); + Check.True(FakeHost.Logs.Any(l => l.Contains("the jump cleared")), "and the log says the jump did it"); + Check.False(w.HoldsOpens(now()), "looting is back on"); + }); + } + + private static void NoJumpWhilePacerOutstanding() + { + World(); + FakeHost.TapJumpCalls = true; + var host = FakeHost.Create(Player); + var bot = new Bot(host); + long t = 10_000_000; + ActionPacer.Reset(); + ActionPacer.Enabled = true; + ActionPacer.NowMs = () => t; + try + { + ActionPacer.Begin(host, PacedKind.Cast, 0, "Revitalize Self VI", "Buff", FakeHost.UseDoneSeq); + Check.False((bool)bot.Call("TryUseCheckJump", t, "test")!, "no jump while the cast is unanswered"); + Check.Eq(FakeHost.TapJumps, 0, "nothing sent"); + Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: no jump test - the server still owes an answer")), "logged"); + FakeHost.UseDone(0); + t += 50; + Check.True((bool)bot.Call("TryUseCheckJump", t, "test")!, "answered: the jump goes"); + Check.Eq(FakeHost.TapJumps, 1, "one jump"); + } + finally + { + ActionPacer.Enabled = false; + ActionPacer.Reset(); + ActionPacer.NowMs = () => Environment.TickCount64; + } + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs index c9d9d44..2e70afc 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs @@ -22,6 +22,8 @@ internal static class VitalsTests { r.Add("vitals: Stamina to Health follows its own health line and stamina floor", StaminaToHealthThresholds); 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: 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); @@ -210,6 +212,75 @@ internal static class VitalsTests return cast; } + // Tom, 2026-10-06: a melee character should drink its listed stamina potions before Revitalize + // (which means switching the weapon for the wand and back). + private static void StaminaPotionFirst() + { + const uint Tincture = 0x80001234; + foreach (int mode in new[] { CombatMode.Melee, CombatMode.Magic }) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = mode; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + FakeHost.Names[Tincture] = "Stamina Tincture"; + 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)Tincture), 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[] { Tincture })); + Check.True(b.CheckVitals(), $"mode {mode}: stamina 20% acts"); + bool drank = FakeHost.Uses.Contains(Tincture); + if (mode == CombatMode.Melee) + { + Check.True(drank, "melee: the tincture is drunk"); + Check.Eq(FakeHost.Casts.Count, 0, "melee: no Revitalize (no wand switch)"); + } + else + { + Check.False(drank, "caster in Magic stance: no potion first"); + Check.True(FakeHost.Casts.Count > 0, "caster: Revitalize is cast"); + } + } + } + + // Tom, 2026-10-06: one Revitalize often doesn't recover enough stamina. + private static void RestamTo() + { + var s = new LegacyUiSettings { RestamAt = 30, RestamTo = 0, TopOffStam = 95 }; + bool run = false; int casts = 0; + Check.Eq(BuffManager.StaminaLine(true, 25, s, ref run, ref casts), 30, "off: Re-stam At"); + Check.Eq(BuffManager.StaminaLine(true, 40, s, ref run, ref casts), 30, "off: at 40% no recharge"); + + s.RestamTo = 70; + Check.Eq(BuffManager.StaminaLine(true, 40, s, ref run, ref casts), 30, "above Re-stam At with no recharge started: nothing new"); + Check.Eq(BuffManager.StaminaLine(true, 25, s, ref run, ref casts), 70, "under Re-stam At: recharge to 70"); + casts++; + Check.Eq(BuffManager.StaminaLine(true, 45, s, ref run, ref casts), 70, "one cast got it to 45%: still recharging (the second cast)"); + casts++; + Check.Eq(BuffManager.StaminaLine(true, 72, s, ref run, ref casts), 30, "reached 70: done"); + Check.False(run, "the recharge ended"); + + // A recharge that never gains stops after the cap. + Check.Eq(BuffManager.StaminaLine(true, 20, s, ref run, ref casts), 70, "new recharge"); + casts = BuffManager.RestamRunMaxCasts; + Check.Eq(BuffManager.StaminaLine(true, 35, s, ref run, ref casts), 30, "cap reached above Re-stam At: back to Re-stam At"); + + // Out of combat the top-off line applies, as before. + Check.Eq(BuffManager.StaminaLine(false, 50, s, ref run, ref casts), 95, "idle: Top Stam"); + s.RestamTo = 20; + Check.Eq(BuffManager.StaminaLine(true, 25, s, ref run, ref casts), 30, "Re-stam To not above Re-stam At: ignored"); + } + private static void StaminaToHealthThresholds() { // Defaults: today's behaviour (30% health, stamina over 20%). diff --git a/Tools/RynthCore.TrackerSessionTests/KillCounterTests.cs b/Tools/RynthCore.TrackerSessionTests/KillCounterTests.cs new file mode 100644 index 0000000..09d48cd --- /dev/null +++ b/Tools/RynthCore.TrackerSessionTests/KillCounterTests.cs @@ -0,0 +1,131 @@ +using System; +using RynthCore.Plugin.RynthTracker; +using RynthCore.Plugin.Shared; + +namespace RynthCore.TrackerSessionTests; + +// KillCounter (RynthTracker 0.3.0): one cast, several kills. The events are what the client +// sees, in the order it sees them: our damage lines (one per monster a spell hurt), the +// server's kill notices, and corpses ("Corpse of X") a few seconds later. +internal static partial class Program +{ + private static readonly DateTime T0 = new(2026, 10, 3, 2, 0, 0, DateTimeKind.Utc); + private static DateTime At(double seconds) => T0.AddSeconds(seconds); + + private static void Hit(KillCounter k, string line, double t) + { + Check(CombatText.TryParseOutgoingHit(line, out string victim, out _), $"parses: {line}"); + k.OnHit(victim, At(t)); + } + + private static void TestKillCounter() + { + Console.WriteLine("-- kill counter"); + + // ACE ring: every kill gets its notice; the corpses that follow add nothing. + { + var k = new KillCounter(); + Hit(k, "You blast Drudge Skulker for 80 points with Flame Ring VI.", 0.0); + Hit(k, "You blast Drudge Slinker for 75 points with Flame Ring VI.", 0.1); + Hit(k, "You blast Mosswart Worshipper for 70 points with Flame Ring VI.", 0.2); + k.OnKillNotice("Drudge Skulker's seared corpse smolders before you!", At(2.0)); + k.OnKillNotice("You bring Drudge Slinker to a fiery end!", At(2.1)); + k.OnKillNotice("Mosswart Worshipper is incinerated by your assault!", At(2.2)); + Eq(k.OnCorpse("Drudge Skulker", At(5.0)), KillCounter.CorpseResult.Notified, "ring: corpse 1 matches its notice"); + Eq(k.OnCorpse("Drudge Slinker", At(5.1)), KillCounter.CorpseResult.Notified, "ring: corpse 2 matches its notice"); + Eq(k.OnCorpse("Mosswart Worshipper", At(5.2)), KillCounter.CorpseResult.Notified, "ring: corpse 3 matches its notice"); + Eq(k.Kills, 3, "ring: three kills, none counted twice"); + } + + // Conquest chain: the primary's kill has a notice, the extra targets' don't. + { + var k = new KillCounter(); + Hit(k, "You blast Drudge Skulker for 120 points with Lightning Chain VI.", 0.0); + Hit(k, "You blast Drudge Slinker for 60 points with Lightning Chain VI.", 0.2); + Hit(k, "You blast Mosswart Worshipper for 30 points with Lightning Chain VI.", 0.4); + k.OnKillNotice("You smite Drudge Skulker mightily!", At(2.0)); // the primary + Hit(k, "You blast Mosswart Worshipper for 30 points with Lightning Chain VI.", 2.2); + // the Slinker died on that cast with no line and no notice + Eq(k.OnCorpse("Drudge Skulker", At(5.0)), KillCounter.CorpseResult.Notified, "chain: the primary's corpse is its notice's"); + Eq(k.OnCorpse("Drudge Slinker", At(5.1)), KillCounter.CorpseResult.Counted, "chain: the silent extra kill counts from its corpse"); + Hit(k, "You blast Mosswart Worshipper for 30 points with Lightning Chain VI.", 6.0); + Eq(k.OnCorpse("Mosswart Worshipper", At(9.0)), KillCounter.CorpseResult.Counted, "chain: the last extra target too"); + Eq(k.Kills, 3, "chain: three kills from the chain fight"); + Eq(k.CorpseKills, 2, "chain: two of them found by their corpse"); + } + + // A swarm: same-named monsters, two die from one cast, one notice. + { + var k = new KillCounter(); + Hit(k, "You blast Olthoi Swarm Soldier for 100 points with Lightning Chain VI.", 0.0); + Hit(k, "You blast Olthoi Swarm Soldier for 100 points with Lightning Chain VI.", 0.1); + k.OnKillNotice("Olthoi Swarm Soldier's death is preceded by a sharp, stabbing pain!", At(1.5)); + Eq(k.OnCorpse("Olthoi Swarm Soldier", At(4.0)), KillCounter.CorpseResult.Notified, "swarm: first corpse takes the notice"); + Eq(k.OnCorpse("Olthoi Swarm Soldier", At(4.1)), KillCounter.CorpseResult.Counted, "swarm: second corpse counts"); + Eq(k.OnCorpse("Olthoi Swarm Soldier", At(4.2)), KillCounter.CorpseResult.HitNotCounted, "swarm: never more corpses than the volley hit"); + Eq(k.Kills, 2, "swarm: two kills"); + } + + // The primary's kill notice and an extra target's line in one volley, same name: the + // notice stands for the primary, so the silent twin still counts from its corpse. + { + var k = new KillCounter(); + Hit(k, "You blast Olthoi Swarm Soldier for 100 points with Lightning Chain VI.", 0.0); // earlier cast, primary + k.OnKillNotice("You slay Olthoi Swarm Soldier viciously enough to impart death several times over!", At(2.0)); + Hit(k, "You blast Olthoi Swarm Soldier for 60 points with Lightning Chain VI.", 2.1); // the twin, same cast + Eq(k.OnCorpse("Olthoi Swarm Soldier", At(5.0)), KillCounter.CorpseResult.Notified, "notice + twin: primary's corpse"); + Hit(k, "You blast Olthoi Swarm Soldier for 60 points with Lightning Chain VI.", 5.5); // a lone hit later on the twin + Eq(k.OnCorpse("Olthoi Swarm Soldier", At(8.0)), KillCounter.CorpseResult.Counted, "notice + twin: the twin counts"); + Eq(k.Kills, 2, "notice + twin: two kills"); + } + + // Several casts at the same two monsters are still two monsters (max, not sum). + { + var k = new KillCounter(); + for (int cast = 0; cast < 4; cast++) + { + Hit(k, "You blast Drudge Skulker for 10 points with Flame Ring VI.", cast * 2.0); + Hit(k, "You blast Drudge Skulker for 10 points with Flame Ring VI.", cast * 2.0 + 0.1); + } + Eq(k.OnCorpse("Drudge Skulker", At(9.0)), KillCounter.CorpseResult.Counted, "repeat casts: first corpse"); + Eq(k.OnCorpse("Drudge Skulker", At(9.1)), KillCounter.CorpseResult.Counted, "repeat casts: second corpse"); + Eq(k.OnCorpse("Drudge Skulker", At(9.2)), KillCounter.CorpseResult.HitNotCounted, "repeat casts: not a third"); + } + + // Single-target fighting: a corpse with no notice is someone else's kill, as before. + { + var k = new KillCounter(); + Hit(k, "You slash Banderling Scout for 12 points of slashing damage!", 0.0); + Hit(k, "You slash Banderling Scout for 14 points of slashing damage!", 1.5); + Eq(k.OnCorpse("Banderling Scout", At(4.0)), KillCounter.CorpseResult.HitNotCounted, "single-target: not counted without a notice"); + Eq(k.OnCorpse("Tusker Guard", At(4.0)), KillCounter.CorpseResult.NotOurs, "a corpse we never hit"); + Eq(k.Kills, 0, "single-target: no kills"); + } + + // Lines a second apart are separate casts (a melee swing each), not one volley. + { + var k = new KillCounter(); + Hit(k, "You slash Banderling Scout for 12 points of slashing damage!", 0.0); + Hit(k, "You slash Banderling Guard for 14 points of slashing damage!", 1.0); + Eq(k.OnCorpse("Banderling Guard", At(3.0)), KillCounter.CorpseResult.HitNotCounted, "a second apart is not multi-target"); + } + + // Expiry: a multi-target hit stops vouching for a corpse after TokenLifeMs. + { + var k = new KillCounter(); + Hit(k, "You blast Drudge Skulker for 10 points with Flame Ring VI.", 0.0); + Hit(k, "You blast Drudge Slinker for 10 points with Flame Ring VI.", 0.1); + Eq(k.OnCorpse("Drudge Slinker", At(0.1 + KillCounter.TokenLifeMs / 1000.0 + 1)), KillCounter.CorpseResult.NotOurs, "an old hit doesn't count"); + } + + // A notice waits NoticeLifeMs for its corpse, then is forgotten (the kill stays counted). + { + var k = new KillCounter(); + k.OnKillNotice("You smite Drudge Skulker mightily!", At(0)); + Eq(k.OnCorpse("Drudge Skulker", At(KillCounter.NoticeLifeMs / 1000.0 + 1)), KillCounter.CorpseResult.NotOurs, "an old notice is gone"); + Eq(k.Kills, 1, "the notice's kill stays counted"); + k.Reset(); + Eq(k.Kills, 0, "reset clears the count"); + } + } +} diff --git a/Tools/RynthCore.TrackerSessionTests/Program.cs b/Tools/RynthCore.TrackerSessionTests/Program.cs index 0713fd5..642541f 100644 --- a/Tools/RynthCore.TrackerSessionTests/Program.cs +++ b/Tools/RynthCore.TrackerSessionTests/Program.cs @@ -11,7 +11,7 @@ namespace RynthCore.TrackerSessionTests; // Self-contained; fails on zero assertions. // // Run: dotnet run -c Release (exit 0 = pass, 1 = fail) -internal static class Program +internal static partial class Program { private static int _asserts; private static int _fails; @@ -45,6 +45,7 @@ internal static class Program TestFileNames(); TestFiles(); TestCleanup(); + TestKillCounter(); Console.WriteLine($"\n{_asserts} assertions, {_fails} failed."); if (_asserts == 0) { Console.WriteLine("ABORT: zero assertions ran."); return 1; } diff --git a/Tools/RynthCore.TrackerSessionTests/RynthCore.TrackerSessionTests.csproj b/Tools/RynthCore.TrackerSessionTests/RynthCore.TrackerSessionTests.csproj index 130092c..8a415b8 100644 --- a/Tools/RynthCore.TrackerSessionTests/RynthCore.TrackerSessionTests.csproj +++ b/Tools/RynthCore.TrackerSessionTests/RynthCore.TrackerSessionTests.csproj @@ -17,6 +17,8 @@ + + From e5950ddb04b5e0f7c42ccfdbbc7c7f5498909ae8 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Wed, 7 Oct 2026 13:13:36 -0400 Subject: [PATCH 5/6] Snapshot for release 2026.10.7.2 (internal caaf7ea) --- .../Combat/AcStubs.cs | 19 +++++-- .../Combat/WorldObjectCache.cs | 54 ++++++++++++++++++ .../Loot/LootEvaluator.cs | 2 +- .../Loot/VTankLootEvaluator.cs | 34 ++++++++--- Shared/RynthCore.LootSdk/AcGameEnums.cs | 11 ++-- .../RynthCore.LootSdk/Editing/LootRuleText.cs | 35 +++++++++--- Tools/RynthCore.LootEditor/TypedEditors.cs | 10 +--- .../Tests/NativeLootTests.cs | 35 +++++++++++- .../Tests/VTankLootTests.cs | 56 ++++++++++++++++++- 9 files changed, 216 insertions(+), 40 deletions(-) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs index c9ff602..562b673 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs @@ -49,7 +49,9 @@ public enum StringValueKey /// /// STypeFloat keys used with TryGetObjectDoubleProperty / WorldObjectCache.GetDoubleProperty. -/// Values match Chorizite's STypeFloat sequential enum. +/// Values match ACE's PropertyFloat and Chorizite's STypeFloat (UNDEF = 0). WeaponOffense and +/// DamageMod were 61/62 until 2026-10-05 (61 is EconRecoveryInterval), so a native "damage +/// percent" loot rule read the weapon's attack mod; PowerLevel/AccuracyLevel were 86/87. /// public enum DoubleValueKey { @@ -59,10 +61,10 @@ public enum DoubleValueKey MaximumVelocity = 26, // missile launcher launch speed (m/s); known once appraised WeaponDefense = 29, UseRadius = 54, - WeaponOffense = 61, - DamageMod = 62, - PowerLevel = 86, - AccuracyLevel = 87, + WeaponOffense = 62, + DamageMod = 63, + PowerLevel = 92, + AccuracyLevel = 93, } // ── Combat mode int constants (matches acclient.exe CM_Combat enum) ──────── @@ -123,6 +125,13 @@ public class WorldObject if (RynthCore.Loot.T11.T11Keys.IsVirtual(key)) return Loot.T11ItemSupport.VirtualValue(this, key, defaultValue); + // Decal's synthetic keys that are a plain int property (MaxDamage = Damage 44, Coverage = + // ClothingPriority 4, ...) read as that property, from the overlay or live. The icon and + // spell ones are data ids: WorldObjectCache.GetIntProperty answers them. + uint decalStype = WorldObjectCache.DecalIntStype(unchecked((uint)key)); + if (decalStype != 0) + return Values(unchecked((int)decalStype), defaultValue); + var o = Overlay; if (o != null) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs index 115b6d3..3c80162 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs @@ -1136,10 +1136,64 @@ public class WorldObjectCache uint uid = unchecked((uint)id); if (stype == DecalTypeKey) return _host.HasGetObjectWcid && _host.TryGetObjectWcid(uid, out uint wcid) ? unchecked((int)wcid) : defaultValue; + if ((stype & 0xFFFFFF00u) == DecalTypeKey) + return GetDecalLongKey(uid, stype, defaultValue); if (!_host.HasGetObjectIntProperty) return defaultValue; return _host.TryGetObjectIntProperty(uid, stype, out int v) ? v : defaultValue; } + /// + /// Decal's other synthetic LongValueKeys (0x0D000001-0x0D00002A, Decal.Adapter's numbering), + /// read as the game property each one is. VTank profiles use them: LootSnobV4 has 336 rules on + /// MaxDamage and 109 on Coverage. They were read as STypeInt ids, which no object has, so + /// they were always 0 and those rules never matched (until 2026-10-07). Icons are the + /// portal.dat index without its 0x06000000 base, as Decal gives them. Keys with no property + /// here (landblock, monarch, physics flags, spell counts) answer the default. + /// + private int GetDecalLongKey(uint uid, uint key, int defaultValue) + { + switch (key) + { + case 0x0D000001: return DecalIcon(uid, 8, defaultValue); // Icon + case 0x0D000008: { uint s = GetDataIdProperty(unchecked((int)uid), 28); return s != 0 ? unchecked((int)s) : defaultValue; } // AssociatedSpell + case 0x0D000029: return DecalIcon(uid, 50, defaultValue); // IconOverlay + case 0x0D00002A: return DecalIcon(uid, 52, defaultValue); // IconUnderlay + } + uint stype = DecalIntStype(key); + if (stype == 0 || !_host.HasGetObjectIntProperty) return defaultValue; + return _host.TryGetObjectIntProperty(uid, stype, out int v) ? v : defaultValue; + } + + /// The STypeInt a Decal synthetic long key is, or 0 (not an int property). + public static uint DecalIntStype(uint key) => key switch + { + 0x0D000004 => 6, // ItemSlots -> ItemsCapacity + 0x0D000005 => 7, // PackSlots -> ContainersCapacity + 0x0D000006 => 12, // StackCount -> StackSize + 0x0D000007 => 11, // StackMax -> MaxStackSize + 0x0D00000B => 10, // WieldingSlot -> CurrentWieldedLocation + 0x0D00000D => 4, // Coverage -> ClothingPriority + 0x0D00000E => 9, // EquipableSlots -> ValidLocations + 0x0D00000F => 51, // EquipType -> CombatUse + 0x0D000010 => 18, // IconOutline -> UiEffects + 0x0D000011 => 50, // MissileType -> AmmoType + 0x0D000012 => 16, // UsageMask -> ItemUseable + 0x0D000014 => 152, // HookMask -> HookItemType + 0x0D000015 => 151, // HookType + 0x0D00001A => 1, // Category -> ItemType + 0x0D00001F => 49, // WeapSpeed -> WeaponTime + 0x0D000020 => 48, // EquipSkill -> WeaponSkill + 0x0D000021 => 45, // DamageType + 0x0D000022 => 44, // MaxDamage -> Damage (the appraisal's weapon profile) + _ => 0, + }; + + private int DecalIcon(uint uid, uint did, int defaultValue) + { + uint v = GetDataIdProperty(unchecked((int)uid), did); + return v != 0 ? unchecked((int)(v & 0x00FFFFFFu)) : defaultValue; + } + /// /// Read an STypeDID property (e.g. a scroll's Spell 28 from its CreateObject header). /// 0 if the API is unavailable or the property is not set. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEvaluator.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEvaluator.cs index 8e7c7ed..9439042 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEvaluator.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEvaluator.cs @@ -72,7 +72,7 @@ public static class LootEvaluator private static double EvalMinDamage(WorldObject item) { - int maxDamage = item.Values(54, 0); // STypeInt MAX_DAMAGE + int maxDamage = item.Values(44, 0); // Damage, the weapon profile's max (was 54, WeaponEncumbrance, until 2026-10-07) double variance = item.Values(DoubleValueKey.DamageVariance, 0.0); return maxDamage - variance * maxDamage; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs index 608f102..14573e3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs @@ -194,8 +194,8 @@ public static class VTankLootEvaluator VTankNodeTypes.StringValueMatch => MatchStringValue(item, d), VTankNodeTypes.LongValKeyLE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) <= val, VTankNodeTypes.LongValKeyGE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) >= val, - VTankNodeTypes.DoubleValKeyLE => Double(d) is var (val,key) && item.Values((DoubleValueKey)key, 0.0) <= val, - VTankNodeTypes.DoubleValKeyGE => Double(d) is var (val,key) && item.Values((DoubleValueKey)key, 0.0) >= val, + VTankNodeTypes.DoubleValKeyLE => Double(d) is var (val,key) && item.Values(FloatKey(key), 0.0) <= val, + VTankNodeTypes.DoubleValKeyGE => Double(d) is var (val,key) && item.Values(FloatKey(key), 0.0) >= val, VTankNodeTypes.DamagePercentGE => false, // VTank source returns false unconditionally VTankNodeTypes.ObjectClass => ScrollLearner.ClassMatches(item, ReadInt(d, 0)), // Scroll (42) also matches scroll Books VTankNodeTypes.SpellCountGE => ctx is null || ctx.GetItemSpellIds(itemId).Length >= ReadInt(d, 0), @@ -216,8 +216,8 @@ public static class VTankLootEvaluator VTankNodeTypes.BuffedMedianDamageGE => MatchBuffedMedianDamageGE(item, d), VTankNodeTypes.BuffedMissileDamageGE => MatchBuffedMissileDamageGE(item, d), VTankNodeTypes.BuffedLongValKeyGE => DoubleKey(d) is var (val,key) && item.Values((LongValueKey)key, 0) >= val, - VTankNodeTypes.BuffedDoubleValKeyGE => DoubleKey(d) is var (val,key) && item.Values((DoubleValueKey)key, 0.0) >= val, - VTankNodeTypes.CalcdBuffedTinkedDamageGE => item.Values(54, 0) >= ReadDouble(d, 0), + VTankNodeTypes.BuffedDoubleValKeyGE => DoubleKey(d) is var (val,key) && item.Values(FloatKey(key), 0.0) >= val, + VTankNodeTypes.CalcdBuffedTinkedDamageGE => item.Values(44, 0) >= ReadDouble(d, 0), VTankNodeTypes.TotalRatingsGE => MatchTotalRatingsGE(item, d), VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE => false, // not implemented VTankNodeTypes.DisabledRule => MatchDisabledRule(d), @@ -278,7 +278,7 @@ public static class VTankLootEvaluator private static bool MatchMinDamageGE(WorldObject item, IList d) { double threshold = ReadDouble(d, 0); - int maxDamage = item.Values(54, 0); + int maxDamage = item.Values(44, 0); // Damage: the weapon profile's max (54 is WeaponEncumbrance; until 2026-10-07) if (maxDamage == 0) return false; double variance = item.Values(DoubleValueKey.DamageVariance, 0.0); double minDamage = maxDamage - (variance * maxDamage); @@ -310,7 +310,7 @@ public static class VTankLootEvaluator private static bool MatchBuffedMedianDamageGE(WorldObject item, IList d) { double threshold = ReadDouble(d, 0); - int maxDamage = item.Values(54, 0); + int maxDamage = item.Values(44, 0); // Damage: the weapon profile's max (54 is WeaponEncumbrance; until 2026-10-07) if (maxDamage == 0) return false; double variance = item.Values(DoubleValueKey.DamageVariance, 0.0); double minDamage = maxDamage - (variance * maxDamage); @@ -320,7 +320,7 @@ public static class VTankLootEvaluator private static bool MatchBuffedMissileDamageGE(WorldObject item, IList d) { double threshold = ReadDouble(d, 0); - int maxDamage = item.Values(54, 0); + int maxDamage = item.Values(44, 0); // Damage: the weapon profile's max (54 is WeaponEncumbrance; until 2026-10-07) if (maxDamage == 0) return false; double elemBonus = item.Values((DoubleValueKey)152, 1.0); if (elemBonus < 1.0) elemBonus = 1.0; @@ -356,4 +356,24 @@ public static class VTankLootEvaluator private static (double Val, int Key) Double(IList d) => (ReadDouble(d, 0), ReadInt(d, 1)); // Buffed long/double helpers store value as double in slot 0 (matching VTank's "Read" of doubles). private static (double Val, int Key) DoubleKey(IList d) => (ReadDouble(d, 0), ReadInt(d, 1)); + + // A double key as the STypeFloat it reads. VTank files the appraisal's armor and weapon + // profiles under Decal's 0x0A0000xx keys (uTank2 LootPlugins.DoubleValueKey), which no + // object property has: read raw they were always 0, so LootSnob's "AttackBonus >=" rules + // never matched (until 2026-10-05). Range (0x0A00000D) and the physics keys stay unmapped. + private static DoubleValueKey FloatKey(int key) => unchecked((uint)key) switch + { + 0x0A000000 => (DoubleValueKey)13, // SlashProt → ArmorModVsSlash + 0x0A000001 => (DoubleValueKey)14, // PierceProt → ArmorModVsPierce + 0x0A000002 => (DoubleValueKey)15, // BludgeonProt → ArmorModVsBludgeon + 0x0A000003 => (DoubleValueKey)18, // AcidProt → ArmorModVsAcid + 0x0A000004 => (DoubleValueKey)19, // LightningProt → ArmorModVsElectric + 0x0A000005 => (DoubleValueKey)17, // FireProt → ArmorModVsFire + 0x0A000006 => (DoubleValueKey)16, // ColdProt → ArmorModVsCold + 0x0A000009 => (DoubleValueKey)280, // SalvageWorkmanship → the engine's workmanship read (as wobjectgetdoubleprop) + 0x0A00000B => DoubleValueKey.DamageVariance, // Variance + 0x0A00000C => DoubleValueKey.WeaponOffense, // AttackBonus + 0x0A00000E => DoubleValueKey.DamageMod, // DamageBonus + _ => (DoubleValueKey)key, + }; } diff --git a/Shared/RynthCore.LootSdk/AcGameEnums.cs b/Shared/RynthCore.LootSdk/AcGameEnums.cs index b22441e..5684224 100644 --- a/Shared/RynthCore.LootSdk/AcGameEnums.cs +++ b/Shared/RynthCore.LootSdk/AcGameEnums.cs @@ -87,27 +87,28 @@ public enum AcIntProperty /// /// Loot-relevant float item properties. Values match Chorizite STypeFloat sequential enum -/// (UNDEF=0, HEARTBEAT_INTERVAL=1, …). Cast to int when calling item.Values(key, 0.0). +/// (UNDEF=0, HEARTBEAT_INTERVAL=1, …) and ACE's PropertyFloat. Cast to int when calling item.Values(key, 0.0). +/// AttackBonus, DamageMod, ManaConvMod and SlayerDamageBonus were one low until 2026-10-05. /// public enum AcFloatProperty { AcidProtMod = 18, // ARMOR_MOD_VS_ACID - AttackBonus = 61, // WEAPON_OFFENSE — attack bonus % + AttackBonus = 62, // WEAPON_OFFENSE — attack bonus % BluntProtMod = 15, // ARMOR_MOD_VS_BLUDGEON ColdProtMod = 16, // ARMOR_MOD_VS_COLD - DamageMod = 62, // DAMAGE_MOD — damage bonus % + DamageMod = 63, // DAMAGE_MOD — damage bonus % DamageVariance = 22, // DAMAGE_VARIANCE DefenseBonus = 29, // WEAPON_DEFENSE — melee defense bonus % ElectricProtMod = 19, // ARMOR_MOD_VS_ELECTRIC ElementalDamageMod = 152, // ELEMENTAL_DAMAGE_MOD FireProtMod = 17, // ARMOR_MOD_VS_FIRE MagicDefBonus = 150, // WEAPON_MAGIC_DEFENSE - ManaConvMod = 143, // MANA_CONVERSION_MOD + ManaConvMod = 144, // MANA_CONVERSION_MOD MissileDefBonus = 149, // WEAPON_MISSILE_DEFENSE NetherProtMod = 165, // ARMOR_MOD_VS_NETHER PierceProtMod = 14, // ARMOR_MOD_VS_PIERCE SlashProtMod = 13, // ARMOR_MOD_VS_SLASH - SlayerDamageBonus = 137, // SLAYER_DAMAGE_BONUS + SlayerDamageBonus = 138, // SLAYER_DAMAGE_BONUS } /// AC material types. Integer values match the live acclient.exe property table. diff --git a/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs b/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs index 24fb2ce..407bd14 100644 --- a/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs +++ b/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs @@ -45,23 +45,42 @@ public static class LootRuleText { var keys = new List<(int, string)> { - (5, "EncumbVal"), (9, "Locations"), (19, "Value"), (25, "Level"), (28, "ArmorLevel"), (44, "Damage"), (45, "DamageType"), - (48, "WeaponSkill"), (54, "MaxDamage"), + (5, "EncumbVal"), (9, "Locations"), (19, "Value"), (25, "Level"), (28, "ArmorLevel"), (44, "Damage (max)"), (45, "DamageType"), + (48, "WeaponSkill"), (54, "WeaponEncumbrance"), // 54 was labelled MaxDamage until 2026-10-07; max damage is 44 (87, "MaxStructure"), (88, "Structure"), (105, "ItemWorkmanship"), (107, "ItemMaxMana"), (131, "MaterialType"), (158, "WieldRequirements"), (159, "WieldSkilltype"), (160, "WieldDifficulty"), (218, "EquippedSlots"), (353, "ImbuedEffect"), (370, "DamageRating"), (371, "DamageResistRating"), (372, "CritRating"), (373, "CritResistRating"), (374, "CritDamageRating"), (375, "CritDamageResistRating"), (376, "HealBoostRating"), (377, "NetherResistRating"), (379, "VitalityRating"), (0x0D000000, "Type (WCID)"), // Decal's synthetic key: the weenie class id + // Decal's other synthetic keys (Decal.Adapter LongValueKey), as VTank's editor names them; + // RynthAi reads each as the game property it is (WorldObjectCache.GetDecalLongKey). + (0x0D000001, "Icon"), (0x0D000004, "ItemSlots"), (0x0D000005, "PackSlots"), + (0x0D000006, "StackCount"), (0x0D000007, "StackMax"), (0x0D000008, "AssociatedSpell"), + (0x0D00000B, "WieldingSlot"), (0x0D00000D, "Coverage"), (0x0D00000E, "EquipableSlots"), + (0x0D00000F, "EquipType"), (0x0D000010, "IconOutline"), (0x0D000011, "MissileType"), + (0x0D000012, "UsageMask"), (0x0D000014, "HookMask"), (0x0D000015, "HookType"), + (0x0D00001A, "Category"), (0x0D00001F, "WeapSpeed"), (0x0D000020, "EquipSkill"), + (0x0D000021, "DamageType (Decal)"), (0x0D000022, "MaxDamage"), + (0x0D000029, "IconOverlay"), (0x0D00002A, "IconUnderlay"), }; keys.AddRange(T11.T11Keys.Names()); return keys.ToArray(); } + /// + /// STypeFloat ids (ACE's PropertyFloat), then the 0x0A0000xx keys VTank's own editor writes + /// for the appraisal's weapon profile (uTank2 LootPlugins.DoubleValueKey). 5, 29, 62, 63 and + /// 167 were labelled ApproachDistance, WeaponLength, WeaponDefense, WeaponOffense and ManaRate + /// until 2026-10-05. + /// public static readonly (int Id, string Name)[] DoubleKeys = { - (5, "ApproachDistance"), (22, "DamageVariance"), (29, "WeaponLength"), (62, "WeaponDefense"), - (63, "WeaponOffense"), (152, "ElementalDamageVsMonsters"), (167, "ManaRate"), + (5, "ManaRate"), (22, "DamageVariance"), (29, "WeaponDefense"), (62, "WeaponOffense"), + (63, "DamageMod"), (144, "ManaConversionMod"), (149, "WeaponMissileDefense"), + (150, "WeaponMagicDefense"), (152, "ElementalDamageVsMonsters"), (167, "CooldownDuration"), + (0x0A000009, "SalvageWorkmanship"), (0x0A00000B, "Variance"), + (0x0A00000C, "AttackBonus"), (0x0A00000E, "DamageBonus"), }; /// String keys. Use (14) and LongDesc (16) hold the T11 "Modifiers:" / "Property Details:" text. @@ -141,8 +160,8 @@ public static class LootRuleText /// public static (int Id, string Name)[]? ValueTableFor(int longKey) => longKey switch { - 45 => DamageTypes, - 48 => Skills, + 45 or 0x0D000021 => DamageTypes, + 48 or 0x0D000020 => Skills, 131 => Materials, 158 => WieldRequirements, 159 => Skills, @@ -151,10 +170,10 @@ public static class LootRuleText }; /// True when the long key's value is a set of flags (a named value is one flag or a common pair). - public static bool ValueTableIsFlags(int longKey) => longKey == 45; + public static bool ValueTableIsFlags(int longKey) => longKey is 45 or 0x0D000021; /// The long keys that have a value table, for the vocabulary. - public static readonly int[] KeysWithValueTables = { 45, 48, 131, 158, 159, T11.T11Keys.WeaponGrade }; + public static readonly int[] KeysWithValueTables = { 45, 48, 131, 158, 159, 0x0D000020, 0x0D000021, T11.T11Keys.WeaponGrade }; /// /// True for the conditions whose value is picked by name when the key has a diff --git a/Tools/RynthCore.LootEditor/TypedEditors.cs b/Tools/RynthCore.LootEditor/TypedEditors.cs index 9639bef..779ccc6 100644 --- a/Tools/RynthCore.LootEditor/TypedEditors.cs +++ b/Tools/RynthCore.LootEditor/TypedEditors.cs @@ -366,15 +366,7 @@ internal static class TypedEditors RynthCore.Loot.Editing.LootRuleText.LongKeys; public static readonly (int Id, string Name)[] DoubleKeys = - { - (5, "ApproachDistance"), - (22, "DamageVariance"), - (29, "WeaponLength"), - (62, "WeaponDefense"), - (63, "WeaponOffense"), - (152, "ElementalDamageVsMonsters"), - (167, "ManaRate"), - }; + RynthCore.Loot.Editing.LootRuleText.DoubleKeys; public static readonly (int Id, string Name)[] StringKeys = { diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NativeLootTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NativeLootTests.cs index 4c5b9a0..96b858b 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/NativeLootTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NativeLootTests.cs @@ -14,8 +14,9 @@ namespace RynthCore.RynthAiHostTests.Tests; // when the selected profile is a .json file. internal static class NativeLootTests { - private const int MaxDamage = 54, Value = 19, ArmorLevel = 28, Workmanship = 105, Material = 131; - private const int DamageVariance = 22, DamageMod = 62, WeaponDefense = 29; + private const int MaxDamage = 44, Value = 19, ArmorLevel = 28, Workmanship = 105, Material = 131; + // ACE PropertyFloat ids (WeaponOffense 62 / DamageMod 63; 61 is EconRecoveryInterval). + private const int DamageVariance = 22, WeaponOffense = 62, DamageMod = 63, WeaponDefense = 29; public static void Register(Runner r) { @@ -32,6 +33,7 @@ internal static class NativeLootTests r.Add("loot native: string regex, case-insensitive, falls back to the name", StringValue); r.Add("loot native: min damage = max - variance * max", MinDamage); r.Add("loot native: damage percent reads DamageMod * 100", DamagePercent); + r.Add("loot native: DoubleValueKey ids are ACE's PropertyFloat (DamageMod 63, not WeaponOffense 62)", DoubleValueKeyIds); r.Add("loot native: total ratings sum keys 370-376 and 379 only", TotalRatings); r.Add("loot native: character skill (null, stub and live skills)", CharacterSkill); r.Add("loot native: unknown condition type passes", UnknownConditionPasses); @@ -211,6 +213,35 @@ internal static class NativeLootTests var bow = new Item("Bow").Dbl(DamageMod, 1.5); Check.True(Eval(new DamagePercentGECondition { Value = 150 }, bow), "1.5 -> 150%"); Check.False(Eval(new DamagePercentGECondition { Value = 151 }, bow), "above"); + + // A launcher with a big attack mod and a small damage mod: the rule must read the damage + // mod (63). With DamageMod = 62 in the enum (before 2026-10-05) it read the attack mod. + var launcher = new Item("Bow").Dbl(WeaponOffense, 1.5).Dbl(DamageMod, 1.1).Dbl(61, 2.0); + Check.True(Eval(new DamagePercentGECondition { Value = 110 }, launcher), "damage mod 1.1 -> 110%"); + Check.False(Eval(new DamagePercentGECondition { Value = 111 }, launcher), "the 1.5 attack mod is not read"); + Check.False(Eval(new DamagePercentGECondition { Value = 150 }, new Item("Bow").Dbl(WeaponOffense, 1.5)), + "attack mod alone: no damage percent"); + } + + private static void DoubleValueKeyIds() + { + Check.Eq((int)DoubleValueKey.DamageVariance, 22, "DamageVariance"); + Check.Eq((int)DoubleValueKey.MaximumVelocity, 26, "MaximumVelocity"); + Check.Eq((int)DoubleValueKey.WeaponDefense, 29, "WeaponDefense"); + Check.Eq((int)DoubleValueKey.UseRadius, 54, "UseRadius"); + Check.Eq((int)DoubleValueKey.WeaponOffense, 62, "WeaponOffense"); + Check.Eq((int)DoubleValueKey.DamageMod, 63, "DamageMod"); + Check.Eq((int)DoubleValueKey.PowerLevel, 92, "PowerLevel"); + Check.Eq((int)DoubleValueKey.AccuracyLevel, 93, "AccuracyLevel"); + Check.Eq((int)AcFloatProperty.AttackBonus, 62, "LootSdk AttackBonus = WeaponOffense"); + Check.Eq((int)AcFloatProperty.DamageMod, 63, "LootSdk DamageMod"); + Check.Eq((int)AcFloatProperty.ManaConvMod, 144, "LootSdk ManaConvMod"); + Check.Eq((int)AcFloatProperty.SlayerDamageBonus, 138, "LootSdk SlayerDamageBonus"); + + // The double-key condition reads the id it is given: 63 is the damage mod. + var bow = new Item("Bow").Dbl(WeaponOffense, 1.25).Dbl(DamageMod, 1.05); + Check.True(Eval(new DoubleValKeyGECondition { Key = 63, Value = 1.05 }, bow), "key 63 reads DamageMod"); + Check.False(Eval(new DoubleValKeyGECondition { Key = 63, Value = 1.06 }, bow), "not WeaponOffense"); } private static void TotalRatings() diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VTankLootTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VTankLootTests.cs index 91afc46..dc72ca7 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/VTankLootTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/VTankLootTests.cs @@ -26,7 +26,9 @@ internal static class VTankLootTests r.Add("loot vtank: string value match", StringValueMatch); r.Add("loot vtank: long keys LE/GE/E/NE and flag, at the boundary", LongKeys); r.Add("loot vtank: Decal's Type key (0x0D000000) is the WCID - 'loot everything that isn't retail'", WcidKey); + r.Add("loot vtank: Decal's long keys (MaxDamage, Coverage, EquipType, IconOverlay) read the game property", DecalLongKeys); r.Add("loot vtank: double keys LE/GE", DoubleKeys); + r.Add("loot vtank: VTank's 0x0A0000xx double keys (AttackBonus, DamageBonus, Variance) read 62/63/22", VTankDoubleKeys); r.Add("loot vtank: object class", ObjectClass); r.Add("loot vtank: value and workmanship requirements", ValueAndWorkmanship); r.Add("loot vtank: damage nodes (min, median, missile, tinked, percent)", DamageNodes); @@ -165,6 +167,33 @@ internal static class VTankLootTests Check.True(M(retail, C(N.LongValKeyE, "20646", type)), "an exact WCID match works too"); } + // 2026-10-07: LootSnobV4's "(2H) Cleaving MAX 350" (Buffed Long Key >= on 218103842) never kept + // anything: Decal's synthetic keys were read as STypeInt ids no object has. 336 of its rules + // use MaxDamage, 109 Coverage, 83 IconOverlay. + private static void DecalLongKeys() + { + var axe = new Item("Greataxe", AcObjectClass.MeleeWeapon).Int(44, 30).Int(51, 5).Int(48, 41); + Check.True(M(axe, C(N.BuffedLongValKeyGE, "25", "218103842")), "MaxDamage 30 >= 25"); + Check.False(M(axe, C(N.BuffedLongValKeyGE, "31", "218103842")), "MaxDamage 30 < 31"); + Check.True(M(axe, C(N.LongValKeyGE, "30", "218103842")), "plain Long Key too"); + Check.True(M(axe, C(N.LongValKeyE, "5", "218103823")), "EquipType = CombatUse (5, two-handed)"); + Check.True(M(axe, C(N.LongValKeyE, "41", "218103840")), "EquipSkill = WeaponSkill"); + var shirt = new Item("Shirt", AcObjectClass.Clothing).Int(4, 0x1A); + Check.True(M(shirt, C(N.LongValKeyFlagExists, "2", "218103821")), "Coverage flag reads ClothingPriority"); + Check.False(M(shirt, C(N.LongValKeyFlagExists, "1", "218103821")), "a flag it lacks"); + Check.Eq(new Item("Stick").Wo.Values(218103820, -7), -7, "an unmapped Decal key (Monarch) answers the default"); + + FakeHost.Reset(); + var host = FakeHost.Create(); + var cache = new WorldObjectCache(host); + const uint Rare = 0x80001101; + FakeHost.DataIds[(Rare, 50)] = 0x06006C38; + var rare = new WorldObject(unchecked((int)Rare), "Pearl of Blood Drinking", AcObjectClass.Misc) { Cache = cache }; + Check.Eq(rare.Values(218103849, 0), 27704, "IconOverlay is the overlay's portal index, as Decal gives it"); + Check.True(M(rare, C(N.LongValKeyE, "27704", "218103849")), "an IconOverlay rule matches"); + Check.Eq(rare.Values(218103850, -1), -1, "no underlay: the default"); + } + private static void DoubleKeys() { var item = new Item("x").Dbl(29, 1.25); @@ -175,6 +204,27 @@ internal static class VTankLootTests Check.True(M(item, C(N.DoubleValKeyGE, "1e0", "29")), "exponent notation parses"); } + // VTank's editor writes the weapon profile's attack/damage mods under Decal's synthetic keys + // (uTank2 LootPlugins.DoubleValueKey AttackBonus 0x0A00000C, DamageBonus 0x0A00000E, + // Variance 0x0A00000B). LootSnobV4's "(H) Axe (AT +8)" rules are BuffedDoubleValKeyGE + // 1.31 on 167772172; read raw the key was never set, so they could not match. + private static void VTankDoubleKeys() + { + var axe = new Item("Axe").Dbl(62, 1.31).Dbl(63, 1.2).Dbl(22, 0.4); + const string attack = "167772172", damage = "167772174", variance = "167772171"; + Check.True(M(axe, C(N.BuffedDoubleValKeyGE, "1.31", attack)), "LootSnob AT rule: attack 1.31 >= 1.31"); + Check.False(M(axe, C(N.BuffedDoubleValKeyGE, "1.32", attack)), "attack just above"); + Check.True(M(axe, C(N.DoubleValKeyGE, "1.2", damage)), "DamageBonus reads DamageMod 63"); + Check.False(M(axe, C(N.DoubleValKeyGE, "1.21", damage)), "not WeaponOffense"); + Check.True(M(axe, C(N.DoubleValKeyLE, "0.4", variance)), "Variance reads DamageVariance 22"); + Check.False(M(axe, C(N.DoubleValKeyLE, "0.39", variance)), "variance below"); + Check.False(M(new Item("Stick"), C(N.DoubleValKeyGE, "0.1", attack)), "no attack mod: reads 0"); + + var armor = new Item("Coat").Dbl(13, 1.6).Dbl(19, 0.8); + Check.True(M(armor, C(N.DoubleValKeyGE, "1.6", "167772160")), "SlashProt reads ArmorModVsSlash 13"); + Check.True(M(armor, C(N.DoubleValKeyLE, "0.8", "167772164")), "LightningProt reads ArmorModVsElectric 19"); + } + private static void ObjectClass() { Check.True(M(new Item("x", AcObjectClass.Salvage), C(N.ObjectClass, "39")), "salvage is class 39"); @@ -199,7 +249,7 @@ internal static class VTankLootTests private static void DamageNodes() { - var sword = new Item("Sword").Int(54, 40).Dbl(22, 0.5); // min 20, median 30 + var sword = new Item("Sword").Int(44, 40).Dbl(22, 0.5); // min 20, median 30 Check.True(M(sword, C(N.MinDamageGE, "20")), "min 20"); Check.False(M(sword, C(N.MinDamageGE, "20.5")), "min above"); Check.True(M(sword, C(N.BuffedMedianDamageGE, "30")), "median 30"); @@ -211,10 +261,10 @@ internal static class VTankLootTests Check.False(M(nodmg, C(N.BuffedMedianDamageGE, "0")), "no max damage: median fails"); Check.False(M(nodmg, C(N.BuffedMissileDamageGE, "0")), "no max damage: missile fails"); - var bow = new Item("Bow").Int(54, 50).Dbl(152, 1.2); + var bow = new Item("Bow").Int(44, 50).Dbl(152, 1.2); Check.True(M(bow, C(N.BuffedMissileDamageGE, "60")), "50 * elemental 1.2 = 60"); Check.False(M(bow, C(N.BuffedMissileDamageGE, "60.1")), "just above"); - var weakBow = new Item("Bow").Int(54, 50).Dbl(152, 0.5); + var weakBow = new Item("Bow").Int(44, 50).Dbl(152, 0.5); Check.True(M(weakBow, C(N.BuffedMissileDamageGE, "50")), "an elemental bonus below 1 counts as 1"); } From 0daf0a44a378f8890b240e7c59edd060ce050537 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Thu, 8 Oct 2026 17:29:51 -0400 Subject: [PATCH 6/6] Snapshot for release 2026.10.8.1 (internal f3d67ec) --- .../Combat/BuffManager.cs | 48 ++- .../Combat/CombatManager.cs | 313 ++++++++++++++++- .../Combat/SpellDatabase.cs | 41 +++ .../Combat/SpellManager.cs | 8 +- .../Combat/WorldObjectCache.cs | 18 + .../CorpseOpenController.cs | 42 ++- .../LegacyUi/LegacyAdvancedSettingsUi.cs | 50 ++- .../LegacyUi/LegacyDashboardRenderer.cs | 47 ++- .../LegacyUi/LegacyNavigationUi.cs | 2 +- .../LegacyUi/LegacyUiSettings.cs | 56 ++- .../LegacyUi/NavRouteParser.cs | 14 +- .../Loot/LootEditorBridge.cs | 12 +- .../ManaStoneManager.cs | 58 +++- .../Meta/AfFileWriter.cs | 2 +- .../Meta/ExpressionEngine.cs | 27 +- .../NavigationEngine.cs | 2 +- .../RynthAiCommands.cs | 27 +- .../RynthAiPlugin.HazardEscape.cs | 323 +++++++++++++++++ .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 65 +++- .../Vendor/AutoVendorManager.cs | 26 ++ .../Vendor/AutoVendorPlanner.cs | 4 +- Plugins/RynthCore.Plugin.RynthNav/Atlas.cs | 33 +- .../RynthCore.Plugin.RynthNav/RecallMemory.cs | 19 +- .../RecallPlanner.cs | 115 +++++- .../RynthNavPlugin.Blocked.cs | 109 ++++++ .../RynthNavPlugin.Panel.cs | 7 +- .../RynthNavPlugin.Travel.cs | 235 +++++++++++-- .../RynthNavPlugin.cs | 45 ++- .../RynthCore.LootSdk/Editing/LootEditWire.cs | 9 + .../Editing/LootItemRules.cs | 75 +++- Tools/RynthCore.AutoVendorTests/Program.cs | 3 +- .../RynthCore.LootSdkTests/LootAddT11Tests.cs | 117 +++++++ Tools/RynthCore.LootSdkTests/Program.cs | 1 + .../RynthCore.MonsterEditor/MainWindow.axaml | 8 + Tools/RynthCore.MonsterEditor/Models.cs | 3 +- .../Fakes/FakeHost.cs | 12 +- Tools/RynthCore.RynthAiHostTests/Program.cs | 4 + .../Tests/AttackLatencyTests.cs | 4 +- .../Tests/BuffTests.cs | 128 ++++++- .../Tests/CustomDebuffTests.cs | 55 +++ .../Tests/GiveTests.cs | 17 + .../Tests/HazardEscapeTests.cs | 161 +++++++++ .../Tests/LootCorpseTests.cs | 21 ++ .../Tests/ManaStoneChoiceTests.cs | 56 +++ .../Tests/MonsterEditorTests.cs | 2 +- .../Tests/VitalsTests.cs | 37 ++ .../Tests/WallTests.cs | 327 ++++++++++++++++++ Tools/RynthNav.Baker/NavBake.cs | 9 +- Tools/RynthNav.RouteTests/Program.cs | 126 +++++++ 49 files changed, 2802 insertions(+), 121 deletions(-) create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HazardEscape.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs create mode 100644 Tools/RynthCore.LootSdkTests/LootAddT11Tests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/CustomDebuffTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/HazardEscapeTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/WallTests.cs diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 8d10537..66272b3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -158,6 +158,15 @@ public class BuffManager : IDisposable private readonly Dictionary _buffFailCooldownUntil = new(); private const double BuffFailCooldownSec = 120.0; + // A vital spell LEVEL the server refused for missing components (Revitalize, Heal, Stamina + // to Mana...): that level is passed over for NoComponentsLevelSec and the next lower level + // with components is cast instead. It used to park the whole family, then retry the same + // top level the character had no components for (2026-10-08). + private readonly Dictionary _noComponentsUntil = new(); + private const double NoComponentsLevelSec = 600.0; + private bool LevelLacksComponents(int spellId) + => _noComponentsUntil.TryGetValue(spellId, out DateTime until) && DateTime.Now < until; + // Per-family SILENT no-show counter. Distinct from _buffFailCooldownUntil // (which catches chat-explicit hard rejects). This catches the /god case: // skill is Trained → IsSkillUsable says yes → BuildDynamicBuffList includes @@ -476,6 +485,27 @@ public class BuffManager : IDisposable { AcSkillType.Summoning, "Summoning Mastery" }, }; + /// + /// The prots and banes the Buffing settings let the player untick (LegacyUiSettings.DisabledBuffs), + /// paired by element for the two-column grid: (buff base name, label). Armor Self and + /// Impenetrability head the columns. The cast order stays BuildDynamicBuffList's. + /// + internal static readonly (string Buff, string Label)[] ToggleProtections = + { + ("Armor Self", "Armor"), ("Fire Protection Self", "Fire"), ("Cold Protection Self", "Cold"), + ("Acid Protection Self", "Acid"), ("Lightning Protection Self", "Lightning"), + ("Blade Protection Self", "Blade"), ("Piercing Protection Self", "Piercing"), + ("Bludgeoning Protection Self", "Bludgeoning"), + }; + + internal static readonly (string Buff, string Label)[] ToggleBanes = + { + ("Impenetrability", "Impenetrability"), ("Flame Bane", "Flame"), ("Frost Bane", "Frost"), + ("Acid Bane", "Acid"), ("Lightning Bane", "Lightning"), + ("Blade Bane", "Blade"), ("Piercing Bane", "Piercing"), + ("Bludgeoning Bane", "Bludgeoning"), + }; + public BuffManager(RynthCoreHost host, LegacyUiSettings settings, SpellManager spellManager, PlayerVitalsCache vitals) { _host = host; @@ -1620,7 +1650,7 @@ public class BuffManager : IDisposable _healWaitKind = "server finishing the last cast"; return true; } - int spellId = FindBestSpellId(baseName, AcSkillType.LifeMagic); + int spellId = _spellManager.GetDynamicSelfBuffId(baseName, AcSkillType.LifeMagic, LevelLacksComponents); // A heal with nothing known at the allowed tiers: the lowest known tier above them. // Vitae can drop Life Magic under a tier line while only higher tiers are known. if (spellId == 0 && baseName is "Heal Self" or "Stamina to Health Self") @@ -3107,6 +3137,12 @@ public class BuffManager : IDisposable final.AddRange(step5_LifeAndItem); final.AddRange(step6_WeaponAuras); final.AddRange(step7_ArmorBanes); + + // Buffs the player unticked (Buffing settings: prots and banes) leave the list here, so + // the cast loop never casts them and NeedsAnyBuff never waits on them: a skipped buff + // can't hold the bot in Buffing. + if (_settings.DisabledBuffs.Count > 0) + final.RemoveAll(_settings.IsBuffDisabled); return final; } @@ -3316,7 +3352,15 @@ public class BuffManager : IDisposable if (_pendingSpellId != 0) { var pendingSpell = SpellTableStub.GetById(_pendingSpellId); - if (pendingSpell != null) + bool noCompsVital = _pendingSpellId == _pendingVitalSpellId + && (lower.Contains("components") || lower.Contains("missing some required")); + if (pendingSpell != null && noCompsVital) + { + // A vital spell: pass over this level only; the next lower one goes next. + _noComponentsUntil[_pendingSpellId] = DateTime.Now.AddSeconds(NoComponentsLevelSec); + _host.WriteToChat($"[RynthAi] No components for {pendingSpell.Name}: using a lower level for {NoComponentsLevelSec / 60:0} min.", 2); + } + else if (pendingSpell != null) { if (IsItemEnchantment(pendingSpell.Name)) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index 8d17476..d23066a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -184,6 +184,60 @@ public partial class CombatManager : IDisposable private DateTime _faceSettledAt = DateTime.MinValue; private const double FACE_SETTLE_MS = 140.0; // let the turn-stop reach the server (≥ one 30Hz tick) before the cast packet + // ── Wall facing (2026-10-08) ───────────────────────────────────────────── + // A wall is untargeted: ACE launches it along the caster's facing and never turns the caster + // for it (see CountMonstersInWallPath). So before a wall the bot turns the character itself: + // an instant heading snap (TurnToHeading) when it is more than WallFaceToleranceDeg off the + // target, then no cast until WallFaceSettleMs later so the server has the new heading. The + // snap changes only the client's heading; the client tells the server in its next position + // event, which goes out at most once per second while the position or heading keeps + // changing (CommandInterpreter::ShouldSendPositionEvent 0x006B5520; the 1.0 s interval is set + // in the constructor 0x006B4D80), so the settle covers a full second plus a frame. Only ever + // inside AttackWithMagic, i.e. after the cadence guard and the gesture gate: never while a + // cast is resolving, and nothing turns during the wall's windup. Targeted shapes are unchanged. + // Always face the target exactly before a wall (owner, 2026-10-08: "for walls he always has to + // turn to the target"): a wall flies straight, so a few degrees off misses at range. Only a + // facing within WallFaceToleranceDeg casts without a turn. + internal const double WallFaceToleranceDeg = 1.0; + internal const double WallFaceSettleMs = 1100.0; + // After the settle the wall goes if the target is still within this of the snapped heading; + // further (it moved during the second) the bot turns again, at most WallFaceMaxSnaps times + // per wall, then casts anyway rather than chase a running monster forever. + internal const double WallFaceDriftDeg = 5.0; // the most allowed (close in) + internal const int WallFaceMaxSnaps = 3; + // How far to the side of the wall's centre line the target may have moved during the settle + // (metres): at 70 yd, 5 degrees is 6 m off - wider than half the wall (owner, 2026-10-08). + internal const double WallAimSlackMeters = 1.8; + + /// The drift allowed after the settle for a target this far away: the angle that puts + /// it to the side, between the tolerance and WallFaceDriftDeg. + internal static double WallDriftAllowedDeg(double distanceMeters) + { + if (distanceMeters <= 0.1) return WallFaceDriftDeg; + double deg = Math.Atan2(WallAimSlackMeters, distanceMeters) * 180.0 / Math.PI; + return Math.Clamp(deg, WallFaceToleranceDeg, WallFaceDriftDeg); + } + + private double WallDriftAllowedDeg(int targetId) + { + try + { + if (_host.TryGetPlayerPose(out _, out float px, out float py, out _, out _, out _, out _, out _) + && _host.TryGetObjectPosition((uint)targetId, out _, out float tx, out float ty, out _)) + return WallDriftAllowedDeg(Math.Sqrt((tx - px) * (tx - px) + (ty - py) * (ty - py))); + } + catch { } + return WallFaceToleranceDeg; + } + private int _wallFaceSnaps; + private int _wallFaceTarget; + private DateTime _wallFaceAt = DateTime.MinValue; + // Set by AttackWithMagic when it held a wall for its turn: Think then ends the tick without + // counting it as an attack (no attack interval starts, so the wall goes once settled). + private bool _wallFaceHeld; + /// Tests: the clock the wall facing reads. + internal Func WallClock { get; set; } = () => DateTime.Now; + // ── Magic cast cadence guard ──────────────────────────────────────────── // Don't issue the next combat cast until the previous one's server windup // has resolved (a UseDone arrived, or a hard timeout). Re-casting into the @@ -214,7 +268,7 @@ public partial class CombatManager : IDisposable private DateTime _lastNoSpellChatAt = DateTime.MinValue; private readonly Dictionary _ringMissingChatAt = new(StringComparer.OrdinalIgnoreCase); private const double NoSpellChatIntervalMs = 30_000; - private bool _lastCastWasRing = false; + private bool _lastCastWasRing = false; // the last attack hit an area: a ring, or a wall (2026-10-08) private const double ATTACK_SPELL_COOLDOWN_MS = 100.0; private bool _returnToPhysicalCombat = false; @@ -535,6 +589,7 @@ public partial class CombatManager : IDisposable public int Id; public double Distance; public double Angle; // absolute facing error to target, degrees (0 = directly ahead) + public double Bearing; // heading from the player to it, degrees (0 = north, clockwise); NaN = unknown public string Name; } @@ -860,16 +915,18 @@ public partial class CombatManager : IDisposable } double angle = 180.0; + double bearing = double.NaN; if (hasPose && hasMobPos) // the mob's position was read for the distance above { double desired = Math.Atan2(tx - ppx, ty - ppy) * (180.0 / Math.PI); if (desired < 0) desired += 360.0; + bearing = desired; double err = desired - playerHeadingDeg; while (err > 180.0) err -= 360.0; while (err < -180.0) err += 360.0; angle = Math.Abs(err); } - _scannedTargets.Add(new ScannedTarget { Id = wo.Id, Distance = dist, Angle = angle, Name = wo.Name }); + _scannedTargets.Add(new ScannedTarget { Id = wo.Id, Distance = dist, Angle = angle, Bearing = bearing, Name = wo.Name }); } // Primary: closest first. Tiebreaker within 0.5yd: smallest facing angle first. @@ -1023,8 +1080,22 @@ public partial class CombatManager : IDisposable { "Yield", new[] { "Magic Yield Other", "Yield" } }, }; - // Shape index into the SpellShapes / VoidSpellShapes rows. - internal const int ShapeArc = 0, ShapeRing = 1, ShapeStreak = 2, ShapeBolt = 3, ShapeBlast = 4; + // Shape index into the SpellShapes / VoidSpellShapes rows. ShapeWall (2026-10-08) has no row: + // walls have no tiered base names and are found by spell category (WallCategories). + internal const int ShapeArc = 0, ShapeRing = 1, ShapeStreak = 2, ShapeBolt = 3, ShapeBlast = 4, ShapeWall = 5; + + // Wall spells per element: ACE SpellCategory AcidWall 229, BludgeoningWall 230, ColdWall 231, + // ElectricWall 232, FireWall 233, PiercingWall 234, SlashingWall 235 (column 3 of SpellData.txt). + // Retail has one per element (Blistering Creeper, Hammering Crawler, Foon-Ki's Glacial Floe, + // Os' Wall, Slithering Flames, Spike Strafe, Bed of Blades: power 200, so level 5 by ACE's + // server formula); the categories also hold other spells (Demon's Tongues, Burning Earth, the + // "... Whip" spells) that a character on some server may know, so a wall is picked by category, + // not by name. Void (Nether) has no walls. + private static readonly Dictionary WallCategories = new(StringComparer.OrdinalIgnoreCase) + { + { "Acid", 229 }, { "Bludgeon", 230 }, { "Cold", 231 }, { "Lightning", 232 }, + { "Fire", 233 }, { "Pierce", 234 }, { "Blade", 235 }, { "Slash", 235 }, + }; // Base names per element, by shape: Arc, Ring, Streak, Bolt, Blast. Every non-ring base has // "{base} I".."VI" (blasts: III-VI only, retail has no blast I/II) and "Incantation of {base}" @@ -2290,6 +2361,9 @@ public partial class CombatManager : IDisposable /// the full interval anyway. internal const double NewTargetCastFloorMs = 300; + /// The least Attack Spell Delay on an engine without the server gates. + internal const double NoGatesAttackFloorMs = 250; + /// True when is positive only because AC lowered it inline at a /// server UseDone the busy hook can't see (see ). internal bool BusyIsLeftover() @@ -2314,7 +2388,12 @@ public partial class CombatManager : IDisposable internal static double AttackIntervalMs(int combatMode, int attackSpellIntervalMs, bool hasServerGates, bool newTarget) { if (combatMode != CombatMode.Magic) return 1000.0; - double interval = attackSpellIntervalMs > 0 ? attackSpellIntervalMs : 1500; + // 0 is allowed (2026-10-08): no delay of its own, the server gates (UseDone and the cast + // gesture) alone hold the next cast until the last one is done. A file without the setting + // keeps 1500 (the payload is nullable). An engine without those gates keeps a 250 ms floor, + // the old slider minimum, so casts can't be sent back to back into "You're too busy!". + double interval = attackSpellIntervalMs >= 0 ? attackSpellIntervalMs : 1500; + if (!hasServerGates) interval = Math.Max(interval, NoGatesAttackFloorMs); if (newTarget && hasServerGates) return Math.Min(interval, NewTargetCastFloorMs); return interval; } @@ -2687,6 +2766,9 @@ public partial class CombatManager : IDisposable // MELEE the same: ACE's HandleActionTargetedMeleeAttack_Inner rotates to the // target (past melee_max_angle) before the swing, so the servo made the same // swing-spin-swing with a knife in an Olthoi swarm (2026-09-29, Lucy). + // The one exception is a WALL spell (2026-10-08): untargeted, so the server doesn't + // turn for it. AttackWithMagic snaps the heading before a wall (HoldForWallFacing), + // behind the cadence guard above, and never during a windup. if (CurrentCombatMode == CombatMode.Magic || CurrentCombatMode == CombatMode.Missile || CurrentCombatMode == CombatMode.Melee) { @@ -2775,6 +2857,15 @@ public partial class CombatManager : IDisposable AttackWithMagic(targetObj); + // A wall held for its turn (2026-10-08): nothing was sent but a heading snap. End + // the tick here so it doesn't count as an attack: the attack interval doesn't start + // and the wall goes the first tick after the settle (HoldForWallFacing). + if (_wallFaceHeld) + { + _tickWait = CombatLatencyTracker.Wait.Face; + return true; + } + // Don't restore the physical weapon on top of a cast just issued this tick // (AttackWithMagic → MarkCombatCastIssued): the UseObject + re-equip below would // truncate the in-flight gesture and strand Player.IsBusy. Defer one windup @@ -4625,6 +4716,64 @@ public partial class CombatManager : IDisposable catch { } } + /// + /// Before a wall at : true = don't cast this tick. Facing within + /// : false, cast (no turn). Further off: snap the heading to + /// the target and hold for , then cast, unless the target has + /// since drifted more than off (then snap again). + /// + internal bool HoldForWallFacing(int targetId) + { + DateTime now = WallClock(); + if (_wallFaceAt != DateTime.MinValue && _wallFaceTarget == targetId) + { + if ((now - _wallFaceAt).TotalMilliseconds < WallFaceSettleMs) return true; // the server catching up + _wallFaceAt = DateTime.MinValue; + if (GetFacingError(targetId) <= WallDriftAllowedDeg(targetId) || _wallFaceSnaps >= WallFaceMaxSnaps) + { + _wallFaceSnaps = 0; + return false; // turned and settled: cast + } + } + else _wallFaceSnaps = 0; + _wallFaceAt = DateTime.MinValue; + + if (!TryGetHeadingTo(targetId, out double desiredDeg, out double error)) return false; // can't tell: cast as is + if (error <= WallFaceToleranceDeg) return false; + if (!_host.HasTurnToHeading) return false; // FindBestShapedSpell doesn't pick a wall then + if (!_host.TurnToHeadingBy("Combat", (float)desiredDeg)) return true; // held by the pacer: next tick + _wallFaceTarget = targetId; + _wallFaceAt = now; + _wallFaceSnaps++; + _host.Log($"[CombatCast] wall: facing 0x{(uint)targetId:X8} first ({error:0} deg off), casting in {WallFaceSettleMs:0} ms"); + return true; + } + + /// The heading from the player to (0 = north, clockwise) + /// and how far the player's facing is off it (absolute degrees). + private bool TryGetHeadingTo(int targetId, out double desiredDeg, out double absError) + { + desiredDeg = 0; absError = 180.0; + try + { + if (!_host.TryGetPlayerPose(out _, out float px, out float py, out _, + out float qw, out _, out _, out float qz)) + return false; + if (!_host.TryGetObjectPosition((uint)targetId, out _, out float tx, out float ty, out _)) + return false; + desiredDeg = Math.Atan2(tx - px, ty - py) * (180.0 / Math.PI); + if (desiredDeg < 0) desiredDeg += 360.0; + double physYawDeg = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI); + double currentDeg = ((-physYawDeg) % 360.0 + 720.0) % 360.0; + double error = desiredDeg - currentDeg; + while (error > 180.0) error -= 360.0; + while (error < -180.0) error += 360.0; + absError = Math.Abs(error); + return true; + } + catch { return false; } + } + private void ClearCombatTurnMotions() { _host.SetMotionBy("Combat", MotionTurnRight, false); @@ -4888,6 +5037,7 @@ public partial class CombatManager : IDisposable private void AttackWithMagic(WorldObject target) { + _wallFaceHeld = false; if (_spellManager == null || target == null) return; // Hard safety veto: never cast offensive magic at something AC's combat @@ -4988,7 +5138,7 @@ public partial class CombatManager : IDisposable if (rule != null && PickBaseShape(rule) < 0) { - _host.Log($"[CombatCast] rule '{rule.Name}' has no attack shapes enabled (UseArc/Ring/Streak/Bolt/Blast all false) — no offensive cast"); + _host.Log($"[CombatCast] rule '{rule.Name}' has no attack shapes enabled (UseArc/Ring/Streak/Bolt/Blast/Wall all false) — no offensive cast"); LastCombatSkipReason = "no-attack-shapes"; // D4 record-only return; } @@ -5013,6 +5163,16 @@ public partial class CombatManager : IDisposable } } LogArcChoice(rule, target, castShape); + // A wall flies along the caster's facing and the server doesn't turn the caster for it: + // face the target first and let the new heading reach the server (2026-10-08). + if (offensiveSpellId != 0 && castShape == ShapeWall && HoldForWallFacing(activeTargetId)) + { + _wallFaceHeld = true; + LastCombatSkipReason = "wall-face"; // D4 record-only + return; + } + // A ring or a wall hits several monsters: its damage isn't the fight target's alone. + bool multiTarget = isRing || castShape == ShapeWall; if (offensiveSpellId != 0) { LastCombatSkipReason = "cast"; // D4 record-only: offensive cast issued this tick @@ -5028,7 +5188,8 @@ public partial class CombatManager : IDisposable SessionAttackCasts++; // D6: offensive attack-cast tally for the casts-per-kill signal CastsSinceLastKill++; // reset in OnKillNotification when a kill lands _lastSpellCast = DateTime.Now; - _lastCastWasRing = isRing; + _lastCastWasRing = multiTarget; // walls too: area casts (2026-10-08) + _wallFaceAt = DateTime.MinValue; // the next wall checks its facing afresh // _offensiveCastThisCycle is NOT set here anymore — a cast // attempt that the server refuses (e.g. "You're too busy!") // must not count toward the blacklist miss streak. The @@ -5051,10 +5212,16 @@ public partial class CombatManager : IDisposable // castable tier (which made every magic kill record tier 8). Fall back to the // old max-tier only if the level can't be derived, so it never regresses to blank. int castLevel = SpellTableStub.GetById(offensiveSpellId)?.Level ?? 0; + // Walls have no tier in their names: their level from their power (2026-10-08). + if (castLevel <= 0 && SpellDatabase.TryGetCategoryAndPower(offensiveSpellId, out _, out int castPower)) + castLevel = SpellDatabase.LevelFromPower(castPower); int castTierMag = castLevel > 0 ? castLevel : Math.Max(warTier, voidTier); // Ring spells are stored as a NEGATIVE tier so the Damage tab can render them as // "R" (e.g. a level-2 ring = -2 -> "R2"); non-ring stays positive; 0 = none. - _lastCastTier = isRing ? -castTierMag : castTierMag; + // Walls are filed with the rings (2026-10-08): an area cast's kills and casts-to-kill + // must not mix with the single-target tier of the same level. (The Damage tab shows + // them as "R" until it has a label of its own for walls.) + _lastCastTier = multiTarget ? -castTierMag : castTierMag; // Record the latest tier used vs this monster so the Damage tab's collapsed row // reflects it immediately (covers ring casts, which skip RecordHit). if (_fightTargetWcid != 0) _damageStore?.NoteCast(_fightTargetWcid, _lastCastTier, _fightTargetName); @@ -5071,7 +5238,7 @@ public partial class CombatManager : IDisposable _lastFightCount = _fightCastCount; StampRecentFight(); } - EvaluateKillShot(_lastCastWeaponId, element, _lastCastTier, isRing); + EvaluateKillShot(_lastCastWeaponId, element, _lastCastTier, multiTarget); } catch { } } @@ -5214,7 +5381,11 @@ public partial class CombatManager : IDisposable name = name.Trim(); int id = TrySpellByName(name); if (id != 0) return id; - int maxTier = Math.Max(EffectiveMaxTier(AcSkillType.CreatureEnchantment), EffectiveMaxTier(AcSkillType.LifeMagic)); + // Void too (2026-10-08): "Corruption" with Corruption V and VII known cast V, because only + // Creature and Life set the cap and the search started below VII. Debuffs come from these + // three schools; a level the character doesn't know is never picked. + int maxTier = Math.Max(Math.Max(EffectiveMaxTier(AcSkillType.CreatureEnchantment), EffectiveMaxTier(AcSkillType.LifeMagic)), + EffectiveMaxTier(AcSkillType.VoidMagic)); if (maxTier >= 8) { id = TrySpellByName($"Incantation of {name}"); if (id != 0) { tier = 8; return id; } } for (int t = Math.Min(maxTier, 7); t >= 1; t--) { @@ -5345,7 +5516,8 @@ public partial class CombatManager : IDisposable /// /// The base shape a rule asks for when no ring is due: Arc, then Streak, then Blast, then /// Bolt (the first one on wins; Blast beats Bolt so turning Blast on next to the default Bolt - /// does something). A ring-only rule casts Bolt between rings. -1 = no shape on at all. + /// does something). A ring-only rule casts Bolt between rings, and a wall-only rule (or ring and + /// wall only) Bolt between walls. -1 = no shape on at all. /// internal static int PickBaseShape(MonsterRule? rule) { @@ -5354,7 +5526,7 @@ public partial class CombatManager : IDisposable if (rule.UseStreak) return ShapeStreak; if (rule.UseBlast) return ShapeBlast; if (rule.UseBolt) return ShapeBolt; - return rule.UseRing ? ShapeBolt : -1; + return rule.UseRing || rule.UseWall ? ShapeBolt : -1; } /// @@ -5385,9 +5557,83 @@ public partial class CombatManager : IDisposable return count; } + // ── Wall spells (2026-10-08) ───────────────────────────────────────────────── + // A wall is 10 projectiles in a block 5 wide and 2 high (ACE spell table: dims 5x1x2, padding + // 0.8, created 2 m ahead of the caster) that fly straight along the caster's facing: it is an + // UNTARGETED spell (the client sends CastUntargetedSpell for it even with a target selected, + // and ACE launches it along the caster's forward vector), so the server never turns the caster + // to the target as it does for bolts and blasts. Its swath is therefore a corridor a few metres + // wide, not a fan: monsters are counted when they are ahead of the caster, within the range, + // and within WallHalfWidth of the line to the target (the target included). We turn to face + // the target before the cast (HoldForWallFacing), so that line is where the wall goes. + internal const double WallHalfWidth = 4.0; + + /// Tests: the wall-path count instead of the scan (the scan needs a live world). + internal Func? WallPathCountOverride { get; set; } + + /// Monsters (the target included) in a wall's path toward : + /// ahead of the caster, within , and within + /// of the line to the target. From the combat scan: LOS-clear and attackable. 0 when the target + /// isn't in the scan (its bearing is unknown). + private int CountMonstersInWallPath(double rangeYards, int targetId) + { + if (WallPathCountOverride != null) return WallPathCountOverride(); + double toTarget = double.NaN; + foreach (var c in _scannedTargets) + if (c.Id == targetId) { toTarget = c.Bearing; break; } + if (double.IsNaN(toTarget)) return 0; + int count = 0; + foreach (var c in _scannedTargets) + { + if (c.Distance > rangeYards || double.IsNaN(c.Bearing) || _recentlyKilled.ContainsKey(c.Id)) continue; + if (InWallPath(c.Distance, c.Bearing - toTarget)) count++; + } + return count; + } + + /// Is a monster away, degrees off the + /// line to the target, in the wall's path: ahead of the caster and within + /// of that line. + internal static bool InWallPath(double distance, double offDeg) + { + double rad = offDeg * (Math.PI / 180.0); + double ahead = distance * Math.Cos(rad); + double aside = Math.Abs(distance * Math.Sin(rad)); + return ahead >= 0 && aside <= WallHalfWidth; + } + + /// + /// The wall of to cast: among the known spells of its wall category + /// (), the highest level the War tier allows (the level by ACE's + /// server formula from the spell's power, : the same + /// tier limit the tiered shapes use), then the highest power, then the lowest id (the retail + /// wall). 0 = none: Nether, an element without walls, War untrained, or no wall known. + /// + internal int FindBestWallSpell(string element) + { + if (_spellManager == null || !_spellManager.IsKnownSnapshotWarm) return 0; // cold: don't guess + if (!WallCategories.TryGetValue(element, out int category)) return 0; + if (_charSkills != null && _charSkills[AcSkillType.WarMagic].Training < 2) return 0; + int maxTier = EffectiveMaxTier(AcSkillType.WarMagic); + int best = 0, bestLevel = 0, bestPower = -1; + foreach (int id in SpellDatabase.IdsInCategory(category)) + { + if (!_spellManager.IsKnownSpellId(id)) continue; + SpellDatabase.TryGetCategoryAndPower(id, out _, out int power); + int level = SpellDatabase.LevelFromPower(power); + if (level < 1 || level > maxTier) continue; + if (level > bestLevel || (level == bestLevel && power > bestPower)) + { + best = id; bestLevel = level; bestPower = power; + } + } + return best; + } + internal static string ShapeName(int shape) => shape switch { - ShapeArc => "Arc", ShapeRing => "Ring", ShapeStreak => "Streak", ShapeBolt => "Bolt", ShapeBlast => "Blast", _ => "?", + ShapeArc => "Arc", ShapeRing => "Ring", ShapeStreak => "Streak", ShapeBolt => "Bolt", ShapeBlast => "Blast", + ShapeWall => "Wall", _ => "?", }; /// @@ -5441,16 +5687,24 @@ public partial class CombatManager : IDisposable /// 2. Blast override (Blast Range on): Blast when its fan count is met, else the rule's /// other shape (, ); /// 3. Ring override (Ring Range on): Ring when its count is met (); + /// 3b. Wall override (Wall Range on, 2026-10-08): Wall when its path count is met and a wall + /// is known (), unless a ring is due. So with several due: Ring, + /// then Wall, then Blast, then the base shape. A ring hits all around and needs no turn; + /// a wall reaches further along a line but costs a turn, and outdoes a blast's 3 bolts; /// 4. Arc when clear: an Arc whose flight path to the target is blocked (a wall, or a /// ceiling the arc rises into) gives way to the rule's other shape: Streak, then Blast /// (when Blast isn't conditional), then Bolt. An Arc-only rule casts Bolt, as a ring-only /// rule does between rings. - /// is asked only in step 4, so a ring or a non-arc rule costs - /// no ray test; null (no test, or it can't tell: raycasting off or not ready) casts the Arc - /// as before. says step 4 replaced the Arc. + /// is asked only in step 4, so a ring, a wall or a non-arc rule + /// costs no ray test; null (no test, or it can't tell: raycasting off or not ready) casts the + /// Arc as before. says step 4 replaced the Arc. /// internal static int ChooseCastShape(MonsterRule? rule, bool blastConditional, bool blastFanMet, bool ringDue, Func? arcBlocked, out bool arcGaveWay) + => ChooseCastShape(rule, blastConditional, blastFanMet, ringDue, wallDue: false, arcBlocked, out arcGaveWay); + + internal static int ChooseCastShape(MonsterRule? rule, bool blastConditional, bool blastFanMet, bool ringDue, + bool wallDue, Func? arcBlocked, out bool arcGaveWay) { arcGaveWay = false; int shape = PickBaseShape(rule); @@ -5459,6 +5713,8 @@ public partial class CombatManager : IDisposable shape = blastFanMet ? ShapeBlast : PickBaseShapeWithoutBlast(rule); if (ringDue) return ShapeRing; + if (wallDue) + return ShapeWall; if (shape == ShapeArc && arcBlocked != null && arcBlocked() == true) { arcGaveWay = true; @@ -5549,7 +5805,7 @@ public partial class CombatManager : IDisposable _host.Log($"[CombatCast] rule '{rule.Name}': Arc when its flight path is clear, else {other}" + (_settings.EnableRaycasting ? "" : " (raycasting off: arcs are always cast)")); } - if (castShape == ShapeRing) return; // the ring override won: no arc question this cast + if (castShape == ShapeRing || castShape == ShapeWall) return; // an override won: no arc question this cast string state = _lastShapeArcGaveWay ? $"arc blocked ({(ArcBlockedOverride != null ? "test" : DescribeArcBlock(in _arcVerdictDetail))}): {(castShape >= 0 ? ShapeName(castShape) : "nothing")} instead" : "arc clear"; @@ -5596,10 +5852,31 @@ public partial class CombatManager : IDisposable bool ringDue = rule != null && rule.UseRing && _settings.RingRange > 0 && CountMonstersInRange(_settings.RingRange) >= Math.Max(1, _settings.MinRingTargets); - int shapeIdx = ChooseCastShape(rule, blastConditional, blastFanMet, ringDue, + // Wall override (Wall Range on): a wall when enough monsters are in its path toward the + // target and the character knows a wall of this element (none for Nether). Asked only for a + // real cast (an element probe has no target, so no path), and only when no ring is due. + // Without the host's heading snap the character can't be turned, so a wall is cast only + // when it already faces the target. + int wallId = 0; + bool wallDue = false; + if (!ringDue && arcTargetId != 0 && rule != null && rule.UseWall && _settings.WallRange > 0 + && CountMonstersInWallPath(_settings.WallRange, arcTargetId) >= Math.Max(1, _settings.MinWallTargets) + && (_host.HasTurnToHeading || GetFacingError(arcTargetId) <= WallFaceToleranceDeg)) + { + wallId = FindBestWallSpell(element); + wallDue = wallId != 0; + } + + int shapeIdx = ChooseCastShape(rule, blastConditional, blastFanMet, ringDue, wallDue, arcTargetId != 0 ? () => IsArcBlockedTo(arcTargetId) : null, out bool arcGaveWay); if (arcTargetId != 0) _lastShapeArcGaveWay = arcGaveWay; + if (shapeIdx == ShapeWall) + { + castShape = ShapeWall; + return wallId; + } + if (!TryGetShapeBase(element, shapeIdx, useVoid, out string baseName, out string? t7, out bool forcedWar)) return 0; if (forcedWar) skill = AcSkillType.WarMagic; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellDatabase.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellDatabase.cs index e0dc966..3fd4e6c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellDatabase.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellDatabase.cs @@ -8,6 +8,11 @@ namespace RynthCore.Plugin.RynthAi; public static class SpellDatabase { private static readonly Dictionary _spellNames = new(); + // The data's category (ACE SpellCategory, column 3) and power (difficulty, column 7) per id, + // and the ids of each category. Read for wall spells (2026-10-08): they have no tier in their + // names ("Slithering Flames"), so a wall is found by its category and ranked by its power. + private static readonly Dictionary _spellMeta = new(); + private static readonly Dictionary> _idsByCategory = new(); private static bool _loaded = false; private static readonly Dictionary _builtinSpells = new Dictionary @@ -38,6 +43,8 @@ public static class SpellDatabase public static void Load(Action? log = null) { _spellNames.Clear(); + _spellMeta.Clear(); + _idsByCategory.Clear(); _loaded = false; try @@ -59,7 +66,17 @@ public static class SpellDatabase if (string.IsNullOrWhiteSpace(line)) continue; string[] columns = line.Split('\t'); if (columns.Length >= 2 && int.TryParse(columns[0].Trim(), out int spellId)) + { _spellNames[spellId] = columns[1].Trim(); + if (columns.Length >= 7 && int.TryParse(columns[2].Trim(), out int category) + && int.TryParse(columns[6].Trim(), out int power)) + { + _spellMeta[spellId] = (category, power); + if (!_idsByCategory.TryGetValue(category, out List? ids)) + _idsByCategory[category] = ids = new List(); + ids.Add(spellId); + } + } } _loaded = _spellNames.Count > 0; @@ -93,6 +110,30 @@ public static class SpellDatabase return _spellNames.ContainsKey(spellId) || _builtinSpells.ContainsKey(spellId); } + /// The spell's category (ACE SpellCategory) and power from the data; false when the + /// spell isn't in it. + public static bool TryGetCategoryAndPower(int spellId, out int category, out int power) + { + if (_spellMeta.TryGetValue(spellId, out var m)) { category = m.Category; power = m.Power; return true; } + category = 0; power = 0; + return false; + } + + /// Every spell id of a category (ACE SpellCategory), in data order. + public static IReadOnlyList IdsInCategory(int category) + => _idsByCategory.TryGetValue(category, out List? ids) ? ids : Array.Empty(); + + /// + /// A spell's level by ACE's server formula (Spell.Level): the highest level whose minimum power + /// it reaches, 1/50/100/150/200/250/300/400 for levels 1-8 (SpellFormula.MinPower). The tiered + /// war lines have exactly those powers (Flame Bolt V 200, the tier-7 lore 300, Incantations + /// 400; blasts +25), so it is the same tier limit the other shapes use. 0 = no power. + /// + public static int LevelFromPower(int power) => power switch + { + >= 400 => 8, >= 300 => 7, >= 250 => 6, >= 200 => 5, >= 150 => 4, >= 100 => 3, >= 50 => 2, >= 1 => 1, _ => 0, + }; + /// Builds a name→id reverse map for SpellManager initialisation. public static Dictionary BuildNameToIdMap() { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs index 4c4d384..ba6b58a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellManager.cs @@ -194,7 +194,9 @@ public class SpellManager return 0; } - public int GetDynamicSelfBuffId(string baseSpellName, AcSkillType magicSkill) + /// Levels to pass over (a level the server refused for missing components): + /// the next lower known level is returned instead. + public int GetDynamicSelfBuffId(string baseSpellName, AcSkillType magicSkill, Func? skip = null) { RefreshKnownSpells(); // keep the authoritative inventory current (throttled) @@ -207,8 +209,8 @@ public class SpellManager for (int tier = maxTier; tier >= 1; tier--) { - if (TryGetTierId(cleanBase, tier, out int id)) return id; - if (alias != null && TryGetTierId(alias, tier, out int idAlias)) return idAlias; + if (TryGetTierId(cleanBase, tier, out int id) && (skip == null || !skip(id))) return id; + if (alias != null && TryGetTierId(alias, tier, out int idAlias) && (skip == null || !skip(idAlias))) return idAlias; } return 0; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs index 3c80162..7d4502c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs @@ -1840,6 +1840,24 @@ public class WorldObjectCache get { lock (_gate) return _hazardVersion; } } + /// + /// A dungeon cell the character took hotspot damage in ("You suffer 32 damage from acid!"): + /// registered and persisted like a sighted hazard, so the patrol reroutes around it now and + /// on every later visit. Outdoor cells (a 24 m land cell) are never registered. True when new. + /// + public bool RegisterDamageHazardCell(uint cellId, string source) + { + if (cellId == 0 || (cellId & 0xFFFF) < 0x0100) return false; + lock (_gate) + { + if (!_hazardCells.Add(cellId)) return false; + _hazardVersion++; + } + DungeonHazardStore.Append(cellId >> 16, cellId); + _host.Log($"[Hazard] took {source} damage in cell 0x{cellId:X8} (persisted)"); + return true; + } + public bool IsHazardCell(uint cellId) { lock (_gate) diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index 9678880..ba75bd4 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -98,6 +98,8 @@ public sealed partial class RynthAiPlugin private bool _corpseAutorunActive; private int _currentLootItemMoveAttempts; private long _currentLootItemStillSince; + private long _currentLootItemLeftAt; + private bool _currentLootItemSawAnim; private long _pickupAnimSince; private string _currentLootItemActionLabel = string.Empty; private string _currentLootItemName = string.Empty; @@ -1285,7 +1287,9 @@ public sealed partial class RynthAiPlugin pendingDataCount++; continue; } - // Still nameless well past the window — skip this item. + // Still nameless well past the window — skip this item (and say so: it used to + // leave nothing in the log, so a missed item couldn't be traced). + LootDiag($"[LootEval] 0x{(uint)item.Id:X8} on 0x{(uint)corpseId:X8} still has no name after the wait (value={item.Values(19, 0)} type=0x{item.Values(1, 0):X} wcid={item.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0)}) -> left"); _processedCorpseItems.Add(item.Id); continue; } @@ -1325,7 +1329,7 @@ public sealed partial class RynthAiPlugin // once the assess window expires, so an unappraised item can match a // rule it should not. If keeps correlate with appraised=False, that // is the cause. - LootDiag($"[LootEval] '{item.Name}' cls={item.ObjectClass} appraised={hasAppraisalData} timedOut={assessTimedOut} -> " + + 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")); if (classified) @@ -1463,6 +1467,20 @@ public sealed partial class RynthAiPlugin /// Longest a pickup waits on the motion queue (the engine's own hold is 2.5 s). internal const long PickupAnimMaxMs = 3000; + /// After the item leaves the corpse: how long to wait for its bend-down to start. + internal const long PickupSettleMs = 1000; + + /// Off the corpse but not seen in the inventory: counted after this anyway. + internal const long PickupArriveMaxMs = 4000; + + /// The container is the character or a pack it carries. + private bool InPlayerInventory(int containerId) + { + if (containerId == 0 || _playerId == 0 || _objectCache == null) return false; + int player = unchecked((int)_playerId); + return containerId == player || _objectCache.GetContainerId(containerId) == player; + } + /// /// The character still has motions queued (the engine's cast gate, GetCastBusyState): /// the bend-down of the last pickup is playing. False after PickupAnimMaxMs of it, so a @@ -1495,10 +1513,24 @@ public sealed partial class RynthAiPlugin int currentContainer = currentItem?.Container ?? 0; bool stillVisibleOnCorpse = IsCorpseItemVisible(_openedContainerId, _currentLootItemId); - // Check every tick — confirm immediately as soon as the item leaves the corpse. - // Don't gate this on a timer; the timer only applies to the RETRY path below. + // Watch for this pickup's bend-down (the server plays it once the move reaches it). + bool animating = PickupAnimating(now); + if (animating) _currentLootItemSawAnim = true; + + // Off the corpse is not done yet: confirming then closed the corpse while the pickup was + // still under way, and the character picked the last item up after the corpse closed + // (2026-10-07). It counts once the item shows up in the inventory (the main pack, a side + // pack, or merged into a stack already there: the picked object is gone) and its + // bend-down has played out. Off the corpse but never seen in the inventory: counted + // after PickupArriveMaxMs anyway, so looting can't stall on it. if (currentItem == null || !stillVisibleOnCorpse || (currentContainer != 0 && currentContainer != _openedContainerId)) { + if (_currentLootItemLeftAt == 0) _currentLootItemLeftAt = now; + bool inInventory = currentItem == null || InPlayerInventory(currentContainer); + long since = now - _currentLootItemLeftAt; + bool settled = !animating && (_currentLootItemSawAnim || since >= PickupSettleMs); + if (!(inInventory && settled) && since < PickupArriveMaxMs) + return; ConfirmCurrentLootItemMoved( now, currentItem == null @@ -2339,6 +2371,8 @@ public sealed partial class RynthAiPlugin _currentLootItemMoveRequestedAt = 0; _currentLootItemMoveAttempts = 0; _currentLootItemStillSince = 0; + _currentLootItemLeftAt = 0; + _currentLootItemSawAnim = false; _currentLootItemActionLabel = string.Empty; _currentLootItemName = string.Empty; _currentLootItemIsSalvage = false; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index 0da3631..5694b3a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -184,6 +184,14 @@ internal sealed class LegacyAdvancedSettingsUi catch { return false; } } + /// One cell of the Protections and Banes grid: ticked = cast it. + private void BuffToggle((string Buff, string Label) toggle) + { + bool on = !_settings.IsBuffDisabled(toggle.Buff); + if (ImGui.Checkbox($"{toggle.Label}##buff_{toggle.Buff}", ref on)) + _settings.SetBuffEnabled(toggle.Buff, on); + } + private void RenderTabContent(int tabIndex) { if (tabIndex < 0 || tabIndex >= _settings.AdvancedTabs.Length) @@ -265,6 +273,9 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Checkbox("Patrol On Login", ref _settings.PatrolOnLogin); if (ImGui.IsItemHovered()) ImGui.SetTooltip("Automatically starts dungeon patrol when RynthAi loads."); + ImGui.Checkbox("Escape Acid and Lava", ref _settings.EscapeHazards); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("When acid or lava hurts you, stop everything (combat, buffs, healing, looting)\nand walk back out the way you came. The spot is remembered so the patrol avoids it.\nTurn off for a character that walks through acid on purpose."); ImGui.Checkbox("Enable Raycasting", ref _settings.EnableRaycasting); ImGui.Separator(); @@ -496,12 +507,12 @@ internal sealed class LegacyAdvancedSettingsUi "Below 200ms may cause fizzles or dropped casts on laggy servers."); ImGui.SetNextItemWidth(180); - ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 250, 5000); + ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 0, 5000); if (ImGui.IsItemHovered()) ImGui.SetTooltip( - "Delay between offensive (war/void) COMBAT casts only.\n" + - "Spacing casts ~1-2s (1500ms default) stops back-to-back\n" + - "\"You're too busy!\" refusals that drop casts and cost kills.\n" + + "Least time between offensive (war/void) COMBAT casts at one target.\n" + + "The next cast also waits until the last one is finished (the server's\n" + + "answer and the casting animation), so 0 = cast again as soon as it is.\n" + "Does NOT affect buffing speed."); ImGui.Spacing(); @@ -515,6 +526,12 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.InputInt("Min Blast Targets", ref _settings.MinBlastTargets); if (ImGui.IsItemHovered()) ImGui.SetTooltip("If this many monsters are within ring range, ring spells are used instead of arc/bolt/streak."); + ImGui.InputInt("Wall Range (0 = off)", ref _settings.WallRange); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Monster rules with Wall on cast their element's wall spell when enough monsters\n" + + "are within this many yards in the wall's path toward the target.\n" + + "The character turns to face the target first. 0 = no walls."); + ImGui.InputInt("Min Wall Targets", ref _settings.MinWallTargets); ImGui.Spacing(); ImGui.Separator(); @@ -727,6 +744,31 @@ internal sealed class LegacyAdvancedSettingsUi "For servers with buff augments, where your own cast is stronger or\n" + "lasts longer. On by default: on retail it costs a few extra casts."); + ImGui.Spacing(); + ImGui.Separator(); + ImGui.Text("Protections and Banes"); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip( + "Untick a protection or bane to stop the bot casting it.\n" + + "Unticked buffs are skipped and never hold the bot in Buffing.\n" + + "All on by default."); + if (ImGui.BeginTable("##protsBanes", 2, ImGuiTableFlags.SizingStretchSame)) + { + ImGui.TableSetupColumn("Protections"); + ImGui.TableSetupColumn("Banes"); + ImGui.TableHeadersRow(); + int rows = Math.Max(BuffManager.ToggleProtections.Length, BuffManager.ToggleBanes.Length); + for (int i = 0; i < rows; i++) + { + ImGui.TableNextRow(); + ImGui.TableSetColumnIndex(0); + if (i < BuffManager.ToggleProtections.Length) BuffToggle(BuffManager.ToggleProtections[i]); + ImGui.TableSetColumnIndex(1); + if (i < BuffManager.ToggleBanes.Length) BuffToggle(BuffManager.ToggleBanes[i]); + } + ImGui.EndTable(); + } + ImGui.Spacing(); ImGui.Separator(); ImGui.Text("Buff Difficulty (Min Buffed Skill)"); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index f023612..f56e36b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -989,6 +989,8 @@ internal sealed class LegacyDashboardRenderer MinRingTargets = s.MinRingTargets, BlastRange = s.BlastRange, MinBlastTargets = s.MinBlastTargets, + WallRange = s.WallRange, + MinWallTargets = s.MinWallTargets, MinSkillLevelTier1 = s.MinSkillLevelTier1, MinSkillLevelTier2 = s.MinSkillLevelTier2, MinSkillLevelTier3 = s.MinSkillLevelTier3, @@ -1039,6 +1041,7 @@ internal sealed class LegacyDashboardRenderer RebuffSecondsRemaining = s.RebuffSecondsRemaining, RebuffTopOffSecondsRemaining = s.RebuffTopOffSecondsRemaining, CastBuffsOverItemBuffs = s.CastBuffsOverItemBuffs, + DisabledBuffs = new List(s.DisabledBuffs), BuffMinSkillLevelTier1 = s.BuffMinSkillLevelTier1, BuffMinSkillLevelTier2 = s.BuffMinSkillLevelTier2, BuffMinSkillLevelTier3 = s.BuffMinSkillLevelTier3, @@ -1060,6 +1063,7 @@ internal sealed class LegacyDashboardRenderer LootJumpHeight = s.LootJumpHeight, LootOwnership = s.LootOwnership, LootOwnCorpse = s.LootOwnCorpse, + EscapeHazards = s.EscapeHazards, TravelToOwnCorpse = s.TravelToOwnCorpse, ItemInfoOnSelect = s.ItemInfoOnSelect, EnableAutostack = s.EnableAutostack, @@ -1192,11 +1196,13 @@ internal sealed class LegacyDashboardRenderer s.PetMinMonsters = p.PetMinMonsters; // Spell Combat s.SpellCastIntervalMs = p.SpellCastIntervalMs; - s.AttackSpellIntervalMs = p.AttackSpellIntervalMs; + if (p.AttackSpellIntervalMs is int attackDelay) s.AttackSpellIntervalMs = attackDelay; // absent = unchanged s.CastDispelSelf = p.CastDispelSelf; s.MinRingTargets = p.MinRingTargets; s.BlastRange = p.BlastRange; s.MinBlastTargets = p.MinBlastTargets; + if (p.WallRange is int wallRange) s.WallRange = wallRange; // null = an engine without walls + if (p.MinWallTargets is int minWall) s.MinWallTargets = minWall; s.MinSkillLevelTier1 = p.MinSkillLevelTier1; s.MinSkillLevelTier2 = p.MinSkillLevelTier2; s.MinSkillLevelTier3 = p.MinSkillLevelTier3; @@ -1247,6 +1253,7 @@ internal sealed class LegacyDashboardRenderer s.RebuffSecondsRemaining = p.RebuffSecondsRemaining; if (p.RebuffTopOffSecondsRemaining > 0) s.RebuffTopOffSecondsRemaining = p.RebuffTopOffSecondsRemaining; if (p.CastBuffsOverItemBuffs is bool castOverItems) s.CastBuffsOverItemBuffs = castOverItems; // absent = unchanged + if (p.DisabledBuffs is { } disabledBuffs) s.DisabledBuffs = new List(disabledBuffs); // absent = unchanged s.BuffMinSkillLevelTier1 = p.BuffMinSkillLevelTier1; s.BuffMinSkillLevelTier2 = p.BuffMinSkillLevelTier2; s.BuffMinSkillLevelTier3 = p.BuffMinSkillLevelTier3; @@ -1264,6 +1271,7 @@ internal sealed class LegacyDashboardRenderer s.LootJumpEnabled = p.LootJumpEnabled; s.LootJumpHeight = p.LootJumpHeight; s.LootOwnership = p.LootOwnership; + if (p.EscapeHazards is bool escape) s.EscapeHazards = escape; // absent = unchanged if (p.LootOwnCorpse is bool lootOwn) s.LootOwnCorpse = lootOwn; // absent = unchanged if (p.TravelToOwnCorpse is bool travelOwn) s.TravelToOwnCorpse = travelOwn; // absent = unchanged if (p.ItemInfoOnSelect is bool infoOnSelect) s.ItemInfoOnSelect = infoOnSelect; // absent = unchanged @@ -1647,6 +1655,8 @@ internal sealed class LegacyDashboardRenderer dst.MinRingTargets = tmp.MinRingTargets; dst.BlastRange = tmp.BlastRange; dst.MinBlastTargets = tmp.MinBlastTargets; + dst.WallRange = tmp.WallRange; + dst.MinWallTargets = tmp.MinWallTargets; dst.FollowNavMin = tmp.FollowNavMin; dst.NavRingThickness = tmp.NavRingThickness; dst.NavLineThickness = tmp.NavLineThickness; @@ -1668,6 +1678,7 @@ internal sealed class LegacyDashboardRenderer dst.AutoUnlockDoors = tmp.AutoUnlockDoors; dst.LootOwnership = tmp.LootOwnership; dst.LootOwnCorpse = tmp.LootOwnCorpse; + dst.EscapeHazards = tmp.EscapeHazards; dst.TravelToOwnCorpse = tmp.TravelToOwnCorpse; dst.ItemInfoOnSelect = tmp.ItemInfoOnSelect; dst.LootOnlyRareCorpses = tmp.LootOnlyRareCorpses; @@ -1676,6 +1687,7 @@ internal sealed class LegacyDashboardRenderer dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining; dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining; dst.CastBuffsOverItemBuffs = tmp.CastBuffsOverItemBuffs; + dst.DisabledBuffs = tmp.DisabledBuffs; dst.BlacklistAttempts = tmp.BlacklistAttempts; dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec; // 0 is never meant (every UI floors it at 250+) and is what the Settings-panel bug @@ -2101,28 +2113,41 @@ internal sealed class LegacyDashboardRenderer _selectedNavIdx = sel; } - private DateTime _navFolderStamp; + private DateTime _navFolderStamp, _lootFolderStamp, _metaFolderStamp, _profileFolderStamp; private long _nextNavFolderCheckMs; /// - /// Lists NavProfiles again when the folder changed since the last look (a route saved there by - /// RynthNav's "save as nav route", or a file copied in), so the Nav picker shows it without a - /// relog. One folder time check every 3 s. Plugin tick. + /// Lists a folder again when it changed since the last look (a file added, removed or renamed: + /// a route saved by RynthNav's "save as nav route", a loot profile or meta copied in, a settings + /// profile saved), so its picker shows it without a relog or a reload. NavProfiles since + /// 2026-10; LootProfiles, MetaFiles and the character's settings profiles since 2026-10-08 + /// (a loot profile copied in didn't show until a hot reload). One folder time check each every + /// 3 s. Plugin tick. /// public void TickNavFolder() { long now = Environment.TickCount64; if (now < _nextNavFolderCheckMs) return; _nextNavFolderCheckMs = now + 3000; + if (FolderChanged(_navFolder, ref _navFolderStamp)) RefreshNavFiles(); + if (FolderChanged(_lootFolder, ref _lootFolderStamp)) RefreshLootFiles(); + if (FolderChanged(_metaFolder, ref _metaFolderStamp)) RefreshMetaFiles(); + if (FolderChanged(_charFolder, ref _profileFolderStamp)) RefreshProfilesList(); + } + + /// True when 's write time moved since the last call (never on + /// the first look, which only records it: the lists were built at load). + private static bool FolderChanged(string? folder, ref DateTime stamp) + { try { - DateTime stamp = Directory.Exists(_navFolder) ? Directory.GetLastWriteTimeUtc(_navFolder) : DateTime.MinValue; - if (stamp == _navFolderStamp) return; - bool first = _navFolderStamp == default; - _navFolderStamp = stamp; - if (!first) RefreshNavFiles(); + DateTime now = !string.IsNullOrEmpty(folder) && Directory.Exists(folder) ? Directory.GetLastWriteTimeUtc(folder) : DateTime.MinValue; + if (now == stamp) return false; + bool first = stamp == default; + stamp = now; + return !first; } - catch { } + catch { return false; } } /// Save button and /ra nav save [name]. Returns the chat line. diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs index 579659a..72fb301 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs @@ -143,7 +143,7 @@ internal sealed class LegacyNavigationUi for (int ri = 0; ri < ids.Length; ri++) { - string name = $"Spell {ids[ri]}"; + string name = NavPoint.RecallName(ids[ri]); if (ImGui.Selectable($"{name} ({ids[ri]})")) { if (_host.HasGetPlayerPose && _host.TryGetPlayerPose(out _, out float x, out float y, out float z, out _, out _, out _, out _)) diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index 110d5f1..9856c5d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -159,6 +159,12 @@ public sealed class LegacyUiSettings // degrees) toward the target; otherwise its other shape. 0 = off: Blast is just a shape. public int BlastRange = 0; public int MinBlastTargets = 3; + // Wall spells (2026-10-08): with WallRange > 0, a rule with Wall on casts its element's wall + // (Slithering Flames, Os' Wall...) when MinWallTargets monsters are within WallRange in the + // wall's path toward the target, turning to face the target first (a wall flies along the + // caster's facing). Below a due ring, above a due blast. 0 = off: no walls at all. + public int WallRange = 0; + public int MinWallTargets = 3; // Nav point reach (VTank "Follow/Nav Min Distance"), yards: how close nav gets to each // nav point before moving on to the next, and how close Follow gets to its leader. // Metas set it as FollowNavMin (yards) or VTank's NavCloseStopRange (landblock units, @@ -202,6 +208,13 @@ public sealed class LegacyUiSettings /// public bool LootOwnCorpse = true; /// + /// Out of acid or lava at once (RynthAiPlugin.HazardEscape.cs): the first hotspot hit stops + /// everything and walks back out, and the spot becomes a hazard the patrol avoids. On by + /// default (2026-10-07); off for characters that walk through acid on purpose (then the spot + /// isn't learned either). A profile saved before this setting loads it as on. + /// + public bool EscapeHazards = true; + /// /// After a death and respawn, travel back to where you died (RynthNav, outdoors only), fight /// on the way as usual, recover the corpse, then carry on. Off by default. /// @@ -237,6 +250,35 @@ public sealed class LegacyUiSettings /// as on for good (the behaviour before 2026-10-05). /// public bool CastBuffsOverItemBuffs = true; + /// + /// Buff base names the player unticked in Buffing settings (the Protections and Banes grid, + /// e.g. "Fire Protection Self", "Flame Bane"): left out of the buff list, so never cast and + /// never waited on. Empty = every buff on, which is also what a profile saved before this + /// setting existed loads as. Replaced, not edited in place (SetBuffEnabled), so a reader + /// holding the old list never sees it change under it. + /// + public List DisabledBuffs + { + get => _disabledBuffs; + set => _disabledBuffs = value ?? new List(); + } + private List _disabledBuffs = new(); + + public bool IsBuffDisabled(string buffBaseName) + { + foreach (string b in _disabledBuffs) + if (string.Equals(b, buffBaseName, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + public void SetBuffEnabled(string buffBaseName, bool enabled) + { + if (enabled == !IsBuffDisabled(buffBaseName)) return; + var next = new List(_disabledBuffs); + if (enabled) next.RemoveAll(b => string.Equals(b, buffBaseName, StringComparison.OrdinalIgnoreCase)); + else next.Add(buffBaseName); + _disabledBuffs = next; + } public bool StartMacroOnLogin; public bool PatrolOnLogin; /// @@ -631,6 +673,10 @@ public sealed class MonsterRule /// Blast spells (Flame Blast, Frost Blast...: a spread of projectiles). Off in files /// from before 2026-10-03. Wins over Bolt when both are on; see CombatManager.PickBaseShape. public bool UseBlast { get; set; } + /// Wall spells (Slithering Flames, Os' Wall...: a row of projectiles flying straight + /// ahead). An override like the ring, cast only with Wall Range on and enough monsters in the + /// wall's path; a wall-only rule casts Bolt between walls. Off in files from before 2026-10-08. + public bool UseWall { get; set; } public string ExVuln { get; set; } = "None"; /// The off hand for this rule: 0 = the global setting (OffhandDefault), 1 Auto, /// 2 Shield, 3 Offhand weapon, 4 None (OffhandRules.Rule*); any other value is a listed @@ -822,11 +868,16 @@ public sealed class SettingsBridgePayload // Spell Combat public int SpellCastIntervalMs { get; set; } - public int AttackSpellIntervalMs { get; set; } + // Nullable since 0 became a real value (2026-10-08): a file without it keeps the default. + public int? AttackSpellIntervalMs { get; set; } public bool CastDispelSelf { get; set; } public int MinRingTargets { get; set; } public int BlastRange { get; set; } public int MinBlastTargets { get; set; } = 3; // absent from an older engine: keep the default + // Walls (2026-10-08): null = sent by an engine without the Wall Range control, which then + // leaves the plugin's own values alone (a profile's or a meta's) instead of zeroing them. + public int? WallRange { get; set; } + public int? MinWallTargets { get; set; } public int MinSkillLevelTier1 { get; set; } public int MinSkillLevelTier2 { get; set; } public int MinSkillLevelTier3 { get; set; } @@ -883,6 +934,8 @@ public sealed class SettingsBridgePayload // Nullable: an engine that predates the setting doesn't send it, and a save from its // Settings face must leave the setting alone rather than force it either way. public bool? CastBuffsOverItemBuffs { get; set; } + // Null (absent) likewise leaves the unticked prots/banes alone; an empty list ticks them all. + public List? DisabledBuffs { get; set; } public int BuffMinSkillLevelTier1 { get; set; } public int BuffMinSkillLevelTier2 { get; set; } public int BuffMinSkillLevelTier3 { get; set; } @@ -908,6 +961,7 @@ public sealed class SettingsBridgePayload // Nullable, as CastBuffsOverItemBuffs: an engine that predates them doesn't send them, // and its save must leave them alone. public bool? LootOwnCorpse { get; set; } + public bool? EscapeHazards { get; set; } public bool? TravelToOwnCorpse { get; set; } public bool? ItemInfoOnSelect { get; set; } public bool EnableAutostack { get; set; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs index 0a6b84e..26d2c91 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs @@ -74,12 +74,24 @@ public sealed class NavPoint /// public bool Doorway { get; set; } + /// "Lifestone Recall": a recall step by its spell's name (it showed "Spell 1635", + /// 2026-10-08); the id when the spell table doesn't know it. + internal static string RecallName(int spellId) + { + string? name = SpellNameLookup?.Invoke(spellId); + return string.IsNullOrEmpty(name) ? $"Spell {spellId}" : name; + } + + /// The spell table's name for an id; RynthAi sets it (this file is also compiled into + /// tools without the spell table, which keep "Spell N"). + internal static Func? SpellNameLookup { get; set; } + public override string ToString() { return Type switch { NavPointType.Point => $"[Point] {NS:F3}, {EW:F3}", - NavPointType.Recall => $"[Recall] Spell {SpellId}", + NavPointType.Recall => $"[Recall] {RecallName(SpellId)}", NavPointType.Pause => $"[Pause] {PauseTimeMs / 1000.0:F1}s", NavPointType.Chat => $"[Chat] {ChatCommand}", NavPointType.OpenVendor => $"[Vendor] {TargetName}", diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs index 22ca87f..e75a3b3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs @@ -182,8 +182,10 @@ internal sealed class LootEditorBridge if (id == 0) return Refuse(d, "No item selected. Click an item first."); d.ItemId = id; var match = (LootItemMatch)Math.Clamp(req.Match, 0, 2); - LootItemFacts? facts = Items.Facts(id, match == LootItemMatch.Like); + d.IncludeT11 = req.IncludeT11; + LootItemFacts? facts = Items.Facts(id, match == LootItemMatch.Like, req.IncludeT11); if (facts == null) return Refuse(d, $"RynthAi doesn't know item 0x{id:X8} yet. Select it again in a moment."); + d.IsT11 = facts.T11?.IsT11 == true; d.ItemName = facts.Name; d.ClassName = LootItemRules.ClassName(facts.ObjectClass); d.Stackable = facts.Stackable; @@ -207,6 +209,7 @@ internal sealed class LootEditorBridge Action = req.Action == 0 ? null : (VTankLootAction)req.Action, KeepCount = req.KeepCount < 0 ? null : req.KeepCount, RuleName = req.RuleName, + IncludeT11 = req.IncludeT11, }; LootItemRuleDraft? draft = LootItemRules.Build(facts, options, out string error); if (draft == null) return Refuse(d, error); @@ -336,8 +339,11 @@ internal sealed class LootItemHooks { /// The item selected in the game, or 0. public Func SelectedItemId { get; set; } = () => 0; - /// The item's facts from the object cache, or null. The bool: "items like this" (ask for an ID if it isn't identified). - public Func Facts { get; set; } = (_, _) => null; + /// + /// The item's facts from the object cache, or null. The bools: "items like this" and + /// "include T11 attributes"; either asks for an ID when the item isn't identified. + /// + public Func Facts { get; set; } = (_, _, _) => null; /// The first rule of the .utl profile that matches the item now, or -1. public Func FirstMatchUtl { get; set; } = (_, _) => -1; /// The first rule of the native profile that matches the item now, or -1. diff --git a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs index 1125ac2..2f16781 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs @@ -110,8 +110,11 @@ internal sealed class ManaStoneManager // off or the macro is stopped must leave the set too. PruneLootedForTap(NowMs); - // An Eternal Mana Charge refills gear for free, so it works with tapping off too. - if (!_settings.EnableManaTapping && !HasEternalCharge()) { Reset(); return; } + // Refilling worn gear from a charged stone (or a free Eternal charge) works with tapping + // off too; only draining loot into empty stones needs tapping on. It used to need tapping + // on for any refill, so charged stones and bought Mana Charges were never used with it + // off (2026-10-08). + if (!_settings.EnableManaTapping && !HasChargedRefillStone()) { Reset(); return; } if (!_settings.IsMacroRunning) { Reset(); return; } long now = NowMs; @@ -487,12 +490,23 @@ internal sealed class ManaStoneManager if (hasRule) return false; // explicit rules → match by name only if (!_settings.EnableManaTapping) return false; // no rules → auto-detect only when tapping is on - if (item.ObjectClass == AcObjectClass.ManaStone) return true; - return !string.IsNullOrEmpty(item.Name) - && (item.Name.Contains("Mana Stone", StringComparison.OrdinalIgnoreCase) - || item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase)); + // Only the ordinary tapping stones and mana charges. Retail also has special stones + // (Aligned, Aetheria, Unstable, Enchanted, Adjanite Mana Stone) that are not for + // draining or recharging: an Aligned Mana Stone was used on a wand (2026-10-08). A + // special stone is only touched when a ManaStone consumable rule names it. + if (string.IsNullOrEmpty(item.Name)) + return item.ObjectClass == AcObjectClass.ManaStone; // unnamed yet: the class decides (looting) + return OrdinaryStoneNames.Contains(item.Name) + || item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase); } + /// The retail tapping stones (ACE world data names), smallest to largest. + internal static readonly HashSet OrdinaryStoneNames = new(StringComparer.OrdinalIgnoreCase) + { + "Minor Mana Stone", "Lesser Mana Stone", "Moderate Mana Stone", "Mana Stone", + "Greater Mana Stone", "Major Mana Stone", + }; + /// /// An unlimited mana charge (Eternal Mana Charge: 10,000 mana, never used up). Always /// "charged", never an empty stone to drain into, and preferred for refilling gear. @@ -500,6 +514,35 @@ internal sealed class ManaStoneManager private static bool IsEternal(WorldObject item) => !string.IsNullOrEmpty(item.Name) && item.Name.StartsWith("Eternal Mana", StringComparison.OrdinalIgnoreCase); + /// + /// A stone that may refill worn gear when charged: what takes, but + /// with tapping off as well (no rules: the ordinary stones and mana charges; with ManaStone + /// rules: the named ones). + /// + internal bool IsRefillStone(WorldObject item) + { + if (IsManaStone(item)) return true; + if (_settings.EnableManaTapping || string.IsNullOrEmpty(item.Name)) return false; + foreach (var rule in _settings.ConsumableRules) + if (rule.Type.Equals("ManaStone", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(rule.Name)) + return false; // rules decide (IsManaStone already said no) + return OrdinaryStoneNames.Contains(item.Name) + || item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase); + } + + // FindChargedStone walks every known object; with tapping off it gates the whole tick, so + // the answer is kept for a few seconds. + private long _chargedCheckAt; + private bool _chargedCached; + private bool HasChargedRefillStone() + { + long now = NowMs; + if (now - _chargedCheckAt < 5000) return _chargedCached; + _chargedCheckAt = now; + _chargedCached = HasEternalCharge() || FindChargedStone() != 0; + return _chargedCached; + } + private bool HasEternalCharge() { int playerId = unchecked((int)_host.GetPlayerId()); @@ -608,7 +651,7 @@ internal sealed class ManaStoneManager foreach (var item in _objectCache.AllKnownObjects()) { - if (!IsManaStone(item)) continue; + if (!IsRefillStone(item)) continue; if (!IsOwnedByPlayer(item, playerId)) continue; // Skip stones that timed out on use-on-player recently. @@ -617,7 +660,6 @@ 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 (!_settings.EnableManaTapping) continue; // tapping off: only the free charge if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int cur)) continue; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs index a10fd2d..643014a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs @@ -344,7 +344,7 @@ internal static class AfFileWriter 5543 => "Neftet Recall", 6321 => "Rynthid Recall", 6322 => "Viridian Rise Recall", - _ => $"Spell {spellId}" + _ => NavPoint.RecallName(spellId) }; } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index e6157a2..a3421c9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -349,7 +349,8 @@ internal sealed class ExpressionEngine "wobjectfindallinventorybynamerx" => EvalWobjectFindAllInventoryByNameRx(Tmpl(0)), "wobjectfindininventorybyname" => EvalWobjectFindInInventoryByName(Tmpl(0)), "wobjectfindininventorybynamerx" => EvalWobjectFindInInventoryByNameRx(Tmpl(0)), - "wobjectfindalllandscapebytemplatetype" => EvalWobjectFindAllLandscapeByTemplateType(A(0)), + "wobjectfindalllandscapebyobjectclass" => EvalWobjectFindAllLandscapeByObjectClass(A(0)), + "wobjectfindalllandscapebytemplatetype" =>EvalWobjectFindAllLandscapeByTemplateType(A(0)), "wobjectfindalllandscapebynamerx" => EvalWobjectFindAllLandscapeByNameRx(Tmpl(0)), "wobjectfindallbycontainer" => EvalWobjectFindAllByContainer(A(0)), "wobjectgetselection" => EvalWobjectGetSelection(), @@ -1642,6 +1643,24 @@ internal sealed class ExpressionEngine return NewList(items); } + private string EvalWobjectFindAllLandscapeByObjectClass(string arg) + { + if (_worldObjectCache == null) return "[]"; + if (!int.TryParse(arg.Trim(), out int targetClass)) return "[]"; + + var items = new List(); + var seen = new System.Collections.Generic.HashSet(); + void Check(WorldObject wo) + { + if (!seen.Add(wo.Id)) return; + if (ResolveEffectiveObjectClass(wo) == targetClass) + items.Add(MakeWobjectHandle(unchecked((uint)wo.Id), wo.Name)); + } + foreach (var wo in _worldObjectCache.GetLandscapeObjects()) Check(wo); + foreach (var wo in _worldObjectCache.GetLandscape()) Check(wo); + return NewList(items); + } + private string EvalWobjectFindAllLandscapeByTemplateType(string arg) { if (_worldObjectCache == null || !_host.HasGetObjectWcid) return "[]"; @@ -2420,8 +2439,7 @@ internal sealed class ExpressionEngine if (!TryParseWobjectHandle(arg, out uint uid, out _) || uid == 0) return "0"; if (!_host.HasSelectItem) return "0"; RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(uid); - _host.SelectItem(uid); - return "0"; + return _host.SelectItem(uid) ? "1" : "0"; } private string EvalActionTryUseItem(string arg) @@ -3318,6 +3336,7 @@ internal sealed class ExpressionEngine ["StopMacroOnNoComponents"] = (() => B(s.StopMacroOnNoComponents), v => s.StopMacroOnNoComponents = ToDouble(v) != 0), ["StopLootingWhenPackFull"] = (() => B(s.StopLootingWhenPackFull), v => s.StopLootingWhenPackFull = ToDouble(v) != 0), ["LootOwnCorpse"] = (() => B(s.LootOwnCorpse), v => s.LootOwnCorpse = ToDouble(v) != 0), + ["EscapeHazards"] = (() => B(s.EscapeHazards), v => s.EscapeHazards = ToDouble(v) != 0), ["TravelToOwnCorpse"] = (() => B(s.TravelToOwnCorpse), v => s.TravelToOwnCorpse = ToDouble(v) != 0), ["ItemInfoOnSelect"] = (() => B(s.ItemInfoOnSelect), v => s.ItemInfoOnSelect = ToDouble(v) != 0), ["StopMacroWhenPackFull"] = (() => B(s.StopMacroWhenPackFull), v => s.StopMacroWhenPackFull = ToDouble(v) != 0), @@ -3338,6 +3357,8 @@ internal sealed class ExpressionEngine ["MinRingTargets"] = (() => I(s.MinRingTargets), v => { if (int.TryParse(v, out int i)) s.MinRingTargets = i; }), ["BlastRange"] = (() => I(s.BlastRange), v => { if (int.TryParse(v, out int i)) s.BlastRange = i; }), ["MinBlastTargets"] = (() => I(s.MinBlastTargets), v => { if (int.TryParse(v, out int i)) s.MinBlastTargets = i; }), + ["WallRange"] = (() => I(s.WallRange), v => { if (int.TryParse(v, out int i)) s.WallRange = i; }), + ["MinWallTargets"] = (() => I(s.MinWallTargets), v => { if (int.TryParse(v, out int i)) s.MinWallTargets = i; }), ["HealAt"] = (() => I(s.HealAt), v => { if (int.TryParse(v, out int i)) s.HealAt = i; }), ["RestamAt"] = (() => I(s.RestamAt), v => { if (int.TryParse(v, out int i)) s.RestamAt = i; }), ["RestamTo"] = (() => I(s.RestamTo), v => { if (int.TryParse(v, out int i)) s.RestamTo = i; }), diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs index da7361d..7b98ee5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs @@ -1761,7 +1761,7 @@ internal sealed class NavigationEngine // teleport happened but wasn't seen, or the route stays on this side). if (NextWalkTargetBeyond(route, _settings.ActiveNavIndex, OffTrackYards, out int farIdx, out double farYd)) { - string what = pt.Type == NavPointType.Recall ? $"the recall (spell {pt.SpellId})" : $"the portal '{pt.TargetName}'"; + string what = pt.Type == NavPointType.Recall ? $"the recall ({NavPoint.RecallName(pt.SpellId)})" : $"the portal '{pt.TargetName}'"; string msg = $"Nav: {what} didn't teleport within {ActionTimeoutMs / 1000:F0}s, and the next waypoint [{farIdx}] is {farYd:F0}yd away - navigation stopped."; _host.Log(msg); _host.WriteToChat(msg, 1); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 485a9e9..3911895 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -1603,8 +1603,12 @@ public sealed partial class RynthAiPlugin if (inUse) ReloadLootProfileInUse(d.TargetPath); } - /// What a loot rule can be built from: the item's name, class, stack and key properties, from the object cache. - private RynthCore.Loot.Editing.LootItemFacts? BuildLootItemFacts(uint itemId, bool like) + /// + /// What a loot rule can be built from: the item's name, class, stack, key properties and + /// T11 reading, from the object cache. adds its spells; + /// asks for an ID when a T11 item's text hasn't arrived. + /// + private RynthCore.Loot.Editing.LootItemFacts? BuildLootItemFacts(uint itemId, bool like, bool t11) { WorldObject? wo = _objectCache?[unchecked((int)itemId)]; if (wo == null) return null; @@ -1634,6 +1638,10 @@ public sealed partial class RynthAiPlugin // Material, workmanship and spells need an ID: ask for one, so the next preview has them. if (Host.HasRequestId && Host.HasHasAppraisalData && !Host.HasAppraisalData(itemId)) Host.RequestId(itemId); } + // Always read (a cached parse), so the popup knows whether the T11 option applies. + f.T11 = Loot.T11ItemSupport.Get(wo); + // T11 tier, grade and modifiers are appraisal text: ask for it, so the next preview has them. + if (t11 && f.T11.IsT11 && !f.T11.HasText && Host.HasRequestId) Host.RequestId(itemId); return f; } @@ -1656,17 +1664,18 @@ public sealed partial class RynthAiPlugin } /// - /// /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview]: a rule for + /// /ra loot add [keep|keep N|salvage|sell|read] [name|like] [t11] [preview]: a rule for /// the selected item, straight into the loot profile in use (the defaults: exact /// name and class; Read for scrolls, Keep # one full stack for stacks, else Keep). + /// t11 also requires the item's T11 attributes. /// private void HandleLootCommand(string[] parts) { string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty; if (sub != "add") { - ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item to the loot profile in use"); - ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. preview = show it, add nothing."); + ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [t11] [preview] — add a loot rule for the selected item to the loot profile in use"); + ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. t11 = also require its T11 tier, grade and modifiers (at least this good). preview = show it, add nothing."); ChatLine("[RynthAi] Also: right-click an item in the Inventory panel, or 'Add selected item' in the Loot Editor."); return; } @@ -1686,6 +1695,7 @@ public sealed partial class RynthAiPlugin case "name": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.Name; break; case "like": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.Like; break; case "exact": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.NameAndClass; break; + case "t11": req.IncludeT11 = true; break; case "preview": case "?": preview = true; break; default: @@ -1695,7 +1705,7 @@ public sealed partial class RynthAiPlugin req.KeepCount = n; break; } - ChatLine($"[RynthAi] loot add: '{parts[i]}'? Use keep, keep N, salvage, sell, read, name, like or preview."); + ChatLine($"[RynthAi] loot add: '{parts[i]}'? Use keep, keep N, salvage, sell, read, name, like, t11 or preview."); return; } } @@ -2879,6 +2889,11 @@ public sealed partial class RynthAiPlugin return; } settings.IsMacroRunning = true; + // The patrol picked its own start (the first waypoint in sight). Starting the macro + // here must not also trigger the macro-start "nearest waypoint" pick on the next + // tick: on a loop that is often a waypoint near the END (it comes back to the start), + // so the bot walked there, back to waypoint 0, and only then on (2026-10-08). + _macroWasRunning = true; } settings.CurrentNavPath = string.Empty; settings.CurrentRoute = route; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HazardEscape.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HazardEscape.cs new file mode 100644 index 0000000..a435671 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HazardEscape.cs @@ -0,0 +1,323 @@ +using System; +using System.Text.RegularExpressions; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Out of the acid at once. A hotspot (an acid or lava pool, ACE's Hotspot) hurts every couple of +/// seconds while you stand in it and says so: "You suffer 32 damage from acid!". On 2026-10-07 +/// Drakkon died twice that way in an hour: the patrol (once after a reload, once after a fight) +/// left him in a pool the hazard list didn't know, and topping up with healing kits held him there +/// - every kit stopped him, the acid matched each kit, and the kits ran his stamina out. +/// +/// Now the first hotspot hit, while the macro runs, stops everything (combat, buffs, healing, +/// 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. +/// +public sealed partial class RynthAiPlugin +{ + /// The escape clock (ms); host tests replace it. + internal static Func HazardClock = static () => Environment.TickCount64; + + /// No hit for this long = out of it (hotspots hit about every 2.5-3.5 s). + internal const long HazardQuietMs = 4000; + /// An escape that hasn't got out by then gives the tick back (and says so). + internal const long HazardEscapeMaxMs = 20000; + private const long HazardTrailSampleMs = 250; + private const int HazardTrailSize = 80; // 20 s of positions + private const double HazardArriveMeters = 0.6; + /// A footstep on the way counts as passed this close (the target needs HazardArriveMeters). + private const double HazardStepMeters = 1.0; + private const double HazardMinBackMeters = 2.5; + /// A trail point this long before the first hit is taken as outside the pool. + private const long HazardBeforeHitMs = 750; + + private static readonly Regex HotspotDamageRx = new( + @"^You suffer (\d+) (?:points of )?damage from (?:the )?([A-Za-z][A-Za-z ]*?)[.!]*$", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + private readonly (long At, uint Cell, float X, float Y)[] _hazardTrail = new (long, uint, float, float)[HazardTrailSize]; + private int _hazardTrailHead; + private int _hazardTrailCount; + private long _hazardTrailLastAt; + + private long _hazardLastHitAt; + private long _hazardFirstHitAt; + private long _hazardEscapeSince; // 0 = not escaping + private long _hazardArrivedAt; // 0 = still running to the target + private bool _hazardHasTarget; + private uint _hazardTargetCell; + private float _hazardTargetX, _hazardTargetY; + private long _hazardTargetAt; // the trail time of the target (older = further back) + /// The footsteps back to the target, newest first; the last one is the target. + private readonly System.Collections.Generic.List<(uint Cell, float X, float Y)> _hazardPath = new(); + private int _hazardPathIdx; + private bool _hazardRunning; + private long _hazardRunBeatAt; + private string _hazardSource = ""; + + /// True while the escape owns the character. + internal bool HazardEscaping => _hazardEscapeSince != 0; + + /// "You suffer 32 damage from acid!" -> 32, "acid". Broadcast text only. + internal static bool TryParseHotspotDamage(string? text, out int amount, out string source) + { + amount = 0; + source = ""; + if (string.IsNullOrEmpty(text)) return false; + Match m = HotspotDamageRx.Match(text.Trim()); + if (!m.Success || !int.TryParse(m.Groups[1].Value, out amount)) return false; + source = m.Groups[2].Value.Trim().ToLowerInvariant(); + return true; + } + + /// Chat hook: a hotspot hit starts (or pushes on) the escape. + 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. + 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 (_dashboard?.Settings is not { IsMacroRunning: true }) return; + if (!HazardEscaping) + { + StartHazardEscape(now, amount); + return; + } + // Got to the target and still hurt: the pool reaches further back. Go further. + if (_hazardArrivedAt != 0 || !_hazardHasTarget) + { + _hazardArrivedAt = 0; + if (!PickHazardTarget(now, olderThan: _hazardHasTarget ? _hazardTargetAt : _hazardFirstHitAt - HazardBeforeHitMs + 1)) + Log("[RynthAi] Hazard: still taking damage and no older spot to run back to; running on."); + } + } + + /// Every tick: where the character stood (not while escaping, nor dead). + internal void RecordHazardTrail() + { + if (HazardEscaping) return; + long now = HazardClock(); + if (now - _hazardTrailLastAt < HazardTrailSampleMs) return; + if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out _, out _, out _, out _, out _) || cell == 0) + return; + _hazardTrailLastAt = now; + _hazardTrail[_hazardTrailHead] = (now, cell, x, y); + _hazardTrailHead = (_hazardTrailHead + 1) % HazardTrailSize; + if (_hazardTrailCount < HazardTrailSize) _hazardTrailCount++; + } + + private void StartHazardEscape(long now, int amount) + { + _hazardEscapeSince = now; + _hazardArrivedAt = 0; + _hazardRunning = false; + PickHazardTarget(now, olderThan: _hazardFirstHitAt - HazardBeforeHitMs + 1); + Log($"[RynthAi] Hazard: took {amount} {_hazardSource} damage - stopping everything and moving out" + + (_hazardHasTarget ? $" (back to ({_hazardTargetX:0.0}, {_hazardTargetY:0.0}))." : " (no earlier spot known: running back the way it faces).")); + try { Host.WriteToChat($"[RynthAi] Standing in {_hazardSource} - stopping everything to move out.", 1); } catch { } + + try { if (Host.HasCancelAttack) Host.CancelAttack(); } catch { } + _combatManager?.ReleaseHeldTurn(); + _navigationEngine?.Stop(); + try { StopCorpseMovement(); } catch { } + } + + /// + /// The newest trail point older than , in this landblock, at least + /// HazardMinBackMeters away, preferring one outside a known hazard cell. False = none; then + /// the escape runs straight back from where it faces. + /// + private bool PickHazardTarget(long now, long olderThan) + { + _hazardHasTarget = false; + if (!Host.TryGetPlayerPose(out uint cell, out float px, out float py, out _, out float qw, out _, out _, out float qz)) + return false; + + int fallback = -1; + for (int k = 1; k <= _hazardTrailCount; k++) + { + int i = (_hazardTrailHead - k + HazardTrailSize) % HazardTrailSize; + var p = _hazardTrail[i]; + 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 (fallback < 0) fallback = i; + continue; + } + SetHazardTarget(p); + return true; + } + if (fallback >= 0) + { + SetHazardTarget(_hazardTrail[fallback]); + return true; + } + + // No trail (fresh login, or it all lies in the pool): 4 m straight back from the facing. + double yawDeg = ((-(2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI)) % 360.0 + 720.0) % 360.0; + double back = (yawDeg + 180.0) * Math.PI / 180.0; + SetHazardTarget((olderThan - 1, cell, (float)(px + 4.0 * Math.Sin(back)), (float)(py + 4.0 * Math.Cos(back)))); + return false; + } + + private void SetHazardTarget((long At, uint Cell, float X, float Y) p) + { + _hazardHasTarget = true; + _hazardTargetAt = p.At; + _hazardTargetCell = p.Cell; + _hazardTargetX = p.X; + _hazardTargetY = p.Y; + + // The footsteps from now back to the target, newest first, thinned to about 1 m apart: + // the way it came in is a way it can walk out (no straight line through a wall). + _hazardPath.Clear(); + _hazardPathIdx = 0; + float lx = float.NaN, ly = float.NaN; + for (int k = 1; k <= _hazardTrailCount; k++) + { + var t = _hazardTrail[(_hazardTrailHead - k + HazardTrailSize) % HazardTrailSize]; + if (t.At <= p.At) break; + if ((t.Cell >> 16) != (p.Cell >> 16)) continue; + if (!float.IsNaN(lx) && (t.X - lx) * (t.X - lx) + (t.Y - ly) * (t.Y - ly) < 1.0f) continue; + _hazardPath.Add((t.Cell, t.X, t.Y)); + lx = t.X; ly = t.Y; + } + _hazardPath.Add((p.Cell, p.X, p.Y)); + } + + /// + /// Called in OnTick right after the death hold. True = the escape owns this tick: nothing else + /// runs (no buffs, healing kits, combat, looting, route or meta). + /// + internal bool HoldForHazardEscape() + { + if (!HazardEscaping) return false; + long now = HazardClock(); + + if (_dashboard?.Settings is { EscapeHazards: false }) + { + EndHazardEscape("Escape Acid and Lava was turned off"); + return false; + } + if (_dashboard?.Settings is not { IsMacroRunning: true }) + { + EndHazardEscape("the macro was stopped"); + return false; + } + + // Died, recalled or portalled meanwhile: the target is somewhere else now. + if (_hazardHasTarget && Host.TryGetPlayerPose(out uint cellNow, out _, out _, out _, out _, out _, out _, out _) + && (cellNow >> 16) != (_hazardTargetCell >> 16)) + { + EndHazardEscape("left the area"); + return false; + } + + bool quiet = now - _hazardLastHitAt >= HazardQuietMs; + if (now - _hazardEscapeSince > HazardEscapeMaxMs && quiet) + { + EndHazardEscape("no hit for a while"); + return false; + } + if (now - _hazardEscapeSince > HazardEscapeMaxMs * 2) + { + EndHazardEscape($"still hurt after {HazardEscapeMaxMs * 2 / 1000} s - giving the tick back"); + return false; + } + + if (_hazardArrivedAt == 0 && _hazardHasTarget) + RunToHazardTarget(now); + if (_hazardArrivedAt != 0 && quiet) + { + EndHazardEscape("out of it"); + return false; + } + return true; + } + + private void RunToHazardTarget(long now) + { + if (!Host.TryGetPlayerPose(out _, out float px, out float py, out _, out _, out _, out _, out _)) + return; + // Skip to just past the furthest footstep already reached (it may have been carried + // along, or started near the end); the last one is the target. + for (int j = _hazardPath.Count - 1; j >= _hazardPathIdx; j--) + { + var r = _hazardPath[j]; + double rd = Math.Sqrt((r.X - px) * (r.X - px) + (r.Y - py) * (r.Y - py)); + if (rd <= (j == _hazardPath.Count - 1 ? HazardArriveMeters : HazardStepMeters)) + { + _hazardPathIdx = j + 1; + break; + } + } + double dx = 0, dy = 0; + if (_hazardPathIdx < _hazardPath.Count) + { + var w = _hazardPath[_hazardPathIdx]; + dx = w.X - px; dy = w.Y - py; + } + if (_hazardPathIdx >= _hazardPath.Count) + { + _hazardArrivedAt = now; + StopHazardRun(); + return; + } + double desired = Math.Atan2(dx, dy) * (180.0 / Math.PI); + if (desired < 0) desired += 360.0; + bool aligned = _navigationEngine?.ServoToward(desired) ?? TurnDirect(desired); + if (!aligned) + { + if (_hazardRunning) StopHazardRun(); + return; + } + if (!_hazardRunning || now - _hazardRunBeatAt >= 500) + { + Host.SetAutoRunBy("Hazard", true); + _hazardRunning = true; + _hazardRunBeatAt = now; + } + } + + private bool TurnDirect(double desired) + { + if (Host.HasTurnToHeading) Host.TurnToHeadingBy("Hazard", (float)desired); + return true; + } + + private void StopHazardRun() + { + if (!_hazardRunning) return; + _hazardRunning = false; + Host.SetAutoRunBy("Hazard", false); + if (Host.HasStopCompletely) Host.StopCompletelyBy("Hazard"); + } + + private void EndHazardEscape(string why) + { + StopHazardRun(); + Log($"[RynthAi] Hazard: {why} after {(HazardClock() - _hazardEscapeSince) / 1000.0:0.0} s - resuming."); + _hazardEscapeSince = 0; + _hazardArrivedAt = 0; + _hazardHasTarget = false; + _hazardPath.Clear(); + _hazardTrailCount = 0; // the old trail runs through the pool + _navigationEngine?.ResumeFromNearestWaypoint(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 7b556ad..d4dedb8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -131,6 +131,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // Give queue — drained one item per tick with a cooldown (interval comes from settings) private readonly Queue<(uint itemId, uint targetId, int stackSize)> _pendingGives = new(); private DateTime _lastGiveAt = DateTime.MinValue; + // The give the server hasn't answered yet (0 = none): the next one waits for it. + private uint _giveInFlightId, _giveInFlightTarget; + private int _giveInFlightAmount, _giveInFlightStack, _giveInFlightTries; + private long _giveInFlightAt; + private const long GiveConfirmMs = 3000; + private const int GiveMaxTries = 2; private RynthCore.Loot.LootProfile? _nativeLootProfile; private string _nativeLootProfilePath = string.Empty; private DateTime _nativeLootProfileTime = DateTime.MinValue; @@ -677,6 +683,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { _inventoryManager = new InventoryManager(Host, _dashboard.Settings, _objectCache); _manaStoneManager = new ManaStoneManager(Host, _dashboard.Settings, _objectCache); + LegacyUi.NavPoint.SpellNameLookup = id => SpellTableStub.GetById(id)?.Name; // recall steps by name _manaStoneManager.IsLootKept = IsKeptByLootProfile; _petManager = new PetManager(Host, _dashboard.Settings, _objectCache, _combatManager, _charSkills); _combatManager.SummonOut = () => _petManager?.CurrentSummon(); @@ -877,7 +884,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase ["MeleeAttackPower"] = (-1, 100), ["MissileAttackPower"] = (-1, 100), ["MeleeAttackHeight"] = (0, 2), ["MissileAttackHeight"] = (0, 2), ["PetMinMonsters"] = (1, 20), - ["SpellCastIntervalMs"] = (100, 1500), ["AttackSpellIntervalMs"] = (250, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100), + ["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), @@ -1476,6 +1483,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // finally below still submits the nav markers. if (HoldForDeath()) return; + // Standing in acid or lava: nothing but getting out (RynthAiPlugin.HazardEscape.cs). + RecordHazardTrail(); + if (HoldForHazardEscape()) + return; if (diag) Host.Log("[RynthAi] OnTick: before CheckBusyTimeout"); CheckBusyTimeout(); @@ -2035,6 +2046,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase try { mmEat = MetaScheduleChat(text); } catch { } if (mmEat) eat = 1; else _dashboard?.PushChatLine(text, chatType); + try { NoteHotspotChat(text, chatType); } catch (Exception ex) { Host.Log($"[RynthAi] Hazard chat check failed: {ex.Message}"); } _buffManager?.OnChatWindowText(text, chatType); _manaStoneManager?.OnChatWindowText(text); _petManager?.OnChatWindowText(text); @@ -3007,13 +3019,48 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { int count = _pendingGives.Count; _pendingGives.Clear(); + _giveInFlightId = 0; ChatLine(count > 0 ? $"[RynthAi] Give queue cancelled ({count} item(s) remaining)." : "[RynthAi] Give queue is already empty."); } + /// + /// One give at a time, each after the server has taken the last: the item has left the + /// inventory (or its stack shrank, for part of a stack). The queue used to send a give + /// every 150 ms; the server takes one give at a time and answers the rest "too busy", + /// so /ub give handed over one item and dropped the rest (2026-10-08). A give with no + /// answer in GiveConfirmMs is sent once more, then skipped. + /// private void DrainGiveQueue() { + long now = Environment.TickCount64; + if (_giveInFlightId != 0) + { + if (GiveLanded()) + { + _giveInFlightId = 0; + _lastGiveAt = DateTime.UtcNow; + if (_pendingGives.Count == 0) + ChatLine("[RynthAi] Give queue complete."); + } + else if (now - _giveInFlightAt < GiveConfirmMs) + return; + else if (_giveInFlightTries < GiveMaxTries) + { + GiveItem(_giveInFlightId, _giveInFlightTarget, _giveInFlightAmount, _giveInFlightStack); + _giveInFlightTries++; + _giveInFlightAt = now; + return; + } + else + { + ChatLine($"[RynthAi] Give: the server didn't take 0x{_giveInFlightId:X8} - skipping it."); + _giveInFlightId = 0; + if (_pendingGives.Count == 0) return; + } + } + if (_pendingGives.Count == 0) return; int intervalMs = _dashboard?.Settings.GiveQueueIntervalMs ?? 150; if ((DateTime.UtcNow - _lastGiveAt).TotalMilliseconds < intervalMs) return; @@ -3024,9 +3071,21 @@ public sealed partial class RynthAiPlugin : RynthPluginBase int whole = _objectCache?[unchecked((int)itemId)] is WorldObject wo ? Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) : stackSize; GiveItem(itemId, targetId, stackSize, whole); _lastGiveAt = DateTime.UtcNow; + _giveInFlightId = itemId; + _giveInFlightTarget = targetId; + _giveInFlightAmount = stackSize; + _giveInFlightStack = whole; + _giveInFlightTries = 1; + _giveInFlightAt = now; + } - if (_pendingGives.Count == 0) - ChatLine("[RynthAi] Give queue complete."); + /// The in-flight give went through: the item left the inventory, or part of its stack did. + private bool GiveLanded() + { + if (_objectCache?[unchecked((int)_giveInFlightId)] is not WorldObject wo) return true; + if (!InPlayerInventory(wo.Container)) return true; + return _giveInFlightAmount < _giveInFlightStack + && Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) < _giveInFlightStack; } /// diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs index 3862d9e..b023789 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs @@ -76,6 +76,7 @@ internal sealed class AutoVendorManager private long _nextPollAt; private int _failures; private readonly HashSet _sessionSkip = new(); // items the engine refused to sell + private readonly HashSet _sellSkipLogged = new(StringComparer.OrdinalIgnoreCase); // names logged as held back this session private readonly List _idQueue = new(); private readonly Dictionary _idState = new(); @@ -457,6 +458,7 @@ internal sealed class AutoVendorManager _profilePath = path; _failures = 0; _sessionSkip.Clear(); + _sellSkipLogged.Clear(); _bailAt = Now(); _nextActionAt = 0; _host.Log($"[RynthAi] AutoVendor: {_vendorName} [0x{merchantId:X8}] profile '{path}' ({_profile.Rules.Count} rules)"); @@ -853,14 +855,36 @@ internal sealed class AutoVendorManager SafetyFacts safety = ReadSafety(wo, player); string? unsafeWhy = AutoVendorPlanner.UnsafeReason(safety, _settings.AutoVendorOnlyFromMainPack); if (unsafeWhy != null && heldBack == null) + { + if (!_sellSkipLogged.Contains(wo.Name)) + { + ProfileVerdict uv = AutoVendorRules.Decide(_profile.Rules, Judge(EvalObject(wo), InventoryFacts(wo, safety.Appraised), ctx)); + // "Not identified" is usually just not yet (the IDs are on their way): only a + // certain Sell match is worth a line. + if (uv.Rule?.Action == VTankLootAction.Sell && uv.Certain && _sellSkipLogged.Add(wo.Name)) + _host.Log($"[RynthAi] AutoVendor: not selling '{wo.Name}' (rule '{uv.RuleName}'): {unsafeWhy}."); + } continue; + } uint type = ItemType(wo); int stack = StackOf(wo); bool isNote = wo.ObjectClass == AcObjectClass.TradeNote || (type & AutoVendorPlanner.ItemTypePromissoryNote) != 0; int unitValue = stack > 1 ? safety.Value / stack : safety.Value; if (unsafeWhy == null && !AutoVendorPlanner.VendorWillBuy(v, type, isNote, unitValue)) + { + // A Sell rule wanted it and the vendor won't take it: say why, once per name a + // session (peas not sold at Aun Amanaualuan, 2026-10-07, with nothing logged). + if (heldBack == null && !_sellSkipLogged.Contains(wo.Name)) + { + ProfileVerdict sv = AutoVendorRules.Decide(_profile.Rules, Judge(EvalObject(wo), InventoryFacts(wo, safety.Appraised), ctx)); + if (sv.Rule?.Action == VTankLootAction.Sell && sv.Certain && _sellSkipLogged.Add(wo.Name)) + _host.Log(!v.Buys(type) + ? $"[RynthAi] AutoVendor: not selling '{wo.Name}' (rule '{sv.RuleName}'): this vendor doesn't buy {AutoVendorPlanner.CategoryName(type)} (item type 0x{type:X}, vendor buys 0x{v.ItemTypes:X})." + : $"[RynthAi] AutoVendor: not selling '{wo.Name}' (rule '{sv.RuleName}'): worth {unitValue:n0} each, this vendor pays for items up to {v.MaxValue:n0}."); + } continue; + } ItemFacts f = InventoryFacts(wo, safety.Appraised); ProfileVerdict verdict = AutoVendorRules.Decide(_profile.Rules, Judge(EvalObject(wo), f, ctx)); @@ -876,6 +900,8 @@ internal sealed class AutoVendorManager { if (heldBack != null && verdict.Rule?.Action == VTankLootAction.Sell) heldBack.Add($"{wo.Name} - {sd.Reason}"); + else if (heldBack == null && verdict.Rule?.Action == VTankLootAction.Sell && _sellSkipLogged.Add(wo.Name)) + _host.Log($"[RynthAi] AutoVendor: not selling '{wo.Name}': {sd.Reason}."); continue; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs index 737eda2..7427481 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs @@ -254,7 +254,9 @@ internal static class AutoVendorPlanner if (f.IsRare) return "rare"; if (onlyFromMainPack && !f.InMainPack) return "not in main pack"; if (f.Attuned != 0) return "attuned"; - if (f.Bonded != 0) return "bonded"; + // Not Bonded: on ACE it only decides what a death keeps (PropertyInt.Bonded, Player_Death); + // it never stops a sale. Peas, trade notes and salvage bags are bonded so a death keeps + // them, and AutoVendor held them all back (2026-10-07). Quest items are not sellable anyway. if (f.Retained) return "retained"; if (f.TimesTinkered > 0) return "tinkered"; if (f.Imbued != 0) return "imbued"; diff --git a/Plugins/RynthCore.Plugin.RynthNav/Atlas.cs b/Plugins/RynthCore.Plugin.RynthNav/Atlas.cs index 761f82a..521eaf8 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/Atlas.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/Atlas.cs @@ -22,7 +22,7 @@ internal sealed class AtlasLocation // A portal's destination. public bool HasDest, DestOnMap; public double DestNs, DestEw; - public string DestName = "", DestPlace = ""; + public string DestName = "", DestPlace = "", DestCell = ""; public int MinLevel, MaxLevel; public bool Quest, Closed; } @@ -92,6 +92,7 @@ internal sealed class Atlas l.DestOnMap = TryNum(d, "ns", out l.DestNs) & TryNum(d, "ew", out l.DestEw); l.DestName = Str(d, "name"); l.DestPlace = Str(d, "place"); + l.DestCell = Str(d, "cell"); } locs.Add(l); } @@ -110,6 +111,36 @@ internal sealed class Atlas public AtlasLocation? ById(int id) => _byId.TryGetValue(id, out var l) ? l : null; + /// + /// Landblocks that are dungeons: places (and portal destinations) the Atlas has in "dungeon" + /// cells, less any landblock with places on the map. A dungeon's nav_XXXX.tile holds only that + /// landblock's surface (a flat sheet; RynthNav.Baker leaves dungeon cells out), so it isn't + /// a navmesh for walking inside the dungeon. + /// + public HashSet DungeonLandblocks() + { + var dungeon = new HashSet(); + var map = new HashSet(); + foreach (AtlasLocation l in Locations) + { + if (TryLandblock(l.Cell, out uint lb)) + { + if (l.OnMap) map.Add(lb); + else if (l.Place.Equals("dungeon", StringComparison.Ordinal)) dungeon.Add(lb); + } + if (l.HasDest && !l.DestOnMap && l.DestPlace.Equals("dungeon", StringComparison.Ordinal) && TryLandblock(l.DestCell, out uint dlb)) + dungeon.Add(dlb); + } + dungeon.ExceptWith(map); + return dungeon; + } + + private static bool TryLandblock(string cell, out uint lb) + { + lb = 0; + return cell.Length == 8 && uint.TryParse(cell.AsSpan(0, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lb); + } + // ── Search ─────────────────────────────────────────────────────────────── /// How well matches (lower case): 0 = not at all. diff --git a/Plugins/RynthCore.Plugin.RynthNav/RecallMemory.cs b/Plugins/RynthCore.Plugin.RynthNav/RecallMemory.cs index 612afe2..53ef54a 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RecallMemory.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RecallMemory.cs @@ -8,7 +8,11 @@ namespace RynthCore.Plugin.RynthNav; // Where a character's personal recalls land. The client is never told (the server keeps // a character's lifestone, ties, last portal and house), so RynthNav learns them from what // it sees: the server's messages ("You have attuned your spirit to this Lifestone.", "X is -// recalling home.") and the teleport that follows. Saved per character in +// recalling home.") and the teleport that follows, and a teleport right after your own spell +// words (a recall cast by hand: RecallPlanner.GuessHandCast). ACE sends a character neither +// its tie positions (PlayerDescription carries only LastOutsideDeath) nor the tied portals' +// data ids (LinkedPortalOne/Two aren't SendOnLogin and change silently), so a tie made +// before RynthNav was there is learned on the first cast of its recall. Saved per character in // NavData\recalls.txt. No host calls: the offline tests compile this file. // (GoArrow kept the same kind of per-character recall list; Digero 2006, Virindi 2011, MIT.) @@ -61,6 +65,9 @@ internal enum RecallEvent RecallingHometown, /// "Name is recalling to the marketplace." (lands in a dungeon: never used for routes). RecallingMarketplace, + /// "You say, "Zojak Ququ"" on the spellcasting channel: you started casting a spell + /// (a recall cast by hand teleports a few seconds later). + OwnSpellWords, } internal sealed class RecallMemory @@ -108,15 +115,21 @@ internal sealed class RecallMemory } } + /// ChatMessageType.Spellcasting: the words a caster speaks (yours: "You say, "..."). + public const int ChatTypeSpellcasting = 17; + /// /// Reads a chat line (the server's own wording, ACE's Player_Location / Lifestone / /// WorldObject_Magic). picks out your own "is recalling" - /// lines from other players' nearby. + /// lines from other players' nearby. tells your spell words + /// (Spellcasting, 17) from something you typed in local chat (Speech, 2). /// - public static RecallEvent Classify(string? text, string? playerName) + public static RecallEvent Classify(string? text, string? playerName, int chatType = -1) { if (string.IsNullOrEmpty(text)) return RecallEvent.None; string t = text.Trim(); + if (chatType == ChatTypeSpellcasting && t.StartsWith("You say, \"", StringComparison.Ordinal)) + return RecallEvent.OwnSpellWords; if (t.StartsWith("You have attuned your spirit to this Lifestone", StringComparison.OrdinalIgnoreCase)) return RecallEvent.AttunedLifestone; if (t.StartsWith("You have successfully linked with the life stone", StringComparison.OrdinalIgnoreCase)) diff --git a/Plugins/RynthCore.Plugin.RynthNav/RecallPlanner.cs b/Plugins/RynthCore.Plugin.RynthNav/RecallPlanner.cs index 4d2f6dd..66fdd97 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RecallPlanner.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RecallPlanner.cs @@ -71,13 +71,13 @@ internal static class RecallPlanner if (known != null) { AddLearnedSpell(list, notes, known, memory, charKey, LifestoneRecall, "Lifestone Recall", RecallSlot.Lifestone, - "cast Lifestone Tie on a lifestone"); + "cast Lifestone Tie on a lifestone, cast Lifestone Recall once, or /rnav tie lifestone at the tied lifestone"); AddLearnedSpell(list, notes, known, memory, charKey, PortalRecall, "Portal Recall", RecallSlot.LastPortal, "walk through a portal"); AddLearnedSpell(list, notes, known, memory, charKey, PrimaryPortalTieRecall, "Primary Portal Tie Recall", RecallSlot.Tie1, - "cast Primary Portal Tie on a portal"); + "cast Primary Portal Tie on a portal, cast Primary Portal Tie Recall once, or /rnav tie 1 at the tied portal"); AddLearnedSpell(list, notes, known, memory, charKey, SecondaryPortalTieRecall, "Secondary Portal Tie Recall", RecallSlot.Tie2, - "cast Secondary Portal Tie on a portal"); + "cast Secondary Portal Tie on a portal, cast Secondary Portal Tie Recall once, or /rnav tie 2 at the tied portal"); } // Command recalls (no spell): @lifestone always; house, mansion and hometown @@ -123,6 +123,115 @@ internal static class RecallPlanner private static string Where(RecallSpot s) => s.Label.Length > 0 ? "in " + s.Label : "in a dungeon"; + // ── Learning from a recall cast by hand ────────────────────────────────── + + /// Recall the Sanctuary (Lifestone Sending): lands where @lifestone does. + public const int RecallTheSanctuary = 2023; + /// WeenieError YouMustLinkToLifestoneToRecall / YouMustLinkToPortalToRecall. + public const uint ErrorMustLinkLifestone = 0x049E, ErrorMustLinkPortal = 0x04A3; + + /// What a teleport right after your own spell words teaches. + public enum HandCast + { + /// Nothing new (already known, a fixed recall, or can't tell); why says which. + Nothing, + /// The landing of slot. + Learn, + /// A portal tie recall, but not which: ask (/rnav tie 1|2). + AskTie, + } + + /// + /// You spoke spell words, stood still and were teleported: a recall cast by hand. Which + /// one, from where it landed: on a lifestone, Lifestone Recall; anywhere else, a portal tie + /// recall (Portal Recall's landing is the last portal's, already known). A landing that + /// matches a recall already known teaches nothing. When the spellbook leaves more than one + /// tie recall (or Portal Recall with no last portal known), ask. No host calls. + /// + /// The landing is on a lifestone (the Atlas's). + /// Two landings this close are the same place. + public static HandCast GuessHandCast(RecallSpot landing, bool atLifestone, ISet? known, RecallMemory memory, + string charKey, double nearUnits, out RecallSlot slot, out string why) + { + slot = RecallSlot.Lifestone; + if (known == null) { why = "the spellbook isn't read yet"; return HandCast.Nothing; } + if (atLifestone) + { + if (!known.Contains(LifestoneRecall)) { why = "on a lifestone, but Lifestone Recall isn't in the spellbook"; return HandCast.Nothing; } + if (Same(memory.Get(charKey, RecallSlot.Lifestone), landing, nearUnits)) { why = "Lifestone Recall, already known"; return HandCast.Nothing; } + if (known.Contains(RecallTheSanctuary) && Same(memory.Get(charKey, RecallSlot.Sanctuary), landing, nearUnits)) + { why = "on your @lifestone lifestone: Lifestone Recall or Recall the Sanctuary, can't tell"; return HandCast.Nothing; } + why = "on a lifestone: Lifestone Recall"; + return HandCast.Learn; + } + if (Same(memory.Get(charKey, RecallSlot.LastPortal), landing, nearUnits)) { why = "where the last portal went: Portal Recall"; return HandCast.Nothing; } + var ties = new List(2); + if (known.Contains(PrimaryPortalTieRecall)) ties.Add(RecallSlot.Tie1); + if (known.Contains(SecondaryPortalTieRecall)) ties.Add(RecallSlot.Tie2); + foreach (RecallSlot t in ties) + if (Same(memory.Get(charKey, t), landing, nearUnits)) { slot = t; why = RecallMemory.SlotName(t) + ", already known"; return HandCast.Nothing; } + if (ties.Count == 0) { why = "no portal tie recall in the spellbook (a spell's teleport RynthNav doesn't know)"; return HandCast.Nothing; } + bool maybePortalRecall = known.Contains(PortalRecall) && memory.Get(charKey, RecallSlot.LastPortal) == null; + if (ties.Count == 1 && !maybePortalRecall) + { + slot = ties[0]; + why = "the only portal tie recall in the spellbook"; + return HandCast.Learn; + } + slot = ties[0]; + why = maybePortalRecall ? "a portal tie recall or Portal Recall (no last portal known yet)" : "a portal tie recall, primary or secondary"; + return HandCast.AskTie; + } + + /// Two landings are the same place: on the map within ; off it, the same label. + public static bool Same(RecallSpot? a, RecallSpot b, double nearUnits) + { + if (a == null || a.OnMap != b.OnMap) return false; + if (a.OnMap) return NavCoords.Distance(a.Ns, a.Ew, b.Ns, b.Ew) < nearUnits; + return a.Label.Equals(b.Label, StringComparison.OrdinalIgnoreCase); + } + + /// + /// The recall the server says isn't linked: "You must link to a lifestone to recall it" is + /// always Lifestone Recall; "...to a portal..." is whichever portal recall was just cast + /// (, 0 = not known: nothing). + /// + public static RecallSlot? SlotUnlinked(uint error, int castSpell) => error switch + { + ErrorMustLinkLifestone => RecallSlot.Lifestone, + ErrorMustLinkPortal => castSpell switch + { + PrimaryPortalTieRecall => RecallSlot.Tie1, + SecondaryPortalTieRecall => RecallSlot.Tie2, + PortalRecall => RecallSlot.LastPortal, + _ => null, + }, + _ => null, + }; + + /// The recall spell whose landing a slot holds (0 for the command recalls). + public static int SpellFor(RecallSlot slot) => slot switch + { + RecallSlot.Lifestone => LifestoneRecall, + RecallSlot.LastPortal => PortalRecall, + RecallSlot.Tie1 => PrimaryPortalTieRecall, + RecallSlot.Tie2 => SecondaryPortalTieRecall, + _ => 0, + }; + + /// A slot's name for players ("Primary Portal Tie Recall", "@lifestone"). + public static string Title(RecallSlot slot) => slot switch + { + RecallSlot.Sanctuary => "@lifestone", + RecallSlot.Lifestone => "Lifestone Recall", + RecallSlot.LastPortal => "Portal Recall", + RecallSlot.Tie1 => "Primary Portal Tie Recall", + RecallSlot.Tie2 => "Secondary Portal Tie Recall", + RecallSlot.House => "House recall", + RecallSlot.Mansion => "Allegiance mansion recall", + _ => "Allegiance hometown recall", + }; + public static List Links(List options) { var links = new List(options.Count); diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs new file mode 100644 index 0000000..cfbaa31 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs @@ -0,0 +1,109 @@ +using System; +using DotRecast.Core.Numerics; +using DotRecast.Detour; + +namespace RynthCore.Plugin.RynthNav; + +// Running into a wall: the walk is running but the character isn't moving. The navmesh is baked +// with a 2 m agent radius (RynthNav.Baker), which seals gaps under ~4 m and leaves some ground in +// little islands (Shoushi's plaza, where the Town Network drops you, 10-08); where the plan runs +// out the walk heads straight for its goal for a moment (BlindPushTicks), and that, or a wall the +// mesh doesn't show, used to mean running into it until the 30 s progress watchdog. Now: blocked +// for StuckWindowMs = turn away at an angle (alternating sides), plan again, and after +// StuckMaxTries on one leg without progress stop and say where. +public sealed partial class RynthNavPlugin +{ + private const long StuckWindowMs = 1200; // running this long... + private const double StuckMoveUnits = 0.6; // ...and moved less than this = blocked (a run covers 4+ u/s) + private const long UnstickMs = 1600; // then turn away from it and run this long (~0.5 s of it turning) + private const double UnstickAngleDeg = 120.0; // away from where it was heading, off to one side + private const int StuckMaxTries = 4; // blocked this often on a leg without progress = stop + + private bool _ranLastTick; // the walk asked to run last tick (not standing, not turning in place) + private double _lastDriveDeg; + private long _stuckWinMs, _unstickUntilMs; + private double _stuckWx, _stuckWy, _unstickDeg; + private int _stuckTries, _stuckSide = 1; + + /// DriveTo for the walk's own steering: remembers that it ran and which way. + private void WalkDrive(double deg) + { + DriveTo(deg); + _lastDriveDeg = deg; + _ranLastTick = !_turnInPlace; + } + + /// + /// Nothing between here and (, ) as far as the navmesh + /// shows: every metre of the line, bar 2 m at each end (we and a portal stand off the eroded + /// mesh), is within 1.5 m of walkable ground. A wall leaves a gap of twice the agent radius plus + /// its thickness, over 4 m, so its middle fails. No query (no tiles): true, as before. + /// + private bool StraightOnMesh(double tx, double ty) + { + if (_query == null) return true; + var filter = new DtQueryDefaultFilter(); + double dx = tx - _wx, dy = ty - _wy, len = Math.Sqrt(dx * dx + dy * dy); + for (double s = 2.0; s < len - 2.0; s += 1.0) + { + var pt = new RcVec3f((float)(_wx + dx * s / len), (float)_wz, (float)(_wy + dy * s / len)); + _query.FindNearestPoly(pt, new RcVec3f(1.5f, 4, 1.5f), filter, out long r, out _, out _); + if (r == 0) return false; + } + return true; + } + + /// A new leg (or goto): nothing blocked yet. + private void ResetBlocked() + { + _ranLastTick = false; + _stuckWinMs = 0; _unstickUntilMs = 0; _stuckTries = 0; + } + + /// + /// Once per walking tick, before steering. True when it drove this tick (stepping round + /// something) or finished the goto; the caller returns. + /// + private bool StepBlocked() + { + long now = NowMs; + bool ran = _ranLastTick; + _ranLastTick = false; + if (_unstickUntilMs > now) + { + DriveTo(_unstickDeg); + lock (_gate) _status = $"blocked: stepping round it ({_stuckTries}/{StuckMaxTries})"; + return true; + } + if (_unstickUntilMs != 0) + { + // Stepped aside: plan again from here (and allow one more push where the plan ends). + _unstickUntilMs = 0; + lock (_gotoGate) _gotoPath = null; + _blindTicks = 0; _replanTick = 0; + _stuckWinMs = 0; + return false; + } + if (!ran || _stuckWinMs == 0) { _stuckWinMs = now; _stuckWx = _wx; _stuckWy = _wy; return false; } + if (now - _stuckWinMs < StuckWindowMs) return false; + double moved = Math.Sqrt((_wx - _stuckWx) * (_wx - _stuckWx) + (_wy - _stuckWy) * (_wy - _stuckWy)); + _stuckWinMs = now; _stuckWx = _wx; _stuckWy = _wy; + if (moved >= StuckMoveUnits) return false; + + string at = NavCoords.Fmt(NavCoords.NsFromWorld(_wy), NavCoords.EwFromWorld(_wx)); + if (++_stuckTries > StuckMaxTries) + { + string why; lock (_gate) why = _status; + FinishGoto($"stopped: blocked at {at} ({StuckMaxTries} tries to get round it; something in the way the map doesn't show) ({why})"); + return true; + } + _stuckSide = -_stuckSide; + _unstickDeg = ((_lastDriveDeg + 180.0 - _stuckSide * (180.0 - UnstickAngleDeg)) % 360.0 + 360.0) % 360.0; + _unstickUntilMs = now + UnstickMs; + Host.Log($"[RynthNav] walk: blocked at {at} heading {_lastDriveDeg:F0} (moved {moved:F1}u in {StuckWindowMs / 1000.0:F1} s); " + + $"turning to {_unstickDeg:F0} and planning again ({_stuckTries}/{StuckMaxTries})"); + DriveTo(_unstickDeg); + lock (_gate) _status = $"blocked: stepping round it ({_stuckTries}/{StuckMaxTries})"; + return true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs index a9315c5..85fa7cc 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs @@ -114,13 +114,14 @@ public sealed partial class RynthNavPlugin long now = NowMs; if (landblockChanged && _hasPose) { - try { _tileHere = File.Exists(Path.Combine(NavDataDir, $"nav_{CurrentLandblock:X4}.tile")) ? 1 : 0; } catch { _tileHere = -1; } + // A dungeon's tile is its landblock's surface: no navmesh here (RynthNavPlugin.InDungeon). + try { _tileHere = !InDungeon(_cellId) && File.Exists(Path.Combine(NavDataDir, $"nav_{CurrentLandblock:X4}.tile")) ? 1 : 0; } catch { _tileHere = -1; } } if (now < _nextInfoMs || now - Interlocked.Read(ref _lastStatusPollMs) > PanelPollWindowMs) return; _nextInfoMs = now + InfoRefreshMs; if (Interlocked.Exchange(ref _infoBusy, 1) != 0) return; uint lb = CurrentLandblock; - bool hasPose = _hasPose; + bool hasPose = _hasPose, dungeon = InDungeon(_cellId); Task.Run(() => { try @@ -129,7 +130,7 @@ public sealed partial class RynthNavPlugin if (Directory.Exists(NavDataDir)) foreach (string _ in Directory.EnumerateFiles(NavDataDir, "nav_*.tile")) n++; _tilesOnDisk = n; - if (hasPose) _tileHere = File.Exists(Path.Combine(NavDataDir, $"nav_{lb:X4}.tile")) ? 1 : 0; + if (hasPose) _tileHere = !dungeon && File.Exists(Path.Combine(NavDataDir, $"nav_{lb:X4}.tile")) ? 1 : 0; } catch { } finally { Interlocked.Exchange(ref _infoBusy, 0); } diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs index 2957e9e..588f312 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs @@ -29,6 +29,10 @@ public sealed partial class RynthNavPlugin private const long RecallCastWindowMs = 40000; // our own recall cast -> the teleport within this private const long RecallStepTimeoutMs = 45000; // a route's recall step gives up after this private const long RecallRecastMs = 4500; // re-cast a recall spell this often while waiting + private const long HandCastWindowMs = 12000; // your spell words -> portal space within this = a recall cast by hand + private const double HandCastStillUnits = 2.0; // ...standing still meanwhile (walking into a portal moves you) + private const double LifestoneLandUnits = 10.0; // a landing this close to a lifestone = on it (Lifestone Recall) + private const double PortalBesideUnits = 4.0; // a live portal this close as portal space begins: maybe that portal, not a recall private const long StanceRetryMs = 1500; private const long WandAfterMs = 6000; // no magic stance by then: try wielding a wand private const int CombatModeNonCombat = 1, CombatModeMagic = 8; @@ -37,6 +41,7 @@ public sealed partial class RynthNavPlugin private volatile Atlas _atlas = Atlas.Empty; private volatile string _atlasStatus = "loading…"; private HashSet _mapLandblocks = new(); // landblocks with Atlas places on the map (tick thread) + private volatile HashSet _dungeonLandblocks = new(); // dungeon landblocks the Atlas knows (Atlas.DungeonLandblocks; read-only once built) private AtlasStore _store = new(); private RecallMemory _memory = new(); private bool _storesLoaded; @@ -67,12 +72,18 @@ public sealed partial class RynthNavPlugin private int _castRecallSpell; private long _castRecallMs; private RecallSpot? _pendingTie; + // Your own spell words (a recall cast by hand teleports a few seconds later): when and where. + private long _selfCastMs; + private double _selfCastWx, _selfCastWy; + private bool _selfCastDied; + private int _weenieSeq = -1; // the last server refusal looked at (-1 = none yet) // Teleport tracking (tick thread). private bool _trkPortaling, _trkHaveLast, _trkHavePre; private uint _trkLastCell, _trkPreCell; private double _trkLastWx, _trkLastWy, _trkPreWx, _trkPreWy; - private long _trkLastTeleportMs; + private long _trkLastTeleportMs, _trkPortalStartMs; + private bool _trkPortalBeside; // a live portal stood right beside you as portal space began // Route planning with recalls: the recalls the current route can use (by RouteStep.RecallIndex). private List _routeRecalls = new(); @@ -146,7 +157,7 @@ public sealed partial class RynthNavPlugin private void OnLoginTravel() { _charKey = ""; _playerName = ""; _known = null; _nextKnownMs = 0; - _pendingRecallSlot = null; _castRecallSpell = 0; _pendingTie = null; + _pendingRecallSlot = null; _castRecallSpell = 0; _pendingTie = null; _selfCastMs = 0; _trkHaveLast = false; _trkPortaling = false; } @@ -175,6 +186,7 @@ public sealed partial class RynthNavPlugin foreach (var l in atlas.Locations) if (l.OnMap && l.Cell.Length == 8 && uint.TryParse(l.Cell.AsSpan(0, 4), NumberStyles.HexNumber, null, out uint lb)) lbs.Add(lb); _mapLandblocks = lbs; + _dungeonLandblocks = atlas.DungeonLandblocks(); _indexedAtlas = atlas; if (_known != null && atlas.Recalls.Count > 0) LogKnownRecalls(_known); } @@ -183,6 +195,10 @@ public sealed partial class RynthNavPlugin while (_commands.TryDequeue(out string? cmd)) RunCommand(cmd, fromPanel: false); while (_recallEvents.TryDequeue(out var ev)) OnRecallEvent(ev.Event, ev.Ms); + PollRecallRefusal(); + if (_selfCastMs != 0 && !_selfCastDied && now - _selfCastMs < HandCastWindowMs + 30000 + && Host.TryGetPlayerVitals(out uint hp, out uint maxHp, out _, out _, out _, out _) && maxHp > 0 && hp == 0) + _selfCastDied = true; // died mid-cast: the trip to the lifestone that follows isn't a recall bool teleported = TrackTeleport(now); UpdateArrow(teleported); @@ -250,6 +266,12 @@ public sealed partial class RynthNavPlugin /// Outdoors, or in a building of a landblock that has Atlas places on the map. private bool IsOnMap(uint cell) => (cell & 0xFFFF) < 0x100 || _mapLandblocks.Contains(cell >> 16); + /// + /// In a dungeon the Atlas knows. Its landblock's tile is the surface's (dungeon cells aren't + /// baked), so there is no navmesh to walk here even though nav_XXXX.tile exists. + /// + private bool InDungeon(uint cell) => (cell & 0xFFFF) >= 0x100 && _dungeonLandblocks.Contains(cell >> 16); + // ── Teleports: the arrow's portal/recall steps and learning recall landings ── private bool TrackTeleport(long now) @@ -260,6 +282,9 @@ public sealed partial class RynthNavPlugin if (!_trkPortaling) { _trkPortaling = true; + _trkPortalStartMs = now; + // Only worth the look after your own spell words (a hand-cast recall, or a portal used standing at it?). + _trkPortalBeside = _selfCastMs != 0 && now - _selfCastMs < HandCastWindowMs && _trkHaveLast && LivePortalWithin(_trkLastWx, _trkLastWy, PortalBesideUnits); _trkHavePre = _trkHaveLast; _trkPreCell = _trkLastCell; _trkPreWx = _trkLastWx; _trkPreWy = _trkLastWy; } @@ -273,23 +298,32 @@ public sealed partial class RynthNavPlugin bool havePre = _trkPortaling ? _trkHavePre : _trkHaveLast; uint preCell = _trkPortaling ? _trkPreCell : _trkLastCell; double preWx = _trkPortaling ? _trkPreWx : _trkLastWx, preWy = _trkPortaling ? _trkPreWy : _trkLastWy; + long startMs = _trkPortaling ? _trkPortalStartMs : now; + bool portalBeside = _trkPortaling && _trkPortalBeside; _trkPortaling = false; if (now - _trkLastTeleportMs > 2000) { teleported = true; _trkLastTeleportMs = now; - OnTeleported(havePre, preCell, preWx, preWy); + OnTeleported(havePre, preCell, preWx, preWy, startMs, portalBeside); } } _trkHaveLast = true; _trkLastCell = _cellId; _trkLastWx = _wx; _trkLastWy = _wy; return teleported; } - private void OnTeleported(bool havePre, uint preCell, double preWx, double preWy) + private void OnTeleported(bool havePre, uint preCell, double preWx, double preWy, long startMs, bool portalBeside) { long now = NowMs; RecallSpot landing = SpotHere(); string who = _charKey; + // Your spell words shortly before portal space, standing still since, not dead, no portal + // right beside you: a recall cast by hand (walking into a portal moves you; using one you + // stand at doesn't, hence the portal check; dying is a trip, not a recall). + bool handCast = _selfCastMs != 0 && startMs - _selfCastMs >= 0 && startMs - _selfCastMs < HandCastWindowMs + && !_selfCastDied && havePre && !portalBeside + && Math.Sqrt((preWx - _selfCastWx) * (preWx - _selfCastWx) + (preWy - _selfCastWy) * (preWy - _selfCastWy)) < HandCastStillUnits; + _selfCastMs = 0; _selfCastDied = false; if (who.Length == 0) return; if (_pendingRecallSlot is RecallSlot slot && now - _pendingRecallMs < RecallAnnounceWindowMs) @@ -312,7 +346,17 @@ public sealed partial class RynthNavPlugin RecallPlanner.SecondaryPortalTieRecall => RecallSlot.Tie2, _ => null, }; - if (learned is RecallSlot ls) _memory.Set(who, ls, landing); + if (learned is RecallSlot ls) + { + _memory.Set(who, ls, landing); + Host.Log($"[RynthNav] learned {RecallMemory.SlotName(ls)} lands at {Describe(landing)}"); + } + return; + } + // A recall cast by hand (or by another plugin): never the last portal's landing. + if (handCast && !CameThroughAtlasPortal(havePre, preCell, preWx, preWy, landing)) + { + LearnHandCast(landing); return; } // Not a recall we know of: a portal, most likely. Portal Recall goes back to where @@ -341,6 +385,101 @@ public sealed partial class RynthNavPlugin return false; } + /// A live portal object within of a world point (this landblock's objects). + private bool LivePortalWithin(double wx, double wy, double units) + { + if (!Host.HasGetLiveObjectIds) return false; + foreach (uint id in Host.GetLiveObjectIds()) + { + if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) continue; + if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out _) || cell == 0) continue; + double ox = ((cell >> 24) & 0xFF) * 192.0 + x, oy = ((cell >> 16) & 0xFF) * 192.0 + y; + if ((ox - wx) * (ox - wx) + (oy - wy) * (oy - wy) < units * units) return true; + } + return false; + } + + /// + /// A known portal stood where you were, and goes where you landed: the teleport was that + /// portal (used standing at it), not the spell you'd just cast. + /// + private bool CameThroughAtlasPortal(bool havePre, uint preCell, double preWx, double preWy, RecallSpot landing) + { + if (!havePre || !IsOnMap(preCell) || !landing.OnMap) return false; + double pns = NavCoords.NsFromWorld(preWy), pew = NavCoords.EwFromWorld(preWx); + foreach (AtlasLocation l in _atlas.Locations) + { + if (!l.OnMap || !l.HasDest || !l.DestOnMap || !l.Type.Equals("Portal", StringComparison.Ordinal)) continue; + if (NavCoords.Distance(pns, pew, l.Ns, l.Ew) < PortalNearUnits + && NavCoords.Distance(landing.Ns, landing.Ew, l.DestNs, l.DestEw) < RecallNearUnits) return true; + } + return false; + } + + /// + /// A recall cast by hand (RynthNav didn't cast it): learn which one from where it landed + /// (RecallPlanner.GuessHandCast), so ties made before RynthNav was there, or cast from the + /// spell bar, are planned from now on. + /// + private void LearnHandCast(RecallSpot landing) + { + if (landing.OnMap) + foreach (AtlasRecall r in _atlas.Recalls) + if (r.OnMap && NavCoords.Distance(landing.Ns, landing.Ew, r.Ns, r.Ew) < RecallNearUnits) + { + Host.Log($"[RynthNav] recall cast by hand landed at {Describe(landing)}: {r.Name}'s landing, nothing to learn"); + return; + } + AtlasLocation? ls = landing.OnMap ? _atlas.Nearest("Lifestone", landing.Ns, landing.Ew, LifestoneLandUnits) : null; + RecallPlanner.HandCast kind = RecallPlanner.GuessHandCast(landing, ls != null, _known, _memory, _charKey, RecallNearUnits, + out RecallSlot slot, out string why); + switch (kind) + { + case RecallPlanner.HandCast.Learn: + if (ls != null) landing.Label = ls.Name + (landing.Label.Length > 0 ? " (" + landing.Label + ")" : ""); + _memory.Set(_charKey, slot, landing); + Host.Log($"[RynthNav] learned {RecallMemory.SlotName(slot)} lands at {Describe(landing)} (a recall cast by hand: {why})"); + Say($"{RecallPlanner.Title(slot)} takes you to {Describe(landing)}: routes can use it now."); + break; + case RecallPlanner.HandCast.AskTie: + _pendingTie = landing; + Host.Log($"[RynthNav] recall cast by hand landed at {Describe(landing)}: {why}; asking which tie"); + Say($"Recalled to {Describe(landing)}. If that was a portal tie recall: /rnav tie 1 (primary) or /rnav tie 2 (secondary)."); + break; + default: + Host.Log($"[RynthNav] recall cast by hand landed at {Describe(landing)}: {why}"); + break; + } + } + + /// + /// The server's "You must link to a lifestone / portal to recall it": that recall has no + /// tie (any more), so forget its landing; a route waiting on it plans again without it. + /// + private void PollRecallRefusal() + { + if (!Host.HasGetLastWeenieError || !Host.TryGetLastWeenieError(out int seq, out uint error, out _, out _)) return; + if (_weenieSeq < 0 || seq == _weenieSeq) { _weenieSeq = seq; return; } // the first look only notes where the count stands + _weenieSeq = seq; + int cast = _castRecallSpell != 0 && NowMs - _castRecallMs < RecallCastWindowMs ? _castRecallSpell : 0; + if (RecallPlanner.SlotUnlinked(error, cast) is not RecallSlot slot || _charKey.Length == 0) return; + bool had = _memory.Get(_charKey, slot) != null; + _memory.Clear(_charKey, slot); + if (slot == RecallSlot.Tie1 || slot == RecallSlot.Tie2) _pendingTie = null; + string name = RecallPlanner.Title(slot); + Host.Log($"[RynthNav] {name}: the server says it isn't linked (0x{error:X4}){(had ? "; its landing is forgotten" : "")}"); + RecallOption? o = _recallWait ? CurrentRecallOption() : null; + if (o != null && o.SpellId == RecallPlanner.SpellFor(slot) && _gotoActive) + { + string goal = _gotoName, type = _gotoType, enter = _enterName, enterType = _enterType; + double gns = NavCoords.NsFromWorld(_finalTns), gew = NavCoords.EwFromWorld(_finalTew); + Say($"goto: {name} isn't tied to anything; planning again without it"); + EndRecall(); + StartWalk(goal.Length > 0 ? goal : NavCoords.Fmt(gns, gew), type, gns, gew, enter, enterType); + } + else if (had) Say($"{name} isn't tied to anything: routes won't use it until you tie it again."); + } + /// Where you stand now, as a recall landing: on the map or not, and a label. private RecallSpot SpotHere() { @@ -362,7 +501,7 @@ public sealed partial class RynthNavPlugin public override void OnChatWindowText(string? text, int chatType, ref int eat) { - RecallEvent e = RecallMemory.Classify(text, _playerName); + RecallEvent e = RecallMemory.Classify(text, _playerName, chatType); if (e != RecallEvent.None) _recallEvents.Enqueue((e, NowMs)); } @@ -396,6 +535,11 @@ public sealed partial class RynthNavPlugin case RecallEvent.RecallingMarketplace: _pendingRecallSlot = null; break; + case RecallEvent.OwnSpellWords: + // Any spell: only a teleport soon after, standing here, makes it a recall (OnTeleported). + if (!_hasPose) break; + _selfCastMs = ms; _selfCastWx = _wx; _selfCastWy = _wy; _selfCastDied = false; + break; default: if (RecallMemory.SlotFor(e, out RecallSlot slot)) { @@ -428,23 +572,42 @@ public sealed partial class RynthNavPlugin return l == null ? null : new RecallSpot { OnMap = true, Ns = l.Ns, Ew = l.Ew, Label = l.Name }; } - private void OnPortalTied() + /// + /// The tied portal: the selected portal, looked up in the Atlas by its weenie class (ACE + /// ties the portal's class), else the nearest portal in the Atlas within . + /// + private AtlasLocation? TiePortal(double nearUnits) { - // The tied portal's destination: the selected portal, looked up in the Atlas by its - // weenie class (ACE ties the portal's class), else the nearest portal in the Atlas. AtlasLocation? portal = null; uint sel = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0; PlayerMapPos(out double pns, out double pew); if (sel != 0 && Host.TryGetObjectWcid(sel, out uint wcid)) portal = _atlas.PortalByWcid(wcid, pns, pew); - portal ??= _hasPose ? _atlas.Nearest("Portal", pns, pew, 60) : null; + portal ??= _hasPose ? _atlas.Nearest("Portal", pns, pew, nearUnits) : null; + return portal; + } + + private static RecallSpot TieLanding(AtlasLocation portal) => portal.DestOnMap + ? new RecallSpot { OnMap = true, Ns = portal.DestNs, Ew = portal.DestEw, Label = portal.Name } + : new RecallSpot { OnMap = false, Label = portal.DestName.Length > 0 ? portal.DestName : portal.Name }; + + /// /rnav tie 1|2 with no tie waiting: where the portal you've selected or stand at goes. + private RecallSpot? TiedPortalSpot(out string why) + { + AtlasLocation? portal = TiePortal(PortalNearUnits); + why = portal == null ? "select the tied portal, or stand at it, first" + : !portal.HasDest ? $"{portal.Name} isn't in the Atlas with a destination" : ""; + return portal != null && portal.HasDest ? TieLanding(portal) : null; + } + + private void OnPortalTied() + { + AtlasLocation? portal = TiePortal(60); if (portal == null || !portal.HasDest) { Say("Portal tie noted, but the portal isn't in the Atlas: its recall won't be used for routes."); return; } - var spot = portal.DestOnMap - ? new RecallSpot { OnMap = true, Ns = portal.DestNs, Ew = portal.DestEw, Label = portal.Name } - : new RecallSpot { OnMap = false, Label = portal.DestName.Length > 0 ? portal.DestName : portal.Name }; + RecallSpot spot = TieLanding(portal); bool k1 = _known?.Contains(RecallPlanner.PrimaryPortalTie) ?? false, k2 = _known?.Contains(RecallPlanner.SecondaryPortalTie) ?? false; if (k1 && !k2) { _memory.Set(_charKey, RecallSlot.Tie1, spot); Say($"Primary portal tie: {portal.Name}."); return; } if (k2 && !k1) { _memory.Set(_charKey, RecallSlot.Tie2, spot); Say($"Secondary portal tie: {portal.Name}."); return; } @@ -819,7 +982,7 @@ public sealed partial class RynthNavPlugin "/rnav arrow | arrow off | arrow route — the arrow\n" + "/rnav go — walk there (route with portals/recalls when /rnav portals on)\n" + "/rnav route — plan a route (portals and recalls), no walking\n" + - "/rnav atlas — find places | fav [place] — favorite | recalls [on|off] | tie 1|2\n" + + "/rnav atlas — find places | fav [place] — favorite | recalls [on|off] | tie 1|2|lifestone\n" + "/rnav goto | preview | portals on|off | stop | here | load | test | navdata\n" + "/rnav avoid — show; avoid portals on|off| | walls on|off| | corners \n" + "/rnav markers on|off | markers labels on|off | markers guide on|off — the trip on the ground\n" + @@ -1026,14 +1189,46 @@ public sealed partial class RynthNavPlugin foreach (string n in notes) Say(" " + n); } + /// + /// /rnav tie 1|2: which portal tie the last one (or the last tie recall cast by hand) was; + /// with none waiting, the portal you have selected or stand at is that tie (a tie made + /// before RynthNav was there). /rnav tie lifestone: the lifestone you have selected or + /// stand at is the one Lifestone Recall is tied to. /rnav tie clear 1|2|lifestone forgets one. + /// private void CmdTie(string rest) { - if (_pendingTie == null || _charKey.Length == 0) { Note("no portal tie waiting — cast a Portal Tie on a portal first"); return; } - RecallSlot slot = rest.Trim() == "2" ? RecallSlot.Tie2 : rest.Trim() == "1" ? RecallSlot.Tie1 : (RecallSlot)(-1); - if ((int)slot < 0) { Say("/rnav tie 1 (primary) or /rnav tie 2 (secondary)"); return; } - _memory.Set(_charKey, slot, _pendingTie); - Note($"{(slot == RecallSlot.Tie1 ? "Primary" : "Secondary")} portal tie: {Describe(_pendingTie)}"); - _pendingTie = null; + if (_charKey.Length == 0) { Note("not logged in yet"); return; } + string arg = rest.Trim().ToLowerInvariant(); + bool clear = arg.StartsWith("clear", StringComparison.Ordinal); + if (clear) arg = arg.Substring(5).Trim(); + RecallSlot slot = arg switch + { + "1" => RecallSlot.Tie1, + "2" => RecallSlot.Tie2, + "lifestone" or "ls" => RecallSlot.Lifestone, + _ => (RecallSlot)(-1), + }; + if ((int)slot < 0) { Say("/rnav tie 1 (primary) | 2 (secondary) | lifestone, or /rnav tie clear 1|2|lifestone"); return; } + string name = RecallPlanner.Title(slot); + if (clear) + { + _memory.Clear(_charKey, slot); + Note($"{name}: landing forgotten (routes won't use it until it's learned again)"); + return; + } + RecallSpot? spot; + if (slot == RecallSlot.Lifestone) + { + // The Atlas lifestone at the selected object (anything else selected doesn't count), else the nearest one. + RecallSpot? sel = SelectedObjectSpot(out _); + AtlasLocation? ls = sel != null && sel.OnMap ? _atlas.Nearest("Lifestone", sel.Ns, sel.Ew, LifestoneLandUnits) : null; + spot = ls != null ? new RecallSpot { OnMap = true, Ns = ls.Ns, Ew = ls.Ew, Label = ls.Name } : NearestAtlasSpot("Lifestone", 40); + if (spot == null) { Note("tie lifestone: select your tied lifestone, or stand at it, first"); return; } + } + else if (_pendingTie != null) { spot = _pendingTie; _pendingTie = null; } + else if ((spot = TiedPortalSpot(out string why)) == null) { Note($"tie {arg}: {why}"); return; } + _memory.Set(_charKey, slot, spot); + Note($"{name}: {Describe(spot)}"); } /// Plans a route (portals and, unless off, recalls) and shows it in the panel. Tick thread. diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs index d5dc65d..95dd336 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs @@ -496,6 +496,15 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // needs no navmesh here. bool recallFirst = _route != null && _route.Count > 0 && (_route[0].UseRecall || _route[0].IsHub); uint hereLb = CurrentLandblock; + // A dungeon's landblock has a tile too, but it's the surface's (dungeon cells aren't + // baked): walking on it inside the dungeon runs into walls. Say so instead. + if (!recallFirst && InDungeon(_cellId)) + { + _route = null; + lock (_gate) { _status = $"in a dungeon (0x{hereLb:X4}): no navmesh"; _lastPath = ""; } + Note($"goto: no navmesh inside dungeons yet (landblock 0x{hereLb:X4}); walk out through its portal, or turn on recalls so the route can start with one"); + return; + } if (!recallFirst && !File.Exists(Path.Combine(NavDataDir, $"nav_{hereLb:X4}.tile"))) { _route = null; @@ -638,6 +647,15 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // ArrivalUnits from the typed point. Standing on that spot is arriving. bool atMeshGoal = !isPortalLeg && _goalOnMesh && Math.Sqrt((_goalMeshEw - _wx) * (_goalMeshEw - _wx) + (_goalMeshNs - _wy) * (_goalMeshNs - _wy)) < ArrivalUnits; + // A portal is run into straight from PortalArriveUnits: only with nothing between, as far as + // the navmesh shows. A portal round a corner (a wall within 14 u of it) is reached along + // the path first; it used to be run at through the wall, 12 s a try, five tries. + if (isPortalLeg && toGoal < arrive && toGoal > PortalContactUnits && !atMeshGoal) + { + bool pathLeft; + lock (_gotoGate) pathLeft = _gotoPath != null && _gotoIdx < _gotoPath.Count; + if (pathLeft && !StraightOnMesh(_gotoTew, _gotoTns)) arrive = PortalContactUnits; + } if (toGoal < arrive || atMeshGoal) { OnSubGoalReached(); @@ -650,7 +668,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // Following a route over land, progress is what's left of the route (it can lead away // from the target for a while); otherwise the straight distance. double left = _coarse != null ? _coarse.Remaining(_wx, _wy) : toGoal; - if (left < _bestDist - ProgressUnits) { _bestDist = left; _bestTick = _legTicks; } + if (left < _bestDist - ProgressUnits) { _bestDist = left; _bestTick = _legTicks; _stuckTries = 0; } else if (_coarse != null && left > _bestDist + RouteLostUnits) { // Following a route but getting ever farther from it: stop rather than wander. @@ -664,6 +682,8 @@ public sealed partial class RynthNavPlugin : RynthPluginBase FinishGoto($"stopped: no progress for 30 s, {toGoal:F0}u short ({why})"); return; } + // Running into something (RynthNavPlugin.Blocked.cs): turn away, plan again, or stop and say where. + if (StepBlocked()) return; // Plan at once, re-plan every 20 ticks, and every 5 while there is no plan. bool due = _gotoPath == null ? (_replanTick++ % 5) == 0 : (++_replanTick % 20) == 0; @@ -709,7 +729,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // Straight at the goal, or along the route at its next crossing. double bh = (_coarse != null ? Math.Atan2(_aimEw - _wx, _aimNs - _wy) : Math.Atan2(fdew, fdns)) * 180.0 / Math.PI; bh = SteerRoundPortals(bh < 0 ? bh + 360.0 : bh, 10.0); - DriveTo(bh); + WalkDrive(bh); if (_blindTicks % 10 == 0) lock (_gotoGate) _gotoPath = null; // re-plan soon } else if (_blindTicks++ == BlindPushTicks) @@ -728,7 +748,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // hub portals' circles, a wall beside), it held 234 deg into the wall while the path wanted // 301 and re-planned every 0.6 s (10-01 20:07, "just spazzing"). Steering is for the // blind push and the last steps onto a portal, where there is no path. - DriveTo(desired); + WalkDrive(desired); } // ── Portal routing ─────────────────────────────────────────────────────────── @@ -776,6 +796,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase else { _gotoTew = _finalTew; _gotoTns = _finalTns; } // New leg: fresh progress watchdog, and the old leg's walkable end no longer counts. ResetHub(); + ResetBlocked(); _coarseHoldTicks = _graph != null ? CoarseHoldMaxTicks : 0; _nextAvoidMs = 0; _walkHaveLast = false; // a new leg starts where the last step's teleport put us @@ -790,6 +811,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase _gotoActive = false; _route = null; _portalWait = false; ResetHub(); _avoid.Clear(); _coarseHoldTicks = 0; + ResetBlocked(); Host.SetAutoRun(false); Host.StopCompletely(); lock (_gate) _status = status; Host.Log($"[RynthNav] goto: {status}"); @@ -942,7 +964,11 @@ public sealed partial class RynthNavPlugin : RynthPluginBase var filter = new DtQueryDefaultFilter(); var startP = new RcVec3f((float)_wx, (float)_wz, (float)_wy); - _query.FindNearestPoly(startP, new RcVec3f(8, 64, 8), filter, out long sRef, out RcVec3f sPt, out _); + // The ground we stand on first: the mesh keeps the agent radius (2 m) from walls, so close + // up it's within that, at our height. Only then the wide search, which can pick ground on + // the far side of a thin wall or a roof overhead, and the walk then runs into that wall. + _query.FindNearestPoly(startP, new RcVec3f(2.5f, 4, 2.5f), filter, out long sRef, out RcVec3f sPt, out _); + if (sRef == 0) _query.FindNearestPoly(startP, new RcVec3f(8, 64, 8), filter, out sRef, out sPt, out _); // A failed plan drops the old one: StepGoto must not keep following a stale path. if (sRef == 0) { lock (_gate) _status = "off navmesh"; lock (_gotoGate) _gotoPath = null; return; } @@ -1025,8 +1051,10 @@ public sealed partial class RynthNavPlugin : RynthPluginBase double ox = -(ux / ul + vx / vl), oy = -(uy / ul + vy / vl), ol = Math.Sqrt(ox * ox + oy * oy); if (ol < 0.05) continue; // straight on: no corner to clear double nx = px + ox / ol * _wallClearance, ny = py + oy / ol * _wallClearance; - q2.FindNearestPoly(new RcVec3f((float)nx, (float)_wz, (float)ny), new RcVec3f(0.3f, 24, 0.3f), filter, out long rr, out _, out _); - if (rr != 0) wps[i] = (nx, ny); + // Only onto walkable ground itself (inside a polygon), not merely near it: near it, + // the moved corner could sit closer to the wall than the body is wide. + q2.FindNearestPoly(new RcVec3f((float)nx, (float)_wz, (float)ny), new RcVec3f(0.3f, 24, 0.3f), filter, out long rr, out RcVec3f rp, out _); + if (rr != 0 && Math.Abs(rp.X - nx) < 0.05 && Math.Abs(rp.Z - ny) < 0.05) wps[i] = (nx, ny); } } lock (_gotoGate) { _gotoPath = wps; _gotoIdx = 0; } @@ -1161,9 +1189,10 @@ public sealed partial class RynthNavPlugin : RynthPluginBase bool exists = File.Exists(Path.Combine(NavDataDir, $"nav_{lb:X4}.tile")); int onDisk = 0; try { if (Directory.Exists(NavDataDir)) onDisk = Directory.GetFiles(NavDataDir, "nav_*.tile").Length; } catch { } - bool indoors = (_cellId & 0xFFFF) >= 0x0100; + bool indoors = (_cellId & 0xFFFF) >= 0x0100, dungeon = InDungeon(_cellId); string status; lock (_gate) status = _status; - return $"landblock 0x{lb:X4}{(indoors ? " (indoors)" : "")} — tile {(exists ? "FOUND" : "MISSING")}, {_tileCount} loaded, " + return $"landblock 0x{lb:X4}{(dungeon ? " (a dungeon)" : indoors ? " (indoors)" : "")} — tile " + + $"{(dungeon ? (exists ? "surface only, no dungeon navmesh" : "MISSING") : exists ? "FOUND" : "MISSING")}, {_tileCount} loaded, " + $"{onDisk} tile(s) in {NavDataDir}; route graph: {_graphStatus}; Town Network: {_townNetStatus}; goto {(_gotoActive ? "ACTIVE" : "off")}" + $"{(_coarse != null ? $" (route {_coarse.Crossed}/{_coarse.Count})" : "")}, portals {(_portalsEnabled ? "on" : "off")}; status: {status}"; } diff --git a/Shared/RynthCore.LootSdk/Editing/LootEditWire.cs b/Shared/RynthCore.LootSdk/Editing/LootEditWire.cs index 41afa86..ad658ce 100644 --- a/Shared/RynthCore.LootSdk/Editing/LootEditWire.cs +++ b/Shared/RynthCore.LootSdk/Editing/LootEditWire.cs @@ -133,6 +133,11 @@ public sealed class LootEditItemRequest public string RuleName { get; set; } = string.Empty; /// True: the profile open in the Loot Editor; false: the one RynthAi loots with. public bool ToOpenProfile { get; set; } + /// + /// Also require the item's T11 attributes (LootItemRuleOptions.IncludeT11). Added + /// 2026-10-07; an older engine never sends it, so it reads false. + /// + public bool IncludeT11 { get; set; } /// Echoed in the draft so the popup knows the answer is to its latest ask. public int Seq { get; set; } } @@ -156,6 +161,10 @@ public sealed class LootEditItemDraft public string Format { get; set; } = string.Empty; /// What was built (the defaults filled in). public int Match { get; set; } + /// The rule was asked to include the item's T11 attributes (added 2026-10-07). + public bool IncludeT11 { get; set; } + /// The item is T11 gear, so "Include T11 attributes" has something to add (added 2026-10-07). + public bool IsT11 { get; set; } public int Action { get; set; } public int KeepCount { get; set; } public string RuleName { get; set; } = string.Empty; diff --git a/Shared/RynthCore.LootSdk/Editing/LootItemRules.cs b/Shared/RynthCore.LootSdk/Editing/LootItemRules.cs index bd316ba..d6939c5 100644 --- a/Shared/RynthCore.LootSdk/Editing/LootItemRules.cs +++ b/Shared/RynthCore.LootSdk/Editing/LootItemRules.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Text; +using RynthCore.Loot.T11; using RynthCore.Loot.VTank; namespace RynthCore.Loot.Editing; @@ -26,6 +27,11 @@ public sealed class LootItemFacts public Dictionary Doubles { get; set; } = new(); /// The item's spell names (empty when none or not identified). public List Spells { get; set; } = new(); + /// + /// The item's T11 reading (ACECustom tier 11+ text), or null when it wasn't asked for. + /// for an item that isn't T11 gear. + /// + public T11ItemInfo? T11 { get; set; } public bool Stackable => MaxStackSize > 1 || StackSize > 1; @@ -53,6 +59,11 @@ public sealed class LootItemRuleOptions public int? KeepCount { get; set; } /// Null or blank: "Keep Copper Pea" and the like. public string? RuleName { get; set; } + /// + /// Also require the item's T11 attributes (tier, grade, damage %, each modifier, slot + /// special, Cast on Strike), each at least as good as this item's. Works with any match. + /// + public bool IncludeT11 { get; set; } } /// A built rule, ready to preview and insert. @@ -155,6 +166,7 @@ public static class LootItemRules }; bool hasClass = f.ObjectClass != (int)AcObjectClass.Unknown; LootItemMatch match = o.Match; + bool likeBare = false; if (match == LootItemMatch.NameAndClass && !hasClass) { match = LootItemMatch.Name; @@ -177,13 +189,15 @@ public static class LootItemRules return null; } rule.Conditions.Add(Cond(VTankNodeTypes.ObjectClass, Num(f.ObjectClass))); - int extra = AddLikeConditions(rule, f, notes); - if (extra == 0) - notes.Add($"Nothing but the class to go on: this rule matches every {ClassName(f.ObjectClass)}." - + (f.Ints.Count == 0 ? " (Assess the item first for its material, workmanship and stats.)" : string.Empty)); + likeBare = AddLikeConditions(rule, f, notes) == 0; break; } + int t11Added = o.IncludeT11 ? AddT11Conditions(rule, f, notes) : 0; + if (likeBare && t11Added == 0) + notes.Add($"Nothing but the class to go on: this rule matches every {ClassName(f.ObjectClass)}." + + (f.Ints.Count == 0 ? " (Assess the item first for its material, workmanship and stats.)" : string.Empty)); + string defaultName = DefaultRuleName(name.Length > 0 ? name : ClassName(f.ObjectClass), action, keep, match); string ruleName = OneLine(o.RuleName).Trim(); rule.Name = ruleName.Length > 0 ? ruleName : defaultName; @@ -248,6 +262,59 @@ public static class LootItemRules return rule.Conditions.Count - n; } + /// + /// The T11 conditions, on RynthAi's virtual T11 keys: Is T11, then tier, grade, damage %, + /// every catalogued modifier, slot special and Cast on Strike count, each at least this + /// item's. Left out on purpose: Can Wield (the character, not the item), Zone Locked + /// (where it was appraised), the wield gates (they follow from the tier) and the modifier + /// count / rating total / roll % (they follow from the per-modifier values). + /// How many it added. + /// + private static int AddT11Conditions(VTankLootRule rule, LootItemFacts f, List notes) + { + T11ItemInfo? t = f.T11; + if (t == null || !t.IsT11) + { + notes.Add("Not a T11 item, so there are no T11 attributes to add."); + return 0; + } + + int n = rule.Conditions.Count; + void Equal(int key, int v) => rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyE, Num(v), Num(key))); + void AtLeast(int key, int v) { if (v > 0) rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyGE, Num(v), Num(key))); } + + Equal(T11Keys.IsT11, 1); + if (!t.HasText) + { + notes.Add("The item hasn't been identified, so only \"Is T11\" could be added. Assess it and preview again for its tier, grade and modifiers."); + return rule.Conditions.Count - n; + } + + AtLeast(T11Keys.EstimatedTier, t.EstimatedTier); + AtLeast(T11Keys.WeaponGrade, t.GradeRank); + AtLeast(T11Keys.DamagePercent, t.DamagePercent); + + bool valuelessSpecial = false; + var unknown = new List(); + foreach (T11Modifier m in t.Modifiers) + { + if (T11Catalog.ModifierByKey(m.Key) == null) + { + unknown.Add(m.Name); + continue; + } + // A modifier's key reads 0 when it is absent, so a value-less one can't be required by value. + if (m.Value > 0) AtLeast(T11Keys.ForModifier(m.Key), m.Value); + else if (m.IsSlotSpecial) valuelessSpecial = true; + } + if (valuelessSpecial) Equal(T11Keys.HasSlotSpecial, 1); + AtLeast(T11Keys.CastOnStrikeCount, t.Procs.Count); + + if (unknown.Count > 0) + notes.Add("Left out (RynthAi has no loot key for these modifiers yet): " + string.Join(", ", unknown) + "."); + return rule.Conditions.Count - n; + } + private static VTankLootCondition Cond(int type, params string[] lines) => new(type, "0", lines); private static string Num(int v) => v.ToString(CultureInfo.InvariantCulture); diff --git a/Tools/RynthCore.AutoVendorTests/Program.cs b/Tools/RynthCore.AutoVendorTests/Program.cs index f572224..fb2833d 100644 --- a/Tools/RynthCore.AutoVendorTests/Program.cs +++ b/Tools/RynthCore.AutoVendorTests/Program.cs @@ -480,7 +480,6 @@ internal static class Program (new SafetyFacts { Appraised = true, Value = 100, CanBeSold = false }, "not sellable"), (new SafetyFacts { Appraised = true, Value = 100, IsRare = true }, "rare"), (new SafetyFacts { Appraised = true, Value = 100, Attuned = 1 }, "attuned"), - (new SafetyFacts { Appraised = true, Value = 100, Bonded = 1 }, "bonded"), (new SafetyFacts { Appraised = true, Value = 100, Retained = true }, "retained"), (new SafetyFacts { Appraised = true, Value = 100, TimesTinkered = 1 }, "tinkered"), (new SafetyFacts { Appraised = true, Value = 100, Imbued = 1 }, "imbued"), @@ -495,6 +494,8 @@ internal static class Program var side = new SafetyFacts { Appraised = true, Class = AcObjectClass.Salvage, Value = 100, InMainPack = false }; Eq(AutoVendorPlanner.UnsafeReason(side, false), null, "side pack ok by default"); + // Bonded only decides what a death keeps on ACE: peas, trade notes and salvage are bonded and sell (2026-10-07). + Eq(AutoVendorPlanner.UnsafeReason(new SafetyFacts { Appraised = true, Value = 12500, Bonded = 1 }, false), null, "bonded (kept on death) still sells"); Eq(AutoVendorPlanner.UnsafeReason(side, true), "not in main pack", "OnlyFromMainPack"); } diff --git a/Tools/RynthCore.LootSdkTests/LootAddT11Tests.cs b/Tools/RynthCore.LootSdkTests/LootAddT11Tests.cs new file mode 100644 index 0000000..975d404 --- /dev/null +++ b/Tools/RynthCore.LootSdkTests/LootAddT11Tests.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Loot; +using RynthCore.Loot.Editing; +using RynthCore.Loot.T11; +using RynthCore.Loot.VTank; + +namespace RynthCore.LootSdkTests; + +// "Add to loot profile" with "Include T11 attributes" (2026-10-07): the T11 conditions a +// clicked item adds, on the server-format weapon and armor text LootT11Tests parses. +internal static partial class Program +{ + private static void RunLootAddT11Tests() + { + Console.WriteLine("\n-- LootAdd: include T11 attributes --"); + TestAddT11Weapon(); + TestAddT11Armor(); + TestAddT11EdgeCases(); + } + + /// A condition as "type:line,line" for order-sensitive comparisons. + private static string CondText(VTankLootCondition c) => c.NodeType + ":" + string.Join(",", c.DataLines); + + private static string GE(int key, int v) => $"{VTankNodeTypes.LongValKeyGE}:{v},{key}"; + private static string EQ(int key, int v) => $"{VTankNodeTypes.LongValKeyE}:{v},{key}"; + + private static List T11Conds(VTankLootRule r) => + r.Conditions.Where(c => c.DataLines.Count == 2 && int.TryParse(c.DataLines[1], out int k) && T11Keys.IsVirtual(k)) + .Select(CondText).ToList(); + + private static LootItemFacts T11Facts(string name, AcObjectClass cls, string? longDesc, string? use) => new() + { + Id = 0x7000_0001, + Name = name, + ObjectClass = (int)cls, + T11 = T11ItemInfo.Parse(name, longDesc, use), + }; + + private static void TestAddT11Weapon() + { + LootItemFacts f = T11Facts("T11 - Tachi", AcObjectClass.MeleeWeapon, T11WeaponLongDesc, null); + + LootItemRuleDraft? off = LootItemRules.Build(f, new LootItemRuleOptions(), out _); + Eq(off == null ? -1 : T11Conds(off.Rule).Count, 0, "add t11: unchecked adds no T11 conditions"); + + LootItemRuleDraft? d = LootItemRules.Build(f, new LootItemRuleOptions { IncludeT11 = true }, out string err); + Check(d != null, "add t11: weapon builds (" + err + ")"); + if (d == null) return; + Eq(CondText(d.Rule.Conditions[0]), $"{VTankNodeTypes.ObjectClass}:{(int)AcObjectClass.MeleeWeapon}", "add t11: name + class first"); + Eq(string.Join(" | ", T11Conds(d.Rule)), string.Join(" | ", new[] + { + EQ(T11Keys.IsT11, 1), + GE(T11Keys.EstimatedTier, 13), + GE(T11Keys.WeaponGrade, 12), + GE(T11Keys.DamagePercent, 86), + GE(T11Keys.ForModifier(28), 41), // Damage Rating + GE(T11Keys.ForModifier(29), 10), // Crit Damage Rating + GE(T11Keys.ForModifier(44), 2), // Pct HP Damage: a slot special with a value + GE(T11Keys.CastOnStrikeCount, 1), + }), "add t11: weapon conditions, at least this item's"); + Check(d.Rule.Conditions.All(c => CondText(c) != EQ(T11Keys.HasSlotSpecial, 1)), "add t11: valued special needs no Has Slot Special"); + Check(d.Rule.Conditions.All(c => CondText(c) != EQ(T11Keys.ZoneLocked, 1)), "add t11: zone lock left out"); + Eq(d.Notes.Count, 0, "add t11: weapon has no notes"); + Check(LootItemRules.PreviewLines(d.Rule).Any(l => l.Contains("T11 Mod: Damage Rating")), "add t11: preview names the modifier key"); + + var dropped = new List(); + LootRule? native = LootItemRules.ToNative(d.Rule, dropped); + Eq(dropped.Count, 0, "add t11: native format keeps every T11 condition"); + Eq(native?.Conditions.Count ?? -1, d.Rule.Conditions.Count, "add t11: native condition count"); + } + + private static void TestAddT11Armor() + { + LootItemFacts f = T11Facts("T11 - Celdon Breastplate", AcObjectClass.Armor, T11ArmorLongDesc, T11ArmorUse); + LootItemRuleDraft? d = LootItemRules.Build(f, new LootItemRuleOptions { IncludeT11 = true }, out _); + Check(d != null, "add t11: armor builds"); + if (d == null) return; + List t = T11Conds(d.Rule); + Check(t.Contains(GE(T11Keys.EstimatedTier, 16)), "add t11: armor tier from the Triune Weave gate"); + Check(!t.Any(c => c.EndsWith("," + T11Keys.WeaponGrade)), "add t11: no grade on armor"); + Check(t.Contains(GE(T11Keys.ForModifier(50), 8)), "add t11: Damage Resist"); + Check(t.Contains(GE(T11Keys.ForModifier(19), 120)), "add t11: Max Health"); + Check(t.Contains(GE(T11Keys.ForModifier(47), 2)), "add t11: Max Health Pct"); + Check(!t.Any(c => c.EndsWith("," + T11Keys.ForModifier(60))), "add t11: unknown modifier has no condition"); + Check(d.Notes.Any(n => n.Contains("Modifier 60")), "add t11: unknown modifier named in a note"); + } + + private static void TestAddT11EdgeCases() + { + // Not T11 gear: a note, no conditions. + var plain = new LootItemFacts { Id = 2, Name = "Iron Mace", ObjectClass = (int)AcObjectClass.MeleeWeapon, T11 = T11ItemInfo.None }; + LootItemRuleDraft? p = LootItemRules.Build(plain, new LootItemRuleOptions { IncludeT11 = true }, out _); + Eq(p == null ? -1 : T11Conds(p.Rule).Count, 0, "add t11: non-T11 item adds nothing"); + Check(p != null && p.Notes.Any(n => n.StartsWith("Not a T11 item")), "add t11: non-T11 note"); + + // T11 by name but not identified yet: Is T11 only, and a note to assess it. + LootItemFacts unid = T11Facts("T11 - Tachi", AcObjectClass.MeleeWeapon, null, null); + LootItemRuleDraft? u = LootItemRules.Build(unid, new LootItemRuleOptions { IncludeT11 = true }, out _); + Eq(u == null ? "" : string.Join(" | ", T11Conds(u.Rule)), EQ(T11Keys.IsT11, 1), "add t11: unidentified gives Is T11 only"); + Check(u != null && u.Notes.Any(n => n.Contains("hasn't been identified")), "add t11: unidentified note"); + + // A value-less slot special is required through Has Slot Special. + LootItemFacts ring = T11Facts("T11 - Ring", AcObjectClass.Jewelry, null, "Modifiers:\n- Fortify Vitals\n"); + LootItemRuleDraft? r = LootItemRules.Build(ring, new LootItemRuleOptions { IncludeT11 = true }, out _); + Check(r != null && T11Conds(r.Rule).Contains(EQ(T11Keys.HasSlotSpecial, 1)), "add t11: value-less special -> Has Slot Special"); + + // "Items like this": T11 conditions count, so the "matches every X" warning goes away. + LootItemFacts like = T11Facts("T11 - Tachi", AcObjectClass.MeleeWeapon, T11WeaponLongDesc, null); + LootItemRuleDraft? l = LootItemRules.Build(like, new LootItemRuleOptions { Match = LootItemMatch.Like, IncludeT11 = true }, out _); + Check(l != null && !l.Notes.Any(n => n.StartsWith("Nothing but the class")), "add t11: like + T11 is not class-only"); + Check(l != null && l.Rule.Conditions.All(c => c.NodeType != VTankNodeTypes.StringValueMatch), "add t11: like still has no name"); + LootItemRuleDraft? bare = LootItemRules.Build(plain, new LootItemRuleOptions { Match = LootItemMatch.Like, IncludeT11 = true }, out _); + Check(bare != null && bare.Notes.Any(n => n.StartsWith("Nothing but the class")), "add t11: like + non-T11 still warns class-only"); + } +} diff --git a/Tools/RynthCore.LootSdkTests/Program.cs b/Tools/RynthCore.LootSdkTests/Program.cs index c0069ca..e12d48e 100644 --- a/Tools/RynthCore.LootSdkTests/Program.cs +++ b/Tools/RynthCore.LootSdkTests/Program.cs @@ -45,6 +45,7 @@ internal static partial class Program RunLootEditTests(args); RunLootAddTests(args); RunT11Tests(); + RunLootAddT11Tests(); Console.WriteLine($"\nGolden tests: {_asserts} assertions, {_fails} failed."); diff --git a/Tools/RynthCore.MonsterEditor/MainWindow.axaml b/Tools/RynthCore.MonsterEditor/MainWindow.axaml index 79b88a8..5412c54 100644 --- a/Tools/RynthCore.MonsterEditor/MainWindow.axaml +++ b/Tools/RynthCore.MonsterEditor/MainWindow.axaml @@ -124,6 +124,14 @@ + + + + + + diff --git a/Tools/RynthCore.MonsterEditor/Models.cs b/Tools/RynthCore.MonsterEditor/Models.cs index ec0d509..c16fa39 100644 --- a/Tools/RynthCore.MonsterEditor/Models.cs +++ b/Tools/RynthCore.MonsterEditor/Models.cs @@ -18,7 +18,7 @@ public class MonsterRule : INotifyPropertyChanged private string _damageType = "Auto"; private int _weaponId; private bool _fester, _broadside, _gravityWell, _imperil, _yield, _vuln; - private bool _useArc, _useBolt = true, _useRing, _useStreak, _useBlast; + private bool _useArc, _useBolt = true, _useRing, _useStreak, _useBlast, _useWall; private string _exVuln = "None"; private int _offhandId; private string _petDamage = "PAuto"; @@ -46,6 +46,7 @@ public class MonsterRule : INotifyPropertyChanged public bool UseRing { get => _useRing; set { _useRing = value; OnPropertyChanged(); } } public bool UseStreak { get => _useStreak; set { _useStreak = value; OnPropertyChanged(); } } public bool UseBlast { get => _useBlast; set { _useBlast = value; OnPropertyChanged(); } } + public bool UseWall { get => _useWall; set { _useWall = value; OnPropertyChanged(); } } public string ExVuln { get => _exVuln; set { _exVuln = value; OnPropertyChanged(); } } public int OffhandId { get => _offhandId; set { _offhandId = value; OnPropertyChanged(); } } public string PetDamage { get => _petDamage; set { _petDamage = value; OnPropertyChanged(); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index b12bc04..40a2cd0 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -91,6 +91,9 @@ internal static unsafe class FakeHost public static bool GiveCalls; /// Every GiveObjectTo (item, target, amount; 0 = the whole object), in order. public static readonly List<(uint Item, uint Target, int Amount)> Gives = new(); + /// When true (the default) a give lands at once, as the server does when it isn't busy: + /// the item goes to the target. False = the server hasn't taken it (still carried). + public static bool GiveLands = true; /// Opt-in: wires StopCompletely (off by default so no other test sees it). public static bool StopCalls; /// StopCompletely calls (opt-in with ). @@ -196,7 +199,7 @@ internal static unsafe class FakeHost Vitals = default; BaseVitals = default; WorldName = ""; AccountName = ""; HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0; Logs.Clear(); Chat.Clear(); ChatCommands.Clear(); - AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear(); + AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear(); GiveLands = true; Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1; VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0; ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false; @@ -631,7 +634,12 @@ internal static unsafe class FakeHost [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetBusyState() => BusyStateValue; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GiveObjectTo(uint item, uint target, int amount) { Gives.Add((item, target, amount)); return 1; } + private static int GiveObjectTo(uint item, uint target, int amount) + { + Gives.Add((item, target, amount)); + if (GiveLands && amount == 0) Containers[item] = target; + return 1; + } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetCurrentCombatMode() => CombatModeValue; diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 320a21b..efff52e 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -69,6 +69,7 @@ internal static class Program HealLatencyTests.Register(runner); BlastTests.Register(runner); ArcWhenClearTests.Register(runner); + WallTests.Register(runner); UseAtLoginTests.Register(runner); LearnSpellsTests.Register(runner); AttackLatencyTests.Register(runner); @@ -82,6 +83,9 @@ internal static class Program ItemInfoTests.Register(runner); NavOverlayTests.Register(runner); ActionPacingTests.Register(runner); + HazardEscapeTests.Register(runner); + ManaStoneChoiceTests.Register(runner); + CustomDebuffTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/AttackLatencyTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/AttackLatencyTests.cs index aff7402..db4ea89 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/AttackLatencyTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/AttackLatencyTests.cs @@ -87,7 +87,9 @@ internal static class AttackLatencyTests Check.Eq(CombatManager.AttackIntervalMs(Missile, 1500, true, true), 1000.0, "missile: 1000 ms"); Check.Eq(CombatManager.AttackIntervalMs(Magic, 1500, true, false), 1500.0, "magic, same target: the setting"); Check.Eq(CombatManager.AttackIntervalMs(Magic, 2500, true, false), 2500.0, "magic, same target: a slower setting is kept"); - Check.Eq(CombatManager.AttackIntervalMs(Magic, 0, true, false), 1500.0, "magic, setting 0 (old file): 1500"); + Check.Eq(CombatManager.AttackIntervalMs(Magic, 0, true, false), 0.0, "magic, setting 0: no delay of its own (the server gates hold the cast)"); + Check.Eq(CombatManager.AttackIntervalMs(Magic, 0, false, false), CombatManager.NoGatesAttackFloorMs, "setting 0 without the server gates: the 250 ms floor"); + Check.Eq(CombatManager.AttackIntervalMs(Magic, -1, true, false), 1500.0, "unset: 1500"); Check.Eq(CombatManager.AttackIntervalMs(Magic, 1500, true, true), CombatManager.NewTargetCastFloorMs, "magic, new target, server gates: the short floor (UseDone + gesture hold the cast)"); Check.Eq(CombatManager.AttackIntervalMs(Magic, 1500, false, true), 1500.0, diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs index 7dd5cb5..e996a29 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs @@ -21,7 +21,7 @@ namespace RynthCore.RynthAiHostTests.Tests; internal static class BuffTests { private const uint Player = 0x50000B01; - private const uint STypeCreature = 31, STypeItem = 32; + private const uint STypeCreature = 31, STypeItem = 32, STypeLife = 33; /// Buff/tier pairs the name tables used to miss (fixed by 940cb21); NameGapsResolve checks them by name. private static readonly HashSet<(string Buff, int Tier)> NameGaps = new() @@ -54,6 +54,9 @@ internal static class BuffTests r.Add("rebuff: our own lower tier under an expiring higher one counts as on", RebuffUnderExpiringHigherTier); r.Add("rebuff: cast over item-granted buffs (CastBuffsOverItemBuffs on)", RebuffOverItemBuffs); r.Add("rebuff: CastBuffsOverItemBuffs defaults on, loads, saves, bridges", OverItemBuffsSetting); + r.Add("buff toggles: by default every prot and bane is cast", TogglesDefaultAllOn); + r.Add("buff toggles: an unticked prot or bane is never cast and never holds NeedsAnyBuff", UntickedSkipped); + r.Add("buff toggles: an old profile loads all on; the list saves, copies and bridges", TogglesSetting); r.Add("buff choice: spell names the tables miss (Bludgeon Bane, Nuhmudira's, T'ing, Celdiseth's)", NameGapsResolve); // was a known failure; fixed by 940cb21 r.Add("buff choice: a mastery whose name has several spell ids", MultiIdMastery); // was a known failure; fixed by 0aedcee @@ -596,6 +599,129 @@ internal static class BuffTests Check.True(s.CastBuffsOverItemBuffs, "a save with it on turns it on"); } + // ── Prot and bane toggles (Buffing settings, DisabledBuffs) ─────────────── + + private static readonly MethodInfo CastSelfBuffs = + typeof(BuffManager).GetMethod("CheckAndCastSelfBuffs", BindingFlags.NonPublic | BindingFlags.Instance)!; + + /// Tier 6 Life and Item Magic, in Magic stance, knowing two prots and two banes. + private static BuffRig ProtBaneRig() + { + FakeHost.Reset(); + Know("Fire Protection Self VI", "Cold Protection Self VI", "Flame Bane VI", "Frost Bane VI"); + FakeHost.Skills[(Player, STypeLife)] = (300, 2); + FakeHost.Skills[(Player, STypeItem)] = (300, 2); + FakeHost.WeaponCalls = true; // GetCurrentCombatMode answers CombatModeValue + FakeHost.CombatModeValue = CombatMode.Magic; + return new BuffRig(); + } + + /// Runs the buff cast loop until it casts nothing, confirming each cast by chat as the + /// server would. Returns the spells cast in order; = the loop's last + /// answer was "nothing to do" (what ends a batch in the heartbeat). + private static List CastAll(BuffRig rig, out bool done) + { + var cast = new List(); + done = false; + for (int i = 0; i < 20; i++) + { + int before = FakeHost.Casts.Count; + bool acted = (bool)CastSelfBuffs.Invoke(rig.B, null)!; + if (FakeHost.Casts.Count == before) { done = !acted; break; } + string name = NameOf(FakeHost.Casts.Last().SpellId); + cast.Add(name); + rig.B.OnChatWindowText($"You cast {name} on {(name.Contains("Bane") ? "Rune Robe" : "yourself")}", 7); + } + return cast; + } + + private static void TogglesDefaultAllOn() + { + var rig = ProtBaneRig(); + Check.Eq(rig.S.DisabledBuffs.Count, 0, "a new profile unticks nothing"); + foreach (var (buff, _) in BuffManager.ToggleProtections.Concat(BuffManager.ToggleBanes)) + Check.True(rig.B.BuildDynamicBuffList().Contains(buff), $"every toggle names a buff in the list: {buff}"); + rig.Live(("Strength Self I", 3000)); // a registry read, with none of ours on + Check.True(rig.B.NeedsAnyBuff(), "nothing on: needs buffs"); + var cast = CastAll(rig, out bool done); + Check.Eq(string.Join(", ", cast), "Fire Protection Self VI, Cold Protection Self VI, Flame Bane VI, Frost Bane VI", $"all four are cast (last skip: {rig.B.LastBuffSkipReason})"); + Check.True(done, "then the loop has nothing left"); + } + + private static void UntickedSkipped() + { + var rig = ProtBaneRig(); + rig.S.SetBuffEnabled("Fire Protection Self", false); + rig.S.SetBuffEnabled("flame bane", false); // names match case-insensitively + Check.False(rig.B.BuildDynamicBuffList().Contains("Fire Protection Self"), "an unticked prot leaves the list"); + Check.False(rig.B.BuildDynamicBuffList().Contains("Flame Bane"), "an unticked bane leaves the list"); + rig.Live(("Strength Self I", 3000)); + var cast = CastAll(rig, out bool done); + Check.Eq(string.Join(", ", cast), "Cold Protection Self VI, Frost Bane VI", "only the ticked ones are cast"); + Check.True(done, "the loop ends with the unticked ones still off: the batch can finish"); + + // A fresh look, the ticked ones on and the unticked ones never cast: nothing is due. + var idle = ProtBaneRig(); + idle.S.SetBuffEnabled("Fire Protection Self", false); + idle.S.SetBuffEnabled("Flame Bane", false); + idle.Live(("Cold Protection Self VI", 3000)); + idle.B.OnChatWindowText("You cast Frost Bane VI on Rune Robe", 7); + Check.False(idle.B.NeedsAnyBuff(), "unticked and off doesn't hold Buffing"); + idle.S.SetBuffEnabled("Fire Protection Self", true); + Check.True(idle.B.NeedsAnyBuff(), "ticked again: Fire Protection is due"); + Check.False(idle.S.IsBuffDisabled("Fire Protection Self"), "and leaves the list"); + + // Force Rebuff recasts everything, still not the unticked ones. + var fr = ProtBaneRig(); + fr.S.SetBuffEnabled("Cold Protection Self", false); + fr.S.SetBuffEnabled("Frost Bane", false); + fr.Live(("Strength Self I", 3000)); + fr.B.ForceFullRebuff(); + cast = CastAll(fr, out done); + Check.Eq(string.Join(", ", cast), "Fire Protection Self VI, Flame Bane VI", "Force Rebuff skips the unticked ones too"); + Check.True(done, "and finishes"); + Check.False(FakeHost.Casts.Any(c => NameOf(c.SpellId) is "Cold Protection Self VI" or "Frost Bane VI"), "never cast"); + } + + private static void TogglesSetting() + { + var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true,\"RebuffSecondsRemaining\":300}", RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(old != null && old.DisabledBuffs.Count == 0, "a profile saved before the setting: all on"); + var nul = JsonSerializer.Deserialize("{\"DisabledBuffs\":null}", RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(nul != null && nul.DisabledBuffs.Count == 0, "a null list: all on"); + var some = new LegacyUiSettings(); + some.SetBuffEnabled("Acid Bane", false); + some.SetBuffEnabled("Blade Protection Self", false); + var back = JsonSerializer.Deserialize(JsonSerializer.Serialize(some, RynthAiJsonContext.Default.LegacyUiSettings), + RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(back != null && back.IsBuffDisabled("Acid Bane") && back.IsBuffDisabled("Blade Protection Self") && back.DisabledBuffs.Count == 2, + "unticked ones are saved and loaded"); + + // Profile switch/load copies it (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[] { some, dst }); + Check.True(dst.IsBuffDisabled("Acid Bane") && dst.DisabledBuffs.Count == 2, "a profile with unticked ones loads them"); + copy.Invoke(null, new object[] { old!, dst }); + Check.Eq(dst.DisabledBuffs.Count, 0, "an old profile loads all on"); + + // Engine Settings face: the payload carries the list; an engine without the field leaves it alone. + var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(payload != null && payload.DisabledBuffs == null, "an older engine's payload has no list"); + var s = new LegacyUiSettings(); + s.SetBuffEnabled("Frost Bane", 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)); + var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(sent?.DisabledBuffs != null && sent.DisabledBuffs.SequenceEqual(new[] { "Frost Bane" }), "sent to the engine face"); + dash.ApplySettingsJson("{\"PatrolOnLogin\":false}"); + Check.True(s.IsBuffDisabled("Frost Bane"), "a save without the list leaves it alone"); + dash.ApplySettingsJson("{\"DisabledBuffs\":[]}"); + Check.Eq(s.DisabledBuffs.Count, 0, "a save with an empty list ticks everything"); + } + private static BuffRig ArmorRig() { FakeHost.Reset(); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CustomDebuffTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CustomDebuffTests.cs new file mode 100644 index 0000000..e670091 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/CustomDebuffTests.cs @@ -0,0 +1,55 @@ +using System.Reflection; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-10-08: with Corruption V and VII known, the custom debuff "Corruption" cast V. A typed-in +// debuff was capped by Creature and Life alone; Corruption is Void, so the search started at VI. +internal static class CustomDebuffTests +{ + private const uint Player = 0x50000180; + private const uint STypeCreature = 31, STypeLife = 33, STypeVoid = 43; + + public static void Register(Runner r) + { + r.Add("custom debuff: a base name casts the highest known level, capped by Void too (Corruption VII, not V)", VoidCap); + } + + private static void VoidCap() + { + FakeHost.Reset(); + foreach (string n in new[] { "Corruption V", "Corruption VII" }) + foreach (var row in SpellTable.Named(n)) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeCreature)] = (250, 2); // tier 5 by the thresholds below + FakeHost.Skills[(Player, STypeLife)] = (250, 2); + FakeHost.Skills[(Player, STypeVoid)] = (400, 3); // tier 7 + var s = new LegacyUiSettings + { + MinSkillLevelTier1 = 0, MinSkillLevelTier2 = 50, MinSkillLevelTier3 = 100, MinSkillLevelTier4 = 150, + MinSkillLevelTier5 = 200, MinSkillLevelTier6 = 300, MinSkillLevelTier7 = 350, MinSkillLevelTier8 = 10000, + }; + var host = FakeHost.Create(Player); + var cache = FakeHost.MakeCache(host, Player, System.Array.Empty()); + var c = new CombatManager(host, s, cache); + c.SetPlayerId(Player); + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + sm.RefreshKnownSpells(); + c.SetSpellManager(sm); + + MethodInfo find = typeof(CombatManager).GetMethod("FindBestCustomDebuffWithTier", BindingFlags.NonPublic | BindingFlags.Instance)!; + object[] args = { "Corruption", 0 }; + int id = (int)find.Invoke(c, args)!; + Check.Eq(SpellTableStub.GetById(id)?.Name, "Corruption VII", "the highest known level"); + Check.Eq((int)args[1], 7, "tier 7"); + + object[] args5 = { "Corruption V", 0 }; + Check.Eq(SpellTableStub.GetById((int)find.Invoke(c, args5)!)?.Name, "Corruption V", "a full name still casts as is"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs index 7493ce7..8c117b5 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs @@ -27,6 +27,7 @@ internal static class GiveTests r.Add("give: /ub give with a count hands over that many", UbGiveCount); r.Add("give: /mt give hands over only the first match", MtGivesFirst); r.Add("give: /ub givep matches part of the name", UbGivePartial); + r.Add("give: the next give waits until the server took the last (it answers extra gives 'too busy')", WaitsForServer); } private sealed class World @@ -118,4 +119,20 @@ internal static class GiveTests Check.Eq(FakeHost.Gives.Count, 4, "partial: the three Mana Motes and the Lesser Mana Mote"); Check.False(w.GivenItems.Contains(WornMote), "still not the worn one"); } + + // 2026-10-08: the queue sent a give every 150 ms; the server takes one at a time and the + // rest came back "too busy", so /ub give handed over one item. + private static void WaitsForServer() + { + var w = new World(); + FakeHost.GiveLands = false; // the server hasn't taken the first yet + w.Run("/ub give Mana Mote to Town Crier"); + Check.Eq(FakeHost.Gives.Count, 1, "one give, then it waits for the server"); + + FakeHost.Containers[FakeHost.Gives[0].Item] = Npc; // the server took it + FakeHost.GiveLands = true; + for (int i = 0; i < 20; i++) w.Call("DrainGiveQueue"); + Check.Eq(FakeHost.Gives.Count, 3, "then the other two, each after the last landed"); + Check.Eq(FakeHost.Gives.Select(g => g.Item).Distinct().Count(), 3, "no item sent twice"); + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HazardEscapeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HazardEscapeTests.cs new file mode 100644 index 0000000..8bca30b --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/HazardEscapeTests.cs @@ -0,0 +1,161 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-10-07, Drakkon: two deaths in an acid pool in an hour. The patrol left him in a pool the +// hazard list didn't know, and topping up with healing kits held him there. Now the first +// "You suffer N damage from acid!" stops everything and walks him back out along his footsteps. +internal static class HazardEscapeTests +{ + private const uint Player = 0x50000180; + private const uint CellA = 0x63470160, CellB = 0x6347016C; // dungeon cells, one landblock + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + 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: Escape Acid and Lava off - no escape and nothing learned (some walk through acid)", SettingOff); + } + + private static void Parse() + { + Check.True(RynthAiPlugin.TryParseHotspotDamage("You suffer 32 damage from acid!", out int a, out string s) && a == 32 && s == "acid", "acid"); + Check.True(RynthAiPlugin.TryParseHotspotDamage("You suffer 11 damage from the lava.", out a, out s) && a == 11 && s == "lava", "lava, with 'the'"); + Check.False(RynthAiPlugin.TryParseHotspotDamage("You say, \"Malar Zhapaj\"", out _, out _), "speech"); + Check.False(RynthAiPlugin.TryParseHotspotDamage("Olthoi Swarm Worker bites you for 20 points of damage!", out _, out _), "a monster's hit"); + } + + private sealed class Clock { public long Now = 1_000_000; } + + private sealed class Bot + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new() { IsMacroRunning = true }; + public readonly WorldObjectCache Cache; + public readonly Clock C = new(); + + public Bot() + { + FakeHost.Reset(); + FakeHost.StopCalls = true; + var host = FakeHost.Create(Player); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(P, dash); + Cache = new WorldObjectCache(host); + typeof(RynthAiPlugin).GetField("_objectCache", Any)!.SetValue(P, Cache); + var clock = C; + RynthAiPlugin.HazardClock = () => clock.Now; + } + + /// Stands at (x, y), lets time pass and records the footstep. + public void At(uint cell, float x, float y, long ms = 300) + { + FakeHost.PlayerPose = (cell, x, y, -24f); + C.Now += ms; + P.RecordHazardTrail(); + } + + public bool Hold() => P.HoldForHazardEscape(); + public void Hit() => P.NoteHotspotChat("You suffer 32 damage from acid!", 0); + public T Get(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!; + } + + private static (float X, float Y) Target(Bot b) => (b.Get("_hazardTargetX"), b.Get("_hazardTargetY")); + + private static void EscapeAlongFootsteps() + { + var b = new Bot(); + // An L: north up x=60 from y=-185 to y=-175, then east to x=66 - into the acid. + for (int i = 0; i <= 10; i++) b.At(CellA, 60f, -185f + i); + for (int i = 1; i <= 6; i++) b.At(CellB, 60f + i, -175f); + + 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.True(b.Hold(), "the escape owns the tick (nothing else runs)"); + Check.True(FakeHost.AutoRun, "running"); + + var path = b.Get>("_hazardPath"); + Check.True(path.Count >= 3, $"a path of footsteps, not one straight line ({path.Count} points)"); + Check.True(path.Take(path.Count - 1).Any(p => p.Y == -175f && p.X > 60f), "it first walks back east-west along the way it came"); + var t = Target(b); + Check.True(t.X == 60f && t.Y <= -175f, $"and ends back on the north-south leg, outside the hurt cell ({t.X}, {t.Y})"); + + // Walk the footsteps: each tick at the next one. + foreach (var p in path) + { + FakeHost.PlayerPose = (p.Cell, p.X, p.Y, -24f); + b.C.Now += 300; + Check.True(b.Hold(), "still holding while it walks out"); + } + Check.False(FakeHost.AutoRun, "stopped at the target"); + b.C.Now += RynthAiPlugin.HazardQuietMs; + Check.False(b.Hold(), "no hit for a while at the target: the tick is handed back"); + Check.False(b.P.HazardEscaping, "escape over"); + Check.True(FakeHost.Logs.Any(l => l.Contains("Hazard: out of it")), "and it says so"); + } + + private static void FurtherBack() + { + var b = new Bot(); + for (int i = 0; i <= 12; i++) b.At(CellA, 60f, -190f + i); + b.Hit(); + var first = Target(b); + FakeHost.PlayerPose = (CellA, first.X, first.Y, -24f); + b.C.Now += 300; + foreach (var _ in Enumerable.Range(0, 20)) { b.Hold(); FakeHost.PlayerPose = (CellA, first.X, first.Y, -24f); } + Check.False(FakeHost.AutoRun, "arrived at the first spot"); + + b.C.Now += 2500; + b.Hit(); // the pool reaches further back + var second = Target(b); + Check.True(second.Y < first.Y - 1f, $"it goes further back ({first.Y} -> {second.Y})"); + Check.True(b.Hold(), "and keeps the tick"); + Check.True(FakeHost.AutoRun, "running again"); + } + + private static void MacroOff() + { + var b = new Bot(); + 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.P.HazardEscaping, "but nothing moves the character while you play it"); + Check.False(b.Hold(), "and the tick is not held"); + } + + private static void SettingOff() + { + var b = new Bot(); + b.S.EscapeHazards = false; + for (int i = 0; i <= 6; i++) b.At(CellA, 60f, -185f + i); + b.Hit(); + Check.False(b.P.HazardEscaping, "no escape"); + Check.False(b.Cache.IsHazardCell(CellA), "and the cell is not learned (the patrol keeps its way through)"); + Check.False(b.Hold(), "the tick is not held"); + + // Turned off mid-escape: it lets go at once. + b.S.EscapeHazards = true; + b.Hit(); + Check.True(b.P.HazardEscaping, "on again: the next hit escapes"); + b.S.EscapeHazards = false; + Check.False(b.Hold(), "turned off mid-escape: the tick is handed back"); + Check.False(b.P.HazardEscaping, "escape over"); + Check.False(new LegacyUiSettings().EscapeHazards == false, "on by default"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs index 87f2a00..47aad8a 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs @@ -51,6 +51,7 @@ internal static class LootCorpseTests r.Add("corpse close: an abandoned open corpse is closed once", AbandonedCorpseClosed); r.Add("corpse close: stopping the macro mid-loot closes the open corpse, not marked completed", MacroStopClosesCorpse); r.Add("loot pacing: a pickup waits for the last bend-down, and no retry is timed while it plays", PickupWaitsForAnimation); + r.Add("corpse close: not while the last item is between the corpse and the pack - it closes once the item is in the inventory", CloseWaitsForInventory); } // ── World set-up ────────────────────────────────────────────────────────── @@ -486,6 +487,26 @@ internal static class LootCorpseTests Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 2, "then one retry"); } + // 2026-10-07: the client takes an item off the corpse list as soon as the move is sent; the + // corpse was closed then, and the character picked the item up after the corpse closed. + private static void CloseWaitsForInventory() + { + var bot = OpenCorpseAndSendPickup(closeSupported: true); + FakeHost.Containers[Gem] = 0x7FFFFFF0; // off the corpse, not in a pack yet + TickFor(bot, 1500); + Check.Eq(FakeHost.Closes.Count, 0, "not closed while the item is on its way"); + Check.False(Completed(bot), "not completed either"); + + FakeHost.Containers[Gem] = Player; // in the main pack + for (int i = 0; i < 200 && FakeHost.Closes.Count == 0; i++) + { + bot.Tick(BotActivity.Looting); + Thread.Sleep(10); + } + Check.Eq(FakeHost.Closes.Count, 1, "closed once the item is in the inventory"); + Check.True(FakeHost.Logs.Any(l => l.Contains("pickup confirmed")), "and the pickup confirmed"); + } + private static void TickFor(Bot bot, int ms) { long end = Environment.TickCount64 + ms; diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs new file mode 100644 index 0000000..3200b07 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs @@ -0,0 +1,56 @@ +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-10-08: RynthAi used an Aligned Mana Stone on a wand. Only the ordinary tapping stones +// (and mana charges) are stones to RynthAi unless a ManaStone consumable rule names one. +internal static class ManaStoneChoiceTests +{ + public static void Register(Runner r) + { + 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); + } + + private static void OrdinaryOnly() + { + FakeHost.Reset(); + var host = FakeHost.Create(); + var cache = new WorldObjectCache(host); + var s = new LegacyUiSettings { EnableManaTapping = true }; + var m = new ManaStoneManager(host, s, cache); + WorldObject W(string name) => new(0x60001000, name, AcObjectClass.ManaStone); + + foreach (string n in new[] { "Minor Mana Stone", "Lesser Mana Stone", "Moderate Mana Stone", "Mana Stone", "Greater Mana Stone", "Major Mana Stone", "Titan Mana Charge" }) + Check.True(m.IsManaStone(W(n)), $"'{n}' is a stone"); + foreach (string n in new[] { "Aligned Mana Stone", "Aetheria Mana Stone", "Unstable Mana Stone", "Enchanted Mana Stone", "Adjanite Mana Stone" }) + Check.False(m.IsManaStone(W(n)), $"'{n}' is left alone"); + + s.ConsumableRules.Add(new ConsumableRule { Name = "Aligned Mana Stone", Type = "ManaStone" }); + Check.True(m.IsManaStone(W("Aligned Mana Stone")), "a rule naming it opts it in"); + Check.False(m.IsManaStone(W("Mana Stone")), "with rules, only the named stones"); + } + + private static void RefillWithoutTapping() + { + FakeHost.Reset(); + var host = FakeHost.Create(); + var cache = new WorldObjectCache(host); + var s = new LegacyUiSettings { EnableManaTapping = false }; + var m = new ManaStoneManager(host, s, cache); + WorldObject W(string name) => new(0x60001000, name, AcObjectClass.ManaStone); + + Check.False(m.IsManaStone(W("Major Mana Stone")), "tapping off: not a stone to loot or drain into"); + Check.True(m.IsRefillStone(W("Major Mana Stone")), "but a charged one still refills gear"); + Check.True(m.IsRefillStone(W("Titan Mana Charge")), "a bought Mana Charge too"); + Check.False(m.IsRefillStone(W("Aligned Mana Stone")), "never a special stone"); + + s.ConsumableRules.Add(new ConsumableRule { Name = "Aligned Mana Stone", Type = "ManaStone" }); + Check.True(m.IsRefillStone(W("Aligned Mana Stone")), "unless a rule names it"); + Check.False(m.IsRefillStone(W("Major Mana Stone")), "with rules, only the named stones"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs index 23dfedc..b87f5fb 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs @@ -43,7 +43,7 @@ internal static class MonsterEditorTests Name = "Olthoi", Category = "Olthoi nest", MatchExpression = "getcharintprop[25]>=200", Priority = 3, DamageType = "Acid", WeaponId = 0x50001234, Fester = true, Broadside = true, GravityWell = true, Imperil = true, Yield = true, Vuln = true, UseArc = true, UseRing = true, - UseStreak = true, UseBolt = false, UseBlast = true, ExVuln = "Fire", OffhandId = 2, + UseStreak = true, UseBolt = false, UseBlast = true, UseWall = true, ExVuln = "Fire", OffhandId = 2, PetDamage = "Cold", CustomDebuffs = "Corrosion Vulnerability Other, Fire Vulnerability Other VII", }, new PluginRule { Name = "", Category = "Expression only", MatchExpression = "wobjectfindnearestbytemplatetype[1]" }, diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs index 2e70afc..8a54f9f 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs @@ -28,6 +28,7 @@ internal static class VitalsTests 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); r.Add("vitals: 'You're too busy!' paces vital casts, and a long streak stops the character once", TooBusyVitals); + r.Add("vitals: no components for the top level - the next lower level is cast, not the same one again", NoComponentsFallsBack); // Drakkon's death, 2026-10-05 13:43:20 (ops\overnight\2026-10-05-death-fixes.md). r.Add("vitals: a hot reload's login refresh trusts its first read; a real login waits for two equal reads", HotReloadRefresh); r.Add("vitals: RynthAi tells the engine a reload is unsafe while engaged, under a heal line or casting", ReloadBlockerReport); @@ -69,6 +70,42 @@ internal static class VitalsTests Check.Eq(FakeHost.Stops, 1, "only once per streak"); } + // 2026-10-08: with no components for the highest Stamina to Mana / Revitalize / Heal the + // character knew, RynthAi kept retrying that one level; it parked the whole family, then + // tried the same level again. Now that level is passed over and the next lower one is cast. + private static void NoComponentsFallsBack() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + var host = FakeHost.Create(); + var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false }; + 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 = 100, MaxMana = 100, CurrentMana = 10 }; + var b = new BuffManager(host, s, sm, vitals); + b.SetCharacterSkills(skills); + + Check.True(b.CheckVitals(), "10% mana: Stamina to Mana is cast"); + int top = FakeHost.Casts[^1].SpellId; + b.OnChatWindowText("You don't have all the components for this spell.", 0); + for (int i = 0; i < 50 && FakeHost.Casts.Count < 2; i++) + { + b.CheckVitals(); + System.Threading.Thread.Sleep(20); + } + Check.Eq(FakeHost.Casts.Count, 2, "a second cast goes out"); + int next = FakeHost.Casts[^1].SpellId; + Check.True(next != top, $"a different level ({SpellTableStub.GetById(top)?.Name} -> {SpellTableStub.GetById(next)?.Name})"); + Check.True(SpellTableStub.GetById(next)?.Family == SpellTableStub.GetById(top)?.Family, "the same spell, one level down"); + } + // 2026-10-04, "nav and looting have priority over healing, almost dying in packs": the // arbiter only saw a heal on ticks where CheckVitals ran (never while looting kept the client // busy). Health under a line now says "wants vitals" by itself. diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/WallTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/WallTests.cs new file mode 100644 index 0000000..6826fdc --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/WallTests.cs @@ -0,0 +1,327 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Text.Json; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Wall spells (2026-10-08): a monster rule with Wall on casts its element's wall (picked by spell +// category, 229-235) when Wall Range is on and enough monsters are in the wall's path toward the +// target. Priority: Ring, then Wall, then Blast, then the base shape; a wall-only rule casts Bolt +// between walls. A wall is untargeted (ACE flies it along the caster's facing and never turns the +// caster for it), so the bot snaps its heading to the target first and holds the cast until the +// new heading has reached the server; already facing, it casts at once without turning. Walls are +// area casts for the damage bookkeeping. Old profiles and engine payloads load with walls off. +internal static class WallTests +{ + private const uint Player = 0x50000D01; + private const int Target = 0x7000A001; + + public static void Register(Runner r) + { + r.Add("walls: Ring, then Wall, then Blast, then the base shape; wall-only casts Bolt between walls", ShapePriority); + r.Add("walls: each element's wall by category, the tier limit, none for Nether", WallPerElement); + r.Add("walls: Wall Range off, too few in the path, or no wall known: the rule's other shape", WallOverride); + r.Add("walls: the path is a corridor toward the target, ahead of the caster", WallPathGeometry); + r.Add("walls: far off the target, it turns first and casts after the settle; facing it, no turn", WallFacing); + r.Add("walls: the cast itself waits for the turn, then goes as an area cast", WallCastThroughAttack); + r.Add("walls: UseWall, Wall Range and Min Wall Targets load off / 0 / 3 from old files", OldSettings); + } + + private static int Id(string name) => SpellTable.Named(name).Select(r => r.Id).First(); + private static string NameOf(int id) => id == 0 ? "(none)" : SpellTable.ById(id)?.Name ?? $"#{id}"; + + private sealed class Rig + { + public readonly LegacyUiSettings S = new(); + public readonly CombatManager C; + public int InPath = 5; + public DateTime Now = new(2026, 10, 8, 12, 0, 0); + + public Rig(int tier, params string[] known) + { + FakeHost.Reset(); + foreach (string n in known) + foreach (var row in SpellTable.Named(n)) FakeHost.Spellbook.Add((uint)row.Id); + int T(int k) => k <= tier ? 0 : 10000; // the no-skills stub reads 250 buffed + S.MinSkillLevelTier1 = 0; S.MinSkillLevelTier2 = T(2); S.MinSkillLevelTier3 = T(3); S.MinSkillLevelTier4 = T(4); + S.MinSkillLevelTier5 = T(5); S.MinSkillLevelTier6 = T(6); S.MinSkillLevelTier7 = T(7); S.MinSkillLevelTier8 = T(8); + S.RingRange = 0; + S.WallRange = 20; + S.MinWallTargets = 3; + // The player at the origin, the target 10 yd north; the player faces north. + FakeHost.PlayerPose = (0x0101001Bu, 0f, 0f, 0f); + FakeHost.Positions[Player] = FakeHost.PlayerPose; + FakeHost.Positions[(uint)Target] = (0x0101001Bu, 0f, 10f, 0f); + FakeHost.Names[(uint)Target] = "Drudge Skulker"; + FakeHost.HeadingDeg = 0; + var host = FakeHost.Create(Player); + var cache = FakeHost.MakeCache(host, Player, new[] { (uint)Target }); + C = new CombatManager(host, S, cache); + C.SetPlayerId(Player); + var sm = new SpellManager(host, S); + sm.InitializeNatively(); + sm.RefreshKnownSpells(); + C.SetSpellManager(sm); + C.WallPathCountOverride = () => InPath; + C.WallClock = () => Now; + } + + public (string Spell, string Shape) Cast(string element, MonsterRule rule) + { + int id = C.FindBestShapedSpell(element, rule, out _, out int shape, arcTargetId: Target); + return (NameOf(id), CombatManager.ShapeName(shape)); + } + } + + private static MonsterRule Wall(bool bolt = true) => new() { Name = "Drudge", UseBolt = bolt, UseWall = true }; + + private static void ShapePriority() + { + MonsterRule R(bool ring = false, bool bolt = false, bool blast = false, bool wall = false, bool arc = false) + => new() { UseArc = arc, UseRing = ring, UseBolt = bolt, UseBlast = blast, UseWall = wall }; + string N(int s) => CombatManager.ShapeName(s); + int C(MonsterRule r, bool ringDue, bool wallDue, bool blastConditional = false, bool blastFanMet = false) + => CombatManager.ChooseCastShape(r, blastConditional, blastFanMet, ringDue, wallDue, () => true, out _); + + var all = R(ring: true, bolt: true, blast: true, wall: true); + Check.Eq(N(C(all, ringDue: true, wallDue: true, true, true)), "Ring", "all due: Ring"); + Check.Eq(N(C(all, ringDue: false, wallDue: true, true, true)), "Wall", "wall and blast due: Wall"); + Check.Eq(N(C(all, ringDue: false, wallDue: false, true, true)), "Blast", "only the blast due: Blast"); + Check.Eq(N(C(all, ringDue: false, wallDue: false, true, false)), "Bolt", "none due: the base shape (Bolt)"); + Check.Eq(N(C(R(wall: true), false, true)), "Wall", "wall-only, due: Wall"); + Check.Eq(N(C(R(wall: true), false, false)), "Bolt", "wall-only, not due: Bolt between walls (like ring-only)"); + Check.Eq(N(CombatManager.PickBaseShape(R(wall: true))), "Bolt", "wall-only base: Bolt"); + Check.Eq(N(CombatManager.PickBaseShape(R(wall: true, ring: true))), "Bolt", "ring + wall only: Bolt"); + Check.Eq(CombatManager.PickBaseShape(R()), -1, "nothing on: still no cast"); + + int asked = 0; + int s = CombatManager.ChooseCastShape(R(arc: true, wall: true), false, false, false, wallDue: true, () => { asked++; return true; }, out bool g); + Check.Eq(N(s), "Wall", "Arc + Wall, wall due: Wall"); + Check.True(asked == 0 && !g, "a due wall skips the arc test"); + Check.Eq(N(CombatManager.ChooseCastShape(R(arc: true, wall: true), false, false, false, null, out _)), "Arc", + "the old overload (no wall) is unchanged"); + } + + private static void WallPerElement() + { + var cases = new (string Element, string Wall)[] + { + ("Acid", "Blistering Creeper"), ("Bludgeon", "Hammering Crawler"), ("Cold", "Foon-Ki's Glacial Floe"), + ("Lightning", "Os' Wall"), ("Fire", "Slithering Flames"), ("Pierce", "Spike Strafe"), + ("Blade", "Bed of Blades"), ("Slash", "Bed of Blades"), + }; + string[] retail = cases.Select(c => c.Wall).Distinct().ToArray(); + foreach (var (element, wall) in cases) + { + var rig = new Rig(7, retail); + Check.Eq(NameOf(rig.C.FindBestWallSpell(element)), wall, $"{element}: {wall} (of all seven known)"); + Check.Eq(rig.Cast(element, Wall()), (wall, "Wall"), $"{element}: cast as the Wall shape"); + } + var any = new Rig(7, retail); + Check.Eq(any.C.FindBestWallSpell("Nether"), 0, "Nether: no walls"); + Check.Eq(any.Cast("Nether", Wall()).Shape, "?", "Nether, nothing else known: no wall cast"); + + // Retail walls are power 200: level 5 by ACE's server formula, castable from tier 5. + Check.Eq(SpellDatabase.LevelFromPower(SpellTable.ById(Id("Slithering Flames"))!.Power), 5, "Slithering Flames: level 5 (power 200)"); + Check.Eq(NameOf(new Rig(5, "Slithering Flames").C.FindBestWallSpell("Fire")), "Slithering Flames", "tier 5: the retail wall"); + Check.Eq(new Rig(4, "Slithering Flames").C.FindBestWallSpell("Fire"), 0, "tier 4: too hard (the same limit as Flame Bolt V)"); + + // Several known in the category: the highest level the tier allows, then the power. + var fire = new Rig(8, "Slithering Flames", "Burning Earth", "Flame Whip"); + Check.Eq(NameOf(fire.C.FindBestWallSpell("Fire")), "Burning Earth", "tier 8: Burning Earth (power 400, level 8)"); + var fire7 = new Rig(7, "Slithering Flames", "Burning Earth"); + Check.Eq(NameOf(fire7.C.FindBestWallSpell("Fire")), "Slithering Flames", "tier 7: not the level-8 one"); + Check.Eq(new Rig(7, "Flame Bolt VI").C.FindBestWallSpell("Fire"), 0, "no wall known: none"); + + // The cold snapshot: never guess. + FakeHost.Reset(); + var host = FakeHost.Create(Player); + var c = new CombatManager(host, new LegacyUiSettings(), FakeHost.MakeCache(host, Player, Array.Empty())); + var sm = new SpellManager(host, new LegacyUiSettings()); + sm.InitializeNatively(); + c.SetSpellManager(sm); + Check.Eq(c.FindBestWallSpell("Fire"), 0, "spellbook snapshot cold: no wall"); + } + + private static void WallOverride() + { + string[] book = { "Foon-Ki's Glacial Floe", "Frost Bolt VI", "Frost Blast VI", "Frost Arc VI" }; + var rig = new Rig(7, book); + Check.Eq(rig.Cast("Cold", Wall()), ("Foon-Ki's Glacial Floe", "Wall"), "5 in the path (3 needed): the wall"); + rig.InPath = 2; + Check.Eq(rig.Cast("Cold", Wall()), ("Frost Bolt VI", "Bolt"), "2 in the path: Bolt"); + rig.InPath = 5; + rig.S.WallRange = 0; + Check.Eq(rig.Cast("Cold", Wall()), ("Frost Bolt VI", "Bolt"), "Wall Range 0: no walls"); + rig.S.WallRange = 20; + Check.Eq(rig.Cast("Cold", new MonsterRule { UseArc = true, UseWall = true }).Shape, "Wall", "Arc + Wall, due: Wall"); + Check.Eq(rig.Cast("Cold", new MonsterRule { UseBlast = true, UseWall = true, UseBolt = false }).Shape, "Wall", "Blast + Wall, both due: Wall"); + rig.InPath = 1; + Check.Eq(rig.Cast("Cold", new MonsterRule { UseBlast = true, UseWall = true, UseBolt = false }), ("Frost Blast VI", "Blast"), + "Blast + Wall, wall not due: Blast"); + rig.InPath = 5; + Check.Eq(rig.Cast("Cold", new MonsterRule { UseBolt = true }), ("Frost Bolt VI", "Bolt"), "Wall off in the rule: unchanged"); + Check.Eq(rig.C.FindBestShapedSpell("Cold", Wall(), out _, out int probeShape), Id("Frost Bolt VI"), + "an element probe (no target) never picks a wall"); + Check.Eq(CombatManager.ShapeName(probeShape), "Bolt", "probe shape Bolt"); + + var noWall = new Rig(7, "Frost Bolt VI"); + Check.Eq(noWall.Cast("Cold", Wall()), ("Frost Bolt VI", "Bolt"), "no cold wall known: Bolt (the wall isn't due)"); + + Check.Eq(CombatManager.ChooseCastShape(new MonsterRule { UseRing = true, UseWall = true }, false, false, true, true, null, out _), + CombatManager.ShapeRing, "ring and wall due: Ring"); + } + + private static void WallPathGeometry() + { + Check.True(CombatManager.InWallPath(10, 0), "the target itself"); + Check.True(CombatManager.InWallPath(15, 10), "15 yd, 10 deg off: 2.6 yd aside"); + Check.False(CombatManager.InWallPath(15, 25), "15 yd, 25 deg off: 6.3 yd aside, outside"); + Check.True(CombatManager.InWallPath(3, 60), "close, 60 deg off: 2.6 yd aside"); + Check.False(CombatManager.InWallPath(5, 120), "behind the caster: no"); + Check.True(CombatManager.InWallPath(5, -30), "the other side too"); + Check.Near(CombatManager.WallHalfWidth, 4.0, 1e-9, "half width 4 yd (5 projectiles across)"); + } + + private static void WallFacing() + { + var rig = new Rig(7, "Slithering Flames"); + // Facing the target (within 1 degree): cast at once, no turn. + FakeHost.HeadingDeg = 0.5f; + Check.False(rig.C.HoldForWallFacing(Target), "0.5 deg off: cast now"); + Check.Eq(FakeHost.Turns, 0, "no turn"); + + // 90 degrees off: snap to the target, then hold for the settle. + FakeHost.HeadingDeg = 90; + Check.True(rig.C.HoldForWallFacing(Target), "90 deg off: hold"); + Check.Eq(FakeHost.Turns, 1, "one heading snap"); + Check.Near(FakeHost.HeadingDeg, 0, 0.5, "snapped to the target (north)"); + rig.Now = rig.Now.AddMilliseconds(500); + Check.True(rig.C.HoldForWallFacing(Target), "500 ms later: still settling"); + rig.Now = rig.Now.AddMilliseconds(CombatManager.WallFaceSettleMs); + Check.False(rig.C.HoldForWallFacing(Target), "after the settle: cast"); + Check.Eq(FakeHost.Turns, 1, "no second turn"); + + // Turned, but the target walked far off during the settle: turn again. + FakeHost.HeadingDeg = 180; + Check.True(rig.C.HoldForWallFacing(Target), "180 deg off: hold"); + FakeHost.Positions[(uint)Target] = (0x0101001Bu, 10f, 0f, 0f); // now due east + rig.Now = rig.Now.AddMilliseconds(CombatManager.WallFaceSettleMs + 1); + Check.True(rig.C.HoldForWallFacing(Target), "settled but 90 deg off now: turn again"); + Check.Eq(FakeHost.Turns, 3, "the second snap"); + Check.Near(FakeHost.HeadingDeg, 90, 0.5, "to the east"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatCast] wall: facing")), "the turn is logged"); + + // The drift allowed after the settle shrinks with distance (1.8 m to the side). + Check.Near(CombatManager.WallDriftAllowedDeg(64.0), 1.6, 0.1, "70 yd: about 1.6 degrees"); + Check.Near(CombatManager.WallDriftAllowedDeg(9.0), 5.0, 0.01, "10 yd: capped at 5 degrees"); + + // Always turn: 6 degrees off is a snap too (a wall flies straight). + var small = new Rig(7, "Slithering Flames"); + FakeHost.HeadingDeg = 6; + Check.True(small.C.HoldForWallFacing(Target), "6 deg off: turn first"); + Check.Eq(FakeHost.Turns, 1, "one snap"); + + // A target that keeps moving: at most WallFaceMaxSnaps turns, then the wall goes anyway. + var chase = new Rig(7, "Slithering Flames"); + FakeHost.HeadingDeg = 180; + Check.True(chase.C.HoldForWallFacing(Target), "first snap"); + float east = 10f; + for (int i = 1; i < CombatManager.WallFaceMaxSnaps; i++) + { + FakeHost.HeadingDeg = 180; // keeps facing away (the target ran round behind) + chase.Now = chase.Now.AddMilliseconds(CombatManager.WallFaceSettleMs + 1); + Check.True(chase.C.HoldForWallFacing(Target), $"snap {i + 1}"); + } + FakeHost.HeadingDeg = 180; + chase.Now = chase.Now.AddMilliseconds(CombatManager.WallFaceSettleMs + 1); + Check.False(chase.C.HoldForWallFacing(Target), "after the last snap: cast anyway"); + _ = east; + } + + private static void WallCastThroughAttack() + { + var rig = new Rig(7, "Slithering Flames", "Flame Bolt VI"); + rig.S.MonsterRules.Clear(); + rig.S.MonsterRules.Add(new MonsterRule { Name = "Drudge", DamageType = "Fire", UseBolt = true, UseWall = true }); + rig.C.activeTargetId = Target; + var target = new WorldObject(Target, "Drudge Skulker"); + MethodInfo attack = typeof(CombatManager).GetMethod("AttackWithMagic", BindingFlags.NonPublic | BindingFlags.Instance)!; + FieldInfo held = typeof(CombatManager).GetField("_wallFaceHeld", BindingFlags.NonPublic | BindingFlags.Instance)!; + FieldInfo tier = typeof(CombatManager).GetField("_lastCastTier", BindingFlags.NonPublic | BindingFlags.Instance)!; + FieldInfo area = typeof(CombatManager).GetField("_lastCastWasRing", BindingFlags.NonPublic | BindingFlags.Instance)!; + FieldInfo resolving = typeof(CombatManager).GetField("_awaitingCastResolution", BindingFlags.NonPublic | BindingFlags.Instance)!; + + FakeHost.HeadingDeg = 270; // facing west, the target is north + attack.Invoke(rig.C, new object[] { target }); + Check.Eq(FakeHost.Casts.Count, 0, "far off: no cast yet"); + Check.True((bool)held.GetValue(rig.C)!, "the wall is held for its turn"); + Check.Eq(FakeHost.Turns, 1, "turned first"); + + rig.Now = rig.Now.AddMilliseconds(300); + attack.Invoke(rig.C, new object[] { target }); + Check.Eq(FakeHost.Casts.Count, 0, "300 ms later: still no cast (the server catching up)"); + + rig.Now = rig.Now.AddMilliseconds(CombatManager.WallFaceSettleMs); + attack.Invoke(rig.C, new object[] { target }); + Check.Eq(FakeHost.Casts.Count, 1, "after the settle: cast"); + Check.Eq(NameOf(FakeHost.Casts[0].SpellId), "Slithering Flames", "the wall"); + Check.False((bool)held.GetValue(rig.C)!, "not held"); + Check.Eq(FakeHost.Turns, 1, "no turn with the cast"); + Check.True((bool)area.GetValue(rig.C)!, "an area cast for the bookkeeping (like a ring)"); + Check.Eq((int)tier.GetValue(rig.C)!, -5, "filed with the area tiers: level 5, negative"); + + // Already facing: straight to the cast, no turn. (A fresh rig: no cast resolving.) + var facing = new Rig(7, "Slithering Flames", "Flame Bolt VI"); + facing.S.MonsterRules.Add(new MonsterRule { Name = "Drudge", DamageType = "Fire", UseBolt = true, UseWall = true }); + facing.C.activeTargetId = Target; + FakeHost.HeadingDeg = 0; + attack.Invoke(facing.C, new object[] { target }); + Check.Eq(FakeHost.Casts.Count, 1, "facing: cast at once"); + Check.Eq(NameOf(FakeHost.Casts[0].SpellId), "Slithering Flames", "the wall"); + Check.Eq(FakeHost.Turns, 0, "no turn"); + Check.True((bool)resolving.GetValue(facing.C)!, "the cast arms the cadence guard (no turn until it resolves)"); + + // A bolt (wall not due) is single-target as before. + var bolt = new Rig(7, "Slithering Flames", "Flame Bolt VI"); + bolt.S.MonsterRules.Add(new MonsterRule { Name = "Drudge", DamageType = "Fire", UseBolt = true, UseWall = true }); + bolt.C.activeTargetId = Target; + bolt.InPath = 1; + FakeHost.HeadingDeg = 270; + attack.Invoke(bolt.C, new object[] { target }); + Check.Eq(NameOf(FakeHost.Casts.Single().SpellId), "Flame Bolt VI", "wall not due: the bolt, no turn needed"); + Check.Eq(FakeHost.Turns, 0, "targeted casts don't turn (the server does)"); + Check.False((bool)area.GetValue(bolt.C)!, "single-target"); + Check.Eq((int)tier.GetValue(bolt.C)!, 6, "positive tier"); + } + + private static void OldSettings() + { + var old = JsonSerializer.Deserialize("{\"MinRingTargets\":4,\"BlastRange\":10}", RynthAiJsonContext.Default.LegacyUiSettings)!; + Check.Eq(old.WallRange, 0, "old profile: Wall Range off"); + Check.Eq(old.MinWallTargets, 3, "old profile: Min Wall Targets 3"); + var fresh = new LegacyUiSettings(); + Check.True(fresh.WallRange == 0 && fresh.MinWallTargets == 3, "new settings: off / 3"); + + var bridge = JsonSerializer.Deserialize("{\"MinRingTargets\":4}", RynthAiJsonContext.Default.SettingsBridgePayload)!; + Check.True(bridge.WallRange == null && bridge.MinWallTargets == null, "older engine's settings: no wall values (left alone)"); + var newer = JsonSerializer.Deserialize("{\"WallRange\":15,\"MinWallTargets\":4}", RynthAiJsonContext.Default.SettingsBridgePayload)!; + Check.True(newer.WallRange == 15 && newer.MinWallTargets == 4, "an engine with walls: carried"); + + const string oldRules = "[{\"Name\":\"Default\",\"Priority\":1,\"UseBolt\":true},{\"Name\":\"Drudge\",\"UseRing\":true,\"UseBlast\":true}]"; + var rules = JsonSerializer.Deserialize(oldRules, RynthAiJsonContext.Default.MonsterRuleList)!; + Check.False(rules[0].UseWall || rules[1].UseWall, "old monster file: Wall off"); + rules[1].UseWall = true; + string json = JsonSerializer.Serialize(rules, RynthAiJsonContext.Default.MonsterRuleList); + Check.True(json.Contains("\"UseWall\": true"), "saved with UseWall"); + var back = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.MonsterRuleList)!; + Check.True(back[1].UseWall && !back[0].UseWall, "round trip keeps it"); + var payload = JsonSerializer.Deserialize("{\"rules\":[{\"Name\":\"Mite\",\"UseWall\":true}]}", RynthAiJsonContext.Default.MonstersBridgePayload)!; + Check.True(payload.Rules[0].UseWall, "the engine's rules JSON carries UseWall"); + } +} diff --git a/Tools/RynthNav.Baker/NavBake.cs b/Tools/RynthNav.Baker/NavBake.cs index deffb1e..6a7c9e2 100644 --- a/Tools/RynthNav.Baker/NavBake.cs +++ b/Tools/RynthNav.Baker/NavBake.cs @@ -106,6 +106,13 @@ internal static class NavBake /// public static float AgentMaxClimb = 1.0f; + /// + /// How far a wall outline may be simplified. 1.3 m was fine inside the old 2 m agent margin; + /// with a body-sized radius (0.6 m: gaps under about 4 m no longer close, Shoushi 2026-10-08) + /// a 1.3 m simplification could cut a corner through the margin, so it follows the radius. + /// + internal static float EdgeMaxError(float radius) => Math.Min(1.3f, radius + 0.15f); + private static RcNavMeshBuildSettings Settings(float radius, bool tiled, float cellSize) { float slopeDeg = (float)(Math.Acos(TerrainSampler.FloorZ) * 180.0 / Math.PI); @@ -115,7 +122,7 @@ internal static class NavBake agentHeight = 2.0f, agentRadius = radius, agentMaxClimb = AgentMaxClimb, agentMaxSlope = slopeDeg, minRegionSize = 8, mergedRegionSize = 20, partitioning = (int)RcPartition.WATERSHED, filterLowHangingObstacles = true, filterLedgeSpans = true, filterWalkableLowHeightSpans = true, - edgeMaxLen = 12f, edgeMaxError = 1.3f, vertsPerPoly = VertsPerPoly, detailSampleDist = 6f, detailSampleMaxError = 1f, + edgeMaxLen = 12f, edgeMaxError = EdgeMaxError(radius), vertsPerPoly = VertsPerPoly, detailSampleDist = 6f, detailSampleMaxError = 1f, // The solo bake reads the intermediate results (the .obj export); the tiled bake only // needs the finished navmesh, and keeping every tile's heightfields cost 1.5-2.7 GB a chunk. tiled = tiled, tileSize = tiled ? TiledTileSize : 0, keepInterResults = !tiled, buildAll = true, diff --git a/Tools/RynthNav.RouteTests/Program.cs b/Tools/RynthNav.RouteTests/Program.cs index 048fe16..9ce8d16 100644 --- a/Tools/RynthNav.RouteTests/Program.cs +++ b/Tools/RynthNav.RouteTests/Program.cs @@ -39,6 +39,10 @@ internal static partial class Program Run(nameof(RecallListColdSpellbook), RecallListColdSpellbook); Run(nameof(RecallMemoryRoundTrip), RecallMemoryRoundTrip); Run(nameof(RecallMessages), RecallMessages); + Run(nameof(HandCastOnALifestone), HandCastOnALifestone); + Run(nameof(HandCastPortalTie), HandCastPortalTie); + Run(nameof(RecallNotLinked), RecallNotLinked); + Run(nameof(DungeonLandblocksFromTheAtlas), DungeonLandblocksFromTheAtlas); Run(nameof(AtlasSearchAndBestMatch), AtlasSearchAndBestMatch); Run(nameof(ArrowSingleTarget), ArrowSingleTarget); Run(nameof(ArrowAlongRoute), ArrowAlongRoute); @@ -249,6 +253,128 @@ internal static partial class Program Check(RecallMemory.Classify("", "Tom") == RecallEvent.None, "empty"); Check(RecallMemory.SlotFor(RecallEvent.RecallingHome, out var slot) && slot == RecallSlot.House, "house slot"); Check(!RecallMemory.SlotFor(RecallEvent.RecallingMarketplace, out _), "marketplace has no slot"); + // Your spell words (Spellcasting, 17) start a hand cast; the same words typed in local chat don't. + Check(RecallMemory.Classify("You say, \"Zojak Ququ\"", "Tom", RecallMemory.ChatTypeSpellcasting) == RecallEvent.OwnSpellWords, "own spell words"); + Check(RecallMemory.Classify("You say, \"Zojak Ququ\"", "Tom", 2) == RecallEvent.None, "typed in local chat"); + Check(RecallMemory.Classify("You say, \"Zojak Ququ\"", "Tom") == RecallEvent.None, "chat type unknown"); + Check(RecallMemory.Classify("Ann says, \"Zojak Ququ\"", "Tom", RecallMemory.ChatTypeSpellcasting) == RecallEvent.None, "someone else casting"); + } + + // ── A recall cast by hand: which one, from where it landed ─────────────── + + private const string Me = "Aelrynth|Tom"; + + private static RecallSpot At(double ns, double ew, string label = "") => new() { OnMap = true, Ns = ns, Ew = ew, Label = label }; + + private static void HandCastOnALifestone() + { + var mem = new RecallMemory(); + var known = new HashSet { RecallPlanner.LifestoneRecall, RecallPlanner.PrimaryPortalTieRecall }; + var k = RecallPlanner.GuessHandCast(At(42.1, 33.6), atLifestone: true, known, mem, Me, 30, out var slot, out _); + Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Lifestone, "on a lifestone: Lifestone Recall"); + + mem.Set(Me, RecallSlot.Lifestone, At(42.1, 33.6)); + k = RecallPlanner.GuessHandCast(At(42.11, 33.6), true, known, mem, Me, 30, out _, out _); + Check(k == RecallPlanner.HandCast.Nothing, "the same lifestone again: nothing new"); + k = RecallPlanner.GuessHandCast(At(-30.0, 70.0), true, known, mem, Me, 30, out slot, out _); + Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Lifestone, "tied somewhere else since: learned again"); + + k = RecallPlanner.GuessHandCast(At(42.1, 33.6), true, new HashSet { RecallPlanner.PrimaryPortalTieRecall }, new RecallMemory(), Me, 30, out _, out _); + Check(k == RecallPlanner.HandCast.Nothing, "no Lifestone Recall in the spellbook: not it"); + + // On the @lifestone lifestone with Recall the Sanctuary known: either spell, can't tell. + var mem2 = new RecallMemory(); + mem2.Set(Me, RecallSlot.Sanctuary, At(42.1, 33.6)); + var known2 = new HashSet { RecallPlanner.LifestoneRecall, RecallPlanner.RecallTheSanctuary }; + k = RecallPlanner.GuessHandCast(At(42.1, 33.6), true, known2, mem2, Me, 30, out _, out _); + Check(k == RecallPlanner.HandCast.Nothing, "Recall the Sanctuary could land there too"); + k = RecallPlanner.GuessHandCast(At(10, 10), true, null, mem2, Me, 30, out _, out var why); + Check(k == RecallPlanner.HandCast.Nothing && why.Contains("spellbook"), "a cold spellbook teaches nothing"); + } + + private static void HandCastPortalTie() + { + var oneTie = new HashSet { RecallPlanner.SecondaryPortalTieRecall }; + var k = RecallPlanner.GuessHandCast(At(-33.5, 72.8), false, oneTie, new RecallMemory(), Me, 30, out var slot, out _); + Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Tie2, "the only tie recall known"); + + var both = new HashSet { RecallPlanner.PrimaryPortalTieRecall, RecallPlanner.SecondaryPortalTieRecall }; + k = RecallPlanner.GuessHandCast(At(-33.5, 72.8), false, both, new RecallMemory(), Me, 30, out _, out _); + Check(k == RecallPlanner.HandCast.AskTie, "both tie recalls known: ask which"); + + var mem = new RecallMemory(); + mem.Set(Me, RecallSlot.Tie1, At(-33.5, 72.8)); + k = RecallPlanner.GuessHandCast(At(-33.51, 72.8), false, both, mem, Me, 30, out slot, out _); + Check(k == RecallPlanner.HandCast.Nothing && slot == RecallSlot.Tie1, "a known tie's landing: nothing new"); + + // Portal Recall: lands where the last portal went (known: nothing; unknown: ask). + var withPortalRecall = new HashSet { RecallPlanner.PrimaryPortalTieRecall, RecallPlanner.PortalRecall }; + var mem2 = new RecallMemory(); + mem2.Set(Me, RecallSlot.LastPortal, At(12, 34)); + k = RecallPlanner.GuessHandCast(At(12, 34), false, withPortalRecall, mem2, Me, 30, out _, out _); + Check(k == RecallPlanner.HandCast.Nothing, "the last portal's landing: Portal Recall"); + k = RecallPlanner.GuessHandCast(At(-33.5, 72.8), false, withPortalRecall, mem2, Me, 30, out slot, out _); + Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Tie1, "elsewhere, last portal known: the one tie"); + k = RecallPlanner.GuessHandCast(At(-33.5, 72.8), false, withPortalRecall, new RecallMemory(), Me, 30, out _, out _); + Check(k == RecallPlanner.HandCast.AskTie, "last portal unknown: could be Portal Recall, ask"); + + k = RecallPlanner.GuessHandCast(At(1, 1), false, new HashSet { RecallPlanner.LifestoneRecall }, new RecallMemory(), Me, 30, out _, out _); + Check(k == RecallPlanner.HandCast.Nothing, "off a lifestone with no tie recall: not one RynthNav knows"); + + // A dungeon landing (off the map) is learned too, and matched by its label. + var dungeon = new RecallSpot { OnMap = false, Label = "a dungeon (landblock 6145)" }; + k = RecallPlanner.GuessHandCast(dungeon, false, oneTie, new RecallMemory(), Me, 30, out slot, out _); + Check(k == RecallPlanner.HandCast.Learn && slot == RecallSlot.Tie2, "a tie into a dungeon"); + var mem3 = new RecallMemory(); + mem3.Set(Me, RecallSlot.Tie2, new RecallSpot { OnMap = false, Label = "a dungeon (landblock 6145)" }); + k = RecallPlanner.GuessHandCast(dungeon, false, oneTie, mem3, Me, 30, out _, out _); + Check(k == RecallPlanner.HandCast.Nothing, "the same dungeon again: nothing new"); + + // Once learned, the planner uses it. + var plannerMem = new RecallMemory(); + plannerMem.Set(Me, RecallSlot.Tie2, At(-33.5, 72.8, "Shoushi")); + var list = RecallPlanner.Build(Atlas.Empty, oneTie, plannerMem, Me, new List()); + Check(list.Exists(o => o.SpellId == RecallPlanner.SecondaryPortalTieRecall && Math.Abs(o.Ns + 33.5) < 1e-9), "the learned tie is planned"); + } + + private static void DungeonLandblocksFromTheAtlas() + { + // A dungeon landblock's tile is its surface (dungeon cells aren't baked): the walk must + // know it's in one. Dungeon places and dungeon portal destinations count; a landblock + // with places on the map (a town, its cellars) never does. + Atlas atlas = Atlas.Parse(@"{""locations"":[ + {""name"":""Surface"",""type"":""Portal"",""cell"":""000102C8"",""place"":""dungeon"",""dest"":{""cell"":""26E5001D"",""place"":""outdoor"",""ns"":81.68,""ew"":-71.16}}, + {""name"":""Holtburg Dungeon Portal"",""type"":""Portal"",""cell"":""A9B40021"",""place"":""outdoor"",""ns"":42.0,""ew"":33.0,""dest"":{""cell"":""01F60230"",""place"":""dungeon""}}, + {""name"":""Shoushi"",""type"":""Town"",""cell"":""DA55001D"",""place"":""outdoor"",""ns"":-33.5,""ew"":72.8}, + {""name"":""Cellar Vendor"",""type"":""Vendor"",""cell"":""DA550105"",""place"":""dungeon""}, + {""name"":""Odd"",""type"":""Landmark"",""cell"":""zz"",""place"":""dungeon""} + ]}"); + HashSet d = atlas.DungeonLandblocks(); + Check(d.Contains(0x0001), "a dungeon place's landblock"); + Check(d.Contains(0x01F6), "a portal's dungeon destination"); + Check(!d.Contains(0x26E5) && !d.Contains(0xA9B4), "outdoor landblocks aren't dungeons"); + Check(!d.Contains(0xDA55), "a town landblock with a dungeon cell isn't one"); + Check(d.Count == 2, "nothing else (a bad cell is skipped)"); + } + + private static void RecallNotLinked() + { + Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkLifestone, 0) == RecallSlot.Lifestone, "no lifestone tie: Lifestone Recall"); + Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkPortal, RecallPlanner.PrimaryPortalTieRecall) == RecallSlot.Tie1, "no primary tie"); + Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkPortal, RecallPlanner.SecondaryPortalTieRecall) == RecallSlot.Tie2, "no secondary tie"); + Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkPortal, RecallPlanner.PortalRecall) == RecallSlot.LastPortal, "no last portal"); + Check(RecallPlanner.SlotUnlinked(RecallPlanner.ErrorMustLinkPortal, 0) == null, "a portal recall cast by hand: can't tell which"); + Check(RecallPlanner.SlotUnlinked(0x0402, RecallPlanner.LifestoneRecall) == null, "a fizzle isn't a missing tie"); + Check(RecallPlanner.SpellFor(RecallSlot.Tie2) == RecallPlanner.SecondaryPortalTieRecall && RecallPlanner.SpellFor(RecallSlot.House) == 0, "slot spells"); + + var mem = new RecallMemory(); + mem.Set(Me, RecallSlot.Lifestone, At(42.1, 33.6)); + int v = mem.Version; + mem.Clear(Me, RecallSlot.Lifestone); + Check(mem.Get(Me, RecallSlot.Lifestone) == null && mem.Version > v, "forgotten (and saved)"); + var notes = new List(); + RecallPlanner.Build(Atlas.Empty, new HashSet { RecallPlanner.LifestoneRecall }, mem, Me, notes); + Check(notes.Exists(n => n.Contains("Lifestone Recall") && n.Contains("cast Lifestone Recall once")), "the note says how to teach it"); } // ── Atlas ────────────────────────────────────────────────────────────────